Refine location details hierarchy, relationships and spatial awareness

This commit is contained in:
Codex 2026-12-06 15:38:26 +00:00
parent 5a1950c79c
commit 85cc4b1358
11 changed files with 1086 additions and 142 deletions

View File

@ -3,11 +3,16 @@ using Microsoft.AspNetCore.Authorization;
using PlotLine.Services;
using PlotLine.Data;
using PlotLine.ViewModels;
using PlotLine.Models;
using PlotLine.Services.Context;
using Microsoft.Data.SqlClient;
namespace PlotLine.Controllers;
[Authorize]
public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography, IProjectRepository projects, ICurrentUserService currentUser, ContextSavedData savedData) : Controller
public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography, IProjectRepository projects, ICurrentUserService currentUser, ContextSavedData savedData,
LocationDetailsRepository details, ILocationRepository records, MapRepository maps,
IProjectActivityService activity) : Controller
{
public async Task<IActionResult> Index(int projectId)
{
@ -30,9 +35,85 @@ public sealed class LocationsController(ILocationService locations, GeographicHi
public async Task<IActionResult> Details(int id, string? tab = null)
{
ViewData["LocationTab"] = tab;
if (currentUser.UserId is not int userId) return Unauthorized();
var model = await locations.GetDetailAsync(id);
return model is null ? NotFound() : View(model);
if (model is null) return NotFound();
var project = await projects.GetForUserAsync(model.Project.ProjectID, userId);
if (project is null) return NotFound();
ViewData["LocationTab"] = tab == "geography" ? "spatial" : tab;
model.CanEdit = ContextEditPolicy.CanEdit(project) && !model.Location.IsArchived;
var directory = model.Locations.ToDictionary(location => location.LocationID);
var ancestors = new List<int>();
var seen = new HashSet<int>();
for (LocationItem? location = model.Location; location is not null && seen.Add(location.LocationID);
location = directory.GetValueOrDefault(location.ParentLocationID.GetValueOrDefault()))
{
ancestors.Add(location.LocationID);
}
model.Usage = await details.ReadUsageAsync(project.ProjectID, id);
model.Spatial = await details.ReadSpatialAsync(project.ProjectID, ancestors);
return View(model);
}
[HttpGet]
public async Task<IActionResult> DetailRelationships(int id)
{
var location = await records.GetAsync(id);
if (location is null) return NotFound();
var active = (await records.ListByProjectAsync(location.ProjectID))
.Where(item => !item.IsArchived).Select(item => item.LocationID).ToHashSet();
var relationships = (await records.ListRelationshipsByProjectAsync(location.ProjectID))
.Where(item => active.Contains(item.FromLocationID) && active.Contains(item.ToLocationID));
return Json(relationships);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> WriteDetailRelationship(LocationRelationshipEditViewModel model,
DateTime? expectedUpdatedDate, bool archive)
{
if (currentUser.UserId is not int userId) return Unauthorized();
if (!ModelState.IsValid || model.ProjectID <= 0 || model.LocationRelationshipID < 0 ||
model.FromLocationID <= 0 || model.ToLocationID <= 0 || model.FromLocationID == model.ToLocationID ||
model.Strength is < 1 or > 10 || (!archive && model.LocationRelationshipTypeID <= 0))
{
return BadRequest(new { error = "Check the locations, relationship type and strength." });
}
try
{
var id = await details.WriteRelationshipAsync(userId, model, expectedUpdatedDate, archive);
var verb = archive ? "Archived" : model.LocationRelationshipID == 0 ? "Created" : "Updated";
await activity.RecordAsync(model.ProjectID, verb, "Location Relationship", id, "Location relationship");
await savedData.Project(model.ProjectID, "locations", id, "Location Relationship");
return Json(new { id });
}
catch (SqlException ex) when (ex.Number == 51010)
{
return Forbid();
}
catch (SqlException ex) when (ex.Number == 51011)
{
return Conflict(new { error = ex.Message });
}
}
[HttpGet]
public async Task<IActionResult> SpatialMap(int id, int mapId, Guid featureId)
{
if (currentUser.UserId is not int userId) return Unauthorized();
var location = await records.GetAsync(id);
if (location is null) return NotFound();
var project = await projects.GetForUserAsync(location.ProjectID, userId);
if (project is null) return NotFound();
var document = await maps.GetAsync(project.ProjectID, mapId, userId);
if (document is null || !document.Features.Any(feature => feature.FeatureID == featureId && feature.IsPlaced))
return NotFound();
ViewData["SpatialRenderer"] = true;
ViewData["DetachedWorkspace"] = true;
return View("~/Views/Maps/Index.cshtml", new MapsViewModel { Project = project, Maps = [document.Map], Document = document });
}
public async Task<IActionResult> Merge(int id)

View File

@ -0,0 +1,57 @@
using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.ViewModels;
namespace PlotLine.Data;
public sealed class LocationDetailsRepository(ISqlConnectionFactory connections)
{
public async Task<IReadOnlyList<LocationUsageEntry>> ReadUsageAsync(int projectId, int locationId)
{
using var db = connections.CreateConnection();
return (await db.QueryAsync<LocationUsageEntry>("dbo.Location_DetailUsage",
new { ProjectID = projectId, LocationID = locationId }, commandType: CommandType.StoredProcedure)).AsList();
}
public async Task<LocationSpatialPreview> ReadSpatialAsync(int projectId, IReadOnlyList<int> ancestors)
{
using var db = connections.CreateConnection();
using var rows = await db.QueryMultipleAsync("dbo.Location_DetailSpatialLinks",
new { ProjectID = projectId, AncestorIDs = JsonSerializer.Serialize(ancestors) },
commandType: CommandType.StoredProcedure);
var map = await rows.ReadSingleOrDefaultAsync<LocationMapLink>();
var floor = await rows.ReadSingleOrDefaultAsync<LocationFloorLink>();
rows.Dispose();
if (floor is null) return new(map, null, null);
using var plan = await db.QueryMultipleAsync("dbo.FloorPlan_GetEditor", new { floor.FloorPlanID },
commandType: CommandType.StoredProcedure);
var header = await plan.ReadSingleOrDefaultAsync<FloorPlanEditViewModel>();
if (header?.ProjectID != projectId) return new(map, null, null);
return new(map, floor, new FloorPlanEditorViewModel
{
Project = new() { ProjectID = projectId },
FloorPlan = header,
Floors = (await plan.ReadAsync<FloorPlanFloorEditViewModel>()).AsList(),
Blocks = (await plan.ReadAsync<FloorPlanBlockEditViewModel>()).AsList(),
Transitions = (await plan.ReadAsync<FloorPlanTransitionEditViewModel>()).AsList()
});
}
public async Task<int> WriteRelationshipAsync(int userId, LocationRelationshipEditViewModel model,
DateTime? expectedUpdatedDate, bool archive)
{
using var db = connections.CreateConnection();
var parameters = new DynamicParameters(new
{
UserID = userId, model.ProjectID, model.LocationRelationshipID, model.FromLocationID, model.ToLocationID,
model.LocationRelationshipTypeID, model.IsBidirectional, model.Strength, model.CanHearNormalSpeech,
model.CanHearLoudNoise, model.CanSeeMovement, model.CanSeeClearly, model.CanTravelDirectly, model.Notes,
Archive = archive
});
parameters.Add("ExpectedUpdatedDate", expectedUpdatedDate, DbType.DateTime2, scale: 7);
return await db.QuerySingleAsync<int>("dbo.Location_DetailRelationshipWrite", parameters,
commandType: CommandType.StoredProcedure);
}
}

View File

@ -283,6 +283,7 @@ public class Program
builder.Services.AddScoped<IAssetService, AssetService>();
builder.Services.AddScoped<ICharacterService, CharacterService>();
builder.Services.AddScoped<ILocationService, LocationService>();
builder.Services.AddScoped<LocationDetailsRepository>();
builder.Services.AddScoped<IFloorPlanService, FloorPlanService>();
builder.Services.AddScoped<IContinuityValidationService, ContinuityValidationService>();
builder.Services.AddScoped<IAnalyticsService, AnalyticsService>();

View File

@ -8412,21 +8412,8 @@ public sealed class LocationService(
Project = project,
Location = location,
Aliases = await locations.ListAliasesAsync(location.LocationID),
ChildLocations = allLocations.Where(x => x.ParentLocationID == location.LocationID).ToList(),
Relationships = await locations.ListRelationshipsByLocationAsync(location.LocationID),
Scenes = await locations.ListScenesByLocationAsync(location.LocationID),
Characters = await locations.ListCharactersByLocationAsync(location.LocationID),
Assets = await locations.ListAssetsByLocationAsync(location.LocationID),
NewRelationship = new LocationRelationshipEditViewModel
{
ProjectID = project.ProjectID,
FromLocationID = location.LocationID,
LocationRelationshipTypeID = lookups.RelationshipTypes.FirstOrDefault()?.LocationRelationshipTypeID ?? 0
},
LocationOptions = allLocations.Where(x => x.LocationID != location.LocationID)
.Select(x => new SelectListItem(new string(' ', x.Depth * 2) + x.LocationName, x.LocationID.ToString()))
.ToList(),
RelationshipTypeOptions = ChapterService.ToSelectList(lookups.RelationshipTypes, x => x.LocationRelationshipTypeID, x => x.TypeName)
Locations = allLocations.Where(x => !x.IsArchived).ToList(),
RelationshipTypes = lookups.RelationshipTypes
};
}

View File

@ -0,0 +1,124 @@
CREATE OR ALTER PROCEDURE dbo.Location_DetailUsage
@ProjectID int,
@LocationID int
AS
BEGIN
SET NOCOUNT ON;
WITH Placements AS
(
SELECT s.SceneID, N'Scenes' AS Kind, s.SceneTitle AS Name, CAST(NULL AS nvarchar(max)) AS Description
FROM dbo.Scenes s WHERE s.PrimaryLocationID = @LocationID
UNION ALL
SELECT sc.SceneID, N'Characters', c.CharacterName, NULL
FROM dbo.SceneCharacters sc
JOIN dbo.Characters c ON c.CharacterID = sc.CharacterID
WHERE sc.LocationID = @LocationID AND c.ProjectID = @ProjectID AND c.IsArchived = 0
UNION ALL
SELECT sal.SceneID, N'Assets', a.AssetName, sal.Description
FROM dbo.SceneAssetLocations sal
JOIN dbo.StoryAssets a ON a.StoryAssetID = sal.StoryAssetID
WHERE sal.LocationID = @LocationID AND a.ProjectID = @ProjectID AND a.IsArchived = 0
)
SELECT p.Kind, p.Name, p.Description, manuscript.BookID, manuscript.BookTitle, manuscript.BookSubtitle,
c.ChapterID, c.ChapterNumber, c.ChapterTitle, manuscript.SceneID, manuscript.SceneNumber
FROM Placements p
JOIN dbo.CharacterWorkspace_SceneOrder(@ProjectID) manuscript ON manuscript.SceneID = p.SceneID
JOIN dbo.Chapters c ON c.ChapterID = manuscript.ChapterID
ORDER BY manuscript.Ordinal, p.Name;
END;
GO
CREATE OR ALTER PROCEDURE dbo.Location_DetailSpatialLinks
@ProjectID int,
@AncestorIDs nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP (1) f.LocationID, m.MapID, m.Name, f.FeatureID
FROM OPENJSON(@AncestorIDs) scope
JOIN dbo.MapFeatures f ON f.LocationID = TRY_CONVERT(int, scope.value)
JOIN dbo.StoryMaps m ON m.MapID = f.MapID
WHERE m.ProjectID = @ProjectID AND f.IsPlaced = 1
ORDER BY CONVERT(int, scope.[key]), m.Name, m.MapID, f.FeatureID;
SELECT TOP (1) association.LocationID, p.FloorPlanID, p.Name, f.FloorPlanFloorID, association.FloorPlanBlockID
FROM dbo.FloorPlans p
JOIN dbo.FloorPlanFloors f ON f.FloorPlanID = p.FloorPlanID
CROSS APPLY
(
SELECT p.LocationID, CAST(NULL AS int) AS FloorPlanBlockID, 2 AS Specificity
UNION ALL SELECT f.LocationID, NULL, 1
UNION ALL SELECT b.LocationID, b.FloorPlanBlockID, 0
FROM dbo.FloorPlanBlocks b WHERE b.FloorPlanFloorID = f.FloorPlanFloorID
) association
JOIN OPENJSON(@AncestorIDs) scope ON TRY_CONVERT(int, scope.value) = association.LocationID
WHERE p.ProjectID = @ProjectID
ORDER BY CONVERT(int, scope.[key]), association.Specificity, p.Name, p.FloorPlanID, f.SortOrder, f.FloorPlanFloorID, association.FloorPlanBlockID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.Location_DetailRelationshipWrite
@UserID int,
@ProjectID int,
@LocationRelationshipID int,
@FromLocationID int,
@ToLocationID int,
@LocationRelationshipTypeID int,
@IsBidirectional bit,
@Strength int = NULL,
@CanHearNormalSpeech bit,
@CanHearLoudNoise bit,
@CanSeeMovement bit,
@CanSeeClearly bit,
@CanTravelDirectly bit,
@Notes nvarchar(max) = NULL,
@ExpectedUpdatedDate datetime2 = NULL,
@Archive bit = 0
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF NOT EXISTS (SELECT 1 FROM dbo.ProjectUserAccess a WITH (HOLDLOCK)
JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = a.ProjectID AND p.IsArchived = 0
WHERE a.ProjectID = @ProjectID AND a.UserID = @UserID AND a.IsActive = 1 AND a.AccessRole IN (N'Owner', N'Collaborator'))
THROW 51010, 'Editing is unavailable.', 1;
IF @FromLocationID = @ToLocationID OR 2 <> (SELECT COUNT(*) FROM dbo.Locations WITH (HOLDLOCK)
WHERE LocationID IN (@FromLocationID, @ToLocationID) AND ProjectID = @ProjectID AND IsArchived = 0)
THROW 51011, 'Choose two active locations in this project.', 1;
IF @LocationRelationshipID <> 0 AND NOT EXISTS
(
SELECT 1 FROM dbo.LocationRelationships WITH (UPDLOCK, HOLDLOCK)
WHERE LocationRelationshipID = @LocationRelationshipID AND IsArchived = 0
AND FromLocationID = @FromLocationID AND ToLocationID = @ToLocationID
AND UpdatedDate = @ExpectedUpdatedDate
)
THROW 51011, 'This relationship changed. Reload the matrix and try again.', 1;
IF @Archive = 1
BEGIN
IF @LocationRelationshipID = 0 THROW 51011, 'Choose a saved relationship to archive.', 1;
EXEC dbo.LocationRelationship_Archive @LocationRelationshipID;
SELECT @LocationRelationshipID;
END
ELSE
BEGIN
IF NOT EXISTS (SELECT 1 FROM dbo.LocationRelationshipTypes
WHERE LocationRelationshipTypeID = @LocationRelationshipTypeID AND IsActive = 1)
AND NOT EXISTS (SELECT 1 FROM dbo.LocationRelationships
WHERE LocationRelationshipID = @LocationRelationshipID AND LocationRelationshipTypeID = @LocationRelationshipTypeID)
THROW 51011, 'Choose an available relationship type.', 1;
EXEC dbo.LocationRelationship_Save @LocationRelationshipID, @FromLocationID, @ToLocationID,
@LocationRelationshipTypeID, @IsBidirectional, @Strength, @CanHearNormalSpeech, @CanHearLoudNoise,
@CanSeeMovement, @CanSeeClearly, @CanTravelDirectly, @Notes;
END
COMMIT;
END;
GO

View File

@ -2326,16 +2326,21 @@ public sealed class LocationDetailViewModel
public Project Project { get; set; } = new();
public LocationItem Location { get; set; } = new();
public IReadOnlyList<LocationAlias> Aliases { get; set; } = [];
public IReadOnlyList<LocationItem> ChildLocations { get; set; } = [];
public IReadOnlyList<LocationRelationship> Relationships { get; set; } = [];
public IReadOnlyList<Scene> Scenes { get; set; } = [];
public IReadOnlyList<SceneCharacter> Characters { get; set; } = [];
public IReadOnlyList<SceneAssetLocation> Assets { get; set; } = [];
public LocationRelationshipEditViewModel NewRelationship { get; set; } = new();
public IReadOnlyList<SelectListItem> LocationOptions { get; set; } = [];
public IReadOnlyList<SelectListItem> RelationshipTypeOptions { get; set; } = [];
public IReadOnlyList<LocationItem> Locations { get; set; } = [];
public IReadOnlyList<LocationRelationshipType> RelationshipTypes { get; set; } = [];
public IReadOnlyList<LocationUsageEntry> Usage { get; set; } = [];
public LocationSpatialPreview? Spatial { get; set; }
public bool CanEdit { get; set; }
}
public sealed record LocationUsageEntry(string Kind, string Name, string? Description,
int BookID, string BookTitle, string? BookSubtitle, int ChapterID, decimal ChapterNumber,
string ChapterTitle, int SceneID, decimal SceneNumber);
public sealed record LocationMapLink(int LocationID, int MapID, string Name, Guid FeatureID);
public sealed record LocationFloorLink(int LocationID, int FloorPlanID, string Name, int FloorPlanFloorID, int? FloorPlanBlockID);
public sealed record LocationSpatialPreview(LocationMapLink? Map, LocationFloorLink? Floor, FloorPlanEditorViewModel? FloorPlan);
public sealed class LocationRelationshipEditViewModel
{
public int LocationRelationshipID { get; set; }

View File

@ -1,11 +1,13 @@
@model LocationDetailViewModel
@using System.Text.Json
@using PlotLine.Models
@{
ViewData["DesktopLayout"] = "details";
ViewData["Title"] = Model.Location.LocationName;
ViewData["ProjectSection"] = "Locations";
IReadOnlyList<(string Id, string Label)> tabs =
[("overview", "Overview"), ("reference", "Reference"), ("hierarchy", "Hierarchy"),
("relationships", "Relationships"), ("usage", "Usage"), ("geography", "Geography")];
("relationships", "Relationships"), ("usage", "Usage"), ("spatial", "Spatial awareness")];
var requestedTab = ViewData["LocationTab"] as string;
var activeTab = tabs.Any(tab => tab.Id == requestedTab) ? requestedTab! : "overview";
var knownNames = Model.Aliases
@ -102,90 +104,44 @@
</div>
<div class="tab-pane @(activeTab == "hierarchy" ? "active" : null)" id="location-panel-hierarchy" role="tabpanel"
aria-labelledby="location-tab-hierarchy" tabindex="0">
<section class="edit-panel">
<section class="edit-panel" data-location-hierarchy>
<h2>Hierarchy</h2>
<p class="eyebrow">Parent</p>
<p>@(Model.Location.ParentLocationName ?? "Top level")</p>
<h3>Child locations <help-icon key="locations.childLocations" /></h3>
@if (!Model.ChildLocations.Any())
{
<p class="muted">No child locations yet.</p>
}
else
{
<div class="location-chip-list">
@foreach (var child in Model.ChildLocations)
{
<a class="location-chip" asp-action="Details" asp-route-id="@child.LocationID">@child.LocationName</a>
}
</div>
}
<div class="button-row mb-2">
<button type="button" class="btn btn-outline-secondary btn-sm" data-tree-zoom="0.8" aria-label="Zoom out">−</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-tree-zoom="1.25" aria-label="Zoom in">+</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-tree-fit>Fit</button>
<button type="button" class="btn btn-outline-secondary btn-sm" data-tree-centre>Centre on current location</button>
</div>
<div class="location-tree-viewport" tabindex="0" aria-label="Location hierarchy. Drag blank space or scroll to pan.">
<div class="location-tree-space"><div class="location-tree-graph"></div></div>
</div>
</section>
</div>
<div class="tab-pane @(activeTab == "relationships" ? "active" : null)" id="location-panel-relationships" role="tabpanel"
aria-labelledby="location-tab-relationships" tabindex="0">
<section class="edit-panel">
<section class="edit-panel" data-location-matrix
data-read-url="@Url.Action("DetailRelationships", new { id = Model.Location.LocationID })"
data-write-url="@Url.Action("WriteDetailRelationship")">
<h2 id="location-relationships">Relationships <help-icon key="locations.relationships" /></h2>
@if (!Model.Relationships.Any())
{
<p class="muted">No relationships defined yet.</p>
}
else
{
<div class="location-relationship-list">
@foreach (var relationship in Model.Relationships)
{
<div class="location-relationship-card">
<div>
<strong>@relationship.FromLocationName</strong>
<span>@relationship.RelationshipTypeName.ToLowerInvariant()</span>
<strong>@relationship.ToLocationName</strong>
@if (relationship.IsBidirectional)
{
<span class="location-badge">both ways</span>
}
<p class="muted">@relationship.Notes</p>
</div>
<form asp-action="ArchiveRelationship" method="post" data-confirm-message="Archive this location relationship?&#10;&#10;This will hide it from active lists and timelines, but the data will be kept and can be restored later.">
<input type="hidden" name="id" value="@relationship.LocationRelationshipID" />
<input type="hidden" name="returnLocationId" value="@Model.Location.LocationID" />
<button class="btn btn-outline-secondary btn-sm" type="submit">Archive</button>
</form>
</div>
}
</div>
}
<form asp-action="AddRelationship" method="post" class="asset-create-form mt-3">
<input asp-for="NewRelationship.ProjectID" type="hidden" name="ProjectID" />
<input asp-for="NewRelationship.FromLocationID" type="hidden" name="FromLocationID" />
<div class="row g-2">
<div class="col-md-5">
<label class="form-label" for="ToLocationID">To location</label>
<select data-location-picker data-project-id="@Model.Project.ProjectID" data-exclude-id="@Model.Location.LocationID" data-picker-label="Choose related location" class="form-select form-select-sm" id="ToLocationID" name="ToLocationID" asp-items="Model.LocationOptions"></select>
</div>
<div class="col-md-4">
<label class="form-label" for="LocationRelationshipTypeID">Relationship</label>
<select class="form-select form-select-sm" id="LocationRelationshipTypeID" name="LocationRelationshipTypeID" asp-items="Model.RelationshipTypeOptions"></select>
</div>
<div class="col-md-3">
<label class="form-label" for="Strength">Strength</label>
<input class="form-control form-control-sm" id="Strength" name="Strength" type="number" min="1" max="10" />
</div>
<div class="col-12 location-flags">
<label><input type="checkbox" name="IsBidirectional" value="true" /> Bidirectional</label>
<label><input type="checkbox" name="CanHearNormalSpeech" value="true" /> Can hear normal 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">
<textarea class="form-control form-control-sm" name="Notes" rows="2" placeholder="Relationship notes"></textarea>
</div>
</div>
<button class="btn btn-outline-primary btn-sm mt-2" type="submit">Add relationship</button>
</form>
@Html.AntiForgeryToken()
<div class="location-matrix-tools">
<label>Relationship type
<select class="form-select form-select-sm" data-matrix-filter><option value="">All types</option></select>
</label>
<label>Add a location to this matrix
<select class="form-select form-select-sm" data-matrix-add><option value="">Choose location</option></select>
</label>
</div>
<p class="small muted">Rows are the starting locations. Columns are the destinations. Select a cell to inspect both directions.</p>
<details class="mb-2">
<summary>Legend</summary>
<div class="location-matrix-legend" data-matrix-legend></div>
</details>
<p role="alert" data-matrix-error hidden></p>
<div class="location-matrix-scroll" tabindex="0" aria-label="Relationship matrix">
<table class="location-matrix-table" data-matrix-table aria-label="Location relationships"></table>
</div>
<div class="location-direction-panels mt-3" data-matrix-editor></div>
</section>
</div>
<div class="tab-pane @(activeTab == "usage" ? "active" : null)" id="location-panel-usage" role="tabpanel"
@ -193,51 +149,80 @@
<section class="edit-panel">
<h2>Used here <help-icon key="locations.usedHere" /></h2>
<div class="row g-3">
<div class="col-md-4">
<h3>Scenes</h3>
@foreach (var scene in Model.Scenes)
{
<p><strong>@SceneLabel(scene.ChapterNumber, scene.SceneNumber)</strong> <a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID" asp-route-SelectedSceneID="@scene.SceneID" asp-route-FocusType="location" asp-route-FocusID="@Model.Location.LocationID" asp-route-navigateFocus="true">@scene.SceneTitle</a></p>
}
@if (!Model.Scenes.Any()) { <p class="muted">No scenes set here.</p> }
</div>
<div class="col-md-4">
<h3>Characters</h3>
@foreach (var character in Model.Characters)
{
<p><strong>@character.CharacterName</strong> <span class="muted">@SceneLabel(character.ChapterNumber, character.SceneNumber)</span></p>
}
@if (!Model.Characters.Any()) { <p class="muted">No character placements yet.</p> }
</div>
<div class="col-md-4">
<h3>Assets</h3>
@foreach (var asset in Model.Assets)
{
<p><strong>@asset.AssetName</strong> <span class="muted">@asset.Description</span></p>
}
@if (!Model.Assets.Any()) { <p class="muted">No asset placements yet.</p> }
</div>
@foreach (var kind in new[] { "Scenes", "Characters", "Assets" })
{
<div class="col-md-4">
<h3>@kind</h3>
@foreach (var book in Model.Usage.Where(entry => entry.Kind == kind).GroupBy(entry => entry.BookID))
{
<h4>@BookTitleFormatter.DisplayTitle(book.First().BookTitle, book.First().BookSubtitle)</h4>
@foreach (var chapter in book.GroupBy(entry => entry.ChapterID))
{
var header = chapter.First();
<h5>Chapter @header.ChapterNumber.ToString("g") · @header.ChapterTitle</h5>
<ul class="location-usage-list">
@foreach (var entry in chapter)
{
<li>
<a asp-controller="Timeline" asp-action="Index" asp-route-ProjectID="@Model.Project.ProjectID"
asp-route-BookID="@entry.BookID" asp-route-SelectedSceneID="@entry.SceneID" asp-route-FocusType="location"
asp-route-FocusID="@Model.Location.LocationID" asp-route-navigateFocus="true">Scene @entry.SceneNumber.ToString("g")</a>
<strong>@entry.Name</strong>
@if (!string.IsNullOrWhiteSpace(entry.Description))
{
<span class="muted">@entry.Description</span>
}
</li>
}
</ul>
}
}
@if (!Model.Usage.Any(entry => entry.Kind == kind))
{
<p class="muted">No @kind.ToLowerInvariant() recorded here.</p>
}
</div>
}
</div>
</section>
</div>
<div class="tab-pane @(activeTab == "geography" ? "active" : null)" id="location-panel-geography" role="tabpanel"
aria-labelledby="location-tab-geography" tabindex="0">
<section class="edit-panel" data-geography-location="@Model.Location.LocationID" data-project-id="@Model.Project.ProjectID">
<h2>Geographical position</h2>
<p role="status" data-geography-status>Loading…</p>
<div data-geography-body></div>
</section>
@Html.AntiForgeryToken()
<div class="tab-pane @(activeTab == "spatial" ? "active" : null)" id="location-panel-spatial" role="tabpanel"
aria-labelledby="location-tab-spatial" tabindex="0">
<partial name="_LocationSpatialPreview" model="Model" />
<details class="edit-panel">
<summary>Geographical lookup</summary>
<div class="mt-2" data-geography-location="@Model.Location.LocationID" data-project-id="@Model.Project.ProjectID">
<p role="status" data-geography-status>Loading…</p>
<div data-geography-body></div>
</div>
@Html.AntiForgeryToken()
</details>
</div>
</div>
</div>
@functions {
private static string SceneLabel(decimal chapterNumber, decimal sceneNumber)
=> chapterNumber > 0 ? $"Chapter {chapterNumber:g}, Scene {sceneNumber:g}" : $"Scene {sceneNumber:g}";
}
<script type="application/json" id="location-detail-data">@Html.Raw(JsonSerializer.Serialize(new
{
Current = Model.Location.LocationID,
Model.Project.ProjectID,
Model.CanEdit,
Locations = Model.Locations.Append(Model.Location).DistinctBy(location => location.LocationID)
.Select(location => new
{
Id = location.LocationID,
Parent = location.ParentLocationID,
Name = location.LocationName,
Path = location.LocationPath,
HierarchyUrl = Url.Action("Details", new { id = location.LocationID, tab = "hierarchy" })
}),
Types = Model.RelationshipTypes.Select(type => new { Id = type.LocationRelationshipTypeID, Name = type.TypeName })
}, new JsonSerializerOptions(JsonSerializerDefaults.Web)))</script>
@section Scripts {
<link rel="stylesheet" href="~/css/floor-plan-workspace.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/location-details.css" asp-append-version="true" />
<script src="~/js/floor-plan-renderer.js" asp-append-version="true" defer></script>
<script src="~/js/location-details.js" asp-append-version="true" defer></script>
<script src="~/js/location-geography.js" asp-append-version="true" defer></script>
<link rel="stylesheet" href="~/css/story-element-references.css" asp-append-version="true" />
<script src="~/js/story-element-references.js" asp-append-version="true"></script>

View File

@ -0,0 +1,53 @@
@model LocationDetailViewModel
@{
var map = Model.Spatial?.Map;
var floor = Model.Spatial?.Floor;
var plan = Model.Spatial?.FloorPlan;
string Caption(int id) => id == Model.Location.LocationID
? Model.Location.LocationName
: $"Containing location: {Model.Locations.FirstOrDefault(item => item.LocationID == id)?.LocationName}";
}
<section class="edit-panel">
<h2>Spatial awareness</h2>
@if (map is not null)
{
<h3>@map.Name</h3>
<p>@Caption(map.LocationID)</p>
<div class="button-row mb-2">
<button type="button" class="btn btn-outline-secondary btn-sm" data-map-centre>Centre on mapped location</button>
<a asp-controller="Maps" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID"
asp-route-id="@map.MapID" asp-route-featureId="@map.FeatureID">Open map in Maps</a>
</div>
<iframe class="location-map-frame" title="Map of @Caption(map.LocationID)" data-location-map="@map.FeatureID"
data-map-label="@Caption(map.LocationID)"
data-src="@Url.Action("SpatialMap", new { id = Model.Location.LocationID, mapId = map.MapID, featureId = map.FeatureID })"></iframe>
}
@if (floor is not null && plan is not null)
{
<h3>@floor.Name</h3>
<p>@Caption(floor.LocationID)@(floor.FloorPlanBlockID.HasValue ? "" : " · No room is linked to this location.")</p>
<p><a asp-controller="FloorPlans" asp-action="Edit" asp-route-id="@floor.FloorPlanID"
asp-route-selectedBlockId="@floor.FloorPlanBlockID">Open plan in Floor Plans</a></p>
<div class="location-floor-preview" data-location-floor="@floor.FloorPlanFloorID" data-location-block="@floor.FloorPlanBlockID">
<label>Floor
<select class="form-select form-select-sm" data-floor-level>
@foreach (var level in plan.Floors.OrderBy(level => level.SortOrder).ThenBy(level => level.Name))
{
<option value="@level.FloorPlanFloorID" selected="@(level.FloorPlanFloorID == floor.FloorPlanFloorID)">@level.Name</option>
}
</select>
</label>
<div class="location-floor-scroll mt-2" tabindex="0" aria-label="Floor plan preview">
<partial name="~/Views/FloorPlans/_FloorPlanStage.cshtml" model="plan" />
</div>
</div>
}
@if (map is null && floor is null)
{
<p>No placed map feature or floor plan is linked to this location or its containing locations.</p>
}
<div class="button-row">
<a asp-controller="Maps" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Browse Maps</a>
<a asp-controller="FloorPlans" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Browse Floor Plans</a>
</div>
</section>

View File

@ -0,0 +1,131 @@
.location-tree-viewport,
.location-matrix-scroll,
.location-floor-scroll {
overflow: auto;
border: 1px solid var(--bs-border-color);
border-radius: .5rem;
background: var(--bs-body-bg);
color: var(--bs-body-color);
}
.location-tree-viewport {
height: clamp(20rem, 55vh, 40rem);
cursor: grab;
}
.location-tree-viewport:active { cursor: grabbing; }
.location-tree-space { position: relative; }
.location-tree-graph {
position: absolute;
left: 50%;
top: 1rem;
width: max-content;
transform-origin: top center;
translate: -50% 0;
padding: 0 .75rem 1rem;
--tree-line: var(--bs-secondary-color);
}
.location-tree-branch { display: flex; flex-direction: column; align-items: center; position: relative; }
.location-tree-node {
display: flex;
align-items: center;
gap: .35rem;
border: 1px solid var(--bs-border-color);
background: var(--bs-tertiary-bg);
border-radius: .45rem;
padding: .5rem .7rem;
}
.location-tree-node a { max-width: 15rem; overflow-wrap: anywhere; }
.location-tree-node[data-current] { background: #f6cc7c; border-color: #9a6008; }
.location-tree-node[data-current] a { color: #352000; font-weight: 700; }
.location-tree-toggle {
border: 1px solid currentColor;
border-radius: .25rem;
color: inherit;
background: transparent;
line-height: 1;
padding: .2rem .35rem;
}
.location-tree-children { display: flex; position: relative; padding-top: 2rem; }
.location-tree-children[hidden] { display: none; }
.location-tree-children::before,
.location-tree-children > .location-tree-branch::before,
.location-tree-children > .location-tree-branch::after {
position: absolute;
content: "";
pointer-events: none;
}
.location-tree-children::before { left: 50%; top: 0; height: 1rem; border-left: 1px solid var(--tree-line); }
.location-tree-children > .location-tree-branch { padding: 0 .55rem; }
.location-tree-children > .location-tree-branch::before {
left: 50%;
top: -1rem;
height: 1rem;
border-left: 1px solid var(--tree-line);
}
.location-tree-children > .location-tree-branch::after {
top: -1rem;
left: 0;
right: 0;
border-top: 1px solid var(--tree-line);
}
.location-tree-children > .location-tree-branch:first-child::after { left: 50%; }
.location-tree-children > .location-tree-branch:last-child::after { right: 50%; }
.location-matrix-tools,
.location-matrix-legend { display: flex; flex-wrap: wrap; gap: .5rem 1rem; }
.location-matrix-tools { margin-bottom: .75rem; }
.location-matrix-tools select { max-width: min(24rem, 76vw); }
.location-matrix-scroll { max-height: 58vh; }
.location-matrix-table { border-collapse: separate; border-spacing: 0; min-width: 100%; }
.location-matrix-table th,
.location-matrix-table td {
border-right: 1px solid var(--bs-border-color);
border-bottom: 1px solid var(--bs-border-color);
background: var(--bs-body-bg);
color: var(--bs-body-color);
}
.location-matrix-table th { background: var(--bs-tertiary-bg); padding: .4rem .55rem; min-width: 7rem; }
.location-matrix-table thead th { position: sticky; top: 0; z-index: 2; }
.location-matrix-table tr > :first-child { position: sticky; left: 0; z-index: 1; }
.location-matrix-table thead tr > :first-child { z-index: 3; }
.location-matrix-table .location-matrix-current {
background: var(--bs-warning-bg-subtle);
color: var(--bs-warning-text-emphasis);
}
.location-matrix-table td { text-align: center; padding: 0; }
.location-matrix-cell {
width: 100%;
min-height: 2.4rem;
padding: .25rem;
border: 1px solid transparent;
color: inherit;
background: transparent;
}
.location-matrix-cell:hover,
.location-matrix-cell[aria-pressed="true"] { border-color: var(--bs-primary); background: var(--bs-primary-bg-subtle); }
.location-matrix-indicator { display: block; white-space: nowrap; }
.location-direction-panels { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .75rem; }
.location-direction-panel {
padding: .8rem;
border: 1px solid var(--bs-border-color);
border-radius: .5rem;
background: var(--bs-body-bg);
color: var(--bs-body-color);
}
.location-direction-panel h3 { overflow-wrap: anywhere; }
.location-direction-field,
.location-direction-check { display: flex; gap: .35rem; margin-bottom: .55rem; }
.location-direction-field { flex-direction: column; }
.location-direction-check { align-items: baseline; }
.location-usage-list { padding-inline-start: 1rem; }
.location-map-frame { width: 100%; height: clamp(18rem, 52vh, 38rem); border: 1px solid var(--bs-border-color); }
.location-floor-scroll { max-height: 55vh; }
.location-floor-preview [data-floor-level] { width: auto; }
.location-floor-preview .location-floor-current { outline: 3px solid #e5a930; outline-offset: -3px; z-index: 2; }
@media (max-width: 640px) {
.location-direction-panels { grid-template-columns: minmax(0, 1fr); }
}
.location-floor-preview .floor-plan-grid-wrap { max-height: none; overflow: visible; }
.location-floor-preview .floor-plan-stage button { cursor: default; }
.location-floor-preview .floor-plan-resize-handle { display: none; }

View File

@ -5,7 +5,7 @@
const origin=location.origin;let channel=null,highlights=[],pointer=null;
const send=(action,extra={})=>{if(channel)parent.postMessage({type:'plotdirector.spatial.renderer',channel,action,...extra},origin);};
const ns='http://www.w3.org/2000/svg',layer=document.createElementNS(ns,'g');layer.dataset.spatialOverlay='';layer.setAttribute('pointer-events','none');canvas.append(layer);
function paint(){const relevant=new Set(highlights.map(h=>h.featureID));for(const feature of canvas.querySelectorAll('[data-feature-id]'))feature.classList.toggle('spatial-map-background',relevant.size>0&&!relevant.has(feature.dataset.featureId));layer.replaceChildren();const scale=api.view.w/Math.max(canvas.clientWidth,1);for(const item of highlights){const f=api.document.features.find(f=>f.featureID===item.featureID);if(!f||!f.isPlaced)continue;const g=document.createElementNS(ns,'g');g.setAttribute('transform',`translate(${f.x} ${f.y})`);g.setAttribute('role','img');g.setAttribute('aria-label',item.label);const roles=[...new Set(item.roles)].sort((a,b)=>a-b);for(let i=0;i<roles.length;i++){const c=document.createElementNS(ns,'circle');c.setAttribute('r',String((15+i*5)*scale));c.setAttribute('class',`spatial-map-ring spatial-position-${roles[i]+1}`);c.setAttribute('fill','none');c.setAttribute('stroke-width',String(3*scale));g.append(c);}const text=document.createElementNS(ns,'text');text.textContent=roles.map(r=>['P','C','N'][r+1]).join(' · ');text.setAttribute('x',String(24*scale));text.setAttribute('y',String(-18*scale));text.setAttribute('font-size',String(13*scale));text.setAttribute('class','spatial-map-badge');g.append(text);const title=document.createElementNS(ns,'title');title.textContent=item.label;g.append(title);layer.append(g);}}
function paint(){const relevant=new Set(highlights.map(h=>h.featureID));for(const feature of canvas.querySelectorAll('[data-feature-id]'))feature.classList.toggle('spatial-map-background',relevant.size>0&&!relevant.has(feature.dataset.featureId));layer.replaceChildren();const scale=api.view.w/Math.max(canvas.clientWidth,1);for(const item of highlights){const f=api.document.features.find(f=>f.featureID===item.featureID);if(!f||!f.isPlaced)continue;const g=document.createElementNS(ns,'g');g.setAttribute('transform',`translate(${f.x} ${f.y})`);g.setAttribute('role','img');g.setAttribute('aria-label',item.label);const roles=[...new Set(item.roles)].sort((a,b)=>a-b);for(let i=0;i<roles.length;i++){const c=document.createElementNS(ns,'circle');c.setAttribute('r',String((15+i*5)*scale));c.setAttribute('class',`spatial-map-ring spatial-position-${roles[i]+1}`);c.setAttribute('fill','none');c.setAttribute('stroke-width',String(3*scale));g.append(c);}const text=document.createElementNS(ns,'text');text.textContent=item.badge??roles.map(r=>['P','C','N'][r+1]).join(' · ');text.setAttribute('x',String(24*scale));text.setAttribute('y',String(-18*scale));text.setAttribute('font-size',String(13*scale));text.setAttribute('class','spatial-map-badge');g.append(text);const title=document.createElementNS(ns,'title');title.textContent=item.label;g.append(title);layer.append(g);}}
app.addEventListener('map-rendered',()=>{paint();send('viewport',{view:api.view});});
window.addEventListener('message',async e=>{if(e.origin!==origin||e.source!==parent||e.data?.type!=='plotdirector.spatial.command')return;const m=e.data;if(channel&&m.channel!==channel)return;channel=m.channel;
if(m.action==='init'){if(m.view)api.setView(m.view);send('ready',{map:api.document.map,features:api.document.features,view:api.view});}

View File

@ -0,0 +1,520 @@
(() => {
const source = document.getElementById('location-detail-data');
if (!source) return;
const data = JSON.parse(source.textContent);
const locations = new Map(data.locations.map(item => [item.id, item]));
const ordered = [...locations.values()].sort((a, b) => a.name.localeCompare(b.name) || a.id - b.id);
const children = new Map();
for (const item of ordered) {
if (!children.has(item.parent)) children.set(item.parent, []);
children.get(item.parent).push(item);
}
function element(tag, text, className) {
const node = document.createElement(tag);
if (text != null) node.textContent = text;
if (className) node.className = className;
return node;
}
function button(text, action, className = 'btn btn-outline-secondary btn-sm') {
const node = element('button', text, className);
node.type = 'button';
node.addEventListener('click', action);
return node;
}
function onTab(name, callback) {
const pane = document.getElementById(`location-panel-${name}`);
document.getElementById(`location-tab-${name}`).addEventListener('shown.bs.tab', callback);
if (pane.classList.contains('active')) callback();
}
function mountHierarchy() {
const root = document.querySelector('[data-location-hierarchy]');
const viewport = root.querySelector('.location-tree-viewport');
const space = root.querySelector('.location-tree-space');
const graph = root.querySelector('.location-tree-graph');
const lineage = new Map();
const visited = new Set();
let top = locations.get(data.current);
for (let parent = locations.get(top.parent); parent && !visited.has(parent.id) && parent.id !== data.current;
parent = locations.get(top.parent)) {
visited.add(parent.id);
lineage.set(parent.id, top);
top = parent;
}
let scale = 1;
let initialized = false;
let drag;
function branch(item, depth) {
const node = element('div', null, 'location-tree-branch');
const card = element('div', null, 'location-tree-node');
const link = element('a', item.name);
link.href = item.hierarchyUrl;
link.title = item.path || item.name;
if (item.id === data.current) {
card.dataset.current = '';
link.setAttribute('aria-current', 'page');
}
card.append(link);
node.append(card);
const descendants = lineage.has(item.id) ? [lineage.get(item.id)] :
(children.get(item.id) || []).filter(child => !visited.has(child.id) && child.id !== data.current);
if (!descendants.length) return node;
const row = element('div', null, 'location-tree-children');
const populate = () => row.replaceChildren(...descendants.map(child => branch(child, depth + 1)));
if (!lineage.has(item.id)) {
row.hidden = depth > lineage.size + 1;
const toggle = button('', () => {
row.hidden = !row.hidden;
if (!row.hidden && !row.childElementCount) populate();
describe();
resize();
}, 'location-tree-toggle');
function describe() {
toggle.textContent = row.hidden ? '+' : '−';
toggle.setAttribute('aria-expanded', String(!row.hidden));
toggle.setAttribute('aria-label', `${row.hidden ? 'Expand' : 'Collapse'} ${item.name} (${descendants.length} children)`);
}
describe();
card.append(toggle);
}
if (!row.hidden) populate();
node.append(row);
return node;
}
function resize() {
graph.style.transform = `scale(${scale})`;
space.style.width = `${viewport.clientWidth + graph.offsetWidth * scale}px`;
space.style.height = `${viewport.clientHeight + graph.offsetHeight * scale}px`;
graph.style.top = `${viewport.clientHeight / 2}px`;
}
function centre(target) {
const bounds = target.getBoundingClientRect();
const frame = viewport.getBoundingClientRect();
viewport.scrollLeft += bounds.left + bounds.width / 2 - frame.left - viewport.clientWidth / 2;
viewport.scrollTop += bounds.top + bounds.height / 2 - frame.top - viewport.clientHeight / 2;
}
function fit() {
scale = Math.max(.03, Math.min(1, (viewport.clientWidth - 34) / graph.offsetWidth,
(viewport.clientHeight - 34) / graph.offsetHeight));
resize();
centre(graph);
}
function zoom(factor) {
const frame = viewport.getBoundingClientRect();
const before = graph.getBoundingClientRect();
const x = (frame.left + viewport.clientWidth / 2 - before.left) / scale;
const y = (frame.top + viewport.clientHeight / 2 - before.top) / scale;
scale = Math.max(.03, Math.min(2.5, scale * factor));
resize();
const after = graph.getBoundingClientRect();
viewport.scrollLeft += after.left + x * scale - frame.left - viewport.clientWidth / 2;
viewport.scrollTop += after.top + y * scale - frame.top - viewport.clientHeight / 2;
}
root.querySelector('[data-tree-fit]').addEventListener('click', fit);
root.querySelector('[data-tree-centre]').addEventListener('click', () => centre(graph.querySelector('[data-current]')));
for (const control of root.querySelectorAll('[data-tree-zoom]')) {
control.addEventListener('click', () => zoom(Number(control.dataset.treeZoom)));
}
viewport.addEventListener('pointerdown', event => {
if (event.button !== 0 || event.target.closest('a, button') ||
event.offsetX >= viewport.clientWidth && event.target === viewport) return;
drag = { x: event.clientX + viewport.scrollLeft, y: event.clientY + viewport.scrollTop };
viewport.setPointerCapture(event.pointerId);
});
viewport.addEventListener('pointermove', event => {
if (!drag) return;
viewport.scrollLeft = drag.x - event.clientX;
viewport.scrollTop = drag.y - event.clientY;
});
viewport.addEventListener('lostpointercapture', () => { drag = null; });
onTab('hierarchy', () => {
if (!initialized) {
graph.append(branch(top, 0));
initialized = true;
fit();
} else resize();
});
new ResizeObserver(() => { if (initialized && viewport.clientWidth) resize(); }).observe(viewport);
}
const typeIcons = new Map([
['Adjacent To', '▥'], ['Above', '↑'], ['Below', '↓'], ['Connected To', '↔'],
['Visible From', '◉'], ['Audible From', '♫'], ['Near', '≈'], ['Leads To', '⇥'],
['Overlooks', '↘'], ['Same Building As', '▣'], ['Same Area As', '▧'],
['Secret Passage', '◇'], ['Road Connection', '═']
]);
const traits = [
['canSeeMovement', '◐', 'See movement'],
['canSeeClearly', '◉', 'See clearly'],
['canHearNormalSpeech', '♪', 'Hear normal speech'],
['canHearLoudNoise', '♫', 'Hear loud noise'],
['canTravelDirectly', '⇢', 'Travel directly']
];
const symbol = name => typeIcons.get(name) || '•';
function mountMatrix() {
const root = document.querySelector('[data-location-matrix]');
const table = root.querySelector('[data-matrix-table]');
const editor = root.querySelector('[data-matrix-editor]');
const filter = root.querySelector('[data-matrix-filter]');
const add = root.querySelector('[data-matrix-add]');
const legend = root.querySelector('[data-matrix-legend]');
const error = root.querySelector('[data-matrix-error]');
const current = locations.get(data.current);
const selected = new Set([
current.id, ...(current.parent ? [current.parent] : []),
...(children.get(current.parent) || []).map(item => item.id),
...(children.get(current.id) || []).map(item => item.id)
]);
const types = new Map(data.types.map(type => [type.id, type]));
const pairs = new Map();
let activePair;
let loaded = false;
let loading = false;
let busy = false;
const key = (from, to) => `${from}/${to}`;
const forPair = (from, to) => pairs.get(key(from, to)) || [];
function status(message = '') {
error.textContent = message;
error.hidden = !message;
}
async function read() {
const response = await fetch(root.dataset.readUrl, { cache: 'no-store' });
if (!response.ok || response.redirected) throw new Error('Unable to load relationships.');
const records = await response.json();
pairs.clear();
for (const record of records) {
const direction = key(record.fromLocationID, record.toLocationID);
if (!pairs.has(direction)) pairs.set(direction, []);
pairs.get(direction).push(record);
if (!types.has(record.locationRelationshipTypeID)) {
types.set(record.locationRelationshipTypeID, {
id: record.locationRelationshipTypeID, name: record.relationshipTypeName, inactive: true
});
}
if (record.fromLocationID === current.id) selected.add(record.toLocationID);
if (record.toLocationID === current.id) selected.add(record.fromLocationID);
}
}
function renderControls() {
const previous = filter.value;
filter.replaceChildren(new Option('All types', ''), ...[...types.values()].map(type => new Option(type.name, type.id)));
filter.value = previous;
add.replaceChildren(new Option('Choose location', ''), ...ordered.filter(item => !selected.has(item.id))
.map(item => new Option(item.path || item.name, item.id)));
legend.replaceChildren(
element('span', '→ Stored direction'), element('span', '⇄ Explicitly bidirectional'), element('span', '· No relationship'),
...[...types.values()].map(type => element('span', `${symbol(type.name)} ${type.name}`)),
...traits.map(([, icon, label]) => element('span', `${icon} ${label}`))
);
}
function indicators(record) {
const marks = [record.isBidirectional ? '⇄' : '→', symbol(record.relationshipTypeName)];
const labels = [record.relationshipTypeName, record.isBidirectional ? 'both ways' : 'one way'];
for (const [field, icon, label] of traits) {
if (!record[field]) continue;
marks.push(icon);
labels.push(label);
}
const indicator = element('span', marks.join(' '), 'location-matrix-indicator');
indicator.setAttribute('aria-label', labels.join(', '));
indicator.title = labels.join(', ');
return indicator;
}
function drawMatrix() {
const items = ordered.filter(item => selected.has(item.id));
const header = element('tr');
header.append(element('th', 'From / To'));
for (const item of items) header.append(heading(item, 'col'));
const head = element('thead');
head.append(header);
const body = element('tbody');
for (const from of items) {
const row = element('tr');
row.append(heading(from, 'row'));
for (const to of items) {
const cell = element('td');
if (from.id === current.id || to.id === current.id) cell.classList.add('location-matrix-current');
if (from.id === to.id) cell.textContent = '—';
else {
const records = [
...forPair(from.id, to.id),
...forPair(to.id, from.id).filter(record => record.isBidirectional)
].filter(record => !filter.value || String(record.locationRelationshipTypeID) === filter.value);
const control = button('', () => select(from.id, to.id), 'location-matrix-cell');
control.dataset.pair = key(from.id, to.id);
control.disabled = busy;
control.setAttribute('aria-pressed', String(activePair?.[0] === from.id && activePair?.[1] === to.id));
const marks = records.map(indicators);
control.setAttribute('aria-label', `${from.name} to ${to.name}: ${marks.map(mark =>
mark.title).join('; ') || 'No matching relationship'}`);
control.append(...(marks.length ? marks : ['·']));
cell.append(control);
}
row.append(cell);
}
body.append(row);
}
table.replaceChildren(head, body);
}
function heading(item, scope) {
const node = element('th', item.name);
node.scope = scope;
node.title = item.path;
if (item.id === current.id) node.classList.add('location-matrix-current');
return node;
}
function select(from, to) {
if (busy) return;
activePair = [from, to];
for (const cell of table.querySelectorAll('[data-pair]')) {
cell.setAttribute('aria-pressed', String(cell.dataset.pair === key(from, to)));
}
status();
drawEditor();
}
function field(label, input) {
const wrapper = element('label', null, 'location-direction-field');
wrapper.append(element('span', label), input);
return wrapper;
}
function updateReciprocal(section, from, to) {
const notice = section.querySelector('[data-reciprocal]');
const inherited = forPair(to, from).filter(record => record.isBidirectional);
notice.hidden = !inherited.length;
notice.textContent = inherited.length
? `Applies both ways from the opposite panel: ${inherited.map(r => r.relationshipTypeName).join(', ')}.` : '';
}
function panel(from, to, selectedRecord) {
const section = element('section', null, 'location-direction-panel');
section.dataset.direction = key(from, to);
section.append(element('h3', `${locations.get(from).name} → ${locations.get(to).name}`));
const records = forPair(from, to);
const notice = element('p', null, 'small muted');
notice.dataset.reciprocal = '';
section.append(notice);
updateReciprocal(section, from, to);
if (!records.length) section.append(element('p', 'No relationship stored in this direction.', 'small muted'));
const saved = element('select', null, 'form-select form-select-sm');
records.forEach(record => saved.add(new Option(record.relationshipTypeName, record.locationRelationshipID)));
if (data.canEdit) saved.add(new Option('New directional relationship', '0'));
if (records.some(record => record.locationRelationshipID === selectedRecord)) saved.value = selectedRecord;
if (saved.length > 1) section.append(field('Relationship record', saved));
const host = element('div');
section.append(host);
function show() {
const record = records.find(item => item.locationRelationshipID === Number(saved.value));
host.replaceChildren();
if (!record && !data.canEdit) return;
const form = element('form', null, 'location-direction-form');
const controls = element('fieldset');
controls.disabled = !data.canEdit || busy;
const type = element('select', null, 'form-select form-select-sm');
type.name = 'LocationRelationshipTypeID';
type.required = true;
type.add(new Option('Choose type', ''));
for (const item of types.values()) {
if (!item.inactive || item.id === record?.locationRelationshipTypeID) type.add(new Option(item.name, item.id));
}
type.value = record?.locationRelationshipTypeID || filter.value || '';
const strength = element('input', null, 'form-control form-control-sm');
Object.assign(strength, { name: 'Strength', type: 'number', min: '1', max: '10', value: record?.strength ?? '' });
controls.append(field('Type', type), field('Strength (1–10, optional)', strength));
for (const [property, , label] of [...traits, ['isBidirectional', '', 'Applies in both directions']]) {
const input = element('input', null, 'form-check-input');
Object.assign(input, { type: 'checkbox', name: property, value: 'true', checked: Boolean(record?.[property]) });
const checkbox = element('label', null, 'location-direction-check');
checkbox.append(input, label);
controls.append(checkbox);
}
const notes = element('textarea', null, 'form-control form-control-sm');
Object.assign(notes, { name: 'Notes', rows: 3, value: record?.notes || '' });
controls.append(field('Notes', notes));
if (data.canEdit) {
const actions = element('div', null, 'button-row');
const save = element('button', 'Save', 'btn btn-primary btn-sm');
save.type = 'submit';
actions.append(save);
if (record) actions.append(button('Archive', () => {
if (window.confirm('Archive this relationship? It can be restored from Archived Items.')) {
void write(form, from, to, record, true);
}
}));
controls.append(actions);
}
form.append(controls);
form.addEventListener('submit', event => {
event.preventDefault();
void write(form, from, to, record, false);
});
host.append(form);
}
saved.addEventListener('change', show);
show();
return section;
}
function drawEditor() {
if (!activePair) return;
const [from, to] = activePair;
editor.replaceChildren(panel(from, to), panel(to, from));
}
async function write(form, from, to, record, archive) {
if (busy) return;
const body = new FormData(form);
for (const [name, value] of Object.entries({
__RequestVerificationToken: root.querySelector('[name=__RequestVerificationToken]').value,
ProjectID: data.projectID, FromLocationID: from, ToLocationID: to,
LocationRelationshipID: record?.locationRelationshipID || 0,
ExpectedUpdatedDate: record?.updatedDate || '', Archive: archive
})) body.set(name, value);
busy = true;
root.setAttribute('aria-busy', 'true');
editor.inert = true;
status();
let refresh = false;
let saved = false;
let savedId;
try {
const response = await fetch(root.dataset.writeUrl, { method: 'POST', body });
if (!response.ok || response.redirected) {
const problem = await response.json().catch(() => null);
refresh = response.status === 409;
throw new Error(problem?.error || 'Unable to save this relationship.');
}
saved = true;
refresh = true;
savedId = (await response.json()).id;
window.PlotDirector?.toast?.success(archive ? 'Relationship archived.' : 'Relationship saved.');
} catch (failure) {
status(failure.message);
} finally {
try {
if (refresh) {
await read();
renderControls();
}
} catch {
status(saved ? 'Saved. Reload this page to refresh the matrix.' : 'Reload this page to refresh the matrix.');
}
busy = false;
root.removeAttribute('aria-busy');
editor.inert = false;
if (refresh) {
drawMatrix();
editor.querySelector(`[data-direction="${key(from, to)}"]`)
?.replaceWith(panel(from, to, savedId ?? record?.locationRelationshipID));
updateReciprocal(editor.querySelector(`[data-direction="${key(to, from)}"]`), to, from);
table.querySelector(`[data-pair="${key(...activePair)}"]`)?.focus({ preventScroll: true });
}
}
}
add.addEventListener('change', () => {
if (!add.value) return;
selected.add(Number(add.value));
renderControls();
drawMatrix();
});
filter.addEventListener('change', drawMatrix);
onTab('relationships', async () => {
if (loaded || loading) return;
loading = true;
status();
table.setAttribute('aria-busy', 'true');
try {
await read();
renderControls();
drawMatrix();
loaded = true;
} catch (failure) {
status(failure.message);
} finally {
loading = false;
table.removeAttribute('aria-busy');
}
});
}
function mountSpatial() {
const map = document.querySelector('[data-location-map]');
const floor = document.querySelector('[data-location-floor]');
if (map) {
const channel = crypto.randomUUID();
const feature = map.dataset.locationMap;
const send = (action, fields) => map.contentWindow?.postMessage({
type: 'plotdirector.spatial.command', channel, action, ...fields
}, location.origin);
const centre = () => send('centre', { id: feature, force: true });
map.addEventListener('load', () => send('init'));
window.addEventListener('message', event => {
if (event.origin !== location.origin || event.source !== map.contentWindow ||
event.data?.channel !== channel || event.data.type !== 'plotdirector.spatial.renderer' ||
event.data.action !== 'ready') return;
send('highlight', { highlights: [{ featureID: feature, roles: [0], label: map.dataset.mapLabel, badge: '' }] });
send('fit', { ids: [feature] });
});
document.querySelector('[data-map-centre]').addEventListener('click', centre);
}
onTab('spatial', () => {
if (map && !map.getAttribute('src')) map.src = map.dataset.src;
if (!floor || floor.dataset.ready) return;
floor.dataset.ready = 'true';
const level = floor.querySelector('[data-floor-level]');
const engine = window.PlotDirectorFloorPlanRenderer.create(floor);
const scroll = floor.querySelector('.location-floor-scroll');
const highlight = floor.dataset.locationBlock
? floor.querySelector(`[data-block="${floor.dataset.locationBlock}"]`)
: floor.querySelector(`[data-floor-grid="${floor.dataset.locationFloor}"]`);
for (const control of floor.querySelectorAll('.floor-plan-stage button')) {
control.tabIndex = -1;
control.setAttribute('aria-disabled', 'true');
}
highlight?.classList.add('location-floor-current');
function showLevel() {
for (const panel of floor.querySelectorAll('[data-floor-panel]')) {
const active = panel.dataset.floorPanel === level.value;
panel.classList.toggle('active', active);
if (!active) continue;
const visible = engine.refreshSharedWalls(panel);
engine.refreshHiddenLocationStyles(visible);
engine.positionTransitions(panel, visible);
}
if (highlight?.closest('[data-floor-panel]').classList.contains('active')) {
const block = highlight.getBoundingClientRect();
const frame = scroll.getBoundingClientRect();
scroll.scrollLeft += block.left + block.width / 2 - frame.left - scroll.clientWidth / 2;
scroll.scrollTop += block.top + block.height / 2 - frame.top - scroll.clientHeight / 2;
} else scroll.scrollTo(0, 0);
}
showLevel();
level.addEventListener('change', showLevel);
});
}
mountHierarchy();
mountMatrix();
mountSpatial();
})();