diff --git a/Docs/Locations/Refinements.md b/Docs/Locations/Refinements.md new file mode 100644 index 00000000..0a5f19ab --- /dev/null +++ b/Docs/Locations/Refinements.md @@ -0,0 +1,101 @@ +# Locations refinements: picker, taxonomy and shared Attributes + +This refines the existing workspace, without changing its cards, ribbon, containment commands, +merge reconciliation, protected Undo or live-update contracts. See the shared +[Attributes component standard](../UI/AttributesPanel.md). + +## Hierarchical selection + +`location-picker.js` exposes `PlotDirectorLocationPicker.mount(host, options)` and `enhance(select)`. +It sorts roots and siblings alphabetically (independent of the workspace sort), renders containment +branches and canonical icons, highlights selection and shows its full path. Name, alias and full-path +search reveals matching ancestors. Temporary search expansion is separate from ordinary expansion; +clearing search restores the ordinary state. Duplicate names display paths. Arrow keys, Home/End, +Enter and Space navigate/select; Enter in search focuses a result and never submits a mutation. + +Options: `locations`, `types`, `selected`, `allowRoot`, `rootLabel`, `excludeIds`, `excludeBranches`, +`label`, `searchLabel`, `onChange`. IDs may be numeric or stable keys. `excludeBranches` prevents +selecting the source and its descendants while leaving their context visible. Expansion remains +available on unselectable headings. The return object exposes `value`, `path(id)` and `focus()`. +No picker selection itself writes to the database. The operation owns confirmation and saving. + +Workspace Change Parent, branch filter and reviewed merge use the inline picker in their existing +modal. Traditional Create/Edit parent, Details relationship target and traditional Merge opt in using +`select[data-location-picker]`, project ID and operation exclusions. Without JavaScript, the native +form controls remain. The modal uses shared theme variables and up to 900px width; paths wrap. +`LocationWorkspace/Picker` checks project access and uses `Location_PickerRead`, loading only names, +parent/type IDs and aliases, plus the canonical taxonomy. No manuscript prose is loaded. +Map and floor-plan selection interfaces are unchanged. + +Server project ownership, cycle/descendant guards, merge version checks, confirmation and original +relationship validation remain authoritative. Client exclusions are conveniences, not security controls. +The picker is also composed for type selection with grouping headings made unassignable. + +## Canonical taxonomy + +Forward-only migration **338_LocationTypeTaxonomy.sql** adds `LocationTypeTaxonomy` and two read +procedures. The catalogue contains 105 entries: 97 canonical assignable type IDs, the assignable NULL +Unclassified choice, and seven grouping headings. It adds 81 LocationTypes rows, leaving the existing +16 rows, IDs, names, order and active state unchanged. No Locations row is rewritten or specialised. +City already existed (ID 16); it is now discoverable under Settlements. Existing Building, Town, +Room and NULL Unclassified remain exactly those stored values. + +`TypeKey` is the stable taxonomy identity. `LocationTypeID` maps assignable entries to the existing +foreign key. Metadata supplies `ParentKey`, `DisplayName`, `SortOrder`, `IconKey`, `SemanticTone` +and `IsAssignable`. Group headings never become rows in LocationTypes. Assignable categories such +as Residential, Commercial, Public and institutional, Historic and defensive, Building and Room +remain valid selections. NULL Unclassified has a stable metadata key and no invented canonical ID. +Office in premises and Office in a room have distinct canonical IDs/names, with the same friendly +label distinguished by its taxonomy path. Active legacy/custom types absent from metadata are read +under Other with their existing IDs and names. + +Extend via a reviewed forward-only migration: insert an assignable LocationTypes row only when +needed, insert metadata with a unique stable key and existing parent key, choose an existing shared +icon key (or add SVG geometry to ApplicationRibbon), and specify order/tone/assignability. Never +renumber canonical IDs, change existing records or infer specialisations from manuscript text. +The reader and UI consume metadata; no feature-specific taxonomy switch/list is required. + +LocationWorkspace exposes `types` (assignable choices) and `taxonomy` (all nodes). The presentation +adapter resolves metadata icon keys through ApplicationRibbon. Details, type context menus and +traditional forms consume the same taxonomy. Parent-type filtering/counts include the category's +own value and all descendants using sets of assigned IDs; each location counts once. Grouping +headings filter but cannot be assigned or used as record drop targets. The server accepts only active +LocationTypes IDs (or NULL), rejecting heading keys independently of the client. + +Classification taxonomy is not physical containment. A Flat may be under Residential in this +catalogue and under any valid recorded parent in the author's world. No type-based containment +restriction or temporary/temporal tracking is introduced. Real/Fictional provenance remains separate. + +## Consumer compatibility audit + +- `LocationLookup_All`, `Location_Get`, `Location_ListByProject`, `Location_WorkspaceRead`, + `Location_WorkspaceAssign` and the existing model keep their assignable ID/name contracts. +- Import lookup procedures and `ImportServices` still resolve canonical IDs/names. Existing + StoryIntelligenceLocationImportService generic matching is not changed or re-run; old sort priority + is retained and new types follow it. This task adds no AI request or geocoding work. +- Project backup/export/restore and story-bible location summaries still use LocationTypeID and + canonical TypeName. Global taxonomy metadata is deployment configuration, not duplicated project data. +- Geography chain/hierarchy reads join the same IDs/names; explicit geography review remains intact. +- Maps, Floor Plans, Context and Word Companion keep their location identities, references, existing + detection/Quick Add flags and provider contracts. Their interfaces and focus/Hold/Follow are unchanged. + +Verification, screenshots, delivery identifiers and remaining environment limits are recorded below +once the final release has completed validation. + +## Reproduce the focused rendered checks + +Start the existing executable harness with `--toolbar-browser-host`. On a qualified disposable +Locations clone, export the current catalogue (metadata/icons only): + +```bash +dotnet run --project PlotLine.Tests -- --location-taxonomy-fixture /private/clone.json /tmp/pd-refinements-taxonomy.json +node PlotLine.Tests/Browser/workspace-refinements.cjs +xvfb-run -a node PlotLine.Tests/Browser/workspace-refinements.cjs --installed +node PlotLine.Tests/Browser/shared-attributes-comparison.cjs +xvfb-run -a node PlotLine.Tests/Browser/shared-attributes-comparison.cjs --installed +``` + +`PD_TAXONOMY_FIXTURE` can override the snapshot path. No second production taxonomy definition is +maintained in JavaScript. The browser tests use actual compiled Razor/shared assets with synthetic +HTTP mutations. `PlotLine.Tests/Sql/LocationTaxonomy.sql` is guarded to disposable clones and rolls +its fixtures back. Existing Characters and Locations browser regressions remain separate checks. diff --git a/Docs/UI/AttributesPanel.md b/Docs/UI/AttributesPanel.md new file mode 100644 index 00000000..be17d0f7 --- /dev/null +++ b/Docs/UI/AttributesPanel.md @@ -0,0 +1,53 @@ +# Shared Attributes panel standard + +The Locations tool palette is the visual standard for Attributes: compact rows, semantic icons, +aligned count and Assign columns, modest hover/active styling and independently scrolling panels. +Characters and Locations use the same `attributes-panel.js` renderer and `attributes-panel.css`. +Do not copy either workspace's former palette CSS. Character cards/biographies are outside this component. + +## Composition + +`PlotDirectorAttributesPanel.mount(host, options)` returns `update({counts: true})`. +Pass `groups` with `{id,label,editable,values}`. A value has `{value,label,key?,parentKey?,assignable?}` +and the consumer's icon presentation fields. Optional keys/parents form nested categories. The renderer +preserves supplied order; the canonical provider owns ordering. A non-assignable category can still +filter its descendants. The expand button operates independently of its filter button and Assign. + +Supply these callbacks: + +- `icon(value)` returns a safe DOM/SVG node. Do not interpolate labels into HTML. +- `count(group,value)` and `isActive(group,value)` derive current filter state. +- `onFilter(group,value)` applies a consumer-defined filter and refreshes the workspace. +- `onAssign(group,value)` executes the consumer's targeted single/bulk command. +- `onDragStart(event,group,value)` supplies that workspace's drag payload/preview. +- `canEdit()`, `busy()`, `hasSelection()` determine editable controls and drag state. +- `isExpanded(key,fallback)` and `onExpansion(key,open)` use workspace-scoped preferences. + +`recordLabel` customises accessible Assign labels. `rowClass` is an optional compatibility class. +Rows expose `data-attribute`, `data-value` and `data-assignable`; consumers retain their existing +record drop handlers. Only `data-assignable=true` accepts record drops. Consumers supply valid/invalid +drop feedback using `is-drop-target` / `is-invalid-target` and must enforce server validation. +The entire row/filter surface supports dragging; Assign and expansion controls do not start drags. + +Keep records, selection, filters, counts, no-op rules, concurrency, ownership, server requests, +Undo receipts, context commands and live refresh in the consumer. The shared renderer knows no +character/location-specific attribute names. `update({counts:false})` updates controls without +recomputing aggregates during selection changes. Do not remount after every local record update. + +## Layout, preferences and themes + +Compose with `PlotDirectorWorkspaceSurface.split` or an existing workspace profile for panel widths +and dividers. The palette does not create a second resize/persistence mechanism. The consuming +aside owns independent scrolling and collapse/restore. Scope preferences to the author/workspace; +project-specific expansion keys must also contain project ID. + +Characters retain their existing width/collapse keys and group order. Their expansion map is +`pd.character.attributes.v1...groups`. Locations retain +`pd.locations.workspace.v1..` and the existing divider scope; nested expansion keys +are `type:`. These do not collide with character group keys. + +Shared theme tokens supply colours. A container query adapts indentation, spacing and fixed columns +at narrow widths. Labels wrap to two lines with a complete tooltip; count/Assign columns stay aligned. +Native details/summary, buttons, pressed states and focus outlines provide keyboard alternatives. +Future Assets adoption should supply its own groups, state, commands and drag payload, compose the +existing divider, and use this renderer. No Assets implementation is included in this change. diff --git a/PlotLine.Tests/Browser/character-attributes.cjs b/PlotLine.Tests/Browser/character-attributes.cjs index b53ae396..2a350041 100644 --- a/PlotLine.Tests/Browser/character-attributes.cjs +++ b/PlotLine.Tests/Browser/character-attributes.cjs @@ -18,6 +18,8 @@ const {chromium}=require('playwright');const os=require('node:os'),path=require( await page.route('**/CharacterAttributes/Undo',async route=>{const token=route.request().postDataJSON().token,state=undo.get(token);assert(state);if(state.versions.some(([id,version])=>records.find(r=>r.id===id).version!==version))return route.fulfill({status:409,json:{message:'Characters changed in another window.'}});const changed=state.previous.map(old=>{const r=records.find(r=>r.id===old.id);r.values=old.values;r.version=`v${clock++}`;return r;});await route.fulfill({json:{saved:true,characters:changed}});}); assert.deepEqual(groups.map(g=>g.id),['importance','life','sex','type','quickAdd']); const start=Date.now();await page.goto(`http://127.0.0.1:5238/character-attributes-fixture?count=${count}`);await page.locator('[data-attribute="importance"]').first().waitFor();const load=Date.now()-start; + await page.locator('[data-attribute-groups] details[data-attribute-group=type]').evaluate(n=>n.open=true); // Independent fixture cases explicitly restore this now-persisted group. + const expose=async node=>{await page.evaluate(()=>document.querySelectorAll('[data-toast-host] button[aria-label^="Dismiss"]').forEach(b=>b.click()));await node.scrollIntoViewIfNeeded();}; const card=id=>page.locator(`.character-card[data-drag-id="${id}"]`),value=(a,v)=>page.locator(`[data-attribute="${a}"][data-value="${v}"]`); assert.deepEqual(await card(1).locator('[data-attribute-indicators]>span').evaluateAll(nodes=>nodes.map(n=>n.title.split(':')[0])),['Story importance','Life status','Sex','Character Type','Quick Add Bar']); @@ -78,6 +80,10 @@ const {chromium}=require('playwright');const os=require('node:os'),path=require( const width=await page.locator('.character-card-grid').evaluate(n=>n.getBoundingClientRect().width);await page.locator('[data-attributes-toggle]').click();assert(await page.locator('[data-attribute-sidebar]').isHidden());assert(await page.locator('.character-card-grid').evaluate(n=>n.getBoundingClientRect().width)>width);await page.locator('[data-attributes-toggle]').click(); if(count>=100){await page.evaluate(()=>{let n=document.querySelector('[data-character-attributes]');for(;n;n=n.parentElement){if(/auto|scroll/.test(getComputedStyle(n).overflowY)&&n.scrollHeight>n.clientHeight){n.scrollTo({top:1200,behavior:'instant'});return;}}window.scrollTo({top:1200,behavior:'instant'});});const box=await page.locator('[data-attribute-sidebar]').boundingBox();assert(box.y>=0&&box.y<1000&&box.y+box.height<=1001);await page.evaluate(()=>{let n=document.querySelector('[data-character-attributes]');for(;n;n=n.parentElement)n.scrollTo({top:0,left:0,behavior:'instant'});window.scrollTo({top:0,behavior:'instant'});});} await page.evaluate(()=>document.querySelectorAll('.pd-toast button[aria-label^="Dismiss"]').forEach(b=>b.click())); + if(count===100){ + for(const direction of ['Shift+ArrowRight','Shift+ArrowLeft']){for(let step=0;step<12;step++)await divider.press(direction);const positions=await page.locator('[data-attribute-groups] .pd-attribute-row').evaluateAll(ns=>ns.filter(n=>n.getClientRects().length).map(n=>({count:Math.round(n.querySelector('[data-count]').getBoundingClientRect().right),assign:Math.round(n.querySelector('[data-assign]').getBoundingClientRect().right)})));assert.equal(new Set(positions.map(p=>p.count)).size,1);assert.equal(new Set(positions.map(p=>p.assign)).size,1);} + await divider.press('Home'); + } for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);if(count===100)await page.screenshot({path:`/tmp/character-attributes-${installed?'installed-':''}${theme}.png`});} for(const [width,height] of [[1920,1080],[1440,900],[1366,768],[1280,720],[1024,768],[768,1024],[390,844]]){await page.setViewportSize({width,height});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));if(width>850&&count>=100){await page.evaluate(()=>window.scrollTo({top:1200,behavior:'instant'}));const bounds=await page.locator('[data-attribute-sidebar]').boundingBox();assert(bounds.y>=0&&bounds.y+bounds.height<=height+1);await page.evaluate(()=>window.scrollTo({top:0,behavior:'instant'}));}} assert.equal(await card(1).locator('.visual-card-heading p.muted').textContent(),biography);assert.deepEqual(errors,[]);results.push({count,loadMs:load,assignments:requests.length});await page.close(); diff --git a/PlotLine.Tests/Browser/locations-workspace.cjs b/PlotLine.Tests/Browser/locations-workspace.cjs index f357ce46..444307bc 100644 --- a/PlotLine.Tests/Browser/locations-workspace.cjs +++ b/PlotLine.Tests/Browser/locations-workspace.cjs @@ -4,9 +4,10 @@ const installed=process.argv.includes('--installed'),origin='http://127.0.0.1:52 (async()=>{const profile=installed?fs.mkdtempSync('/tmp/pd-locations-pwa-'):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}):null,browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null,manifestId=origin+'/Projects',results=[];if(installed){await persistent.pages()[0].goto(origin+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:origin+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});}async function newPage(){if(!installed)return browser.newPage({viewport:{width:1440,height:1000}});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:origin+'/fixture?page=calendar-test'});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return page;}try{for(const count of process.argv.includes('--persistence-only')?[50]:[50,200,500,1000]){ const page=await newPage(),errors=[],timings={};page.on('pageerror',e=>errors.push(e.message)); const types=await (await page.request.get(`${origin}/locations-workspace-types-fixture`)).json();let clock=0,requests=[],undo=new Map(),rejectNext=false,delayDirectory=false,releaseDirectory=null;const records=Array.from({length:count},(_,i)=>({id:i+1,name:['Meridian','Northern coast','Port Halcyon','Observatory','Reading room'][i]||`Location ${String(i+1).padStart(3,'0')}`,parent:i===0||i%13===0?null:i<10?i:Math.floor((i-1)/12)*12+1,type:String(i%9+1),typeName:types[i%9].label,classification:i%4===0?'Fictional':'',description:i%5===0?'':('Salt air drifts through the open windows. The old charts record a coastline changed by generations of storms. ').repeat(i%7+1),quickAdd:'0',detection:'0',version:`v${clock++}`,aliases:i===4?['Quiet study']:[],maps:i%5===0?[{id:1,name:'Coast chart'}]:[],floors:i%7===0?[{id:2,name:'Observatory floors'}]:[],scenes:i%3})); - records[count-1].parent=2147483647; records[0].maps.push({id:2,name:'Northern chart'});records[0].floors.push({id:3,name:'Annex floor plan'}); if(count>=500){for(let i=count-100;i{const snapshot=structuredClone(records);if(delayDirectory){delayDirectory=false;await new Promise(resolve=>releaseDirectory=resolve);}await r.fulfill({json:{canEdit:true,types,locations:snapshot}});}); await page.route('**/LocationWorkspace/Assign',async route=>{assert(route.request().headers().requestverificationtoken);const input=route.request().postDataJSON();requests.push(input);if(rejectNext){rejectNext=false;return route.fulfill({status:409,json:{message:'Simulated concurrent edit rejected.'}});}let changes=input.changes;const ids=new Set(changes.map(c=>c.id));if(input.attribute==='parent')changes=changes.filter(c=>{let p=records.find(r=>r.id===c.id).parent;const seen=new Set();while(p&&!seen.has(p)){if(ids.has(p))return false;seen.add(p);p=records.find(r=>r.id===p)?.parent;}return true;});const previous=[],changed=[];for(const c of changes){const r=records.find(r=>r.id===c.id);if(r.version!==c.version)return route.fulfill({status:409,json:{message:'Changed in another window.'}});previous.push({id:r.id,value:r[input.attribute],version:r.version});r[input.attribute]=input.attribute==='parent'?(c.value?Number(c.value):null):c.value;r.version=`v${clock++}`;changed.push({id:r.id,value:c.value,version:r.version});}const token=`u${clock}`;undo.set(token,{attribute:input.attribute,previous});await route.fulfill({json:{saved:true,changes:changed,attribute:input.attribute,undoToken:token}});}); await page.route('**/LocationWorkspace/Undo',async route=>{const receipt=undo.get(route.request().postDataJSON().token),changes=[];for(const old of receipt.previous){const r=records.find(r=>r.id===old.id);r[receipt.attribute]=old.value;r.version=`v${clock++}`;changes.push({id:r.id,value:old.value?.toString()||'',version:r.version});}await route.fulfill({json:{saved:true,changes,attribute:receipt.attribute,undoToken:'unused-redo-token'}});}); @@ -31,7 +32,7 @@ const installed=process.argv.includes('--installed'),origin='http://127.0.0.1:52 await row(4).focus();await page.keyboard.press('F2');const rename=row(4).getByRole('textbox',{name:'Location name'});await rename.fill('West observatory');await shot('inline-rename');const renameStart=performance.now();await rename.press('Enter');await page.waitForTimeout(80);timings.renameMs=Math.round(performance.now()-renameStart);assert.equal(records[3].name,'West observatory');if(count===50){await row(4).focus();await page.keyboard.press('F2');await row(4).getByRole('textbox',{name:'Location name'}).fill('Discard this name');await page.keyboard.press('Escape');assert.equal(records[3].name,'West observatory');} await row(4).click({button:'right'});await page.getByRole('menu').first().waitFor();await shot('context-menu');await page.keyboard.press('Escape');if(count===50){await row(4).focus();await page.keyboard.press('Shift+F10');await page.getByRole('menu').first().waitFor();await page.keyboard.press('Escape');} await row(4).locator('[data-location-name]').click();await page.getByRole('button',{name:'Create child location',exact:true}).click();await page.getByRole('textbox',{name:'New location name'}).fill('Chart room');await shot('create-child');await page.locator('[data-dialog-save]').click();await page.waitForTimeout(150);assert.equal(records.at(-1).parent,4); - await row(4).locator('[data-location-name]').click();await page.getByRole('button',{name:'Edit description',exact:true}).click();const description=page.getByRole('textbox',{name:'Location description'});await description.fill('Preserved author prose.\nSecond paragraph.');if(count===50){await row(4).locator('[data-location-name]').click();assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');page.once('dialog',d=>d.accept());await page.getByRole('button',{name:'Create child location',exact:true}).click();await page.locator('[data-dialog-cancel]').click();assert.equal(await page.locator('[data-description-editor]').count(),0);await page.getByRole('button',{name:'Edit description',exact:true}).click();await description.fill('Preserved author prose.\nSecond paragraph.');}page.once('dialog',d=>d.dismiss());await row(1).locator('[data-location-name]').click();assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');await shot('details-edit');if(count===50){await drag(attribute('type','6').locator('button').first(),row(4));assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');assert.equal(await page.locator('[data-details]').getByRole('combobox',{name:'Location type',exact:true}).inputValue(),'6');}await page.locator('[data-details]').getByRole('button',{name:'Save',exact:true}).click();await page.waitForTimeout(100);assert.equal(records[3].description,'Preserved author prose.\nSecond paragraph.'); + await row(4).locator('[data-location-name]').click();await page.getByRole('button',{name:'Edit description',exact:true}).click();const description=page.getByRole('textbox',{name:'Location description'});await description.fill('Preserved author prose.\nSecond paragraph.');if(count===50){await row(4).locator('[data-location-name]').click();assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');page.once('dialog',d=>d.accept());await page.getByRole('button',{name:'Create child location',exact:true}).click();await page.locator('[data-dialog-cancel]').click();assert.equal(await page.locator('[data-description-editor]').count(),0);await page.getByRole('button',{name:'Edit description',exact:true}).click();await description.fill('Preserved author prose.\nSecond paragraph.');}page.once('dialog',d=>d.dismiss());await row(1).locator('[data-location-name]').click();assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');await shot('details-edit');if(count===50){await drag(attribute('type','6').locator('button').first(),row(4));assert.equal(await description.inputValue(),'Preserved author prose.\nSecond paragraph.');assert.equal(await page.locator('[data-details]').getByRole('button',{name:'Location type',exact:true}).textContent(),'Room');}await page.locator('[data-details]').getByRole('button',{name:'Save',exact:true}).click();await page.waitForTimeout(100);assert.equal(records[3].description,'Preserved author prose.\nSecond paragraph.'); const searchStart=performance.now();await page.locator('[data-search]').fill('Quiet study');await page.waitForTimeout(80);assert(await row(5).isVisible());assert(await row(1).isVisible());const searchMs=Math.round(performance.now()-searchStart);await shot('search-context');await page.locator('[data-clear-search]').click(); await row(1).locator('[data-select-location]').check();const cardsStart=performance.now();await page.getByRole('button',{name:'Cards',exact:true}).click();timings.cardsMs=Math.round(performance.now()-cardsStart);assert(await row(1).locator('[data-select-location]').isChecked());await shot('cards');const heights=await page.locator('.location-record').evaluateAll(ns=>ns.slice(0,12).map(n=>n.getBoundingClientRect().height));assert(new Set(heights.map(Math.round)).size>3); if(count===50){ @@ -39,7 +40,7 @@ const installed=process.argv.includes('--installed'),origin='http://127.0.0.1:52 await page.getByRole('button',{name:'Hierarchy',exact:true}).click();assert.equal(await fictional.getAttribute('aria-pressed'),'true');assert(await row(1).locator('[data-select-location]').isChecked());await page.getByRole('button',{name:'Cards',exact:true}).click(); await attribute('classification','Real').getByRole('button',{name:/Assign/}).click();await page.waitForTimeout(100);assert(!(await row(1).count()));assert.equal(records[0].classification,'Real');assert.match(await page.locator('[data-result-count]').textContent(),new RegExp('^'+(matching-1)+' of '));await page.getByRole('button',{name:'Undo',exact:true}).first().click();await row(1).waitFor(); await page.locator('[data-clear-filters]').click();await attribute('mapState','yes').locator('button').click();assert.equal(await page.locator('[data-location-id]').count(),records.filter(r=>r.maps.length).length);assert.equal(await attribute('mapState','yes').locator('[data-assign]').count(),0);await page.locator('[data-clear-filters]').click(); - await page.locator('[data-branch-filter]').click();await page.getByRole('listbox',{name:'Parent location'}).selectOption('1');await page.locator('[data-dialog-save]').click();const inBranch=r=>{const seen=new Set();while(r&&!seen.has(r.id)){if(r.id===1)return true;seen.add(r.id);r=records.find(x=>x.id===r.parent);}return false;};assert.equal(await page.locator('[data-location-id]').count(),records.filter(inBranch).length);await page.locator('[data-clear-filters]').click(); + await page.locator('[data-branch-filter]').click();await page.locator('[data-location-dialog] [data-picker-id="1"] .pd-location-picker-name').click();await page.locator('[data-dialog-save]').click();const inBranch=r=>{const seen=new Set();while(r&&!seen.has(r.id)){if(r.id===1)return true;seen.add(r.id);r=records.find(x=>x.id===r.parent);}return false;};assert.equal(await page.locator('[data-location-id]').count(),records.filter(inBranch).length);await page.locator('[data-clear-filters]').click(); } await page.getByRole('button',{name:'Hierarchy',exact:true}).click();await page.locator('[data-clear-selection]').click();const divider=page.getByRole('separator',{name:'Resize left panel'});await divider.press('ArrowRight');const right=page.getByRole('separator',{name:'Resize right panel'});await right.press('ArrowLeft');if(count===50)for(const [handle,delta]of [[divider,55],[right,-55]]){const box=await handle.boundingBox(),before=Number(await handle.getAttribute('aria-valuenow'));await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(box.x+box.width/2+delta,box.y+box.height/2,{steps:8});await page.mouse.up();assert(Number(await handle.getAttribute('aria-valuenow'))>=before+50);}await shot('resized-panels'); diff --git a/PlotLine.Tests/Browser/shared-attributes-comparison.cjs b/PlotLine.Tests/Browser/shared-attributes-comparison.cjs new file mode 100644 index 00000000..bddf76a6 --- /dev/null +++ b/PlotLine.Tests/Browser/shared-attributes-comparison.cjs @@ -0,0 +1,14 @@ +// Both consumers in one authenticated fixture session: shared appearance, independent preferences. +const{chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict');const base='http://127.0.0.1:5238',out='/tmp/pd-refinements-evidence',installed=process.argv.includes('--installed'),taxonomy=JSON.parse(fs.readFileSync(process.env.PD_TAXONOMY_FIXTURE||'/tmp/pd-refinements-taxonomy.json')); +(async()=>{let browser,context,cdp,profile;try{if(installed){profile=fs.mkdtempSync('/tmp/pd-shared-attributes-pwa-');context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}});browser=context.browser();cdp=await browser.newBrowserCDPSession();await context.pages()[0].goto(base+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:base+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});}else{browser=await chromium.launch();context=await browser.newContext({viewport:{width:1440,height:1000}});}let page;if(installed){const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId:base+'/Projects',url:base+'/fixture?page=calendar-test'});page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));const groups=await(await page.request.get(base+'/character-attribute-definitions-fixture')).json(); + await page.route('**/CharacterAttributes/Directory?*',r=>r.fulfill({json:{canEdit:true,groups,characters:Array.from({length:20},(_,i)=>({id:i+1,name:`Fixture character ${i+1}`,version:'v1',values:{importance:i%2?'6':'10',life:i%2?'0':'1',sex:i%2?'1':'2',type:'person',quickAdd:i%2?'0':'1'}}))}})); + await page.route('**/LocationWorkspace/Directory?*',r=>r.fulfill({json:{canEdit:true,types:taxonomy.filter(t=>t.assignable),taxonomy,locations:Array.from({length:20},(_,i)=>({id:i+1,name:`Zone ${i+1}`,parent:i?1:null,type:taxonomy.find(t=>t.key===(i%2?'room':'house')).value,classification:'',description:'Complete synthetic location description. '.repeat(i%5+1),aliases:[],maps:[],floors:[],scenes:0,characters:0,assets:0,relationships:0,quickAdd:'0',detection:'0',version:'v1'}))}})); + const theme=async name=>page.evaluate(name=>{document.documentElement.dataset.appTheme=name;document.documentElement.dataset.bsTheme=name.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=name.endsWith('dark')?'dark':'light';},name); + await page.goto(base+'/locations-workspace-fixture?count=20');await page.locator('[data-location-records][aria-busy=false]').waitFor();await page.locator('[data-value="@premises"] .pd-attribute-expand').click();const residential=taxonomy.find(t=>t.key==='residential').value;await page.locator(`[data-attribute=type][data-value="${residential}"] .pd-attribute-expand`).click();await page.getByRole('separator',{name:'Resize left panel'}).press('ArrowRight');await page.waitForTimeout(100);const locationStorage=await page.evaluate(()=>Object.fromEntries(Object.keys(localStorage).filter(k=>k.includes('locations')).map(k=>[k,localStorage.getItem(k)]))); + for(const name of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await theme(name);await page.locator('.locations-attributes').screenshot({path:`${out}/locations-attributes-${installed?'pwa':'browser'}-${name}.png`});} + await page.goto(base+'/character-attributes-fixture?count=20');await page.locator('[data-attribute=importance]').first().waitFor();const group=page.locator('details[data-attribute-group=type]');await group.locator('summary').click();assert.equal(await group.evaluate(n=>n.open),false);const divider=page.getByRole('separator',{name:'Resize Attributes panel'});await divider.press('ArrowRight');const charWidth=await page.locator('[data-attribute-sidebar]').evaluate(n=>Math.round(n.getBoundingClientRect().width)); + for(const name of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await theme(name);await page.locator('[data-attribute-sidebar]').screenshot({path:`${out}/characters-attributes-${installed?'pwa':'browser'}-${name}.png`});} + await theme('modern-light');await page.screenshot({path:`${out}/characters-cards-${installed?'pwa':'browser'}.png`});const biography=await page.locator('.character-card').first().locator('.visual-card-heading p.muted').textContent();assert(biography.includes('Complete biography for character 1'));const heights=await page.locator('.character-card').evaluateAll(ns=>ns.slice(0,9).map(n=>Math.round(n.getBoundingClientRect().height)));assert(new Set(heights).size>1); + await page.goto(base+'/locations-workspace-fixture?count=20');await page.locator('[data-location-records][aria-busy=false]').waitFor();await page.waitForTimeout(100);assert.deepEqual(await page.evaluate(()=>Object.fromEntries(Object.keys(localStorage).filter(k=>k.includes('locations')).map(k=>[k,localStorage.getItem(k)]))),locationStorage);assert(await page.locator(`[data-attribute=type][data-value="${taxonomy.find(t=>t.key==='house').value}"]`).isVisible()); + await page.goto(base+'/character-attributes-fixture?count=20');await page.locator('[data-attribute=importance]').first().waitFor();assert.equal(await page.locator('details[data-attribute-group=type]').evaluate(n=>n.open),false);assert.equal(await page.locator('[data-attribute-sidebar]').evaluate(n=>Math.round(n.getBoundingClientRect().width)),charWidth);assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/shared-${installed?'pwa':'browser'}.json`,JSON.stringify({status:'passed',themes:7,checks:['both real consumers use shared renderer','same-session independent group/width preferences','width and nested expansion restore','unaltered character biographies and variable card dimensions']},null,2));console.log('PASS same-session shared Attributes styling, seven themes, independent state and unaltered character cards.'); + }finally{if(cdp)await cdp.send('PWA.uninstall',{manifestId:base+'/Projects'}).catch(()=>{});if(context)await context.close();if(browser?.isConnected())await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/workspace-refinements.cjs b/PlotLine.Tests/Browser/workspace-refinements.cjs new file mode 100644 index 00000000..9064f6d7 --- /dev/null +++ b/PlotLine.Tests/Browser/workspace-refinements.cjs @@ -0,0 +1,42 @@ +// Actual Razor and shared assets; catalogue snapshot exported from a disposable qualified SQL clone. +const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); +const taxonomy=JSON.parse(fs.readFileSync(process.env.PD_TAXONOMY_FIXTURE||'/tmp/pd-refinements-taxonomy.json','utf8')); +const base='http://127.0.0.1:5238',out='/tmp/pd-refinements-evidence',installed=process.argv.includes('--installed');fs.mkdirSync(out,{recursive:true}); +const type=key=>taxonomy.find(t=>t.key===key).value; +(async()=>{let browser,context,cdp,profile;const results=[];try{ + if(installed){profile=fs.mkdtempSync('/tmp/pd-refinements-pwa-');context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}});browser=context.browser();cdp=await browser.newBrowserCDPSession();await context.pages()[0].goto(base+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:base+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'}); + }else browser=await chromium.launch(); + for(const count of [50,500,1000]){ + let page;if(installed){const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId:base+'/Projects',url:base+'/fixture?page=calendar-test'});page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else page=await browser.newPage({viewport:{width:1440,height:1000}}); + const errors=[];page.on('pageerror',e=>errors.push(e.message));let clock=0,requests=[],receipts=new Map();let records=Array.from({length:count},(_,i)=>({id:i+1,name:i===0?'Zeta system':i===1?'Alpha country':i===2||i===4?'Control room':i===3?'Western district':i===5?'Omega colony':`Level ${String(i+1).padStart(4,'0')}`,parent:i<6?([null,null,1,2,4,null][i]):i<105?(i===6?6:i):null,type:type(['house','city','room','residential','flat'][i%5]),typeName:'',classification:'',description:i%3===0?'Complete, author-entered synthetic description.\n'+('A substantial location history remains visible. '.repeat(15)):'',aliases:i===4?['Old observatory']:[],maps:[],floors:[],scenes:0,relationships:0,characters:0,assets:0,quickAdd:'0',detection:'0',version:`v${clock++}`})); + for(const [offset,name]of ['Amber bay','Zebra gate','Birch lane'].entries()){const record=records[(count===50?9:105)+offset];record.parent=4;record.name=name;} + const directory=()=>({canEdit:true,types:taxonomy.filter(t=>t.assignable),taxonomy,locations:records}); + await page.route('**/LocationWorkspace/Directory?*',route=>route.fulfill({json:directory()}));await page.route('**/LocationWorkspace/Picker?*',route=>route.fulfill({json:directory()}));await page.route('**/LocationWorkspace/Taxonomy',route=>route.fulfill({json:taxonomy})); + await page.route('**/LocationWorkspace/Assign',route=>{const input=route.request().postDataJSON(),previous=[];requests.push(input);for(const c of input.changes){const r=records.find(r=>r.id===c.id);assert.equal(r.version,c.version);const old=input.attribute==='parent'?r.parent==null?'':String(r.parent):r[input.attribute];if(old===c.value)continue;previous.push({id:r.id,value:old});if(input.attribute==='parent')r.parent=c.value?Number(c.value):null;else r[input.attribute]=c.value;r.version=`v${clock++}`;}const token=`receipt-${clock}`;receipts.set(token,{attribute:input.attribute,previous});return route.fulfill({json:{attribute:input.attribute,changes:previous.map(c=>({id:c.id,value:input.changes.find(x=>x.id===c.id).value,version:records.find(r=>r.id===c.id).version})),undoToken:token}});}); + await page.route('**/LocationWorkspace/Undo',route=>{const receipt=receipts.get(route.request().postDataJSON().token);const changes=receipt.previous.map(c=>{const r=records.find(r=>r.id===c.id);if(receipt.attribute==='parent')r.parent=c.value?Number(c.value):null;else r[receipt.attribute]=c.value;r.version=`v${clock++}`;return{id:r.id,value:c.value,version:r.version};});return route.fulfill({json:{attribute:receipt.attribute,changes}});}); + await page.route('**/LocationWorkspace/Merge',route=>{const input=route.request().postDataJSON();requests.push({merge:input});assert(input.confirm);assert.equal(input.sourceVersion,records.find(r=>r.id===input.sourceId).version);assert.equal(input.targetVersion,records.find(r=>r.id===input.targetId).version);for(const r of records)if(r.parent===input.sourceId)r.parent=input.targetId;records=records.filter(r=>r.id!==input.sourceId);return route.fulfill({json:{id:input.targetId}});}); + const start=performance.now();await page.goto(base+`/locations-workspace-fixture?count=${count}`);await page.locator('[data-location-records][aria-busy=false]').waitFor();const loadMs=Math.round(performance.now()-start),row=id=>page.locator(`[data-location-id="${id}"]`),attribute=key=>page.locator(`[data-attribute=type][data-value="${type(key)}"]`),group=key=>page.locator(`[data-attribute=type][data-value="@${key}"]`),expand=async locator=>{const b=locator.locator('.pd-attribute-expand');if(await b.getAttribute('aria-expanded')==='false')await b.click();}; + await expand(group('premises'));await expand(attribute('residential'));assert(await attribute('house').isVisible());assert.equal(await group('premises').locator('[data-assign]').count(),0);assert.equal(await attribute('residential').locator('[data-assign]').count(),1); + const residentialValues=new Set(['residential','house','flat'].map(type)),expected=records.filter(r=>residentialValues.has(r.type)).length;assert.equal(Number(await attribute('residential').locator('[data-count]').textContent()),expected); + await attribute('residential').locator('[data-attribute-filter]').click();assert.match(await page.locator('[data-result-count]').textContent(),new RegExp(`^${expected} of `));await page.getByRole('button',{name:'Cards',exact:true}).click();assert.equal(await page.locator('[data-location-id]').count(),expected); + await page.getByRole('button',{name:'Select displayed',exact:true}).click();await expand(attribute('institutional'));await attribute('hospital').locator('[data-assign]').click();await page.waitForTimeout(100);assert.equal(requests.at(-1).changes.length,expected);assert.equal(await page.locator('[data-location-id]').count(),0);await page.locator('[data-undo]').click();await page.waitForTimeout(100);assert.equal(records.filter(r=>residentialValues.has(r.type)).length,expected);await page.locator('[data-clear-filters]').click();await page.getByRole('button',{name:'Hierarchy',exact:true}).click(); + if(count===50){ + await row(1).locator('[data-location-name]').click();await page.locator('[data-clear-selection]').click();await attribute('house').locator('[data-attribute-filter]').dragTo(row(2));await page.waitForTimeout(100);assert.equal(records[1].type,type('house'));await page.locator('[data-undo]').click();await page.waitForTimeout(100);assert.equal(records[1].type,type('city')); + await row(2).locator('[data-drag-location]').dragTo(attribute('house'));await page.waitForTimeout(100);assert.equal(records[1].type,type('house'));await page.locator('[data-undo]').click();await page.waitForTimeout(100); + await page.reload();await page.locator('[data-location-records][aria-busy=false]').waitFor();assert(await attribute('house').isVisible(),'nested category state persists');await row(1).locator('[data-location-name]').click(); + await page.locator('[data-details]').getByRole('button',{name:'Location type',exact:true}).click();const typeDialog=page.locator('dialog.pd-location-picker-dialog');await typeDialog.getByRole('searchbox',{name:'Search location types'}).fill('Office');assert.equal(await typeDialog.getByRole('button',{name:'Office',exact:true}).count(),2);await typeDialog.locator('[data-picker-id=office-room] .pd-location-picker-name').click();assert.match(await typeDialog.locator('[role=status]').textContent(),/Interior spaces \/ Room \/ Office/);await typeDialog.getByRole('button',{name:'Choose type',exact:true}).click();await page.waitForTimeout(100);assert.equal(records[0].type,type('office-room'));await page.locator('[data-undo]').click();await page.waitForTimeout(100); + await page.getByRole('button',{name:'Change parent',exact:true}).click();let dialog=page.locator('[data-location-dialog]');const roots=await dialog.locator('[data-picker-id][aria-level="1"]').evaluateAll(ns=>ns.map(n=>n.dataset.pickerId));assert.deepEqual(roots,['','2','6','1']);assert.equal(await dialog.locator('[data-picker-id="1"]').getAttribute('aria-disabled'),'true');await dialog.locator('[data-picker-id="1"]>button').click();assert.equal(await dialog.locator('[data-picker-id="3"]').getAttribute('aria-disabled'),'true');await dialog.locator('[data-picker-id="2"]>button').click();await dialog.locator('[data-picker-id="4"]>button').click();assert.deepEqual(await dialog.locator('[aria-level="3"] .pd-location-picker-name').allTextContents(),['Amber bay','Birch lane','Control room','Zebra gate']); + await dialog.getByRole('searchbox',{name:'Search locations'}).fill('old observatory');assert(await dialog.locator('[data-picker-id="5"]').isVisible());assert(await dialog.locator('[data-picker-id="2"]').isVisible());await dialog.getByRole('searchbox',{name:'Search locations'}).fill('Alpha country / Western district');assert(await dialog.locator('[data-picker-id="5"]').isVisible());await dialog.locator('[data-picker-id="5"] .pd-location-picker-name').click();assert.match(await dialog.locator('[role=status]').textContent(),/Alpha country \/ Western district \/ Control room/);await page.screenshot({path:`${out}/picker-${installed?'pwa':'browser'}.png`});await page.locator('[data-dialog-save]').click();await page.waitForTimeout(100);assert.equal(records[0].parent,5);assert.equal(records[2].parent,1);await page.reload();await page.locator('[data-location-records][aria-busy=false]').waitFor();assert.equal(records[0].parent,5); + await page.locator('[data-expand=true]').click();await row(1).locator('[data-location-name]').click();await page.getByRole('button',{name:'Change parent',exact:true}).click();dialog=page.locator('[data-location-dialog]');await dialog.getByRole('searchbox',{name:'Search locations'}).fill('nothing matches this');assert(await dialog.getByText(/No matching locations/).isVisible());await dialog.getByRole('button',{name:'Clear search',exact:true}).click();await dialog.locator('[data-picker-id=""]').focus();await page.keyboard.press('ArrowDown');await page.keyboard.press('Enter');assert.match(await dialog.locator('[role=status]').textContent(),/Alpha country/);await dialog.locator('[data-picker-id=""]').click();await page.locator('[data-dialog-save]').click();await page.waitForTimeout(100);assert.equal(records[0].parent,null);assert.equal(records[2].parent,1); + await row(1).locator('[data-location-name]').click();await page.locator('[data-details]').getByRole('button',{name:'Location type',exact:true}).click();await typeDialog.getByRole('searchbox',{name:'Search location types'}).fill('house');await typeDialog.getByRole('button',{name:'House',exact:true}).click();await typeDialog.getByRole('button',{name:'Choose type',exact:true}).click(); // Existing value is a no-op. + await row(1).evaluate(n=>n.scrollIntoView({block:'center',behavior:'instant'}));await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));await row(1).click({button:'right'});await page.getByRole('menuitem',{name:'Location type',exact:true}).hover();await page.getByRole('menuitem',{name:'Buildings and premises',exact:true}).hover();await page.getByRole('menuitem',{name:'Residential',exact:true}).hover();await page.getByRole('menuitemradio',{name:'Assign Residential',exact:true}).click();await page.waitForTimeout(100);assert.equal(records[0].type,type('residential')); + await page.locator('[data-sort]').selectOption('desc');await row(1).evaluate(n=>n.scrollIntoView({block:'center',behavior:'instant'}));await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));await row(1).click({button:'right'});await page.getByRole('menuitem',{name:'Merge with another location…',exact:true}).click();dialog=page.locator('[data-location-dialog]');await dialog.getByRole('searchbox',{name:'Search locations'}).fill('Control room');assert.equal(await dialog.getByRole('button',{name:'Control room',exact:true}).count(),2);assert.equal(await dialog.locator('[data-picker-id="3"]').getAttribute('aria-disabled'),'true');await dialog.locator('[data-picker-id="2"]>button').click();await dialog.locator('[data-picker-id="4"]>button').click();assert.deepEqual(await dialog.locator('[aria-level="3"] .pd-location-picker-name').allTextContents(),['Amber bay','Birch lane','Control room','Zebra gate']);await dialog.locator('[data-picker-id="5"] .pd-location-picker-name').click();await page.locator('[data-dialog-save]').click();assert.match(await page.locator('[data-dialog-error]').textContent(),/confirm/);await dialog.locator('input[type=checkbox]').check();await page.locator('[data-dialog-save]').click();await dialog.waitFor({state:'hidden'});assert(requests.some(r=>r.merge?.targetId===5)); + } + if(count>50){await row(1).locator('[data-location-name]').click();const pickerStart=performance.now();await page.getByRole('button',{name:'Change parent',exact:true}).click();const dialog=page.locator('[data-location-dialog]');await dialog.getByRole('searchbox',{name:'Search locations'}).fill('Level 0105');const deep=dialog.locator('[data-picker-id="105"]');await deep.waitFor();assert(Number(await deep.getAttribute('aria-level'))>=99);await deep.locator('.pd-location-picker-name').click();assert((await dialog.locator('[role=status]').textContent()).length>1000);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));if(count===1000)await page.screenshot({path:`${out}/picker-large-${installed?'pwa':'browser'}.png`});await page.locator('[data-dialog-save]').click();await page.waitForTimeout(100);assert.equal(records[0].parent,105);assert.equal(records[2].parent,1);console.log('Large/deep picker',count,Math.round(performance.now()-pickerStart),'ms');} + await page.locator('[data-clear-filters]').click();await page.getByRole('button',{name:'Cards',exact:true}).click();const heights=await page.locator('.location-record').evaluateAll(ns=>ns.slice(0,10).map(n=>Math.round(n.getBoundingClientRect().height)));assert(new Set(heights).size>1); + const measurements=[];for(const width of [1024,1440,1920]){await page.setViewportSize({width,height:1000});for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));if(count===50&&width===1440)await page.screenshot({path:`${out}/taxonomy-${installed?'pwa':'browser'}-${theme}.png`});}measurements.push(width);} + const divider=page.getByRole('separator',{name:'Resize left panel'});for(const direction of ['Shift+ArrowRight','Shift+ArrowLeft']){for(let step=0;step<12;step++)await divider.press(direction);const rects=await page.locator('[data-groups] .pd-attribute-row').evaluateAll(ns=>ns.filter(n=>n.getClientRects().length&&n.querySelector('[data-assign]')).map(n=>({count:n.querySelector('[data-count]').getBoundingClientRect().right,assign:n.querySelector('[data-assign]').getBoundingClientRect().right})));assert(new Set(rects.map(r=>Math.round(r.assign))).size<=1,'Assign column aligns');assert(new Set(rects.map(r=>Math.round(r.count))).size<=1,'count column aligns: '+JSON.stringify(rects));} + assert.deepEqual(errors,[]);results.push({count,loadMs,assignments:requests.length,themes:7,widths:measurements});await page.close(); + } + fs.writeFileSync(`${out}/results-${installed?'pwa':'browser'}.json`,JSON.stringify({status:'passed',results},null,2));console.log('PASS hierarchical picker, canonical taxonomy, nested counts/filtering/assignment/Undo, native bidirectional drag, menus, merge review, persistence, seven themes, widths and variable cards',results); + }finally{if(cdp)await cdp.send('PWA.uninstall',{manifestId:base+'/Projects'}).catch(()=>{});if(context)await context.close();else if(browser)await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs b/PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs index 72a7f8e3..5f28ac4f 100644 --- a/PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs +++ b/PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs @@ -9,6 +9,17 @@ using PlotLine.Data; internal static class LocationsWorkspaceDatabaseTests { + public static async Task ExportTaxonomy(string configPath, string outputPath) + { + using var config=JsonDocument.Parse(await File.ReadAllTextAsync(configPath)); + var builder=new SqlConnectionStringBuilder(config.RootElement.GetProperty("connection").GetString()); + if(builder.DataSource!="192.168.10.10,1433"||!builder.InitialCatalog.StartsWith("PlotDirector_Qualification_Locations",StringComparison.Ordinal))throw new InvalidOperationException("Disposable Locations clone required."); + using var db=new SqlConnection(builder.ConnectionString); + var taxonomy=await db.QueryAsync("dbo.LocationTypeTaxonomy_Read",commandType:CommandType.StoredProcedure); + await File.WriteAllTextAsync(outputPath,JsonSerializer.Serialize(taxonomy.Select(PlotLine.Services.LocationWorkspaceIcons.Presentation),new JsonSerializerOptions(JsonSerializerDefaults.Web))); + Console.WriteLine("PASS exported canonical taxonomy presentation from disposable clone; no manuscript data."); + } + public static async Task Run(string configPath) { using var config=JsonDocument.Parse(await File.ReadAllTextAsync(configPath)); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 98861e7f..ad4b1a9e 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -15,6 +15,7 @@ using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; +if(args.Contains("--location-taxonomy-fixture")){await LocationsWorkspaceDatabaseTests.ExportTaxonomy(args[^2],args[^1]);return;} if(args.Contains("--locations-workspace-database")){await LocationsWorkspaceDatabaseTests.Run(args.Last());return;} if(args.Contains("--shared-focus-concurrent")){await SharedFocusDatabaseTests.Concurrent();return;} if(args.Contains("--shared-focus-cleanup")){await SharedFocusDatabaseTests.Concurrent(true);return;} diff --git a/PlotLine.Tests/Sql/LocationTaxonomy.sql b/PlotLine.Tests/Sql/LocationTaxonomy.sql new file mode 100644 index 00000000..819bb624 --- /dev/null +++ b/PlotLine.Tests/Sql/LocationTaxonomy.sql @@ -0,0 +1,50 @@ +-- Disposable qualification clones only. No committed author-data changes. +SET NOCOUNT ON; +SET XACT_ABORT ON; +IF DB_NAME() NOT LIKE N'PlotDirector_Qualification_Locations%' THROW 51000,'Disposable Locations clone required.',1; +IF (SELECT COUNT(*) FROM dbo.LocationTypeTaxonomy)<100 THROW 51000,'Expanded taxonomy missing.',1; +IF EXISTS(SELECT 1 FROM dbo.LocationTypeTaxonomy x LEFT JOIN dbo.LocationTypes t ON t.LocationTypeID=x.LocationTypeID WHERE x.IsAssignable=1 AND x.TypeKey<>N'unclassified' AND t.LocationTypeID IS NULL) THROW 51000,'Assignable type missing.',1; +IF EXISTS(SELECT 1 FROM dbo.LocationTypeTaxonomy WHERE IsAssignable=0 AND LocationTypeID IS NOT NULL) THROW 51000,'Grouping leaked into assignable IDs.',1; +IF NOT EXISTS(SELECT 1 FROM dbo.LocationTypeTaxonomy WHERE TypeKey=N'office-room' AND ParentKey=N'room') OR NOT EXISTS(SELECT 1 FROM dbo.LocationTypeTaxonomy WHERE TypeKey=N'office-premises' AND ParentKey=N'commercial') THROW 51000,'Office contexts lost.',1; +PRINT 'PASS 105-node canonical taxonomy, assignable/group separation and disambiguated Office contexts'; +DECLARE @p int,@u int; +SELECT TOP(1) @p=p.ProjectID,@u=a.UserID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.IsArchived=0 AND a.IsActive=1 AND a.AccessRole=N'Owner' ORDER BY p.ProjectID; +BEGIN TRANSACTION; +DECLARE @id int,@second int; +INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Taxonomy fixture root');SET @id=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Taxonomy fixture child',@id);SET @second=SCOPE_IDENTITY(); +DECLARE @key nvarchar(80),@type int,@version nvarchar(50),@changes nvarchar(max); +DECLARE choices CURSOR LOCAL FAST_FORWARD FOR SELECT TypeKey,LocationTypeID FROM dbo.LocationTypeTaxonomy WHERE TypeKey IN(N'city',N'building',N'residential',N'house',N'room',N'kitchen',N'office-room',N'office-premises',N'hospital',N'spacecraft'); +OPEN choices;FETCH NEXT FROM choices INTO @key,@type; +WHILE @@FETCH_STATUS=0 +BEGIN + SELECT @version=CONVERT(nvarchar(50),UpdatedDate,126) FROM dbo.Locations WHERE LocationID=@id; + SET @changes=(SELECT @id AS Id,CONVERT(nvarchar(20),@type) AS Value,@version AS Version FOR JSON PATH); + EXEC dbo.Location_WorkspaceAssign @p,@u,N'type',@changes; + IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@id AND LocationTypeID=@type AND ParentLocationID IS NULL AND Classification IS NULL) THROW 51000,'Type assignment changed unrelated data.',1; + IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@second AND ParentLocationID=@id) THROW 51000,'Type assignment imposed containment restrictions.',1; + SET @changes=(SELECT LocationID AS Id,N'' AS Value,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@id,@second) AND LocationTypeID IS NOT NULL FOR JSON PATH); + EXEC dbo.Location_WorkspaceAssign @p,@u,N'type',@changes,1; + IF EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@id AND LocationTypeID IS NOT NULL) THROW 51000,'Type Undo failed to restore Unclassified.',1; + FETCH NEXT FROM choices INTO @key,@type; +END; +CLOSE choices;DEALLOCATE choices; +PRINT 'PASS generic and specialised assignments, exact Undo, unchanged containment/provenance'; +SELECT @type=LocationTypeID FROM dbo.LocationTypeTaxonomy WHERE TypeKey=N'house'; +SET @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@type) AS Value,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@id,@second) FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'type',@changes; +IF (SELECT COUNT(*) FROM dbo.Locations WHERE LocationID IN(@id,@second) AND LocationTypeID=@type)<>2 THROW 51000,'Bulk type assignment failed.',1; +SET @changes=(SELECT LocationID AS Id,N'' AS Value,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@id,@second) AND LocationTypeID IS NOT NULL FOR JSON PATH);EXEC dbo.Location_WorkspaceAssign @p,@u,N'type',@changes,1; +PRINT 'PASS bulk specialisation and individual prior-value Undo'; +SELECT @version=CONVERT(nvarchar(50),UpdatedDate,126) FROM dbo.Locations WHERE LocationID=@id; +SET @changes=(SELECT @id AS Id,N'@premises' AS Value,@version AS Version FOR JSON PATH); +BEGIN TRY + EXEC dbo.Location_WorkspaceAssign @p,@u,N'type',@changes; + THROW 51000,'Grouping assignment should have failed.',1; +END TRY +BEGIN CATCH + IF ERROR_NUMBER()<>51012 THROW; + IF XACT_STATE()<>0 ROLLBACK; +END CATCH; +IF @@TRANCOUNT<>0 ROLLBACK; +PRINT 'PASS server rejects taxonomy headings as type IDs; all fixture data rolled back'; diff --git a/PlotLine/Controllers/LocationWorkspaceController.cs b/PlotLine/Controllers/LocationWorkspaceController.cs index 200ca2a7..8b521dfe 100644 --- a/PlotLine/Controllers/LocationWorkspaceController.cs +++ b/PlotLine/Controllers/LocationWorkspaceController.cs @@ -41,8 +41,10 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection var maps = (await result.ReadAsync()).ToLookup(a => a.LocationID); var floors = (await result.ReadAsync()).ToLookup(a => a.LocationID); var usage = (await result.ReadAsync()).ToDictionary(a => a.LocationID, a => a.SceneCount); - var types = (await result.ReadAsync