Share Attributes palettes and add hierarchical location and type pickers

This commit is contained in:
Nick Beckley 2026-11-27 14:37:45 +00:00
parent d256457c6b
commit 0e5a380501
28 changed files with 678 additions and 55 deletions

View File

@ -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.

View File

@ -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.<user>.<project>.groups`. Locations retain
`pd.locations.workspace.v1.<user>.<project>` and the existing divider scope; nested expansion keys
are `type:<TypeKey>`. 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.

View File

@ -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();

View File

@ -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<count;i++)records[i].parent=i===count-100?1:i;records[count-2].name='Reading room';records[count-1].name='Reading room';}
records[count-1].parent=2147483647; // Keep the unavailable-parent fixture after deep-tree construction.
await page.route('**/LocationWorkspace/Directory?*',async r=>{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');

View File

@ -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;});

View File

@ -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;});

View File

@ -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<LocationTypeTaxonomyEntry>("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));

View File

@ -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;}

View File

@ -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';

View File

@ -41,8 +41,10 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection
var maps = (await result.ReadAsync<Link>()).ToLookup(a => a.LocationID);
var floors = (await result.ReadAsync<Link>()).ToLookup(a => a.LocationID);
var usage = (await result.ReadAsync<Usage>()).ToDictionary(a => a.LocationID, a => a.SceneCount);
var types = (await result.ReadAsync<Option>()).ToArray();
return Json(new { canEdit = ContextEditPolicy.CanEdit(project), types = types.Select(t => LocationWorkspaceIcons.Presentation(t.ID.ToString(), t.Name)),
await result.ReadAsync<Option>(); // Keep the established six-result directory contract for other readers.
result.Dispose();
var taxonomy = (await db.QueryAsync<LocationTypeTaxonomyEntry>("dbo.LocationTypeTaxonomy_Read", commandType: CommandType.StoredProcedure)).ToArray();
return Json(new { canEdit = ContextEditPolicy.CanEdit(project), types = taxonomy.Where(t => t.IsAssignable).Select(LocationWorkspaceIcons.Presentation), taxonomy = taxonomy.Select(LocationWorkspaceIcons.Presentation),
locations = records.Select(r => new { id = r.LocationID, name = r.LocationName, parent = r.ParentLocationID,
type = r.LocationTypeID?.ToString() ?? "", typeName = r.LocationTypeName, classification = r.Classification ?? "",
relationships = r.RelationshipCount, characters = r.CharacterCount, assets = r.AssetCount,
@ -50,6 +52,30 @@ public sealed class LocationWorkspaceController(ISqlConnectionFactory connection
version = r.UpdatedDate.ToString("O"), aliases = aliases[r.LocationID], maps = maps[r.LocationID], floors = floors[r.LocationID], scenes = usage.GetValueOrDefault(r.LocationID) }) });
}
[HttpGet]
public async Task<IActionResult> Taxonomy()
{
using var db = connections.CreateConnection();
var taxonomy = await db.QueryAsync<LocationTypeTaxonomyEntry>("dbo.LocationTypeTaxonomy_Read", commandType: CommandType.StoredProcedure);
return Json(taxonomy.Select(LocationWorkspaceIcons.Presentation));
}
[HttpGet]
public async Task<IActionResult> Picker(int projectId)
{
if (user.UserId is not int author) return Unauthorized();
if (await projects.GetForUserAsync(projectId, author) is null) return NotFound();
using var db = connections.CreateConnection();
using var result = await db.QueryMultipleAsync("dbo.Location_PickerRead", new { ProjectID = projectId, UserID = author }, commandType: CommandType.StoredProcedure);
var locations = (await result.ReadAsync<LocationWorkspaceRecord>()).ToArray();
var aliases = (await result.ReadAsync<LocationAlias>()).ToLookup(a => a.LocationID, a => a.Alias);
result.Dispose();
var taxonomy = await db.QueryAsync<LocationTypeTaxonomyEntry>("dbo.LocationTypeTaxonomy_Read", commandType: CommandType.StoredProcedure);
return Json(new { types = taxonomy.Where(t => t.IsAssignable).Select(LocationWorkspaceIcons.Presentation),
locations = locations.Select(r => new { id = r.LocationID, name = r.LocationName, parent = r.ParentLocationID,
type = r.LocationTypeID?.ToString() ?? "", aliases = aliases[r.LocationID] }) });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Assign([FromBody] Assignment input)
{

View File

@ -76,3 +76,25 @@ review carefully before confirming. No similar names are merged automatically.
- [Location details](/Help/Article/locations.details)
- [Scenes](/Help/Article/scenes.overview)
- [Story Assets](/Help/Article/storyAssets.overview)
## Choose a location in its hierarchy
Change Parent, Merge and the location forms now use a hierarchical picker. Expand branches or search
by location name, alias or any part of its full path. Roots and siblings are alphabetical; repeated
names show their paths. The selected path appears below the tree. Use the arrow keys to navigate,
Enter or Space to select, then the operation's Save or Choose button. Clear search returns to normal
browsing. Change Parent includes Root level; invalid source/descendant targets cannot be selected.
Merging still requires reviewing its consequences and explicit confirmation.
## Choose a location type
Location types are organised into expandable categories and specialisations. Expand the arrow to
browse; click the row to filter the workspace, or use Assign for selected locations. A category filter
includes its specialisations and counts each location once. Generic classifications such as Building,
Residential and Room are valid choices—you do not have to choose a leaf. Grouping headings filter
but have no Assign control. The Details panel and full forms offer the same searchable type tree.
Type categories describe what a place is, not where it is contained. A flat can be classified under
Residential while its actual parent is a building, street or another valid location. Existing types
are retained; no specialisations are inferred automatically. Attributes group expansion and panel
widths are remembered independently in Characters and Locations.

View File

@ -0,0 +1,14 @@
namespace PlotLine.Models;
// Presentation hierarchy; never a containment constraint. Assignable IDs remain LocationTypes IDs.
public sealed class LocationTypeTaxonomyEntry
{
public string TypeKey { get; set; } = "";
public string? ParentKey { get; set; }
public int? LocationTypeID { get; set; }
public string DisplayName { get; set; } = "";
public int SortOrder { get; set; }
public string IconKey { get; set; } = "locations";
public string SemanticTone { get; set; } = "secondary";
public bool IsAssignable { get; set; }
}

View File

@ -1,26 +1,18 @@
using PlotLine.Models;
namespace PlotLine.Services;
// Opt-in mapping; existing Location/Context consumers keep their current presentation.
// Canonical metadata supplies icon keys/tones. The shared library supplies SVG geometry.
public static class LocationWorkspaceIcons
{
public static (string Icon, string Tone) Type(string? name) => name?.ToLowerInvariant() switch
public static object Presentation(string value, string name, string icon = "locations", string tone = "secondary")
=> CharacterQuickAttributes.Presentation(new(value, name, icon, tone));
public static object Presentation(LocationTypeTaxonomyEntry entry)
{
"country" or "planet" => ("location-globe", "info"),
"region" or "district" => ("maps", "success"),
"town" or "city" or "village" => ("location-city", "primary"),
"street" => ("location-street", "warning"),
"building" => ("location-house", "primary"),
"floor" => ("location-level", "info"),
"room" => ("location-door", "data-5"),
"outdoor area" => ("location-tree", "success"),
"vehicle interior" => ("location-vehicle", "warning"),
"landmark" or "natural feature" => ("location-mountain", "success"),
"other" => ("locations", "secondary"),
_ => ("help", "secondary")
};
public static object Presentation(string value, string name)
{
var (icon, tone) = Type(name);
return CharacterQuickAttributes.Presentation(new(value, name, icon, tone));
var icon = ApplicationRibbon.Icon(entry.IconKey);
return new { key = entry.TypeKey, parentKey = entry.ParentKey,
value = entry.IsAssignable ? entry.LocationTypeID?.ToString() ?? "" : "@" + entry.TypeKey,
label = entry.DisplayName, assignable = entry.IsAssignable,
icon = entry.IconKey, tone = entry.SemanticTone, path = icon.IconPath, icon.Filled };
}
}

View File

@ -47,6 +47,14 @@ public static class RibbonPresentation
public static IReadOnlyList<RibbonIcon> AdditionalIcons { get; } = [
new("location-globe", "M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0 M2 12h20 M12 2c-6 6-6 14 0 20 6-6 6-14 0-20", "world"),
new("location-city", "M3 22V8h8v14 M11 22V2h10v20 M6 11h2 M6 15h2 M14 6h4 M14 10h4 M14 14h4 M14 18h4", "world"),
new("location-shop", "M3 10h18 M5 10v11h14V10 M2 10l3-7h14l3 7 M9 21v-7h6v7", "world"),
new("location-coffee", "M4 3h12v12a5 5 0 0 1-10 0V3 M16 5h3a3 3 0 0 1 0 6h-3 M2 22h19", "world"),
new("location-institution", "M2 8L12 2l10 6H2 M4 21h16 M6 10v8 M12 10v8 M18 10v8", "world"),
new("location-medical", "M3 22V7h18v15 M8 2v10 M3 7h10 M9 22v-7h6v7", "world"),
new("location-castle", "M3 22V3h4v4h3V3h4v4h3V3h4v19H3 M9 22v-7h6v7", "world"),
new("location-water", "M2 17q3-3 6 0t6 0t8 0 M2 22q3-3 6 0t6 0t8 0 M5 12l7-10 7 10H5", "world"),
new("location-rail", "M5 18V5q0-3 7-3t7 3v13H5 M5 10h14 M8 14h1 M15 14h1 M8 18l-3 4 M16 18l3 4", "world"),
new("location-plane", "M22 2L9 9 2 7l-1 3 6 4 4 9 3-1-1-7 9-13Z", "world"),
new("location-house", "M2 11L12 2l10 9 M5 9v13h14V9 M10 22v-8h4v8", "world"),
new("location-door", "M4 22h16 M6 22V2h12v20 M14 12h1", "world"),
new("location-tree", "M12 2l-6 8h3l-6 8h7v4h4v-4h7l-6-8h3z", "world"),

View File

@ -0,0 +1,162 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Metadata is separate from physical containment. LocationTypes contains assignable values only.
IF OBJECT_ID(N'dbo.LocationTypeTaxonomy',N'U') IS NULL
BEGIN
CREATE TABLE dbo.LocationTypeTaxonomy(
TypeKey nvarchar(80) NOT NULL CONSTRAINT PK_LocationTypeTaxonomy PRIMARY KEY,
ParentKey nvarchar(80) NULL,LocationTypeID int NULL,DisplayName nvarchar(100) NOT NULL,
SortOrder int NOT NULL,IconKey nvarchar(80) NOT NULL,SemanticTone nvarchar(30) NOT NULL,
IsAssignable bit NOT NULL,
CONSTRAINT FK_LocationTypeTaxonomy_Parent FOREIGN KEY(ParentKey) REFERENCES dbo.LocationTypeTaxonomy(TypeKey),
CONSTRAINT FK_LocationTypeTaxonomy_Type FOREIGN KEY(LocationTypeID) REFERENCES dbo.LocationTypes(LocationTypeID),
CONSTRAINT CK_LocationTypeTaxonomy_Self CHECK(ParentKey<>TypeKey),
CONSTRAINT CK_LocationTypeTaxonomy_Assignable CHECK((LocationTypeID IS NOT NULL AND IsAssignable=1) OR (LocationTypeID IS NULL AND (IsAssignable=0 OR TypeKey=N'unclassified')))
);
CREATE UNIQUE INDEX UX_LocationTypeTaxonomy_Type ON dbo.LocationTypeTaxonomy(LocationTypeID) WHERE LocationTypeID IS NOT NULL;
END;
GO
SET XACT_ABORT ON;
BEGIN TRANSACTION;
DECLARE @seed TABLE(TypeKey nvarchar(80),ParentKey nvarchar(80),DisplayName nvarchar(100),TypeName nvarchar(100),IconKey nvarchar(80),Tone nvarchar(30),IsAssignable bit,SortOrder int);
INSERT @seed VALUES
(N'geography',NULL,N'Geography',NULL,N'location-globe',N'info',0,10),
(N'planet',N'geography',N'Planet',N'Planet',N'location-globe',N'info',1,20),
(N'continent',N'geography',N'Continent',N'Continent',N'location-globe',N'info',1,30),
(N'country',N'geography',N'Country',N'Country',N'location-globe',N'info',1,40),
(N'region',N'geography',N'Region',N'Region',N'maps',N'success',1,50),
(N'county',N'geography',N'County',N'County',N'maps',N'success',1,60),
(N'settlements',NULL,N'Settlements and administrative areas',NULL,N'location-city',N'primary',0,70),
(N'city',N'settlements',N'City',N'City',N'location-city',N'primary',1,80),
(N'town',N'settlements',N'Town',N'Town',N'location-city',N'primary',1,90),
(N'village',N'settlements',N'Village',N'Village',N'location-city',N'primary',1,100),
(N'hamlet',N'settlements',N'Hamlet',N'Hamlet',N'location-city',N'primary',1,110),
(N'district',N'settlements',N'District',N'District',N'location-city',N'primary',1,120),
(N'suburb',N'settlements',N'Suburb',N'Suburb',N'location-city',N'primary',1,130),
(N'street',N'settlements',N'Street',N'Street',N'location-street',N'warning',1,140),
(N'premises',NULL,N'Buildings and premises',NULL,N'location-house',N'primary',0,150),
(N'building',N'premises',N'Building',N'Building',N'location-house',N'primary',1,160),
(N'residential',N'premises',N'Residential',N'Residential',N'location-house',N'primary',1,170),
(N'house',N'residential',N'House',N'House',N'location-house',N'primary',1,180),
(N'flat',N'residential',N'Flat / Apartment',N'Flat / Apartment',N'location-house',N'primary',1,190),
(N'cottage',N'residential',N'Cottage',N'Cottage',N'location-house',N'primary',1,200),
(N'mansion',N'residential',N'Mansion',N'Mansion',N'location-house',N'primary',1,210),
(N'residential-block',N'residential',N'Residential block',N'Residential block',N'location-city',N'primary',1,220),
(N'commercial',N'premises',N'Commercial',N'Commercial',N'location-shop',N'warning',1,230),
(N'shop',N'commercial',N'Shop',N'Shop',N'location-shop',N'warning',1,240),
(N'pub',N'commercial',N'Pub',N'Pub',N'location-coffee',N'warning',1,250),
(N'restaurant',N'commercial',N'Restaurant',N'Restaurant',N'location-coffee',N'warning',1,260),
(N'cafe',N'commercial',N'Café',N'Café',N'location-coffee',N'warning',1,270),
(N'hotel',N'commercial',N'Hotel',N'Hotel',N'location-shop',N'warning',1,280),
(N'nightclub',N'commercial',N'Nightclub',N'Nightclub',N'location-shop',N'warning',1,290),
(N'office-premises',N'commercial',N'Office',N'Office',N'location-shop',N'warning',1,300),
(N'factory',N'commercial',N'Factory',N'Factory',N'location-shop',N'warning',1,310),
(N'warehouse',N'commercial',N'Warehouse',N'Warehouse',N'location-shop',N'warning',1,320),
(N'institutional',N'premises',N'Public and institutional',N'Public and institutional',N'location-institution',N'info',1,330),
(N'hospital',N'institutional',N'Hospital',N'Hospital',N'location-medical',N'info',1,340),
(N'medical-practice',N'institutional',N'Medical practice',N'Medical practice',N'location-medical',N'info',1,350),
(N'police',N'institutional',N'Police station',N'Police station',N'location-institution',N'info',1,360),
(N'fire',N'institutional',N'Fire station',N'Fire station',N'location-institution',N'info',1,370),
(N'school',N'institutional',N'School',N'School',N'location-institution',N'info',1,380),
(N'college',N'institutional',N'College',N'College',N'location-institution',N'info',1,390),
(N'university',N'institutional',N'University',N'University',N'location-institution',N'info',1,400),
(N'church',N'institutional',N'Church',N'Church',N'location-institution',N'info',1,410),
(N'court',N'institutional',N'Court',N'Court',N'location-institution',N'info',1,420),
(N'prison',N'institutional',N'Prison',N'Prison',N'location-institution',N'info',1,430),
(N'library',N'institutional',N'Library',N'Library',N'location-institution',N'info',1,440),
(N'museum',N'institutional',N'Museum',N'Museum',N'location-institution',N'info',1,450),
(N'historic',N'premises',N'Historic and defensive',N'Historic and defensive',N'location-castle',N'data-5',1,460),
(N'castle',N'historic',N'Castle',N'Castle',N'location-castle',N'data-5',1,470),
(N'palace',N'historic',N'Palace',N'Palace',N'location-castle',N'data-5',1,480),
(N'fort',N'historic',N'Fort',N'Fort',N'location-castle',N'data-5',1,490),
(N'ruin',N'historic',N'Ruin',N'Ruin',N'location-castle',N'data-5',1,500),
(N'interiors',NULL,N'Interior spaces',NULL,N'location-door',N'data-5',0,510),
(N'floor',N'interiors',N'Floor',N'Floor',N'location-level',N'info',1,520),
(N'room',N'interiors',N'Room',N'Room',N'location-door',N'data-5',1,530),
(N'bedroom',N'room',N'Bedroom',N'Bedroom',N'location-door',N'data-5',1,540),
(N'bathroom',N'room',N'Bathroom',N'Bathroom',N'location-door',N'data-5',1,550),
(N'kitchen',N'room',N'Kitchen',N'Kitchen',N'location-door',N'data-5',1,560),
(N'living-room',N'room',N'Living room',N'Living room',N'location-door',N'data-5',1,570),
(N'dining-room',N'room',N'Dining room',N'Dining room',N'location-door',N'data-5',1,580),
(N'study',N'room',N'Study',N'Study',N'location-door',N'data-5',1,590),
(N'office-room',N'room',N'Office',N'Office (room)',N'location-door',N'data-5',1,600),
(N'cellar',N'room',N'Cellar',N'Cellar',N'location-door',N'data-5',1,610),
(N'attic',N'room',N'Attic',N'Attic',N'location-door',N'data-5',1,620),
(N'garage',N'room',N'Garage',N'Garage',N'location-door',N'data-5',1,630),
(N'corridor',N'room',N'Corridor',N'Corridor',N'location-door',N'data-5',1,640),
(N'stairwell',N'room',N'Stairwell',N'Stairwell',N'location-door',N'data-5',1,650),
(N'outdoors',NULL,N'Outdoor and natural locations',NULL,N'location-tree',N'success',0,660),
(N'outdoor',N'outdoors',N'Outdoor area',N'Outdoor Area',N'location-tree',N'success',1,670),
(N'garden',N'outdoor',N'Garden',N'Garden',N'location-tree',N'success',1,680),
(N'park',N'outdoor',N'Park',N'Park',N'location-tree',N'success',1,690),
(N'field',N'outdoor',N'Field',N'Field',N'location-tree',N'success',1,700),
(N'playground',N'outdoor',N'Playground',N'Playground',N'location-tree',N'success',1,710),
(N'courtyard',N'outdoor',N'Courtyard',N'Courtyard',N'location-tree',N'success',1,720),
(N'natural',N'outdoors',N'Natural feature',N'Natural Feature',N'location-mountain',N'success',1,730),
(N'mountain',N'natural',N'Mountain',N'Mountain',N'location-mountain',N'success',1,740),
(N'hill',N'natural',N'Hill',N'Hill',N'location-mountain',N'success',1,750),
(N'valley',N'natural',N'Valley',N'Valley',N'location-mountain',N'success',1,760),
(N'woodland',N'natural',N'Woodland',N'Woodland',N'location-tree',N'success',1,770),
(N'forest',N'natural',N'Forest',N'Forest',N'location-tree',N'success',1,780),
(N'river',N'natural',N'River',N'River',N'location-water',N'success',1,790),
(N'lake',N'natural',N'Lake',N'Lake',N'location-water',N'success',1,800),
(N'beach',N'natural',N'Beach',N'Beach',N'location-water',N'success',1,810),
(N'cave',N'natural',N'Cave',N'Cave',N'location-mountain',N'success',1,820),
(N'island',N'natural',N'Island',N'Island',N'location-water',N'success',1,830),
(N'landmark',N'outdoors',N'Landmark',N'Landmark',N'location-mountain',N'success',1,840),
(N'monument',N'landmark',N'Monument',N'Monument',N'location-institution',N'success',1,850),
(N'bridge',N'landmark',N'Bridge',N'Bridge',N'location-institution',N'success',1,860),
(N'transport',NULL,N'Transport and infrastructure',NULL,N'location-vehicle',N'warning',0,870),
(N'road',N'transport',N'Road',N'Road',N'location-street',N'warning',1,880),
(N'motorway',N'road',N'Motorway',N'Motorway',N'location-street',N'warning',1,890),
(N'layby',N'road',N'Layby',N'Layby',N'location-street',N'warning',1,900),
(N'railway',N'transport',N'Railway station',N'Railway station',N'location-rail',N'warning',1,910),
(N'airport',N'transport',N'Airport',N'Airport',N'location-plane',N'warning',1,920),
(N'harbour',N'transport',N'Harbour',N'Harbour',N'location-water',N'warning',1,930),
(N'bus-station',N'transport',N'Bus station',N'Bus station',N'location-vehicle',N'warning',1,940),
(N'vehicle',N'transport',N'Vehicle interior',N'Vehicle Interior',N'location-vehicle',N'warning',1,950),
(N'car',N'vehicle',N'Car',N'Car',N'location-vehicle',N'warning',1,960),
(N'train',N'vehicle',N'Train',N'Train',N'location-rail',N'warning',1,970),
(N'bus',N'vehicle',N'Bus',N'Bus',N'location-vehicle',N'warning',1,980),
(N'aircraft',N'vehicle',N'Aircraft',N'Aircraft',N'location-plane',N'warning',1,990),
(N'boat',N'vehicle',N'Boat',N'Boat',N'location-water',N'warning',1,1000),
(N'ship',N'vehicle',N'Ship',N'Ship',N'location-water',N'warning',1,1010),
(N'spacecraft',N'vehicle',N'Spacecraft',N'Spacecraft',N'location-plane',N'warning',1,1020),
(N'other-group',NULL,N'Other',NULL,N'locations',N'secondary',0,1030),
(N'other',N'other-group',N'Other',N'Other',N'locations',N'secondary',1,1040),
(N'unclassified',N'other-group',N'Unclassified',NULL,N'help',N'secondary',1,1050);
INSERT dbo.LocationTypes(TypeName,SortOrder)
SELECT s.TypeName,1000+s.SortOrder FROM @seed s WHERE s.TypeName IS NOT NULL
AND NOT EXISTS(SELECT 1 FROM dbo.LocationTypes t WHERE t.TypeName=s.TypeName);
-- Seed once; later forward migrations may extend/reorganise metadata without replacing identifiers.
INSERT dbo.LocationTypeTaxonomy(TypeKey,ParentKey,LocationTypeID,DisplayName,SortOrder,IconKey,SemanticTone,IsAssignable)
SELECT s.TypeKey,NULL,t.LocationTypeID,s.DisplayName,s.SortOrder,s.IconKey,s.Tone,s.IsAssignable
FROM @seed s LEFT JOIN dbo.LocationTypes t ON t.TypeName=s.TypeName
WHERE NOT EXISTS(SELECT 1 FROM dbo.LocationTypeTaxonomy x WHERE x.TypeKey=s.TypeKey);
UPDATE x SET ParentKey=s.ParentKey FROM dbo.LocationTypeTaxonomy x JOIN @seed s ON s.TypeKey=x.TypeKey WHERE x.ParentKey IS NULL AND s.ParentKey IS NOT NULL;
COMMIT;
GO
CREATE OR ALTER PROCEDURE dbo.LocationTypeTaxonomy_Read
AS
BEGIN
SET NOCOUNT ON;
SELECT x.TypeKey,x.ParentKey,x.LocationTypeID,x.DisplayName,x.SortOrder,x.IconKey,x.SemanticTone,x.IsAssignable
FROM dbo.LocationTypeTaxonomy x LEFT JOIN dbo.LocationTypes t ON t.LocationTypeID=x.LocationTypeID
WHERE x.LocationTypeID IS NULL OR t.IsActive=1
UNION ALL
SELECT CONCAT(N'legacy-',t.LocationTypeID),N'other-group',t.LocationTypeID,t.TypeName,100000+t.SortOrder,N'locations',N'secondary',CONVERT(bit,1)
FROM dbo.LocationTypes t WHERE t.IsActive=1 AND NOT EXISTS(SELECT 1 FROM dbo.LocationTypeTaxonomy x WHERE x.LocationTypeID=t.LocationTypeID)
ORDER BY SortOrder,DisplayName;
END;
GO
CREATE OR ALTER PROCEDURE dbo.Location_PickerRead @ProjectID int,@UserID int
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND p.IsArchived=0) THROW 51010,'Locations unavailable.',1;
SELECT LocationID,ParentLocationID,LocationName,LocationTypeID FROM dbo.Locations WHERE ProjectID=@ProjectID AND IsArchived=0;
SELECT a.LocationID,a.Alias FROM dbo.LocationAliases a JOIN dbo.Locations l ON l.LocationID=a.LocationID WHERE l.ProjectID=@ProjectID AND l.IsArchived=0;
END;
GO

View File

@ -156,7 +156,7 @@
<div class="row g-2">
<div class="col-md-5">
<label class="form-label" for="ToLocationID">To location</label>
<select class="form-select form-select-sm" id="ToLocationID" name="ToLocationID" asp-items="Model.LocationOptions"></select>
<select data-location-picker data-project-id="@Model.Project.ProjectID" data-exclude-id="@Model.Location.LocationID" data-picker-label="Choose related location" class="form-select form-select-sm" id="ToLocationID" name="ToLocationID" asp-items="Model.LocationOptions"></select>
</div>
<div class="col-md-4">
<label class="form-label" for="LocationRelationshipTypeID">Relationship</label>

View File

@ -56,13 +56,13 @@
<div class="pd-record-group-label" role="heading" aria-level="2">Hierarchy</div>
<div class="col-md-4 pd-record-span-6">
<label asp-for="LocationTypeID" class="form-label">Location type <help-icon key="locations.fields.locationType" mode="inline" /></label>
<select asp-for="LocationTypeID" asp-items="Model.LocationTypeOptions" class="form-select">
<select data-location-type-picker asp-for="LocationTypeID" asp-items="Model.LocationTypeOptions" class="form-select">
<option value="">Not set</option>
</select>
</div>
<div class="col-12 pd-record-span-6">
<label asp-for="ParentLocationID" class="form-label">Parent location <help-icon key="locations.fields.parentLocation" mode="inline" /></label>
<select asp-for="ParentLocationID" asp-items="Model.ParentLocationOptions" class="form-select">
<select data-location-picker data-project-id="@Model.ProjectID" data-exclude-branch="@Model.LocationID" data-allow-root="true" data-picker-label="Choose parent location" asp-for="ParentLocationID" asp-items="Model.ParentLocationOptions" class="form-select">
<option value="">Top level</option>
</select>
</div>

View File

@ -35,7 +35,7 @@
<div class="row g-3">
<div class="col-md-8">
<label asp-for="Form.TargetID" class="form-label">Canonical location</label>
<select asp-for="Form.TargetID" asp-items="Model.TargetOptions" class="form-select">
<select data-location-picker data-project-id="@Model.Project.ProjectID" data-exclude-branch="@Model.Form.SourceID" data-picker-label="Choose surviving location" asp-for="Form.TargetID" asp-items="Model.TargetOptions" class="form-select">
<option value="">Choose location</option>
</select>
</div>

View File

@ -140,6 +140,11 @@
<link rel="stylesheet" href="~/css/application-shell.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/record-workspace.css" asp-append-version="true" />
<link rel="preload" as="script" href="~/js/application-page-context.js" asp-append-version="true" />
<link rel="stylesheet" href="~/css/attributes-panel.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/location-picker.css" asp-append-version="true" />
<script src="~/js/attributes-panel.js" asp-append-version="true" defer></script>
<script src="~/js/location-picker.js" asp-append-version="true" defer></script>
<script src="~/js/location-types.js" asp-append-version="true" defer></script>
<link rel="stylesheet" href="~/css/desktop-promotion.css" asp-append-version="true" />
<script src="~/js/desktop-promotion.js" asp-append-version="true" defer></script>
<script src="~/js/application-pwa.js" asp-append-version="true" defer></script>

View File

@ -0,0 +1,9 @@
/* The Locations tool palette is the shared Attributes visual standard. Layout/resizers stay with consumers. */
.pd-attributes-panel{min-width:0}.pd-attributes-panel details{margin-top:1rem}.pd-attributes-panel summary{font-weight:600;margin-bottom:.4rem;cursor:pointer}.pd-attributes-panel details>p{font-size:.75rem;color:var(--pd-muted);margin-bottom:.3rem}
.pd-attribute-row{display:grid;grid-template-columns:minmax(0,1fr) 1.1rem 2.9rem;align-items:center;gap:.15rem;margin-bottom:.15rem;padding-left:min(calc(var(--attribute-depth,0)*.65rem),4rem);border-radius:.3rem;min-width:0}
.pd-attribute-filter{display:grid;grid-template-columns:1.15rem minmax(0,1fr) max-content;align-items:center;gap:.4rem;text-align:left;width:100%;min-width:0;font-size:.8rem;padding:.3rem;border:1px solid transparent;border-radius:.3rem;background:transparent;color:inherit}
.pd-attribute-label{overflow-wrap:anywhere;line-height:1.3}.pd-attribute-count{text-align:right;opacity:.75;font-variant-numeric:tabular-nums;white-space:nowrap}.pd-attributes-panel .pd-attribute-icon{width:1.05rem;height:1.05rem;flex:none;vertical-align:middle}.pd-attribute-assign{font-size:.68rem;border:1px solid var(--pd-border,var(--bs-border-color));border-radius:.3rem;background:transparent;color:inherit;padding:.2rem .3rem;white-space:nowrap}.pd-attribute-expand{grid-column:2;background:none;border:0;color:inherit;padding:.1rem;line-height:1.3}.pd-attribute-expand[hidden]{display:block!important;visibility:hidden}.pd-attribute-row:hover{background:var(--pd-hover,var(--bs-secondary-bg))}.pd-attribute-row.is-filter-active{background:var(--pd-selected,var(--bs-secondary-bg));box-shadow:inset 2px 0 var(--pd-accent)}.pd-attribute-row[draggable=true]{cursor:grab}.pd-attribute-row button{cursor:pointer}.pd-attribute-row button:disabled{opacity:.45;cursor:default}.pd-attribute-row.is-drop-target{outline:2px solid var(--pd-success,var(--bs-success));outline-offset:-2px}.pd-attribute-row.is-invalid-target{outline:2px dashed var(--pd-danger,var(--bs-danger))}.pd-attributes-panel :focus-visible{outline:2px solid var(--pd-accent);outline-offset:1px}.pd-attribute-children[hidden]{display:none!important}
.pd-attribute-icon.text-info{color:var(--pd-info)!important}.pd-attribute-icon.text-warning{color:var(--pd-warning)!important}.pd-attribute-icon.text-secondary{color:var(--pd-muted)!important}.pd-attribute-icon.text-success{color:var(--pd-success,var(--bs-success))!important}.pd-attribute-icon.text-primary{color:var(--pd-accent)!important}.pd-attribute-icon.text-data-5{color:var(--pd-data-5)!important}
.pd-attributes-panel{container-type:inline-size;container-name:attribute-palette}.pd-attribute-label{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}
@container attribute-palette (max-width:210px){.pd-attribute-row{padding-left:min(calc(var(--attribute-depth,0)*.25rem),1rem);grid-template-columns:minmax(0,1fr) .85rem 2.4rem;gap:.1rem}.pd-attribute-filter{grid-template-columns:1.05rem minmax(0,1fr) max-content;gap:.2rem;padding-inline:.15rem}.pd-attribute-assign{padding-inline:.1rem}}
@container attribute-palette (max-width:140px){.pd-attribute-row{padding-left:min(calc(var(--attribute-depth,0)*.1rem),.5rem);grid-template-columns:minmax(0,1fr) .8rem 2.1rem}.pd-attribute-filter{grid-template-columns:1rem minmax(0,1fr) max-content;gap:.1rem;padding-inline:0}.pd-attribute-assign{font-size:.6rem;padding-inline:.1rem}.pd-attributes-panel .pd-attribute-icon{width:1rem;height:1rem}}

View File

@ -1,14 +1,14 @@
.character-attribute-toolbar{margin-bottom:1rem;flex-wrap:wrap}
.character-attribute-layout{display:grid;grid-template-columns:minmax(12rem,16rem) minmax(0,1fr);gap:1rem;align-items:start}
.character-attribute-sidebar{position:sticky;top:calc(var(--pd-sticky-height, 0px) + 1rem);max-height:calc(100dvh - calc(var(--pd-sticky-height, 0px) + 1rem) - 1rem);overflow-y:auto;border:1px solid var(--bs-border-color);border-radius:.6rem;padding:.75rem;background:var(--bs-body-bg)}
.character-attribute-sidebar h2{font-size:1.1rem}.character-attribute-sidebar summary{font-weight:600;cursor:pointer;padding:.6rem 0}
.character-attribute-value{display:flex;align-items:center;gap:.3rem;margin:.2rem 0}.character-attribute-value>button:first-child{flex:1;text-align:left}.character-attribute-value button{font-size:.85rem}
.character-attribute-sidebar h2{font-size:1.1rem}
.character-attribute-icon{width:1.05rem;height:1.05rem;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;vertical-align:middle;flex:none}
.character-attribute-indicators{display:flex;gap:.4rem;margin:.3rem 0}.character-attribute-indicators span{display:inline-flex}
.character-attribute-controls{display:flex;gap:.5rem;align-items:center;margin-bottom:.5rem;font-size:.8rem}.character-attribute-controls [data-character-menu]{margin-left:auto}
[data-character-attributes] .is-selected{outline:2px solid var(--bs-primary);outline-offset:2px}
[data-character-attributes] .is-drop-target{outline:3px solid var(--bs-success);outline-offset:2px}
[data-character-attributes].dragging-attribute .character-card,[data-character-attributes].dragging-characters .character-attribute-value{box-shadow:0 0 0 1px var(--bs-primary)}
[data-character-attributes] .character-card.is-drop-target{outline:3px solid var(--bs-success);outline-offset:2px}
[data-character-attributes].dragging-attribute .character-card,[data-character-attributes].dragging-characters .pd-attribute-row{box-shadow:0 0 0 1px var(--bs-primary)}
[data-character-attributes].attributes-collapsed .character-attribute-layout{grid-template-columns:minmax(0,1fr)}
[data-character-attributes] [hidden]{display:none!important}
.character-attribute-sidebar :focus-visible{outline:2px solid var(--bs-primary);outline-offset:1px}

View File

@ -0,0 +1 @@
.pd-location-picker-dialog,.locations-dialog:has(.pd-location-picker){width:min(900px,calc(100vw - 24px));max-height:90dvh;background:var(--pd-elevated,var(--bs-body-bg));color:var(--pd-text,var(--bs-body-color));border:1px solid var(--pd-border,var(--bs-border-color));border-radius:.8rem;padding:1.25rem;overflow:auto}.pd-location-picker-dialog::backdrop{background:#0007}.pd-location-picker-dialog h2{font-size:1.2rem}.pd-location-picker-tools{display:flex;flex-wrap:wrap;gap:.4rem;margin:.6rem 0}.pd-location-picker-tools input{flex:1;min-width:200px}.pd-location-picker-tools button{font-size:.8rem;background:transparent;color:inherit;border:1px solid var(--pd-border,var(--bs-border-color));border-radius:.3rem;padding:.3rem .5rem}.pd-location-picker-tree{max-height:48dvh;min-height:180px;overflow:auto;border-block:1px solid var(--pd-border,var(--bs-border-color));padding:.35rem 0;overscroll-behavior:contain}.pd-location-picker-row{display:flex;align-items:center;gap:.4rem;border:1px solid transparent;border-radius:.3rem;min-height:34px;padding:.25rem .4rem;padding-left:calc(.4rem + min(var(--picker-depth,0),16)*1.05rem);cursor:pointer}.pd-location-picker-row>button{width:1.1rem;flex:none;border:0;background:transparent;color:inherit;padding:0}.pd-location-picker-row>span{min-width:0;flex:1}.pd-location-picker-name{text-align:left;overflow-wrap:anywhere;width:100%;border:0;background:none;color:inherit;padding:0}.pd-location-picker-row small{display:block;font-size:.72rem;color:var(--pd-muted);overflow-wrap:anywhere}.pd-location-picker-row[aria-selected=true]{background:var(--pd-selected,var(--bs-secondary-bg));border-color:var(--pd-accent)}.pd-location-picker-row[aria-disabled=true]{opacity:.5;cursor:default}.pd-location-picker-row:hover{background:var(--pd-hover,var(--bs-secondary-bg))}.pd-location-picker-row:focus-visible{outline:2px solid var(--pd-accent);outline-offset:-2px}.pd-location-picker-path{font-size:.8rem;overflow-wrap:anywhere;margin:.7rem 0;white-space:pre-wrap}.pd-location-picker-trigger{display:block;width:100%;text-align:left;white-space:normal;overflow-wrap:anywhere}.pd-location-picker-icon{height:1.1rem;width:1.1rem;flex:none;stroke:currentColor;stroke-width:1.7;fill:none;stroke-linecap:round;stroke-linejoin:round}.pd-location-picker-icon.text-info{color:var(--pd-info)!important}.pd-location-picker-icon.text-warning{color:var(--pd-warning)!important}.pd-location-picker-icon.text-primary{color:var(--pd-accent)!important}.pd-location-picker-icon.text-success{color:var(--pd-success,var(--bs-success))!important}

View File

@ -1,14 +1,16 @@
.location-page{min-width:0;--location-border:var(--plotline-line,var(--bs-border-color));--location-panel:var(--plotline-panel,var(--bs-body-bg));--location-accent:var(--plotline-accent,var(--bs-primary));}
.locations-toolbar,.locations-search,.locations-selection{display:flex;align-items:center;flex-wrap:wrap;gap:.45rem;padding:.5rem 0}.locations-toolbar{border-bottom:1px solid var(--location-border)}.locations-toolbar [aria-pressed=true]{background:var(--location-accent);color:var(--bs-body-bg)}.locations-search [data-search]{flex:1;min-width:180px}.locations-search select{width:auto}.locations-search [role=status]{font-size:.85rem;white-space:nowrap}
.locations-layout{display:grid;grid-template-columns:var(--workspace-left,240px) minmax(0,1fr) var(--workspace-right,320px);height:calc(100dvh - var(--locations-top,290px) - 16px);min-height:360px;gap:0;border:1px solid var(--location-border);border-radius:.7rem;overflow:hidden;background:var(--location-panel)}
.locations-attributes,.locations-details,.locations-centre{min-width:0;overflow:auto;overscroll-behavior:contain;padding:1rem}.locations-attributes{border-right:1px solid var(--location-border)}.locations-details{border-left:1px solid var(--location-border)}.locations-layout h2{font-size:1.05rem}.locations-attributes p{line-height:1.45}.locations-attributes details{margin-top:1rem}.locations-attributes summary{font-weight:600;margin-bottom:.4rem;cursor:pointer}.location-attribute-row{display:flex;gap:.25rem;margin-bottom:.2rem}.location-attribute-row>button:first-child{flex:1;text-align:left;display:flex;align-items:center;gap:.4rem;border-color:transparent}.location-attribute-row [data-count]{margin-left:auto;opacity:.75}.location-attribute-row [aria-pressed=true]{background:var(--bs-secondary-bg);border-color:var(--location-accent)}.location-attribute-row>button:last-child{padding-inline:.35rem;font-size:.72rem}.location-icon{height:1.15rem;width:1.15rem;flex-shrink:0;stroke:currentColor;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;vertical-align:middle}.location-tone-success{color:var(--bs-success)}.location-tone-info{color:var(--bs-info)}.location-tone-primary{color:var(--location-accent)}.location-tone-warning{color:var(--bs-warning)}.location-tone-data-5{color:var(--pd-data-5,var(--location-accent))}
.locations-attributes,.locations-details,.locations-centre{min-width:0;overflow:auto;overscroll-behavior:contain;padding:1rem}.locations-attributes{border-right:1px solid var(--location-border)}.locations-details{border-left:1px solid var(--location-border)}.locations-layout h2{font-size:1.05rem}.locations-attributes p{line-height:1.45}.location-icon{height:1.15rem;width:1.15rem;flex-shrink:0;stroke:currentColor;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;vertical-align:middle}.location-tone-success{color:var(--pd-success,var(--bs-success))}.location-tone-info{color:var(--pd-info,var(--bs-info))}.location-tone-primary{color:var(--location-accent)}.location-tone-warning{color:var(--pd-warning,var(--bs-warning))}.location-tone-data-5{color:var(--pd-data-5,var(--location-accent))}
.locations-selection{padding:0 0 .7rem;font-size:.8rem}.locations-root{border:1px dashed var(--location-border);padding:.55rem .7rem;border-radius:.4rem;font-size:.85rem;margin-bottom:.6rem}.locations-root:focus-visible{outline:2px solid var(--location-accent)}
.location-record{position:relative;border:1px solid transparent;border-radius:.4rem;margin-bottom:.2rem;scroll-margin-block:1rem}.location-record .location-row-main{display:flex;align-items:center;gap:.4rem;min-height:42px;padding:.35rem .4rem;padding-left:calc(.4rem + min(var(--depth,0),20)*1.1rem)}.location-record .location-row-main:before{content:"";position:absolute;left:calc(.3rem + min(var(--depth,0),20)*1.1rem);height:100%;border-left:1px solid var(--location-border);opacity:.5;pointer-events:none}.location-record button{position:relative}.location-record .location-label{font-weight:600;text-align:left;background:none;border:0;color:inherit;overflow-wrap:anywhere;padding:.1rem;min-width:0;flex:1}.location-record [data-expand-id]{width:1.5rem;padding:0;background:none;border:0;color:inherit;flex-shrink:0}.location-record .location-row-menu{margin-left:auto}.location-record .location-indicators{display:flex;gap:.35rem;align-items:center;font-size:.75rem}.location-record .location-child-count{font-size:.7rem;opacity:.7}.location-record.is-active{background:var(--bs-secondary-bg);border-color:var(--location-accent)}.location-record.is-selected{box-shadow:inset 3px 0 var(--location-accent)}.location-record.is-ancestor .location-label{color:var(--location-accent)}.location-record.is-context{opacity:.72}.location-record:focus-visible{outline:2px solid var(--location-accent)}.location-record [data-drag-location]{cursor:grab;padding:.1rem .25rem;background:none;border:0;color:inherit}.location-record.is-drop-target,.location-attribute-row.is-drop-target,.locations-root.is-drop-target{outline:2px solid var(--bs-success);outline-offset:-2px}.location-record.is-invalid-target{outline:2px dashed var(--bs-danger)}
.location-record{position:relative;border:1px solid transparent;border-radius:.4rem;margin-bottom:.2rem;scroll-margin-block:1rem}.location-record .location-row-main{display:flex;align-items:center;gap:.4rem;min-height:42px;padding:.35rem .4rem;padding-left:calc(.4rem + min(var(--depth,0),20)*1.1rem)}.location-record .location-row-main:before{content:"";position:absolute;left:calc(.3rem + min(var(--depth,0),20)*1.1rem);height:100%;border-left:1px solid var(--location-border);opacity:.5;pointer-events:none}.location-record button{position:relative}.location-record .location-label{font-weight:600;text-align:left;background:none;border:0;color:inherit;overflow-wrap:anywhere;padding:.1rem;min-width:0;flex:1}.location-record [data-expand-id]{width:1.5rem;padding:0;background:none;border:0;color:inherit;flex-shrink:0}.location-record .location-row-menu{margin-left:auto}.location-record .location-indicators{display:flex;gap:.35rem;align-items:center;font-size:.75rem}.location-record .location-child-count{font-size:.7rem;opacity:.7}.location-record.is-active{background:var(--bs-secondary-bg);border-color:var(--location-accent)}.location-record.is-selected{box-shadow:inset 3px 0 var(--location-accent)}.location-record.is-ancestor .location-label{color:var(--location-accent)}.location-record.is-context{opacity:.72}.location-record:focus-visible{outline:2px solid var(--location-accent)}.location-record [data-drag-location]{cursor:grab;padding:.1rem .25rem;background:none;border:0;color:inherit}.location-record.is-drop-target,.locations-root.is-drop-target{outline:2px solid var(--bs-success);outline-offset:-2px}.location-record.is-invalid-target{outline:2px dashed var(--bs-danger)}
.locations-cards{column-width:290px;column-gap:.85rem}.locations-cards .location-record{display:inline-block;vertical-align:top;break-inside:avoid;width:100%;border-color:var(--location-border);padding:.65rem;margin:0 0 .85rem}.locations-cards .location-row-main{padding:0!important;flex-wrap:wrap}.locations-cards .location-row-main:before{display:none}.locations-cards .location-indicators{width:100%;padding:.5rem 0}.locations-cards .location-label{font-size:1.05rem}.location-card-description,.locations-description{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6;font-size:.9rem}.location-card-path,.location-details-path{font-size:.78rem;overflow-wrap:anywhere;opacity:.75;margin:.55rem 0}.location-type-caption{font-size:.78rem;color:var(--bs-secondary-color)}
.location-detail-heading{display:flex;gap:.6rem;align-items:flex-start}.location-detail-heading>.location-icon{width:1.7rem;height:1.7rem}.location-detail-heading h2{font-size:1.2rem;overflow-wrap:anywhere}.location-detail-actions{display:flex;flex-wrap:wrap;gap:.4rem;margin:.7rem 0}.location-detail-attributes{display:grid;gap:.65rem;margin:1rem 0}.location-detail-attributes label{font-size:.8rem;font-weight:600}.locations-details section{border-top:1px solid var(--location-border);margin-top:1rem;padding-top:1rem}.locations-details section h3{font-size:.95rem}.locations-details [data-description-editor]{width:100%;min-height:180px}.locations-details .location-child-link{display:block;text-align:left;margin:.3rem 0}.locations-details [data-related] a{display:block;margin-block:.4rem}.locations-dialog{background:var(--location-panel);color:var(--bs-body-color);border:1px solid var(--location-border);border-radius:.8rem;width:min(520px,calc(100vw - 24px));padding:1.5rem;max-height:85dvh;overflow:auto}.locations-dialog::backdrop{background:#0007}.locations-dialog h2{font-size:1.25rem}.locations-dialog [data-dialog-body]{margin-block:1rem}.locations-dialog input,.locations-dialog select{margin-bottom:.6rem}.locations-layout.attributes-collapsed{grid-template-columns:0 minmax(0,1fr) var(--workspace-right,320px)}.locations-layout.details-collapsed{grid-template-columns:var(--workspace-left,240px) minmax(0,1fr) 0}.locations-layout.attributes-collapsed.details-collapsed{grid-template-columns:0 minmax(0,1fr) 0}.locations-layout.attributes-collapsed>.pd-panel-divider[data-panel-side=left],.locations-layout.details-collapsed>.pd-panel-divider[data-panel-side=right]{display:none}.locations-layout [hidden]{display:none!important}
@media(max-width:899px){.locations-layout{grid-template-columns:minmax(0,1fr);height:auto;max-height:none;overflow:visible}.locations-attributes,.locations-details,.locations-centre{max-height:65dvh}.locations-attributes,.locations-details{border:0;border-bottom:1px solid var(--location-border)}.locations-layout.attributes-collapsed,.locations-layout.details-collapsed,.locations-layout.attributes-collapsed.details-collapsed{grid-template-columns:minmax(0,1fr)}.locations-centre{min-height:280px}.location-record .location-row-main{padding-left:calc(.2rem + min(var(--depth,0),8)*.7rem)}.location-record .location-indicators{flex-wrap:wrap}.locations-search{gap:.3rem}.locations-selection{flex-wrap:wrap}}
.location-attribute-row>button:first-child{font-size:.8rem;padding-inline:.3rem}.location-attribute-row>button:last-child{font-size:.68rem;padding-inline:.25rem}.location-attribute-row>button>span{overflow-wrap:normal}.location-attribute-row [data-count]{flex-shrink:0;white-space:nowrap}
.locations-primary-commands{display:flex;flex-wrap:wrap;gap:.45rem}.location-page .btn-outline-secondary{background:var(--location-panel);color:var(--bs-body-color);border-color:var(--location-border)}.location-page .btn-outline-secondary:hover,.location-page .btn-outline-secondary:focus-visible{background:var(--bs-secondary-bg);border-color:var(--location-accent)}
.locations-root{position:sticky;top:0;z-index:2;background:var(--location-panel)}
.location-tone-secondary{color:var(--pd-muted,var(--bs-secondary-color))}

View File

@ -0,0 +1,38 @@
/* Shared attribute palette. Consumers own records, filters, commands, drag payloads and preferences. */
(() => {
'use strict';
const node=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
const control=(label,run)=>{const b=node('button',label);b.type='button';b.addEventListener('click',run);return b;};
function mount(host,options){
host.classList.add('pd-attributes-panel');host.replaceChildren();const rows=[];
for(const group of options.groups){
const section=node('details');section.dataset.attributeGroup=group.id;section.open=options.isExpanded?.(group.id,true)??true;
section.append(node('summary',group.label));section.addEventListener('toggle',()=>options.onExpansion?.(group.id,section.open));
if(group.editable===false)section.append(node('p','Filter only'));
const values=group.values,byParent=new Map(),byKey=new Map(values.map(v=>[v.key??v.value,v]));
for(const v of values){const parent=v.parentKey&&byKey.has(v.parentKey)?v.parentKey:null;if(!byParent.has(parent))byParent.set(parent,[]);byParent.get(parent).push(v);}
const visited=new Set();
function append(v,parent,depth){
const key=v.key??v.value;if(visited.has(key))return;visited.add(key);
const branch=node('div');branch.className='pd-attribute-branch';const row=node('div');row.className='pd-attribute-row '+(options.rowClass||'');row.dataset.attribute=group.id;row.dataset.value=v.value;row.style.setProperty('--attribute-depth',depth);row.dataset.assignable=String(group.editable!==false&&v.assignable!==false);
const descendants=byParent.get(key)||[],expansionKey=`${group.id}:${key}`;let opened=options.isExpanded?.(expansionKey,false)??false;
const expand=control('',()=>{opened=!opened;sync();options.onExpansion?.(expansionKey,opened);});expand.className='pd-attribute-expand';expand.hidden=!descendants.length;
const filter=control('',()=>options.onFilter(group,v));filter.className='pd-attribute-filter';filter.dataset.attributeFilter='';filter.title=v.filterHint||`${group.label}: ${v.label}${descendants.length?' (includes descendants)':''}`;
const image=options.icon(v);image.classList.add('pd-attribute-icon');const label=node('span',v.label);label.className='pd-attribute-label';const count=node('span','0');count.dataset.count='';count.className='pd-attribute-count';filter.append(image,label,count);row.append(filter,descendants.length?expand:Object.assign(node('span'),{className:'pd-attribute-expand'}));
if(group.editable!==false&&v.assignable!==false){const assign=control('Assign',()=>options.onAssign(group,v));assign.className='pd-attribute-assign';assign.dataset.assign='';assign.setAttribute('aria-label',`Assign ${group.label}: ${v.label} to selected ${options.recordLabel||'records'}`);row.append(assign);}
row.draggable=group.editable!==false&&v.assignable!==false&&options.canEdit();
let dragBlocked=false;row.addEventListener('pointerdown',e=>{dragBlocked=!!e.target.closest('[data-assign],button.pd-attribute-expand');});
row.addEventListener('dragstart',e=>{if(dragBlocked||e.target.closest('[data-assign],.pd-attribute-expand')||!row.draggable){e.preventDefault();return;}options.onDragStart?.(e,group,v);});
row.addEventListener('click',e=>{if(!e.target.closest('button'))filter.click();});
const children=node('div');children.className='pd-attribute-children';
function sync(){children.hidden=!opened;expand.textContent=opened?'▾':'▸';expand.setAttribute('aria-label',`${opened?'Collapse':'Expand'} ${v.label}`);expand.setAttribute('aria-expanded',String(opened));}
sync();branch.append(row,children);parent.append(branch);rows.push({row,filter,count,group,value:v});for(const child of descendants)append(child,children,depth+1);
}
for(const v of byParent.get(null)||[])append(v,section,0);for(const v of values)if(!visited.has(v.key??v.value))append(v,section,0);
host.append(section);
}
function update({counts=true}={}){for(const entry of rows){const {row,filter,count,group,value}=entry;const active=!!options.isActive(group,value);filter.setAttribute('aria-pressed',String(active));row.classList.toggle('is-filter-active',active);if(counts)count.textContent=String(options.count(group,value));const assign=row.querySelector('[data-assign]');if(assign)assign.disabled=!options.canEdit()||options.busy()||!options.hasSelection();row.draggable=!!assign&&options.canEdit()&&!options.busy();}}
update();return{update};
}
window.PlotDirectorAttributesPanel=Object.freeze({mount});
})();

View File

@ -2,21 +2,27 @@
'use strict';
const root=document.querySelector('[data-character-attributes]');if(!root)return;
const project=Number(root.dataset.projectId),cards=[...root.querySelectorAll('.character-card')],byId=new Map(cards.map(c=>[Number(c.dataset.dragId),c])),selected=new Set(),filter=new Map(),sidebar=root.querySelector('[data-attribute-sidebar]'),groupsHost=root.querySelector('[data-attribute-groups]'),undoButton=root.querySelector('[data-undo]'),toggle=root.querySelector('[data-attributes-toggle]');
const toast=window.PlotDirector?.toast;let groups=[],records=new Map(),canEdit=false,busy=false,anchor=null,undo=null,drag=null,ignoreClickUntil=0,connection=null,refreshing=null,readEpoch=0,pendingRefresh=false;
const toast=window.PlotDirector?.toast;let attributePanel=null;let groups=[],records=new Map(),canEdit=false,busy=false,anchor=null,undo=null,drag=null,ignoreClickUntil=0,connection=null,refreshing=null,readEpoch=0,pendingRefresh=false;
const button=(label,fn)=>{const b=document.createElement('button');b.type='button';b.className='btn btn-outline-secondary btn-sm';b.textContent=label;b.addEventListener('click',fn);return b;};
function icon(value){const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('class',`character-attribute-icon text-${value.tone}`);svg.setAttribute('aria-hidden','true');const path=document.createElementNS(svg.namespaceURI,'path');path.setAttribute('d',value.path);path.setAttribute('fill',value.filled?'currentColor':'none');path.setAttribute('fill-rule','evenodd');svg.append(path);return svg;}
function shown(){return cards.filter(c=>!c.hidden);}
function scope(id){return selected.has(id)?[...selected]:[id];}
function selection(){for(const [id,c]of byId){c.classList.toggle('is-selected',selected.has(id));c.querySelector('[data-character-select]').checked=selected.has(id);}root.querySelector('[data-selection-count]').textContent=`${selected.size} selected`;groupsHost.querySelectorAll('[data-assign]').forEach(b=>b.disabled=!canEdit||busy||!selected.size);}
function selection(){for(const [id,c]of byId){c.classList.toggle('is-selected',selected.has(id));c.querySelector('[data-character-select]').checked=selected.has(id);}root.querySelector('[data-selection-count]').textContent=`${selected.size} selected`;attributePanel?.update({counts:false});}
function matching(record,except){return [...filter].every(([a,v])=>a===except||displayValue(a,record?.values[a])===v);}
function displayValue(a,v){if(a==='sex'&&v?.startsWith('legacy:')){const label=v.slice(7).trim().toLowerCase(),recorded=groups.find(g=>g.id==='sex')?.values.find(value=>value.recordedLabels?.includes(label));return recorded?.value??v;}if(a==='importance'&&v!=='')return Number(v)>=8?'10':Number(v)>=4?'6':Number(v)>=1?'2':'';return v;}
function render(){
for(const [id,card]of byId){const r=records.get(id);if(!r)continue;card.hidden=!matching(r);const indicators=card.querySelector('[data-attribute-indicators]'),signature=JSON.stringify(r.values);if(indicators.dataset.values===signature)continue;indicators.dataset.values=signature;indicators.replaceChildren();for(const g of groups){const v=g.values.find(v=>v.value===displayValue(g.id,r.values[g.id]))||(g.id==='sex'&&r.values.sex?.startsWith('legacy:')?{...g.fallback,label:r.values.sex.slice(7)}:null);if(!v)continue;const span=document.createElement('span');span.title=`${g.label}: ${v.label}`;span.setAttribute('role','img');span.setAttribute('aria-label',span.title);span.append(icon(v));indicators.append(span);}}
for(const row of groupsHost.querySelectorAll('[data-attribute]')){const g=row.dataset.attribute,v=row.dataset.value,b=row.firstElementChild,count=[...records.values()].filter(r=>matching(r,g)&&displayValue(g,r.values[g])===v).length;b.querySelector('[data-count]').textContent=` (${count})`;b.setAttribute('aria-pressed',String(filter.get(g)===v));b.classList.toggle('active',filter.get(g)===v);}
attributePanel?.update();
// A filtered-out selection must never silently participate in the next bulk action.
for(const id of selected)if(byId.get(id)?.hidden)selected.delete(id);selection();
}
function build(){const signature=JSON.stringify(groups);if(groupsHost.dataset.definitions===signature){render();return;}groupsHost.dataset.definitions=signature;root.querySelectorAll('[data-character-drag]').forEach(b=>b.disabled=!canEdit);groupsHost.replaceChildren();for(const g of groups){const details=document.createElement('details');details.open=true;const summary=document.createElement('summary');summary.textContent=g.label;details.append(summary);for(const v of g.values){const row=document.createElement('div');row.className='character-attribute-value';row.dataset.attribute=g.id;row.dataset.value=v.value;const b=button(v.label,()=>{if(Date.now()<ignoreClickUntil)return;filter.get(g.id)===v.value?filter.delete(g.id):filter.set(g.id,v.value);render();});b.prepend(icon(v),document.createTextNode(' '));const count=document.createElement('span');count.dataset.count='';b.append(count);b.draggable=canEdit;b.addEventListener('dragstart',e=>{if(!canEdit)return e.preventDefault();drag={attribute:g.id,value:v.value};e.dataTransfer.setData('application/x-plotdirector-attribute',JSON.stringify(drag));e.dataTransfer.effectAllowed='copy';preview(e,`${g.label}: ${v.label}`);root.classList.add('dragging-attribute');});row.append(b);const assign=button('Assign',()=>assignTo(g.id,v.value,[...selected]));assign.dataset.assign='';assign.setAttribute('aria-label',`Assign ${g.label}: ${v.label} to selected characters`);row.append(assign);details.append(row);}groupsHost.append(details);}render();}
function build(){const signature=JSON.stringify(groups);if(groupsHost.dataset.definitions===signature){render();return;}groupsHost.dataset.definitions=signature;root.querySelectorAll('[data-character-drag]').forEach(b=>b.disabled=!canEdit);
let expansion={};try{expansion=JSON.parse(localStorage.getItem(preference+'.groups')||'{}');}catch{}
attributePanel=window.PlotDirectorAttributesPanel.mount(groupsHost,{groups,rowClass:'character-attribute-value',recordLabel:'characters',icon,canEdit:()=>canEdit,busy:()=>busy,hasSelection:()=>selected.size>0,
isExpanded:(key,fallback)=>expansion[key]??fallback,onExpansion:(key,open)=>{expansion[key]=open;try{localStorage.setItem(preference+'.groups',JSON.stringify(expansion));}catch{}},
isActive:(g,v)=>filter.get(g.id)===v.value,count:(g,v)=>[...records.values()].filter(r=>matching(r,g.id)&&displayValue(g.id,r.values[g.id])===v.value).length,
onFilter:(g,v)=>{if(Date.now()<ignoreClickUntil)return;filter.get(g.id)===v.value?filter.delete(g.id):filter.set(g.id,v.value);render();},onAssign:(g,v)=>assignTo(g.id,v.value,[...selected]),
onDragStart:(e,g,v)=>{drag={attribute:g.id,value:v.value};e.dataTransfer.setData('application/x-plotdirector-attribute',JSON.stringify(drag));e.dataTransfer.effectAllowed='copy';preview(e,`${g.label}: ${v.label}`);root.classList.add('dragging-attribute');}});render();}
async function refresh(){if(refreshing)return refreshing;const epoch=readEpoch;refreshing=(async()=>{try{const response=await fetch(`/CharacterAttributes/Directory?projectId=${project}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Character attributes are unavailable.');const data=await response.json();if(epoch!==readEpoch)return;canEdit=data.canEdit;groups=data.groups;records=new Map(data.characters.filter(r=>byId.has(r.id)).map(r=>[r.id,r]));build();}catch(e){toast?.error(e.message);}finally{refreshing=null;}})();return refreshing;}
async function currentRefresh(){if(refreshing)await refreshing;return refresh();}
async function persist(attribute,changes,isUndo=false){if(busy){toast?.info('An attribute update is still saving. Try again in a moment.');return;}if(!canEdit||!changes?.length)return;busy=true;readEpoch++;selection();try{const response=await fetch(isUndo?'/CharacterAttributes/Undo':'/CharacterAttributes/Assign',{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':root.querySelector('[name="__RequestVerificationToken"]').value},body:JSON.stringify(isUndo?{token:changes}:{projectId:project,attribute,changes})});if(!response.ok||response.redirected){let message='Could not save character attributes.';try{message=(await response.json()).message||message;}catch{}throw Error(message);}const data=await response.json();if(!data.saved)throw Error('The save was not confirmed.');for(const r of data.characters)records.set(r.id,r);render();window.PlotDirectorContextMenus?.close();if(!data.characters.length){toast?.info('Those attributes are already recorded.');return;}if(isUndo){undo=null;undoButton.hidden=true;toast?.success('Character attributes restored.');}else{undo=data.undoToken;const operation=undo;undoButton.hidden=false;toast?.success(`${data.characters.length} character${data.characters.length===1?'':'s'} updated.`,{duration:10000,action:{label:'Undo',run:()=>persist(null,operation,true)}});}}catch(e){toast?.error(e.message);await currentRefresh();}finally{busy=false;selection();if(pendingRefresh){pendingRefresh=false;void currentRefresh();}}}

View File

@ -0,0 +1,39 @@
/* Containment selection only. Never changes data; operations retain their own server validation. */
(() => {
'use strict';
const element=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
const button=(label,run)=>{const b=element('button',label);b.type='button';b.addEventListener('click',run);return b;};
function mount(host,options){
host.classList.add('pd-location-picker');const records=new Map(options.locations.map(r=>[String(r.id),r])),children=new Map(),expanded=new Set(),excluded=new Set((options.excludeIds||[]).map(String)),types=new Map((options.types||[]).map(t=>[String(t.value),t]));
const searchOverrides=new Map();let forcedExpanded=new Set();let value=options.selected===undefined?undefined:String(options.selected??''),query='',visible=[],focus=value;
function ancestors(id){const result=[],seen=new Set([id]);let p=records.get(id)?.parent;while(p!=null&&records.has(String(p))&&!seen.has(String(p))){p=String(p);seen.add(p);result.push(p);p=records.get(p).parent;}return result;}
function path(id){if(id==='')return options.rootLabel||'Root level';const r=records.get(id);if(!r)return'';const chain=ancestors(id).reverse(),highest=records.get(chain[0]||id);return [...(highest.parent!=null&&!records.has(String(highest.parent))?['Parent unavailable']:[]),...chain.map(a=>records.get(a).name),r.name].join(' / ');}
const branches=new Set((options.excludeBranches||[]).map(String));const allowed=id=>!excluded.has(id)&&!branches.has(id)&&!ancestors(id).some(a=>branches.has(a));
for(const [id,r]of records){const parent=r.parent!=null&&records.has(String(r.parent))?String(r.parent):null;if(!children.has(parent))children.set(parent,[]);children.get(parent).push(id);}
const names=new Map();for(const r of records.values())names.set(r.name,(names.get(r.name)||0)+1);
const compare=(a,b)=>records.get(a).name.localeCompare(records.get(b).name,undefined,{numeric:true,sensitivity:'base'})||Number(a)-Number(b);for(const list of children.values())list.sort(compare);
if(value)ancestors(value).forEach(id=>expanded.add(id));
const tools=element('div',undefined,'pd-location-picker-tools'),search=element('input');search.type='search';search.className='form-control form-control-sm';search.placeholder='Search names, aliases and paths…';search.setAttribute('aria-label',options.searchLabel||'Search locations');tools.append(search,button('Clear search',()=>{search.value='';query='';searchOverrides.clear();render();search.focus();}),button('Expand all',()=>{for(const id of children.keys())if(id){if(query)searchOverrides.set(id,true);else expanded.add(id);}render();}),button('Collapse all',()=>{if(query){for(const id of children.keys())if(id)searchOverrides.set(id,false);}else expanded.clear();render();}));
const tree=element('div',undefined,'pd-location-picker-tree');tree.setAttribute('role','tree');tree.setAttribute('aria-label',options.label||'Choose location');const selected=element('p',undefined,'pd-location-picker-path');selected.setAttribute('role','status');host.replaceChildren(tools,tree,selected);
function choose(id){if(id!==''&&!allowed(id))return;value=id;focus=id;render();options.onChange?.(id);tree.querySelector(`[data-picker-id="${id}"]`)?.focus({preventScroll:true});}
function render(){
const matched=new Set(),context=new Set(),forced=new Set();for(const [id,r]of records)if(!query||[r.name,...(r.aliases||[]),path(id)].some(s=>s.toLocaleLowerCase().includes(query))){matched.add(id);context.add(id);for(const a of ancestors(id)){context.add(a);forced.add(a);}}
forcedExpanded=forced;visible=[];const fragment=document.createDocumentFragment(),seen=new Set();
function row(id,depth){if(seen.has(id)||query&&!context.has(id))return;seen.add(id);visible.push(id);const r=records.get(id),hasChildren=!!children.get(id)?.length,open=query?(searchOverrides.get(id)??forced.has(id)):expanded.has(id),entry=element('div',undefined,'pd-location-picker-row');entry.dataset.pickerId=id;entry.setAttribute('role','treeitem');entry.setAttribute('aria-level',String(depth+1));entry.setAttribute('aria-selected',String(value===id));entry.setAttribute('aria-disabled',String(!allowed(id)));entry.style.setProperty('--picker-depth',depth);entry.tabIndex=focus===id?0:-1;entry.title=path(id);if(hasChildren)entry.setAttribute('aria-expanded',String(open));
const expand=button(hasChildren?(open?'▾':'▸'):'',()=>{if(query)searchOverrides.set(id,!open);else expanded.has(id)?expanded.delete(id):expanded.add(id);focus=id;render();tree.querySelector(`[data-picker-id="${id}"]`)?.focus();});expand.disabled=!hasChildren;expand.setAttribute('aria-disabled',String(!hasChildren));expand.tabIndex=-1;expand.setAttribute('aria-label',`${open?'Collapse':'Expand'} ${r.name}`);entry.append(expand);
const t=types.get(String(r.type??''));if(t?.path){const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('class',`pd-location-picker-icon text-${t.tone||'secondary'}`);svg.setAttribute('aria-hidden','true');const p=document.createElementNS(svg.namespaceURI,'path');p.setAttribute('d',t.path);p.setAttribute('fill',t.filled?'currentColor':'none');svg.append(p);entry.append(svg);}
const name=button(r.name,()=>choose(id));name.className='pd-location-picker-name';name.disabled=!allowed(id);name.tabIndex=-1;const label=element('span');label.append(name);if(query||names.get(r.name)>1)label.append(element('small',path(id)));entry.append(label);entry.addEventListener('click',e=>{if(e.target===entry)choose(id);});fragment.append(entry);if(open)for(const child of children.get(id)||[])row(child,depth+1);
}
if(options.allowRoot){const root=element('div',options.rootLabel||'Root level','pd-location-picker-row pd-location-picker-root');root.dataset.pickerId='';root.setAttribute('role','treeitem');root.setAttribute('aria-level','1');root.setAttribute('aria-selected',String(value===''));root.tabIndex=focus===''?0:-1;root.addEventListener('click',()=>choose(''));fragment.append(root);visible.push('');}
for(const id of children.get(null)||[])row(id,0);for(const id of records.keys())if(!seen.has(id)&&!ancestors(id).some(a=>seen.has(a)))row(id,0);
tree.replaceChildren(fragment);if(!visible.length||query&&!matched.size)tree.append(element('p','No matching locations. Clear search to see the hierarchy.'));if(!visible.includes(focus)){focus=visible[0];tree.firstElementChild?.setAttribute('tabindex','0');}selected.textContent=value===undefined?'No location selected.':`Selected: ${path(value)}`;
}
search.addEventListener('keydown',e=>{if(e.key!=='Enter'&&e.key!=='ArrowDown')return;e.preventDefault();e.stopPropagation();focus=visible.find(id=>id!==''&&allowed(id)&&(!query||[records.get(id).name,...(records.get(id).aliases||[]),path(id)].some(s=>s.toLocaleLowerCase().includes(query))))??visible[0];const row=[...tree.querySelectorAll('[data-picker-id]')].find(n=>n.dataset.pickerId===focus);if(row){tree.querySelectorAll('[tabindex]').forEach(n=>n.tabIndex=-1);row.tabIndex=0;row.focus();}});
search.addEventListener('input',()=>{query=search.value.trim().toLocaleLowerCase();searchOverrides.clear();render();});tree.addEventListener('keydown',e=>{if(e.target.closest('input'))return;const id=e.target.closest('[data-picker-id]')?.dataset.pickerId;if(id===undefined)return;let next=id;const index=visible.indexOf(id),r=records.get(id);
if(e.key==='ArrowDown')next=visible[Math.min(index+1,visible.length-1)];else if(e.key==='ArrowUp')next=visible[Math.max(index-1,0)];else if(e.key==='Home')next=visible[0];else if(e.key==='End')next=visible.at(-1);else if(e.key==='ArrowRight'){if(children.get(id)?.length){if(!(query?(searchOverrides.get(id)??forcedExpanded.has(id)):expanded.has(id))){query?searchOverrides.set(id,true):expanded.add(id);render();}else next=children.get(id)[0];}}else if(e.key==='ArrowLeft'){if(query?(searchOverrides.get(id)??forcedExpanded.has(id)):expanded.has(id)){query?searchOverrides.set(id,false):expanded.delete(id);render();}else if(r?.parent!=null)next=String(r.parent);}else if(e.key==='Enter'||e.key===' '){choose(id);}else return;e.preventDefault();e.stopPropagation();focus=next;const target=[...tree.querySelectorAll('[data-picker-id]')].find(n=>n.dataset.pickerId===next);tree.querySelectorAll('[tabindex]').forEach(n=>n.tabIndex=-1);if(target){target.tabIndex=0;target.focus();}
});render();return{get value(){return value===''?(options.allowRoot?'':undefined):(value!==undefined&&records.has(value)&&allowed(value)?value:undefined);},focus:()=>search.focus(),path};
}
async function data(project){const response=await fetch(`/LocationWorkspace/Picker?projectId=${project}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Locations are unavailable.');return response.json();}
function enhance(select){if(select.dataset.pickerReady)return;select.dataset.pickerReady='true';const trigger=button('',async()=>{trigger.disabled=true;let dialog;try{const directory=await data(select.dataset.projectId);dialog=element('dialog',undefined,'pd-location-picker-dialog');const heading=element('h2',select.dataset.pickerLabel||'Choose location'),body=element('div'),actions=element('div',undefined,'button-row');const picker=mount(body,{...directory,label:heading.textContent,allowRoot:select.dataset.allowRoot==='true',selected:select.value||(select.dataset.allowRoot==='true'?'':undefined),rootLabel:'Root level',excludeIds:select.dataset.excludeId?[select.dataset.excludeId]:[],excludeBranches:select.dataset.excludeBranch?[select.dataset.excludeBranch]:[]});const save=button('Choose location',()=>{if(picker.value===undefined)return;const id=picker.value;if(![...select.options].some(o=>o.value===id))select.add(new Option(picker.path(id),id));select.value=id;select.dispatchEvent(new Event('change',{bubbles:true}));update();dialog.close();});save.className='btn btn-primary btn-sm';const cancel=button('Cancel',()=>dialog.close());cancel.className='btn btn-outline-secondary btn-sm';actions.append(save,cancel);dialog.append(heading,body,actions);dialog.addEventListener('close',()=>{dialog.remove();trigger.focus();});document.body.append(dialog);dialog.showModal();picker.focus();}catch(e){window.PlotDirector?.toast?.error(e.message);dialog?.remove();}finally{trigger.disabled=select.disabled;}});trigger.className='btn btn-outline-secondary pd-location-picker-trigger';trigger.setAttribute('aria-haspopup','dialog');trigger.setAttribute('aria-label',select.dataset.pickerLabel||'Choose location');function update(){trigger.textContent=select.selectedOptions[0]?.textContent?.trim()||'Choose location…';trigger.disabled=select.disabled;}select.addEventListener('change',update);update();select.hidden=true;select.after(trigger);}
document.querySelectorAll('select[data-location-picker]').forEach(enhance);window.PlotDirectorLocationPicker=Object.freeze({mount,enhance,data});
})();

View File

@ -0,0 +1,15 @@
/* Canonical taxonomy selection, shared by workspace Details and traditional forms. */
(() => {
'use strict';let pending;
async function definitions(){if(!pending)pending=fetch('/LocationWorkspace/Taxonomy',{cache:'no-store'}).then(async response=>{if(!response.ok||response.redirected)throw Error('Location types are unavailable.');return response.json();}).catch(e=>{pending=null;throw e;});return pending;}
async function choose({taxonomy,selected=''}){
taxonomy=taxonomy||await definitions();return new Promise(resolve=>{
const dialog=document.createElement('dialog');dialog.className='pd-location-picker-dialog';const title=document.createElement('h2');title.textContent='Choose location type';const body=document.createElement('div'),actions=document.createElement('div');actions.className='button-row';
const selectedEntry=taxonomy.find(t=>t.assignable!==false&&t.value===selected),entries=taxonomy.map(t=>({id:t.key??t.value,parent:t.parentKey||null,name:t.label,type:t.value}));
const picker=window.PlotDirectorLocationPicker.mount(body,{locations:entries,types:taxonomy,label:'Location type taxonomy',searchLabel:'Search location types',selected:selectedEntry?.key??selectedEntry?.value,excludeIds:taxonomy.filter(t=>t.assignable===false).map(t=>t.key)});
let result=null;const save=document.createElement('button');save.type='button';save.className='btn btn-primary btn-sm';save.textContent='Choose type';save.addEventListener('click',()=>{const entry=taxonomy.find(t=>(t.key??t.value)===picker.value);if(!entry||entry.assignable===false)return;result=entry.value;dialog.close();});const cancel=document.createElement('button');cancel.type='button';cancel.className='btn btn-outline-secondary btn-sm';cancel.textContent='Cancel';cancel.addEventListener('click',()=>dialog.close());actions.append(save,cancel);dialog.append(title,body,actions);dialog.addEventListener('close',()=>{dialog.remove();resolve(result);});document.body.append(dialog);dialog.showModal();picker.focus();
});
}
function enhance(select){const trigger=document.createElement('button');trigger.type='button';trigger.className='btn btn-outline-secondary pd-location-picker-trigger';trigger.setAttribute('aria-haspopup','dialog');trigger.setAttribute('aria-label','Location type');const update=()=>{trigger.textContent=select.selectedOptions[0]?.textContent?.trim()||'Unclassified';trigger.disabled=select.disabled;};trigger.addEventListener('click',async()=>{try{const taxonomy=await definitions(),value=await choose({taxonomy,selected:select.value});if(value===null)return;const entry=taxonomy.find(t=>t.assignable!==false&&t.value===value);if(![...select.options].some(o=>o.value===value))select.add(new Option(entry.label,value));select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));update();trigger.focus();}catch(e){window.PlotDirector?.toast?.error(e.message);}});select.addEventListener('change',update);update();select.hidden=true;select.after(trigger);}
document.querySelectorAll('select[data-location-type-picker]').forEach(enhance);window.PlotDirectorLocationTypes=Object.freeze({choose,definitions});
})();

View File

@ -4,23 +4,23 @@
const $=s=>root.querySelector(s),project=Number(root.dataset.projectId),layout=$('.locations-layout'),host=$('[data-location-records]'),details=$('[data-details]'),groupsHost=$('[data-groups]'),dialog=$('[data-location-dialog]');
const toast=window.PlotDirector?.toast,user=document.querySelector('[data-toast-host]')?.dataset.toastUser||'session',key=`pd.locations.workspace.v1.${user}.${project}`;
let prefs={view:'tree',sort:'asc',expanded:[],groups:{},attributes:false,details:false};try{Object.assign(prefs,JSON.parse(localStorage.getItem(key)||'{}'));}catch{}
let readEpoch=0,records=new Map(),children=new Map(),types=[],groups=[],selected=new Set(),active=null,filters=new Map(),expanded=new Set(prefs.expanded),query='',busy=false,drag=null,undo=null,canEdit=false,hoverTimer=null,hoverId=null,connection=null,pendingRefresh=false,refreshing=null,descriptionDraft=null,rendered=[],dialogSave=null,anchor=null;
let taxonomy=[],typeMembers=new Map(),attributePanel=null;let readEpoch=0,records=new Map(),children=new Map(),types=[],groups=[],selected=new Set(),active=null,filters=new Map(),expanded=new Set(prefs.expanded),query='',busy=false,drag=null,undo=null,canEdit=false,hoverTimer=null,hoverId=null,connection=null,pendingRefresh=false,refreshing=null,descriptionDraft=null,rendered=[],dialogSave=null,anchor=null;
const savePrefs=()=>{prefs.expanded=[...expanded];try{localStorage.setItem(key,JSON.stringify(prefs));}catch{}};
function el(tag,text,cls){const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;}
function button(label,fn,cls='btn btn-outline-secondary btn-sm'){const n=el('button',label,cls);n.type='button';n.addEventListener('click',fn);return n;}
function icon(value){const n=document.createElementNS('http://www.w3.org/2000/svg','svg');n.setAttribute('viewBox','0 0 24 24');n.setAttribute('class',`location-icon location-tone-${value?.tone||'secondary'}`);n.setAttribute('aria-hidden','true');const p=document.createElementNS(n.namespaceURI,'path');p.setAttribute('d',value?.path||'M12 3v12 M12 20v1');p.setAttribute('fill',value?.filled?'currentColor':'none');n.append(p);return n;}
function type(r){return types.find(t=>t.value===r.type)||{...types[0],label:r.typeName||'Unclassified'};}
function type(r){return types.find(t=>t.value===r.type)||{...(types.find(t=>t.value==='')||{icon:'help',tone:'secondary'}),label:r.typeName||'Unclassified'};}
function path(id,includeSelf=true){const result=[],visited=new Set(),start=records.get(id);let missing=!includeSelf&&start?.parent&&!records.has(start.parent),r=includeSelf?start:records.get(start?.parent);while(r&&!visited.has(r.id)){visited.add(r.id);result.unshift(r.name);if(r.parent&&!records.has(r.parent))missing=true;r=records.get(r.parent);}if(missing)result.unshift('Parent unavailable');return result.join(' / ');}
function ancestors(id){const result=[],visited=new Set([id]);let p=records.get(id)?.parent;while(records.has(p)&&!visited.has(p)){visited.add(p);result.push(p);p=records.get(p).parent;}return result;}
function index(){children=new Map();for(const r of records.values()){const parent=records.has(r.parent)?r.parent:null;if(!children.has(parent))children.set(parent,[]);children.get(parent).push(r.id);}const order=(a,b)=>records.get(a).name.localeCompare(records.get(b).name,undefined,{numeric:true,sensitivity:'base'})*(prefs.sort==='desc'?-1:1)||a-b;for(const ids of children.values())ids.sort(order);}
function scope(id){return selected.has(id)?[...selected]:[id];}
function value(r,a){if(a==='parent')return r.parent?.toString()||'';if(a==='name')return r.name;return r[a]??'';}
function matches(r){if(query&&!([r.name,...r.aliases].some(t=>t.toLocaleLowerCase().includes(query))))return false;for(const [a,v]of filters){if(a==='branch'){if(v&&r.id!==Number(v)&&!ancestors(r.id).includes(Number(v)))return false;}else if(a==='parentState'){if((v==='root')!==(r.parent===null))return false;}else if(a==='descriptionState'){if((v==='yes')!==!!r.description.trim())return false;}else if(a==='childrenState'){if((v==='yes')!==!!children.get(r.id)?.length)return false;}else if(a==='mapState'){if((v==='yes')!==!!r.maps.length)return false;}else if(a==='floorState'){if((v==='yes')!==!!r.floors.length)return false;}else if(a==='usageState'){if((v==='yes')!==(r.scenes>0))return false;}else if(value(r,a)!==v)return false;}return true;}
function matches(r){if(query&&!([r.name,...r.aliases].some(t=>t.toLocaleLowerCase().includes(query))))return false;for(const [a,v]of filters){if(a==='branch'){if(v&&r.id!==Number(v)&&!ancestors(r.id).includes(Number(v)))return false;}else if(a==='parentState'){if((v==='root')!==(r.parent===null))return false;}else if(a==='descriptionState'){if((v==='yes')!==!!r.description.trim())return false;}else if(a==='childrenState'){if((v==='yes')!==!!children.get(r.id)?.length)return false;}else if(a==='mapState'){if((v==='yes')!==!!r.maps.length)return false;}else if(a==='floorState'){if((v==='yes')!==!!r.floors.length)return false;}else if(a==='usageState'){if((v==='yes')!==(r.scenes>0))return false;}else if(a==='type'){if(!typeMembers.get(v)?.has(r.type))return false;}else if(value(r,a)!==v)return false;}return true;}
function dirty(){return descriptionDraft&&descriptionDraft.value!==descriptionDraft.original;}
function leaveDraft(){if(!dirty())return true;return window.confirm('Discard the unsaved description? Choose Cancel to keep editing.');}
async function post(action,data){const response=await fetch(`/LocationWorkspace/${action}`,{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':$('[name=__RequestVerificationToken]').value},body:JSON.stringify(data)});if(response.redirected)throw Error('Your session has expired. Sign in again before saving.');const result=await response.json().catch(()=>({message:'The change could not be saved.'}));if(!response.ok)throw Error(result.message||'The change could not be saved.');return result;}
function failure(e){$('[data-workspace-error]').textContent=e.message;toast?.error(e.message);}
async function refresh(){if(refreshing)return refreshing;if(busy||dirty()){pendingRefresh=true;return;}const epoch=readEpoch;refreshing=(async()=>{try{const response=await fetch(`/LocationWorkspace/Directory?projectId=${project}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Locations could not be loaded. Reload to retry.');const data=await response.json();if(epoch!==readEpoch||dirty()){pendingRefresh=true;return;}canEdit=data.canEdit;records=new Map(data.locations.map(r=>[r.id,r]));types=[{value:'',label:'Unclassified',icon:'help',path:'M9 8a3 3 0 1 1 4 3c-1 1-1 2-1 3 M12 18v1 M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0',tone:'secondary'},...data.types];index();buildGroups();render();renderDetails();$('[data-workspace-error]').textContent='';}catch(e){failure(e);}finally{refreshing=null;host.setAttribute('aria-busy','false');if(pendingRefresh&&!busy&&!dirty()){pendingRefresh=false;queueMicrotask(()=>void refresh());}}})();return refreshing;}
async function refresh(){if(refreshing)return refreshing;if(busy||dirty()){pendingRefresh=true;return;}const epoch=readEpoch;refreshing=(async()=>{try{const response=await fetch(`/LocationWorkspace/Directory?projectId=${project}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Locations could not be loaded. Reload to retry.');const data=await response.json();if(epoch!==readEpoch||dirty()){pendingRefresh=true;return;}canEdit=data.canEdit;records=new Map(data.locations.map(r=>[r.id,r]));types=data.types.some(t=>t.value==='')?data.types:[{value:'',label:'Unclassified',icon:'help',tone:'secondary'},...data.types];taxonomy=data.taxonomy||types;indexTaxonomy();index();buildGroups();render();renderDetails();$('[data-workspace-error]').textContent='';}catch(e){failure(e);}finally{refreshing=null;host.setAttribute('aria-busy','false');if(pendingRefresh&&!busy&&!dirty()){pendingRefresh=false;queueMicrotask(()=>void refresh());}}})();return refreshing;}
async function assign(attribute,newValue,ids,isUndo=false,token=null){if(busy){toast?.info('A location update is still saving. Try again in a moment.');return false;}if(!canEdit)return false;if(!isUndo){ids=ids.filter(id=>records.has(id)&&(attribute==='parent'||value(records.get(id),attribute)!==newValue));if(!ids.length)return;}
busy=true;readEpoch++;$('[data-workspace-error]').textContent='';selection();try{const data=await post(isUndo?'Undo':'Assign',isUndo?{token}:{projectId:project,attribute,changes:ids.map(id=>({id,value:newValue,version:records.get(id).version}))});
if(!data.changes.length)return true;
@ -28,25 +28,29 @@
undo=isUndo?null:data.undoToken;$('[data-undo]').hidden=!undo;index();render();renderDetails();if(data.changes.length){const receipt=undo;toast?.success(isUndo?'Location changes restored.':`${data.changes.length} location${data.changes.length===1?'':'s'} updated.`,receipt?{action:{label:'Undo',run:()=>assign(null,null,[],true,receipt)}}:undefined);}
return true;
}catch(e){failure(e);return false;}finally{busy=false;selection();if(pendingRefresh&&!dirty()){pendingRefresh=false;void refresh();}}}
function indexTaxonomy(){typeMembers=new Map();const byKey=new Map(taxonomy.map(v=>[v.key??v.value,v]));for(const entry of taxonomy){const members=new Set();for(const child of taxonomy){if(child.assignable===false)continue;let current=child;const seen=new Set();while(current&&!seen.has(current)){seen.add(current);if(current===entry){members.add(child.value);break;}current=byKey.get(current.parentKey);}}typeMembers.set(entry.value,members);}}
function informational(id,label,yes,no,iconName){return {id,label,editable:false,values:[{value:'yes',label:yes,icon:iconName},{value:'no',label:no,icon:'help'}]};}
function buildGroups(){groups=[{id:'type',label:'Location type',editable:true,values:types},{id:'classification',label:'Classification',editable:true,values:[{value:'',label:'Unclassified',icon:'help'},{value:'Real',label:'Real',icon:'location-globe'},{value:'Fictional',label:'Fictional',icon:'bible'},{value:'Fictionalised',label:'Fictionalised',icon:'writer'}]},
function buildGroups(){groups=[{id:'type',label:'Location type',editable:true,values:taxonomy},{id:'classification',label:'Classification',editable:true,values:[{value:'',label:'Unclassified',icon:'help'},{value:'Real',label:'Real',icon:'location-globe'},{value:'Fictional',label:'Fictional',icon:'bible'},{value:'Fictionalised',label:'Fictionalised',icon:'writer'}]},
{id:'quickAdd',label:'Quick Add Bar',editable:true,values:[{value:'1',label:'Included',icon:'attribute-pin'},{value:'0',label:'Excluded',icon:'attribute-unpin'}]},
{id:'detection',label:'Word Companion detection',editable:true,values:[{value:'0',label:'Included',icon:'validate'},{value:'1',label:'Excluded',icon:'help'}]},
{id:'parentState',label:'Hierarchy',editable:false,values:[{value:'root',label:'Root locations',icon:'locations'},{value:'parent',label:'Has parent',icon:'location-level'}]},
informational('mapState','Maps','Mapped','Unmapped','maps'),informational('floorState','Floor plans','Has floor plan','No floor plan','floorplans'),informational('usageState','Manuscript assignments','Used in scenes','No recorded scene use','scenes'),informational('descriptionState','Description','Recorded','Missing','edit'),informational('childrenState','Contained locations','Has children','No children','location-level')];
groupsHost.replaceChildren();for(const g of groups){const section=el('details');section.open=prefs.groups[g.id]!==false;const summary=el('summary',g.label);section.append(summary);section.addEventListener('toggle',()=>{prefs.groups[g.id]=section.open;savePrefs();});if(!g.editable)section.append(el('p','Filter only','small muted'));
for(const v of g.values){const row=el('div',undefined,'location-attribute-row');row.dataset.attribute=g.id;row.dataset.value=v.value;const filter=button('',()=>{filters.get(g.id)===v.value?filters.delete(g.id):filters.set(g.id,v.value);render();});filter.append(presentationIcon(v),el('span',v.label));const count=el('span','0');count.dataset.count='';filter.append(count);row.append(filter);filter.draggable=g.editable&&canEdit;filter.addEventListener('dragstart',e=>{if(!canEdit)return e.preventDefault();drag={attribute:g.id,value:v.value};e.dataTransfer.setData('application/x-plotdirector-location-attribute',JSON.stringify(drag));e.dataTransfer.effectAllowed='copy';});if(g.editable){const apply=button('Assign',()=>void assign(g.id,v.value,[...selected]));apply.dataset.assign='';apply.setAttribute('aria-label',`Assign ${g.label}: ${v.label} to selected locations`);row.append(apply);}section.append(row);}groupsHost.append(section);}
attributePanel=window.PlotDirectorAttributesPanel.mount(groupsHost,{groups,rowClass:'location-attribute-row',recordLabel:'locations',icon:presentationIcon,canEdit:()=>canEdit,busy:()=>busy,hasSelection:()=>selected.size>0,
isExpanded:(key,fallback)=>prefs.groups[key]??fallback,onExpansion:(key,open)=>{prefs.groups[key]=open;savePrefs();},isActive:(g,v)=>filters.get(g.id)===v.value,
count:(g,v)=>{const old=filters.get(g.id);filters.set(g.id,v.value);const count=[...records.values()].filter(matches).length;old===undefined?filters.delete(g.id):filters.set(g.id,old);return count;},
onFilter:(g,v)=>{filters.get(g.id)===v.value?filters.delete(g.id):filters.set(g.id,v.value);render();},onAssign:(g,v)=>void assign(g.id,v.value,[...selected]),
onDragStart:(e,g,v)=>{drag={attribute:g.id,value:v.value};e.dataTransfer.setData('application/x-plotdirector-location-attribute',JSON.stringify(drag));e.dataTransfer.effectAllowed='copy';}});
const section=el('details');section.open=prefs.groups.branch!==false;section.append(el('summary','Parent / branch'));section.addEventListener('toggle',()=>{prefs.groups.branch=section.open;savePrefs();});const b=button('Filter by branch…',()=>parentDialog('Filter locations in branch',id=>{id?filters.set('branch',id):filters.delete('branch');render();},true));b.dataset.branchFilter='';section.append(b,button('Change selected parent…',()=>parentDialog('Change parent',id=>void assign('parent',id,[...selected]))));groupsHost.append(section);
}
function presentationIcon(v){if(v.path)return icon(v);const source=document.querySelector('[data-pwa-icon-catalog]')?.content.querySelector(`[data-icon-key="${v.icon}"]`);if(source){const n=source.cloneNode(true);n.removeAttribute('data-icon-key');n.classList.add('location-icon');return n;}return icon(types[0]);}
function selection(){for(const row of host.querySelectorAll('[data-location-id]')){const id=Number(row.dataset.locationId);row.classList.toggle('is-selected',selected.has(id));row.querySelector('[data-select-location]').checked=selected.has(id);row.setAttribute('aria-selected',String(selected.has(id)));}groupsHost.querySelectorAll('[data-assign]').forEach(b=>b.disabled=!canEdit||busy||!selected.size);$('[data-selection-count]').textContent=`${selected.size} selected`;$('[data-selection-menu]').disabled=!selected.size;$('[data-undo]').disabled=busy;for(const s of ['[data-new-child]','[data-change-parent]','[data-create-relationship]'])$(s).disabled=!canEdit||busy||!records.has(active);}
function presentationIcon(v){if(v.path)return icon(v);const source=document.querySelector('[data-pwa-icon-catalog]')?.content.querySelector(`[data-icon-key="${v.icon}"]`);if(source){const n=source.cloneNode(true);n.removeAttribute('data-icon-key');n.classList.add('location-icon');return n;}return icon(types.find(t=>t.value===''));}
function selection(){for(const row of host.querySelectorAll('[data-location-id]')){const id=Number(row.dataset.locationId);row.classList.toggle('is-selected',selected.has(id));row.querySelector('[data-select-location]').checked=selected.has(id);row.setAttribute('aria-selected',String(selected.has(id)));}attributePanel?.update({counts:false});$('[data-selection-count]').textContent=`${selected.size} selected`;$('[data-selection-menu]').disabled=!selected.size;$('[data-undo]').disabled=busy;for(const s of ['[data-new-child]','[data-change-parent]','[data-create-relationship]'])$(s).disabled=!canEdit||busy||!records.has(active);}
function render(){index();const matchesIds=new Set([...records.values()].filter(matches).map(r=>r.id)),filtered=!!query||filters.size>0,visibleIds=new Set(matchesIds);if(filtered&&prefs.view==='tree')for(const id of matchesIds)ancestors(id).forEach(p=>visibleIds.add(p));
const order=[],visited=new Set();function walk(id,depth){if(visited.has(id))return;visited.add(id);if(filtered&&!visibleIds.has(id))return;order.push({id,depth});if(filtered||expanded.has(id))for(const c of children.get(id)||[])walk(c,depth+1);}
if(prefs.view==='tree'){for(const id of children.get(null)||[])walk(id,0);/* Preserve visibility for malformed legacy cycles without recursing indefinitely. */if(!filtered)for(const id of records.keys())if(!visited.has(id)&&!ancestors(id).some(a=>visited.has(a)))walk(id,0);}else{const ids=[...matchesIds].sort((a,b)=>records.get(a).name.localeCompare(records.get(b).name,undefined,{numeric:true})*(prefs.sort==='desc'?-1:1));ids.forEach(id=>order.push({id,depth:0}));}
const scroll=$('.locations-centre').scrollTop,focused=host.contains(document.activeElement)?document.activeElement.closest('[data-location-id]')?.dataset.locationId:null;rendered=order.map(x=>x.id);for(const id of selected)if(!matchesIds.has(id))selected.delete(id);
host.className=prefs.view==='cards'?'locations-cards':'';host.setAttribute('role',prefs.view==='cards'?'list':'tree');host.setAttribute('aria-label',prefs.view==='cards'?'Location cards':'Location hierarchy');const fragment=document.createDocumentFragment();for(const {id,depth}of order)fragment.append(recordNode(records.get(id),depth,filtered&&!matchesIds.has(id)));if(!order.length)fragment.append(el('p',records.size?'No matching locations. Clear filters or try another name.':'Your world starts here. Create your first location.','muted'));host.replaceChildren(fragment);$('.locations-centre').scrollTop=scroll;if(focused)host.querySelector(`[data-location-id="${focused}"]`)?.focus({preventScroll:true});
$('[data-result-count]').textContent=`${matchesIds.size} of ${records.size} locations${filtered&&prefs.view==='tree'?' · ancestors shown for context':''}`;
for(const g of groups)for(const v of g.values){const row=[...groupsHost.querySelectorAll('[data-attribute]')].find(n=>n.dataset.attribute===g.id&&n.dataset.value===v.value);if(!row)continue;const old=filters.get(g.id);filters.set(g.id,v.value);row.querySelector('[data-count]').textContent=[...records.values()].filter(matches).length;old===undefined?filters.delete(g.id):filters.set(g.id,old);row.firstElementChild.setAttribute('aria-pressed',String(old===v.value));}
attributePanel?.update();
const branch=groupsHost.querySelector('[data-branch-filter]');if(branch)branch.textContent=filters.has('branch')?`Branch: ${path(Number(filters.get('branch')))}`:'Filter by branch…';
root.querySelectorAll('[data-view]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.view===prefs.view)));selection();
}
@ -70,10 +74,10 @@
dialog.querySelector('[data-dialog-cancel]')?.addEventListener('click',()=>dialog.close());
dialog.querySelector('[data-dialog-save]').addEventListener('click',async()=>{const b=dialog.querySelector('[data-dialog-save]');b.disabled=true;try{if(await dialogSave()!==false)dialog.close();}catch(e){dialog.querySelector('[data-dialog-error]').textContent=e.message;}finally{b.disabled=false;}});
dialog.querySelector('form').addEventListener('submit',e=>{if(e.submitter?.value==='cancel')return;e.preventDefault();dialog.querySelector('[data-dialog-save]').click();});
function parentDialog(title,save,filterOnly=false,ids=[...selected]){const body=el('div'),search=el('input');search.type='search';search.className='form-control';search.placeholder='Find a parent by name or path';search.setAttribute('aria-label','Search parent locations');const select=el('select');select.className='form-select';select.size=9;select.setAttribute('aria-label','Parent location');function options(){const q=search.value.toLocaleLowerCase();select.replaceChildren(new Option(filterOnly?'All branches':'Root level',''));for(const r of records.values()){if(!filterOnly&&(ids.includes(r.id)||ancestors(r.id).some(a=>ids.includes(a))))continue;const p=path(r.id);if(!q||p.toLocaleLowerCase().includes(q))select.add(new Option(p,String(r.id)));}select.value='';}search.addEventListener('input',options);body.append(search,select);options();openDialog(title,body,()=>save(select.value));}
function parentDialog(title,save,filterOnly=false,ids=[...selected]){const body=el('div'),picker=window.PlotDirectorLocationPicker.mount(body,{locations:[...records.values()],types,allowRoot:true,rootLabel:filterOnly?'All branches':'Root level',selected:filterOnly?(filters.get('branch')||''):(ids.length===1?value(records.get(ids[0]),'parent'):undefined),excludeBranches:filterOnly?[]:ids});openDialog(title,body,()=>{if(picker.value===undefined)throw Error('Choose a parent or Root level.');return save(picker.value);});picker.focus();}
function createChild(parent){if(!canEdit||!leaveDraft())return;descriptionDraft=null;renderDetails();const body=el('div'),input=el('input');input.className='form-control';input.maxLength=200;input.setAttribute('aria-label','New location name');body.append(el('p',parent?`Inside ${path(parent)}`:'Create a root location','muted'),input);openDialog('Create child location',body,async()=>{if(!input.value.trim())throw Error('Enter a name.');const result=await post('Create',{projectId:project,name:input.value,parentId:parent});if(parent)expanded.add(parent);if(!leaveDraft())return false;descriptionDraft=null;readEpoch++;if(refreshing)await refreshing;await refresh();reveal(result.id);toast?.success('Location created.');});}
function field(label,control){const n=el('label',label);n.append(control);return n;}
function attributeSelect(attribute,r){const select=el('select');select.className='form-select form-select-sm';select.setAttribute('aria-label',groups.find(g=>g.id===attribute).label);for(const v of groups.find(g=>g.id===attribute).values)select.add(new Option(v.label,v.value));if(attribute==='type'&&r.type&&!types.some(t=>t.value===r.type)){const recorded=new Option(`${r.typeName||'Recorded type'} (unavailable)`,r.type);recorded.disabled=true;select.add(recorded);}select.value=value(r,attribute);select.disabled=!canEdit;select.addEventListener('change',async()=>{const old=value(r,attribute);select.disabled=true;const ok=await assign(attribute,select.value,[r.id]);if(!ok){select.value=old;select.disabled=!canEdit;}});return select;}
function attributeSelect(attribute,r){if(attribute==='type'){const control=button(type(r)?.label||'Unclassified',async()=>{const next=await window.PlotDirectorLocationTypes.choose({taxonomy,selected:r.type});if(next!==null)await assign('type',next,[r.id]);details.querySelector('[aria-label="Location type"]')?.focus();});control.setAttribute('aria-label','Location type');control.setAttribute('aria-haspopup','dialog');control.disabled=!canEdit||busy;return control;}const select=el('select');select.className='form-select form-select-sm';select.setAttribute('aria-label',groups.find(g=>g.id===attribute).label);for(const v of groups.find(g=>g.id===attribute).values)select.add(new Option(v.label,v.value));if(attribute==='type'&&r.type&&!types.some(t=>t.value===r.type)){const recorded=new Option(`${r.typeName||'Recorded type'} (unavailable)`,r.type);recorded.disabled=true;select.add(recorded);}select.value=value(r,attribute);select.disabled=!canEdit;select.addEventListener('change',async()=>{const old=value(r,attribute);select.disabled=true;const ok=await assign(attribute,select.value,[r.id]);if(!ok){select.value=old;select.disabled=!canEdit;}});return select;}
function renderDetails(){const held=dirty()?details.querySelector('[data-description-section]'):null,heldFocus=held?.contains(document.activeElement)?document.activeElement:null;const r=records.get(active);details.replaceChildren();if(!r){details.append(el('h2','Your world, in detail'),el('p','Select a location to edit its attributes and explore its connections.','muted'));return;}
const heading=el('div',undefined,'location-detail-heading');heading.append(icon(type(r)),el('h2',r.name));details.append(heading,el('p',path(r.id),'location-details-path'));const actions=el('div',undefined,'location-detail-actions');for(const [label,action]of [['Full details','Details'],['Edit location','Edit']]){const a=el('a',label,'btn btn-outline-secondary btn-sm');a.href=`/Locations/${action}/${r.id}`;actions.append(a);}if(canEdit)actions.append(button('Rename',()=>{reveal(r.id);rename(r.id);}));details.append(actions);
const attrs=el('div',undefined,'location-detail-attributes');for(const a of ['type','classification','quickAdd','detection'])attrs.append(field(groups.find(g=>g.id===a).label,attributeSelect(a,r)));const p=button(r.parent?path(r.id,false):'Root level',()=>parentDialog('Change parent',id=>void assign('parent',id,[r.id]),false,[r.id]));p.disabled=!canEdit;attrs.append(field('Parent',p));details.append(attrs);
@ -82,17 +86,18 @@
const related=el('section');related.dataset.related='';related.append(el('h3','Connections'));for(const [label,items,route]of [['Maps',r.maps,'Maps'],['Floor plans',r.floors,'FloorPlans']]){related.append(el('h4',`${label} · ${items.length}`,'small'));for(const link of items){const a=el('a',link.name);a.href=route==='Maps'?`/Maps?projectId=${project}&id=${link.id}`:`/FloorPlans/Edit/${link.id}`;related.append(a);}}const a=el('a',`${r.scenes} recorded scene appearance(s) · relationships and characters`);a.href=`/Locations/Details/${r.id}`;related.append(a,el('p',`${r.relationships||0} relationships · ${r.characters||0} explicitly located characters · ${r.assets||0} assets currently here`,'small muted'));details.append(related);if(heldFocus?.isConnected)heldFocus.focus({preventScroll:true});
}
function commands(id){const r=records.get(id);if(!r)return null;const ids=scope(id),bulk=ids.length>1,commands=[{label:bulk?`${ids.length} locations selected`:r.name,icon:'locations',disabled:true}];if(!bulk)commands.push({label:'View Location Details',icon:'details',run:()=>location.assign(`/Locations/Details/${id}`)},{label:'Edit Location',icon:'writer',run:()=>location.assign(`/Locations/Edit/${id}`)});
if(canEdit){commands.push({separator:true});if(!bulk)commands.push({label:'Rename',icon:'writer',run:()=>{if(!host.querySelector(`[data-location-id="${id}"]`))reveal(id);rename(id);}},{label:'Create child location',icon:'add',run:()=>createChild(id)});for(const g of groups.filter(g=>g.editable))commands.push({label:g.label,icon:g.values[0].icon,children:g.values.map(v=>({label:v.label,icon:v.icon,checked:ids.every(id=>value(records.get(id),g.id)===v.value),disabled:busy,run:()=>void assign(g.id,v.value,ids)}))});commands.push({label:'Change parent…',icon:'location-level',run:()=>parentDialog('Change parent',p=>void assign('parent',p,ids),false,ids)},{label:'Move to root',icon:'locations',disabled:busy,run:()=>void assign('parent','',ids)});if(!bulk){commands.push({separator:true},{label:'Merge with another location…',icon:'merge',run:()=>mergeDialog(id)});for(const [name,links,route]of [['Open associated map',r.maps,'Maps'],['Open associated floor plan',r.floors,'FloorPlans']])if(links.length)commands.push({label:name,icon:route==='Maps'?'maps':'floorplans',children:links.map(l=>({label:l.name,icon:route==='Maps'?'maps':'floorplans',run:()=>location.assign(route==='Maps'?`/Maps?projectId=${project}&id=${l.id}`:`/FloorPlans/Edit/${l.id}`)}))});commands.push({label:'Archive location',icon:'archive',destructive:true,run:()=>archive(id)});}}
if(canEdit){commands.push({separator:true});if(!bulk)commands.push({label:'Rename',icon:'writer',run:()=>{if(!host.querySelector(`[data-location-id="${id}"]`))reveal(id);rename(id);}},{label:'Create child location',icon:'add',run:()=>createChild(id)});for(const g of groups.filter(g=>g.editable))commands.push({label:g.label,icon:g.values[0].icon,children:attributeCommands(g,ids)});commands.push({label:'Change parent…',icon:'location-level',run:()=>parentDialog('Change parent',p=>void assign('parent',p,ids),false,ids)},{label:'Move to root',icon:'locations',disabled:busy,run:()=>void assign('parent','',ids)});if(!bulk){commands.push({separator:true},{label:'Merge with another location…',icon:'merge',run:()=>mergeDialog(id)});for(const [name,links,route]of [['Open associated map',r.maps,'Maps'],['Open associated floor plan',r.floors,'FloorPlans']])if(links.length)commands.push({label:name,icon:route==='Maps'?'maps':'floorplans',children:links.map(l=>({label:l.name,icon:route==='Maps'?'maps':'floorplans',run:()=>location.assign(route==='Maps'?`/Maps?projectId=${project}&id=${l.id}`:`/FloorPlans/Edit/${l.id}`)}))});commands.push({label:'Archive location',icon:'archive',destructive:true,run:()=>archive(id)});}}
return {commands,invoker:host.querySelector(`[data-location-id="${id}"]`)||$('[data-selection-menu]')};
}
function mergeDialog(id){if(!leaveDraft())return;descriptionDraft=null;renderDetails();const source=records.get(id),body=el('div'),select=el('select');select.className='form-select';select.setAttribute('aria-label','Surviving location');select.add(new Option('Choose the surviving location',''));for(const r of records.values())if(r.id!==id&&!ancestors(r.id).includes(id))select.add(new Option(path(r.id),String(r.id)));const review=el('div'),confirm=el('input');confirm.type='checkbox';const label=el('label');label.append(confirm,document.createTextNode(' I have reviewed the consequences. Archive the source and retain the selected location.'));body.append(el('p',`Merge ${source.name} into:`),select,review,label);select.addEventListener('change',()=>{confirm.checked=false;review.replaceChildren();const target=records.get(Number(select.value));if(!target)return;review.append(el('p',`Source: ${path(source.id)}. ${children.get(source.id)?.length||0} immediate children, ${source.scenes} recorded scene appearances, ${source.maps.length} maps and ${source.floors.length} floor plans. Survivor: ${path(target.id)}.`),el('p',`The survivor keeps its name, type and parent (${path(target.id,false)||'root'}). Its classification is retained; an unclassified survivor inherits the source classification. All child locations, recorded scene references, aliases, relationships, maps and floor plan links transfer. Direct source/survivor relationships are archived. The source is archived; its original details and geography evidence remain available there. This merge cannot be undone here.`),el('p',`Type: ${source.typeName||'Unclassified'} → ${target.typeName||'Unclassified'}. Classification: ${source.classification||'Unclassified'} → ${target.classification||'Unclassified'}.`),el('h3','Survivor description'),el('p',target.description||'None','locations-description'),el('h3','Source description'),el('p',source.description||'None','locations-description'),el('p','Different descriptions are preserved together on the survivor, labelled with the source name. Geography confirmation is not transferred automatically.'));});openDialog('Review location merge',body,async()=>{if(!select.value||!confirm.checked)throw Error('Choose a survivor and confirm the reviewed consequences.');const target=records.get(Number(select.value));await post('Merge',{projectId:project,sourceId:id,targetId:target.id,sourceVersion:source.version,targetVersion:target.version,confirm:true});active=target.id;undo=null;$('[data-undo]').hidden=true;selected.clear();readEpoch++;if(refreshing)await refreshing;await refresh();toast?.success('Locations merged. The source is archived.');});}
function attributeCommands(g,ids){const action=v=>({label:v.label,icon:v.icon,tone:v.tone,checked:ids.every(id=>value(records.get(id),g.id)===v.value),disabled:busy,run:()=>void assign(g.id,v.value,ids)});if(g.id!=='type')return g.values.map(action);const build=parent=>taxonomy.filter(v=>(v.parentKey||null)===parent).map(v=>{const children=build(v.key);if(!children.length)return v.assignable===false?{label:v.label,icon:v.icon,disabled:true}:action(v);return{label:v.label,icon:v.icon,tone:v.tone,children:[...(v.assignable!==false?[{...action(v),label:`Assign ${v.label}`},{separator:true}]:[]),...children]};});return build(null);}
function mergeDialog(id){if(!leaveDraft())return;descriptionDraft=null;renderDetails();const source=records.get(id),body=el('div'),pickerHost=el('div');let selectedTarget;const review=el('div'),confirm=el('input');confirm.type='checkbox';const label=el('label');label.append(confirm,document.createTextNode(' I have reviewed the consequences. Archive the source and retain the selected location.'));body.append(el('p',`Merge ${source.name} into:`),pickerHost,review,label);const picker=window.PlotDirectorLocationPicker.mount(pickerHost,{locations:[...records.values()],types,excludeBranches:[id],onChange:chosen=>{selectedTarget=chosen;confirm.checked=false;review.replaceChildren();const target=records.get(Number(selectedTarget));if(!target)return;review.append(el('p',`Source: ${path(source.id)}. ${children.get(source.id)?.length||0} immediate children, ${source.scenes} recorded scene appearances, ${source.maps.length} maps and ${source.floors.length} floor plans. Survivor: ${path(target.id)}.`),el('p',`The survivor keeps its name, type and parent (${path(target.id,false)||'root'}). Its classification is retained; an unclassified survivor inherits the source classification. All child locations, recorded scene references, aliases, relationships, maps and floor plan links transfer. Direct source/survivor relationships are archived. The source is archived; its original details and geography evidence remain available there. This merge cannot be undone here.`),el('p',`Type: ${source.typeName||'Unclassified'} → ${target.typeName||'Unclassified'}. Classification: ${source.classification||'Unclassified'} → ${target.classification||'Unclassified'}.`),el('h3','Survivor description'),el('p',target.description||'None','locations-description'),el('h3','Source description'),el('p',source.description||'None','locations-description'),el('p','Different descriptions are preserved together on the survivor, labelled with the source name. Geography confirmation is not transferred automatically.'));}});openDialog('Review location merge',body,async()=>{if(!selectedTarget||!confirm.checked)throw Error('Choose a survivor and confirm the reviewed consequences.');const target=records.get(Number(selectedTarget));await post('Merge',{projectId:project,sourceId:id,targetId:target.id,sourceVersion:source.version,targetVersion:target.version,confirm:true});active=target.id;undo=null;$('[data-undo]').hidden=true;selected.clear();readEpoch++;if(refreshing)await refreshing;await refresh();toast?.success('Locations merged. The source is archived.');});}
function archive(id){if(!leaveDraft()||!confirm('Archive this location? Its data and references are retained. Restore it later from Archived Items.'))return;const form=el('form');form.method='post';form.action='/Locations/Archive';for(const [name,value]of [['id',id],['projectId',project],['__RequestVerificationToken',$('[name=__RequestVerificationToken]').value]]){const n=el('input');n.type='hidden';n.name=name;n.value=value;form.append(n);}root.append(form);form.submit();}
window.PlotDirectorContextMenus?.register('[data-locations-workspace] [data-location-id]',target=>{if(target.closest('input,textarea,select')||window.getSelection()?.toString())return null;return commands(Number(target.closest('[data-location-id]').dataset.locationId));});
const selectionMenu=$('[data-selection-menu]');selectionMenu.dataset.pdContext='location-selection';selectionMenu.dataset.pdContextLabel='Selected locations';selectionMenu.dataset.pdContextWeb='';window.PlotDirectorContextMenus?.register('[data-locations-workspace] [data-selection-menu]',()=>{const id=selected.values().next().value;const result=id?commands(id):null;if(result)result.invoker=selectionMenu;return result;});selectionMenu.addEventListener('click',()=>window.PlotDirectorContextMenus?.open(selectionMenu));
function validParent(ids,parent){return !ids.some(id=>id===parent||ancestors(parent).includes(id));}
root.addEventListener('dragover',e=>{if(!drag||!canEdit||busy)return;const attr=e.target.closest('[data-attribute]'),row=e.target.closest('[data-location-id]'),rootDrop=e.target.closest('[data-root-drop]');let target=null,valid=false;if(drag.attribute&&row){target=row;valid=true;}else if(drag.ids&&attr){target=attr;valid=groups.find(g=>g.id===attr.dataset.attribute)?.editable;}else if(drag.ids&&(row||rootDrop)){target=row||rootDrop;valid=validParent(drag.ids,row?Number(row.dataset.locationId):null);}
root.addEventListener('dragover',e=>{if(!drag||!canEdit||busy)return;const attr=e.target.closest('[data-attribute]'),row=e.target.closest('[data-location-id]'),rootDrop=e.target.closest('[data-root-drop]');let target=null,valid=false;if(drag.attribute&&row){target=row;valid=true;}else if(drag.ids&&attr){target=attr;valid=attr.dataset.assignable==='true';}else if(drag.ids&&(row||rootDrop)){target=row||rootDrop;valid=validParent(drag.ids,row?Number(row.dataset.locationId):null);}
root.querySelectorAll('.is-drop-target,.is-invalid-target').forEach(n=>n.classList.remove('is-drop-target','is-invalid-target'));if(!target)return;target.classList.add(valid?'is-drop-target':'is-invalid-target');if(valid){e.preventDefault();e.dataTransfer.dropEffect=drag.attribute?'copy':'move';}const id=row?Number(row.dataset.locationId):null;if(valid&&drag.ids&&id&&hoverId!==id){clearTimeout(hoverTimer);hoverId=id;hoverTimer=setTimeout(()=>{if(drag&&children.get(id)?.length&&!expanded.has(id)){expanded.add(id);render();}},650);}else if(!row){clearTimeout(hoverTimer);hoverId=null;}});
root.addEventListener('drop',e=>{if(!drag)return;e.preventDefault();e.stopPropagation();const attr=e.target.closest('[data-attribute]'),row=e.target.closest('[data-location-id]'),rootDrop=e.target.closest('[data-root-drop]');if(drag.attribute&&row)void assign(drag.attribute,drag.value,scope(Number(row.dataset.locationId)));else if(drag.ids&&attr&&groups.find(g=>g.id===attr.dataset.attribute)?.editable)void assign(attr.dataset.attribute,attr.dataset.value,drag.ids);else if(drag.ids&&(row||rootDrop)){const parent=row?Number(row.dataset.locationId):null;if(validParent(drag.ids,parent)){if(parent)expanded.add(parent);savePrefs();void assign('parent',parent?.toString()||'',drag.ids);}else toast?.error('Choose a parent outside the selected branches.');}endDrag();});
root.addEventListener('drop',e=>{if(!drag)return;e.preventDefault();e.stopPropagation();const attr=e.target.closest('[data-attribute]'),row=e.target.closest('[data-location-id]'),rootDrop=e.target.closest('[data-root-drop]');if(drag.attribute&&row)void assign(drag.attribute,drag.value,scope(Number(row.dataset.locationId)));else if(drag.ids&&attr&&attr.dataset.assignable==='true')void assign(attr.dataset.attribute,attr.dataset.value,drag.ids);else if(drag.ids&&(row||rootDrop)){const parent=row?Number(row.dataset.locationId):null;if(validParent(drag.ids,parent)){if(parent)expanded.add(parent);savePrefs();void assign('parent',parent?.toString()||'',drag.ids);}else toast?.error('Choose a parent outside the selected branches.');}endDrag();});
function endDrag(){drag=null;clearTimeout(hoverTimer);hoverId=null;root.querySelectorAll('.is-drop-target,.is-invalid-target').forEach(n=>n.classList.remove('is-drop-target','is-invalid-target'));}root.addEventListener('dragend',endDrag);
$('[data-new-child]').addEventListener('click',()=>createChild(active));$('[data-change-parent]').addEventListener('click',()=>parentDialog('Change parent',p=>void assign('parent',p,selected.size?[...selected]:[active]),false,selected.size?[...selected]:[active]));$('[data-create-relationship]').addEventListener('click',()=>{if(active&&leaveDraft())location.assign(`/Locations/Details/${active}#location-relationships`);});
$('[data-search]').addEventListener('input',e=>{query=e.target.value.trim().toLocaleLowerCase();render();});$('[data-clear-search]').addEventListener('click',()=>{$('[data-search]').value='';query='';render();});$('[data-clear-filters]').addEventListener('click',()=>{filters.clear();render();});$('[data-sort]').value=prefs.sort;$('[data-sort]').addEventListener('change',e=>{prefs.sort=e.target.value;savePrefs();render();});