Add character attribute assignment workspace with bulk actions and safe undo

This commit is contained in:
Nick Beckley 2026-11-26 11:08:36 +00:00
parent 0c29af87e0
commit 59298af9a7
18 changed files with 495 additions and 10 deletions

View File

@ -0,0 +1,57 @@
# Main Characters attribute workspace
The directory retains its existing `CharacterCardLayout.ColumnSpan`, full `DefaultDescription`, portraits, names, details links, Edit links and Archive forms. There is no card-height or biography-length rule in this feature. Assignment never submits the Character Editor model.
## Canonical model audit
- Story importance: nullable integer `CharacterImportance`. The editor assigns Major 10, Supporting 6, Minor 2 and Unclassified NULL. Existing intermediate values are retained; display uses the existing workspace bands (8+, 4+, 1+, otherwise Unclassified). No import defaults change.
- Life status: nullable `IsDeceased`: false = Living, true = Deceased, NULL = Unrecorded. Independent of `IsArchived` and without inferred death date, scene or knowledge.
- Sex: `SexValueID` plus canonical text `Sex`, using active system values and the project owner's custom `CharacterSexValues`. Existing catalogue values are reusable. “Add new…” stays in the editor and follows its existing owner-scoped get/create workflow. Legacy text without an ID is displayed as recorded and can be restored exactly by Undo.
- Quick Add Bar: existing boolean `ShowInQuickAddBar` (Included / Excluded).
- Eye colour: `EyeColour` is free text; there is no reusable canonical catalogue. It remains in the editor to avoid creating a competing vocabulary. Height, birth date, age, biographies, preferred names and aliases remain editor fields.
- Other existing lookups (scene role/presence, relationship state, knowledge state) describe other records, not global character attributes; they are not directory assignments.
## Shared character attribute icon standard
`CharacterQuickAttributes.Definitions` supplies IDs, canonical values, labels, icon keys and semantic theme tones for the sidebar, indicators and context menus. SVG paths come from `ApplicationRibbon.Icon`; attribute-specific additions use the existing ribbon SVG vocabulary. The directory fetches the catalogue once per authenticated refresh, never per card.
| Attribute | Icon key | Theme tone |
| --- | --- | --- |
| Major | attribute-star | warning (gold intention) |
| Supporting | characters | info (blue intention) |
| Minor | attribute-person | secondary |
| Unclassified / unrecorded / not set | help | secondary |
| Living | attribute-heart | success |
| Deceased | attribute-flower | data-5 (existing purple theme palette) |
| Recorded sex | attribute-person | secondary |
| Quick Add included | attribute-pin | primary |
| Quick Add excluded | attribute-unpin | secondary |
All indicators have the full attribute/value in their tooltip and accessible name. Shapes, labels, menu checks and selection outlines supplement colour. Unrecorded life status is visibly unknown; no Living default is inferred. Legacy sex text is never represented as “Not set”. Additional discrete fields require one definition plus explicit focused persistence and validation; this is not a generic entity framework.
## Persistence, concurrency and Undo
Migration `323_CharacterQuickAttributes.sql` adds two procedures, without new data stores or changes to historical migrations:
- `Character_QuickAttributes_Read` returns only active, authorised character attribute snapshots, without biographies.
- `Character_QuickAttributes_Assign` accepts a project, acting user, attribute and a JSON selection. It locks and authorises every active character against the same active project and checks each exact `UpdatedDate`. Only Owner/Collaborator can write. A failure rolls back the complete selection. No-op rows do not change timestamps or produce invalidations. Only the selected column (and the canonical sex ID/text pair) changes; `UpdatedDate` records the update.
All drag, explicit Assign and menu interactions POST the same antiforgery-protected `/CharacterAttributes/Assign` endpoint. The returned snapshots update icons/counts/filter visibility without replacing cards, changing order or reloading the page. Stored snapshots are captured under the write locks and returned after commit.
The server returns a protected, author-bound, ten-minute Undo receipt containing each changed character's individual previous value and post-write timestamp. `/CharacterAttributes/Undo` verifies the receipt before using the same procedure. Restore also checks every current timestamp, so even an unrelated subsequent character edit conservatively prevents stale Undo. Legacy sex text and intermediate importance values can be restored exactly. A toast action captures its own receipt, rather than accidentally undoing a later operation. A persistent toolbar Undo button offers the same accessible operation.
## Interaction and integration
- The sidebar is sticky, with bounded internal scrolling and collapsible groups. Its expanded preference uses the existing user/project-scoped local UI preference convention; narrow layouts use a compact panel above the unchanged responsive grid.
- Filters combine across attributes. Counts respect other active attribute filters. Select displayed includes only visible cards; hidden selections are removed when filtering. Checkboxes, Ctrl/Cmd-click and Shift-click ranges support bulk assignment. Dragging uses a separate handle, leaving biography selection, details links and existing form buttons intact.
- The existing `PlotDirectorContextMenus` provider handles individual and selected scopes, nested submenus, viewport positioning, dismissal and keyboard navigation. This feature adds optional `checked` and `tone` command properties, and exposes `openAt`/`close` for component invocation. It does not add another menu framework or suppress context menus outside the existing shell policy. Ctrl-right-click and text selection retain existing shell/browser behavior. Open/Edit/Archive appear only for an individual; Archive submits its original confirmation-protected form.
- The shared toast service accepts an optional `{action:{label,run}}`; content remains plain text, with existing roles, bounds, timing and dismissal. There is no separate notification host.
- Successful writes emit one lightweight existing `ContextInvalidated` hint (`projectId`, `kind: characters`) through `ContextWorkspaceNotifications`. The directory reuses `PlotDirectorPresenceConnection`, with authenticated snapshot retrieval and no per-card connections. Existing Character Details and Context listeners continue their existing refresh behavior, including Held Context; no position/focus command is emitted.
## Verification
Build and executable harness must run serially. `CharacterQuickAttributesTests` checks catalogue/custom/unknown semantics, biography-free snapshots, protected Undo author/expiry/tamper rejection and endpoint boundaries. `PlotLine.Tests/Sql/CharacterQuickAttributes.sql` refuses non-qualification databases and exercises atomic persistence on disposable characters in a disposable database copy.
With `--toolbar-browser-host` running, `node PlotLine.Tests/Browser/character-attributes.cjs` renders the actual compiled Characters Razor view and production scripts with isolated HTTP state. It covers 10/100/500 cards and records performance/screenshot artifacts in `/tmp`. `xvfb-run -a node PlotLine.Tests/Browser/character-attributes.cjs --installed` installs and launches a real Chromium app, asserting standalone display mode; it is not a matchMedia simulation. Neither browser fixture mutates an author's manuscript.
Fixture HTTP responses do not substitute for authenticated Development persistence smoke checks or manifest-based schema deployment qualification. Delivery evidence must distinguish these checks explicitly.

View File

@ -9,6 +9,8 @@ PlotDirector.toast.warning('Word connection interrupted');
PlotDirector.toast.error('Unable to save changes');
```
An optional action uses `{ action: { label: 'Undo', run: () => undoOperation() } }` as the second argument. The button uses plain text, dismisses that toast before invoking the callback, and does not take focus when shown. The caller owns safe concurrency checks and error feedback; capture the specific operation rather than a mutable “latest action”.
Use success for completed user actions, info for meaningful background completion, warning for attention required, and error for unsuccessful operations. Routine successful background sync, paragraph changes and navigation should stay silent. Keep progress indicators, field validation, destructive confirmations, persistent connection state, and substantial recovery instructions in their existing workflow.
Success/info dismiss after six seconds. Warning/error remain until dismissed. An optional second argument `{ duration: 10000 }` overrides the duration; zero means manual dismissal. The returned function dismisses that toast. Hover/focus pauses auto dismissal; leaving restarts the duration. Close buttons work with the keyboard and Escape dismisses the focused toast. Notifications never take focus. Status/alert roles announce messages; labels convey categories without relying on colour.

View File

@ -0,0 +1,14 @@
{
"target": "Development on Atlas only",
"database": "PlotDirector_Development",
"starting_schema_sha256": "432931e506b7f02570952bc098b952fcc82228c9f1dbca0fef1619ff869763c7",
"resulting_schema_sha256": "e2c2475bd10b8139e1d91c6ea4da417acdad6f595b88cc350823ba939984f153",
"migration": "323_CharacterQuickAttributes.sql",
"requires": ["322_DeploymentRuntimeHealth"],
"prerequisites": ["dbo.Characters", "dbo.CharacterSexValues", "dbo.ProjectUserAccess", "dbo.Projects"],
"postconditions": ["dbo.Character_QuickAttributes_Assign", "dbo.Character_QuickAttributes_Read"],
"review": "Additive stored procedures only; no tables, default changes, existing character assignments, import work, analysis, or manuscript position changes. Authorised assignment writes only its selected attribute and UpdatedDate. Restore is exposed only through protected, author-bound, expiring Undo receipts. Bulk validation is atomic under locks.",
"qualification": "Verify a COPY_ONLY/CHECKSUM Development backup; qualify the complete immutable ledger plus migration 323 on two fresh disposable copies through DatabaseWorker. Require exact starting/resulting schema, unchanged original business-column fingerprints and integrity checks. Run isolated character fixture SQL regressions separately. Prepare and sign the exact committed application and qualification evidence using release.py, then use the fixed Development helper for validation and activation.",
"recovery": "Retain backup, receipts and disposable qualification evidence on failure. Do not modify numbered scripts or roll back SQL. Procedures are additive; a compatible application rollback must be another signed manifest release.",
"production_authorised": false
}

View File

@ -0,0 +1,44 @@
// Real compiled Razor + production shell/assets, with isolated in-memory HTTP fixtures.
const {chromium}=require('playwright');const os=require('node:os'),path=require('node:path');const assert=require('node:assert/strict');const fs=require('node:fs');
(async()=>{const installed=process.argv.includes('--installed'),profile=installed?fs.mkdtempSync(path.join(os.tmpdir(),'pd-attributes-pwa-')):null;
const persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}):null;
const browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null;
const manifestId='http://127.0.0.1:5238/Projects';
if(installed){await persistent.pages()[0].goto('http://127.0.0.1:5238/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:'http://127.0.0.1:5238/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:'http://127.0.0.1:5238/fixture?page=calendar-test'});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return page;}
const results=[];try{
for(const count of [10,100,500]){
const page=await newPage(),errors=[];console.log('ACCEPTANCE',installed?'installed':'browser',count);page.on('pageerror',e=>errors.push(e.message));
const groups=await (await page.request.get('http://127.0.0.1:5238/character-attribute-definitions-fixture')).json();
let clock=0,requests=[],undo=new Map(),records=Array.from({length:count},(_,i)=>({id:i+1,name:`Fixture character ${String(i+1).padStart(3,'0')}`,version:`v${clock++}`,values:{importance:(i+1)%3===0?'10':(i+1)%3===1?'6':'2',life:'',sex:'',quickAdd:'0'}}));
await page.route('**/CharacterAttributes/Directory?*',route=>route.fulfill({json:{canEdit:true,groups,characters:records}}));
await page.route('**/CharacterAttributes/Assign',async route=>{const input=route.request().postDataJSON();requests.push(input);assert(route.request().headers().requestverificationtoken);const previous=[],changed=[];for(const c of input.changes){const r=records.find(r=>r.id===c.id);if(r.version!==c.version)return route.fulfill({status:409,json:{message:'Characters changed in another window.'}});if(r.values[input.attribute]!==c.value){previous.push(structuredClone(r));r.values[input.attribute]=c.value;r.version=`v${clock++}`;changed.push(r);}}const token=`undo-${clock}`;undo.set(token,{previous,versions:changed.map(r=>[r.id,r.version])});await route.fulfill({json:{saved:true,characters:changed,undoToken:token}});});
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}});});
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;
const card=id=>page.locator(`.character-card[data-drag-id="${id}"]`),value=(a,v)=>page.locator(`[data-attribute="${a}"][data-value="${v}"]`);
assert.equal(await page.locator('.character-card').count(),count);const biography=await card(1).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=>n.getBoundingClientRect().height));assert(new Set(heights.map(Math.round)).size>1);
await value('importance','10').locator('button').first().dragTo(card(1));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [data-attribute-indicators]').textContent===''&&document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Major"]'));assert.equal(records[0].values.importance,'10');
await card(2).locator('[data-character-drag]').dragTo(value('importance','6'));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Supporting"]'));assert.equal(records[1].values.importance,'6');
await card(1).locator('[data-character-select]').check();await card(2).locator('[data-character-select]').check();await value('importance','2').getByRole('button',{name:/Assign/}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Minor"]'));assert.equal(requests.at(-1).changes.length,2);
await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="1"] [title="Story importance: Major"]'));assert.equal(records[1].values.importance,'6');
await card(1).locator('[data-character-drag]').dragTo(value('importance','2'));await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Minor"]'));assert.equal(requests.at(-1).changes.length,2);await page.locator('[data-undo]').click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Story importance: Supporting"]'));
await card(1).scrollIntoViewIfNeeded();await page.waitForTimeout(400);await card(1).click({button:'right'});await page.getByRole('menuitem',{name:'2 characters selected',exact:true}).waitFor();await page.getByRole('menuitem',{name:'Life status',exact:true}).hover();await page.getByRole('menuitemradio',{name:'Living',exact:true}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="2"] [title="Life status: Living"]'));assert.equal(requests.at(-1).changes.length,2);
await page.locator('[data-clear-selection]').click();
// Modifier selection follows displayed order and does not navigate character links.
await card(1).locator('h2 a').click({modifiers:['Control']});await card(3).locator('h2 a').click({modifiers:['Shift']});assert.equal(await page.locator('[data-character-select]:checked').count(),3);assert(page.url().includes('character-attributes-fixture'));
await card(4).scrollIntoViewIfNeeded();await page.waitForTimeout(400);await card(4).click({button:'right'});assert.equal(await page.getByRole('menuitem',{name:'Open character',exact:true}).count(),1);await page.keyboard.press('Escape');
await card(1).scrollIntoViewIfNeeded();await page.waitForTimeout(400);await card(1).click({button:'right'});await page.getByRole('menuitem',{name:'Story importance · Mixed values',exact:true}).hover();assert.equal(await page.getByRole('menuitemradio',{checked:true}).count(),0);await page.keyboard.press('Escape');
await page.locator('[data-clear-selection]').click();await card(3).focus();await page.waitForTimeout(400);await page.keyboard.press('Shift+F10');await page.getByRole('menuitem',{name:'Story importance',exact:true}).focus();await page.keyboard.press('ArrowRight');await page.getByRole('menuitemradio',{name:'Major',exact:true}).waitFor();assert.equal(await page.getByRole('menuitemradio',{name:'Major',exact:true}).getAttribute('aria-checked'),'true');await page.keyboard.press('Escape');assert.equal(await page.locator('.pd-context-popup').count(),0);
await card(4).evaluate(n=>n.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:innerWidth-2,clientY:innerHeight-2})));await page.getByRole('menuitem',{name:'Quick Add Bar',exact:true}).hover();const menus=await page.locator('.pd-context-popup').evaluateAll(ns=>ns.map(n=>{const r=n.getBoundingClientRect();return {x:r.x,y:r.y,right:r.right,bottom:r.bottom}}));assert(menus.every(r=>r.x>=0&&r.y>=0&&r.right<=1440&&r.bottom<=1000));await page.getByRole('menuitemradio',{name:'Included',exact:true}).click();await page.waitForFunction(()=>document.querySelector('.character-card[data-drag-id="4"] [title="Quick Add Bar: Included"]'));assert.equal(requests.at(-1).changes.length,1);
const beforeCancel=requests.length;await page.evaluate(()=>{const b=document.querySelector('[data-attribute="importance"][data-value="10"] button'),transfer=new DataTransfer();b.dispatchEvent(new DragEvent('dragstart',{bubbles:true,dataTransfer:transfer}));document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}));document.dispatchEvent(new DragEvent('dragend',{bubbles:true,dataTransfer:transfer}));});assert.equal(requests.length,beforeCancel);await page.waitForTimeout(260);
await value('importance','10').locator('button').first().click();assert(await card(2).isHidden());await page.locator('[data-select-visible]').click();const visibleCount=await page.locator('.character-card:visible').count();assert.equal(await page.locator('[data-character-select]:checked').count(),visibleCount);await page.locator('[data-clear-filter]').click();await page.locator('[data-clear-selection]').click();
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()));
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';},theme);if(count===100)await page.screenshot({path:`/tmp/character-attributes-${installed?'installed-':''}${theme}.png`});}
for(const width of [1920,1366,1024,768,390]){await page.setViewportSize({width,height:1000});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}
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();
}
fs.writeFileSync(`/tmp/character-attributes-${installed?'installed-':''}performance.json`,JSON.stringify(results,null,2));console.log('PASS rendered directory: biography/card dimensions, bidirectional drag, bulk, individual prior-value Undo, individual/multi context, keyboard, filters/counts/selection scope, sticky/collapse, themes and responsive widths',results);
}finally{if(installed){await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await persistent.close();fs.rmSync(profile,{recursive:true,force:true});}else await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -0,0 +1,27 @@
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Controllers;
using PlotLine.Models;
using PlotLine.Services;
internal static class CharacterQuickAttributesTests
{
public static async Task Run()
{
void Check(bool value,string label){if(!value)throw new Exception(label);Console.WriteLine("PASS character quick attributes: "+label);}
var definitions=CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=17,SexName="Recorded custom value"}]);
Check(definitions.Single(g=>g.Id=="sex").Values.Any(v=>v.Value=="17"&&v.Label=="Recorded custom value"),"custom catalogue values remain available without binary assumptions");
var snapshot=JsonSerializer.Serialize(CharacterQuickAttributes.Snapshot(new(){CharacterID=5,IsDeceased=null,Sex="Legacy custom sex",DefaultDescription="Private complete biography"}));
Check(!snapshot.Contains("Private complete biography")&&snapshot.Contains("legacy:Legacy custom sex")&&snapshot.Contains("\"life\":\"\""),"live snapshots preserve unknown/legacy states and omit biographies");
var user=NativeWorkflowTests.Proxy<ICurrentUserService>((name,a)=>name=="get_UserId"?23:throw new Exception(name));
var protection=new EphemeralDataProtectionProvider();
var controller=new CharacterAttributesController(null!,null!,null!,user,null!,null!,protection);
var receipt=new CharacterAttributesController.UndoReceipt(24,7,"importance",[],DateTime.UtcNow.AddMinutes(10));
string Protect(CharacterAttributesController.UndoReceipt r)=>protection.CreateProtector("CharacterQuickAttributes.Undo.v1").Protect(JsonSerializer.Serialize(r));
Check(await controller.Undo(new(Protect(receipt))) is BadRequestObjectResult,"Undo receipt cannot be used by another author");
Check(await controller.Undo(new(Protect(receipt with{User=23,Expires=DateTime.UtcNow.AddSeconds(-1)}))) is BadRequestObjectResult,"expired Undo is rejected before persistence");
Check(await controller.Undo(new(Protect(receipt)+"tampered")) is BadRequestObjectResult,"modified Undo receipt is rejected before persistence");
Check(await controller.Assign(new(7,"biography",[new(5,"rewrite",DateTime.UtcNow.ToString("O"))])) is BadRequestObjectResult,"precision/free-text fields cannot enter the quick-assignment endpoint");
Check(await controller.Assign(new(7,"life",[new(5,"1",DateTime.UtcNow.ToString("O")),new(5,"0",DateTime.UtcNow.ToString("O"))])) is BadRequestObjectResult,"duplicate IDs cannot widen or repeat a bulk assignment");
}
}

View File

@ -200,6 +200,7 @@ if(args.Contains("--focus-diagnostics")){SharedFocusDiagnosticsTests.Run();retur
var tests = new (string Name, Action Test)[]
{
("Deployment health is loopback-only, database-backed and fails closed",DeploymentOperationsTests.Run),
("Character quick attributes and protected Undo", () => CharacterQuickAttributesTests.Run().GetAwaiter().GetResult()),
("Main Character workspace lazy reads and safe management",()=>CharacterWorkspaceTests.Run().GetAwaiter().GetResult()),
("Scene family identification and branch exploration",ContextFamilyTests.Run),
("Context Family/Story projection and bounded reads",()=>ContextRelationshipLensTests.Run().GetAwaiter().GetResult()),

View File

@ -0,0 +1,54 @@
-- Run ONLY on a disposable qualification copy with migration 323 installed.
IF DB_NAME() NOT LIKE N'PlotDirector_Qualification[_]%' THROW 51000,'Disposable qualification database required',1;
SET NOCOUNT ON;
DECLARE @project int=(SELECT TOP(1) a.ProjectID FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.AccessRole=N'Owner' AND a.IsActive=1 AND p.IsArchived=0 ORDER BY a.ProjectID);
DECLARE @user int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@project AND AccessRole=N'Owner' AND IsActive=1);
IF @project IS NULL THROW 51000,'Qualification owner required',1;
INSERT dbo.Characters(ProjectID,CharacterName,DefaultDescription,CharacterImportance,Sex,EyeColour) VALUES(@project,N'Quick assignment fixture A',N'Entire biography retained exactly',10,N'Legacy recorded custom value',N'Existing eye value');
DECLARE @a int=SCOPE_IDENTITY();
INSERT dbo.Characters(ProjectID,CharacterName,DefaultDescription,CharacterImportance) VALUES(@project,N'Quick assignment fixture B',N'Another complete biography',6);
DECLARE @b int=SCOPE_IDENTITY(),@json nvarchar(max),@stamp datetime2,@error int;
SELECT @json=(SELECT CharacterID AS Id,N'2' AS Value,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Characters WHERE CharacterID IN(@a,@b) FOR JSON PATH);
EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'importance',@json;
IF (SELECT COUNT(*) FROM dbo.Characters WHERE CharacterID IN(@a,@b) AND CharacterImportance=2)<>2 THROW 51000,'Bulk assignment failed',1;
IF NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE CharacterID=@a AND DefaultDescription=N'Entire biography retained exactly' AND Sex=N'Legacy recorded custom value' AND EyeColour=N'Existing eye value' AND IsDeceased IS NULL) THROW 51000,'Unrelated fields changed',1;
-- Undo each distinct prior importance, using the post-assignment versions.
SELECT @json=(SELECT CharacterID AS Id,CASE WHEN CharacterID=@a THEN N'10' ELSE N'6' END AS Value,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Characters WHERE CharacterID IN(@a,@b) FOR JSON PATH);
EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'importance',@json,1;
IF NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE CharacterID=@a AND CharacterImportance=10) OR NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE CharacterID=@b AND CharacterImportance=6) THROW 51000,'Individual previous values not restored',1;
-- No-op must retain the timestamp.
SELECT @stamp=UpdatedDate FROM dbo.Characters WHERE CharacterID=@a;
SELECT @json=(SELECT @a AS Id,N'10' AS Value,CONVERT(nvarchar(50),@stamp,126) AS Version FOR JSON PATH);
EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'importance',@json;
IF (SELECT UpdatedDate FROM dbo.Characters WHERE CharacterID=@a)<>@stamp THROW 51000,'No-op wrote a row',1;
-- Invalid canonical value, denied user, foreign project and mixed valid/invalid selection are atomic.
SELECT @json=(SELECT CharacterID AS Id,N'9' AS Value,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Characters WHERE CharacterID IN(@a,@b) FOR JSON PATH);
SET @error=0;BEGIN TRY EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'importance',@json;END TRY BEGIN CATCH SET @error=ERROR_NUMBER();END CATCH;
IF @error<>51012 THROW 51000,'Invalid canonical value accepted',1;
SELECT @json=(SELECT @a AS Id,N'2' AS Value,CONVERT(nvarchar(50),@stamp,126) AS Version FOR JSON PATH);
SET @error=0;BEGIN TRY EXEC dbo.Character_QuickAttributes_Assign @project,-1,N'importance',@json;END TRY BEGIN CATCH SET @error=ERROR_NUMBER();END CATCH;
IF @error<>51010 THROW 51000,'Unauthorised user accepted',1;
DECLARE @foreign int=ISNULL((SELECT MAX(ProjectID) FROM dbo.Projects),0)+1;
SET @error=0;BEGIN TRY EXEC dbo.Character_QuickAttributes_Assign @foreign,@user,N'importance',@json;END TRY BEGIN CATCH SET @error=ERROR_NUMBER();END CATCH;
IF @error<>51010 THROW 51000,'Cross-project assignment accepted',1;
SELECT @json=(SELECT Id,N'2' AS Value,CONVERT(nvarchar(50),@stamp,126) AS Version FROM (VALUES(@a),(-1)) x(Id) FOR JSON PATH);
SET @error=0;BEGIN TRY EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'importance',@json;END TRY BEGIN CATCH SET @error=ERROR_NUMBER();END CATCH;
IF @error<>51010 OR (SELECT CharacterImportance FROM dbo.Characters WHERE CharacterID=@a)<>10 THROW 51000,'Partial assignment occurred',1;
-- Stale version (including stale Undo) rejects the entire operation.
UPDATE dbo.Characters SET UpdatedDate=DATEADD(second,1,UpdatedDate) WHERE CharacterID=@a;
SELECT @json=(SELECT @a AS Id,N'2' AS Value,CONVERT(nvarchar(50),@stamp,126) AS Version FOR JSON PATH);
SET @error=0;BEGIN TRY EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'importance',@json,1;END TRY BEGIN CATCH SET @error=ERROR_NUMBER();END CATCH;
IF @error<>51011 OR (SELECT CharacterImportance FROM dbo.Characters WHERE CharacterID=@a)<>10 THROW 51000,'Concurrent Undo overwrote a newer value',1;
-- Individual nullable life status remains independent of archive.
SELECT @json=(SELECT @a AS Id,N'1' AS Value,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Characters WHERE CharacterID=@a FOR JSON PATH);
EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'life',@json;
IF NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE CharacterID=@a AND IsDeceased=1 AND IsArchived=0) THROW 51000,'Life status did not remain independent of archive',1;
-- Restore legacy sex exactly, even without a catalogue ID.
DECLARE @sex int=(SELECT TOP(1) CharacterSexValueID FROM dbo.CharacterSexValues WHERE IsSystem=1 AND IsActive=1);
SELECT @json=(SELECT @a AS Id,CONVERT(nvarchar(100),@sex) AS Value,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Characters WHERE CharacterID=@a FOR JSON PATH);
EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'sex',@json;
SELECT @json=(SELECT @a AS Id,N'' AS Value,N'Legacy recorded custom value' AS Sex,CONVERT(nvarchar(50),UpdatedDate,126) AS Version FROM dbo.Characters WHERE CharacterID=@a FOR JSON PATH);
EXEC dbo.Character_QuickAttributes_Assign @project,@user,N'sex',@json,1;
IF NOT EXISTS(SELECT 1 FROM dbo.Characters WHERE CharacterID=@a AND SexValueID IS NULL AND Sex=N'Legacy recorded custom value') THROW 51000,'Legacy sex Undo lost data',1;
DELETE dbo.Characters WHERE CharacterID IN(@a,@b);
PRINT N'PASS individual/bulk, unrelated fields, canonical validation, authorisation, cross-project isolation, atomic failure, no-op, stale Undo, nullable life status and legacy custom sex restoration';

View File

@ -268,6 +268,11 @@ internal static class ToolbarBrowserHost
await context.RequestServices.GetRequiredService<INarrativeFocus>().Open(context.RequestServices.GetRequiredService<ICurrentUserService>().UserId!.Value,null,id);
await RenderFullAsync(context,"Scenes","Edit",model);
}).WithOrder(-1);
app.MapGet("/character-attribute-definitions-fixture",()=>Results.Json(CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=1,SexName="Male"},new(){CharacterSexValueID=2,SexName="Female"},new(){CharacterSexValueID=3,SexName="Custom recorded sex"}]).Select(g=>new{g.Id,g.Label,values=g.Values.Select(v=>new{v.Value,v.Label,v.Icon,v.Tone,path=ApplicationRibbon.Icon(v.Icon).IconPath})})));
app.MapGet("/character-attributes-fixture",async (HttpContext context)=>{
var count=int.TryParse(context.Request.Query["count"],out var n)?Math.Clamp(n,1,500):10;
await RenderFullAsync(context,"Characters","Index",new CharacterListViewModel{Project=new(){ProjectID=7,ProjectName="Character attribute acceptance fixture",AccessRole="Owner"},Characters=Enumerable.Range(1,count).Select(i=>new Character{CharacterID=i,ProjectID=7,CharacterName=$"Fixture character {i:D3}",CharacterImportance=i%3==0?10:i%3==1?6:2,DefaultDescription=string.Join(" ",Enumerable.Repeat($"Complete biography for character {i}: remembered history, motivations and relationships.",i%9+1))}).ToArray()});
});
app.MapGet("/Characters",async (HttpContext context)=>await RenderFullAsync(context,"Characters","Index",new CharacterListViewModel{Project=new(){ProjectID=7,ProjectName="Fixture project",AccessRole="Owner"},Characters=[new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant",CharacterImportance=6}]})).WithOrder(-1);
app.MapGet("/Projects", () => Results.Redirect("/fixture"));
app.MapGet("/map-story-fixture", () => {

View File

@ -0,0 +1,79 @@
using System.Data;
using System.Security.Cryptography;
using Microsoft.AspNetCore.DataProtection;
using System.Text.Json;
using Dapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize]
public sealed class CharacterAttributesController(IProjectRepository projects,ICharacterRepository characters,IProjectCollaborationRepository collaboration,ICurrentUserService user,ISqlConnectionFactory connections,ContextWorkspaceNotifications notifications,IDataProtectionProvider protection) : Controller
{
[HttpGet]
public async Task<IActionResult> Directory(int projectId)
{
if(user.UserId is not int author)return Unauthorized();
var project=await projects.GetForUserAsync(projectId,author);
if(project is null)return NotFound();
var owner=await collaboration.GetOwnerUserIdAsync(projectId);
var definitions=CharacterQuickAttributes.Definitions(owner.HasValue?await characters.ListSexValuesAsync(owner.Value):[]);
using var db=connections.CreateConnection();
var rows=await db.QueryAsync<Character>("dbo.Character_QuickAttributes_Read",new {ProjectID=projectId,UserID=author},commandType:CommandType.StoredProcedure);
return Json(new {canEdit=ContextEditPolicy.CanEdit(project),groups=definitions.Select(g=>new {g.Id,g.Label,values=g.Values.Select(v=>new {v.Value,v.Label,v.Tone,v.Icon,path=ApplicationRibbon.Icon(v.Icon).IconPath})}),characters=rows.Select(CharacterQuickAttributes.Snapshot)});
}
public sealed record UndoChange(int Id,string Value,string? Sex,string Version);
public sealed record UndoReceipt(int User,int ProjectId,string Attribute,UndoChange[] Changes,DateTime Expires);
public sealed record UndoRequest(string Token);
private sealed class PreviousValue {public int Id{get;set;}public string Value{get;set;}="";public string? Sex{get;set;}}
[HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> Undo([FromBody] UndoRequest request)
{
if(user.UserId is not int author)return Unauthorized();
if(!ModelState.IsValid||request is null||request.Token is null||request.Token.Length>1000000)return BadRequest("Undo is unavailable.");
try
{
var receipt=JsonSerializer.Deserialize<UndoReceipt>(protection.CreateProtector("CharacterQuickAttributes.Undo.v1").Unprotect(request.Token));
if(receipt is null||receipt.User!=author||receipt.Expires<DateTime.UtcNow)return BadRequest("Undo has expired.");
return await Execute(receipt.ProjectId,receipt.Attribute,receipt.Changes,true);
}
catch(Exception e) when(e is CryptographicException or JsonException or ArgumentException){return BadRequest("Undo is unavailable.");}
}
[HttpPost,ValidateAntiForgeryToken]
public async Task<IActionResult> Assign([FromBody] CharacterQuickAssignment input)
{
if(user.UserId is not int author)return Unauthorized();
if(!ModelState.IsValid||input is null||input.Changes is null||input.Changes.Any(c=>c is null)||input.Changes.Length is <1 or >2000||input.Changes.Select(c=>c.Id).Distinct().Count()!=input.Changes.Length)return BadRequest("Choose a distinct character selection.");
if(input.Attribute is not ("importance" or "life" or "sex" or "quickAdd"))return BadRequest("Unknown attribute.");
if(input.Changes.Any(c=>c.Value?.Length>100||!DateTime.TryParse(c.Version,out _)))return BadRequest("Invalid assignment.");
return await Execute(input.ProjectId,input.Attribute,input.Changes.Select(c=>new UndoChange(c.Id,c.Value??"",null,c.Version)).ToArray(),false);
}
private async Task<IActionResult> Execute(int projectId,string attribute,UndoChange[] changes,bool restore)
{
var author=user.UserId!.Value;
try
{
using var db=connections.CreateConnection();
using var result=await db.QueryMultipleAsync("dbo.Character_QuickAttributes_Assign",new {ProjectID=projectId,UserID=author,Attribute=attribute,Changes=JsonSerializer.Serialize(changes),Restore=restore},commandType:CommandType.StoredProcedure);
var rows=(await result.ReadAsync<Character>()).ToArray();
var before=(await result.ReadAsync<PreviousValue>()).ToArray();
string? undoToken=null;
if(rows.Length>0)
{
var versions=rows.ToDictionary(c=>c.CharacterID,c=>c.UpdatedDate.ToString("O"));
undoToken=protection.CreateProtector("CharacterQuickAttributes.Undo.v1").Protect(JsonSerializer.Serialize(new UndoReceipt(author,projectId,attribute,before.Select(c=>new UndoChange(c.Id,c.Value,c.Sex,versions[c.Id])).ToArray(),DateTime.UtcNow.AddMinutes(10))));
await notifications.Invalidate(author,projectId:projectId,kind:"characters");
}
return Json(new {saved=true,characters=rows.Select(CharacterQuickAttributes.Snapshot),undoToken});
}
catch(SqlException e) when(e.Number is 51010 or 51011 or 51012){return StatusCode(e.Number==51010?403:409,new {message=e.Number==51011?"Characters changed in another window. Refresh their attributes and try again.":"The selection or attribute value is no longer available."});}
}
}

View File

@ -0,0 +1,18 @@
using PlotLine.Models;
namespace PlotLine.Services;
// One vocabulary for the directory legend, indicators and assignment menus.
public sealed record CharacterQuickValue(string Value,string Label,string Icon,string Tone="secondary");
public sealed record CharacterQuickGroup(string Id,string Label,IReadOnlyList<CharacterQuickValue> Values);
public static class CharacterQuickAttributes
{
public static IReadOnlyList<CharacterQuickGroup> Definitions(IEnumerable<CharacterSexValue> sex) => [
new("importance","Story importance",[new("10","Major","attribute-star","warning"),new("6","Supporting","characters","info"),new("2","Minor","attribute-person"),new("","Unclassified","help")]),
new("life","Life status",[new("0","Living","attribute-heart","success"),new("1","Deceased","attribute-flower","data-5"),new("","Unrecorded","help")]),
new("sex","Sex",new[]{new CharacterQuickValue("","Not set","help")}.Concat(sex.Select(s=>new CharacterQuickValue(s.CharacterSexValueID.ToString(),s.SexName,"attribute-person"))).ToArray()),
new("quickAdd","Quick Add Bar",[new("1","Included","attribute-pin","primary"),new("0","Excluded","attribute-unpin")])
];
public static object Snapshot(Character c)=>new {id=c.CharacterID,name=c.CharacterName,version=c.UpdatedDate.ToString("O"),values=new Dictionary<string,string>{["importance"]=c.CharacterImportance?.ToString()??"",["life"]=c.IsDeceased.HasValue?(c.IsDeceased.Value?"1":"0"):"",["sex"]=c.SexValueID?.ToString()??(string.IsNullOrWhiteSpace(c.Sex)?"":"legacy:"+c.Sex),["quickAdd"]=c.ShowInQuickAddBar?"1":"0"}};
}
public sealed record CharacterQuickChange(int Id,string? Value,string Version);
public sealed record CharacterQuickAssignment(int ProjectId,string Attribute,CharacterQuickChange[] Changes);

View File

@ -45,6 +45,12 @@ public static class RibbonPresentation
return null;
}
public static IReadOnlyList<RibbonIcon> AdditionalIcons { get; } = [
new("attribute-star", "M12 2l3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z", "characters"),
new("attribute-person", "M16 6a4 4 0 1 0-8 0 4 4 0 0 0 8 0 M4 22v-3a8 8 0 0 1 16 0v3z", "characters"),
new("attribute-heart", "M12 21L3 12C-3 4 7-1 12 6c5-7 15-2 9 6z", "characters"),
new("attribute-flower", "M12 22v-8 M12 19l6-3 M12 5c-6-9-10 2-5 4-8 3 0 10 5 5 5 5 13-2 5-5 5-2 1-13-5-4z", "characters"),
new("attribute-pin", "M8 3h8l-1 7 4 4H5l4-4z M12 14v8", "characters"),
new("attribute-unpin", "M8 3h8l-1 7 4 4H9 M12 14v8 M3 3l18 18", "characters"),
new("chevron-left", "M15 4l-8 8 8 8", "planning"),
new("chevron-right", "M9 4l8 8-8 8", "planning"),
new("minimise", "M3 9h6V3 M21 9h-6V3 M3 15h6v6 M21 15h-6v6", "planning"),

View File

@ -0,0 +1,58 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Atomic, authorised, compare-and-swap assignment. No biography or other editor fields are written.
CREATE OR ALTER PROCEDURE dbo.Character_QuickAttributes_Assign
@ProjectID int,@UserID int,@Attribute nvarchar(30),@Changes nvarchar(max),@Restore bit=0
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF @Attribute NOT IN(N'importance',N'life',N'sex',N'quickAdd') THROW 51012,'Invalid attribute',1;
DECLARE @items TABLE(Id int PRIMARY KEY,Value nvarchar(100),Sex nvarchar(100),Version datetime2);
INSERT @items SELECT Id,ISNULL(Value,N''),Sex,TRY_CONVERT(datetime2,Version) FROM OPENJSON(@Changes) WITH(Id int,Value nvarchar(100),Sex nvarchar(100),Version nvarchar(50));
IF (SELECT COUNT(*) FROM @items) NOT BETWEEN 1 AND 2000 OR EXISTS(SELECT 1 FROM @items WHERE Version IS NULL) THROW 51012,'Invalid selection',1;
BEGIN TRY
BEGIN TRANSACTION;
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WITH(HOLDLOCK) JOIN dbo.Projects p WITH(HOLDLOCK) ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND a.AccessRole IN(N'Owner',N'Collaborator') AND p.IsArchived=0) THROW 51010,'Editing unavailable',1;
IF EXISTS(SELECT 1 FROM @items i LEFT JOIN dbo.Characters c WITH(UPDLOCK,HOLDLOCK) ON c.CharacterID=i.Id AND c.ProjectID=@ProjectID AND c.IsArchived=0 WHERE c.CharacterID IS NULL) THROW 51010,'Character unavailable',1;
IF EXISTS(SELECT 1 FROM @items i JOIN dbo.Characters c ON c.CharacterID=i.Id WHERE c.UpdatedDate<>i.Version) THROW 51011,'Characters changed',1;
IF @Restore=0 AND @Attribute=N'importance' AND EXISTS(SELECT 1 FROM @items WHERE Value NOT IN(N'',N'10',N'6',N'2')) THROW 51012,'Invalid importance',1;
IF @Attribute=N'life' AND EXISTS(SELECT 1 FROM @items WHERE Value NOT IN(N'',N'0',N'1')) THROW 51012,'Invalid life status',1;
IF @Attribute=N'quickAdd' AND EXISTS(SELECT 1 FROM @items WHERE Value NOT IN(N'0',N'1')) THROW 51012,'Invalid Quick Add value',1;
IF @Restore=0 AND @Attribute=N'sex' AND EXISTS(SELECT 1 FROM @items i WHERE i.Value<>N'' AND NOT EXISTS(SELECT 1 FROM dbo.CharacterSexValues s JOIN dbo.ProjectUserAccess a ON a.ProjectID=@ProjectID AND a.AccessRole=N'Owner' AND a.IsActive=1 WHERE s.CharacterSexValueID=TRY_CONVERT(int,i.Value) AND s.IsActive=1 AND (s.IsSystem=1 OR s.OwnerUserID=a.UserID))) THROW 51012,'Invalid sex value',1;
DECLARE @changed TABLE(Id int PRIMARY KEY,Value nvarchar(100),OldSex nvarchar(100),CharacterName nvarchar(200),UpdatedDate datetime2,CharacterImportance int,IsDeceased bit,SexValueID int,Sex nvarchar(100),ShowInQuickAddBar bit);
UPDATE c SET
CharacterImportance=CASE WHEN @Attribute=N'importance' THEN TRY_CONVERT(int,NULLIF(i.Value,N'')) ELSE c.CharacterImportance END,
IsDeceased=CASE WHEN @Attribute=N'life' THEN TRY_CONVERT(bit,NULLIF(i.Value,N'')) ELSE c.IsDeceased END,
ShowInQuickAddBar=CASE WHEN @Attribute=N'quickAdd' THEN CONVERT(bit,i.Value) ELSE c.ShowInQuickAddBar END,
SexValueID=CASE WHEN @Attribute=N'sex' THEN TRY_CONVERT(int,NULLIF(i.Value,N'')) ELSE c.SexValueID END,
Sex=CASE WHEN @Attribute=N'sex' THEN CASE WHEN @Restore=1 THEN i.Sex ELSE (SELECT SexName FROM dbo.CharacterSexValues WHERE CharacterSexValueID=TRY_CONVERT(int,NULLIF(i.Value,N''))) END ELSE c.Sex END,
UpdatedDate=SYSUTCDATETIME()
OUTPUT inserted.CharacterID,
CASE @Attribute WHEN N'importance' THEN ISNULL(CONVERT(nvarchar(100),deleted.CharacterImportance),N'') WHEN N'life' THEN ISNULL(CONVERT(nvarchar(100),deleted.IsDeceased),N'') WHEN N'quickAdd' THEN CONVERT(nvarchar(100),deleted.ShowInQuickAddBar) WHEN N'sex' THEN ISNULL(CONVERT(nvarchar(100),deleted.SexValueID),N'') END,
deleted.Sex,inserted.CharacterName,inserted.UpdatedDate,inserted.CharacterImportance,inserted.IsDeceased,inserted.SexValueID,inserted.Sex,inserted.ShowInQuickAddBar INTO @changed
FROM dbo.Characters c JOIN @items i ON i.Id=c.CharacterID
WHERE i.Value<>CASE @Attribute WHEN N'importance' THEN ISNULL(CONVERT(nvarchar(100),c.CharacterImportance),N'') WHEN N'life' THEN ISNULL(CONVERT(nvarchar(100),c.IsDeceased),N'') WHEN N'quickAdd' THEN CONVERT(nvarchar(100),c.ShowInQuickAddBar) WHEN N'sex' THEN ISNULL(CONVERT(nvarchar(100),c.SexValueID),N'') END OR (@Attribute=N'sex' AND @Restore=1 AND ISNULL(c.Sex,N'')<>ISNULL(i.Sex,N''));
COMMIT;
SELECT Id AS CharacterID,CharacterName,UpdatedDate,CharacterImportance,IsDeceased,SexValueID,Sex,ShowInQuickAddBar FROM @changed;
SELECT Id,Value,OldSex AS Sex FROM @changed;
END TRY
BEGIN CATCH
IF @@TRANCOUNT>0 ROLLBACK;
THROW;
END CATCH;
END;
GO
CREATE OR ALTER PROCEDURE dbo.Character_QuickAttributes_Read @ProjectID int,@UserID int
AS
BEGIN
SET NOCOUNT ON;
SELECT c.CharacterID,c.CharacterName,c.UpdatedDate,c.CharacterImportance,c.IsDeceased,c.SexValueID,c.Sex,c.ShowInQuickAddBar
FROM dbo.Characters c JOIN dbo.Projects p ON p.ProjectID=c.ProjectID
WHERE c.ProjectID=@ProjectID AND c.IsArchived=0 AND p.IsArchived=0
AND EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a WHERE a.ProjectID=c.ProjectID AND a.UserID=@UserID AND a.IsActive=1);
END;
GO

View File

@ -23,6 +23,23 @@
</div>
</div>
<link rel="stylesheet" href="~/css/character-attributes.css" asp-append-version="true" />
<div data-character-attributes data-project-id="@Model.Project.ProjectID">
@Html.AntiForgeryToken()
<div class="character-attribute-toolbar button-row">
<button type="button" class="btn btn-outline-secondary" data-attributes-toggle aria-expanded="true">Attributes</button>
<span data-selection-count role="status">0 selected</span>
<button type="button" class="btn btn-outline-secondary btn-sm" data-select-visible>Select displayed</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-clear-selection>Clear selection</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-undo hidden>Undo attribute change</button>
</div>
<div class="character-attribute-layout">
<aside class="character-attribute-sidebar" aria-label="Attributes" data-attribute-sidebar>
<h2>Attributes</h2>
<p class="small muted">Click to filter. Drag to assign, or select characters and choose Assign.</p>
<button type="button" class="btn btn-outline-secondary btn-sm" data-clear-filter>Clear filters</button>
<div data-attribute-groups aria-live="polite">Loading attributes…</div>
</aside>
<section class="list-section character-card-list">
@if (!Model.Characters.Any())
{
@ -33,12 +50,18 @@
<div class="asset-card-grid character-card-grid">
@foreach (var character in Model.Characters)
{
<article data-pd-context="character" data-pd-context-id="@character.CharacterID" data-pd-context-label="@character.CharacterName" class="asset-card character-card character-card--span-@CharacterCardLayout.ColumnSpan(character)" draggable="true" data-drag-type="character" data-drag-id="@character.CharacterID" data-drag-label="@character.CharacterName">
<article data-pd-context="character" data-pd-context-id="@character.CharacterID" data-pd-context-label="@character.CharacterName" class="asset-card character-card character-card--span-@CharacterCardLayout.ColumnSpan(character)" tabindex="0" data-drag-type="character" data-drag-id="@character.CharacterID" data-drag-label="@character.CharacterName">
<div class="character-attribute-controls">
<label><input type="checkbox" data-character-select aria-label="Select @character.CharacterName" /> Select</label>
<button type="button" class="btn btn-outline-secondary btn-sm" draggable="true" data-character-drag aria-label="Drag @character.CharacterName to an attribute" title="Drag to an attribute">↕</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-character-menu aria-label="Actions for @character.CharacterName" aria-haspopup="menu">⋯</button>
</div>
<div class="visual-card-heading">
<partial name="_Avatar" model="@(new AvatarViewModel { DisplayName = character.CharacterName, ImagePath = character.AvatarImagePath ?? character.ImagePath, ThumbnailPath = character.AvatarThumbnailPath ?? character.ThumbnailPath })" />
<div>
<p class="eyebrow">Character</p>
<h2><a asp-action="Details" asp-route-id="@character.CharacterID">@character.CharacterName</a></h2>
<div class="character-attribute-indicators" data-attribute-indicators></div>
<p class="muted">@character.DefaultDescription</p>
</div>
</div>
@ -59,3 +82,7 @@
</div>
}
</section>
</div>
</div>
<script src="~/js/character-attributes.js" asp-append-version="true" defer></script>

View File

@ -4,14 +4,14 @@
font: 13px/1.35 var(--pd-font-ui); color: var(--pd-text); background: var(--pd-elevated);
border: 1px solid var(--pd-border); border-radius: var(--pd-radius); box-shadow: 0 6px 22px rgb(0 0 0 / 20%);
}
.pd-context-popup [role="menuitem"] {
.pd-context-popup :is([role="menuitem"],[role="menuitemradio"]) {
display: flex; align-items: center; gap: 9px; width: 100%; min-height: 29px;
padding: 5px 8px; border: 0; border-radius: 3px; text-align: left;
background: transparent; color: inherit; font: inherit; cursor: default;
}
.pd-context-popup [role="menuitem"]:hover:not([aria-disabled="true"]),
.pd-context-popup [role="menuitem"]:focus-visible { background: var(--pd-hover); }
.pd-context-popup [role="menuitem"]:focus-visible { outline: 2px solid var(--pd-focus); outline-offset: -2px; }
.pd-context-popup :is([role="menuitem"],[role="menuitemradio"]):hover:not([aria-disabled="true"]),
.pd-context-popup :is([role="menuitem"],[role="menuitemradio"]):focus-visible { background: var(--pd-hover); }
.pd-context-popup :is([role="menuitem"],[role="menuitemradio"]):focus-visible { outline: 2px solid var(--pd-focus); outline-offset: -2px; }
.pd-context-popup [aria-disabled="true"] { color: var(--pd-disabled-text); opacity: .65; }
.pd-context-popup [data-destructive="true"] { color: var(--pd-danger); }
.pd-context-popup .pd-icon { width: 17px; height: 17px; flex: 0 0 17px; }

View File

@ -0,0 +1,21 @@
.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-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].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}
@media(max-width:850px){.character-attribute-layout{grid-template-columns:minmax(0,1fr)}.character-attribute-sidebar{position:relative;top:0;max-height:45dvh}.character-attribute-controls{flex-wrap:wrap}}
.character-attribute-drag-preview{position:fixed;left:-10000px;top:0;padding:.5rem .75rem;border:1px solid var(--pd-accent);border-radius:.5rem;background:var(--pd-elevated);color:var(--pd-text);font-weight:600}
.character-attribute-controls{white-space:nowrap}.character-attribute-controls [data-character-drag]{cursor:grab;font-size:1rem;line-height:1}.character-attribute-controls input{vertical-align:middle}
.text-data-5{color:var(--pd-data-5,var(--pd-icon-characters))!important}

View File

@ -7,7 +7,7 @@
const icons = shell.querySelector('[data-pwa-icon-catalog]')?.content;
const boundary = '[data-pd-context]';
const providers=window.PlotDirectorContextProviders||[];window.PlotDirectorContextProviders=providers;
window.PlotDirectorContextMenus={register(selector,provider){providers.push({selector,provider});},open:(target)=>open(target,0,0,true)};
window.PlotDirectorContextMenus={register(selector,provider){providers.push({selector,provider});},open:(target)=>open(target,0,0,true),openAt:(target,x,y,keyboard=false)=>open(target,x,y,keyboard),close};
let popup = null, child = null, owner = null, invoker = null, pointerType = '', sequence = 0;
const create = (tag, attributes = {}, text = '') => {
const node = document.createElement(tag);
@ -26,7 +26,7 @@
sequence++; closeSubmenu(); popup?.remove(); popup = null;
if (restore && invoker?.isConnected) invoker.focus({ preventScroll: true });
}
const items = menu => [...menu.querySelectorAll(':scope > [role="menuitem"]')];
const items = menu => [...menu.querySelectorAll(':scope > [role="menuitem"], :scope > [role="menuitemradio"]')];
function position(menu, x, y) {
const width = document.documentElement.clientWidth || innerWidth;
menu.style.maxWidth = `${Math.min(310, width - 12)}px`; menu.style.minWidth = `${Math.min(205, width - 12)}px`;
@ -36,13 +36,13 @@
menu.style.top = `${Math.max(6, Math.min(y, innerHeight - rect.height - 6))}px`;
}
function openSubmenu(button, commands, keyboard = false) {
if (owner === button && child) { if (keyboard) items(child)[0]?.focus(); return; }
if (owner === button && child) { if (keyboard) items(child)[0]?.focus({preventScroll:true}); return; }
closeSubmenu(); owner = button; button.setAttribute('aria-expanded', 'true');
child = render(commands, button.textContent.trim());
child.id = button.getAttribute('aria-controls'); document.body.append(child);
const rect = button.getBoundingClientRect(), width = child.getBoundingClientRect().width;
position(child, rect.right + width + 6 > (document.documentElement.clientWidth || innerWidth) ? rect.left - width - 3 : rect.right + 3, rect.top);
if (keyboard) items(child)[0]?.focus();
if (keyboard) items(child)[0]?.focus({preventScroll:true});
}
function render(commands, name) {
const menu = create('div', { class: 'pd-context-popup', role: 'menu', 'aria-label': name });
@ -50,6 +50,12 @@
if (command.separator) { if (menu.childElementCount) menu.append(create('div', { role: 'separator' })); continue; }
const button = create('button', { type: 'button', role: 'menuitem', tabindex: '-1', 'aria-label': command.label, 'aria-disabled': String(!!command.disabled) });
button.append(icon(command.icon), create('span', { class: 'pd-context-item-label' }, command.label));
if (command.checked !== undefined) {
button.setAttribute('aria-checked', String(command.checked));
button.setAttribute('role', 'menuitemradio');
if (command.checked) button.append(create('span', {'aria-hidden':'true'}, '✓'));
}
if (command.tone && ['warning','primary','secondary','success','info','data-5'].includes(command.tone)) button.querySelector('svg')?.classList.add('text-'+command.tone);
if (command.destructive) button.dataset.destructive = 'true';
if (command.children) {
button.setAttribute('aria-haspopup', 'menu'); button.setAttribute('aria-expanded', 'false'); button.setAttribute('aria-controls', `pd-context-submenu-${++sequence}`);

View File

@ -0,0 +1,59 @@
(() => {
'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 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);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 matching(record,except){return [...filter].every(([a,v])=>a===except||displayValue(a,record?.values[a])===v);}
function displayValue(a,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.values[0],label:r.values.sex.slice(7),path:groups.find(g=>g.id==='importance').values[2].path}: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);}
// 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();}
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();}}}
function assignTo(attribute,value,ids){return persist(attribute,ids.filter(id=>records.has(id)).map(id=>({id,value,version:records.get(id).version})));}
function restore(){if(undo)void persist(null,undo,true);}
undoButton.addEventListener('click',restore);
root.querySelector('[data-select-visible]').addEventListener('click',()=>{shown().forEach(c=>selected.add(Number(c.dataset.dragId)));selection();});root.querySelector('[data-clear-selection]').addEventListener('click',()=>{selected.clear();selection();});root.querySelector('[data-clear-filter]').addEventListener('click',()=>{filter.clear();render();});
// Reuse the user-scoped local UI preference convention used by the character workspace.
const user=document.querySelector('[data-toast-host]')?.dataset.toastUser||'session',preference=`pd.character.attributes.v1.${user}.${project}`;
function collapse(value){root.classList.toggle('attributes-collapsed',value);sidebar.hidden=value;toggle.setAttribute('aria-expanded',String(!value));}
try{collapse(localStorage.getItem(preference)==='collapsed');}catch{}
toggle.addEventListener('click',()=>{const value=!sidebar.hidden;collapse(value);try{localStorage.setItem(preference,value?'collapsed':'expanded');}catch{}});
cards.forEach(card=>{const id=Number(card.dataset.dragId),checkbox=card.querySelector('[data-character-select]'),handle=card.querySelector('[data-character-drag]');
checkbox.addEventListener('change',()=>{checkbox.checked?selected.add(id):selected.delete(id);anchor=id;selection();});
card.addEventListener('click',e=>{if(e.target.closest('button,input,form'))return;if(Date.now()<ignoreClickUntil){e.preventDefault();return;}if(e.ctrlKey||e.metaKey||e.shiftKey){e.preventDefault();const visible=shown().map(c=>Number(c.dataset.dragId));if(e.shiftKey&&anchor!==null&&visible.includes(anchor)){const a=visible.indexOf(anchor),b=visible.indexOf(id);visible.slice(Math.min(a,b),Math.max(a,b)+1).forEach(x=>selected.add(x));}else selected.has(id)?selected.delete(id):selected.add(id);anchor=id;selection();}});
handle.addEventListener('dragstart',e=>{if(!canEdit)return e.preventDefault();drag={ids:scope(id)};e.stopPropagation();e.dataTransfer.setData('application/x-plotdirector-characters',JSON.stringify(drag));e.dataTransfer.effectAllowed='copy';preview(e,`${drag.ids.length} character${drag.ids.length===1?'':'s'}`);root.classList.add('dragging-characters');handle.title=`${drag.ids.length} characters`;});
card.querySelector('[data-character-menu]').addEventListener('click',e=>openMenu(id,e.clientX,e.clientY,e.currentTarget));
card.addEventListener('contextmenu',e=>{if(e.ctrlKey||e.target.closest('input,textarea,[contenteditable]')||window.getSelection()?.toString())return;e.preventDefault();e.stopPropagation();openMenu(id,e.clientX,e.clientY,e.target);});
card.addEventListener('keydown',e=>{if(e.key==='ContextMenu'||(e.shiftKey&&e.key==='F10')){e.preventDefault();e.stopPropagation();const r=card.getBoundingClientRect();openMenu(id,r.left+20,r.top+20,e.target);}});
});
root.addEventListener('dragover',e=>{if(!canEdit||!drag)return;const target=drag.attribute?e.target.closest('.character-card'):e.target.closest('[data-attribute]');if(!target)return;e.preventDefault();e.dataTransfer.dropEffect='copy';root.querySelectorAll('.is-drop-target').forEach(n=>n.classList.remove('is-drop-target'));target.classList.add('is-drop-target');});
root.addEventListener('drop',e=>{if(!drag)return;const target=drag.attribute?e.target.closest('.character-card'):e.target.closest('[data-attribute]');if(!target)return;e.preventDefault();e.stopPropagation();if(drag.attribute)void assignTo(drag.attribute,drag.value,scope(Number(target.dataset.dragId)));else void assignTo(target.dataset.attribute,target.dataset.value,drag.ids);endDrag();});
function preview(event,label){const node=document.createElement('div');node.className='character-attribute-drag-preview';node.textContent=label;document.body.append(node);event.dataTransfer.setDragImage(node,12,12);requestAnimationFrame(()=>node.remove());}
root.addEventListener('dragleave',e=>{const target=e.target.closest('.is-drop-target');if(target&&!target.contains(e.relatedTarget))target.classList.remove('is-drop-target');});
function endDrag(){drag=null;ignoreClickUntil=Date.now()+250;root.classList.remove('dragging-attribute','dragging-characters');root.querySelectorAll('.is-drop-target').forEach(n=>n.classList.remove('is-drop-target'));}
document.addEventListener('dragend',endDrag);document.addEventListener('keydown',e=>{if(e.key==='Escape'){endDrag();window.PlotDirectorContextMenus?.close(true);}});
function commandsFor(id,target){
const ids=scope(id),bulk=ids.length>1,card=byId.get(id),commands=[{label:bulk?`${ids.length} characters selected`:records.get(id)?.name||card.dataset.dragLabel,icon:'characters',disabled:true}];
if(!bulk)for(const [label,selector,icon]of [['Open character','h2 a','details'],['Edit character','a[href*="Edit"]','edit']]){const link=card.querySelector(selector);commands.push({label,icon,source:link,run:()=>link.click()});}
commands.push({separator:true});
if(canEdit)for(const g of groups){const values=ids.map(id=>displayValue(g.id,records.get(id)?.values[g.id])),mixed=new Set(values).size>1;commands.push({label:g.label+(mixed?' · Mixed values':''),icon:g.values[0].icon,children:g.values.map(v=>({label:v.label,icon:v.icon,tone:v.tone,checked:values.every(x=>x===v.value),disabled:busy,run:()=>assignTo(g.id,v.value,ids)}))});}
if(!bulk){const archive=card.querySelector('form.archive-button-form button[type=submit]');commands.push({separator:true},{label:'Archive',icon:'archive',source:archive,disabled:archive.disabled,destructive:true,run:()=>archive.click()});}
return {commands,invoker:target?.closest('input,textarea,select,button,a,[tabindex]')||card};
}
function openMenu(id,x,y,origin){window.PlotDirectorContextMenus?.openAt(origin,x,y,origin.tagName==='BUTTON');}
function registerMenu(){window.PlotDirectorContextMenus?.register('[data-character-attributes] .character-card',target=>{if(target.closest('input,textarea,[contenteditable]')||window.getSelection()?.toString())return null;return commandsFor(Number(target.closest('.character-card').dataset.dragId),target);});}
registerMenu();
function wire(c){if(connection||!c)return;connection=c;c.on('ContextInvalidated',hint=>{if(!hint.projectId||Number(hint.projectId)===project){if(busy)pendingRefresh=true;else void refresh();}});c.onreconnected(()=>void refresh());}
document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));wire(window.PlotDirectorPresenceConnection);void refresh();
})();

View File

@ -75,7 +75,14 @@
const dismiss = () => { clearTimeout(timer); node.remove(); active.delete(key); };
close.addEventListener('click', dismiss);
node.addEventListener('keydown', event => { if (event.key === 'Escape') dismiss(); });
node.append(content, close); regions[type === 'error' || type === 'warning' ? 'assertive' : 'polite'].append(node); active.set(key, dismiss);
node.append(content);
if (options.action && typeof options.action.run === 'function') {
const action = document.createElement('button');
action.type = 'button'; action.textContent = String(options.action.label || 'Undo');
action.addEventListener('click', () => { dismiss(); options.action.run(); });
node.append(action);
}
node.append(close); regions[type === 'error' || type === 'warning' ? 'assertive' : 'polite'].append(node); active.set(key, dismiss);
const duration = options.duration ?? (type === 'error' || type === 'warning' ? 0 : 6000);
const start = () => { clearTimeout(timer); if (duration > 0) timer = setTimeout(dismiss, duration); };
node.addEventListener('mouseenter', () => clearTimeout(timer));