diff --git a/PlotLine/Controllers/LocationsController.cs b/PlotLine/Controllers/LocationsController.cs index 694029cf..91f13682 100644 --- a/PlotLine/Controllers/LocationsController.cs +++ b/PlotLine/Controllers/LocationsController.cs @@ -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 Index(int projectId) { @@ -30,9 +35,85 @@ public sealed class LocationsController(ILocationService locations, GeographicHi public async Task 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(); + var seen = new HashSet(); + 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 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 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 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 Merge(int id) diff --git a/PlotLine/Data/LocationDetailsRepository.cs b/PlotLine/Data/LocationDetailsRepository.cs new file mode 100644 index 00000000..5e5850e2 --- /dev/null +++ b/PlotLine/Data/LocationDetailsRepository.cs @@ -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> ReadUsageAsync(int projectId, int locationId) + { + using var db = connections.CreateConnection(); + return (await db.QueryAsync("dbo.Location_DetailUsage", + new { ProjectID = projectId, LocationID = locationId }, commandType: CommandType.StoredProcedure)).AsList(); + } + + public async Task ReadSpatialAsync(int projectId, IReadOnlyList 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(); + var floor = await rows.ReadSingleOrDefaultAsync(); + 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(); + 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()).AsList(), + Blocks = (await plan.ReadAsync()).AsList(), + Transitions = (await plan.ReadAsync()).AsList() + }); + } + + public async Task 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("dbo.Location_DetailRelationshipWrite", parameters, + commandType: CommandType.StoredProcedure); + } +} diff --git a/PlotLine/Program.cs b/PlotLine/Program.cs index 289553bd..be3ec8df 100644 --- a/PlotLine/Program.cs +++ b/PlotLine/Program.cs @@ -283,6 +283,7 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 106ce5a3..a314bac8 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -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 }; } diff --git a/PlotLine/Sql/355_LocationDetails.sql b/PlotLine/Sql/355_LocationDetails.sql new file mode 100644 index 00000000..e1ba564c --- /dev/null +++ b/PlotLine/Sql/355_LocationDetails.sql @@ -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 diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 0594ce76..18bb17a9 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -2326,16 +2326,21 @@ public sealed class LocationDetailViewModel public Project Project { get; set; } = new(); public LocationItem Location { get; set; } = new(); public IReadOnlyList Aliases { get; set; } = []; - public IReadOnlyList ChildLocations { get; set; } = []; - public IReadOnlyList Relationships { get; set; } = []; - public IReadOnlyList Scenes { get; set; } = []; - public IReadOnlyList Characters { get; set; } = []; - public IReadOnlyList Assets { get; set; } = []; - public LocationRelationshipEditViewModel NewRelationship { get; set; } = new(); - public IReadOnlyList LocationOptions { get; set; } = []; - public IReadOnlyList RelationshipTypeOptions { get; set; } = []; + public IReadOnlyList Locations { get; set; } = []; + public IReadOnlyList RelationshipTypes { get; set; } = []; + public IReadOnlyList 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; } diff --git a/PlotLine/Views/Locations/Details.cshtml b/PlotLine/Views/Locations/Details.cshtml index a14c13fa..49f858cd 100644 --- a/PlotLine/Views/Locations/Details.cshtml +++ b/PlotLine/Views/Locations/Details.cshtml @@ -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 @@
-
+

Hierarchy

-

Parent

-

@(Model.Location.ParentLocationName ?? "Top level")

-

Child locations

- @if (!Model.ChildLocations.Any()) - { -

No child locations yet.

- } - else - { -
- @foreach (var child in Model.ChildLocations) - { - @child.LocationName - } -
- } +
+ + + + +
+
+
+
-
+

Relationships

- @if (!Model.Relationships.Any()) - { -

No relationships defined yet.

- } - else - { -
- @foreach (var relationship in Model.Relationships) - { -
-
- @relationship.FromLocationName - @relationship.RelationshipTypeName.ToLowerInvariant() - @relationship.ToLocationName - @if (relationship.IsBidirectional) - { - both ways - } -

@relationship.Notes

-
-
- - - -
-
- } -
- } - -
- - -
-
- - -
-
- - -
-
- - -
-
- - - - - - -
-
- -
-
- -
+ @Html.AntiForgeryToken() +
+ + +
+

Rows are the starting locations. Columns are the destinations. Select a cell to inspect both directions.

+
+ Legend +
+
+ +
+
+
+

Used here

-
-

Scenes

- @foreach (var scene in Model.Scenes) - { -

@SceneLabel(scene.ChapterNumber, scene.SceneNumber) @scene.SceneTitle

- } - @if (!Model.Scenes.Any()) {

No scenes set here.

} -
-
-

Characters

- @foreach (var character in Model.Characters) - { -

@character.CharacterName @SceneLabel(character.ChapterNumber, character.SceneNumber)

- } - @if (!Model.Characters.Any()) {

No character placements yet.

} -
-
-

Assets

- @foreach (var asset in Model.Assets) - { -

@asset.AssetName @asset.Description

- } - @if (!Model.Assets.Any()) {

No asset placements yet.

} -
+ @foreach (var kind in new[] { "Scenes", "Characters", "Assets" }) + { +
+

@kind

+ @foreach (var book in Model.Usage.Where(entry => entry.Kind == kind).GroupBy(entry => entry.BookID)) + { +

@BookTitleFormatter.DisplayTitle(book.First().BookTitle, book.First().BookSubtitle)

+ @foreach (var chapter in book.GroupBy(entry => entry.ChapterID)) + { + var header = chapter.First(); +
Chapter @header.ChapterNumber.ToString("g") · @header.ChapterTitle
+ + } + } + @if (!Model.Usage.Any(entry => entry.Kind == kind)) + { +

No @kind.ToLowerInvariant() recorded here.

+ } +
+ }
-
-
-

Geographical position

-

Loading…

-
-
- @Html.AntiForgeryToken() +
+ +
+ Geographical lookup +
+

Loading…

+
+
+ @Html.AntiForgeryToken() +
-@functions { - private static string SceneLabel(decimal chapterNumber, decimal sceneNumber) - => chapterNumber > 0 ? $"Chapter {chapterNumber:g}, Scene {sceneNumber:g}" : $"Scene {sceneNumber:g}"; -} + @section Scripts { + + + + diff --git a/PlotLine/Views/Locations/_LocationSpatialPreview.cshtml b/PlotLine/Views/Locations/_LocationSpatialPreview.cshtml new file mode 100644 index 00000000..15437929 --- /dev/null +++ b/PlotLine/Views/Locations/_LocationSpatialPreview.cshtml @@ -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}"; +} +
+

Spatial awareness

+ @if (map is not null) + { +

@map.Name

+

@Caption(map.LocationID)

+
+ + Open map in Maps +
+ + } + @if (floor is not null && plan is not null) + { +

@floor.Name

+

@Caption(floor.LocationID)@(floor.FloorPlanBlockID.HasValue ? "" : " · No room is linked to this location.")

+

Open plan in Floor Plans

+
+ +
+ +
+
+ } + @if (map is null && floor is null) + { +

No placed map feature or floor plan is linked to this location or its containing locations.

+ } + +
diff --git a/PlotLine/wwwroot/css/location-details.css b/PlotLine/wwwroot/css/location-details.css new file mode 100644 index 00000000..1b1ab103 --- /dev/null +++ b/PlotLine/wwwroot/css/location-details.css @@ -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; } diff --git a/PlotLine/wwwroot/js/context-map-renderer.js b/PlotLine/wwwroot/js/context-map-renderer.js index 9f136d6e..665ab9b9 100644 --- a/PlotLine/wwwroot/js/context-map-renderer.js +++ b/PlotLine/wwwroot/js/context-map-renderer.js @@ -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['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['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});} diff --git a/PlotLine/wwwroot/js/location-details.js b/PlotLine/wwwroot/js/location-details.js new file mode 100644 index 00000000..58ef995e --- /dev/null +++ b/PlotLine/wwwroot/js/location-details.js @@ -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(); +})();