From eebbf3b6fb8586c6f728a6771a28f5bbb3851a1d Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 27 Nov 2026 13:22:54 +0000 Subject: [PATCH] Preserve location mutation versions and unsaved description state --- .../Browser/locations-workspace.cjs | 2 +- PlotLine.Tests/Sql/LocationsWorkspace.sql | 28 ++++++++- .../337_LocationMutationVersionIntegrity.sql | 61 +++++++++++++++++++ PlotLine/wwwroot/js/locations-workspace.js | 6 +- 4 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 PlotLine/Sql/337_LocationMutationVersionIntegrity.sql diff --git a/PlotLine.Tests/Browser/locations-workspace.cjs b/PlotLine.Tests/Browser/locations-workspace.cjs index 88cf4d1c..f357ce46 100644 --- a/PlotLine.Tests/Browser/locations-workspace.cjs +++ b/PlotLine.Tests/Browser/locations-workspace.cjs @@ -31,7 +31,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.');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('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.'); 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){ diff --git a/PlotLine.Tests/Sql/LocationsWorkspace.sql b/PlotLine.Tests/Sql/LocationsWorkspace.sql index fea1d93e..20cc9ac5 100644 --- a/PlotLine.Tests/Sql/LocationsWorkspace.sql +++ b/PlotLine.Tests/Sql/LocationsWorkspace.sql @@ -43,6 +43,16 @@ EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes; SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),CASE WHEN LocationID=@b THEN @a ELSE @d END) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@b,@leaf) FOR JSON PATH); EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes,1; IF (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@b)<>@a OR (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@leaf)<>@d OR (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@c)<>@b THROW 51000,'Bulk parent undo did not restore each original branch.',1; +DECLARE @future datetime2=DATEADD(SECOND,5,SYSUTCDATETIME()); +UPDATE dbo.Locations SET UpdatedDate=@future WHERE LocationID=@a; +SELECT @changes=(SELECT LocationID AS Id,N'1' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'quickAdd',@changes; +IF (SELECT UpdatedDate FROM dbo.Locations WHERE LocationID=@a)<=@future THROW 51000,'Location version did not advance monotonically.',1; +SELECT @changes=(SELECT LocationID AS Id,N'Exact prose ' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'description',@changes; +SELECT @changes=(SELECT LocationID AS Id,N'Exact prose ' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH); +EXEC dbo.Location_WorkspaceAssign @p,@u,N'description',@changes; +IF (SELECT DATALENGTH(Description) FROM dbo.Locations WHERE LocationID=@a)<>DATALENGTH(N'Exact prose ') THROW 51000,'Trailing-space description edit was not preserved.',1; ROLLBACK; PRINT 'PASS bulk branch preservation, root moves, classification, targeted rename, exact undo'; -- Expected failures roll back the complete transaction, including their fixtures. @@ -95,6 +105,7 @@ INSERT dbo.StoryMaps(ProjectID,Name,Kind) VALUES(@p,N'Workspace merge map',N'Loc INSERT dbo.MapFeatures(MapID,FeatureID,Name,Type,GeometryClass,Layer,X,Y,Width,Height,Rotation,ZOrder,IsPlaced,IsProvisional,IsLocked,ShowLabel,LabelX,LabelY,LocationID,GeometryJson) VALUES(@map,@feature,N'Preserved marker',N'Location',N'Marker',N'Places',10,20,5,5,0,0,1,0,0,1,0,0,@a,N'{"fixture":"unchanged"}'); INSERT dbo.FloorPlans(ProjectID,Name,LocationID) VALUES(@p,N'Workspace merge floor plan',@a);SET @plan=SCOPE_IDENTITY(); +DECLARE @childBefore datetime2=(SELECT UpdatedDate FROM dbo.Locations WHERE LocationID=@c); SELECT @old=UpdatedDate FROM dbo.Locations WHERE LocationID=@a;SELECT @updated=UpdatedDate FROM dbo.Locations WHERE LocationID=@b; EXEC dbo.Location_WorkspaceMerge @p,@u,@a,@b,@old,@updated; IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@a AND IsArchived=1 AND Description=N'Source prose') THROW 51000,'Merge source not preserved.',1; @@ -106,7 +117,12 @@ IF NOT EXISTS(SELECT 1 FROM dbo.LocationRelationships WHERE LocationRelationship IF NOT EXISTS(SELECT 1 FROM dbo.LocationAliases WHERE LocationID=@b AND Alias=N'Former source name') THROW 51000,'Merge lost aliases.',1; IF NOT EXISTS(SELECT 1 FROM dbo.MapFeatures WHERE MapID=@map AND FeatureID=@feature AND LocationID=@b AND X=10 AND Y=20 AND GeometryJson=N'{"fixture":"unchanged"}') THROW 51000,'Merge changed map identity/geometry or lost its association.',1; IF (SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map)<>1 OR (SELECT LocationID FROM dbo.FloorPlans WHERE FloorPlanID=@plan)<>@b THROW 51000,'Map revision/floor-plan association not preserved.',1; -ROLLBACK; +IF (SELECT UpdatedDate FROM dbo.Locations WHERE LocationID=@c)<=@childBefore THROW 51000,'Merge did not invalidate child versions.',1; +SELECT @changes=(SELECT @c AS Id,N'' AS Value,CONVERT(nvarchar(33),@childBefore,126) AS Version FOR JSON PATH); +BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes,1;THROW 51099,'Pre-merge child Undo was accepted.',1; +END TRY BEGIN CATCH IF ERROR_NUMBER()<>51011 THROW; END CATCH; +IF @@TRANCOUNT>0 ROLLBACK; +PRINT 'PASS merge invalidates pre-merge child Undo receipts'; PRINT 'PASS transactional merge preserves conflicting descriptions, source, classification, children, map geometry, floor-plan links, scene assignments, aliases and non-hierarchical relationships'; -- Traditional forms/import repository cannot bypass hierarchy validation either (336). BEGIN TRAN; @@ -133,3 +149,13 @@ EXEC dbo.Location_Save @LocationID=@b,@ProjectID=@p,@ParentLocationID=@a,@Locati IF @@TRANCOUNT<>1 OR NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@b AND ParentLocationID=@a AND Classification=N'Fictional' AND Description=N'Preserved historical containment') THROW 51000,'Traditional save changed historical parent/classification or escaped the outer transaction.',1; ROLLBACK; PRINT 'PASS traditional save preserves unchanged archived-parent references, classification and import transaction'; + +BEGIN TRAN; +INSERT dbo.Locations(ProjectID,LocationName,Description) VALUES(@p,N'Case source',N'CASE prose ');SET @a=SCOPE_IDENTITY(); +INSERT dbo.Locations(ProjectID,LocationName,Description) VALUES(@p,N'Case survivor',N'case prose ');SET @b=SCOPE_IDENTITY(); +SELECT @old=UpdatedDate FROM dbo.Locations WHERE LocationID=@a;SELECT @updated=UpdatedDate FROM dbo.Locations WHERE LocationID=@b; +EXEC dbo.Location_WorkspaceMerge @p,@u,@a,@b,@old,@updated; +DECLARE @expected nvarchar(max)=N'case prose '+NCHAR(13)+NCHAR(10)+NCHAR(13)+NCHAR(10)+N'Preserved from Case source:'+NCHAR(13)+NCHAR(10)+N'CASE prose '; +IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@b AND Description COLLATE Latin1_General_100_BIN2=@expected COLLATE Latin1_General_100_BIN2 AND DATALENGTH(Description)=DATALENGTH(@expected)) THROW 51000,'Merge discarded case/whitespace description differences.',1; +ROLLBACK; +PRINT 'PASS merge preserves case-only and trailing-space prose differences'; diff --git a/PlotLine/Sql/337_LocationMutationVersionIntegrity.sql b/PlotLine/Sql/337_LocationMutationVersionIntegrity.sql new file mode 100644 index 00000000..85a38ac9 --- /dev/null +++ b/PlotLine/Sql/337_LocationMutationVersionIntegrity.sql @@ -0,0 +1,61 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +-- All location writers must advance the existing optimistic-concurrency timestamp, +-- including children moved by a merge. No new version field or existing data rewrite. +SET XACT_ABORT ON; +BEGIN TRY +BEGIN TRANSACTION; +DECLARE @merge nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Location_Merge')); +IF @merge NOT LIKE N'%LocationsMergeVersions337%' +BEGIN + IF CHARINDEX(N'UPDATE dbo.Locations SET ParentLocationID = @TargetID WHERE ParentLocationID = @SourceID;',@merge)=0 + THROW 51012,'Review the location merge child-update contract.',1; + SET @merge=REPLACE(@merge,N'UPDATE dbo.Locations SET ParentLocationID = @TargetID WHERE ParentLocationID = @SourceID;', + N'UPDATE dbo.Locations SET ParentLocationID = @TargetID,UpdatedDate=@Now,ModifiedDateUTC=@Now,ModifiedByUserID=@UserID WHERE ParentLocationID = @SourceID;'); + SET @merge=REPLACE(@merge,N'@SourceDescription=@TargetDescription', + N'(@SourceDescription COLLATE Latin1_General_100_BIN2=@TargetDescription COLLATE Latin1_General_100_BIN2 AND DATALENGTH(@SourceDescription)=DATALENGTH(@TargetDescription))'); + SET @merge=REPLACE(@merge,N'UpdatedDate=@Now',N'UpdatedDate=CASE WHEN @Now<=UpdatedDate THEN DATEADD(NANOSECOND,100,UpdatedDate) ELSE @Now END'); + SET @merge=REPLACE(@merge,N'UpdatedDate = @Now',N'UpdatedDate = CASE WHEN @Now<=UpdatedDate THEN DATEADD(NANOSECOND,100,UpdatedDate) ELSE @Now END'); + SET @merge=STUFF(@merge,1,CHARINDEX(N'PROCEDURE',@merge)-1,N'CREATE OR ALTER ')+NCHAR(10)+N'-- LocationsMergeVersions337'; + EXEC sys.sp_executesql @merge; +END; +DECLARE @name sysname,@reference nvarchar(100),@definition nvarchar(max),@replacement nvarchar(500); +DECLARE writers CURSOR LOCAL FAST_FORWARD FOR SELECT Name,Reference FROM(VALUES + (N'Location_WorkspaceAssign',N'l.UpdatedDate'),(N'Location_Save',N'UpdatedDate'), + (N'Location_Reparent',N'UpdatedDate'),(N'Location_SetPreferredName',N'UpdatedDate'))v(Name,Reference); +OPEN writers;FETCH NEXT FROM writers INTO @name,@reference; +WHILE @@FETCH_STATUS=0 +BEGIN + SET @definition=OBJECT_DEFINITION(OBJECT_ID(N'dbo.'+@name)); + IF @definition IS NULL THROW 51012,'A required location writer is unavailable.',1; + IF @definition NOT LIKE N'%LocationsWriterVersion337%' + BEGIN + IF @definition NOT LIKE N'%UpdatedDate%SYSUTCDATETIME()%' AND @definition NOT LIKE N'%UpdatedDate%@Now%' + THROW 51012,'Review the location writer version contract.',1; + SET @replacement=N'UpdatedDate=CASE WHEN SYSUTCDATETIME()<='+@reference+N' THEN DATEADD(NANOSECOND,100,'+@reference+N') ELSE SYSUTCDATETIME() END'; + SET @definition=REPLACE(@definition,N'UpdatedDate=SYSUTCDATETIME()',@replacement); + SET @definition=REPLACE(@definition,N'UpdatedDate = SYSUTCDATETIME()',@replacement); + SET @replacement=N'UpdatedDate=CASE WHEN @Now<='+@reference+N' THEN DATEADD(NANOSECOND,100,'+@reference+N') ELSE @Now END'; + SET @definition=REPLACE(@definition,N'UpdatedDate=@Now',@replacement); + SET @definition=REPLACE(@definition,N'UpdatedDate = @Now',@replacement); + IF @name=N'Location_WorkspaceAssign' + BEGIN + IF CHARINDEX(N'END) COLLATE Latin1_General_100_BIN2;',@definition)=0 THROW 51012,'Review the location assignment text comparison.',1; + SET @definition=REPLACE(@definition,N'END) COLLATE Latin1_General_100_BIN2;', + N'END) COLLATE Latin1_General_100_BIN2 OR (@Attribute=N''description'' AND DATALENGTH(i.Value)<>DATALENGTH(ISNULL(l.Description,N'''')));'); + END; + SET @definition=STUFF(@definition,1,CHARINDEX(N'PROCEDURE',@definition)-1,N'CREATE OR ALTER ')+NCHAR(10)+N'-- LocationsWriterVersion337'; + EXEC sys.sp_executesql @definition; + END; + FETCH NEXT FROM writers INTO @name,@reference; +END; +CLOSE writers;DEALLOCATE writers; +COMMIT; +END TRY +BEGIN CATCH + IF XACT_STATE()<>0 ROLLBACK; + THROW; +END CATCH; +GO diff --git a/PlotLine/wwwroot/js/locations-workspace.js b/PlotLine/wwwroot/js/locations-workspace.js index 61a11ea3..1625943e 100644 --- a/PlotLine/wwwroot/js/locations-workspace.js +++ b/PlotLine/wwwroot/js/locations-workspace.js @@ -63,7 +63,7 @@ row.addEventListener('dblclick',e=>{if(canEdit&&e.target.closest('[data-location-name]'))rename(r.id);});return row; } function focusRow(id){host.querySelector(`[data-location-id="${id}"]`)?.focus();} - function select(id){if(id!==active&&!leaveDraft())return;active=id;descriptionDraft=null;render();renderDetails();} + function select(id){if(id!==active){if(!leaveDraft())return;active=id;descriptionDraft=null;}render();renderDetails();} function reveal(id=active){if(!records.has(id))return;if(!leaveDraft())return;active=id;ancestors(id).forEach(a=>expanded.add(a));query='';$('[data-search]').value='';filters.clear();prefs.view='tree';savePrefs();render();renderDetails();focusRow(id);host.querySelector(`[data-location-id="${id}"]`)?.scrollIntoView({block:'nearest'});} function rename(id){if(!canEdit||busy)return;const row=host.querySelector(`[data-location-id="${id}"]`);if(!row)return;const r=records.get(id),label=row.querySelector('[data-location-name]'),input=el('input');input.className='form-control form-control-sm';input.value=r.name;input.maxLength=200;input.setAttribute('aria-label','Location name');label.replaceWith(input);input.focus();input.select();let saving=false;input.addEventListener('keydown',async e=>{if(e.key==='Escape'){e.preventDefault();render();focusRow(id);}if(e.key==='Enter'&&!saving){e.preventDefault();saving=true;input.disabled=true;if(await assign('name',input.value,[id]))focusRow(id);else{input.disabled=false;input.focus();saving=false;}}});} function openDialog(title,body,save){dialog.querySelector('[data-dialog-title]').textContent=title;dialog.querySelector('[data-dialog-body]').replaceChildren(body);dialog.querySelector('[data-dialog-error]').textContent='';dialogSave=save;dialog.showModal();setTimeout(()=>dialog.querySelector('input,select')?.focus(),0);} @@ -71,7 +71,7 @@ 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 createChild(parent){if(!canEdit||!leaveDraft())return;descriptionDraft=null;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 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 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;} @@ -85,7 +85,7 @@ 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)});}} return {commands,invoker:host.querySelector(`[data-location-id="${id}"]`)||$('[data-selection-menu]')}; } - function mergeDialog(id){if(!leaveDraft())return;descriptionDraft=null;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 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 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));