Add customisable per-user application toolbar and compact menu chrome
This commit is contained in:
parent
83d889b8ea
commit
66c771d417
126
PlotLine.Tests/Browser/application-toolbar.cjs
Normal file
126
PlotLine.Tests/Browser/application-toolbar.cjs
Normal file
@ -0,0 +1,126 @@
|
||||
// Start: dotnet run --project PlotLine.Tests -- --toolbar-browser-host
|
||||
const { chromium } = require('playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH });
|
||||
const base = 'http://127.0.0.1:5238';
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
const visible = () => page.locator('[data-toolbar-key]:visible').evaluateAll(items => items.map(item => item.dataset.toolbarKey));
|
||||
const open = async () => {
|
||||
await page.locator('#accountMenuButton').click();
|
||||
await page.getByRole('button', { name: 'Customise toolbar…', exact: true }).click();
|
||||
await page.locator('#customiseToolbar.show').waitFor();
|
||||
};
|
||||
const close = async (name) => {
|
||||
await page.locator('[data-toolbar-form] .modal-footer').getByRole('button', { name, exact: true }).click();
|
||||
await page.locator('#customiseToolbar').waitFor({ state: 'hidden' });
|
||||
};
|
||||
try {
|
||||
await page.goto(base + '/fixture');
|
||||
await open();
|
||||
await page.getByRole('button', { name: 'Restore defaults', exact: true }).click();
|
||||
await close('Save');
|
||||
assert.deepEqual(await visible(), ['overview','timeline','calendar','characters','threads','relationships','review']);
|
||||
assert.equal(await page.locator('[data-toolbar-key="calendar"]').getAttribute('aria-current'), 'page');
|
||||
assert.match(await page.locator('[data-toolbar-key="calendar"]').getAttribute('href'), /projectId=7/);
|
||||
assert.match(await page.locator('[data-toolbar-key="review"]').getAttribute('href'), /book\/12\/review-centre/);
|
||||
const chrome = await page.locator('header').boundingBox();
|
||||
assert(chrome.height < 100, 'Desktop chrome stays compact');
|
||||
await page.screenshot({ path: '/tmp/plotdirector-toolbar-desktop.png' });
|
||||
await page.locator('#appStoryMenu').click();
|
||||
assert(await page.locator('#appStoryMenu + ul').isVisible());
|
||||
assert.match(await page.locator('#appStoryMenu + ul').getByText('Calendar', { exact: true }).getAttribute('href'), /projectId=7/);
|
||||
await page.locator('#appProjectMenu').click();
|
||||
assert.equal(await page.getByText('Switch project…', { exact: true }).getAttribute('href'), '/Projects');
|
||||
await page.keyboard.press('Escape');
|
||||
// A Calendar AJAX book change updates both levels of navigation.
|
||||
await page.evaluate(() => {
|
||||
const old = document.querySelector('[data-navigation-book-id]');
|
||||
const copy = old.cloneNode(true); copy.dataset.navigationBookId = '13'; old.replaceWith(copy);
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelector('[data-toolbar-key="review"]').href.includes('/13/'));
|
||||
assert.match(await page.locator('[data-app-review-link]').getAttribute('href'), /book\/13\/review-centre/);
|
||||
await open();
|
||||
await page.locator('[data-command-key="timeline"] input').uncheck();
|
||||
await page.locator('[data-command-key="locations"] input').check();
|
||||
await page.locator('[data-command-key="calendar"] [data-move="-1"]').click();
|
||||
await page.screenshot({ path: '/tmp/plotdirector-toolbar-dialog.png' });
|
||||
await close('Cancel');
|
||||
assert.deepEqual(await visible(), ['overview','timeline','calendar','characters','threads','relationships','review']);
|
||||
await open();
|
||||
await page.locator('[data-command-key="timeline"] input').uncheck();
|
||||
await page.locator('[data-command-key="locations"] input').check();
|
||||
await page.locator('[data-command-key="calendar"] [data-move="-1"]').click();
|
||||
await close('Save');
|
||||
assert.deepEqual(await visible(), ['calendar','overview','characters','threads','relationships','review','locations']);
|
||||
await page.reload();
|
||||
assert.equal((await visible())[0], 'calendar');
|
||||
const fresh = await browser.newContext();
|
||||
const secondSession = await fresh.newPage();
|
||||
await secondSession.goto(base + '/fixture');
|
||||
assert.equal(await secondSession.locator('[data-toolbar-key]:visible').first().getAttribute('data-toolbar-key'), 'calendar');
|
||||
await fresh.close();
|
||||
await context.addCookies([{ name: 'fixture-user', value: '5', url: base }]);
|
||||
await page.reload();
|
||||
assert.equal((await visible())[0], 'overview', 'Another user has independent defaults');
|
||||
await context.clearCookies();
|
||||
await page.reload();
|
||||
await open();
|
||||
await page.getByRole('button', { name: 'Restore defaults', exact: true }).click();
|
||||
await close('Save');
|
||||
await open();
|
||||
await page.locator('[data-command-key="overview"]').dragTo(page.locator('[data-command-key="calendar"]'));
|
||||
await close('Save');
|
||||
assert.deepEqual((await visible()).slice(0,3), ['timeline','calendar','overview']);
|
||||
// Antiforgery is enforced by MVC, not just by a mocked fetch.
|
||||
assert.equal((await context.request.post(base + '/Toolbar/Save', { form: { commandKeys: 'calendar' } })).status(), 400);
|
||||
await open();
|
||||
await page.getByRole('button', { name: 'Restore defaults', exact: true }).click();
|
||||
await close('Save');
|
||||
// Failed saves keep the draft open and leave the saved strip unchanged.
|
||||
await open();
|
||||
await page.locator('[data-command-key="timeline"] input').uncheck();
|
||||
await page.route('**/Toolbar/Save', route => route.fulfill({ status: 500, body: 'fixture failure' }));
|
||||
await page.locator('[data-toolbar-form] button[type="submit"]').click();
|
||||
await page.locator('[data-toolbar-error]').filter({ hasText: 'Unable to save' }).waitFor();
|
||||
assert((await visible()).includes('timeline'));
|
||||
await page.unroute('**/Toolbar/Save');
|
||||
await close('Cancel');
|
||||
await open();
|
||||
while (await page.locator('[data-toolbar-choices] input:checked').count()) await page.locator('[data-toolbar-choices] input:checked').first().uncheck();
|
||||
await close('Save');
|
||||
assert.deepEqual(await visible(), []);
|
||||
await page.reload();
|
||||
assert(await page.locator('[data-toolbar-empty]').isVisible());
|
||||
await open();
|
||||
await page.getByRole('button', { name: 'Restore defaults', exact: true }).click();
|
||||
await close('Cancel');
|
||||
assert.deepEqual(await visible(), []);
|
||||
await open();
|
||||
await page.getByRole('button', { name: 'Restore defaults', exact: true }).click();
|
||||
await close('Save');
|
||||
await page.goto(base + '/fixture?project=none');
|
||||
assert.equal(await page.locator('[data-toolbar-key="calendar"]').getAttribute('href'), null);
|
||||
assert.equal(await page.locator('[data-toolbar-key="calendar"]').getAttribute('aria-disabled'), 'true');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.locator('.navbar-toggler').click();
|
||||
await page.locator('#applicationMenu.collapse.show').waitFor();
|
||||
await page.locator('#accountMenuButton').click();
|
||||
assert(await page.getByRole('button', { name: 'Customise toolbar…', exact: true }).isVisible());
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('.navbar-toggler').click();
|
||||
await page.locator('#applicationMenu').waitFor({ state: 'hidden' });
|
||||
await page.screenshot({ path: '/tmp/plotdirector-toolbar-mobile.png' });
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Mobile chrome does not overflow viewport');
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.goto(base + '/fixture');
|
||||
await page.evaluate(() => { document.documentElement.dataset.theme = 'dark'; document.documentElement.dataset.bsTheme = 'dark'; });
|
||||
await page.waitForTimeout(350); // Allow the existing theme colour transition to finish.
|
||||
await page.screenshot({ path: '/tmp/plotdirector-toolbar-dark.png' });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS application toolbar: real Razor, default/custom order, show/hide, drag/keyboard, cancel/reset, fresh sessions, users, menus, project/book context, CSRF, desktop/mobile/dark');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@ -1,5 +1,13 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": { "test": "node timeline-metric-layout.cjs", "test:locations": "node location-reparent.cjs", "test:characters": "node character-enrichment-detail.cjs" },
|
||||
"devDependencies": { "chart.js": "4.4.9", "playwright": "1.58.2" }
|
||||
"scripts": {
|
||||
"test": "node timeline-metric-layout.cjs",
|
||||
"test:locations": "node location-reparent.cjs",
|
||||
"test:characters": "node character-enrichment-detail.cjs",
|
||||
"test:toolbar": "node application-toolbar.cjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"chart.js": "4.4.9",
|
||||
"playwright": "1.58.2"
|
||||
}
|
||||
}
|
||||
|
||||
@ -17,6 +17,12 @@ using PlotLine.ViewModels;
|
||||
|
||||
#pragma warning disable CS8321
|
||||
|
||||
if (args.Contains("--toolbar-browser-host"))
|
||||
{
|
||||
await ToolbarBrowserHost.RunAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
var tests = new (string Name, Action Test)[]
|
||||
{
|
||||
("Exception review uses evidence, identity, consequence and directional conflicts", ExceptionReviewTests.DomainPolicy),
|
||||
@ -313,6 +319,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Writing Intent route uses canonical story context and planning data", WritingIntentRouteUsesCanonicalStoryContextAndPlanningData),
|
||||
("Writing Intent client uses shared writing follow helper", WritingIntentClientUsesSharedWritingFollowHelper),
|
||||
("Obsolete global Word navigation is removed while writing windows remain live", GlobalWordNavigationIsRemoved),
|
||||
("Toolbar preferences, authorisation and contextual routes", ToolbarTests.PreferencesAndRoutes),
|
||||
("Application navigation resolves authorised project and book context", ApplicationNavigationTests.ContextAndPermissions),
|
||||
("Writing pair shares canonical follow infrastructure", WritingPairSharesCanonicalFollowInfrastructure),
|
||||
("Writing workspace presence scopes browser windows", WritingWorkspacePresenceScopesBrowserWindows),
|
||||
|
||||
80
PlotLine.Tests/ToolbarBrowserHost.cs
Normal file
80
PlotLine.Tests/ToolbarBrowserHost.cs
Normal file
@ -0,0 +1,80 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Abstractions;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
using Microsoft.AspNetCore.Mvc.ViewEngines;
|
||||
using Microsoft.AspNetCore.Mvc.ViewFeatures;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
// Isolated, loopback-only host: renders real compiled Razor chrome, never starts app workers or connects to a database.
|
||||
internal static class ToolbarBrowserHost
|
||||
{
|
||||
public static async Task RunAsync()
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(ToolbarController).Assembly.FullName });
|
||||
builder.Services.AddControllersWithViews().AddApplicationPart(typeof(ToolbarController).Assembly);
|
||||
builder.Services.AddSingleton<IToolbarPreferenceRepository, ToolbarMemoryPreferences>();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddSingleton<IHelpService, HelpService>();
|
||||
builder.Services.AddScoped<ICurrentUserService>(services => new ToolbarTestUser(int.Parse(services.GetRequiredService<IHttpContextAccessor>().HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!)));
|
||||
var app = builder.Build();
|
||||
app.Urls.Add("http://127.0.0.1:5238");
|
||||
app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.GetFullPath("PlotLine/wwwroot")) });
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
var user = context.Request.Cookies["fixture-user"] == "5" ? "5" : "4";
|
||||
context.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user), new Claim(ClaimTypes.Name, "Fixture Author")], "Fixture"));
|
||||
await next();
|
||||
});
|
||||
app.UseRouting();
|
||||
app.UseAuthorization();
|
||||
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
|
||||
app.MapGet("/fixture", async context =>
|
||||
{
|
||||
var model = new ApplicationNavigationViewModel { ActiveSection = "Calendar", ShowCompanionPresence = true };
|
||||
if (context.Request.Query["project"] != "none")
|
||||
{
|
||||
model.Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = "Owner" };
|
||||
model.Book = new Book { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore", BookNumber = 1 };
|
||||
model.Books = [model.Book, new Book { BookID = 13, ProjectID = 7, BookTitle = "The Return", BookNumber = 2 }];
|
||||
}
|
||||
var route = new RouteData(); route.Values["controller"] = "StoryCalendar"; route.Values["action"] = "Index";
|
||||
var action = new ActionContext(context, route, new ActionDescriptor());
|
||||
async Task<string> Render(string name, object? viewModel = null)
|
||||
{
|
||||
var view = context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null, $"/Views/{name}.cshtml", false);
|
||||
if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations));
|
||||
using var writer = new StringWriter();
|
||||
var data = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = viewModel ?? model };
|
||||
var temp = new TempDataDictionary(context, context.RequestServices.GetRequiredService<ITempDataProvider>());
|
||||
await view.View.RenderAsync(new ViewContext(action, view.View, data, temp, writer, new HtmlHelperOptions()));
|
||||
return writer.ToString();
|
||||
}
|
||||
var menu = await Render("Shared/_ApplicationNavigation");
|
||||
var toolbar = await Render("Shared/_ApplicationToolbar");
|
||||
var calendar = new StoryCalendarViewModel { Project = model.Project ?? new(), SelectedBookID = model.Book?.BookID,
|
||||
SelectedMonth = new DateOnly(2026, 10, 1), EarliestStoryDate = new DateOnly(2026, 10, 3), LatestStoryDate = new DateOnly(2026, 10, 3),
|
||||
BookOptions = [new SelectListItem("A Distant Shore", "12"), new SelectListItem("The Return", "13")],
|
||||
MonthOptions = [new SelectListItem("October 2026", "2026-10")],
|
||||
DatedScenes = [new StoryCalendarSceneViewModel { Title = "Arrival", StoryDate = new DateOnly(2026, 10, 3) }],
|
||||
Weeks = Enumerable.Range(0, 5).Select(week => new StoryCalendarWeekViewModel {
|
||||
Days = Enumerable.Range(0, 7).Select(day => new StoryCalendarDayViewModel { Date = new DateOnly(2026, 9, 28).AddDays(week * 7 + day), IsInSelectedMonth = week * 7 + day >= 3 }).ToList()
|
||||
}).ToList()
|
||||
};
|
||||
var surface = await Render("StoryCalendar/_StoryCalendarSurface", calendar);
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
await context.Response.WriteAsync("<!doctype html><html lang='en' data-theme='light'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'></head><body class='app-layout'><header>" + menu + toolbar + "</header><main class='plotline-help-main container-fluid'>" + surface + "</main><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script></body></html>");
|
||||
});
|
||||
await app.RunAsync();
|
||||
}
|
||||
}
|
||||
66
PlotLine.Tests/ToolbarTests.cs
Normal file
66
PlotLine.Tests/ToolbarTests.cs
Normal file
@ -0,0 +1,66 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
internal static class ToolbarTests
|
||||
{
|
||||
public static void PreferencesAndRoutes()
|
||||
{
|
||||
Check(ToolbarCommands.Resolve(null).SequenceEqual(ToolbarCommands.Defaults), "New users receive current defaults.");
|
||||
Check(ToolbarCommands.Resolve("[]").Length == 0, "An intentionally empty toolbar stays empty.");
|
||||
Check(ToolbarCommands.Resolve("[\"calendar\",\"removed\",\"calendar\",\"timeline\"]").SequenceEqual(new[] { "calendar", "timeline" }), "Unknown keys are discarded, order retained and new defaults not added.");
|
||||
Check(!ToolbarCommands.IsValid(["calendar", "calendar"]) && !ToolbarCommands.IsValid(["/evil"]), "Reject duplicate or unknown commands.");
|
||||
var context = new ApplicationNavigationViewModel { Project = new Project { ProjectID = 7 }, Book = new Book { BookID = 12, ProjectID = 7 } };
|
||||
foreach (var command in ToolbarCommands.All)
|
||||
{
|
||||
Check(command.IsAvailable(context), "Registered navigation commands available in authorised context.");
|
||||
if (command.RequiresProject)
|
||||
{
|
||||
Check(!command.IsAvailable(new()), "Project commands disabled without context.");
|
||||
var values = JsonSerializer.Serialize(command.RouteValues(context));
|
||||
Check(values.Contains(command.RequiresBook ? "12" : "7"), "Links preserve authorised context.");
|
||||
}
|
||||
}
|
||||
var calendar = ToolbarCommands.All.Single(x => x.Key == "calendar");
|
||||
Check(calendar.IsActive("StoryCalendar", "Index", "Calendar") && calendar.IsActive("StoryCalendar", "Settings", "Calendar"), "Calendar feature active across actions.");
|
||||
var review = ToolbarCommands.All.Single(x => x.Key == "review");
|
||||
Check(!review.IsAvailable(new() { Project = context.Project }), "Review never invents a book.");
|
||||
Check(review.IsActive("Onboarding", "StoryIntelligenceCharacters", "Onboarding") && !review.IsActive("Onboarding", "Index", "Onboarding"), "Review pages are distinct from setup.");
|
||||
Check(typeof(ToolbarController).GetCustomAttributes(typeof(AuthorizeAttribute), true).Length == 1, "Preference endpoint requires authentication.");
|
||||
Check(typeof(ToolbarController).GetMethod("Save")!.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), true).Length == 1, "Preference endpoint requires antiforgery.");
|
||||
var store = new ToolbarMemoryPreferences();
|
||||
var first = new ToolbarController(new ToolbarTestUser(4), store);
|
||||
var second = new ToolbarController(new ToolbarTestUser(5), store);
|
||||
first.Save(["calendar", "timeline"]).GetAwaiter().GetResult();
|
||||
second.Save([]).GetAwaiter().GetResult();
|
||||
Check(ToolbarCommands.Resolve(store.GetAsync(4).Result).SequenceEqual(new[] { "calendar", "timeline" }), "Preferences survive new controller/session instances.");
|
||||
Check(ToolbarCommands.Resolve(store.GetAsync(5).Result).Length == 0, "Users have independent configurations.");
|
||||
Check(first.Save(["unknown"]).Result is BadRequestResult, "Invalid changes rejected.");
|
||||
first.Save([], true).GetAwaiter().GetResult();
|
||||
Check(store.GetAsync(4).Result is null, "Restore defaults removes custom configuration.");
|
||||
}
|
||||
private static void Check(bool value, string message) { if (!value) throw new Exception(message); }
|
||||
}
|
||||
|
||||
internal sealed class ToolbarTestUser(int id) : ICurrentUserService
|
||||
{
|
||||
public int? UserId => id;
|
||||
public string? Email => "fixture@example.test";
|
||||
public string? DisplayName => "Fixture Author";
|
||||
public bool IsAuthenticated => true;
|
||||
}
|
||||
internal sealed class ToolbarMemoryPreferences : IToolbarPreferenceRepository
|
||||
{
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<int, string> values = new();
|
||||
public Task<string?> GetAsync(int userId) => Task.FromResult(values.GetValueOrDefault(userId));
|
||||
public Task SaveAsync(int userId, string? commandKeysJson)
|
||||
{
|
||||
if (commandKeysJson is null) values.TryRemove(userId, out _); else values[userId] = commandKeysJson;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
20
PlotLine/Controllers/ToolbarController.cs
Normal file
20
PlotLine/Controllers/ToolbarController.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize]
|
||||
public sealed class ToolbarController(ICurrentUserService user, IToolbarPreferenceRepository preferences) : Controller
|
||||
{
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Save(string[] commandKeys, bool useDefaults = false)
|
||||
{
|
||||
if (user.UserId is not int userId) return Unauthorized();
|
||||
if (!ModelState.IsValid || !ToolbarCommands.IsValid(commandKeys)) return BadRequest();
|
||||
await preferences.SaveAsync(userId, useDefaults ? null : JsonSerializer.Serialize(commandKeys));
|
||||
return Json(new { commandKeys = useDefaults ? ToolbarCommands.Defaults : commandKeys });
|
||||
}
|
||||
}
|
||||
24
PlotLine/Data/ToolbarPreferenceRepository.cs
Normal file
24
PlotLine/Data/ToolbarPreferenceRepository.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
|
||||
namespace PlotLine.Data;
|
||||
|
||||
public interface IToolbarPreferenceRepository
|
||||
{
|
||||
Task<string?> GetAsync(int userId);
|
||||
Task SaveAsync(int userId, string? commandKeysJson);
|
||||
}
|
||||
|
||||
public sealed class ToolbarPreferenceRepository(ISqlConnectionFactory connections) : IToolbarPreferenceRepository
|
||||
{
|
||||
public async Task<string?> GetAsync(int userId)
|
||||
{
|
||||
using var connection = connections.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<string>("dbo.UserToolbar_Get", new { UserID = userId }, commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task SaveAsync(int userId, string? commandKeysJson)
|
||||
{
|
||||
using var connection = connections.CreateConnection();
|
||||
await connection.ExecuteAsync("dbo.UserToolbar_Save", new { UserID = userId, CommandKeysJson = commandKeysJson }, commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
}
|
||||
@ -112,6 +112,7 @@ public class Program
|
||||
builder.Services.AddScoped<IFeatureRequestRepository, FeatureRequestRepository>();
|
||||
builder.Services.AddScoped<IProjectRepository, ProjectRepository>();
|
||||
builder.Services.AddScoped<ApplicationNavigation>();
|
||||
builder.Services.AddScoped<IToolbarPreferenceRepository, ToolbarPreferenceRepository>();
|
||||
builder.Services.AddScoped<IBookRepository, BookRepository>();
|
||||
builder.Services.AddScoped<IManuscriptDocumentRepository, ManuscriptDocumentRepository>();
|
||||
builder.Services.AddScoped<IChapterRepository, ChapterRepository>();
|
||||
|
||||
58
PlotLine/Services/ToolbarCommands.cs
Normal file
58
PlotLine/Services/ToolbarCommands.cs
Normal file
@ -0,0 +1,58 @@
|
||||
using System.Text.Json;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
namespace PlotLine.Services;
|
||||
|
||||
public sealed record ToolbarCommand(string Key, string Label, string IconPath, string Controller,
|
||||
string Action, string Section, bool IsDefault = false, bool RequiresProject = true, bool RequiresBook = false)
|
||||
{
|
||||
public bool IsAvailable(ApplicationNavigationViewModel context) =>
|
||||
(!RequiresProject || context.Project is not null) && (!RequiresBook || context.Book is not null);
|
||||
|
||||
public bool IsActive(string controller, string action, string section) => Key == "review"
|
||||
? controller == "Onboarding" && (action.StartsWith("StoryIntelligence", StringComparison.Ordinal) || action == "ContinueStoryIntelligence")
|
||||
: Key == "projects" ? controller == "Projects" && action == "Index"
|
||||
: string.Equals(Section, section, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public object RouteValues(ApplicationNavigationViewModel context) => RequiresBook
|
||||
? new { bookId = context.Book?.BookID }
|
||||
: Key == "overview" ? new { id = context.Project?.ProjectID }
|
||||
: RequiresProject ? new { projectId = context.Project?.ProjectID } : new { };
|
||||
}
|
||||
|
||||
public static class ToolbarCommands
|
||||
{
|
||||
public static IReadOnlyList<ToolbarCommand> All { get; } = Array.AsReadOnly<ToolbarCommand>([
|
||||
new("overview", "Overview", "M3 3h7v7H3z M14 3h7v7h-7z M3 14h7v7H3z M14 14h7v7h-7z", "Projects", "Details", "Overview", true),
|
||||
new("timeline", "Timeline", "M3 6h18 M3 12h18 M3 18h18 M7 3v6 M15 9v6 M10 15v6", "Timeline", "Index", "Timeline", true),
|
||||
new("calendar", "Calendar", "M4 5h16v16H4z M4 10h16 M8 3v4 M16 3v4 M8 14h2 M14 14h2 M8 18h2", "StoryCalendar", "Index", "Calendar", true),
|
||||
new("characters", "Characters", "M9 3a3 3 0 1 0 0 6 3 3 0 0 0 0-6 M3 21v-4a6 6 0 0 1 12 0v4 M17 4a3 3 0 0 1 0 6 M18 13a5 5 0 0 1 3 5v3", "Characters", "Index", "Characters", true),
|
||||
new("threads", "Threads", "M4 3v18 M4 7h8l6 10h3 M4 17h8l6-10h3", "PlotThreads", "Index", "Threads", true),
|
||||
new("relationships", "Relationships", "M4 4h5v5H4z M15 15h5v5h-5z M15 4h5v5h-5z M9 6h6 M6 9v8h9", "RelationshipMap", "Index", "Relationships", true),
|
||||
new("review", "Review Centre", "M5 3h14v18H5z M8 8l2 2 5-5 M8 14h8 M8 18h6", "Onboarding", "StoryIntelligenceBookReviewCentre", "Review", true, RequiresBook: true),
|
||||
new("locations", "Locations", "M12 21s7-7 7-12a7 7 0 0 0-14 0c0 5 7 12 7 12 M12 6a3 3 0 1 0 0 6 3 3 0 0 0 0-6", "Locations", "Index", "Locations"),
|
||||
new("assets", "Assets", "M3 7l9-4 9 4v11l-9 4-9-4z M3 7l9 4 9-4 M12 11v11", "StoryAssets", "Index", "Assets"),
|
||||
new("names", "Names", "M4 4h16v16H4z M7 8h10 M7 12h7 M7 16h10", "Names", "Index", "Names"),
|
||||
new("point", "At This Point", "M12 3v18 M3 12h18 M12 6a6 6 0 1 0 0 12 6 6 0 0 0 0-12", "StoryPoint", "Index", "At This Point"),
|
||||
new("scenarios", "Scenarios", "M5 3v7l14 7v4 M5 10l14-5V3 M5 10v11", "Scenarios", "Index", "Scenarios"),
|
||||
new("floorplans", "Floor Plans", "M3 3h18v18H3z M3 12h7 M14 12h7 M12 3v6 M12 15v6", "FloorPlans", "Index", "Floor Plans"),
|
||||
new("bible", "Story Bible", "M12 5C8 2 4 3 2 4v16c4-2 7-1 10 1 3-2 6-3 10-1V4c-4-2-7-1-10 1v16", "StoryBible", "Index", "Story Bible"),
|
||||
new("continuity", "Continuity", "M4 5h16 M4 12h16 M4 19h16 M8 3v4 M16 10v4 M10 17v4", "ContinuityExplorer", "Index", "Continuity Explorer"),
|
||||
new("metrics", "Metrics", "M3 3v18h18 M7 17v-5 M12 17V7 M17 17V4", "ProjectMetrics", "Index", "Metrics"),
|
||||
new("health", "Health", "M2 12h5l3-8 4 16 3-8h5", "Analytics", "Index", "Health"),
|
||||
new("warnings", "Warnings", "M12 3L2 21h20z M12 9v5 M12 17v1", "Warnings", "Index", "Warnings"),
|
||||
new("archive", "Archive", "M3 3h18v5H3z M5 8v13h14V8 M9 12h6", "Archives", "Index", "Archive"),
|
||||
new("projects", "Projects", "M3 5h7l2 3h9v13H3z", "Projects", "Index", "Projects", RequiresProject: false),
|
||||
new("writer", "Writer", "M4 20l1-5L17 3l4 4L9 19z M14 6l4 4", "Writer", "Index", "Writer", RequiresProject: false)
|
||||
]);
|
||||
public static string[] Defaults => All.Where(x => x.IsDefault).Select(x => x.Key).ToArray();
|
||||
// An explicit ordered list is a complete custom configuration: absent keys are disabled.
|
||||
public static string[] Resolve(string? json)
|
||||
{
|
||||
if (json is null) return Defaults;
|
||||
try { return (JsonSerializer.Deserialize<string[]>(json) ?? []).Where(key => All.Any(x => x.Key == key)).Distinct().ToArray(); }
|
||||
catch (JsonException) { return Defaults; }
|
||||
}
|
||||
public static bool IsValid(string[] keys) => keys.Length <= All.Count && keys.Distinct().Count() == keys.Length
|
||||
&& keys.All(key => All.Any(x => x.Key == key));
|
||||
}
|
||||
26
PlotLine/Sql/201_UserToolbarPreferences.sql
Normal file
26
PlotLine/Sql/201_UserToolbarPreferences.sql
Normal file
@ -0,0 +1,26 @@
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
-- NULL follows current defaults. JSON array order is display order; absent keys are disabled.
|
||||
-- Lives on the existing account so hard account deletion needs no extra cleanup.
|
||||
IF COL_LENGTH(N'dbo.AppUser', N'ToolbarCommandKeysJson') IS NULL
|
||||
ALTER TABLE dbo.AppUser ADD ToolbarCommandKeysJson nvarchar(max) NULL;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.UserToolbar_Get @UserID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SELECT ToolbarCommandKeysJson FROM dbo.AppUser WHERE UserID = @UserID;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.UserToolbar_Save @UserID int, @CommandKeysJson nvarchar(max) = NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF @CommandKeysJson IS NOT NULL AND ISJSON(@CommandKeysJson, ARRAY) <> 1
|
||||
THROW 50001, 'Toolbar preferences must be a JSON array.', 1;
|
||||
UPDATE dbo.AppUser SET ToolbarCommandKeysJson = @CommandKeysJson WHERE UserID = @UserID;
|
||||
IF @@ROWCOUNT <> 1 THROW 50002, 'Account not found.', 1;
|
||||
END;
|
||||
GO
|
||||
@ -57,6 +57,7 @@
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-book-url="@Url.Action("Details", "Books", new { id = (int?)null })" asp-controller="Books" asp-action="Details" asp-route-id="@book?.BookID">Book overview</a></li>
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-book-url="@Url.Action("Edit", "Books", new { id = (int?)null })" asp-controller="Books" asp-action="Edit" asp-route-id="@book?.BookID">Edit book</a></li>
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-book-url="@Url.Action("Create", "Chapters", new { id = (int?)null })" data-app-book-param="bookId" asp-controller="Chapters" asp-action="Create" asp-route-bookId="@book?.BookID">Add chapter</a></li>
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-review-link data-review-url="@Url.Action("StoryIntelligenceBookReviewCentre", "Onboarding", new { bookId = 0 })" asp-controller="Onboarding" asp-action="StoryIntelligenceBookReviewCentre" asp-route-bookId="@book?.BookID">Review Centre</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Projects" asp-action="Details" asp-route-id="@project.ProjectID">All books / project overview</a></li>
|
||||
<li><hr class="dropdown-divider" /></li>
|
||||
@foreach (var choice in Model.Books)
|
||||
@ -87,6 +88,10 @@
|
||||
<li><h2 class="dropdown-header">@User.Identity?.Name</h2></li>
|
||||
<li><a class="dropdown-item" asp-controller="ManageAccount" asp-action="Index">Manage Account</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Onboarding" asp-action="Index">Setup preferences</a></li>
|
||||
@if (!(ViewData["ShellClass"] as string ?? "").Contains("marketing-shell", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
<li><button type="button" class="dropdown-item" data-bs-toggle="modal" data-bs-target="#customiseToolbar">Customise toolbar…</button></li>
|
||||
}
|
||||
<li><a class="dropdown-item" asp-controller="ManageAccount" asp-action="Subscription">Billing / Subscription</a></li>
|
||||
@if (Model.IsAdmin)
|
||||
{
|
||||
|
||||
63
PlotLine/Views/Shared/_ApplicationToolbar.cshtml
Normal file
63
PlotLine/Views/Shared/_ApplicationToolbar.cshtml
Normal file
@ -0,0 +1,63 @@
|
||||
@model ApplicationNavigationViewModel
|
||||
@inject PlotLine.Data.IToolbarPreferenceRepository ToolbarPreferences
|
||||
@inject ICurrentUserService CurrentToolbarUser
|
||||
@using System.Text.Json
|
||||
@{
|
||||
var keys = ToolbarCommands.Resolve(CurrentToolbarUser.UserId is int toolbarUserId ? await ToolbarPreferences.GetAsync(toolbarUserId) : null);
|
||||
var ordered = keys.Select(key => ToolbarCommands.All.Single(x => x.Key == key))
|
||||
.Concat(ToolbarCommands.All.Where(x => !keys.Contains(x.Key))).ToList();
|
||||
var controller = ViewContext.RouteData.Values["controller"]?.ToString() ?? "";
|
||||
var action = ViewContext.RouteData.Values["action"]?.ToString() ?? "";
|
||||
}
|
||||
<nav class="app-toolbar" aria-label="Your toolbar" data-app-toolbar>
|
||||
<div class="app-toolbar-commands" data-toolbar-commands>
|
||||
@foreach (var command in ordered)
|
||||
{
|
||||
var available = command.IsAvailable(Model);
|
||||
var active = available && command.IsActive(controller, action, Model.ActiveSection);
|
||||
<a class="app-toolbar-command @(active ? "active" : null)" data-toolbar-key="@command.Key"
|
||||
data-review-url="@(command.RequiresBook ? Url.Action(command.Action, command.Controller, new { bookId = 0 }) : null)"
|
||||
hidden="@(!keys.Contains(command.Key))" href="@(available ? Url.Action(command.Action, command.Controller, command.RouteValues(Model)) : null)"
|
||||
aria-current="@(active ? "page" : null)" aria-disabled="@(!available ? "true" : null)"
|
||||
title="@(available ? command.Label : command.RequiresBook && Model.Project is not null ? "Select a book to open Review Centre" : "Select a project to use this tool")">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="@command.IconPath" /></svg><span>@command.Label</span>
|
||||
</a>
|
||||
}
|
||||
<span class="app-toolbar-empty" data-toolbar-empty hidden="@(keys.Length != 0)">Choose shortcuts from Customise toolbar…</span>
|
||||
</div>
|
||||
<button type="button" class="app-toolbar-customise" data-bs-toggle="modal" data-bs-target="#customiseToolbar" title="Customise toolbar" aria-label="Customise toolbar">⋯</button>
|
||||
</nav>
|
||||
<div class="modal fade" id="customiseToolbar" tabindex="-1" aria-labelledby="customiseToolbarTitle" aria-hidden="true" data-toolbar-dialog>
|
||||
<div class="modal-dialog modal-dialog-scrollable">
|
||||
<form class="modal-content" action="@Url.Action("Save", "Toolbar")" method="post" data-toolbar-form>
|
||||
@Html.AntiForgeryToken()
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title fs-5" id="customiseToolbarTitle">Customise toolbar</h2>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cancel"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p class="small text-muted" id="toolbarInstructions">Select your shortcuts. Drag rows or use Move up and Move down to set their order. Changes apply when you save.</p>
|
||||
<div data-toolbar-choices aria-describedby="toolbarInstructions">
|
||||
@foreach (var command in ToolbarCommands.All)
|
||||
{
|
||||
<div class="toolbar-choice" data-command-key="@command.Key" draggable="true">
|
||||
<span class="toolbar-drag-handle" aria-hidden="true">⠿</span>
|
||||
<label><input type="checkbox" value="@command.Key" /> @command.Label</label>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" data-move="-1" aria-label="Move @command.Label up">↑</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" data-move="1" aria-label="Move @command.Label down">↓</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<p class="small text-muted mt-2 mb-0">Project tools need an open project. Review Centre also needs a selected book.</p>
|
||||
<p class="text-danger mt-2 mb-0" role="alert" data-toolbar-error></p>
|
||||
<span class="visually-hidden" role="status" data-toolbar-status></span>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-outline-secondary me-auto" data-toolbar-defaults>Restore defaults</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary">Save</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<script type="application/json" data-toolbar-config>@Html.Raw(JsonSerializer.Serialize(new { keys, defaults = ToolbarCommands.Defaults }))</script>
|
||||
@ -129,6 +129,10 @@
|
||||
@if (User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
<partial name="_ApplicationNavigation" model="appNavigation" />
|
||||
@if (!isMarketingPage)
|
||||
{
|
||||
<partial name="_ApplicationToolbar" model="appNavigation" />
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -324,6 +328,10 @@
|
||||
@if (User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
<script src="~/js/application-navigation.js" asp-append-version="true"></script>
|
||||
@if (!isMarketingPage)
|
||||
{
|
||||
<script src="~/js/application-toolbar.js" asp-append-version="true"></script>
|
||||
}
|
||||
<script src="~/js/word-companion-presence.js" asp-append-version="true"></script>
|
||||
<script src="~/js/story-intelligence-global-progress.js" asp-append-version="true"></script>
|
||||
}
|
||||
|
||||
@ -47,3 +47,30 @@
|
||||
[data-theme="dark"] .app-navigation .dropdown-item.active { background: rgba(241, 195, 143, .12); color: var(--app-link); }
|
||||
[data-theme="dark"] .app-layout .breadcrumb-trail a,
|
||||
[data-theme="dark"] .app-layout .breadcrumb-trail span { background: transparent !important; }
|
||||
|
||||
/* Two levels of application chrome, scoped away from the public website. */
|
||||
.app-layout .app-navigation { margin-bottom: 0; padding-block: 2px; }
|
||||
.app-layout .app-navigation .navbar-brand { font-size: .95rem; padding-right: .75rem; border-right: 1px solid var(--bs-border-color); }
|
||||
.app-layout .app-navigation .nav-link { border-radius: 2px; padding-block: .3rem; font-size: .8125rem; }
|
||||
.app-layout #appProjectMenu { margin-right: .6rem; padding-right: .75rem; border-right: 1px solid var(--bs-border-color); font-weight: 600; }
|
||||
.app-toolbar { display: flex; align-items: center; gap: .25rem; min-height: 40px; padding: 3px 12px; margin-bottom: .5rem; border-bottom: 1px solid var(--bs-border-color); background: var(--bs-tertiary-bg); color: var(--plotline-text); }
|
||||
.app-toolbar-commands { display: flex; align-items: center; gap: 2px; overflow-x: auto; min-width: 0; flex: 1; }
|
||||
.app-toolbar-command { display: inline-flex; flex: 0 0 auto; align-items: center; gap: 6px; padding: 5px 8px; color: inherit; text-decoration: none; font-size: .8125rem; line-height: 20px; border: 1px solid transparent; border-radius: 2px; white-space: nowrap; }
|
||||
.app-toolbar-command svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.app-toolbar-command:hover { background: var(--bs-secondary-bg); color: inherit; }
|
||||
.app-toolbar-command.active { background: var(--plotline-soft); border-color: var(--plotline-accent); color: var(--plotline-text); box-shadow: inset 0 -2px var(--plotline-accent); }
|
||||
.app-toolbar-command[aria-disabled="true"] { opacity: .5; cursor: default; }
|
||||
.app-toolbar-command:focus-visible, .app-toolbar-customise:focus-visible { outline: 2px solid var(--plotline-accent); outline-offset: -2px; }
|
||||
.app-toolbar-customise { flex: 0 0 auto; border: 0; border-left: 1px solid var(--bs-border-color); background: transparent; color: inherit; padding: 2px 10px; font-size: 1.2rem; }
|
||||
.app-toolbar-empty { font-size: .8rem; color: var(--plotline-muted); }
|
||||
.app-toolbar [hidden] { display: none !important; }
|
||||
.toolbar-choice { display: flex; align-items: center; gap: .4rem; padding: .35rem .2rem; border-bottom: 1px solid var(--bs-border-color); }
|
||||
.toolbar-choice label { flex: 1; font-size: .875rem; cursor: pointer; }
|
||||
.toolbar-choice input { margin-right: .4rem; accent-color: var(--plotline-accent); }
|
||||
.toolbar-drag-handle { color: var(--plotline-muted); cursor: grab; }
|
||||
.toolbar-choice:not([draggable="true"]) .toolbar-drag-handle { opacity: .3; cursor: default; }
|
||||
@media (max-width: 575.98px) { .app-toolbar { padding-inline: 6px; } .app-toolbar-command { padding-inline: 6px; } }
|
||||
[data-theme="dark"] .app-toolbar-command.active { background: rgba(241, 195, 143, .12); color: var(--app-link); }
|
||||
#customiseToolbar .btn { border-radius: 3px; }
|
||||
#customiseToolbar .modal-body { max-height: 65vh; overflow-y: auto; }
|
||||
#customiseToolbar .toolbar-choice .btn { padding: 2px 9px; }
|
||||
|
||||
@ -23,6 +23,18 @@
|
||||
if (active) choice.setAttribute('aria-current', 'page');
|
||||
else choice.removeAttribute('aria-current');
|
||||
});
|
||||
document.querySelectorAll('[data-review-url]').forEach(link => {
|
||||
if (!link.dataset.reviewUrl) return;
|
||||
if (selected) {
|
||||
link.href = link.dataset.reviewUrl.replace('/0/', `/${id}/`);
|
||||
link.removeAttribute('aria-disabled');
|
||||
link.title = 'Review Centre';
|
||||
} else {
|
||||
link.removeAttribute('href');
|
||||
link.setAttribute('aria-disabled', 'true');
|
||||
link.title = 'Select a book to open Review Centre';
|
||||
}
|
||||
});
|
||||
navigation.querySelectorAll('[data-app-book-action]').forEach(item => {
|
||||
item.hidden = !selected;
|
||||
const link = item.querySelector('[data-app-book-url]');
|
||||
|
||||
100
PlotLine/wwwroot/js/application-toolbar.js
Normal file
100
PlotLine/wwwroot/js/application-toolbar.js
Normal file
@ -0,0 +1,100 @@
|
||||
(() => {
|
||||
const dialog = document.querySelector('[data-toolbar-dialog]');
|
||||
if (!dialog) return;
|
||||
const config = JSON.parse(document.querySelector('[data-toolbar-config]').textContent);
|
||||
const form = dialog.querySelector('form');
|
||||
const list = dialog.querySelector('[data-toolbar-choices]');
|
||||
const rows = new Map([...list.children].map(row => [row.dataset.commandKey, row]));
|
||||
const strip = document.querySelector('[data-toolbar-commands]');
|
||||
const links = new Map([...strip.querySelectorAll('[data-toolbar-key]')].map(link => [link.dataset.toolbarKey, link]));
|
||||
const error = dialog.querySelector('[data-toolbar-error]');
|
||||
const status = dialog.querySelector('[data-toolbar-status]');
|
||||
let saved = [...config.keys], useDefaults = false, saving = false, dragged = null;
|
||||
function updateMoves() {
|
||||
const enabled = [...list.children].filter(row => row.querySelector('input').checked);
|
||||
for (const row of list.children) {
|
||||
const index = enabled.indexOf(row);
|
||||
row.querySelector('[data-move="-1"]').disabled = index <= 0;
|
||||
row.querySelector('[data-move="1"]').disabled = index < 0 || index === enabled.length - 1;
|
||||
row.draggable = index >= 0;
|
||||
}
|
||||
}
|
||||
function populate(keys) {
|
||||
for (const key of [...keys, ...rows.keys()].filter((key, index, all) => all.indexOf(key) === index)) {
|
||||
const row = rows.get(key);
|
||||
if (!row) continue;
|
||||
row.querySelector('input').checked = keys.includes(key);
|
||||
list.append(row);
|
||||
}
|
||||
updateMoves();
|
||||
}
|
||||
function changed() { useDefaults = false; updateMoves(); }
|
||||
dialog.addEventListener('show.bs.modal', () => { populate(saved); useDefaults = false; error.textContent = ''; status.textContent = ''; });
|
||||
dialog.addEventListener('hide.bs.modal', event => { if (saving) event.preventDefault(); });
|
||||
list.addEventListener('change', event => {
|
||||
const row = event.target.closest('[data-command-key]');
|
||||
if (!row) return;
|
||||
if (event.target.checked) {
|
||||
const firstDisabled = [...list.children].find(other => other !== row && !other.querySelector('input').checked);
|
||||
list.insertBefore(row, firstDisabled || null);
|
||||
} else list.append(row);
|
||||
changed();
|
||||
});
|
||||
list.addEventListener('click', event => {
|
||||
const button = event.target.closest('[data-move]');
|
||||
if (!button) return;
|
||||
const row = button.closest('[data-command-key]');
|
||||
const enabled = [...list.children].filter(item => item.querySelector('input').checked);
|
||||
const target = enabled[enabled.indexOf(row) + Number(button.dataset.move)];
|
||||
if (!target) return;
|
||||
if (Number(button.dataset.move) < 0) target.before(row); else target.after(row);
|
||||
changed();
|
||||
const focus = button.disabled ? row.querySelector('input') : button;
|
||||
focus.focus();
|
||||
status.textContent = `${row.querySelector('label').textContent.trim()} moved.`;
|
||||
});
|
||||
list.addEventListener('dragstart', event => {
|
||||
dragged = event.target.closest('[data-command-key]');
|
||||
if (!dragged?.querySelector('input').checked) { event.preventDefault(); return; }
|
||||
event.dataTransfer.setData('text/plain', dragged.dataset.commandKey);
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
});
|
||||
list.addEventListener('dragover', event => { if (dragged) event.preventDefault(); });
|
||||
list.addEventListener('drop', event => {
|
||||
event.preventDefault();
|
||||
const target = event.target.closest('[data-command-key]');
|
||||
if (dragged && target && target !== dragged && target.querySelector('input').checked) {
|
||||
const after = [...list.children].indexOf(dragged) < [...list.children].indexOf(target);
|
||||
if (after) target.after(dragged); else target.before(dragged);
|
||||
changed();
|
||||
}
|
||||
dragged = null;
|
||||
});
|
||||
list.addEventListener('dragend', () => { dragged = null; });
|
||||
dialog.querySelector('[data-toolbar-defaults]').addEventListener('click', () => { populate(config.defaults); useDefaults = true; status.textContent = 'Defaults restored. Save to apply.'; });
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (saving) return;
|
||||
const keys = [...list.children].filter(row => row.querySelector('input').checked).map(row => row.dataset.commandKey);
|
||||
const data = new FormData(form);
|
||||
keys.forEach(key => data.append('commandKeys', key));
|
||||
data.append('useDefaults', String(useDefaults));
|
||||
saving = true; error.textContent = '';
|
||||
const controls = [...form.querySelectorAll('button,input')];
|
||||
const disabled = controls.map(control => control.disabled);
|
||||
controls.forEach(control => { control.disabled = true; });
|
||||
try {
|
||||
const response = await fetch(form.action, { method: 'POST', body: data, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
|
||||
if (!response.ok || response.redirected) throw new Error('Unable to save. Your session may have expired. Please try again or reload the page.');
|
||||
const result = await response.json();
|
||||
if (!Array.isArray(result.commandKeys)) throw new Error('Unable to confirm the saved toolbar. Please reload the page.');
|
||||
saved = result.commandKeys;
|
||||
links.forEach(link => { link.hidden = true; });
|
||||
saved.forEach(key => { const link = links.get(key); if (link) { link.hidden = false; strip.append(link); } });
|
||||
strip.querySelector('[data-toolbar-empty]').hidden = saved.length !== 0;
|
||||
saving = false;
|
||||
bootstrap.Modal.getInstance(dialog).hide();
|
||||
} catch (failure) { error.textContent = failure.message || 'Unable to save. Please try again.'; }
|
||||
finally { saving = false; controls.forEach((control, i) => { control.disabled = disabled[i]; }); updateMoves(); }
|
||||
});
|
||||
})();
|
||||
51
docs/navigation/application-toolbar.md
Normal file
51
docs/navigation/application-toolbar.md
Normal file
@ -0,0 +1,51 @@
|
||||
# Authenticated application toolbar
|
||||
|
||||
The existing `ApplicationNavigation` service remains the authority for project/book context. It uses the user-scoped project repository, rejects inaccessible projects and limits book selection to that project's non-archived books. The Bootstrap application menus, account/status controls and mobile menu collapse remain in place. Public navigation and feature page content are unchanged.
|
||||
|
||||
`_ApplicationToolbar.cshtml` renders immediately below the application menu only for authenticated, non-marketing pages. It uses the existing Bootstrap modal/dropdown facilities and theme variables, with small inline SVG icons consistent with the existing codebase (there is no shared icon package). The strip is approximately 40px high; on narrow screens its labelled links scroll horizontally and the existing application menu collapses. Unavailable shortcuts are disabled without an href. Menus remain the comprehensive navigation mechanism.
|
||||
|
||||
## Command registry
|
||||
|
||||
`PlotLine/Services/ToolbarCommands.cs` defines stable keys, labels, SVG paths, destination controllers/actions, default membership, project/book requirements, route values and active-state detection. Current defaults, in order:
|
||||
|
||||
- Overview, Timeline, Calendar, Characters, Threads, Relationships, Review Centre.
|
||||
|
||||
Other commands:
|
||||
|
||||
- Locations, Assets, Names, At This Point, Scenarios, Floor Plans, Story Bible, Continuity, Metrics, Health, Warnings, Archive, Projects, Writer.
|
||||
|
||||
Threads uses the existing PlotThreads destination. There is no independent project-wide Plot Lines or Knowledge landing page to expose. Review Centre uses the existing book review route; it requires a selected book and does not choose one implicitly. Review Centre is also in the Book menu. No new AI or review preparation operation was added. All registered destinations use existing access checks; there are no owner/admin-only toolbar commands. Adding a restricted command must include its visibility/availability check here as well as the destination's normal server-side authorisation.
|
||||
|
||||
To add a command, add a `ToolbarCommand` to `All`, choose a unique stable key and set the actual MVC destination and section. Supply a 24x24 SVG path; labels remain visible. Set `IsDefault` if new/default users should see it. Array order determines default order. `RouteValues` handles project destinations, overview IDs and book review IDs; extend it for a destination with different parameters. Never store URLs in preferences. The registry and rendering partial are separate from the preference model, so future command execution can extend dispatch without changing stored identifiers. No speculative context commands are implemented.
|
||||
|
||||
## Preferences and migration
|
||||
|
||||
Apply `PlotLine/Sql/201_UserToolbarPreferences.sql` **before deploying this code**, following the repository's backup and manual migration procedure. This work does not apply it to shared development or production.
|
||||
|
||||
The nullable `dbo.AppUser.ToolbarCommandKeysJson` column is accessed exclusively through `dbo.UserToolbar_Get` and `dbo.UserToolbar_Save` and `IToolbarPreferenceRepository`. It belongs to the existing account row and is removed naturally when the account is deleted. No preference rows are created by rendering a page.
|
||||
|
||||
- SQL NULL means follow the current system defaults.
|
||||
- A JSON array of stable keys is an explicit custom configuration. Array position is display order; membership means enabled and absence means disabled. An empty array deliberately hides every command.
|
||||
- New commands are never appended to an existing custom array. Removed keys are ignored; remaining order is preserved. Malformed stored JSON falls back to defaults.
|
||||
- Restore defaults previews current defaults, then Save writes NULL. Cancel (including Escape/backdrop/close) leaves the persisted configuration and toolbar unchanged.
|
||||
- `ToolbarController.Save` requires authentication and antiforgery, obtains the user ID from the authenticated identity, validates command keys/duplicates and never accepts a target user ID or URL.
|
||||
- Preferences are loaded from SQL on each authenticated application page, so they survive logout, browser changes and app restarts. Concurrent browser saves use last-save-wins behavior.
|
||||
|
||||
The modal uses native drag/drop and named up/down buttons, with no new JavaScript dependencies. It updates the current toolbar only after a successful save, keeps errors in the dialog and prevents closing during the save. Unavailable commands can still be configured for use when the relevant project/book context becomes available.
|
||||
|
||||
## Active feature and book changes
|
||||
|
||||
The existing `ApplicationNavigationViewModel.ActiveSection` identifies whole features across actions. Registry matching uses it rather than matching URL substrings. Review Centre additionally recognises the Onboarding Story Intelligence action family; ordinary onboarding setup does not activate it. Projects uses the Projects/Index destination explicitly.
|
||||
|
||||
`application-navigation.js` already observes Calendar/At This Point partial replacements. The same hook updates Review Centre's book URL using only a book present in the authorised menu choices, or disables the shortcut when the page shows all books. Project switching continues through the existing project menu.
|
||||
|
||||
## Validation
|
||||
|
||||
- `dotnet build PlotLine.slnx`
|
||||
- `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj`
|
||||
- In one terminal at the repository root: `dotnet run --project PlotLine.Tests -- --toolbar-browser-host`
|
||||
- In `PlotLine.Tests/Browser`: `npm run test:toolbar`
|
||||
|
||||
The loopback-only browser host renders the real compiled navigation, toolbar, modal and Calendar surface with isolated fixtures and an in-memory preference repository. It starts no application workers and accesses no live database. Tests cover menu links/project switching, active Calendar, authorised project/book links and asynchronous book changes, show/hide, keyboard/native-drag ordering, cancel/reset, fresh browser sessions and independent identities, CSRF rejection, no-project pages, desktop/mobile and dark theme. Screenshots go to `/tmp`, never the repository. It does not replace a live authenticated smoke test after deployment.
|
||||
|
||||
SQL was separately checked in a disposable verification database: migration applied twice, SQL NULL defaults, ordered/empty preferences, independent user records, retrieval through a fresh repository and restoring defaults. The disposable database was dropped after verification; shared databases were unchanged.
|
||||
Loading…
x
Reference in New Issue
Block a user