diff --git a/PlotLine.Tests/Browser/timeline-scene-drops.cjs b/PlotLine.Tests/Browser/timeline-scene-drops.cjs new file mode 100644 index 00000000..bc71886d --- /dev/null +++ b/PlotLine.Tests/Browser/timeline-scene-drops.cjs @@ -0,0 +1,95 @@ +const { chromium } = require('playwright'); +const assert = require('node:assert/strict'); +(async () => { + const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH }); + try { + const page = await browser.newPage({ viewport: { width: 1280, height: 900 } }); + const failures = []; + page.on('pageerror', e => failures.push(e.message)); + let posts = []; + let failSave = false; + await page.route('**/Timeline/Drop*', async route => { + posts.push({ url: route.request().url(), body: route.request().postData() }); + await route.fulfill({ status: failSave ? 400 : 200, contentType: 'application/json', body: JSON.stringify(failSave ? { success: false, message: 'This character is already in the scene.' } : { success: true }) }); + }); + const url = `${process.env.PD_BROWSER_FIXTURE_URL || 'http://127.0.0.1:5238'}/fixture?page=timeline-render`; + await page.goto(url); + await page.locator('[data-drag-palette]').evaluate(el => el.open = true); + const modal = page.locator('[data-scene-assignment-modal]'); + const card = page.locator('.timeline-scene-card[data-scene-id="101"]'); + const drop = async type => { + const source = page.locator(`.drag-chip[data-drag-type="${type}"]`); + const data = await source.evaluate(el => ({ type: el.dataset.dragType, id: el.dataset.dragId, label: el.dataset.dragLabel })); + await card.evaluate((el, data) => { + const transfer = new DataTransfer(); + transfer.setData('application/json', JSON.stringify(data)); + el.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: transfer })); + if (!el.classList.contains('drop-target-active')) throw new Error('Scene rejected drag target'); + el.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: transfer })); + }, data); + await modal.waitFor({ state: 'visible' }); + await page.waitForTimeout(350); + }; + assert.equal(await page.locator('.drag-chip.location .pd-icon').count(), 1); + for (const theme of ['light', 'dark']) { + await page.evaluate(theme => { document.documentElement.dataset.appTheme = `modern-${theme}`; document.documentElement.dataset.theme = theme; document.documentElement.dataset.bsTheme = theme; }, theme); + await page.evaluate(() => window.scrollTo({ top: 120, behavior: "instant" })); + const scrollBefore = await page.evaluate(() => window.scrollY); + await drop('character'); + await page.screenshot({ path: `/tmp/task50-character-${theme}.png` }); + assert.match(await modal.innerText(), /Traveller.*Arrival/s); + assert.equal(await modal.locator('select').count(), 3); + assert.equal(await page.locator('[data-drag-drop-panel]').isVisible(), false); + assert.equal(await modal.locator('select').first().evaluate(el => el === document.activeElement), true); + await page.keyboard.press('Escape'); + await modal.waitFor({ state: 'hidden' }); + await page.waitForFunction(() => document.activeElement?.dataset.sceneId === '101'); + assert.equal(await page.evaluate(() => window.scrollY), scrollBefore); + } + assert.equal(posts.length, 0, 'Cancel must not post'); + await drop('location'); + assert.match(await modal.innerText(), /Station.*Arrival/s); + assert.match(await modal.innerText(), /North Pier/); + await modal.locator('form:not(.d-none) button[type=submit]').click(); + assert.equal(posts.length, 0, 'Replacement requires explicit consent'); + await modal.locator('[name=ConfirmReplacement]').check(); + await modal.locator('form:not(.d-none) [data-drag-cancel]').click(); + await modal.waitFor({ state: 'hidden' }); + assert.equal(posts.length, 0); + await page.setViewportSize({ width: 390, height: 740 }); + await drop('character'); + const bounds = await modal.locator('.modal-dialog').boundingBox(); + assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 390); + await page.screenshot({ path: '/tmp/task50-character-narrow.png' }); + failSave = true; + await modal.locator('form:not(.d-none) button[type=submit]').click(); + await modal.locator('[data-scene-assignment-error]:not([hidden])').waitFor(); + assert.match(await modal.innerText(), /already in the scene/); + assert.equal(await modal.isVisible(), true); + await modal.locator('form:not(.d-none) [data-drag-cancel]').click(); + await modal.waitFor({ state: 'hidden' }); + failSave = false; + await page.locator('[data-timeline-search]').evaluate(el => { el.value = 'Arrival'; el.dispatchEvent(new Event('input', { bubbles: true })); }); + await drop('location'); + await modal.locator('[name=ConfirmReplacement]').check(); + await Promise.all([page.waitForEvent('load'), modal.locator('form:not(.d-none) button[type=submit]').click()]); + await page.waitForTimeout(400); + assert.equal(page.url(), url); + assert.equal(await page.locator('[data-timeline-search]').inputValue(), 'Arrival'); + assert.equal(await card.evaluate(el => el === document.activeElement), true); + assert.match(posts.at(-1).url, /DropLocation/); + assert.match(posts.at(-1).body, /name="ExpectedLocationID"\r\n\r\n77/); + await page.locator('[data-drag-palette]').evaluate(el => el.open = true); + await drop('character'); + await modal.locator('[name=RoleInSceneTypeID]').selectOption('4'); + await modal.locator('[name=PresenceTypeID]').selectOption('5'); + await modal.locator('select[name=LocationID]').selectOption('78'); + await Promise.all([page.waitForEvent('load'), modal.locator('form:not(.d-none) button[type=submit]').click()]); + assert.match(posts.at(-1).url, /DropCharacter/); + for (const [name, value] of [['CharacterID', '3'], ['RoleInSceneTypeID', '4'], ['PresenceTypeID', '5'], ['LocationID', '78']]) { + assert.ok(posts.at(-1).body.includes(`name="${name}"\r\n\r\n${value}`), `${name} must reach the save endpoint`); + } + assert.equal(failures.length, 0, failures.join('\n')); + console.log('PASS timeline character/location modal themes, responsive layout, cancellation, confirmation, errors and state restoration (mock save transport)'); + } finally { await browser.close(); } +})().catch(e => { console.error(e); process.exitCode = 1; }); diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index b8fd21da..e4dcd6c7 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -209,8 +209,11 @@ if(args.Contains("--context-characters")){await ContextCharacterTests.Run();retu if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;} if(args.Contains("--focus-diagnostics")){SharedFocusDiagnosticsTests.Run();return;} +if (args.Contains("--timeline-drops")) { await TimelineDropTests.Run(); Console.WriteLine("PASS timeline scene drop domain guards and persistence"); return; } + var tests = new (string Name, Action Test)[] { + ("Timeline scene drop domain guards and persistence", () => TimelineDropTests.Run().GetAwaiter().GetResult()), ("Explicit help visibility and administrator-only access", HelpVisibilityTests.Run), ("Application domain routing and safe sign in", ApplicationDomainBoundaryTests.Run), ("Bounded contextual name verification and cache reuse",()=>NameVerificationTests.Run().GetAwaiter().GetResult()), diff --git a/PlotLine.Tests/TimelineDropTests.cs b/PlotLine.Tests/TimelineDropTests.cs new file mode 100644 index 00000000..f1142df9 --- /dev/null +++ b/PlotLine.Tests/TimelineDropTests.cs @@ -0,0 +1,71 @@ +using System.Reflection; +using Microsoft.AspNetCore.Mvc.Rendering; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.ViewModels; + +internal static class TimelineDropTests +{ + public static async Task Run() + { + var current = new SceneEditViewModel { + SceneID = 10, PrimaryLocationID = 1, + LocationOptions = [new SelectListItem("Old quay", "1"), new SelectListItem("Station", "2")], + CharacterOptions = [new SelectListItem("Traveller", "3")], + CharacterRoleOptions = [new SelectListItem("Participant", "4")], + PresenceTypeOptions = [new SelectListItem("Present", "5")] + }; + var saves = 0; + SceneCharacter? savedCharacter = null; + var sceneService = Proxy((name, args) => name switch { + "GetEditAsync" => Task.FromResult(current), + "SaveAsync" => SaveScene(), + _ => throw new NotSupportedException(name) + }); + Task SaveScene() { saves++; return Task.FromResult(10); } + var characters = Proxy((name, args) => { + if (name != "SaveSceneCharacterAsync") throw new NotSupportedException(name); + savedCharacter = (SceneCharacter)args![0]!; + return Task.FromResult(42); + }); + var service = new TimelineService(null!, null!, null!, null!, null!, null!, sceneService, + null!, characters, null!, null!, null!, null!, null!, null!); + async Task Reject(Func operation) { + try { await operation(); } + catch (InvalidOperationException) { return; } + throw new Exception("Invalid drop was accepted."); + } + await Reject(() => service.AddLocationByDropAsync(new() { SceneID = 10, LocationID = 2, ExpectedLocationID = 1 })); + await Reject(() => service.AddLocationByDropAsync(new() { SceneID = 10, LocationID = 2, ExpectedLocationID = null, ConfirmReplacement = true })); + await Reject(() => service.AddLocationByDropAsync(new() { SceneID = 10, LocationID = 99, ExpectedLocationID = 1, ConfirmReplacement = true })); + await Reject(() => service.AddLocationByDropAsync(new() { SceneID = 10, LocationID = 1, ExpectedLocationID = 1, ConfirmReplacement = true })); + if (saves != 0) throw new Exception("Rejected location drop mutated the scene."); + await service.AddLocationByDropAsync(new() { SceneID = 10, LocationID = 2, ExpectedLocationID = 1, ConfirmReplacement = true }); + if (current.PrimaryLocationID != 2 || saves != 1) throw new Exception("Explicit replacement was not saved."); + current.PrimaryLocationID = null; + await service.AddLocationByDropAsync(new() { SceneID = 10, LocationID = 1 }); + if (current.PrimaryLocationID != 1 || saves != 2) throw new Exception("Empty scene assignment was not saved."); + await Reject(() => service.AddCharacterByDropAsync(new() { SceneID = 10, CharacterID = 99 })); + await Reject(() => service.AddCharacterByDropAsync(new() { SceneID = 10, CharacterID = 3, PresenceTypeID = 99 })); + current.SceneCharacters = [new() { CharacterID = 3 }]; + await Reject(() => service.AddCharacterByDropAsync(new() { SceneID = 10, CharacterID = 3 })); + if (savedCharacter is not null) throw new Exception("Rejected character drop was saved."); + current.SceneCharacters = []; + await service.AddCharacterByDropAsync(new() { SceneID = 10, CharacterID = 3, RoleInSceneTypeID = 4, PresenceTypeID = 5, LocationID = 2 }); + if (savedCharacter is not { SceneID: 10, CharacterID: 3, RoleInSceneTypeID: 4, PresenceTypeID: 5, LocationID: 2 }) + throw new Exception("Character fields did not reach persistence."); + } + + private static T Proxy(Func handler) where T : class + { + var proxy = DispatchProxy.Create(); + ((DropProxy)(object)proxy).Handler = handler; + return proxy; + } + public class DropProxy : DispatchProxy + { + public Func Handler = null!; + protected override object? Invoke(MethodInfo? method, object?[]? args) => Handler(method!.Name, args); + } +} diff --git a/PlotLine.Tests/ToolbarBrowserHost.cs b/PlotLine.Tests/ToolbarBrowserHost.cs index 0c1830f8..79f62701 100644 --- a/PlotLine.Tests/ToolbarBrowserHost.cs +++ b/PlotLine.Tests/ToolbarBrowserHost.cs @@ -633,7 +633,7 @@ internal static class ToolbarBrowserHost if (context.Request.Query["page"] == "timeline-render") { var scenes = new List { - new() { SceneID = 101, ChapterID = 21, SceneNumber = 1, SceneTitle = "Arrival", Summary = "The crossing begins." }, + new() { SceneID = 101, ChapterID = 21, SceneNumber = 1, SceneTitle = "Arrival", Summary = "The crossing begins.", PrimaryLocationID = 77, PrimaryLocationName = "North Pier" }, new() { SceneID = 102, ChapterID = 21, SceneNumber = 2, SceneTitle = "Departure", Summary = "The crossing ends." } }; var scenario = context.Request.Query["scenario"] == "true"; @@ -644,6 +644,11 @@ internal static class ToolbarBrowserHost Filter = new TimelineFilterViewModel { ProjectID = 7, PlotLineID = 1, FocusType = "plotline", FocusID = 1 }, Books = [new() { Book = model.Book!, Chapters = [new() { Chapter = new Chapter { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "The crossing" }, Scenes = scenes }] }], OrderedScenes = scenes, MatchingSceneIDs = new HashSet { 101 }, FocusSceneIDs = new HashSet { 101 }, FocusLabel = "Harbour mystery", + QuickAddCharacters = [new() { CharacterID = 3, CharacterName = "Traveller" }], + QuickAddLocations = [new() { LocationID = 78, LocationName = "Station" }], + CharacterRoleOptions = [new SelectListItem("Participant", "4")], + PresenceTypeOptions = [new SelectListItem("Present", "5")], + LocationOptions = [new SelectListItem("Station", "78")], ScenePlotSearchText = new Dictionary { [101] = "Harbour mystery First clues Revelation" }, PlotLineOptions = [new SelectListItem("Harbour mystery", "1", true)], PlotThreadOptions = [new SelectListItem("First clues", "11")] diff --git a/PlotLine/Controllers/TimelineController.cs b/PlotLine/Controllers/TimelineController.cs index 618814c1..c50f0a1a 100644 --- a/PlotLine/Controllers/TimelineController.cs +++ b/PlotLine/Controllers/TimelineController.cs @@ -114,10 +114,32 @@ public sealed class TimelineController(ITimelineService timeline) : Controller [ValidateAntiForgeryToken] public async Task DropCharacter(TimelineSceneCharacterDropViewModel model) { + if (Request.Headers.Accept.ToString().Contains("application/json")) + return await SaveSceneDropAsync(() => timeline.AddCharacterByDropAsync(model)); await RunDropActionAsync(() => timeline.AddCharacterByDropAsync(model), "Character added to scene."); return RedirectToAction(nameof(Index), new { projectId = model.ReturnProjectID, bookId = model.ReturnBookID, selectedSceneId = model.SceneID }); } + [HttpPost] + [ValidateAntiForgeryToken] + public Task DropLocation(TimelineSceneLocationDropViewModel model) => + SaveSceneDropAsync(() => timeline.AddLocationByDropAsync(model)); + + private async Task SaveSceneDropAsync(Func action) + { + if (!ModelState.IsValid) + return BadRequest(new { success = false, message = "Check the selected values and try again." }); + try + { + await action(); + return Json(new { success = true }); + } + catch (InvalidOperationException ex) + { + return BadRequest(new { success = false, message = ex.Message }); + } + } + [HttpPost] [ValidateAntiForgeryToken] public async Task DropAssetEvent(TimelineAssetEventDropViewModel model) diff --git a/PlotLine/Help/Articles/Timeline/Fields/DragCharacterRole.md b/PlotLine/Help/Articles/Timeline/Fields/DragCharacterRole.md index 180a54c8..a10ba5c0 100644 --- a/PlotLine/Help/Articles/Timeline/Fields/DragCharacterRole.md +++ b/PlotLine/Help/Articles/Timeline/Fields/DragCharacterRole.md @@ -13,3 +13,7 @@ screenshot: # Overview When dropping a character onto a scene, choose role and presence to record how the scene uses them. This affects character focus and filters, POV review, scene context and continuity. + +Drop a character avatar onto a scene card to open the confirmation dialog. Choose role, presence and an optional current location, then select **Add Character**. Cancel or Escape closes the dialog without saving. A character already in the scene must be edited through the existing appearance. + +Location shortcuts use a location pin icon. Drop one onto a scene to assign its primary location. Each scene supports one primary location: replacing an existing location requires the confirmation checkbox. The dialog names both the location and target scene. Cancel leaves the scene unchanged; failed saves keep the dialog open with an error. After saving, the timeline retains its filters, search, scroll position and scene focus. diff --git a/PlotLine/Services/CoreServices.cs b/PlotLine/Services/CoreServices.cs index 257c43b8..d028ac8c 100644 --- a/PlotLine/Services/CoreServices.cs +++ b/PlotLine/Services/CoreServices.cs @@ -318,6 +318,7 @@ public interface ITimelineService Task ArchivePresetAsync(int timelineViewPresetId); Task MoveSceneByDropAsync(TimelineSceneDropMoveViewModel model); Task AddCharacterByDropAsync(TimelineSceneCharacterDropViewModel model); + Task AddLocationByDropAsync(TimelineSceneLocationDropViewModel model); Task AddAssetEventByDropAsync(TimelineAssetEventDropViewModel model); Task AddAssetDependencyByDropAsync(TimelineAssetDependencyDropViewModel model); Task AddLocationRelationshipByDropAsync(TimelineLocationRelationshipDropViewModel model); @@ -2883,6 +2884,22 @@ public sealed class TimelineService( : await warnings.ValidateProjectAsync(model.ProjectID); } + public async Task AddLocationByDropAsync(TimelineSceneLocationDropViewModel model) + { + var current = await scenes.GetEditAsync(model.SceneID) + ?? throw new InvalidOperationException("The scene is no longer available."); + if (model.LocationID <= 0 || !current.LocationOptions.Any(x => x.Value == model.LocationID.ToString())) + throw new InvalidOperationException("Choose an existing location in this project."); + if (current.PrimaryLocationID == model.LocationID) + throw new InvalidOperationException("This location is already assigned to the scene."); + if (current.PrimaryLocationID != model.ExpectedLocationID) + throw new InvalidOperationException("The scene location has changed. Reload the timeline before assigning a location."); + if (current.PrimaryLocationID.HasValue && !model.ConfirmReplacement) + throw new InvalidOperationException("Confirm replacement of the scene's existing primary location."); + current.PrimaryLocationID = model.LocationID; + await scenes.SaveAsync(current); + } + public async Task AddCharacterByDropAsync(TimelineSceneCharacterDropViewModel model) { var characterId = model.CharacterID.GetValueOrDefault(); @@ -2891,6 +2908,19 @@ public sealed class TimelineService( throw new InvalidOperationException("Choose a character to drop onto the scene."); } + var current = await scenes.GetEditAsync(model.SceneID) + ?? throw new InvalidOperationException("The scene is no longer available."); + if (!current.CharacterOptions.Any(x => x.Value == characterId.ToString())) + throw new InvalidOperationException("Choose an existing character in this project."); + if (model.RoleInSceneTypeID.HasValue && !current.CharacterRoleOptions.Any(x => x.Value == model.RoleInSceneTypeID.Value.ToString())) + throw new InvalidOperationException("Choose an existing role in scene."); + if (model.PresenceTypeID.HasValue && !current.PresenceTypeOptions.Any(x => x.Value == model.PresenceTypeID.Value.ToString())) + throw new InvalidOperationException("Choose an existing presence type."); + if (current.SceneCharacters.Any(x => x.CharacterID == characterId)) + throw new InvalidOperationException("This character is already in the scene. Edit the existing appearance instead."); + if (model.LocationID.HasValue && !current.LocationOptions.Any(x => x.Value == model.LocationID.Value.ToString())) + throw new InvalidOperationException("Choose an existing location in this project."); + await characters.SaveSceneCharacterAsync(new SceneCharacter { SceneID = model.SceneID, diff --git a/PlotLine/ViewModels/CoreViewModels.cs b/PlotLine/ViewModels/CoreViewModels.cs index 26e265a1..651494bb 100644 --- a/PlotLine/ViewModels/CoreViewModels.cs +++ b/PlotLine/ViewModels/CoreViewModels.cs @@ -1532,6 +1532,14 @@ public sealed class TimelineSceneDropMoveViewModel public int? ReturnSelectedSceneID { get; set; } } +public sealed class TimelineSceneLocationDropViewModel +{ + public int SceneID { get; set; } + public int LocationID { get; set; } + public int? ExpectedLocationID { get; set; } + public bool ConfirmReplacement { get; set; } +} + public sealed class TimelineSceneCharacterDropViewModel { public int SceneID { get; set; } diff --git a/PlotLine/Views/Timeline/Index.cshtml b/PlotLine/Views/Timeline/Index.cshtml index ce6fcd5c..f043cdbb 100644 --- a/PlotLine/Views/Timeline/Index.cshtml +++ b/PlotLine/Views/Timeline/Index.cshtml @@ -540,7 +540,7 @@ } @foreach (var location in Model.QuickAddLocations) { - @location.LocationName + Location: @location.LocationName } @@ -577,22 +577,6 @@

-
- - - - -
-
-
-
-
-
- - -
-
-
@@ -654,6 +638,51 @@
+ +