Build interactive Locations workspace with safe hierarchy and bulk editing
163
Docs/Locations/Acceptance.md
Normal file
@ -0,0 +1,163 @@
|
||||
# Locations workspace delivery and acceptance
|
||||
|
||||
Implementation is complete. Development activation and authenticated smoke evidence will be
|
||||
appended after the signed release is activated. Production is outside this task.
|
||||
|
||||
## Delivered architecture
|
||||
|
||||
The full-width directory has independently resizable/collapsible Attributes and Details panels,
|
||||
an expandable tree and variable-height cards, search/filters/sibling sorting, selection and
|
||||
bulk assignment, bidirectional attribute drag, branch/root drag moves with hover expansion,
|
||||
inline rename, child creation, description Save/Cancel, and shared context menus.
|
||||
The same records and commands drive both views. Traditional forms and non-hierarchical
|
||||
relationship editing remain available. See [architecture and safeguards](Workspace.md).
|
||||
|
||||
Reused: Dapper/stored procedures, canonical location records and aliases, project ownership roles,
|
||||
`workspace-surface.js`, shared context menus/ribbon icons, `PlotDirector.toast`, protected Undo
|
||||
receipts, existing merge reconciliation/audit, and Context invalidation notifications.
|
||||
|
||||
Migration **335_LocationsWorkspace.sql** adds nullable classification (Real/Fictional/Fictionalised;
|
||||
NULL is Unclassified), four compatible canonical types (Planet, District, Natural Feature, City),
|
||||
and targeted workspace procedures. No existing type or classification is replaced. Quick Add and
|
||||
Word Companion exclusion are existing quick switches; detection priority remains in Edit.
|
||||
The project export selector and `LocationItem` retain classification through backup/restore.
|
||||
The established merge now also preserves maps and conflicting descriptions, including when
|
||||
opened through the traditional Details page. The workspace adds conflict review and version checks.
|
||||
No AI processing or geocoding is invoked by these workspace commands.
|
||||
|
||||
## Verification
|
||||
|
||||
- `dotnet build PlotLine.slnx`: passed, zero warnings/errors.
|
||||
- Executable regression harness: **889 PASS**, successful exit. Existing Characters, Names,
|
||||
Relationships, Maps/topology, Floor Plans, Assets, import, Context and shared focus contracts
|
||||
remain covered by the existing harness; this is not a claim of exhaustive manual workflow testing.
|
||||
- Actual compiled Razor and production CSS/JavaScript: Chromium browser and a genuinely installed
|
||||
Chromium PWA under Xvfb. Collections of 50/200/500/1,000 records; deep chains, wide branches,
|
||||
repeated names, complete long descriptions, map/floor-plan indicators.
|
||||
- Physical attribute/location dragging, hover-expand reparenting, root drops and invalid target
|
||||
rejection; bulk assignment, individual-value Undo, no-op assignment, simulated save failure,
|
||||
inline rename Save/Escape, child creation, right-click/keyboard/visible menus, unsaved-description
|
||||
protection, filters, cards, sorting, and a delayed live-refresh race.
|
||||
- Both divider pointer drags and keyboard resizing; saved widths, collapsed panels, view, attribute
|
||||
groups and expanded branches survive reload. View changes retain selection and filters.
|
||||
- All seven available theme choices; 390/768/1024/1280/1440/1920-pixel viewport checks without
|
||||
horizontal document overflow. Native physical Windows/Edge installation was not available.
|
||||
- Focused SQL regressions run only on disposable clones and roll back: ancestor/descendant bulk
|
||||
safety, root moves, exact original parents on Undo, no-op versions, cycle/unavailable/cross-project
|
||||
parent rejection, unauthorized/stale writes, and targeted rename preserving scene assignment.
|
||||
Merge preserves source records, descriptions, classification, children, aliases, authored
|
||||
relationships, scene assignments, map feature IDs/geometry and floor-plan links.
|
||||
- Real Dapper create/assignment/Undo and six directory result sets, including entry/exit-only
|
||||
character scene assignments counted once. Actual typed project export and generic location JSON
|
||||
restore retain a non-null classification. Restore fixture is rolled back and removed.
|
||||
- Two fresh final-schema qualification clones produce identical schema hashes. All **208** other
|
||||
original business tables retain fingerprints; existing LocationTypes rows are unchanged and the
|
||||
only data addition is four canonical types. DBCC integrity and constraints pass (zero violations).
|
||||
See [sanitised qualification](Evidence/database-qualification.json).
|
||||
|
||||
## Performance
|
||||
|
||||
Milliseconds, single representative passes on the isolated Razor host. Browser transport/data
|
||||
mutations are synthetic; these are not authenticated network benchmarks. The richer after-workspace
|
||||
also renders indicators, controls and descriptions. The large after fixtures include a 100-level
|
||||
chain. Search/interaction timings include deliberate settling waits; no statistical speedup is claimed.
|
||||
|
||||
| Locations | Old list load | New browser load | Installed PWA load | Expand all (browser) | Search (browser) | Cards (browser) |
|
||||
|---:|---:|---:|---:|---:|---:|---:|
|
||||
| 50 | 257 | 266 | 302 | 102 | 108 | 116 |
|
||||
| 200 | 230 | 292 | 375 | 167 | 148 | 200 |
|
||||
| 500 | 410 | 317 | 451 | 334 | 126 | 436 |
|
||||
| 1000 | 609 | 445 | 729 | 636 | 163 | 1248 |
|
||||
|
||||
The first cold post-build 50-record request measured **1,424 ms**; warm 50-record passes were about
|
||||
266–302 ms. At 1,000 records the measured browser bulk interaction was 858 ms, rename 123 ms,
|
||||
reparent 283 ms and selected-details 103 ms in one pass; later passes vary. Card rendering at this
|
||||
scale is approximately 1.2 seconds with full descriptions. There is no card virtualization.
|
||||
Raw passes: [before](Evidence/before.json), [after](Evidence/after-large.json),
|
||||
[cold request](Evidence/after-cold-release.json), [PWA](Evidence/pwa-performance.json).
|
||||
|
||||
Actual SQL/Dapper reads, on a disposable Development clone with 69 existing records in addition
|
||||
to each synthetic collection: old simple list / new six-result directory = 25.5/82.1 ms (50),
|
||||
41.2/18.3 ms (200), 55.9/41.2 ms (500), 71.3/68.1 ms (1,000).
|
||||
The new read includes aliases, maps, floor plans, usage, types and relationship/character/asset
|
||||
counts, without per-location queries. [Raw database results](Evidence/database-performance.txt).
|
||||
|
||||
## Acceptance matrix
|
||||
|
||||
“Passed” means exercised by the stated browser/SQL/harness checks, not merely compiled.
|
||||
|
||||
| Requirement | Status | Evidence / boundary |
|
||||
|---|---|---|
|
||||
| Full-width three-panel workspace; responsive layouts | Passed | Rendered browser/PWA, viewport overflow checks |
|
||||
| Both pointer/keyboard dividers; independent saved widths | Passed | Native pointer checks, reload assertions |
|
||||
| Collapse/restore Attributes and Details | Passed | Both modes, reload assertions |
|
||||
| Tree expansion, remembered branches, ancestral paths | Passed | Tree/search/reload checks |
|
||||
| Native reparenting and hover-expanded branches | Passed | Native pointer test and hover screenshot |
|
||||
| Root-level drop and invalid descendant target feedback | Passed | Native drop/no-write checks; SQL rejection |
|
||||
| Bulk branch preservation and exact parent Undo | Passed | Transactional SQL fixture with different original parents |
|
||||
| Server ownership, active-parent and cycle validation | Passed | Unauthorized, cross-project, unavailable and cycle SQL/HTTP contracts |
|
||||
| Type/classification and existing quick switches | Passed | Browser assignments and SQL/Dapper round trip |
|
||||
| Bidirectional attribute drag, selection and bulk assignment | Passed | Browser/PWA drag and selection checks |
|
||||
| Counts, derived filters, aliases, branch search and clear | Passed | Rendered tests; authoritative batched SQL |
|
||||
| Shared toast and version-protected Undo | Passed | Browser actions and real Dapper exact-version restore |
|
||||
| No-op and failed-assignment preservation | Passed | No-request and simulated conflict checks; SQL version checks |
|
||||
| F2/menu rename, Enter save, Escape cancel | Passed | Native keyboard/browser checks; scene IDs preserved |
|
||||
| Direct child creation and description editing | Passed | Rendered dialog/details tests; unsaved draft checks |
|
||||
| Context menus, visible menu and keyboard alternative | Passed | Browser right-click, Shift+F10, installed PWA |
|
||||
| Hierarchy/cards, complete descriptions, variable heights | Passed | DOM height checks and rendered screenshots |
|
||||
| Selection/filter preservation and branch-safe sorting | Passed | View/sibling-order checks |
|
||||
| Multiple map/floor-plan associations and same-window links | Passed | Directory links and SQL preservation checks |
|
||||
| Merge review, reconciliation and rollback safeguards | Passed | SQL data-integrity fixtures; workspace review implemented |
|
||||
| Backup/export/restore retains optional classification | Passed | Actual typed export and generic restore round trip |
|
||||
| No new AI, no manuscript focus writes | Passed | Command paths contain no AI/geography/focus calls; existing harness |
|
||||
| Existing related workspace behavior | Passed | 889-check harness; authenticated route smoke pending activation |
|
||||
| Live updates across actual Development windows | Not verified | Pending post-activation dedicated-account check |
|
||||
| Development deployment and authenticated mutations | Not verified | Pending signed release activation |
|
||||
| Every existing Context consumer with physical Word/PWA | Not verified | Existing contracts/hints preserved; physical Word unavailable |
|
||||
| Windows/Edge installed-PWA behavior | Not verified | Linux Chromium browser + real installed PWA verified |
|
||||
| Collections above 1,000; exhaustive keyboard/assistive-tech audit | Not verified | No claim beyond measured cases |
|
||||
| New location image storage | Not implemented | No canonical location-image attribute exists; conditional scope only |
|
||||
| New feature-level reveal inside Maps/Floor Plans | Not implemented | Existing routes select map/plan; their editors are unchanged |
|
||||
|
||||
No unresolved failing check is known. The last two “Not implemented” items are conditional features
|
||||
without an existing canonical field/route, not replacement representations or editor redesigns.
|
||||
|
||||
## Rendered evidence
|
||||
|
||||
All screenshots use controlled synthetic data, never the author's manuscripts/locations.
|
||||
|
||||
| Demonstration | Screenshot |
|
||||
|---|---|
|
||||
| Baseline list | [Before](Evidence/before.png) |
|
||||
| Complete workspace | [Browser](Evidence/workspace.png), [installed PWA](Evidence/pwa-workspace.png) |
|
||||
| Populated multilevel hierarchy | [Hierarchy](Evidence/hierarchy.png) |
|
||||
| Attribute assignment | [Assignment](Evidence/attribute-assignment.png) |
|
||||
| Reparenting and hover expansion | [Move](Evidence/reparenting.png), [hover](Evidence/hover-reparent.png), [root drop](Evidence/root-drop.png) |
|
||||
| Bulk assignment | [Bulk](Evidence/bulk-assignment.png) |
|
||||
| Inline rename | [Rename](Evidence/inline-rename.png) |
|
||||
| Context menu | [Menu](Evidence/context-menu.png) |
|
||||
| Direct child creation | [Child](Evidence/create-child.png) |
|
||||
| Editable Details | [Description](Evidence/details-edit.png) |
|
||||
| Variable-size cards | [Cards](Evidence/cards.png), [PWA](Evidence/pwa-cards.png) |
|
||||
| Search with ancestors | [Search](Evidence/search-context.png) |
|
||||
| Map/floor-plan indicators | [Workspace](Evidence/workspace.png) |
|
||||
| Resized panels | [Dividers](Evidence/resized-panels.png), [PWA](Evidence/pwa-resized-panels.png) |
|
||||
| Representative light/dark themes | [Light](Evidence/theme-modern-light.png), [dark](Evidence/theme-modern-dark.png) |
|
||||
| Large hierarchy | [1,000 locations](Evidence/large-hierarchy.png), [PWA](Evidence/pwa-large-hierarchy.png) |
|
||||
|
||||
Additional screenshots cover PlotDirector, warm light/dark, rose pink and baby blue themes.
|
||||
|
||||
## Known boundaries
|
||||
|
||||
Geography confirmations are not regenerated by quick edits or inherited during merge. Existing
|
||||
explicit geography review remains available. Location images do not currently exist in the model.
|
||||
Map/plan navigation uses current route contracts; no editor geometry or interaction is redesigned.
|
||||
Description editing is explicit Save/Cancel; merge and archive have no workspace Undo. Undo rejects
|
||||
stale records or unavailable original parents rather than overwriting later changes. Bulk commands
|
||||
are bounded at 2,000 records, consistent with the Characters convention.
|
||||
|
||||
Non-hierarchical sensory/travel relationships remain on the established Details editor. Temporary
|
||||
asset/scene circumstances stay separate from permanent containment; no temporal tracking system is
|
||||
added. Full descriptions are preserved; very large card collections render all matches.
|
||||
|
||||
User help: [Locations overview](../../PlotLine/Help/Articles/Locations/Overview.md).
|
||||
30
Docs/Locations/Evidence/after-cold-release.json
Normal file
@ -0,0 +1,30 @@
|
||||
[
|
||||
{
|
||||
"count": 50,
|
||||
"loadMs": 1424,
|
||||
"expandMs": 134,
|
||||
"searchMs": 115,
|
||||
"assignments": 7
|
||||
},
|
||||
{
|
||||
"count": 200,
|
||||
"loadMs": 350,
|
||||
"expandMs": 167,
|
||||
"searchMs": 142,
|
||||
"assignments": 6
|
||||
},
|
||||
{
|
||||
"count": 500,
|
||||
"loadMs": 399,
|
||||
"expandMs": 332,
|
||||
"searchMs": 131,
|
||||
"assignments": 6
|
||||
},
|
||||
{
|
||||
"count": 1000,
|
||||
"loadMs": 416,
|
||||
"expandMs": 593,
|
||||
"searchMs": 163,
|
||||
"assignments": 6
|
||||
}
|
||||
]
|
||||
50
Docs/Locations/Evidence/after-large.json
Normal file
@ -0,0 +1,50 @@
|
||||
[
|
||||
{
|
||||
"count": 50,
|
||||
"loadMs": 266,
|
||||
"expandMs": 102,
|
||||
"searchMs": 108,
|
||||
"detailsMs": 66,
|
||||
"bulkMs": 175,
|
||||
"reparentMs": 236,
|
||||
"renameMs": 98,
|
||||
"cardsMs": 116,
|
||||
"assignments": 7
|
||||
},
|
||||
{
|
||||
"count": 200,
|
||||
"loadMs": 292,
|
||||
"expandMs": 167,
|
||||
"searchMs": 148,
|
||||
"detailsMs": 62,
|
||||
"bulkMs": 273,
|
||||
"reparentMs": 354,
|
||||
"renameMs": 106,
|
||||
"cardsMs": 200,
|
||||
"assignments": 6
|
||||
},
|
||||
{
|
||||
"count": 500,
|
||||
"loadMs": 317,
|
||||
"expandMs": 334,
|
||||
"searchMs": 126,
|
||||
"detailsMs": 80,
|
||||
"bulkMs": 498,
|
||||
"reparentMs": 528,
|
||||
"renameMs": 113,
|
||||
"cardsMs": 436,
|
||||
"assignments": 6
|
||||
},
|
||||
{
|
||||
"count": 1000,
|
||||
"loadMs": 445,
|
||||
"expandMs": 636,
|
||||
"searchMs": 163,
|
||||
"detailsMs": 106,
|
||||
"bulkMs": 873,
|
||||
"reparentMs": 297,
|
||||
"renameMs": 133,
|
||||
"cardsMs": 1248,
|
||||
"assignments": 6
|
||||
}
|
||||
]
|
||||
BIN
Docs/Locations/Evidence/attribute-assignment.png
Normal file
|
After Width: | Height: | Size: 191 KiB |
22
Docs/Locations/Evidence/before.json
Normal file
@ -0,0 +1,22 @@
|
||||
[
|
||||
{
|
||||
"count": 50,
|
||||
"loadMs": 257,
|
||||
"dom": 1803
|
||||
},
|
||||
{
|
||||
"count": 200,
|
||||
"loadMs": 230,
|
||||
"dom": 3904
|
||||
},
|
||||
{
|
||||
"count": 500,
|
||||
"loadMs": 410,
|
||||
"dom": 8104
|
||||
},
|
||||
{
|
||||
"count": 1000,
|
||||
"loadMs": 609,
|
||||
"dom": 15104
|
||||
}
|
||||
]
|
||||
BIN
Docs/Locations/Evidence/before.png
Normal file
|
After Width: | Height: | Size: 114 KiB |
BIN
Docs/Locations/Evidence/bulk-assignment.png
Normal file
|
After Width: | Height: | Size: 192 KiB |
BIN
Docs/Locations/Evidence/cards.png
Normal file
|
After Width: | Height: | Size: 239 KiB |
BIN
Docs/Locations/Evidence/context-menu.png
Normal file
|
After Width: | Height: | Size: 226 KiB |
BIN
Docs/Locations/Evidence/create-child.png
Normal file
|
After Width: | Height: | Size: 218 KiB |
6
Docs/Locations/Evidence/database-performance.txt
Normal file
@ -0,0 +1,6 @@
|
||||
PASS Dapper read: 50 synthetic + 69 existing clone records, old list 25.5 ms (119 rows), new six-result directory 82.1 ms
|
||||
PASS Dapper read: 200 synthetic + 69 existing clone records, old list 41.2 ms (269 rows), new six-result directory 18.3 ms
|
||||
PASS Dapper read: 500 synthetic + 69 existing clone records, old list 55.9 ms (569 rows), new six-result directory 41.2 ms
|
||||
PASS Dapper read: 1000 synthetic + 69 existing clone records, old list 71.3 ms (1069 rows), new six-result directory 68.1 ms
|
||||
PASS Dapper create result, exact-version assignment/Undo, directory projections including entry/exit-only usage, and rollback; no live data changed.
|
||||
PASS actual typed ProjectBackup export and generic location JSON restore retain classification; restore rolled back.
|
||||
31
Docs/Locations/Evidence/database-qualification.json
Normal file
@ -0,0 +1,31 @@
|
||||
{
|
||||
"status": "passed",
|
||||
"runs": [
|
||||
{
|
||||
"clone": 4,
|
||||
"starting_schema_sha256": "dc6afafb8c25fd63d98a97d016402ddda7474fdfa296a18722b3ddc2569ecb91",
|
||||
"resulting_schema_sha256": "53a1d38ea01c4a0c6f601dc280a3dbdf706060b05b3ce9e9dd45ca83312ccbd4",
|
||||
"executed": 1,
|
||||
"unchanged_original_tables": 208,
|
||||
"existing_canonical_types_unchanged": true,
|
||||
"only_data_addition": "four canonical location types",
|
||||
"integrity": {
|
||||
"integrity": true,
|
||||
"constraint_violations": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"clone": 5,
|
||||
"starting_schema_sha256": "dc6afafb8c25fd63d98a97d016402ddda7474fdfa296a18722b3ddc2569ecb91",
|
||||
"resulting_schema_sha256": "53a1d38ea01c4a0c6f601dc280a3dbdf706060b05b3ce9e9dd45ca83312ccbd4",
|
||||
"executed": 1,
|
||||
"unchanged_original_tables": 208,
|
||||
"existing_canonical_types_unchanged": true,
|
||||
"only_data_addition": "four canonical location types",
|
||||
"integrity": {
|
||||
"integrity": true,
|
||||
"constraint_violations": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
BIN
Docs/Locations/Evidence/details-edit.png
Normal file
|
After Width: | Height: | Size: 198 KiB |
BIN
Docs/Locations/Evidence/hierarchy.png
Normal file
|
After Width: | Height: | Size: 192 KiB |
BIN
Docs/Locations/Evidence/hover-reparent.png
Normal file
|
After Width: | Height: | Size: 190 KiB |
BIN
Docs/Locations/Evidence/inline-rename.png
Normal file
|
After Width: | Height: | Size: 197 KiB |
BIN
Docs/Locations/Evidence/large-hierarchy.png
Normal file
|
After Width: | Height: | Size: 186 KiB |
BIN
Docs/Locations/Evidence/pwa-cards.png
Normal file
|
After Width: | Height: | Size: 284 KiB |
BIN
Docs/Locations/Evidence/pwa-large-hierarchy.png
Normal file
|
After Width: | Height: | Size: 215 KiB |
30
Docs/Locations/Evidence/pwa-performance.json
Normal file
@ -0,0 +1,30 @@
|
||||
[
|
||||
{
|
||||
"count": 50,
|
||||
"loadMs": 302,
|
||||
"expandMs": 130,
|
||||
"searchMs": 127,
|
||||
"assignments": 7
|
||||
},
|
||||
{
|
||||
"count": 200,
|
||||
"loadMs": 375,
|
||||
"expandMs": 210,
|
||||
"searchMs": 131,
|
||||
"assignments": 6
|
||||
},
|
||||
{
|
||||
"count": 500,
|
||||
"loadMs": 451,
|
||||
"expandMs": 416,
|
||||
"searchMs": 163,
|
||||
"assignments": 6
|
||||
},
|
||||
{
|
||||
"count": 1000,
|
||||
"loadMs": 729,
|
||||
"expandMs": 851,
|
||||
"searchMs": 161,
|
||||
"assignments": 6
|
||||
}
|
||||
]
|
||||
BIN
Docs/Locations/Evidence/pwa-resized-panels.png
Normal file
|
After Width: | Height: | Size: 232 KiB |
BIN
Docs/Locations/Evidence/pwa-theme-modern-dark.png
Normal file
|
After Width: | Height: | Size: 225 KiB |
BIN
Docs/Locations/Evidence/pwa-workspace.png
Normal file
|
After Width: | Height: | Size: 190 KiB |
BIN
Docs/Locations/Evidence/reparenting.png
Normal file
|
After Width: | Height: | Size: 196 KiB |
BIN
Docs/Locations/Evidence/resized-panels.png
Normal file
|
After Width: | Height: | Size: 200 KiB |
BIN
Docs/Locations/Evidence/root-drop.png
Normal file
|
After Width: | Height: | Size: 189 KiB |
BIN
Docs/Locations/Evidence/search-context.png
Normal file
|
After Width: | Height: | Size: 187 KiB |
7
Docs/Locations/Evidence/sql-regressions.txt
Normal file
@ -0,0 +1,7 @@
|
||||
PASS bulk branch preservation, root moves, classification, targeted rename, exact undo
|
||||
PASS descendant cycle rejection
|
||||
PASS unavailable parent rejection
|
||||
PASS cross-project parent rejection
|
||||
PASS stale write rejection
|
||||
PASS unauthorized mutation rejection
|
||||
PASS transactional merge preserves conflicting descriptions, source, classification, children, map geometry, floor-plan links, scene assignments, aliases and non-hierarchical relationships
|
||||
BIN
Docs/Locations/Evidence/theme-baby-blue.png
Normal file
|
After Width: | Height: | Size: 189 KiB |
BIN
Docs/Locations/Evidence/theme-modern-dark.png
Normal file
|
After Width: | Height: | Size: 196 KiB |
BIN
Docs/Locations/Evidence/theme-modern-light.png
Normal file
|
After Width: | Height: | Size: 191 KiB |
BIN
Docs/Locations/Evidence/theme-plotdirector.png
Normal file
|
After Width: | Height: | Size: 201 KiB |
BIN
Docs/Locations/Evidence/theme-rose-pink.png
Normal file
|
After Width: | Height: | Size: 189 KiB |
BIN
Docs/Locations/Evidence/theme-warm-dark.png
Normal file
|
After Width: | Height: | Size: 194 KiB |
BIN
Docs/Locations/Evidence/theme-warm-light.png
Normal file
|
After Width: | Height: | Size: 190 KiB |
BIN
Docs/Locations/Evidence/workspace.png
Normal file
|
After Width: | Height: | Size: 175 KiB |
94
Docs/Locations/Workspace.md
Normal file
@ -0,0 +1,94 @@
|
||||
# Locations workspace
|
||||
|
||||
The main directory uses the existing `dbo.Locations` identifiers. `LocationWorkspaceController`
|
||||
reads a flat directory and recorded associations using Dapper and `Location_WorkspaceRead`.
|
||||
The browser builds hierarchy paths and child indexes without a recursive SQL view or per-location
|
||||
queries. The initial MVC request reads the authorised project only. Associated manuscript prose
|
||||
is never loaded. Existing Details/Edit, archive, scene assignment and relationship forms remain.
|
||||
|
||||
The three panels reuse `workspace-surface.js` (a Locations profile), shared theme tokens,
|
||||
`PlotDirectorContextMenus`, `PlotDirector.toast` and `ContextWorkspaceNotifications.Invalidate`.
|
||||
Browser and installed PWA use the same commands and same-window links. Nothing changes narrative
|
||||
focus or invokes AI/geocoding. Location images are not currently a canonical location attribute;
|
||||
there are no fabricated image placeholders.
|
||||
|
||||
## Canonical attributes
|
||||
|
||||
Existing types: Country, Region, Town, Village, Street, Building, Floor, Room, Outdoor Area,
|
||||
Vehicle Interior, Landmark and Other. Migration 335 adds Planet, District, Natural Feature and
|
||||
City without changing existing IDs or values. Existing aliases, description, Quick Add inclusion,
|
||||
Word Companion exclusion and detection priority are retained. Quick Add and detection exclusion
|
||||
are suitable quick switches; numeric detection priority remains in the full form.
|
||||
|
||||
`Locations.Classification` is optional: NULL (Unclassified), Real, Fictional, Fictionalised.
|
||||
It is independent of type. No existing location is classified automatically. Classification
|
||||
is edited in the workspace and preserved by existing full forms, which do not update this column.
|
||||
`LocationItem.Classification` and the existing export selector preserve it through project backups;
|
||||
the generic restore contract already accepts the additional column. `LocationWorkspaceIcons` maps
|
||||
canonical labels onto opt-in shared ribbon icons without changing other consumers.
|
||||
|
||||
## Mutation and hierarchy safety
|
||||
|
||||
`Location_WorkspaceAssign` validates project role (Owner/Collaborator), active project/location,
|
||||
canonical values, parent membership and optimistic `UpdatedDate` versions inside a transaction.
|
||||
Only the selected attribute is written. Permanent containment can be arbitrarily nested.
|
||||
The final parent graph is checked on the server, including Undo; cycles and self/descendant moves
|
||||
are rejected. Root is NULL. For ordinary bulk moves, selected descendants whose ancestor is also
|
||||
selected are omitted, retaining complete branches. Undo restores only the roots actually changed.
|
||||
No-op assignments do not update timestamps or audit history. Unavailable ancestors are shown as
|
||||
“Parent unavailable”; original parent IDs are retained, and the Root filter means an actual NULL
|
||||
parent. Recorded unavailable types remain visible in Details rather than being relabelled Unclassified.
|
||||
|
||||
Each mutation records the established project audit. Audit result sets are captured internally.
|
||||
The response returns exact post-save versions and changed values. A user-bound, protected receipt
|
||||
expires after ten minutes; Undo compares the current version before applying the original value.
|
||||
A stale receipt cannot overwrite later edits. The browser updates its directory, counts and details
|
||||
without navigating/reloading. Live invalidations refresh other windows; dirty descriptions defer
|
||||
refresh. Explicit Save/Cancel and discard confirmation protect unsaved descriptions.
|
||||
|
||||
`Location_WorkspaceCreate` validates ownership/parent and creates a child transactionally from only
|
||||
a name. Naming matches existing forms (required, 200 characters; repeated names are allowed).
|
||||
Aliases and manuscript text are never rewritten by rename. Traditional creation remains available.
|
||||
|
||||
## Merge
|
||||
|
||||
Workspace merge is explicit, reviewed and has no Undo. The author chooses the survivor and sees
|
||||
both descriptions and type/classification conflicts. `Location_WorkspaceMerge` validates both
|
||||
record versions and the editing role, then wraps the established `Location_Merge` transaction.
|
||||
That operation transfers scene/character/asset references, children, aliases, floor plans,
|
||||
import references and non-hierarchical links; direct source/survivor links are archived. The forward-only extension to the established merge
|
||||
also transfers MapFeatures.LocationID and increments affected map revisions without changing any
|
||||
feature ID or geometry. Different descriptions are retained together with a source label.
|
||||
An unclassified survivor inherits source classification; otherwise survivor classification wins.
|
||||
Survivor name, type and parent remain. Source records and original information stay archived.
|
||||
Geographic confirmation evidence stays with its original record and is not inferred for the survivor.
|
||||
The older full merge form remains available and receives the same preservation safeguards. The
|
||||
workspace additionally previews conflicts and rejects records changed since review.
|
||||
|
||||
## Filters, associations and preferences
|
||||
|
||||
Map/floor-plan indicators come from MapFeatures and direct plan/floor/block links. Multiple links
|
||||
are listed individually rather than selecting one implicitly. Map links open the existing selected
|
||||
map; floor-plan links open its existing editor. Location/feature reveal inside those editors is
|
||||
limited to their current route contracts. Scene use counts distinct recorded primary, character current/entry/exit and asset scene assignments;
|
||||
it is not textual name matching. Relationship, explicitly located character and current asset
|
||||
counts come from authoritative records; full evidence remains on Details. Derived filters are
|
||||
read-only. Branch-filter results retain ancestors without modifying permanent expansion state.
|
||||
|
||||
`pd.locations.workspace.v1.<user>.<project>` stores view, sorting, expanded branches, collapsed
|
||||
panels and expanded attribute groups. The shared divider key is independently scoped to the same
|
||||
user/project. Dragging dividers writes local preferences only on completion. Narrow displays stack
|
||||
the panels, without horizontal page overflow. Tree keyboard commands: arrows, Home/End, Enter,
|
||||
Space selection, F2 rename, Shift+F10/context-menu key. Shared menus handle focus/dismissal.
|
||||
|
||||
## Boundaries and limitations
|
||||
|
||||
Permanent containment is separate from sensory/travel relationships and `SceneAssetLocations` /
|
||||
asset current location. A vehicle temporarily parked somewhere must not become its permanent child
|
||||
unless the author explicitly chooses that hierarchy. No temporal asset tracking is added.
|
||||
No Context, Maps, Floor Plans, Assets, Characters or Names workspace is redesigned.
|
||||
|
||||
Geography confirmations are not regenerated after workspace changes. Existing explicit geography
|
||||
review remains available. Large trees render only expanded branches; card view renders matching
|
||||
cards, with complete descriptions and variable height. There is no card virtualization.
|
||||
See `Acceptance.md` for measured verification and remaining limitations.
|
||||
9
PlotLine.Tests/Browser/locations-workspace-dev-pwa.cjs
Normal file
@ -0,0 +1,9 @@
|
||||
// Actual installed Development PWA; reads only the dedicated fixture left by locations-workspace-dev.cjs.
|
||||
const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
const base='https://dev.plotdirector.com',file=process.argv[2];if(!file?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated private identity required');const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-'));assert(identity.ProjectID);
|
||||
(async()=>{const profile=fs.mkdtempSync('/tmp/pd-locations-dev-pwa-'),context=await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}),cdp=await context.browser().newBrowserCDPSession(),manifestId=base+'/Projects';try{
|
||||
const tab=context.pages()[0];await tab.goto(base+'/Account/Login');await tab.locator('[name=Email]').fill(identity.Email);await tab.locator('[name=Password]').fill(identity.Password);await tab.locator('form button[type=submit]').click();await tab.waitForURL(base+'/Projects');
|
||||
await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/Projects'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=context.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+`/Locations?projectId=${identity.ProjectID}`});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));await page.locator('[data-location-records][aria-busy=false]').waitFor();const row=page.locator('[data-location-id]').first();await row.locator('[data-location-name]').click();assert.equal(await page.locator('[data-details]').getByRole('combobox',{name:'Classification',exact:true}).inputValue(),'Fictional');await row.getByRole('button',{name:/Actions for/}).click();await page.getByRole('menu').first().waitFor();await page.screenshot({path:'/tmp/pd-locations-evidence/development-pwa-context.png'});await page.keyboard.press('Escape');
|
||||
await page.getByRole('button',{name:'Cards',exact:true}).click();assert(await page.getByText('Author-controlled synthetic description.',{exact:true}).count());await page.screenshot({path:'/tmp/pd-locations-evidence/development-pwa-cards.png'});const pages=context.pages().length;await page.locator('[data-details]').getByRole('link',{name:'Full details',exact:true}).click();await page.waitForURL(/\/Locations\/Details\/\d+/);assert.equal(context.pages().length,pages,'same-window navigation');
|
||||
fs.writeFileSync('/tmp/pd-locations-evidence/development-pwa-smoke.json',JSON.stringify({status:'passed',target:'Development',installed:true,checks:['real installed Chromium PWA','authenticated workspace directory','saved classification','shared context menu','card description','same-window Location Details navigation']},null,2));console.log('PASS actual authenticated installed Development PWA, saved state, context menu, cards and same-window details.');
|
||||
}finally{await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await context.close();fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
27
PlotLine.Tests/Browser/locations-workspace-dev.cjs
Normal file
@ -0,0 +1,27 @@
|
||||
// Explicit Development-only operational smoke. Uses only a dedicated disposable identity/project.
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
const base='https://dev.plotdirector.com',file=process.argv[2],setup=process.argv.includes('--setup');
|
||||
if(!file?.startsWith('/tmp/pd-dev-browser-'))throw Error('Private dedicated identity file required.');
|
||||
const identity=JSON.parse(fs.readFileSync(file,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-')&&identity.Email.endsWith('@example.invalid'));
|
||||
(async()=>{const browser=await chromium.launch(),context=await browser.newContext({viewport:{width:1440,height:1000}}),page=await context.newPage();try{
|
||||
await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await page.locator('form button[type=submit]').click();await page.waitForURL(base+'/Projects');
|
||||
if(setup){assert(!identity.ProjectID);await page.goto(base+'/Projects/Create');await page.locator('[name=ProjectName]').fill('Locations acceptance · disposable world');await page.getByRole('button',{name:'Save project',exact:true}).click();await page.waitForURL(/\/Projects\/Details\/\d+/);identity.ProjectID=Number(page.url().split('/').pop());await page.goto(base+`/Books/Create?projectId=${identity.ProjectID}`);await page.locator('[name=BookTitle]').fill('Locations acceptance fixture');await page.getByRole('button',{name:'Save book',exact:true}).click();await page.waitForURL(/\/Books\/Details\/\d+/);identity.BookID=Number(page.url().split('/').pop());fs.writeFileSync(file,JSON.stringify(identity,null,2),{mode:0o600});console.log('PASS dedicated fixture project/book created through normal Development forms.');return;}
|
||||
assert(identity.ProjectID&&identity.BookID);const q=`projectId=${identity.ProjectID}`;
|
||||
const api=async(action,body)=>page.evaluate(async({action,body})=>{const response=await fetch('/LocationWorkspace/'+action,{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':document.querySelector('[data-location-token] [name=__RequestVerificationToken]').value},body:JSON.stringify(body)});return{status:response.status,body:await response.json()};},{action,body});
|
||||
const directory=async()=>{const response=await page.request.get(base+`/LocationWorkspace/Directory?${q}`);assert.equal(response.status(),200);return response.json();};
|
||||
await page.goto(base+`/Locations?${q}`);await page.locator('[data-location-records][aria-busy=false]').waitFor();let data=await directory();assert.equal(data.locations.length,0,'only an empty dedicated project may be populated');
|
||||
const created=await api('Create',{projectId:identity.ProjectID,name:'Meridian acceptance',parentId:null});assert.equal(created.status,200);const id=created.body.id;await page.reload();const row=()=>page.locator(`[data-location-id="${id}"]`);await row().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('Observatory acceptance');await page.getByRole('textbox',{name:'New location name'}).press('Enter');await page.locator('[data-location-dialog]').waitFor({state:'hidden'});data=await directory();const child=data.locations.find(r=>r.name==='Observatory acceptance');assert.equal(child.parent,id);
|
||||
await row().locator('[data-location-name]').click();const peer=await context.newPage();await peer.goto(base+`/Locations?${q}`);await peer.locator('[data-location-records][aria-busy=false]').waitFor();
|
||||
await page.locator('[data-details]').getByRole('combobox',{name:'Classification',exact:true}).selectOption('Fictional');await page.waitForTimeout(250);data=await directory();assert.equal(data.locations.find(r=>r.id===id).classification,'Fictional');
|
||||
await peer.locator(`[data-location-id="${id}"] [aria-label="Fictional"]`).waitFor({timeout:20000});
|
||||
await row().focus();await page.keyboard.press('F2');await row().getByRole('textbox',{name:'Location name'}).fill('Meridian renamed');await row().getByRole('textbox',{name:'Location name'}).press('Enter');await row().getByRole('button',{name:'Meridian renamed',exact:true}).waitFor();data=await directory();assert.equal(data.locations.find(r=>r.id===child.id).parent,id);
|
||||
await row().locator('[data-location-name]').click();await page.getByRole('button',{name:'Edit description',exact:true}).click();await page.getByRole('textbox',{name:'Location description'}).fill('Author-controlled synthetic description.');await page.locator('[data-details]').getByRole('button',{name:'Save',exact:true}).click();await page.waitForTimeout(200);data=await directory();assert.equal(data.locations.find(r=>r.id===id).description,'Author-controlled synthetic description.');
|
||||
const bulk=await api('Assign',{projectId:identity.ProjectID,attribute:'quickAdd',changes:data.locations.map(r=>({id:r.id,value:'1',version:r.version}))});assert.equal(bulk.status,200);assert.equal(bulk.body.changes.length,2);assert(bulk.body.undoToken);const restored=await api('Undo',{token:bulk.body.undoToken});assert.equal(restored.status,200);data=await directory();assert(data.locations.every(r=>r.quickAdd==='0'));
|
||||
const current=data.locations.find(r=>r.id===id),bad=await api('Assign',{projectId:identity.ProjectID,attribute:'parent',changes:[{id,value:String(child.id),version:current.version}]});assert.equal(bad.status,409);const unauthorised=await api('Assign',{projectId:2147483647,attribute:'classification',changes:[{id,value:'Real',version:current.version}]});assert.equal(unauthorised.status,403);
|
||||
const out='/tmp/pd-locations-evidence';await page.screenshot({path:out+'/development-workspace.png'});
|
||||
const checks=[];for(const route of [`/Characters?${q}`,`/Names?${q}`,`/RelationshipMap?${q}`,`/Maps?${q}`,`/FloorPlans?${q}`,`/StoryAssets?${q}`,`/Locations/Details/${id}`,`/Locations/Edit/${id}`,`/Writer?${q}&bookId=${identity.BookID}`]){const response=await page.goto(base+route);assert.equal(response.status(),200,route);assert(!page.url().includes('/Account/'));checks.push(route.split('?')[0]);}
|
||||
await page.goto(base+`/Locations/Details/${id}`);await page.locator('[name=ToLocationID]').selectOption(String(child.id));await page.locator('[name=Notes]').fill('Disposable non-hierarchical relationship');await page.getByRole('button',{name:'Add relationship',exact:true}).click();await page.waitForLoadState();assert(await page.getByText('Disposable non-hierarchical relationship',{exact:true}).count());
|
||||
await page.goto(base+`/Locations?${q}`);await page.locator('[data-location-records][aria-busy=false]').waitFor();await page.getByRole('button',{name:'Expand all',exact:true}).click();await page.locator(`[data-location-id="${child.id}"]`).getByRole('button',{name:'Actions for Observatory acceptance'}).click();await page.getByRole('menuitem',{name:'Merge with another location…',exact:true}).click();await page.getByRole('combobox',{name:'Surviving location'}).selectOption(String(id));await page.locator('[data-location-dialog] input[type=checkbox]').check();await page.locator('[data-dialog-save]').click();await page.locator('[data-location-dialog]').waitFor({state:'hidden'});data=await directory();assert.equal(data.locations.length,1);assert.equal(data.locations[0].id,id);assert.equal(data.locations[0].description,'Author-controlled synthetic description.');
|
||||
fs.writeFileSync(out+'/development-smoke.json',JSON.stringify({status:'passed',target:'Development',checks:['real Directory/Create/Assign/Undo/Merge endpoints','bulk assignment and protected Undo','normal non-hierarchical relationship form','reviewed merge archives source and retains survivor','inline child Enter-save','classification','inline rename preserves child identifiers','description save','server cycle rejection','cross-project mutation rejection','actual second-window live invalidation',...checks]},null,2));console.log('PASS authenticated Development workspace mutations, hierarchy safeguards, cross-window live updates and related route smoke; disposable data only.');
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
58
PlotLine.Tests/Browser/locations-workspace.cjs
Normal file
@ -0,0 +1,58 @@
|
||||
// Actual compiled Locations Razor + shared shell. All mutations use synthetic HTTP fixtures.
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
const installed=process.argv.includes('--installed'),origin='http://127.0.0.1:5238',out='/tmp/pd-locations-evidence'+(installed?'/pwa':'');fs.mkdirSync(out,{recursive:true});
|
||||
(async()=>{const profile=installed?fs.mkdtempSync('/tmp/pd-locations-pwa-'):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1440,height:1000}}):null,browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null,manifestId=origin+'/Projects',results=[];if(installed){await persistent.pages()[0].goto(origin+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:origin+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});}async function newPage(){if(!installed)return browser.newPage({viewport:{width:1440,height:1000}});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:origin+'/fixture?page=calendar-test'});const page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return page;}try{for(const count of process.argv.includes('--persistence-only')?[50]:[50,200,500,1000]){
|
||||
const page=await newPage(),errors=[],timings={};page.on('pageerror',e=>errors.push(e.message));
|
||||
const types=await (await page.request.get(`${origin}/locations-workspace-types-fixture`)).json();let clock=0,requests=[],undo=new Map(),rejectNext=false,delayDirectory=false,releaseDirectory=null;const records=Array.from({length:count},(_,i)=>({id:i+1,name:['Meridian','Northern coast','Port Halcyon','Observatory','Reading room'][i]||`Location ${String(i+1).padStart(3,'0')}`,parent:i===0||i%13===0?null:i<10?i:Math.floor((i-1)/12)*12+1,type:String(i%9+1),typeName:types[i%9].label,classification:i%4===0?'Fictional':'',description:i%5===0?'':('Salt air drifts through the open windows. The old charts record a coastline changed by generations of storms. ').repeat(i%7+1),quickAdd:'0',detection:'0',version:`v${clock++}`,aliases:i===4?['Quiet study']:[],maps:i%5===0?[{id:1,name:'Coast chart'}]:[],floors:i%7===0?[{id:2,name:'Observatory floors'}]:[],scenes:i%3}));
|
||||
records[count-1].parent=2147483647;
|
||||
records[0].maps.push({id:2,name:'Northern chart'});records[0].floors.push({id:3,name:'Annex floor plan'});
|
||||
if(count>=500){for(let i=count-100;i<count;i++)records[i].parent=i===count-100?1:i;records[count-2].name='Reading room';records[count-1].name='Reading room';}
|
||||
await page.route('**/LocationWorkspace/Directory?*',async r=>{const snapshot=structuredClone(records);if(delayDirectory){delayDirectory=false;await new Promise(resolve=>releaseDirectory=resolve);}await r.fulfill({json:{canEdit:true,types,locations:snapshot}});});
|
||||
await page.route('**/LocationWorkspace/Assign',async route=>{assert(route.request().headers().requestverificationtoken);const input=route.request().postDataJSON();requests.push(input);if(rejectNext){rejectNext=false;return route.fulfill({status:409,json:{message:'Simulated concurrent edit rejected.'}});}let changes=input.changes;const ids=new Set(changes.map(c=>c.id));if(input.attribute==='parent')changes=changes.filter(c=>{let p=records.find(r=>r.id===c.id).parent;const seen=new Set();while(p&&!seen.has(p)){if(ids.has(p))return false;seen.add(p);p=records.find(r=>r.id===p)?.parent;}return true;});const previous=[],changed=[];for(const c of changes){const r=records.find(r=>r.id===c.id);if(r.version!==c.version)return route.fulfill({status:409,json:{message:'Changed in another window.'}});previous.push({id:r.id,value:r[input.attribute],version:r.version});r[input.attribute]=input.attribute==='parent'?(c.value?Number(c.value):null):c.value;r.version=`v${clock++}`;changed.push({id:r.id,value:c.value,version:r.version});}const token=`u${clock}`;undo.set(token,{attribute:input.attribute,previous});await route.fulfill({json:{saved:true,changes:changed,attribute:input.attribute,undoToken:token}});});
|
||||
await page.route('**/LocationWorkspace/Undo',async route=>{const receipt=undo.get(route.request().postDataJSON().token),changes=[];for(const old of receipt.previous){const r=records.find(r=>r.id===old.id);r[receipt.attribute]=old.value;r.version=`v${clock++}`;changes.push({id:r.id,value:old.value?.toString()||'',version:r.version});}await route.fulfill({json:{saved:true,changes,attribute:receipt.attribute}});});
|
||||
await page.route('**/LocationWorkspace/Create',async route=>{const input=route.request().postDataJSON(),id=records.length+1;records.push({id,name:input.name,parent:input.parentId,type:'',classification:'',description:'',quickAdd:'0',detection:'0',version:`v${clock++}`,aliases:[],maps:[],floors:[],scenes:0});await route.fulfill({json:{id}});});
|
||||
const shot=async name=>{if(count===50){await page.evaluate(()=>document.querySelectorAll('[data-toast-host] button[aria-label^=Dismiss]').forEach(b=>b.click()));await page.screenshot({path:`${out}/${name}.png`});}};const row=id=>page.locator(`[data-location-id="${id}"]`),attribute=(a,v)=>page.locator(`[data-attribute="${a}"][data-value="${v}"]`);
|
||||
const start=performance.now();await page.goto(`${origin}/locations-workspace-fixture?count=${count}`);await row(1).waitFor();const loadMs=Math.round(performance.now()-start);const detailsStart=performance.now();await row(1).locator('[data-location-name]').click();timings.detailsMs=Math.round(performance.now()-detailsStart);assert.equal(await page.locator('[data-related] a[href^="/Maps"]').count(),2);assert.equal(await page.locator('[data-related] a[href^="/FloorPlans"]').count(),2);assert.equal(await page.locator('[data-related] a[target]').count(),0);await shot('workspace');
|
||||
const expandStart=performance.now();await page.getByRole('button',{name:'Expand all',exact:true}).click();await row(5).waitFor();const expandMs=Math.round(performance.now()-expandStart);assert.match(await row(count).getAttribute('title'),/Parent unavailable/);await shot('hierarchy');if(count===50){
|
||||
const parents=records.map(r=>r.parent);await page.locator('[data-sort]').selectOption('desc');const order=await page.locator('[data-location-id]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.locationId)));for(const r of records)if(r.parent)assert(order.indexOf(r.parent)<order.indexOf(r.id));assert.deepEqual(records.map(r=>r.parent),parents);await page.locator('[data-sort]').selectOption('asc');
|
||||
await row(1).focus();await page.keyboard.press('Space');assert(await row(1).locator('[data-select-location]').isChecked());await page.keyboard.press('Space');assert(!(await row(1).locator('[data-select-location]').isChecked()));
|
||||
}
|
||||
const drag=async(source,target)=>{await source.dragTo(target);await page.waitForTimeout(100);};
|
||||
await drag(attribute('type','6').locator('button').first(),row(1));await page.waitForFunction(()=>document.querySelector('[data-undo]').hidden===false);assert.equal(records[0].type,'6');await shot('attribute-assignment');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(60);assert.equal(records[0].type,'1');
|
||||
if(count===50){await page.evaluate(()=>{window.fixtureHints={};document.dispatchEvent(new CustomEvent('pd-presence-connection',{detail:{on:(name,fn)=>window.fixtureHints[name]=fn,onreconnected:()=>{}}}));});delayDirectory=true;await page.evaluate(()=>{const handlers=Object.values(window.PlotDirectorPresenceConnection||{}).find(v=>v&&typeof v==='object'&&Array.isArray(v.contextinvalidated))?.contextinvalidated;if(handlers?.length)for(const handler of handlers)handler({projectId:7});else if(window.fixtureHints.ContextInvalidated)window.fixtureHints.ContextInvalidated({projectId:7});else throw Error('No live invalidation handler registered.');});for(let attempt=0;!releaseDirectory&&attempt<50;attempt++)await page.waitForTimeout(20);assert(releaseDirectory,'live invalidation requests fresh data');await page.waitForTimeout(30);await drag(attribute('type','6').locator('button').first(),row(1));assert.equal(records[0].type,'6');releaseDirectory();await page.waitForTimeout(150);assert.equal(await row(1).getByRole('img',{name:'Room',exact:true}).count(),1);await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(100);}
|
||||
const noOpRequests=requests.length;await drag(attribute('type','1').locator('button').first(),row(1));assert.equal(requests.length,noOpRequests);rejectNext=true;await drag(attribute('type','6').locator('button').first(),row(1));assert.equal(records[0].type,'1');assert.match(await page.locator('[data-workspace-error]').textContent(),/concurrent/);
|
||||
await row(2).locator('[data-select-location]').check();await row(3).locator('[data-select-location]').check();const bulkStart=performance.now();await attribute('classification','Real').getByRole('button',{name:/Assign/}).click();await page.waitForTimeout(100);assert.equal(records[1].classification,'Real');assert.equal(records[2].classification,'Real');timings.bulkMs=Math.round(performance.now()-bulkStart);await shot('bulk-assignment');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(60);assert.equal(records[1].classification,'');
|
||||
if(count===50){
|
||||
await row(1).locator('[data-expand-id]').click();const from=await row(14).locator('[data-drag-location]').boundingBox(),to=await row(1).boundingBox();
|
||||
await page.mouse.move(from.x+from.width/2,from.y+from.height/2);await page.mouse.down();await page.mouse.move(from.x+from.width/2+9,from.y+from.height/2,{steps:3});await page.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:10});await page.waitForTimeout(850);assert.equal(await row(1).getAttribute('aria-expanded'),'true');await shot('hover-reparent');await page.mouse.move(to.x+to.width/2+1,to.y+to.height/2);await page.mouse.up();await page.waitForTimeout(150);assert.equal(records[13].parent,1);await row(14).locator('[data-drag-location]').dragTo(page.locator('[data-root-drop]'));await page.waitForTimeout(150);assert.equal(records[13].parent,null);await shot('root-drop');
|
||||
const beforeInvalid=requests.length;await row(1).locator('[data-drag-location]').dragTo(row(11));await page.waitForTimeout(80);assert.equal(requests.length,beforeInvalid);assert.equal(records[0].parent,null);
|
||||
}
|
||||
await page.locator('[data-clear-selection]').click();const reparentStart=performance.now();await row(5).locator('[data-drag-location]').dragTo(row(3));await page.waitForTimeout(100);assert.equal(records[4].parent,3);assert.equal(records[5].parent,5);timings.reparentMs=Math.round(performance.now()-reparentStart);await shot('reparenting');await page.getByRole('button',{name:'Undo',exact:true}).first().click();await page.waitForTimeout(100);assert.equal(records[4].parent,4);
|
||||
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');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){
|
||||
const fictional=attribute('classification','Fictional').locator('button').first();await fictional.click();assert(await row(1).isVisible());assert(!(await row(2).count()));const matching=records.filter(r=>r.classification==='Fictional').length;assert.match(await page.locator('[data-result-count]').textContent(),new RegExp('^'+matching+' of '));
|
||||
await page.getByRole('button',{name:'Hierarchy',exact:true}).click();assert.equal(await fictional.getAttribute('aria-pressed'),'true');assert(await row(1).locator('[data-select-location]').isChecked());await page.getByRole('button',{name:'Cards',exact:true}).click();
|
||||
await attribute('classification','Real').getByRole('button',{name:/Assign/}).click();await page.waitForTimeout(100);assert(!(await row(1).count()));assert.equal(records[0].classification,'Real');assert.match(await page.locator('[data-result-count]').textContent(),new RegExp('^'+(matching-1)+' of '));await page.getByRole('button',{name:'Undo',exact:true}).first().click();await row(1).waitFor();
|
||||
await page.locator('[data-clear-filters]').click();await attribute('mapState','yes').locator('button').click();assert.equal(await page.locator('[data-location-id]').count(),records.filter(r=>r.maps.length).length);assert.equal(await attribute('mapState','yes').locator('[data-assign]').count(),0);await page.locator('[data-clear-filters]').click();
|
||||
await page.locator('[data-branch-filter]').click();await page.getByRole('listbox',{name:'Parent location'}).selectOption('1');await page.locator('[data-dialog-save]').click();const inBranch=r=>{const seen=new Set();while(r&&!seen.has(r.id)){if(r.id===1)return true;seen.add(r.id);r=records.find(x=>x.id===r.parent);}return false;};assert.equal(await page.locator('[data-location-id]').count(),records.filter(inBranch).length);await page.locator('[data-clear-filters]').click();
|
||||
}
|
||||
|
||||
await page.getByRole('button',{name:'Hierarchy',exact:true}).click();await page.locator('[data-clear-selection]').click();const divider=page.getByRole('separator',{name:'Resize left panel'});await divider.press('ArrowRight');const right=page.getByRole('separator',{name:'Resize right panel'});await right.press('ArrowLeft');if(count===50)for(const [handle,delta]of [[divider,55],[right,-55]]){const box=await handle.boundingBox(),before=Number(await handle.getAttribute('aria-valuenow'));await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(box.x+box.width/2+delta,box.y+box.height/2,{steps:8});await page.mouse.up();assert(Number(await handle.getAttribute('aria-valuenow'))>=before+50);}await shot('resized-panels');
|
||||
for(const panel of ['attributes','details']){await page.getByRole('button',{name:panel==='attributes'?'Attributes':'Details',exact:true}).click();assert(await page.locator(`.locations-${panel}`).isHidden());await page.getByRole('button',{name:panel==='attributes'?'Attributes':'Details',exact:true}).click();}
|
||||
for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(t=>{document.documentElement.dataset.appTheme=t;document.documentElement.dataset.bsTheme=t.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=t.endsWith('dark')?'dark':'light';},theme);await shot(`theme-${theme}`);}
|
||||
for(const [width,height]of [[1920,1080],[1440,900],[1280,720],[1024,768],[768,1024],[390,844]]){await page.setViewportSize({width,height});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),`no horizontal overflow at ${width}`);}
|
||||
await page.setViewportSize({width:1440,height:1000});if(count===1000)await page.screenshot({path:`${out}/large-hierarchy.png`});if(count===50){
|
||||
const widths=await page.locator('.locations-layout').evaluate(n=>[n.style.getPropertyValue('--workspace-left'),n.style.getPropertyValue('--workspace-right')]);
|
||||
await page.locator('[data-groups]>details').first().evaluate(n=>n.open=false);await page.waitForTimeout(20);
|
||||
await page.getByRole('button',{name:'Cards',exact:true}).click();await page.getByRole('button',{name:'Details',exact:true}).click();await page.reload();await row(1).waitFor();
|
||||
assert(await page.locator('.locations-details').isHidden());assert(await page.locator('.locations-cards').count());assert.equal(await page.locator('[data-groups]>details').first().evaluate(n=>n.open),false);
|
||||
assert.deepEqual(await page.locator('.locations-layout').evaluate(n=>[n.style.getPropertyValue('--workspace-left'),n.style.getPropertyValue('--workspace-right')]),widths);
|
||||
await page.getByRole('button',{name:'Details',exact:true}).click();await page.getByRole('button',{name:'Hierarchy',exact:true}).click();await row(5).waitFor();await page.locator('[data-groups]>details').first().evaluate(n=>n.open=true);
|
||||
}
|
||||
assert.deepEqual(errors,[]);results.push({count,loadMs,expandMs,searchMs,...timings,assignments:requests.length});console.log('PASS',results.at(-1));await page.close();
|
||||
}fs.writeFileSync(`${out}/after.json`,JSON.stringify(results,null,2));}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;});
|
||||
78
PlotLine.Tests/LocationsWorkspaceDatabaseTests.cs
Normal file
@ -0,0 +1,78 @@
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Data;
|
||||
|
||||
internal static class LocationsWorkspaceDatabaseTests
|
||||
{
|
||||
public static async Task Run(string configPath)
|
||||
{
|
||||
using var config=JsonDocument.Parse(await File.ReadAllTextAsync(configPath));
|
||||
var builder=new SqlConnectionStringBuilder(config.RootElement.GetProperty("connection").GetString());
|
||||
if(builder.DataSource!="192.168.10.10,1433"||!builder.InitialCatalog.StartsWith("PlotDirector_Qualification_Locations",StringComparison.Ordinal))throw new InvalidOperationException("Disposable Locations clone required.");
|
||||
using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();
|
||||
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!=builder.InitialCatalog)throw new InvalidOperationException("Wrong database.");
|
||||
var identity=await db.QueryFirstAsync<(int ProjectID,int UserID)>("SELECT TOP(1) p.ProjectID,a.UserID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.IsArchived=0 AND a.IsActive=1 AND a.AccessRole=N'Owner' ORDER BY p.ProjectID");
|
||||
using var transaction=db.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var created=await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate",new{identity.ProjectID,identity.UserID,Name="Dapper workspace contract",ParentID=(int?)null},transaction,commandType:CommandType.StoredProcedure);
|
||||
if(!await db.ExecuteScalarAsync<bool>("SELECT CONVERT(bit,COUNT(*)) FROM dbo.Locations WHERE LocationID=@created AND LocationName=N'Dapper workspace contract'",new{created},transaction))throw new Exception("Create returned an audit identifier instead of the location identifier.");
|
||||
var row=await db.QuerySingleAsync<LocationWorkspaceRecord>("SELECT * FROM dbo.Locations WHERE LocationID=@created",new{created},transaction);
|
||||
var changes=new[]{new LocationWorkspaceController.Change(created,"Fictionalised",row.UpdatedDate.ToString("O"))};
|
||||
var before=(await db.QueryAsync<LocationWorkspaceController.Change>("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(changes)},transaction,commandType:CommandType.StoredProcedure)).ToArray();
|
||||
if(before.Length!=1||before[0].Id!=created||before[0].Value!=""||!DateTime.TryParse(before[0].Version,out var version))throw new Exception("Invalid assignment result/undo receipt.");
|
||||
await db.QueryAsync<LocationWorkspaceController.Change>("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(before),Restore=true},transaction,commandType:CommandType.StoredProcedure);
|
||||
if(await db.ExecuteScalarAsync<string?>("SELECT Classification FROM dbo.Locations WHERE LocationID=@created",new{created},transaction)!=null)throw new Exception("Exact timestamp Undo failed.");
|
||||
var presence=await db.QueryFirstOrDefaultAsync<int?>("SELECT TOP(1) sc.SceneCharacterID FROM dbo.SceneCharacters sc JOIN dbo.Scenes s ON s.SceneID=sc.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0",new{identity.ProjectID},transaction);
|
||||
if(presence is null)throw new Exception("Clone character presence fixture required.");
|
||||
await db.ExecuteAsync("UPDATE dbo.SceneCharacters SET LocationID=NULL,EntryLocationID=@created,ExitLocationID=@created WHERE SceneCharacterID=@presence",new{created,presence},transaction);
|
||||
foreach(var count in new[]{50,200,500,1000})
|
||||
{
|
||||
await db.ExecuteAsync("DELETE FROM dbo.Locations WHERE ProjectID=@ProjectID AND LocationName LIKE N'Dapper performance fixture %'; WITH n AS (SELECT TOP(@count) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS ID FROM sys.all_objects) INSERT dbo.Locations(ProjectID,LocationName,Description) SELECT @ProjectID,CONCAT(N'Dapper performance fixture ',ID),REPLICATE(N'Complete synthetic description. ',20) FROM n",new{identity.ProjectID,count},transaction);
|
||||
var baseline=Stopwatch.StartNew();
|
||||
var previousRows=(await db.QueryAsync<LocationItem>("dbo.Location_ListByProject",new{identity.ProjectID},transaction,commandType:CommandType.StoredProcedure)).ToArray();
|
||||
var baselineMs=baseline.Elapsed.TotalMilliseconds;
|
||||
var watch=Stopwatch.StartNew();
|
||||
using var result=await db.QueryMultipleAsync("dbo.Location_WorkspaceRead",new{identity.ProjectID,identity.UserID},transaction,commandType:CommandType.StoredProcedure);
|
||||
var rows=(await result.ReadAsync<LocationWorkspaceRecord>()).ToArray();
|
||||
await result.ReadAsync<LocationAlias>();await result.ReadAsync<LocationWorkspaceController.Link>();await result.ReadAsync<LocationWorkspaceController.Link>();var usage=(await result.ReadAsync<LocationWorkspaceController.Usage>()).ToArray();await result.ReadAsync<LocationWorkspaceController.Option>();
|
||||
if(!usage.Any(u=>u.LocationID==created&&u.SceneCount==1))throw new Exception("Entry/exit-only assignments were missed or double counted.");
|
||||
if(rows.Count(r=>r.LocationName.StartsWith("Dapper performance fixture "))!=count)throw new Exception("Directory lost fixture rows.");
|
||||
Console.WriteLine($"PASS Dapper read: {count} synthetic + {rows.Length-count} existing clone records, old list {baselineMs:F1} ms ({previousRows.Length} rows), new six-result directory {watch.Elapsed.TotalMilliseconds:F1} ms");
|
||||
}
|
||||
transaction.Rollback();
|
||||
Console.WriteLine("PASS Dapper create result, exact-version assignment/Undo, directory projections including entry/exit-only usage, and rollback; no live data changed.");
|
||||
}
|
||||
catch{try{transaction.Rollback();}catch{}throw;}
|
||||
// Verify the typed export and the existing generic location restore on committed clone-only data.
|
||||
var fixture=await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate",new{identity.ProjectID,identity.UserID,Name="Classification round-trip fixture",ParentID=(int?)null},commandType:CommandType.StoredProcedure);
|
||||
try
|
||||
{
|
||||
var original=await db.QuerySingleAsync<LocationWorkspaceRecord>("SELECT * FROM dbo.Locations WHERE LocationID=@fixture",new{fixture});
|
||||
await db.QueryAsync<LocationWorkspaceController.Change>("dbo.Location_WorkspaceAssign",new{identity.ProjectID,identity.UserID,Attribute="classification",Changes=JsonSerializer.Serialize(new[]{new LocationWorkspaceController.Change(fixture,"Fictionalised",original.UpdatedDate.ToString("O"))})},commandType:CommandType.StoredProcedure);
|
||||
var export=await new ProjectBackupRepository(new Connections(builder.ConnectionString)).GetProjectBackupAsync(identity.ProjectID,identity.UserID)??throw new Exception("Export failed.");
|
||||
var exported=export.Data.Locations.Single(l=>l.LocationID==fixture);
|
||||
if(exported.Classification!="Fictionalised")throw new Exception("Typed project export lost classification.");
|
||||
using var restore=db.BeginTransaction();
|
||||
try
|
||||
{
|
||||
await db.ExecuteAsync("DELETE dbo.Locations WHERE LocationID=@fixture",new{fixture},restore);
|
||||
await db.ExecuteAsync("dbo.ProjectRestore_InsertJsonTable",new{TableName="Locations",JsonPath="$.Data.Locations",JsonData=JsonSerializer.Serialize(new{Data=new{Locations=new[]{exported}}}),identity.ProjectID,ProjectScopedOnly=false},restore,commandType:CommandType.StoredProcedure);
|
||||
if(await db.ExecuteScalarAsync<string>("SELECT Classification FROM dbo.Locations WHERE LocationID=@fixture",new{fixture},restore)!="Fictionalised")throw new Exception("Location restore lost classification.");
|
||||
restore.Rollback();
|
||||
}
|
||||
catch{try{restore.Rollback();}catch{}throw;}
|
||||
Console.WriteLine("PASS actual typed ProjectBackup export and generic location JSON restore retain classification; restore rolled back.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await db.ExecuteAsync("DELETE dbo.ProjectActivity WHERE ProjectID=@ProjectID AND EntityType=N'Location' AND EntityID=@fixture; DELETE dbo.Locations WHERE LocationID=@fixture AND ProjectID=@ProjectID",new{identity.ProjectID,fixture});
|
||||
}
|
||||
}
|
||||
private sealed class Connections(string value):ISqlConnectionFactory { public IDbConnection CreateConnection()=>new SqlConnection(value); }
|
||||
}
|
||||
@ -15,6 +15,7 @@ using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
if(args.Contains("--locations-workspace-database")){await LocationsWorkspaceDatabaseTests.Run(args.Last());return;}
|
||||
if(args.Contains("--shared-focus-concurrent")){await SharedFocusDatabaseTests.Concurrent();return;}
|
||||
if(args.Contains("--shared-focus-cleanup")){await SharedFocusDatabaseTests.Concurrent(true);return;}
|
||||
if(args.Contains("--relationship-workspace")){RelationshipWorkspaceTests.StateAndEditing();Console.WriteLine("PASS main Relationships canonical editing, historical resolution and isolated author-family access");return;}
|
||||
|
||||
110
PlotLine.Tests/Sql/LocationsWorkspace.sql
Normal file
@ -0,0 +1,110 @@
|
||||
-- Run ONLY on a disposable qualification clone after 335. All fixture writes roll back.
|
||||
SET NOCOUNT ON;
|
||||
IF DB_NAME() NOT LIKE N'PlotDirector_Qualification_Locations%' THROW 51000,'Disposable Locations qualification clone required.',1;
|
||||
DECLARE @p int,@u int;
|
||||
SELECT TOP(1) @p=p.ProjectID,@u=a.UserID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE p.IsArchived=0 AND a.IsActive=1 AND a.AccessRole=N'Owner' ORDER BY p.ProjectID;
|
||||
IF @p IS NULL THROW 51000,'An existing clone-only owner fixture is required.',1;
|
||||
DECLARE @scene int=(SELECT TOP(1) s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@p);
|
||||
IF @scene IS NULL THROW 51000,'Clone project scene fixture required.',1;
|
||||
DECLARE @a int,@b int,@c int,@d int,@changes nvarchar(max),@old datetime2,@updated datetime2;
|
||||
BEGIN TRAN;
|
||||
INSERT dbo.Locations(ProjectID,LocationName,Description) VALUES(@p,N'Workspace test root',N'Author prose');SET @a=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Workspace test child',@a);SET @b=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Workspace test grandchild',@b);SET @c=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Workspace destination');SET @d=SCOPE_IDENTITY();
|
||||
SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@d) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@a,@b) FOR JSON PATH);
|
||||
EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes;
|
||||
IF (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@a)<>@d OR (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@b)<>@a OR (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@c)<>@b THROW 51000,'Bulk move flattened a branch.',1;
|
||||
-- Selecting an already-placed ancestor must still protect its selected descendant.
|
||||
SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@d) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@a,@b) FOR JSON PATH);
|
||||
SELECT @old=UpdatedDate FROM dbo.Locations WHERE LocationID=@a;
|
||||
EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes;
|
||||
IF (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@b)<>@a OR (SELECT UpdatedDate FROM dbo.Locations WHERE LocationID=@a)<>@old THROW 51000,'No-op bulk move flattened a branch or changed its version.',1;
|
||||
SELECT @changes=(SELECT LocationID AS Id,N'' 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'parent',@changes;
|
||||
IF EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@a AND ParentLocationID IS NOT NULL) THROW 51000,'Root move failed.',1;
|
||||
SELECT @changes=(SELECT LocationID AS Id,N'Fictional' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID IN(@a,@b) FOR JSON PATH);
|
||||
EXEC dbo.Location_WorkspaceAssign @p,@u,N'classification',@changes;
|
||||
IF EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID IN(@a,@b) AND ISNULL(Classification,N'')<>N'Fictional') THROW 51000,'Classification assignment failed.',1;
|
||||
UPDATE dbo.Scenes SET PrimaryLocationID=@a WHERE SceneID=@scene;
|
||||
SELECT @old=UpdatedDate FROM dbo.Locations WHERE LocationID=@a;
|
||||
SELECT @changes=(SELECT LocationID AS Id,N'Workspace renamed' 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'name',@changes;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@a AND LocationName=N'Workspace renamed' AND Description=N'Author prose' AND Classification=N'Fictional') THROW 51000,'Rename overwrote unrelated data.',1;
|
||||
IF (SELECT PrimaryLocationID FROM dbo.Scenes WHERE SceneID=@scene)<>@a THROW 51000,'Rename changed the recorded scene assignment.',1;
|
||||
-- Exact-value restore uses the post-save version and preserves unrelated fields.
|
||||
SELECT @changes=(SELECT LocationID AS Id,N'Workspace test root' 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'name',@changes,1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@a AND LocationName=N'Workspace test root' AND Description=N'Author prose') THROW 51000,'Undo failed.',1;
|
||||
DECLARE @leaf int;
|
||||
INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Other branch leaf',@d);SET @leaf=SCOPE_IDENTITY();
|
||||
SELECT @changes=(SELECT LocationID AS Id,N'' 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;
|
||||
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;
|
||||
ROLLBACK;
|
||||
PRINT 'PASS bulk branch preservation, root moves, classification, targeted rename, exact undo';
|
||||
-- Expected failures roll back the complete transaction, including their fixtures.
|
||||
BEGIN TRAN;
|
||||
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Cycle root');SET @a=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Cycle child',@a);SET @b=SCOPE_IDENTITY();
|
||||
SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@b) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH);
|
||||
BEGIN TRY
|
||||
EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes;
|
||||
THROW 51099,'Cycle accepted.',1;
|
||||
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH;
|
||||
PRINT 'PASS descendant cycle rejection';
|
||||
BEGIN TRAN;
|
||||
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Unavailable parent test');SET @a=SCOPE_IDENTITY();
|
||||
SELECT @changes=(SELECT LocationID AS Id,N'2147483647' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH);
|
||||
BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes;THROW 51099,'Unavailable parent accepted.',1;
|
||||
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH;
|
||||
PRINT 'PASS unavailable parent rejection';
|
||||
BEGIN TRAN;
|
||||
DECLARE @other int=(SELECT TOP(1) ProjectID FROM dbo.Projects WHERE ProjectID<>@p);
|
||||
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Cross-project source');SET @a=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@other,N'Cross-project destination');SET @b=SCOPE_IDENTITY();
|
||||
SELECT @changes=(SELECT LocationID AS Id,CONVERT(nvarchar(20),@b) AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH);
|
||||
BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,@u,N'parent',@changes;THROW 51099,'Cross-project parent accepted.',1;
|
||||
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51012 THROW; END CATCH;
|
||||
PRINT 'PASS cross-project parent rejection';
|
||||
BEGIN TRAN;
|
||||
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Stale test');SET @a=SCOPE_IDENTITY();
|
||||
SELECT @changes=(SELECT LocationID AS Id,N'Real' AS Value,N'2000-01-01' AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH);
|
||||
BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,@u,N'classification',@changes;THROW 51099,'Stale update accepted.',1;
|
||||
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51011 THROW; END CATCH;
|
||||
PRINT 'PASS stale write rejection';
|
||||
BEGIN TRAN;
|
||||
INSERT dbo.Locations(ProjectID,LocationName) VALUES(@p,N'Unauthorized test');SET @a=SCOPE_IDENTITY();
|
||||
SELECT @changes=(SELECT LocationID AS Id,N'Real' AS Value,CONVERT(nvarchar(33),UpdatedDate,126) AS Version FROM dbo.Locations WHERE LocationID=@a FOR JSON PATH);
|
||||
BEGIN TRY EXEC dbo.Location_WorkspaceAssign @p,-2147483647,N'classification',@changes;THROW 51099,'Unauthorized update accepted.',1;
|
||||
END TRY BEGIN CATCH IF ERROR_NUMBER()<>51010 THROW; END CATCH;
|
||||
PRINT 'PASS unauthorized mutation rejection';
|
||||
BEGIN TRAN;
|
||||
INSERT dbo.Locations(ProjectID,LocationName,Description,Classification) VALUES(@p,N'Merge source',N'Source prose',N'Fictional');SET @a=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,LocationName,Description) VALUES(@p,N'Merge survivor',N'Survivor prose');SET @b=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@p,N'Merge child',@a);SET @c=SCOPE_IDENTITY();
|
||||
UPDATE dbo.Scenes SET PrimaryLocationID=@a WHERE SceneID=@scene;
|
||||
DECLARE @relationshipType int=(SELECT TOP(1) LocationRelationshipTypeID FROM dbo.LocationRelationshipTypes WHERE IsActive=1),@relationship int,@direct int;
|
||||
INSERT dbo.LocationRelationships(FromLocationID,ToLocationID,LocationRelationshipTypeID,CanHearNormalSpeech,Notes) VALUES(@a,@c,@relationshipType,1,N'Preserve authored relationship');SET @relationship=SCOPE_IDENTITY();
|
||||
INSERT dbo.LocationRelationships(FromLocationID,ToLocationID,LocationRelationshipTypeID,Notes) VALUES(@a,@b,@relationshipType,N'Direct relationship preserved archived');SET @direct=SCOPE_IDENTITY();
|
||||
INSERT dbo.LocationAliases(LocationID,Alias,SortOrder) VALUES(@a,N'Former source name',10);
|
||||
DECLARE @map int,@feature uniqueidentifier=NEWID(),@plan int;
|
||||
INSERT dbo.StoryMaps(ProjectID,Name,Kind) VALUES(@p,N'Workspace merge map',N'Local');SET @map=SCOPE_IDENTITY();
|
||||
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();
|
||||
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;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Locations WHERE LocationID=@b AND Description LIKE N'%Source prose%' AND Description LIKE N'%Survivor prose%' AND Classification=N'Fictional') THROW 51000,'Merge discarded description/classification.',1;
|
||||
IF (SELECT ParentLocationID FROM dbo.Locations WHERE LocationID=@c)<>@b THROW 51000,'Merge child not transferred.',1;
|
||||
IF (SELECT PrimaryLocationID FROM dbo.Scenes WHERE SceneID=@scene)<>@b THROW 51000,'Merge lost the scene assignment.',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.LocationRelationships WHERE LocationRelationshipID=@relationship AND FromLocationID=@b AND ToLocationID=@c AND CanHearNormalSpeech=1 AND Notes=N'Preserve authored relationship' AND IsArchived=0) THROW 51000,'Merge lost the authored non-hierarchical relationship.',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.LocationRelationships WHERE LocationRelationshipID=@direct AND FromLocationID=@a AND ToLocationID=@b AND IsArchived=1) THROW 51000,'Merge did not preserve the archived direct relationship.',1;
|
||||
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;
|
||||
PRINT 'PASS transactional merge preserves conflicting descriptions, source, classification, children, map geometry, floor-plan links, scene assignments, aliases and non-hierarchical relationships';
|
||||
@ -271,6 +271,11 @@ internal static class ToolbarBrowserHost
|
||||
app.MapGet("/relationship-main-state-fixture",async (HttpContext context)=>await context.Response.WriteAsJsonAsync(await RelationshipWorkspaceTests.LargeFixture(int.TryParse(context.Request.Query["cast"],out var n)?Math.Clamp(n,1,200):75,context.Request.Query["network"].ToString(),int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:null)));
|
||||
app.MapGet("/relationship-main-family-fixture",async (HttpContext context)=>{var model=await RelationshipWorkspaceTests.LargeFixture(int.TryParse(context.Request.Query["cast"],out var n)?Math.Clamp(n,1,200):75,"family");await context.Response.WriteAsJsonAsync(new{canEdit=true,relationships=model.Relationships,nodes=model.Cast.Select(c=>new{id=c.CharacterID,name=c.CharacterName,birthDate=(string?)null})});});
|
||||
app.MapGet("/character-attribute-definitions-fixture",()=>Results.Json(CharacterQuickAttributes.Definitions([new(){CharacterSexValueID=1,SexName="Male",IsSystem=true},new(){CharacterSexValueID=2,SexName="Female",IsSystem=true},new(){CharacterSexValueID=3,SexName="Custom recorded sex"}]).Select(g=>new{g.Id,g.Label,values=g.Values.Select(CharacterQuickAttributes.Presentation),fallback=g.RecordedFallback is {} fallback?CharacterQuickAttributes.Presentation(fallback):null})));
|
||||
app.MapGet("/locations-workspace-types-fixture",()=>Results.Json(new[]{"Country","Region","Town","Building","Floor","Room","Outdoor Area","Vehicle Interior","Planet"}.Select((name,i)=>LocationWorkspaceIcons.Presentation((i+1).ToString(),name))));
|
||||
app.MapGet("/locations-workspace-fixture",async (HttpContext context)=>{
|
||||
var count=int.TryParse(context.Request.Query["count"],out var n)?Math.Clamp(n,1,2000):50;
|
||||
await RenderFullAsync(context,"Locations","Index",new LocationListViewModel{Project=new(){ProjectID=7,ProjectName="The Meridian Atlas",AccessRole="Owner"},Locations=Enumerable.Range(1,count).Select(i=>new LocationItem{LocationID=i,ProjectID=7,ParentLocationID=i==1||i%13==0?null:i<12?i-1:((i-2)/12)*12+1,LocationName=i==1?"Meridian":i==2?"Northern coast":i==3?"Port Halcyon":i==4?"Observatory":i==5?"Reading room":$"Location {i:D3}",LocationTypeID=i%4+1,LocationTypeName=new[]{"Region","Town","Building","Room"}[i%4],Depth=Math.Min(i-1,10),LocationPath=$"Meridian / Northern coast / Location {i:D3}",Description=string.Join(" ",Enumerable.Repeat("Salt air drifts through the open windows. The old survey charts record a coastline changed by generations of storms.",i%7+1)),UpdatedDate=new DateTime(2026,11,27,0,0,0,DateTimeKind.Utc)}).ToArray()});
|
||||
});
|
||||
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()});
|
||||
|
||||
133
PlotLine/Controllers/LocationWorkspaceController.cs
Normal file
@ -0,0 +1,133 @@
|
||||
using System.Data;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
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 LocationWorkspaceController(ISqlConnectionFactory connections, ICurrentUserService user,
|
||||
IProjectRepository projects, ContextWorkspaceNotifications notifications, IDataProtectionProvider protection) : Controller
|
||||
{
|
||||
public sealed record Alias(int LocationID, string Value);
|
||||
public sealed record Link(int LocationID, int ID, string Name, string Kind);
|
||||
public sealed record Usage(int LocationID, int SceneCount);
|
||||
public sealed record Option(int ID, string Name);
|
||||
public sealed record Change(int Id, string Value, string Version);
|
||||
public sealed record Assignment(int ProjectId, string Attribute, Change[] Changes);
|
||||
public sealed record Receipt(int User, int ProjectId, string Attribute, Change[] Changes, DateTime Expires);
|
||||
public sealed record UndoRequest(string Token);
|
||||
public sealed record CreateRequest(int ProjectId, string Name, int? ParentId);
|
||||
private IDataProtector Protector => protection.CreateProtector("LocationWorkspace.Undo.v1");
|
||||
|
||||
[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();
|
||||
using var db = connections.CreateConnection();
|
||||
using var result = await db.QueryMultipleAsync("dbo.Location_WorkspaceRead", new { ProjectID = projectId, UserID = author }, commandType: CommandType.StoredProcedure);
|
||||
var records = (await result.ReadAsync<LocationWorkspaceRecord>()).ToArray();
|
||||
var aliases = (await result.ReadAsync<LocationAlias>()).ToLookup(a => a.LocationID, a => a.Alias);
|
||||
var maps = (await result.ReadAsync<Link>()).ToLookup(a => a.LocationID);
|
||||
var floors = (await result.ReadAsync<Link>()).ToLookup(a => a.LocationID);
|
||||
var usage = (await result.ReadAsync<Usage>()).ToDictionary(a => a.LocationID, a => a.SceneCount);
|
||||
var types = (await result.ReadAsync<Option>()).ToArray();
|
||||
return Json(new { canEdit = ContextEditPolicy.CanEdit(project), types = types.Select(t => LocationWorkspaceIcons.Presentation(t.ID.ToString(), t.Name)),
|
||||
locations = records.Select(r => new { id = r.LocationID, name = r.LocationName, parent = r.ParentLocationID,
|
||||
type = r.LocationTypeID?.ToString() ?? "", typeName = r.LocationTypeName, classification = r.Classification ?? "",
|
||||
relationships = r.RelationshipCount, characters = r.CharacterCount, assets = r.AssetCount,
|
||||
description = r.Description ?? "", quickAdd = r.ShowInQuickAddBar ? "1" : "0", detection = r.ExcludeFromCompanionDetection ? "1" : "0",
|
||||
version = r.UpdatedDate.ToString("O"), aliases = aliases[r.LocationID], maps = maps[r.LocationID], floors = floors[r.LocationID], scenes = usage.GetValueOrDefault(r.LocationID) }) });
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Assign([FromBody] Assignment input)
|
||||
{
|
||||
if (user.UserId is null) return Unauthorized();
|
||||
if (!ModelState.IsValid || input is null || input.Changes is null || input.Changes.Length is < 1 or > 2000
|
||||
|| input.Changes.Any(c => c is null || c.Value is null || c.Value.Length > 1000000 || !DateTime.TryParse(c.Version, out _))
|
||||
|| input.Changes.Select(c => c.Id).Distinct().Count() != input.Changes.Length) return BadRequest(new { message = "Choose a valid selection." });
|
||||
if (input.Attribute is not ("type" or "classification" or "parent" or "name" or "description" or "quickAdd" or "detection"))
|
||||
return BadRequest(new { message = "Unknown location attribute." });
|
||||
if (input.Attribute == "classification" && input.Changes.Any(c => c.Value is not ("" or "Real" or "Fictional" or "Fictionalised")))
|
||||
return BadRequest(new { message = "Choose a supported classification." });
|
||||
return await Execute(input, false);
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Undo([FromBody] UndoRequest request)
|
||||
{
|
||||
if (user.UserId is not int author) return Unauthorized();
|
||||
if (!ModelState.IsValid || string.IsNullOrWhiteSpace(request?.Token)) return BadRequest(new { message = "Undo is unavailable." });
|
||||
try
|
||||
{
|
||||
var receipt = JsonSerializer.Deserialize<Receipt>(Protector.Unprotect(request.Token));
|
||||
if (receipt is null || receipt.User != author || receipt.Expires < DateTime.UtcNow) return BadRequest(new { message = "Undo has expired." });
|
||||
return await Execute(new(receipt.ProjectId, receipt.Attribute, receipt.Changes), true);
|
||||
}
|
||||
catch (Exception e) when (e is CryptographicException or JsonException or ArgumentException)
|
||||
{ return BadRequest(new { message = "Undo is unavailable." }); }
|
||||
}
|
||||
|
||||
private async Task<IActionResult> Execute(Assignment input, bool restore)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var db = connections.CreateConnection();
|
||||
var previous = (await db.QueryAsync<Change>("dbo.Location_WorkspaceAssign", new { ProjectID = input.ProjectId,
|
||||
UserID = user.UserId, input.Attribute, Changes = JsonSerializer.Serialize(input.Changes), Restore = restore }, commandType: CommandType.StoredProcedure)).ToArray();
|
||||
string? undoToken = previous.Length == 0 ? null : Protector.Protect(JsonSerializer.Serialize(new Receipt(user.UserId!.Value,
|
||||
input.ProjectId, input.Attribute, previous, DateTime.UtcNow.AddMinutes(10))));
|
||||
if (previous.Length > 0) await notifications.Invalidate(user.UserId!.Value, projectId: input.ProjectId, kind: "locations");
|
||||
return Json(new { saved = true, undoToken, changes = previous.Select(c => new { c.Id, c.Version, value = input.Attribute == "type" && int.TryParse(input.Changes.Single(i => i.Id == c.Id).Value, out var typeId) ? typeId.ToString() : input.Changes.Single(i => i.Id == c.Id).Value }), attribute = input.Attribute });
|
||||
}
|
||||
catch (SqlException e) when (e.Number is 51010 or 51011 or 51012)
|
||||
{ return StatusCode(e.Number == 51010 ? 403 : 409, new { message = e.Message }); }
|
||||
}
|
||||
|
||||
public sealed record MergeRequest(int ProjectId, int SourceId, int TargetId, string SourceVersion, string TargetVersion, bool Confirm);
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Merge([FromBody] MergeRequest input)
|
||||
{
|
||||
if (user.UserId is not int author) return Unauthorized();
|
||||
if (!ModelState.IsValid || input is null || !input.Confirm || !DateTime.TryParse(input.SourceVersion, out var sourceVersion)
|
||||
|| !DateTime.TryParse(input.TargetVersion, out var targetVersion)) return BadRequest(new { message = "Review and confirm the merge." });
|
||||
try
|
||||
{
|
||||
using var db = connections.CreateConnection();
|
||||
await db.QuerySingleAsync<EntityMergeResult>("dbo.Location_WorkspaceMerge", new { ProjectID = input.ProjectId, UserID = author,
|
||||
SourceID = input.SourceId, TargetID = input.TargetId, SourceVersion = sourceVersion, TargetVersion = targetVersion }, commandType: CommandType.StoredProcedure);
|
||||
await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations");
|
||||
return Json(new { id = input.TargetId });
|
||||
}
|
||||
catch (SqlException e) when (e.Number is 51000 or 51010 or 51011 or 51012)
|
||||
{ return StatusCode(e.Number == 51010 ? 403 : 409, new { message = e.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Create([FromBody] CreateRequest input)
|
||||
{
|
||||
if (user.UserId is not int author) return Unauthorized();
|
||||
if (!ModelState.IsValid || input is null || string.IsNullOrWhiteSpace(input.Name) || input.Name.Length > 200) return BadRequest(new { message = "Enter a name of up to 200 characters." });
|
||||
try
|
||||
{
|
||||
using var db = connections.CreateConnection();
|
||||
var id = await db.QuerySingleAsync<int>("dbo.Location_WorkspaceCreate", new { ProjectID = input.ProjectId, UserID = author, input.Name, ParentID = input.ParentId }, commandType: CommandType.StoredProcedure);
|
||||
await notifications.Invalidate(author, projectId: input.ProjectId, kind: "locations");
|
||||
return Json(new { id });
|
||||
}
|
||||
catch (SqlException e) when (e.Number is 51010 or 51012)
|
||||
{ return StatusCode(e.Number == 51010 ? 403 : 409, new { message = e.Message }); }
|
||||
}
|
||||
}
|
||||
@ -1,17 +1,19 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize]
|
||||
public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography) : Controller
|
||||
public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography, IProjectRepository projects, ICurrentUserService currentUser) : Controller
|
||||
{
|
||||
public async Task<IActionResult> Index(int projectId)
|
||||
{
|
||||
var model = await locations.GetLocationsAsync(projectId);
|
||||
return model is null ? NotFound() : View(model);
|
||||
if (currentUser.UserId is not int userId) return Unauthorized();
|
||||
var project = await projects.GetForUserAsync(projectId, userId);
|
||||
return project is null ? NotFound() : View(new LocationListViewModel { Project = project });
|
||||
}
|
||||
|
||||
public async Task<IActionResult> Create(int projectId)
|
||||
|
||||
@ -9,49 +9,70 @@ quickSummary: Locations help you manage story places, keep character movement be
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# Overview
|
||||
# Organise your world
|
||||
|
||||
Locations are the places where your story happens. They can be broad settings, such as a city or estate, or specific places, such as a bedroom, kitchen, railway platform, office, cellar or garden path. PlotDirector uses locations to support both atmosphere and continuity.
|
||||
The Locations workspace has Attributes on the left, your hierarchy or cards in the centre,
|
||||
and editable details on the right. Drag either divider to resize a panel. Attributes and
|
||||
Details buttons collapse or restore them. Your view, widths, sorting and expanded branches
|
||||
are remembered separately for each project.
|
||||
|
||||
A location is not only scenery. It affects what characters can see, hear, hide, discover and misunderstand. In a tightly plotted story, the distance between rooms may matter. In a mystery, who could hear a conversation may matter. In a romance, returning to the same place after an emotional change may matter. Locations give those details a stable home.
|
||||
# Build a hierarchy
|
||||
|
||||
You can begin with a simple list of important places and add detail later. As your project grows, location relationships and scene links help you understand how characters move through the world of the story.
|
||||
Expand a location to see the places it contains. Drag a location onto another to change its
|
||||
parent, or drop it on **Root locations** to remove its parent. Its descendants move with it.
|
||||
Select several locations to move whole branches together. Use **Change parent** for a searchable
|
||||
alternative to dragging. Invalid cycles are rejected.
|
||||
|
||||
# When Should I Use This?
|
||||
Containment means a lasting relationship: a room belongs inside a building. A vehicle parked
|
||||
at a roadside stop does not necessarily belong permanently inside that stop. Keep temporary
|
||||
circumstances in scene/asset location records; use existing location relationships for adjacency,
|
||||
visibility, hearing or travel connections.
|
||||
|
||||
Create a location when a place appears more than once, affects continuity, or shapes the action. A named house, shop, school, hospital ward or train carriage may deserve a record. A vague background street probably does not, unless it becomes important later.
|
||||
# Change attributes directly
|
||||
|
||||
Use locations whenever spatial logic matters. If a character enters from the landing, exits to the kitchen, overhears something through a wall, or hides an asset in a locked cupboard, location tracking can prevent confusion during revision.
|
||||
Click an attribute to filter. Drag it onto a location, drag a location onto it, or select
|
||||
locations and choose **Assign**. The same commands appear in the location menu. Changes save
|
||||
immediately. **Undo** restores supported changes if the records have not changed again.
|
||||
Location type and Real / Fictional / Fictionalised classification are independent. Existing
|
||||
locations remain Unclassified until you choose a classification.
|
||||
|
||||
# How To Use It
|
||||
Maps, floor plans, scene use, descriptions and child counts are informational filters, rather
|
||||
than assignable flags. Scene use means recorded assignments, not textual name matches.
|
||||
Search includes recorded aliases. Matching nested locations appear with their ancestors;
|
||||
clearing search restores your expansion choices.
|
||||
|
||||
Start by naming the location clearly. Add a short description that captures what a writer needs to remember: layout, mood, access, important objects, or story significance. If locations relate to each other, record that relationship. For example, a bedroom may connect to a landing, a cellar may be beneath the kitchen, or an office may overlook a courtyard.
|
||||
# Edit without leaving
|
||||
|
||||
Assign locations to scenes and scene characters where useful. A scene can have a primary location, while characters can have current, entry and exit locations. This is especially helpful when validation warns that a character has no location set.
|
||||
Select a location to edit its attributes in Details. Use **Edit description**, then **Save** or
|
||||
**Cancel** for longer prose. Unsaved descriptions prompt before switching locations.
|
||||
Choose **Create child location** from Details or the menu, enter a name, and its parent is already
|
||||
set. Full creation, Details and Edit pages remain available.
|
||||
|
||||
During revision, use location information to check whether movement, sightlines and timing make sense.
|
||||
Press **F2** on a focused row to rename; **Enter** saves and **Escape** cancels. Renaming preserves
|
||||
identifiers and references and does not rewrite manuscript text. Use arrow keys to navigate the
|
||||
tree, **Space** to select, and **Shift+F10** to open its menu. Right-click or the visible **⋯** button
|
||||
opens the same commands, including parent changes, attributes, archive and merge.
|
||||
|
||||
# Example
|
||||
# Hierarchy and cards
|
||||
|
||||
Location: "Blue Bedroom"
|
||||
Switch to **Cards** for descriptions and compact association indicators. Cards grow with their
|
||||
content. Selection and filters remain when switching views. Sort A–Z or Z–A; in Hierarchy this
|
||||
sorts siblings while retaining parent/child relationships. **Reveal selected** returns to its tree
|
||||
position. **Expand all** and **Collapse all** control the whole tree.
|
||||
|
||||
Description: "A guest bedroom at the back of the house, cold even in summer, with a locked connecting door to the nursery."
|
||||
# Maps, floor plans and merging
|
||||
|
||||
Scenes in this room might involve Rebecca finding a clue, Beth refusing to enter, and later the connecting door being opened. Tracking it as a location keeps the physical logic and emotional meaning together.
|
||||
Details lists each associated map and floor plan individually. Links open in the same window.
|
||||
The editors, geometry and existing scene references are retained.
|
||||
|
||||
# Writer Tip
|
||||
Choose **Merge with another location** from the menu, then choose the survivor and review both
|
||||
descriptions and the consequences. References and children move to the survivor; the source is
|
||||
archived. Different descriptions are preserved together. The survivor keeps its name, type and
|
||||
parent. Geographic confirmations remain with their original records. Merge has no workspace Undo;
|
||||
review carefully before confirming. No similar names are merged automatically.
|
||||
|
||||
Let locations carry story pressure. A place can become more tense each time the reader returns to it, especially if new knowledge changes what the same room means.
|
||||
|
||||
# Common Mistakes
|
||||
|
||||
- Creating locations only as decorative settings rather than story spaces.
|
||||
- Forgetting entry and exit locations when several characters move through a scene.
|
||||
- Changing a building layout in revision without updating earlier scenes.
|
||||
- Treating a location's emotional meaning as static when events have changed it.
|
||||
|
||||
# Related Guides
|
||||
# Related guides
|
||||
|
||||
- [Location details](/Help/Article/locations.details)
|
||||
- [Scenes](/Help/Article/scenes.overview)
|
||||
- [Characters](/Help/Article/characters.overview)
|
||||
- [Story Assets](/Help/Article/storyAssets.overview)
|
||||
|
||||
@ -1451,6 +1451,7 @@ public sealed class LocationRelationshipType
|
||||
|
||||
public sealed class LocationItem
|
||||
{
|
||||
public string? Classification { get; set; }
|
||||
public int? CreatedByUserID { get; set; }
|
||||
public int? ModifiedByUserID { get; set; }
|
||||
public DateTime? CreatedDateUTC { get; set; }
|
||||
|
||||
19
PlotLine/Models/LocationWorkspaceRecord.cs
Normal file
@ -0,0 +1,19 @@
|
||||
namespace PlotLine.Models;
|
||||
|
||||
// Workspace projection; canonical identifiers and attributes remain on dbo.Locations.
|
||||
public class LocationWorkspaceRecord
|
||||
{
|
||||
public int RelationshipCount { get; set; }
|
||||
public int CharacterCount { get; set; }
|
||||
public int AssetCount { get; set; }
|
||||
public int LocationID { get; set; }
|
||||
public string LocationName { get; set; } = "";
|
||||
public int? ParentLocationID { get; set; }
|
||||
public int? LocationTypeID { get; set; }
|
||||
public string? LocationTypeName { get; set; }
|
||||
public string? Classification { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public bool ShowInQuickAddBar { get; set; }
|
||||
public bool ExcludeFromCompanionDetection { get; set; }
|
||||
public DateTime UpdatedDate { get; set; }
|
||||
}
|
||||
26
PlotLine/Services/LocationWorkspaceIcons.cs
Normal file
@ -0,0 +1,26 @@
|
||||
namespace PlotLine.Services;
|
||||
|
||||
// Opt-in mapping; existing Location/Context consumers keep their current presentation.
|
||||
public static class LocationWorkspaceIcons
|
||||
{
|
||||
public static (string Icon, string Tone) Type(string? name) => name?.ToLowerInvariant() switch
|
||||
{
|
||||
"country" or "planet" => ("location-globe", "info"),
|
||||
"region" or "district" => ("maps", "success"),
|
||||
"town" or "city" or "village" => ("location-city", "primary"),
|
||||
"street" => ("location-street", "warning"),
|
||||
"building" => ("location-house", "primary"),
|
||||
"floor" => ("location-level", "info"),
|
||||
"room" => ("location-door", "data-5"),
|
||||
"outdoor area" => ("location-tree", "success"),
|
||||
"vehicle interior" => ("location-vehicle", "warning"),
|
||||
"landmark" or "natural feature" => ("location-mountain", "success"),
|
||||
"other" => ("locations", "secondary"),
|
||||
_ => ("help", "secondary")
|
||||
};
|
||||
public static object Presentation(string value, string name)
|
||||
{
|
||||
var (icon, tone) = Type(name);
|
||||
return CharacterQuickAttributes.Presentation(new(value, name, icon, tone));
|
||||
}
|
||||
}
|
||||
@ -45,6 +45,15 @@ public static class RibbonPresentation
|
||||
return null;
|
||||
}
|
||||
public static IReadOnlyList<RibbonIcon> AdditionalIcons { get; } = [
|
||||
new("location-globe", "M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0 M2 12h20 M12 2c-6 6-6 14 0 20 6-6 6-14 0-20", "world"),
|
||||
new("location-city", "M3 22V8h8v14 M11 22V2h10v20 M6 11h2 M6 15h2 M14 6h4 M14 10h4 M14 14h4 M14 18h4", "world"),
|
||||
new("location-house", "M2 11L12 2l10 9 M5 9v13h14V9 M10 22v-8h4v8", "world"),
|
||||
new("location-door", "M4 22h16 M6 22V2h12v20 M14 12h1", "world"),
|
||||
new("location-tree", "M12 2l-6 8h3l-6 8h7v4h4v-4h7l-6-8h3z", "world"),
|
||||
new("location-vehicle", "M4 17V8l2-5h12l2 5v9z M4 9h16 M7 13h1 M16 13h1 M6 17v4 M18 17v4", "world"),
|
||||
new("location-street", "M12 2v20 M3 5h17l3 4-3 4H3z", "world"),
|
||||
new("location-level", "M2 7l10-5 10 5-10 5z M2 12l10 5 10-5 M2 17l10 5 10-5", "world"),
|
||||
new("location-mountain", "M2 21L10 3l5 10 3-5 5 13z M7 10l3 2 3-2", "world"),
|
||||
new("name-available", "M22 12a10 10 0 1 1-5-8 M7 11l4 4 11-12", "characters"),
|
||||
new("name-alias", "M3 3h18v18H3z M9 7a3 3 0 1 0 0 6 3 3 0 0 0 0-6 M5 19v-2a4 4 0 0 1 8 0v2 M16 8h3 M16 12h3 M16 16h3", "characters"),
|
||||
new("attribute-paw", "M8 15c-5 3-2 8 1 6l3-1 3 1c3 2 6-3 1-6l-4-3z M6 5a2 3 0 1 0 0 6 2 3 0 0 0 0-6 M11 2a2 3 0 1 0 0 6 2 3 0 0 0 0-6 M17 3a2 3 0 1 0 0 6 2 3 0 0 0 0-6 M21 8a2 3 0 1 0 0 6 2 3 0 0 0 0-6", "characters"),
|
||||
|
||||
205
PlotLine/Sql/335_LocationsWorkspace.sql
Normal file
@ -0,0 +1,205 @@
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
-- Optional provenance is independent of canonical location type. NULL means unclassified.
|
||||
IF COL_LENGTH('dbo.Locations','Classification') IS NULL
|
||||
ALTER TABLE dbo.Locations ADD Classification nvarchar(20) NULL
|
||||
CONSTRAINT CK_Locations_Classification CHECK(Classification IN(N'Real',N'Fictional',N'Fictionalised'));
|
||||
GO
|
||||
INSERT dbo.LocationTypes(TypeName,SortOrder)
|
||||
SELECT v.Name,v.SortOrder FROM (VALUES(N'Planet',130),(N'District',140),(N'Natural Feature',150),(N'City',160))v(Name,SortOrder)
|
||||
WHERE NOT EXISTS(SELECT 1 FROM dbo.LocationTypes t WHERE t.TypeName=v.Name);
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Location_WorkspaceRead @ProjectID int,@UserID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID WHERE a.ProjectID=@ProjectID AND a.UserID=@UserID AND a.IsActive=1 AND p.IsArchived=0) THROW 51010,'Locations unavailable.',1;
|
||||
SELECT l.*,t.TypeName AS LocationTypeName,ISNULL(rel.RelationshipCount,0) AS RelationshipCount,ISNULL(ch.CharacterCount,0) AS CharacterCount,ISNULL(a.AssetCount,0) AS AssetCount
|
||||
FROM dbo.Locations l LEFT JOIN dbo.LocationTypes t ON t.LocationTypeID=l.LocationTypeID
|
||||
LEFT JOIN(SELECT x.ID,COUNT(*) AS RelationshipCount FROM dbo.LocationRelationships r CROSS APPLY(VALUES(r.FromLocationID),(r.ToLocationID))x(ID) JOIN dbo.Locations p ON p.LocationID=x.ID WHERE p.ProjectID=@ProjectID AND r.IsArchived=0 GROUP BY x.ID)rel ON rel.ID=l.LocationID
|
||||
LEFT JOIN(SELECT sc.LocationID,COUNT(DISTINCT sc.CharacterID) AS CharacterCount FROM dbo.SceneCharacters sc JOIN dbo.Locations p ON p.LocationID=sc.LocationID JOIN dbo.Scenes s ON s.SceneID=sc.SceneID WHERE p.ProjectID=@ProjectID AND s.IsArchived=0 GROUP BY sc.LocationID)ch ON ch.LocationID=l.LocationID
|
||||
LEFT JOIN(SELECT CurrentLocationID,COUNT(*) AS AssetCount FROM dbo.StoryAssets WHERE ProjectID=@ProjectID AND IsArchived=0 GROUP BY CurrentLocationID)a ON a.CurrentLocationID=l.LocationID
|
||||
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0;
|
||||
SELECT a.LocationID,a.Alias FROM dbo.LocationAliases a JOIN dbo.Locations l ON l.LocationID=a.LocationID WHERE l.ProjectID=@ProjectID AND l.IsArchived=0;
|
||||
SELECT DISTINCT f.LocationID,m.MapID AS ID,m.Name,N'map' AS Kind FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID AND f.LocationID IS NOT NULL;
|
||||
SELECT DISTINCT x.LocationID,p.FloorPlanID AS ID,p.Name AS Name,N'floor' AS Kind FROM dbo.FloorPlans p
|
||||
CROSS APPLY(SELECT p.LocationID UNION SELECT f.LocationID FROM dbo.FloorPlanFloors f WHERE f.FloorPlanID=p.FloorPlanID UNION SELECT b.LocationID FROM dbo.FloorPlanBlocks b JOIN dbo.FloorPlanFloors f ON f.FloorPlanFloorID=b.FloorPlanFloorID WHERE f.FloorPlanID=p.FloorPlanID)x WHERE p.ProjectID=@ProjectID AND x.LocationID IS NOT NULL;
|
||||
-- Authoritative scene assignments, including explicit character/asset locations. Never name matches.
|
||||
SELECT x.LocationID,COUNT(DISTINCT x.SceneID) AS SceneCount FROM (
|
||||
SELECT s.PrimaryLocationID AS LocationID,s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0
|
||||
UNION SELECT assigned.LocationID,sc.SceneID FROM dbo.SceneCharacters sc CROSS APPLY(VALUES(sc.LocationID),(sc.EntryLocationID),(sc.ExitLocationID))assigned(LocationID) JOIN dbo.Scenes s ON s.SceneID=sc.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0
|
||||
UNION SELECT a.LocationID,a.SceneID FROM dbo.SceneAssetLocations a JOIN dbo.Scenes s ON s.SceneID=a.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0
|
||||
)x WHERE x.LocationID IS NOT NULL GROUP BY x.LocationID;
|
||||
SELECT LocationTypeID AS ID,TypeName AS Name FROM dbo.LocationTypes WHERE IsActive=1 ORDER BY SortOrder,TypeName;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Location_WorkspaceAssign @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'type',N'classification',N'parent',N'name',N'description',N'quickAdd',N'detection') THROW 51012,'Unknown attribute.',1;
|
||||
DECLARE @items TABLE(Id int PRIMARY KEY,Value nvarchar(max),Version datetime2);
|
||||
INSERT @items SELECT Id,ISNULL(Value,N''),TRY_CONVERT(datetime2,Version) FROM OPENJSON(@Changes) WITH(Id int,Value nvarchar(max),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;
|
||||
DECLARE @lock int;
|
||||
SELECT @lock=ProjectID FROM dbo.Projects WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID AND IsArchived=0;
|
||||
IF @lock IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WITH(HOLDLOCK) WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole IN(N'Owner',N'Collaborator')) THROW 51010,'Editing unavailable.',1;
|
||||
IF EXISTS(SELECT 1 FROM @items i LEFT JOIN dbo.Locations l WITH(UPDLOCK,HOLDLOCK) ON l.LocationID=i.Id AND l.ProjectID=@ProjectID AND l.IsArchived=0 WHERE l.LocationID IS NULL) THROW 51010,'Location unavailable.',1;
|
||||
IF EXISTS(SELECT 1 FROM @items i JOIN dbo.Locations l ON l.LocationID=i.Id WHERE l.UpdatedDate<>i.Version) THROW 51011,'Locations changed in another window. Refresh and try again.',1;
|
||||
IF @Attribute=N'type' AND EXISTS(SELECT 1 FROM @items i WHERE i.Value<>N'' AND NOT EXISTS(SELECT 1 FROM dbo.LocationTypes t WHERE t.LocationTypeID=TRY_CONVERT(int,i.Value) AND t.IsActive=1)) THROW 51012,'Choose a canonical location type.',1;
|
||||
IF @Attribute=N'classification' AND EXISTS(SELECT 1 FROM @items WHERE Value NOT IN(N'',N'Real',N'Fictional',N'Fictionalised')) THROW 51012,'Invalid classification.',1;
|
||||
IF @Attribute IN(N'quickAdd',N'detection') AND EXISTS(SELECT 1 FROM @items WHERE Value NOT IN(N'0',N'1')) THROW 51012,'Invalid switch.',1;
|
||||
IF @Attribute=N'name' AND EXISTS(SELECT 1 FROM @items WHERE LEN(LTRIM(RTRIM(Value)))=0 OR LEN(Value)>200) THROW 51012,'Enter a name of up to 200 characters.',1;
|
||||
IF @Attribute=N'description' AND EXISTS(SELECT 1 FROM @items WHERE DATALENGTH(Value)>2000000) THROW 51012,'Description is too long.',1;
|
||||
IF @Attribute=N'parent'
|
||||
BEGIN
|
||||
IF EXISTS(SELECT 1 FROM @items i WHERE i.Value<>N'' AND NOT EXISTS(SELECT 1 FROM dbo.Locations p WITH(UPDLOCK,HOLDLOCK) WHERE p.LocationID=TRY_CONVERT(int,i.Value) AND p.ProjectID=@ProjectID AND p.IsArchived=0)) THROW 51012,'Choose an active parent in this project.',1;
|
||||
-- A bulk move applies only to branch roots. Selected descendants keep their parent.
|
||||
-- Restore uses the exact recorded parent for every changed root.
|
||||
IF @Restore=0
|
||||
BEGIN
|
||||
DECLARE @skip TABLE(Id int PRIMARY KEY);
|
||||
;WITH ancestors AS(
|
||||
SELECT i.Id,l.ParentLocationID,0 AS Depth FROM @items i JOIN dbo.Locations l ON l.LocationID=i.Id
|
||||
UNION ALL SELECT a.Id,l.ParentLocationID,a.Depth+1 FROM ancestors a JOIN dbo.Locations l ON l.LocationID=a.ParentLocationID WHERE a.Depth<10000
|
||||
) INSERT @skip SELECT DISTINCT a.Id FROM ancestors a JOIN @items i ON i.Id=a.ParentLocationID OPTION(MAXRECURSION 0);
|
||||
DELETE i FROM @items i JOIN @skip s ON s.Id=i.Id;
|
||||
END;
|
||||
-- Validate the final graph including all proposed assignments (also on Undo).
|
||||
DECLARE @id int,@ancestor int,@next int;
|
||||
DECLARE roots CURSOR LOCAL FAST_FORWARD FOR SELECT Id,TRY_CONVERT(int,NULLIF(Value,N'')) FROM @items;
|
||||
OPEN roots; FETCH NEXT FROM roots INTO @id,@ancestor;
|
||||
WHILE @@FETCH_STATUS=0
|
||||
BEGIN
|
||||
DECLARE @visited TABLE(Id int PRIMARY KEY);
|
||||
DELETE FROM @visited;
|
||||
WHILE @ancestor IS NOT NULL
|
||||
BEGIN
|
||||
IF @ancestor=@id OR EXISTS(SELECT 1 FROM @visited WHERE Id=@ancestor) THROW 51012,'A location cannot be moved beneath itself or a descendant.',1;
|
||||
INSERT @visited VALUES(@ancestor);
|
||||
SET @next=NULL;
|
||||
IF EXISTS(SELECT 1 FROM @items WHERE Id=@ancestor) SELECT @next=TRY_CONVERT(int,NULLIF(Value,N'')) FROM @items WHERE Id=@ancestor;
|
||||
ELSE SELECT @next=ParentLocationID FROM dbo.Locations WITH(UPDLOCK,HOLDLOCK) WHERE LocationID=@ancestor AND ProjectID=@ProjectID;
|
||||
SET @ancestor=@next;
|
||||
END;
|
||||
FETCH NEXT FROM roots INTO @id,@ancestor;
|
||||
END;
|
||||
CLOSE roots; DEALLOCATE roots;
|
||||
END;
|
||||
DECLARE @changed TABLE(Id int,Value nvarchar(max),Version datetime2,Name nvarchar(200));
|
||||
UPDATE l SET
|
||||
LocationTypeID=CASE WHEN @Attribute=N'type' THEN TRY_CONVERT(int,NULLIF(i.Value,N'')) ELSE l.LocationTypeID END,
|
||||
Classification=CASE WHEN @Attribute=N'classification' THEN NULLIF(i.Value,N'') ELSE l.Classification END,
|
||||
ParentLocationID=CASE WHEN @Attribute=N'parent' THEN TRY_CONVERT(int,NULLIF(i.Value,N'')) ELSE l.ParentLocationID END,
|
||||
LocationName=CASE WHEN @Attribute=N'name' THEN LTRIM(RTRIM(i.Value)) ELSE l.LocationName END,
|
||||
Description=CASE WHEN @Attribute=N'description' THEN NULLIF(i.Value,N'') ELSE l.Description END,
|
||||
ShowInQuickAddBar=CASE WHEN @Attribute=N'quickAdd' THEN CONVERT(bit,i.Value) ELSE l.ShowInQuickAddBar END,
|
||||
ExcludeFromCompanionDetection=CASE WHEN @Attribute=N'detection' THEN CONVERT(bit,i.Value) ELSE l.ExcludeFromCompanionDetection END,
|
||||
UpdatedDate=SYSUTCDATETIME(),ModifiedDateUTC=SYSUTCDATETIME(),ModifiedByUserID=@UserID
|
||||
OUTPUT inserted.LocationID,CASE @Attribute WHEN N'type' THEN ISNULL(CONVERT(nvarchar(max),deleted.LocationTypeID),N'') WHEN N'classification' THEN ISNULL(deleted.Classification,N'') WHEN N'parent' THEN ISNULL(CONVERT(nvarchar(max),deleted.ParentLocationID),N'') WHEN N'name' THEN deleted.LocationName WHEN N'description' THEN ISNULL(deleted.Description,N'') WHEN N'quickAdd' THEN CONVERT(nvarchar(max),deleted.ShowInQuickAddBar) WHEN N'detection' THEN CONVERT(nvarchar(max),deleted.ExcludeFromCompanionDetection) END,inserted.UpdatedDate,inserted.LocationName INTO @changed
|
||||
FROM dbo.Locations l JOIN @items i ON i.Id=l.LocationID
|
||||
WHERE i.Value COLLATE Latin1_General_100_BIN2 <> (CASE @Attribute WHEN N'type' THEN ISNULL(CONVERT(nvarchar(max),l.LocationTypeID),N'') WHEN N'classification' THEN ISNULL(l.Classification,N'') WHEN N'parent' THEN ISNULL(CONVERT(nvarchar(max),l.ParentLocationID),N'') WHEN N'name' THEN l.LocationName WHEN N'description' THEN ISNULL(l.Description,N'') WHEN N'quickAdd' THEN CONVERT(nvarchar(max),l.ShowInQuickAddBar) WHEN N'detection' THEN CONVERT(nvarchar(max),l.ExcludeFromCompanionDetection) END) COLLATE Latin1_General_100_BIN2;
|
||||
DECLARE @audit TABLE(ID bigint);
|
||||
DECLARE @entity int,@name nvarchar(200),@summary nvarchar(1000)=CONCAT(N'Workspace ',@Attribute,CASE WHEN @Restore=1 THEN N' restored.' ELSE N' changed.' END);
|
||||
DECLARE audit_rows CURSOR LOCAL FAST_FORWARD FOR SELECT Id,Name FROM @changed;
|
||||
OPEN audit_rows; FETCH NEXT FROM audit_rows INTO @entity,@name;
|
||||
WHILE @@FETCH_STATUS=0
|
||||
BEGIN
|
||||
INSERT @audit EXEC dbo.ProjectAudit_Record @ProjectID=@ProjectID,@UserID=@UserID,@ActivityType=N'Updated',@EntityType=N'Location',@EntityID=@entity,@EntityName=@name,@Description=@summary;
|
||||
FETCH NEXT FROM audit_rows INTO @entity,@name;
|
||||
END;
|
||||
CLOSE audit_rows; DEALLOCATE audit_rows;
|
||||
COMMIT;
|
||||
SELECT Id,Value,CONVERT(nvarchar(33),Version,126) AS Version FROM @changed;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF XACT_STATE()<>0 ROLLBACK;
|
||||
THROW;
|
||||
END CATCH;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Location_WorkspaceCreate @ProjectID int,@UserID int,@Name nvarchar(200),@ParentID int=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
BEGIN TRY
|
||||
BEGIN TRAN;
|
||||
DECLARE @lock int;
|
||||
SELECT @lock=ProjectID FROM dbo.Projects WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID AND IsArchived=0;
|
||||
IF @lock IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole IN(N'Owner',N'Collaborator')) THROW 51010,'Editing unavailable.',1;
|
||||
IF NULLIF(LTRIM(RTRIM(@Name)),N'') IS NULL THROW 51012,'Enter a location name.',1;
|
||||
IF @ParentID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Locations WITH(UPDLOCK,HOLDLOCK) WHERE LocationID=@ParentID AND ProjectID=@ProjectID AND IsArchived=0) THROW 51012,'Parent unavailable.',1;
|
||||
INSERT dbo.Locations(ProjectID,ParentLocationID,LocationName,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC) VALUES(@ProjectID,@ParentID,LTRIM(RTRIM(@Name)),@UserID,@UserID,SYSUTCDATETIME(),SYSUTCDATETIME());
|
||||
DECLARE @id int=CONVERT(int,SCOPE_IDENTITY());
|
||||
DECLARE @audit TABLE(ID bigint);
|
||||
INSERT @audit EXEC dbo.ProjectAudit_Record @ProjectID=@ProjectID,@UserID=@UserID,@ActivityType=N'Created',@EntityType=N'Location',@EntityID=@id,@EntityName=@Name;
|
||||
COMMIT;
|
||||
SELECT @id;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF XACT_STATE()<>0 ROLLBACK;
|
||||
THROW;
|
||||
END CATCH;
|
||||
END;
|
||||
GO
|
||||
-- Preserve the optional classification in the existing typed project export/restore contract.
|
||||
-- Amend only this selector in the current authoritative export; refuse an unexpected definition.
|
||||
DECLARE @export nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectBackup_Export'));
|
||||
IF @export NOT LIKE N'%l.Classification%'
|
||||
BEGIN
|
||||
IF @export NOT LIKE N'%l.LocationName, l.LocationTypeID, lt.TypeName AS LocationTypeName, l.Description,%' THROW 51012,'Review the current location export selector before upgrading.',1;
|
||||
SET @export=REPLACE(@export,N'l.LocationName, l.LocationTypeID, lt.TypeName AS LocationTypeName, l.Description,',N'l.LocationName, l.LocationTypeID, lt.TypeName AS LocationTypeName, l.Description, l.Classification,');
|
||||
SET @export=STUFF(@export,1,CHARINDEX(N'PROCEDURE',@export)-1,N'CREATE OR ALTER ');
|
||||
EXEC sys.sp_executesql @export;
|
||||
END;
|
||||
GO
|
||||
-- Extend the established merge too, so Details/Edit entry points preserve newer spatial links.
|
||||
DECLARE @merge nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.Location_Merge'));
|
||||
IF @merge NOT LIKE N'%LocationsWorkspace335%'
|
||||
BEGIN
|
||||
DECLARE @marker nvarchar(200)=N' UPDATE dbo.Locations'+NCHAR(10)+N' SET IsArchived = 1, ArchivedDate = @Now,';
|
||||
IF CHARINDEX(@marker,REPLACE(@merge,NCHAR(13),N''))=0 THROW 51012,'Review the current location merge before upgrading.',1;
|
||||
SET @merge=REPLACE(@merge,NCHAR(13),N'');
|
||||
SET @merge=REPLACE(@merge,@marker,N' -- LocationsWorkspace335: preserve maps and conflicting author prose.
|
||||
DECLARE @SourceDescription nvarchar(max),@TargetDescription nvarchar(max),@SourceClassification nvarchar(20);
|
||||
SELECT @SourceDescription=Description,@SourceClassification=Classification FROM dbo.Locations WHERE LocationID=@SourceID;
|
||||
SELECT @TargetDescription=Description FROM dbo.Locations WHERE LocationID=@TargetID;
|
||||
UPDATE dbo.Locations SET Description=CASE WHEN NULLIF(@SourceDescription,N'''') IS NULL OR @SourceDescription=@TargetDescription THEN @TargetDescription WHEN NULLIF(@TargetDescription,N'''') IS NULL THEN @SourceDescription ELSE CONCAT(@TargetDescription,NCHAR(13),NCHAR(10),NCHAR(13),NCHAR(10),N''Preserved from '',@SourceName,N'':'',NCHAR(13),NCHAR(10),@SourceDescription) END,
|
||||
Classification=COALESCE(Classification,@SourceClassification),UpdatedDate=@Now,ModifiedDateUTC=@Now,ModifiedByUserID=@UserID WHERE LocationID=@TargetID;
|
||||
UPDATE m SET Revision=Revision+1,ModifiedDate=@Now FROM dbo.StoryMaps m WHERE m.ProjectID=@ProjectID AND EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=m.MapID AND f.LocationID=@SourceID);
|
||||
UPDATE f SET LocationID=@TargetID FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID AND f.LocationID=@SourceID;
|
||||
'+@marker);
|
||||
SET @merge=REPLACE(@merge,N'UserID = @UserID AND IsActive = 1)',N'UserID = @UserID AND IsActive = 1 AND AccessRole IN(N''Owner'',N''Collaborator''))');
|
||||
SET @merge=STUFF(@merge,1,CHARINDEX(N'PROCEDURE',@merge)-1,N'CREATE OR ALTER ');
|
||||
EXEC sys.sp_executesql @merge;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Location_WorkspaceMerge @ProjectID int,@UserID int,@SourceID int,@TargetID int,@SourceVersion datetime2,@TargetVersion datetime2
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @lock int;
|
||||
SELECT @lock=ProjectID FROM dbo.Projects WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID AND IsArchived=0;
|
||||
IF @lock IS NULL OR NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole IN(N'Owner',N'Collaborator')) THROW 51010,'Editing unavailable.',1;
|
||||
IF @SourceID=@TargetID OR NOT EXISTS(SELECT 1 FROM dbo.Locations WITH(UPDLOCK,HOLDLOCK) WHERE LocationID=@SourceID AND ProjectID=@ProjectID AND IsArchived=0 AND UpdatedDate=@SourceVersion)
|
||||
OR NOT EXISTS(SELECT 1 FROM dbo.Locations WITH(UPDLOCK,HOLDLOCK) WHERE LocationID=@TargetID AND ProjectID=@ProjectID AND IsArchived=0 AND UpdatedDate=@TargetVersion) THROW 51011,'Merge records changed. Review the merge again.',1;
|
||||
-- The established merge reconciles all scene, floor plan, alias and relationship references,
|
||||
-- validates descendant targets, and archives the source without deleting its original details.
|
||||
DECLARE @targetName nvarchar(200)=(SELECT LocationName FROM dbo.Locations WHERE LocationID=@TargetID);
|
||||
EXEC dbo.Location_Merge @SourceID=@SourceID,@TargetID=@TargetID,@UserID=@UserID;
|
||||
DECLARE @audit TABLE(ID bigint);
|
||||
INSERT @audit EXEC dbo.ProjectAudit_Record @ProjectID=@ProjectID,@UserID=@UserID,@ActivityType=N'Merged',@EntityType=N'Location',@EntityID=@TargetID,@EntityName=@targetName;
|
||||
COMMIT;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF XACT_STATE()<>0 ROLLBACK;
|
||||
THROW;
|
||||
END CATCH;
|
||||
END;
|
||||
GO
|
||||
@ -119,7 +119,7 @@
|
||||
</section>
|
||||
|
||||
<section class="edit-panel">
|
||||
<h2>Relationships <help-icon key="locations.relationships" /></h2>
|
||||
<h2 id="location-relationships">Relationships <help-icon key="locations.relationships" /></h2>
|
||||
@if (!Model.Relationships.Any())
|
||||
{
|
||||
<p class="muted">No relationships defined yet.</p>
|
||||
|
||||
@ -1,100 +1,49 @@
|
||||
@model LocationListViewModel
|
||||
@{
|
||||
ViewData["DesktopLayout"] = "management";
|
||||
ViewData["ShellClass"] = "location-workspace-shell";
|
||||
ViewData["ShellClass"] = "location-workspace-shell pd-workspace-full-width";
|
||||
ViewData["Title"] = "Locations";
|
||||
ViewData["ProjectSection"] = "Locations";
|
||||
}
|
||||
|
||||
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
|
||||
<a asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a>
|
||||
<span>Locations</span>
|
||||
<a asp-controller="Projects" asp-action="Details" asp-route-id="@Model.Project.ProjectID">@Model.Project.ProjectName</a><span>Locations</span>
|
||||
</nav>
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<div class="location-page">
|
||||
<div data-pwa-header class="page-heading compact">
|
||||
<div>
|
||||
<p class="eyebrow">Locations</p>
|
||||
<h1>@Model.Project.ProjectName <help-icon key="locations.overview" /></h1>
|
||||
<div class="location-page" data-locations-workspace data-project-id="@Model.Project.ProjectID">
|
||||
<div data-pwa-header class="page-heading compact"><div><p class="eyebrow">World building</p><h1>Locations <help-icon key="locations.overview" /></h1></div><span class="muted">@Model.Project.ProjectName</span></div>
|
||||
@if (TempData["LocationMessage"] is string message) { <span hidden data-toast-message="success">@message</span> }
|
||||
@if (TempData["LocationError"] is string error) { <div class="alert alert-danger" role="alert">@error</div> }
|
||||
<form hidden data-location-token>@Html.AntiForgeryToken()</form>
|
||||
<div class="locations-toolbar">
|
||||
<div class="locations-primary-commands" data-pwa-context="Locations" data-pwa-essential="true">
|
||||
<a class="btn btn-primary btn-sm" asp-action="Create" asp-route-projectId="@Model.Project.ProjectID" data-pwa-icon="add">New location</a>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-new-child data-pwa-icon="add" disabled>New child location</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-change-parent data-pwa-icon="merge" disabled>Change parent</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-create-relationship data-pwa-icon="relationships" disabled>Create relationship</button>
|
||||
</div>
|
||||
<a class="btn btn-primary" asp-action="Create" asp-route-projectId="@Model.Project.ProjectID">New location</a>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-panel-toggle="attributes" data-pwa-icon="list" aria-expanded="true">Attributes</button>
|
||||
<div role="group" aria-label="Location view"><button type="button" class="btn btn-outline-secondary btn-sm" data-view="tree" data-pwa-icon="location-level" aria-pressed="true">Hierarchy</button><button type="button" class="btn btn-outline-secondary btn-sm" data-view="cards" data-pwa-icon="layout" aria-pressed="false">Cards</button></div>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-expand="true" data-pwa-icon="add">Expand all</button><button type="button" class="btn btn-outline-secondary btn-sm" data-expand="false" data-pwa-icon="minimise">Collapse all</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-reveal data-pwa-icon="focus">Reveal selected</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-panel-toggle="details" data-pwa-icon="details" aria-expanded="true">Details</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-undo hidden data-pwa-icon="undo">Undo</button>
|
||||
</div>
|
||||
|
||||
@if (TempData["LocationMessage"] is string message)
|
||||
{
|
||||
<span hidden data-toast-message="success">@message</span>
|
||||
}
|
||||
@if (TempData["LocationError"] is string error)
|
||||
{
|
||||
<div class="alert alert-danger" role="alert">@error</div>
|
||||
}
|
||||
<div class="location-hierarchy-toolbar" data-pwa-context="Location hierarchy" data-pwa-essential="true">
|
||||
<span class="fw-semibold">On drop:</span>
|
||||
<div class="location-drag-commands" role="group" aria-label="Location drag behaviour">
|
||||
<button type="button" class="btn btn-outline-primary btn-sm" data-pwa-icon="merge" data-location-drag-choice="parent" aria-pressed="true" title="Move a location and its children beneath a new parent; confirmation required."><svg viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("merge").IconPath" /></svg><span>Change parent</span></button>
|
||||
<button type="button" class="btn btn-outline-primary btn-sm" data-pwa-icon="relationships" data-location-drag-choice="relationship" aria-pressed="false" title="Open the relationship editor for the two locations."><svg viewBox="0 0 24 24" aria-hidden="true"><path d="@ApplicationRibbon.Icon("relationships").IconPath" /></svg><span>Create relationship</span></button>
|
||||
</div>
|
||||
<input type="hidden" value="parent" data-location-drag-action />
|
||||
</div>
|
||||
<p class="text-danger mb-0" role="alert" data-location-move-error></p>
|
||||
<p class="mb-0" role="status" data-location-move-status></p>
|
||||
<form asp-action="Reparent" method="post" data-location-reparent-form
|
||||
data-confirm-message="Change location parent?" data-confirm-button-text="Move location" data-confirm-button-class="btn-primary">
|
||||
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
|
||||
<input type="hidden" name="locationId" />
|
||||
<input type="hidden" name="parentLocationId" />
|
||||
<input type="hidden" name="expectedParentLocationId" />
|
||||
</form>
|
||||
|
||||
<div class="modal fade" tabindex="-1" aria-labelledby="locationRelationshipTitle" aria-hidden="true" data-location-relationship-modal>
|
||||
<div class="modal-dialog modal-dialog-centered modal-lg">
|
||||
<section class="modal-content p-3 d-none" data-drag-drop-panel>
|
||||
<div class="drag-drop-panel-header">
|
||||
<div>
|
||||
<p class="eyebrow" data-drag-panel-kicker>Location relationship</p>
|
||||
<h2 id="locationRelationshipTitle" data-drag-panel-title>Create location relationship</h2>
|
||||
</div>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-drag-cancel>Cancel</button>
|
||||
</div>
|
||||
<p class="muted" data-drag-panel-summary></p>
|
||||
<p class="text-danger" role="alert" data-location-relationship-error></p>
|
||||
<form asp-controller="Locations" asp-action="DropRelationship" method="post" class="drag-drop-form" data-drag-form="location-relationship">
|
||||
<input type="hidden" name="ProjectID" value="@Model.Project.ProjectID" />
|
||||
<input type="hidden" name="FromLocationID" />
|
||||
<input type="hidden" name="ToLocationID" />
|
||||
<div class="row g-2">
|
||||
<div class="col-12"><label class="form-label">Relationship type</label><select class="form-select form-select-sm" name="LocationRelationshipTypeID" asp-items="Model.RelationshipTypeOptions"></select></div>
|
||||
<div class="col-12 drag-check-grid">
|
||||
<label><input type="checkbox" name="IsBidirectional" value="true" /> Bidirectional</label>
|
||||
<label><input type="checkbox" name="CanHearNormalSpeech" value="true" /> Can hear speech</label>
|
||||
<label><input type="checkbox" name="CanHearLoudNoise" value="true" /> Can hear loud noise</label>
|
||||
<label><input type="checkbox" name="CanSeeMovement" value="true" /> Can see movement</label>
|
||||
<label><input type="checkbox" name="CanSeeClearly" value="true" /> Can see clearly</label>
|
||||
<label><input type="checkbox" name="CanTravelDirectly" value="true" /> Can travel directly</label>
|
||||
</div>
|
||||
<div class="col-12"><label class="form-label">Notes</label><textarea class="form-control form-control-sm" name="Notes" rows="2"></textarea></div>
|
||||
</div>
|
||||
<div class="button-row mt-2">
|
||||
<button class="btn btn-primary btn-sm" type="submit">Save</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" data-drag-cancel>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (!Model.Locations.Any())
|
||||
{
|
||||
<section class="empty-panel">
|
||||
<h2>No locations yet</h2>
|
||||
<p>Add buildings, floors, rooms, streets, and other places that matter to the story.</p>
|
||||
<div class="locations-search"><input type="search" class="form-control form-control-sm" data-search aria-label="Search location names and aliases" placeholder="Search locations and aliases…" /><button type="button" class="btn btn-outline-secondary btn-sm" data-clear-search>Clear search</button><select class="form-select form-select-sm" data-sort aria-label="Sort locations"><option value="asc">Name A–Z</option><option value="desc">Name Z–A</option></select><span data-result-count role="status"></span></div>
|
||||
<div class="locations-layout">
|
||||
<aside class="locations-attributes" aria-label="Location attributes"><h2>Attributes</h2><p class="small muted">Click to filter. Drag to assign, or select locations and choose Assign.</p><button type="button" class="btn btn-outline-secondary btn-sm" data-clear-filters>Clear filters</button><div data-groups>Loading attributes…</div></aside>
|
||||
<section class="locations-centre" aria-label="Location directory">
|
||||
<div class="locations-selection"><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><span data-selection-count>0 selected</span><button type="button" class="btn btn-outline-secondary btn-sm" data-selection-menu>Selection ⋯</button></div>
|
||||
<div class="locations-root" data-root-drop tabindex="0">Root locations <span class="muted">— drop here to remove a parent</span></div>
|
||||
<p role="alert" class="text-danger" data-workspace-error></p>
|
||||
<div data-location-records role="tree" aria-label="Location hierarchy" aria-busy="true"></div>
|
||||
</section>
|
||||
}
|
||||
else
|
||||
{
|
||||
<partial name="_LocationTree" model="Model" />
|
||||
}
|
||||
<aside class="locations-details" aria-label="Selected location details"><div data-details><h2>Your world, in detail</h2><p class="muted">Select a location to explore its place in your world, edit its attributes, and open associated maps and floor plans.</p></div></aside>
|
||||
</div>
|
||||
<dialog data-location-dialog class="locations-dialog"><form method="dialog"><h2 data-dialog-title></h2><div data-dialog-body></div><p class="text-danger" data-dialog-error role="alert"></p><div class="button-row"><button type="button" class="btn btn-primary btn-sm" data-dialog-save>Save</button><button type="button" class="btn btn-outline-secondary btn-sm" data-dialog-cancel>Cancel</button></div></form></dialog>
|
||||
<noscript><p>The interactive workspace requires JavaScript. Traditional location forms remain available.</p><partial name="_LocationTree" model="Model" /></noscript>
|
||||
</div>
|
||||
<link rel="stylesheet" href="~/css/workspace-surface.css" asp-append-version="true" />
|
||||
<link rel="stylesheet" href="~/css/locations-workspace.css" asp-append-version="true" />
|
||||
<script src="~/js/workspace-surface.js" asp-append-version="true" defer></script>
|
||||
<script src="~/js/locations-workspace.js" asp-append-version="true" defer></script>
|
||||
|
||||
@ -19,7 +19,7 @@
|
||||
<div>
|
||||
<p class="eyebrow">Location identity</p>
|
||||
<h1>Merge @Model.SourceName</h1>
|
||||
<p class="lead-text">Known names, scene references, child locations, relationships and floor plan links move to the selected location. The source location is archived. The selected location keeps its details. A location cannot be merged into one of its descendants.</p>
|
||||
<p class="lead-text">Known names, scene references, child locations, relationships and floor plan links move to the selected location. The source location is archived. The selected location keeps its name, type and parent. Different descriptions are preserved together; an unclassified survivor inherits the source classification. Map links transfer without changing geometry. Original source details and geographic evidence remain archived. A location cannot be merged into one of its descendants.</p>
|
||||
</div>
|
||||
<a class="btn btn-outline-secondary" asp-action="Details" asp-route-id="@Model.Form.SourceID">Cancel</a>
|
||||
</div>
|
||||
|
||||
14
PlotLine/wwwroot/css/locations-workspace.css
Normal file
@ -0,0 +1,14 @@
|
||||
.location-page{min-width:0;--location-border:var(--plotline-line,var(--bs-border-color));--location-panel:var(--plotline-panel,var(--bs-body-bg));--location-accent:var(--plotline-accent,var(--bs-primary));}
|
||||
.locations-toolbar,.locations-search,.locations-selection{display:flex;align-items:center;flex-wrap:wrap;gap:.45rem;padding:.5rem 0}.locations-toolbar{border-bottom:1px solid var(--location-border)}.locations-toolbar [aria-pressed=true]{background:var(--location-accent);color:var(--bs-body-bg)}.locations-search [data-search]{flex:1;min-width:180px}.locations-search select{width:auto}.locations-search [role=status]{font-size:.85rem;white-space:nowrap}
|
||||
.locations-layout{display:grid;grid-template-columns:var(--workspace-left,240px) minmax(0,1fr) var(--workspace-right,320px);height:calc(100dvh - var(--locations-top,290px) - 16px);min-height:360px;gap:0;border:1px solid var(--location-border);border-radius:.7rem;overflow:hidden;background:var(--location-panel)}
|
||||
.locations-attributes,.locations-details,.locations-centre{min-width:0;overflow:auto;overscroll-behavior:contain;padding:1rem}.locations-attributes{border-right:1px solid var(--location-border)}.locations-details{border-left:1px solid var(--location-border)}.locations-layout h2{font-size:1.05rem}.locations-attributes p{line-height:1.45}.locations-attributes details{margin-top:1rem}.locations-attributes summary{font-weight:600;margin-bottom:.4rem;cursor:pointer}.location-attribute-row{display:flex;gap:.25rem;margin-bottom:.2rem}.location-attribute-row>button:first-child{flex:1;text-align:left;display:flex;align-items:center;gap:.4rem;border-color:transparent}.location-attribute-row [data-count]{margin-left:auto;opacity:.75}.location-attribute-row [aria-pressed=true]{background:var(--bs-secondary-bg);border-color:var(--location-accent)}.location-attribute-row>button:last-child{padding-inline:.35rem;font-size:.72rem}.location-icon{height:1.15rem;width:1.15rem;flex-shrink:0;stroke:currentColor;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;vertical-align:middle}.location-tone-success{color:var(--bs-success)}.location-tone-info{color:var(--bs-info)}.location-tone-primary{color:var(--location-accent)}.location-tone-warning{color:var(--bs-warning)}.location-tone-data-5{color:var(--pd-data-5,var(--location-accent))}
|
||||
.locations-selection{padding:0 0 .7rem;font-size:.8rem}.locations-root{border:1px dashed var(--location-border);padding:.55rem .7rem;border-radius:.4rem;font-size:.85rem;margin-bottom:.6rem}.locations-root:focus-visible{outline:2px solid var(--location-accent)}
|
||||
.location-record{position:relative;border:1px solid transparent;border-radius:.4rem;margin-bottom:.2rem;scroll-margin-block:1rem}.location-record .location-row-main{display:flex;align-items:center;gap:.4rem;min-height:42px;padding:.35rem .4rem;padding-left:calc(.4rem + min(var(--depth,0),20)*1.1rem)}.location-record .location-row-main:before{content:"";position:absolute;left:calc(.3rem + min(var(--depth,0),20)*1.1rem);height:100%;border-left:1px solid var(--location-border);opacity:.5;pointer-events:none}.location-record button{position:relative}.location-record .location-label{font-weight:600;text-align:left;background:none;border:0;color:inherit;overflow-wrap:anywhere;padding:.1rem;min-width:0;flex:1}.location-record [data-expand-id]{width:1.5rem;padding:0;background:none;border:0;color:inherit;flex-shrink:0}.location-record .location-row-menu{margin-left:auto}.location-record .location-indicators{display:flex;gap:.35rem;align-items:center;font-size:.75rem}.location-record .location-child-count{font-size:.7rem;opacity:.7}.location-record.is-active{background:var(--bs-secondary-bg);border-color:var(--location-accent)}.location-record.is-selected{box-shadow:inset 3px 0 var(--location-accent)}.location-record.is-ancestor .location-label{color:var(--location-accent)}.location-record.is-context{opacity:.72}.location-record:focus-visible{outline:2px solid var(--location-accent)}.location-record [data-drag-location]{cursor:grab;padding:.1rem .25rem;background:none;border:0;color:inherit}.location-record.is-drop-target,.location-attribute-row.is-drop-target,.locations-root.is-drop-target{outline:2px solid var(--bs-success);outline-offset:-2px}.location-record.is-invalid-target{outline:2px dashed var(--bs-danger)}
|
||||
.locations-cards{column-width:290px;column-gap:.85rem}.locations-cards .location-record{display:inline-block;vertical-align:top;break-inside:avoid;width:100%;border-color:var(--location-border);padding:.65rem;margin:0 0 .85rem}.locations-cards .location-row-main{padding:0!important;flex-wrap:wrap}.locations-cards .location-row-main:before{display:none}.locations-cards .location-indicators{width:100%;padding:.5rem 0}.locations-cards .location-label{font-size:1.05rem}.location-card-description,.locations-description{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6;font-size:.9rem}.location-card-path,.location-details-path{font-size:.78rem;overflow-wrap:anywhere;opacity:.75;margin:.55rem 0}.location-type-caption{font-size:.78rem;color:var(--bs-secondary-color)}
|
||||
.location-detail-heading{display:flex;gap:.6rem;align-items:flex-start}.location-detail-heading>.location-icon{width:1.7rem;height:1.7rem}.location-detail-heading h2{font-size:1.2rem;overflow-wrap:anywhere}.location-detail-actions{display:flex;flex-wrap:wrap;gap:.4rem;margin:.7rem 0}.location-detail-attributes{display:grid;gap:.65rem;margin:1rem 0}.location-detail-attributes label{font-size:.8rem;font-weight:600}.locations-details section{border-top:1px solid var(--location-border);margin-top:1rem;padding-top:1rem}.locations-details section h3{font-size:.95rem}.locations-details [data-description-editor]{width:100%;min-height:180px}.locations-details .location-child-link{display:block;text-align:left;margin:.3rem 0}.locations-details [data-related] a{display:block;margin-block:.4rem}.locations-dialog{background:var(--location-panel);color:var(--bs-body-color);border:1px solid var(--location-border);border-radius:.8rem;width:min(520px,calc(100vw - 24px));padding:1.5rem;max-height:85dvh;overflow:auto}.locations-dialog::backdrop{background:#0007}.locations-dialog h2{font-size:1.25rem}.locations-dialog [data-dialog-body]{margin-block:1rem}.locations-dialog input,.locations-dialog select{margin-bottom:.6rem}.locations-layout.attributes-collapsed{grid-template-columns:0 minmax(0,1fr) var(--workspace-right,320px)}.locations-layout.details-collapsed{grid-template-columns:var(--workspace-left,240px) minmax(0,1fr) 0}.locations-layout.attributes-collapsed.details-collapsed{grid-template-columns:0 minmax(0,1fr) 0}.locations-layout.attributes-collapsed>.pd-panel-divider[data-panel-side=left],.locations-layout.details-collapsed>.pd-panel-divider[data-panel-side=right]{display:none}.locations-layout [hidden]{display:none!important}
|
||||
@media(max-width:899px){.locations-layout{grid-template-columns:minmax(0,1fr);height:auto;max-height:none;overflow:visible}.locations-attributes,.locations-details,.locations-centre{max-height:65dvh}.locations-attributes,.locations-details{border:0;border-bottom:1px solid var(--location-border)}.locations-layout.attributes-collapsed,.locations-layout.details-collapsed,.locations-layout.attributes-collapsed.details-collapsed{grid-template-columns:minmax(0,1fr)}.locations-centre{min-height:280px}.location-record .location-row-main{padding-left:calc(.2rem + min(var(--depth,0),8)*.7rem)}.location-record .location-indicators{flex-wrap:wrap}.locations-search{gap:.3rem}.locations-selection{flex-wrap:wrap}}
|
||||
|
||||
.location-attribute-row>button:first-child{font-size:.8rem;padding-inline:.3rem}.location-attribute-row>button:last-child{font-size:.68rem;padding-inline:.25rem}.location-attribute-row>button>span{overflow-wrap:normal}.location-attribute-row [data-count]{flex-shrink:0;white-space:nowrap}
|
||||
|
||||
.locations-primary-commands{display:flex;flex-wrap:wrap;gap:.45rem}.location-page .btn-outline-secondary{background:var(--location-panel);color:var(--bs-body-color);border-color:var(--location-border)}.location-page .btn-outline-secondary:hover,.location-page .btn-outline-secondary:focus-visible{background:var(--bs-secondary-bg);border-color:var(--location-accent)}
|
||||
.locations-root{position:sticky;top:0;z-index:2;background:var(--location-panel)}
|
||||
105
PlotLine/wwwroot/js/locations-workspace.js
Normal file
@ -0,0 +1,105 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const root=document.querySelector('[data-locations-workspace]');if(!root)return;
|
||||
const $=s=>root.querySelector(s),project=Number(root.dataset.projectId),layout=$('.locations-layout'),host=$('[data-location-records]'),details=$('[data-details]'),groupsHost=$('[data-groups]'),dialog=$('[data-location-dialog]');
|
||||
const toast=window.PlotDirector?.toast,user=document.querySelector('[data-toast-host]')?.dataset.toastUser||'session',key=`pd.locations.workspace.v1.${user}.${project}`;
|
||||
let prefs={view:'tree',sort:'asc',expanded:[],groups:{},attributes:false,details:false};try{Object.assign(prefs,JSON.parse(localStorage.getItem(key)||'{}'));}catch{}
|
||||
let readEpoch=0,records=new Map(),children=new Map(),types=[],groups=[],selected=new Set(),active=null,filters=new Map(),expanded=new Set(prefs.expanded),query='',busy=false,drag=null,undo=null,canEdit=false,hoverTimer=null,hoverId=null,connection=null,pendingRefresh=false,refreshing=null,descriptionDraft=null,rendered=[],dialogSave=null,anchor=null;
|
||||
const savePrefs=()=>{prefs.expanded=[...expanded];try{localStorage.setItem(key,JSON.stringify(prefs));}catch{}};
|
||||
function el(tag,text,cls){const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;}
|
||||
function button(label,fn,cls='btn btn-outline-secondary btn-sm'){const n=el('button',label,cls);n.type='button';n.addEventListener('click',fn);return n;}
|
||||
function icon(value){const n=document.createElementNS('http://www.w3.org/2000/svg','svg');n.setAttribute('viewBox','0 0 24 24');n.setAttribute('class',`location-icon location-tone-${value?.tone||'secondary'}`);n.setAttribute('aria-hidden','true');const p=document.createElementNS(n.namespaceURI,'path');p.setAttribute('d',value?.path||'M12 3v12 M12 20v1');p.setAttribute('fill',value?.filled?'currentColor':'none');n.append(p);return n;}
|
||||
function type(r){return types.find(t=>t.value===r.type)||{...types[0],label:r.typeName||'Unclassified'};}
|
||||
function path(id,includeSelf=true){const result=[],visited=new Set(),start=records.get(id);let missing=!includeSelf&&start?.parent&&!records.has(start.parent),r=includeSelf?start:records.get(start?.parent);while(r&&!visited.has(r.id)){visited.add(r.id);result.unshift(r.name);if(r.parent&&!records.has(r.parent))missing=true;r=records.get(r.parent);}if(missing)result.unshift('Parent unavailable');return result.join(' / ');}
|
||||
function ancestors(id){const result=[],visited=new Set([id]);let p=records.get(id)?.parent;while(records.has(p)&&!visited.has(p)){visited.add(p);result.push(p);p=records.get(p).parent;}return result;}
|
||||
function index(){children=new Map();for(const r of records.values()){const parent=records.has(r.parent)?r.parent:null;if(!children.has(parent))children.set(parent,[]);children.get(parent).push(r.id);}const order=(a,b)=>records.get(a).name.localeCompare(records.get(b).name,undefined,{numeric:true,sensitivity:'base'})*(prefs.sort==='desc'?-1:1)||a-b;for(const ids of children.values())ids.sort(order);}
|
||||
function scope(id){return selected.has(id)?[...selected]:[id];}
|
||||
function value(r,a){if(a==='parent')return r.parent?.toString()||'';if(a==='name')return r.name;return r[a]??'';}
|
||||
function matches(r){if(query&&!([r.name,...r.aliases].some(t=>t.toLocaleLowerCase().includes(query))))return false;for(const [a,v]of filters){if(a==='branch'){if(v&&r.id!==Number(v)&&!ancestors(r.id).includes(Number(v)))return false;}else if(a==='parentState'){if((v==='root')!==(r.parent===null))return false;}else if(a==='descriptionState'){if((v==='yes')!==!!r.description.trim())return false;}else if(a==='childrenState'){if((v==='yes')!==!!children.get(r.id)?.length)return false;}else if(a==='mapState'){if((v==='yes')!==!!r.maps.length)return false;}else if(a==='floorState'){if((v==='yes')!==!!r.floors.length)return false;}else if(a==='usageState'){if((v==='yes')!==(r.scenes>0))return false;}else if(value(r,a)!==v)return false;}return true;}
|
||||
function dirty(){return descriptionDraft&&descriptionDraft.value!==descriptionDraft.original;}
|
||||
function leaveDraft(){if(!dirty())return true;return window.confirm('Discard the unsaved description? Choose Cancel to keep editing.');}
|
||||
async function post(action,data){const response=await fetch(`/LocationWorkspace/${action}`,{method:'POST',headers:{'Content-Type':'application/json','RequestVerificationToken':$('[name=__RequestVerificationToken]').value},body:JSON.stringify(data)});if(response.redirected)throw Error('Your session has expired. Sign in again before saving.');const result=await response.json().catch(()=>({message:'The change could not be saved.'}));if(!response.ok)throw Error(result.message||'The change could not be saved.');return result;}
|
||||
function failure(e){$('[data-workspace-error]').textContent=e.message;toast?.error(e.message);}
|
||||
async function refresh(){if(refreshing)return refreshing;if(busy||dirty()){pendingRefresh=true;return;}const epoch=readEpoch;refreshing=(async()=>{try{const response=await fetch(`/LocationWorkspace/Directory?projectId=${project}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error('Locations could not be loaded. Reload to retry.');const data=await response.json();if(epoch!==readEpoch||dirty()){pendingRefresh=true;return;}canEdit=data.canEdit;records=new Map(data.locations.map(r=>[r.id,r]));types=[{value:'',label:'Unclassified',icon:'help',path:'M9 8a3 3 0 1 1 4 3c-1 1-1 2-1 3 M12 18v1 M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0',tone:'secondary'},...data.types];index();buildGroups();render();renderDetails();$('[data-workspace-error]').textContent='';}catch(e){failure(e);}finally{refreshing=null;host.setAttribute('aria-busy','false');if(pendingRefresh&&!busy&&!dirty()){pendingRefresh=false;queueMicrotask(()=>void refresh());}}})();return refreshing;}
|
||||
async function assign(attribute,newValue,ids,isUndo=false,token=null){if(busy||!canEdit)return;if(!isUndo){ids=ids.filter(id=>records.has(id)&&(attribute==='parent'||value(records.get(id),attribute)!==newValue));if(!ids.length)return;}
|
||||
busy=true;readEpoch++;$('[data-workspace-error]').textContent='';selection();try{const data=await post(isUndo?'Undo':'Assign',isUndo?{token}:{projectId:project,attribute,changes:ids.map(id=>({id,value:newValue,version:records.get(id).version}))});
|
||||
if(!data.changes.length)return true;
|
||||
for(const c of data.changes){const r=records.get(c.id);if(!r)continue;r.version=c.version;const a=data.attribute;if(a==='parent')r.parent=c.value?Number(c.value):null;else r[a]=a==='name'?c.value.trim():c.value;if(a==='type')r.typeName=types.find(t=>t.value===c.value)?.label;}
|
||||
undo=data.undoToken;$('[data-undo]').hidden=!undo;index();render();renderDetails();if(data.changes.length){const receipt=undo;toast?.success(isUndo?'Location changes restored.':`${data.changes.length} location${data.changes.length===1?'':'s'} updated.`,receipt?{action:{label:'Undo',run:()=>assign(null,null,[],true,receipt)}}:undefined);}
|
||||
return true;
|
||||
}catch(e){failure(e);return false;}finally{busy=false;selection();if(pendingRefresh&&!dirty()){pendingRefresh=false;void refresh();}}}
|
||||
function informational(id,label,yes,no,iconName){return {id,label,editable:false,values:[{value:'yes',label:yes,icon:iconName},{value:'no',label:no,icon:'help'}]};}
|
||||
function buildGroups(){groups=[{id:'type',label:'Location type',editable:true,values:types},{id:'classification',label:'Classification',editable:true,values:[{value:'',label:'Unclassified',icon:'help'},{value:'Real',label:'Real',icon:'location-globe'},{value:'Fictional',label:'Fictional',icon:'bible'},{value:'Fictionalised',label:'Fictionalised',icon:'writer'}]},
|
||||
{id:'quickAdd',label:'Quick Add Bar',editable:true,values:[{value:'1',label:'Included',icon:'attribute-pin'},{value:'0',label:'Excluded',icon:'attribute-unpin'}]},
|
||||
{id:'detection',label:'Word Companion detection',editable:true,values:[{value:'0',label:'Included',icon:'validate'},{value:'1',label:'Excluded',icon:'help'}]},
|
||||
{id:'parentState',label:'Hierarchy',editable:false,values:[{value:'root',label:'Root locations',icon:'locations'},{value:'parent',label:'Has parent',icon:'location-level'}]},
|
||||
informational('mapState','Maps','Mapped','Unmapped','maps'),informational('floorState','Floor plans','Has floor plan','No floor plan','floorplans'),informational('usageState','Manuscript assignments','Used in scenes','No recorded scene use','scenes'),informational('descriptionState','Description','Recorded','Missing','edit'),informational('childrenState','Contained locations','Has children','No children','location-level')];
|
||||
groupsHost.replaceChildren();for(const g of groups){const section=el('details');section.open=prefs.groups[g.id]!==false;const summary=el('summary',g.label);section.append(summary);section.addEventListener('toggle',()=>{prefs.groups[g.id]=section.open;savePrefs();});if(!g.editable)section.append(el('p','Filter only','small muted'));
|
||||
for(const v of g.values){const row=el('div',undefined,'location-attribute-row');row.dataset.attribute=g.id;row.dataset.value=v.value;const filter=button('',()=>{filters.get(g.id)===v.value?filters.delete(g.id):filters.set(g.id,v.value);render();});filter.append(presentationIcon(v),el('span',v.label));const count=el('span','0');count.dataset.count='';filter.append(count);row.append(filter);filter.draggable=g.editable&&canEdit;filter.addEventListener('dragstart',e=>{if(!canEdit)return e.preventDefault();drag={attribute:g.id,value:v.value};e.dataTransfer.setData('application/x-plotdirector-location-attribute',JSON.stringify(drag));e.dataTransfer.effectAllowed='copy';});if(g.editable){const apply=button('Assign',()=>void assign(g.id,v.value,[...selected]));apply.dataset.assign='';apply.setAttribute('aria-label',`Assign ${g.label}: ${v.label} to selected locations`);row.append(apply);}section.append(row);}groupsHost.append(section);}
|
||||
const section=el('details');section.open=prefs.groups.branch!==false;section.append(el('summary','Parent / branch'));section.addEventListener('toggle',()=>{prefs.groups.branch=section.open;savePrefs();});const b=button('Filter by branch…',()=>parentDialog('Filter locations in branch',id=>{id?filters.set('branch',id):filters.delete('branch');render();},true));b.dataset.branchFilter='';section.append(b,button('Change selected parent…',()=>parentDialog('Change parent',id=>void assign('parent',id,[...selected]))));groupsHost.append(section);
|
||||
}
|
||||
function presentationIcon(v){if(v.path)return icon(v);const source=document.querySelector('[data-pwa-icon-catalog]')?.content.querySelector(`[data-icon-key="${v.icon}"]`);if(source){const n=source.cloneNode(true);n.removeAttribute('data-icon-key');n.classList.add('location-icon');return n;}return icon(types[0]);}
|
||||
function selection(){for(const row of host.querySelectorAll('[data-location-id]')){const id=Number(row.dataset.locationId);row.classList.toggle('is-selected',selected.has(id));row.querySelector('[data-select-location]').checked=selected.has(id);row.setAttribute('aria-selected',String(selected.has(id)));}groupsHost.querySelectorAll('[data-assign]').forEach(b=>b.disabled=!canEdit||busy||!selected.size);$('[data-selection-count]').textContent=`${selected.size} selected`;$('[data-selection-menu]').disabled=!selected.size;$('[data-undo]').disabled=busy;for(const s of ['[data-new-child]','[data-change-parent]','[data-create-relationship]'])$(s).disabled=!canEdit||busy||!records.has(active);}
|
||||
function render(){index();const matchesIds=new Set([...records.values()].filter(matches).map(r=>r.id)),filtered=!!query||filters.size>0,visibleIds=new Set(matchesIds);if(filtered&&prefs.view==='tree')for(const id of matchesIds)ancestors(id).forEach(p=>visibleIds.add(p));
|
||||
const order=[],visited=new Set();function walk(id,depth){if(visited.has(id))return;visited.add(id);if(filtered&&!visibleIds.has(id))return;order.push({id,depth});if(filtered||expanded.has(id))for(const c of children.get(id)||[])walk(c,depth+1);}
|
||||
if(prefs.view==='tree'){for(const id of children.get(null)||[])walk(id,0);/* Preserve visibility for malformed legacy cycles without recursing indefinitely. */if(!filtered)for(const id of records.keys())if(!visited.has(id)&&!ancestors(id).some(a=>visited.has(a)))walk(id,0);}else{const ids=[...matchesIds].sort((a,b)=>records.get(a).name.localeCompare(records.get(b).name,undefined,{numeric:true})*(prefs.sort==='desc'?-1:1));ids.forEach(id=>order.push({id,depth:0}));}
|
||||
const scroll=$('.locations-centre').scrollTop,focused=host.contains(document.activeElement)?document.activeElement.closest('[data-location-id]')?.dataset.locationId:null;rendered=order.map(x=>x.id);for(const id of selected)if(!matchesIds.has(id))selected.delete(id);
|
||||
host.className=prefs.view==='cards'?'locations-cards':'';host.setAttribute('role',prefs.view==='cards'?'list':'tree');host.setAttribute('aria-label',prefs.view==='cards'?'Location cards':'Location hierarchy');const fragment=document.createDocumentFragment();for(const {id,depth}of order)fragment.append(recordNode(records.get(id),depth,filtered&&!matchesIds.has(id)));if(!order.length)fragment.append(el('p',records.size?'No matching locations. Clear filters or try another name.':'Your world starts here. Create your first location.','muted'));host.replaceChildren(fragment);$('.locations-centre').scrollTop=scroll;if(focused)host.querySelector(`[data-location-id="${focused}"]`)?.focus({preventScroll:true});
|
||||
$('[data-result-count]').textContent=`${matchesIds.size} of ${records.size} locations${filtered&&prefs.view==='tree'?' · ancestors shown for context':''}`;
|
||||
for(const g of groups)for(const v of g.values){const row=[...groupsHost.querySelectorAll('[data-attribute]')].find(n=>n.dataset.attribute===g.id&&n.dataset.value===v.value);if(!row)continue;const old=filters.get(g.id);filters.set(g.id,v.value);row.querySelector('[data-count]').textContent=[...records.values()].filter(matches).length;old===undefined?filters.delete(g.id):filters.set(g.id,old);row.firstElementChild.setAttribute('aria-pressed',String(old===v.value));}
|
||||
const branch=groupsHost.querySelector('[data-branch-filter]');if(branch)branch.textContent=filters.has('branch')?`Branch: ${path(Number(filters.get('branch')))}`:'Filter by branch…';
|
||||
root.querySelectorAll('[data-view]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.view===prefs.view)));selection();
|
||||
}
|
||||
function recordNode(r,depth,context){const row=el('article',undefined,'location-record');row.dataset.locationId=r.id;row.dataset.pdContext='location';row.dataset.pdContextWeb='';row.dataset.pdContextId=r.id;row.dataset.pdContextLabel=r.name;row.tabIndex=0;row.style.setProperty('--depth',depth);row.setAttribute('role',prefs.view==='tree'?'treeitem':'listitem');if(prefs.view==='tree'){row.setAttribute('aria-level',String(depth+1));if(children.get(r.id)?.length)row.setAttribute('aria-expanded',String(expanded.has(r.id)||!!query||filters.size>0));}row.classList.toggle('is-active',r.id===active);row.classList.toggle('is-ancestor',active!==null&&ancestors(active).includes(r.id));row.classList.toggle('is-context',context);row.title=path(r.id);
|
||||
const main=el('div',undefined,'location-row-main'),check=el('input');check.type='checkbox';check.dataset.selectLocation='';check.setAttribute('aria-label',`Select ${r.name}`);check.addEventListener('change',e=>{if(e.shiftKey&&anchor&&rendered.includes(anchor)){const a=rendered.indexOf(anchor),b=rendered.indexOf(r.id);rendered.slice(Math.min(a,b),Math.max(a,b)+1).forEach(id=>selected.add(id));}else check.checked?selected.add(r.id):selected.delete(r.id);anchor=r.id;selection();});main.append(check);
|
||||
if(prefs.view==='tree'){const expand=button(children.get(r.id)?.length?(expanded.has(r.id)?'▾':'▸'):'',()=>{expanded.has(r.id)?expanded.delete(r.id):expanded.add(r.id);savePrefs();render();},'');expand.dataset.expandId=r.id;expand.disabled=!children.get(r.id)?.length;expand.setAttribute('aria-label',`${expanded.has(r.id)?'Collapse':'Expand'} ${r.name}`);main.append(expand);}
|
||||
const typeIcon=icon(type(r));typeIcon.setAttribute('role','img');typeIcon.setAttribute('aria-label',type(r)?.label||'Unclassified');typeIcon.removeAttribute('aria-hidden');main.append(typeIcon);
|
||||
const label=button(r.name,()=>select(r.id),'location-label');label.dataset.locationName='';main.append(label);if(children.get(r.id)?.length)main.append(el('span',String(children.get(r.id).length),'location-child-count'));
|
||||
const indicators=el('div',undefined,'location-indicators');for(const [condition,text,iconName]of [[r.classification,r.classification,r.classification==='Real'?'location-globe':r.classification==='Fictional'?'bible':'writer'],[r.maps.length,`${r.maps.length} map association(s)`,'maps'],[r.floors.length,`${r.floors.length} floor plan association(s)`,'floorplans'],[r.scenes,`${r.scenes} recorded scene assignment(s)`,'session']])if(condition){const n=el('span');n.title=text;n.setAttribute('role','img');n.setAttribute('aria-label',text);n.append(presentationIcon({icon:iconName}));indicators.append(n);}if(prefs.view==='tree')main.append(indicators);
|
||||
const handle=button('⠿',()=>{},'');handle.draggable=canEdit;handle.dataset.dragLocation='';handle.setAttribute('aria-label',`Drag ${r.name} to a parent or attribute`);handle.addEventListener('dragstart',e=>{drag={ids:scope(r.id)};e.dataTransfer.setData('application/x-plotdirector-locations',JSON.stringify(drag));e.dataTransfer.effectAllowed='move';});main.append(handle);
|
||||
const menu=button('⋯',e=>window.PlotDirectorContextMenus?.openAt(e.currentTarget,e.clientX,e.clientY,true),'btn btn-outline-secondary btn-sm location-row-menu');menu.setAttribute('aria-label',`Actions for ${r.name}`);menu.setAttribute('aria-haspopup','menu');main.append(menu);if(prefs.view==='cards')main.append(indicators);row.append(main);
|
||||
if(prefs.view==='cards'){row.append(el('p',path(r.id,false)||'Root location','location-card-path'),el('div',type(r)?.label||'Unclassified','location-type-caption'));if(r.description)row.append(el('p',r.description,'location-card-description'));}
|
||||
row.addEventListener('keydown',e=>{if(e.target!==row)return;if(e.key==='F2'&&canEdit){e.preventDefault();rename(r.id);}else if(e.key==='Enter'){e.preventDefault();select(r.id);}else if(e.key===' '){e.preventDefault();selected.has(r.id)?selected.delete(r.id):selected.add(r.id);selection();}else if(e.key==='ArrowRight'&&prefs.view==='tree'){e.preventDefault();if(children.get(r.id)?.length&&!expanded.has(r.id)){expanded.add(r.id);savePrefs();render();}else focusRow(children.get(r.id)?.[0]);}else if(e.key==='ArrowLeft'&&prefs.view==='tree'){e.preventDefault();if(expanded.delete(r.id)){savePrefs();render();}else focusRow(r.parent);}else if(['ArrowDown','ArrowUp','Home','End'].includes(e.key)){e.preventDefault();const i=rendered.indexOf(r.id);focusRow(e.key==='Home'?rendered[0]:e.key==='End'?rendered.at(-1):rendered[i+(e.key==='ArrowDown'?1:-1)]);}});
|
||||
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 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);}
|
||||
dialog.querySelector('[data-dialog-cancel]')?.addEventListener('click',()=>dialog.close());
|
||||
dialog.querySelector('[data-dialog-save]').addEventListener('click',async()=>{const b=dialog.querySelector('[data-dialog-save]');b.disabled=true;try{if(await dialogSave()!==false)dialog.close();}catch(e){dialog.querySelector('[data-dialog-error]').textContent=e.message;}finally{b.disabled=false;}});
|
||||
dialog.querySelector('form').addEventListener('submit',e=>{if(e.submitter?.value==='cancel')return;e.preventDefault();dialog.querySelector('[data-dialog-save]').click();});
|
||||
function parentDialog(title,save,filterOnly=false,ids=[...selected]){const body=el('div'),search=el('input');search.type='search';search.className='form-control';search.placeholder='Find a parent by name or path';search.setAttribute('aria-label','Search parent locations');const select=el('select');select.className='form-select';select.size=9;select.setAttribute('aria-label','Parent location');function options(){const q=search.value.toLocaleLowerCase();select.replaceChildren(new Option(filterOnly?'All branches':'Root level',''));for(const r of records.values()){if(!filterOnly&&(ids.includes(r.id)||ancestors(r.id).some(a=>ids.includes(a))))continue;const p=path(r.id);if(!q||p.toLocaleLowerCase().includes(q))select.add(new Option(p,String(r.id)));}select.value='';}search.addEventListener('input',options);body.append(search,select);options();openDialog(title,body,()=>save(select.value));}
|
||||
function 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 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(){if(dirty())return;const r=records.get(active);details.replaceChildren();if(!r){details.append(el('h2','Your world, in detail'),el('p','Select a location to edit its attributes and explore its connections.','muted'));return;}
|
||||
const heading=el('div',undefined,'location-detail-heading');heading.append(icon(type(r)),el('h2',r.name));details.append(heading,el('p',path(r.id),'location-details-path'));const actions=el('div',undefined,'location-detail-actions');for(const [label,action]of [['Full details','Details'],['Edit location','Edit']]){const a=el('a',label,'btn btn-outline-secondary btn-sm');a.href=`/Locations/${action}/${r.id}`;actions.append(a);}if(canEdit)actions.append(button('Rename',()=>{reveal(r.id);rename(r.id);}));details.append(actions);
|
||||
const attrs=el('div',undefined,'location-detail-attributes');for(const a of ['type','classification','quickAdd','detection'])attrs.append(field(groups.find(g=>g.id===a).label,attributeSelect(a,r)));const p=button(r.parent?path(r.id,false):'Root level',()=>parentDialog('Change parent',id=>void assign('parent',id,[r.id]),false,[r.id]));p.disabled=!canEdit;attrs.append(field('Parent',p));details.append(attrs);
|
||||
const description=el('section');description.append(el('h3','Description'));description.append(el('p',r.description||'No description recorded.','locations-description'));if(canEdit)description.append(button('Edit description',()=>{description.replaceChildren(el('h3','Description'));const input=el('textarea');input.dataset.descriptionEditor='';input.className='form-control';input.value=r.description;input.setAttribute('aria-label','Location description');descriptionDraft={id:r.id,original:r.description,value:r.description};input.addEventListener('input',()=>descriptionDraft.value=input.value);const controls=el('div',undefined,'location-detail-actions');controls.append(button('Save',async()=>{const draft=descriptionDraft;descriptionDraft=null;if(!await assign('description',input.value,[r.id])){descriptionDraft=draft;input.focus();}}),button('Cancel',()=>{descriptionDraft=null;renderDetails();if(pendingRefresh){pendingRefresh=false;void refresh();}}));description.append(input,controls);input.focus();}));details.append(description);
|
||||
const contained=el('section');contained.append(el('h3',`Contained locations · ${children.get(r.id)?.length||0}`));for(const id of children.get(r.id)||[])contained.append(button(records.get(id).name,()=>reveal(id),'btn btn-link btn-sm location-child-link'));if(canEdit)contained.append(button('Create child location',()=>createChild(r.id)));details.append(contained);
|
||||
const related=el('section');related.dataset.related='';related.append(el('h3','Connections'));for(const [label,items,route]of [['Maps',r.maps,'Maps'],['Floor plans',r.floors,'FloorPlans']]){related.append(el('h4',`${label} · ${items.length}`,'small'));for(const link of items){const a=el('a',link.name);a.href=route==='Maps'?`/Maps?projectId=${project}&id=${link.id}`:`/FloorPlans/Edit/${link.id}`;related.append(a);}}const a=el('a',`${r.scenes} recorded scene appearance(s) · relationships and characters`);a.href=`/Locations/Details/${r.id}`;related.append(a,el('p',`${r.relationships||0} relationships · ${r.characters||0} explicitly located characters · ${r.assets||0} assets currently here`,'small muted'));details.append(related);
|
||||
}
|
||||
function commands(id){const r=records.get(id);if(!r)return null;const ids=scope(id),bulk=ids.length>1,commands=[{label:bulk?`${ids.length} locations selected`:r.name,icon:'locations',disabled:true}];if(!bulk)commands.push({label:'View Location Details',icon:'details',run:()=>location.assign(`/Locations/Details/${id}`)},{label:'Edit Location',icon:'writer',run:()=>location.assign(`/Locations/Edit/${id}`)});
|
||||
if(canEdit){commands.push({separator:true});if(!bulk)commands.push({label:'Rename',icon:'writer',run:()=>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}"]`)};
|
||||
}
|
||||
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 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));});
|
||||
$('[data-selection-menu]').addEventListener('click',()=>{const id=selected.values().next().value;if(id)window.PlotDirectorContextMenus?.open(host.querySelector(`[data-location-id="${id}"]`));});
|
||||
function validParent(ids,parent){return !ids.some(id=>id===parent||ancestors(parent).includes(id));}
|
||||
root.addEventListener('dragover',e=>{if(!drag||!canEdit||busy)return;const attr=e.target.closest('[data-attribute]'),row=e.target.closest('[data-location-id]'),rootDrop=e.target.closest('[data-root-drop]');let target=null,valid=false;if(drag.attribute&&row){target=row;valid=true;}else if(drag.ids&&attr){target=attr;valid=groups.find(g=>g.id===attr.dataset.attribute)?.editable;}else if(drag.ids&&(row||rootDrop)){target=row||rootDrop;valid=validParent(drag.ids,row?Number(row.dataset.locationId):null);}
|
||||
root.querySelectorAll('.is-drop-target,.is-invalid-target').forEach(n=>n.classList.remove('is-drop-target','is-invalid-target'));if(!target)return;target.classList.add(valid?'is-drop-target':'is-invalid-target');if(valid){e.preventDefault();e.dataTransfer.dropEffect=drag.attribute?'copy':'move';}const id=row?Number(row.dataset.locationId):null;if(valid&&drag.ids&&id&&hoverId!==id){clearTimeout(hoverTimer);hoverId=id;hoverTimer=setTimeout(()=>{if(drag&&children.get(id)?.length&&!expanded.has(id)){expanded.add(id);render();}},650);}else if(!row){clearTimeout(hoverTimer);hoverId=null;}});
|
||||
root.addEventListener('drop',e=>{if(!drag)return;e.preventDefault();e.stopPropagation();const attr=e.target.closest('[data-attribute]'),row=e.target.closest('[data-location-id]'),rootDrop=e.target.closest('[data-root-drop]');if(drag.attribute&&row)void assign(drag.attribute,drag.value,scope(Number(row.dataset.locationId)));else if(drag.ids&&attr&&groups.find(g=>g.id===attr.dataset.attribute)?.editable)void assign(attr.dataset.attribute,attr.dataset.value,drag.ids);else if(drag.ids&&(row||rootDrop)){const parent=row?Number(row.dataset.locationId):null;if(validParent(drag.ids,parent)){if(parent)expanded.add(parent);savePrefs();void assign('parent',parent?.toString()||'',drag.ids);}else toast?.error('Choose a parent outside the selected branches.');}endDrag();});
|
||||
function endDrag(){drag=null;clearTimeout(hoverTimer);hoverId=null;root.querySelectorAll('.is-drop-target,.is-invalid-target').forEach(n=>n.classList.remove('is-drop-target','is-invalid-target'));}root.addEventListener('dragend',endDrag);
|
||||
$('[data-new-child]').addEventListener('click',()=>createChild(active));$('[data-change-parent]').addEventListener('click',()=>parentDialog('Change parent',p=>void assign('parent',p,selected.size?[...selected]:[active]),false,selected.size?[...selected]:[active]));$('[data-create-relationship]').addEventListener('click',()=>{if(active&&leaveDraft())location.assign(`/Locations/Details/${active}#location-relationships`);});
|
||||
$('[data-search]').addEventListener('input',e=>{query=e.target.value.trim().toLocaleLowerCase();render();});$('[data-clear-search]').addEventListener('click',()=>{$('[data-search]').value='';query='';render();});$('[data-clear-filters]').addEventListener('click',()=>{filters.clear();render();});$('[data-sort]').value=prefs.sort;$('[data-sort]').addEventListener('change',e=>{prefs.sort=e.target.value;savePrefs();render();});
|
||||
root.querySelectorAll('[data-view]').forEach(b=>b.addEventListener('click',()=>{if(!leaveDraft())return;descriptionDraft=null;prefs.view=b.dataset.view;savePrefs();render();renderDetails();}));root.querySelectorAll('[data-expand]').forEach(b=>b.addEventListener('click',()=>{expanded=b.dataset.expand==='true'?new Set(children.keys()):new Set();savePrefs();render();}));$('[data-reveal]').addEventListener('click',()=>reveal());$('[data-select-visible]').addEventListener('click',()=>{rendered.filter(id=>matches(records.get(id))).forEach(id=>selected.add(id));selection();});$('[data-clear-selection]').addEventListener('click',()=>{selected.clear();selection();});$('[data-undo]').addEventListener('click',()=>void assign(null,null,[],true,undo));
|
||||
function panels(){for(const side of ['attributes','details']){layout.classList.toggle(`${side}-collapsed`,prefs[side]);$(`.locations-${side}`).hidden=prefs[side];$(`[data-panel-toggle="${side}"]`).setAttribute('aria-expanded',String(!prefs[side]));}window.dispatchEvent(new Event('resize'));}root.querySelectorAll('[data-panel-toggle]').forEach(b=>b.addEventListener('click',()=>{const side=b.dataset.panelToggle;prefs[side]=!prefs[side];savePrefs();panels();}));
|
||||
root.dataset.workspacePreferenceScope=`${user}.${project}`;panels();const surfaceButton=button('Workspace',()=>{});window.PlotDirectorWorkspaceSurface?.attach(root,surfaceButton);function fit(){root.style.setProperty('--locations-top',`${Math.max(0,layout.getBoundingClientRect().top)}px`);}window.addEventListener('resize',fit);window.addEventListener('plotdirector:pwa-mode-changed',fit);requestAnimationFrame(fit);
|
||||
window.addEventListener('beforeunload',e=>{if(dirty()){e.preventDefault();e.returnValue='';}});
|
||||
function wire(c){if(connection||!c)return;connection=c;c.on('ContextInvalidated',hint=>{if(hint.projectId&&Number(hint.projectId)!==project)return;if(busy||dirty())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();
|
||||
})();
|
||||
@ -2,6 +2,7 @@
|
||||
if(window.PlotDirectorWorkspaceSurface)return;
|
||||
function panels(app, signal, single) {
|
||||
const profiles = [
|
||||
['locations', '.locations-layout', '.locations-attributes', '.locations-details', 240, 320],
|
||||
['relationships', '.rw-board', '.rw-navigation', '.rw-rail', 185, 230],
|
||||
['maps', '.maps-body', '.maps-library', '.maps-details', 220, 280],
|
||||
['floorplans', '.floor-plan-layout', '.floor-plan-build', '.floor-plan-inspector', 240, 280]
|
||||
|
||||