fix: confirm timeline character and location drops in modals
This commit is contained in:
parent
8c2734753d
commit
b5672f20b5
95
PlotLine.Tests/Browser/timeline-scene-drops.cjs
Normal file
95
PlotLine.Tests/Browser/timeline-scene-drops.cjs
Normal file
@ -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; });
|
||||
@ -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()),
|
||||
|
||||
71
PlotLine.Tests/TimelineDropTests.cs
Normal file
71
PlotLine.Tests/TimelineDropTests.cs
Normal file
@ -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<ISceneService>((name, args) => name switch {
|
||||
"GetEditAsync" => Task.FromResult<SceneEditViewModel?>(current),
|
||||
"SaveAsync" => SaveScene(),
|
||||
_ => throw new NotSupportedException(name)
|
||||
});
|
||||
Task<int> SaveScene() { saves++; return Task.FromResult(10); }
|
||||
var characters = Proxy<ICharacterRepository>((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<Task> 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<T>(Func<string, object?[]?, object?> handler) where T : class
|
||||
{
|
||||
var proxy = DispatchProxy.Create<T, DropProxy>();
|
||||
((DropProxy)(object)proxy).Handler = handler;
|
||||
return proxy;
|
||||
}
|
||||
public class DropProxy : DispatchProxy
|
||||
{
|
||||
public Func<string, object?[]?, object?> Handler = null!;
|
||||
protected override object? Invoke(MethodInfo? method, object?[]? args) => Handler(method!.Name, args);
|
||||
}
|
||||
}
|
||||
@ -633,7 +633,7 @@ internal static class ToolbarBrowserHost
|
||||
if (context.Request.Query["page"] == "timeline-render")
|
||||
{
|
||||
var scenes = new List<Scene> {
|
||||
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<int> { 101 }, FocusSceneIDs = new HashSet<int> { 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<int,string> { [101] = "Harbour mystery First clues Revelation" },
|
||||
PlotLineOptions = [new SelectListItem("Harbour mystery", "1", true)],
|
||||
PlotThreadOptions = [new SelectListItem("First clues", "11")]
|
||||
|
||||
@ -114,10 +114,32 @@ public sealed class TimelineController(ITimelineService timeline) : Controller
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> 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<IActionResult> DropLocation(TimelineSceneLocationDropViewModel model) =>
|
||||
SaveSceneDropAsync(() => timeline.AddLocationByDropAsync(model));
|
||||
|
||||
private async Task<IActionResult> SaveSceneDropAsync(Func<Task> 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<IActionResult> DropAssetEvent(TimelineAssetEventDropViewModel model)
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -318,6 +318,7 @@ public interface ITimelineService
|
||||
Task ArchivePresetAsync(int timelineViewPresetId);
|
||||
Task<ContinuityValidationSummary?> 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,
|
||||
|
||||
@ -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; }
|
||||
|
||||
@ -540,7 +540,7 @@
|
||||
}
|
||||
@foreach (var location in Model.QuickAddLocations)
|
||||
{
|
||||
<span class="drag-chip location" draggable="true" data-drag-type="location" data-drag-id="@location.LocationID" data-drag-label="@location.LocationName" title="@location.LocationPath">@location.LocationName</span>
|
||||
<span class="drag-chip location" draggable="true" data-drag-type="location" data-drag-id="@location.LocationID" data-drag-label="@location.LocationName" title="@location.LocationPath"><destination-icon primary-icon="locations" /> <span class="visually-hidden">Location: </span>@location.LocationName</span>
|
||||
}
|
||||
</div>
|
||||
</details>
|
||||
@ -577,22 +577,6 @@
|
||||
</div>
|
||||
<p class="muted" data-drag-panel-summary></p>
|
||||
|
||||
<form asp-controller="Timeline" asp-action="DropCharacter" method="post" class="drag-drop-form d-none" data-drag-form="character">
|
||||
<input type="hidden" name="SceneID" />
|
||||
<input type="hidden" name="CharacterID" />
|
||||
<input type="hidden" name="ReturnProjectID" value="@Model.Project.ProjectID" />
|
||||
<input type="hidden" name="ReturnBookID" value="@Model.SelectedBookID" />
|
||||
<div class="row g-2">
|
||||
<div class="col-6"><label class="form-label">Role in scene <help-icon key="timeline.fields.dragCharacterRole" mode="inline" /></label><select class="form-select form-select-sm" name="RoleInSceneTypeID" asp-items="Model.CharacterRoleOptions"><option value="">Not set</option></select></div>
|
||||
<div class="col-6"><label class="form-label">Presence type <help-icon key="timeline.fields.dragCharacterRole" mode="inline" /></label><select class="form-select form-select-sm" name="PresenceTypeID" asp-items="Model.PresenceTypeOptions"><option value="">Not set</option></select></div>
|
||||
<div class="col-12"><label class="form-label">Current location <help-icon key="sceneInspector.fields.characterLocation" mode="inline" /></label><select class="form-select form-select-sm" name="LocationID" asp-items="Model.LocationOptions"><option value="">Optional</option></select></div>
|
||||
</div>
|
||||
<div class="button-row mt-2">
|
||||
<button class="btn btn-primary btn-sm" type="submit">Add Character</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" data-drag-cancel>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<form asp-controller="Timeline" asp-action="DropAssetEvent" method="post" class="drag-drop-form d-none" data-drag-form="asset-event">
|
||||
<input type="hidden" name="SceneID" />
|
||||
<input type="hidden" name="StoryAssetID" />
|
||||
@ -654,6 +638,51 @@
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<div class="modal fade plotline-modal" tabindex="-1" aria-labelledby="timelineAssignmentTitle" aria-describedby="timelineAssignmentSummary" aria-hidden="true" data-scene-assignment-modal>
|
||||
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
|
||||
<div class="modal-content plotline-confirm-modal">
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title" id="timelineAssignmentTitle">Assign to scene</h2>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cancel assignment"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p id="timelineAssignmentSummary"></p>
|
||||
<p class="text-danger" role="alert" data-scene-assignment-error hidden></p>
|
||||
<form asp-controller="Timeline" asp-action="DropCharacter" method="post" class="drag-drop-form d-none" data-drag-form="character">
|
||||
<input type="hidden" name="SceneID" />
|
||||
<input type="hidden" name="CharacterID" />
|
||||
<input type="hidden" name="ReturnProjectID" value="@Model.Project.ProjectID" />
|
||||
<input type="hidden" name="ReturnBookID" value="@Model.SelectedBookID" />
|
||||
<div class="row g-2">
|
||||
<div class="col-6"><label for="timelineDropRoleInSceneTypeID" class="form-label">Role in scene <help-icon key="timeline.fields.dragCharacterRole" mode="inline" /></label><select class="form-select form-select-sm" id="timelineDropRoleInSceneTypeID" name="RoleInSceneTypeID" asp-items="Model.CharacterRoleOptions"><option value="">Not set</option></select></div>
|
||||
<div class="col-6"><label for="timelineDropPresenceTypeID" class="form-label">Presence type <help-icon key="timeline.fields.dragCharacterRole" mode="inline" /></label><select class="form-select form-select-sm" id="timelineDropPresenceTypeID" name="PresenceTypeID" asp-items="Model.PresenceTypeOptions"><option value="">Not set</option></select></div>
|
||||
<div class="col-12"><label for="timelineDropLocationID" class="form-label">Current location <help-icon key="sceneInspector.fields.characterLocation" mode="inline" /></label><select class="form-select form-select-sm" id="timelineDropLocationID" name="LocationID" asp-items="Model.LocationOptions"><option value="">Optional</option></select></div>
|
||||
</div>
|
||||
<div class="button-row mt-2">
|
||||
<button class="btn btn-primary btn-sm" type="submit">Add Character</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" data-drag-cancel>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<form asp-controller="Timeline" asp-action="DropLocation" method="post" class="d-none" data-drag-form="location">
|
||||
<input type="hidden" name="SceneID" />
|
||||
<input type="hidden" name="LocationID" />
|
||||
<input type="hidden" name="ExpectedLocationID" />
|
||||
<p>A scene has one primary location.</p>
|
||||
<div data-location-replacement hidden>
|
||||
<p data-location-replacement-summary></p>
|
||||
<label class="form-check-label"><input class="form-check-input" type="checkbox" name="ConfirmReplacement" value="true" /> Replace the existing primary location</label>
|
||||
</div>
|
||||
<div class="button-row mt-3">
|
||||
<button type="submit" class="btn btn-primary btn-sm">Assign location</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-drag-cancel>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal fade plotline-modal" id="sceneMoveModal" tabindex="-1" aria-labelledby="sceneMoveModalTitle" aria-hidden="true" data-scene-move-modal>
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content plotline-confirm-modal scene-move-modal-content">
|
||||
@ -787,6 +816,8 @@ else
|
||||
<a data-pd-context="scene" data-pd-context-id="@scene.SceneID" data-pd-context-label="Inspect scene" class="timeline-scene-card @selectedClass @matchClass @focusClass"
|
||||
draggable="true"
|
||||
data-scene-id="@scene.SceneID"
|
||||
data-primary-location-id="@scene.PrimaryLocationID"
|
||||
data-primary-location-name="@scene.PrimaryLocationName"
|
||||
data-drag-type="scene"
|
||||
data-drag-id="@scene.SceneID"
|
||||
data-drag-label="Scene @scene.SceneNumber: @scene.SceneTitle"
|
||||
|
||||
@ -1719,6 +1719,18 @@
|
||||
return;
|
||||
}
|
||||
|
||||
const assignmentElement = document.querySelector("[data-scene-assignment-modal]");
|
||||
const assignmentModal = assignmentElement && window.bootstrap?.Modal
|
||||
? window.bootstrap.Modal.getOrCreateInstance(assignmentElement) : null;
|
||||
let assignmentTarget = null;
|
||||
let assignmentSaving = false;
|
||||
assignmentElement?.addEventListener("hide.bs.modal", event => {
|
||||
if (assignmentSaving) event.preventDefault();
|
||||
});
|
||||
assignmentElement?.addEventListener("shown.bs.modal", () => {
|
||||
assignmentElement.querySelector("form:not(.d-none) select, form:not(.d-none) button[type=submit]")?.focus();
|
||||
});
|
||||
assignmentElement?.addEventListener("hidden.bs.modal", () => assignmentTarget?.focus({ preventScroll: true }));
|
||||
const locationRelationshipModalElement = document.querySelector("[data-location-relationship-modal]");
|
||||
const locationRelationshipModal = locationRelationshipModalElement && window.bootstrap?.Modal
|
||||
? window.bootstrap.Modal.getOrCreateInstance(locationRelationshipModalElement) : null;
|
||||
@ -1759,6 +1771,16 @@
|
||||
};
|
||||
|
||||
const showForm = (key, heading, body, actionLabel) => {
|
||||
if ((key === "character" || key === "location") && assignmentModal) {
|
||||
panel.classList.add("d-none");
|
||||
forms.forEach((form, formKey) => form.classList.toggle("d-none", formKey !== key));
|
||||
assignmentElement.querySelector("#timelineAssignmentTitle").textContent = heading;
|
||||
assignmentElement.querySelector("#timelineAssignmentSummary").textContent = body;
|
||||
assignmentElement.querySelector("[data-scene-assignment-error]").hidden = true;
|
||||
assignmentModal.show();
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === "scene") {
|
||||
panel.classList.add("d-none");
|
||||
panel.querySelectorAll("[data-drag-form]").forEach((form) => form.classList.add("d-none"));
|
||||
@ -1793,6 +1815,7 @@
|
||||
};
|
||||
|
||||
const hidePanel = () => {
|
||||
assignmentModal?.hide();
|
||||
locationRelationshipModal?.hide();
|
||||
panel.classList.add("d-none");
|
||||
forms.forEach((form) => form.classList.add("d-none"));
|
||||
@ -1829,6 +1852,52 @@
|
||||
sessionStorage.removeItem(scrollKey);
|
||||
}
|
||||
|
||||
const assignmentStateKey = "plotline.timeline.assignmentReturn";
|
||||
try {
|
||||
const state = JSON.parse(sessionStorage.getItem(assignmentStateKey) || "null");
|
||||
sessionStorage.removeItem(assignmentStateKey);
|
||||
if (state && state.url === location.href) {
|
||||
const search = document.querySelector("[data-timeline-search]");
|
||||
if (search) {
|
||||
search.value = state.search || "";
|
||||
search.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
requestAnimationFrame(() => root?.querySelector(`.timeline-scene-card[data-scene-id='${CSS.escape(state.sceneId)}']`)?.focus({ preventScroll: true }));
|
||||
window.PlotDirector?.toast?.success("Scene assignment saved.");
|
||||
}
|
||||
} catch { /* Storage may be unavailable. */ }
|
||||
|
||||
["character", "location"].forEach(key => {
|
||||
const form = forms.get(key);
|
||||
form?.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
if (assignmentSaving || !form.reportValidity()) return;
|
||||
assignmentSaving = true;
|
||||
const error = assignmentElement.querySelector("[data-scene-assignment-error]");
|
||||
error.hidden = true;
|
||||
const body = new FormData(form);
|
||||
const buttons = [...assignmentElement.querySelectorAll("button")];
|
||||
buttons.forEach(button => button.disabled = true);
|
||||
try {
|
||||
const response = await fetch(form.action, { method: "POST", body, headers: { Accept: "application/json" } });
|
||||
const result = await response.json().catch(() => null);
|
||||
if (!response.ok || !result?.success) throw new Error(result?.message || "Unable to save. Check your connection and reload the timeline before retrying.");
|
||||
window.PlotLineTimelineScroll?.save();
|
||||
try {
|
||||
sessionStorage.setItem(assignmentStateKey, JSON.stringify({ url: location.href, sceneId: assignmentTarget.dataset.sceneId, search: document.querySelector("[data-timeline-search]")?.value || "" }));
|
||||
} catch { /* Saving must still succeed without browser storage. */ }
|
||||
location.reload();
|
||||
} catch (failure) {
|
||||
error.textContent = failure.message || "Unable to save the scene assignment.";
|
||||
error.hidden = false;
|
||||
error.tabIndex = -1;
|
||||
error.focus();
|
||||
assignmentSaving = false;
|
||||
buttons.forEach(button => button.disabled = false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const readPayload = (event) => {
|
||||
try {
|
||||
const payload = JSON.parse(event.dataTransfer.getData("application/json") || "{}");
|
||||
@ -1870,7 +1939,7 @@
|
||||
};
|
||||
document.querySelectorAll("[data-drag-type][draggable='true'], .location-tree-row[data-drag-type]").forEach(bindDraggable);
|
||||
|
||||
panel.querySelectorAll("[data-drag-cancel]").forEach((button) => button.addEventListener("click", hidePanel));
|
||||
document.querySelectorAll("[data-drag-cancel]").forEach((button) => button.addEventListener("click", hidePanel));
|
||||
forms.get("scene")?.addEventListener("submit", saveTimelineScroll);
|
||||
|
||||
root?.querySelectorAll(".timeline-scene-card[data-scene-id]").forEach((card) => {
|
||||
@ -1883,7 +1952,7 @@
|
||||
|
||||
card.addEventListener("dragover", (event) => {
|
||||
const payload = readPayload(event);
|
||||
if (["scene", "character", "asset"].includes(payload.type)) {
|
||||
if (["scene", "character", "asset", "location"].includes(payload.type)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.dataTransfer.dropEffect = payload.type === "scene" ? "move" : "copy";
|
||||
@ -1897,7 +1966,7 @@
|
||||
|
||||
card.addEventListener("drop", (event) => {
|
||||
const payload = readPayload(event);
|
||||
if (!["scene", "character", "asset"].includes(payload.type)) {
|
||||
if (!["scene", "character", "asset", "location"].includes(payload.type)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -1926,8 +1995,24 @@
|
||||
return;
|
||||
}
|
||||
|
||||
assignmentTarget = card;
|
||||
if (payload.type === "location") {
|
||||
const form = forms.get("location");
|
||||
form.reset();
|
||||
setValue(form, "SceneID", sceneId);
|
||||
setValue(form, "LocationID", payload.id);
|
||||
setValue(form, "ExpectedLocationID", card.dataset.primaryLocationId);
|
||||
const replacement = form.querySelector("[data-location-replacement]");
|
||||
replacement.hidden = !card.dataset.primaryLocationId || card.dataset.primaryLocationId === payload.id;
|
||||
form.querySelector("[name=ConfirmReplacement]").required = !replacement.hidden;
|
||||
form.querySelector("[data-location-replacement-summary]").textContent = `Current primary location: ${card.dataset.primaryLocationName || "Unknown"}.`;
|
||||
showForm("location", "Assign scene location", `Assign ${payload.label} to ${card.dataset.dragLabel}.`, "Location drop");
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.type === "character") {
|
||||
const form = forms.get("character");
|
||||
form.reset();
|
||||
setValue(form, "SceneID", sceneId);
|
||||
setValue(form, "CharacterID", payload.id);
|
||||
showForm("character", "Add character to scene", `Add ${payload.label} to ${card.dataset.dragLabel}.`, "Character drop");
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user