From efebbfcd1c55b97a301e6f65ad9b7a49bf380f51 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sat, 21 Nov 2026 21:15:21 +0000 Subject: [PATCH] Add persisted bottom-corner toast position preference --- Docs/Codex/Notifications.md | 8 ++++ PlotLine.Tests/AppearanceTests.cs | 5 +++ PlotLine.Tests/Browser/toast-position.cjs | 25 +++++++++++++ PlotLine/Controllers/AppearanceController.cs | 8 ++++ PlotLine/Data/AppearanceRepository.cs | 6 +++ PlotLine/Services/ApplicationAppearance.cs | 2 + PlotLine/Sql/295_UserToastPosition.sql | 27 ++++++++++++++ .../Views/Shared/_ApplicationToolbar.cshtml | 10 +++++ PlotLine/Views/Shared/_Layout.cshtml | 2 +- PlotLine/Views/Shared/_ToastHost.cshtml | 3 ++ .../Shared/_WritingCompanionLayout.cshtml | 2 +- PlotLine/Views/WordCompanionHost/Index.cshtml | 5 ++- PlotLine/wwwroot/css/notifications.css | 5 ++- PlotLine/wwwroot/js/notifications.js | 37 +++++++++++++++++++ 14 files changed, 141 insertions(+), 4 deletions(-) create mode 100644 PlotLine.Tests/Browser/toast-position.cjs create mode 100644 PlotLine/Sql/295_UserToastPosition.sql create mode 100644 PlotLine/Views/Shared/_ToastHost.cshtml diff --git a/Docs/Codex/Notifications.md b/Docs/Codex/Notifications.md index 781c8525..c66e222e 100644 --- a/Docs/Codex/Notifications.md +++ b/Docs/Codex/Notifications.md @@ -65,3 +65,11 @@ All three web shells (application, embedded writing window, Office Companion) no Retained deliberately: Word unsaved/unverified/mapping/selection/capability warnings; persistent connection/freshness/progress; first-run scan/preview/build and marker-save review instructions; detailed cleanup recovery; destructive unlink/cleanup confirmations; Context/Intent follow status and substantial unavailable-content explanations; native import conflict/review/result summaries and validation. `native-companion-review.js` only selects the submitted session; it has no competing notification mechanism. The native workspace connection label remains persistent and feeds the shared connection presentation. No Windows agent, VSTO ribbon, native modal maintenance/troubleshooting dialog, transport, debounce, capture, paragraph identity, navigation processing or analysis was changed. Focused checks: `shared-notifications.cjs`, `word-toast-outcomes.cjs`, `word-toast-paths.cjs` (actual Razor Writer/manual check/navigation/native-dialog form paths), `writer-word-notifications.cjs` (existing correlated navigation timing/race regression), `reader-word-freshness.cjs`, and `word-companion-regressions.cjs`. The existing navigation test opens the newly collapsed command diagnostics before checking them; its timing/correlation assertions are retained. Office adapter tests execute the production presentation setter without starting Office. Browser and simulated standalone checks do not physically verify Word, native Windows UI, or a genuinely installed PWA. + +## Position preference + +Toasts default to **Bottom left**. Open the account menu → **Customise PlotDirector…** → **Notifications** → **Toast position** to choose **Bottom left** or **Bottom right**. Position changes apply and save immediately, independently of the toolbar Save/Cancel buttons. No top positions are supported. + +The account's `AppUser.ToastPosition` is read through `UserAppearance_Get` and saved through `UserAppearance_SaveToastPosition` (`295_UserToastPosition.sql`), using the existing appearance repository and authenticated, antiforgery-protected `/Appearance/ToastPosition` action. All three shell hosts render that server preference, including fresh sessions and installed PWA use. A user-scoped localStorage event relays confirmed changes to other open same-origin windows; localStorage does not override the database on a new page. Failed saves restore the previous position. + +Toasts stack upwards in arrival order across notification types. Safe-area margins apply on both sides and below; narrow viewports reserve additional space above bottom controls. A shell with additional fixed controls can increase `--pd-toast-bottom-offset`. Existing toast types, timing, deduplication, dismissal and announcements are unchanged. Run `PlotLine.Tests/Browser/toast-position.cjs` against the isolated toolbar browser fixture for position, immediate application, persistence, failure rollback, cross-window and narrow/standalone checks. diff --git a/PlotLine.Tests/AppearanceTests.cs b/PlotLine.Tests/AppearanceTests.cs index 927a4534..fdad4bf0 100644 --- a/PlotLine.Tests/AppearanceTests.cs +++ b/PlotLine.Tests/AppearanceTests.cs @@ -13,6 +13,10 @@ internal static class AppearanceTests controller.Theme("modern-dark").GetAwaiter().GetResult(); controller.Theme("warm-light", true).GetAwaiter().GetResult(); if (store.GetAsync(4).Result.ThemeKey != "modern-dark" || store.GetAsync(5).Result.ThemeKey is not null) throw new Exception("Legacy migration must preserve explicit choices and isolate users."); + if (store.GetAsync(4).Result.ToastPosition != "bottom-left") throw new Exception("Toasts default bottom left."); + controller.ToastPosition("bottom-right").GetAwaiter().GetResult(); + if (store.GetAsync(4).Result.ToastPosition != "bottom-right" || store.GetAsync(5).Result.ToastPosition != "bottom-left") throw new Exception("Toast settings must persist independently per account."); + if (controller.ToastPosition("top-right").Result is not BadRequestResult) throw new Exception("Top toast positions must be rejected."); controller.Ribbon(true).GetAwaiter().GetResult(); if (!store.GetAsync(4).Result.RibbonCollapsed || store.GetAsync(4).Result.ThemeKey != "modern-dark") throw new Exception("Ribbon preference must not overwrite theme."); if (!store.GetAsync(5).Result.ShowProjectContextMenu || !store.GetAsync(5).Result.ShowBookContextMenu) throw new Exception("Application bar menus default visible."); @@ -41,6 +45,7 @@ internal sealed class AppearanceMemoryPreferences : IAppearanceRepository lock(value) { if (!onlyIfUnset || value.ThemeKey is null) value.ThemeKey = theme; } return Task.CompletedTask; } + public Task SaveToastPositionAsync(int id, string position) { GetAsync(id).Result.ToastPosition = position; return Task.CompletedTask; } public Task SaveRibbonAsync(int id, bool collapsed) { GetAsync(id).Result.RibbonCollapsed = collapsed; return Task.CompletedTask; } public Task SaveApplicationBarAsync(int id, bool showProject, bool showBook) { diff --git a/PlotLine.Tests/Browser/toast-position.cjs b/PlotLine.Tests/Browser/toast-position.cjs new file mode 100644 index 00000000..9add3708 --- /dev/null +++ b/PlotLine.Tests/Browser/toast-position.cjs @@ -0,0 +1,25 @@ +// Actual Settings, controller, per-user preference store and toast assets; no live DB. +const {chromium}=require('playwright'),assert=require('node:assert/strict'); +const base=process.env.PD_BROWSER_FIXTURE_URL||'http://127.0.0.1:5238'; +(async()=>{const browser=await chromium.launch();try{for(const standalone of [false,true]){ + const context=await browser.newContext({viewport:{width:1440,height:1000}});if(standalone)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true})); + const page=await context.newPage();await page.goto(base+'/fixture?layout=full');await page.waitForFunction(()=>window.PlotDirector?.toast); + const choose=page.locator('[data-toast-position-choice]'),host=page.locator('[data-toast-host]'); + assert.deepEqual(await choose.locator('option').allTextContents(),['Bottom left','Bottom right']); + await page.evaluate(()=>document.querySelector('[data-toolbar-dialog]').classList.add('show')); + // Bootstrap modal open through its normal API; avoids depending on toolbar visibility. + await page.evaluate(()=>bootstrap.Modal.getOrCreateInstance(document.querySelector('[data-toolbar-dialog]')).show()); + if(await choose.inputValue()!=='bottom-left'){await choose.selectOption('bottom-left');await page.locator('[data-toast-position-status]').filter({hasText:'saved'}).waitFor();} + await page.evaluate(()=>{for(const type of ['success','error','info','warning'])PlotDirector.toast[type]('Position '+type,{duration:0});}); + let rect=await host.boundingBox();assert(rect.x<30&&rect.y>400&&rect.y+rect.height<=984); + const ys=await page.locator('.pd-toast').evaluateAll(nodes=>nodes.sort((a,b)=>Number(a.style.order)-Number(b.style.order)).map(n=>n.getBoundingClientRect().y));assert(ys[0]>ys[1]&&ys[1]>ys[2]&&ys[2]>ys[3],'mixed categories stack upwards in arrival order'); + const sibling=await context.newPage();await sibling.goto(base+'/fixture?layout=full');await sibling.waitForFunction(()=>window.PlotDirector?.toast); + let release;await page.route('**/Appearance/ToastPosition',async route=>{await new Promise(resolve=>release=resolve);await route.continue();}); + await choose.selectOption('bottom-right');assert.equal(await host.getAttribute('data-toast-position'),'bottom-right','active host moves before network save');while(!release)await page.waitForTimeout(10);release();await page.locator('[data-toast-position-status]').filter({hasText:'saved'}).waitFor();await page.unroute('**/Appearance/ToastPosition'); + await sibling.waitForFunction(()=>document.querySelector('[data-toast-host]').dataset.toastPosition==='bottom-right'); + const fresh=await browser.newContext(),freshPage=await fresh.newPage();await freshPage.goto(base+'/fixture?layout=full');assert.equal(await freshPage.locator('[data-toast-host]').getAttribute('data-toast-position'),'bottom-right','server preference survives a new browser session');await fresh.close(); + await page.setViewportSize({width:390,height:844});rect=await host.boundingBox();assert(rect.x>=15&&rect.x+rect.width<=375&&rect.y+rect.height<=772,'narrow viewport reserves bottom controls/margins: '+JSON.stringify(rect)); + await page.route('**/Appearance/ToastPosition',r=>r.fulfill({status:500,body:'Synthetic failure'}));await choose.selectOption('bottom-left');await page.locator('[data-toast-position-status]').filter({hasText:'Could not save'}).waitFor();assert.equal(await host.getAttribute('data-toast-position'),'bottom-right','failed save restores previous choice'); + await page.unroute('**/Appearance/ToastPosition');await choose.selectOption('bottom-left');await page.locator('[data-toast-position-status]').filter({hasText:'saved'}).waitFor(); + console.log('PASS toast Settings: exactly two choices, bottom-left default, immediate move, upward mixed stack, server/new-session and cross-window persistence, failure rollback, mobile bounds; standalone='+standalone);await context.close(); +}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine/Controllers/AppearanceController.cs b/PlotLine/Controllers/AppearanceController.cs index 5c306eb8..2ad210f6 100644 --- a/PlotLine/Controllers/AppearanceController.cs +++ b/PlotLine/Controllers/AppearanceController.cs @@ -16,6 +16,14 @@ public sealed class AppearanceController(ICurrentUserService user, IAppearanceRe return Json(await preferences.GetAsync(id)); } [HttpPost, ValidateAntiForgeryToken] + public async Task ToastPosition(string position) + { + if (user.UserId is not int id) return Unauthorized(); + if (!ModelState.IsValid || !ApplicationAppearance.IsValidToastPosition(position)) return BadRequest(); + await preferences.SaveToastPositionAsync(id, position); + return Json(await preferences.GetAsync(id)); + } + [HttpPost, ValidateAntiForgeryToken] public async Task Ribbon(bool collapsed) { if (user.UserId is not int id) return Unauthorized(); diff --git a/PlotLine/Data/AppearanceRepository.cs b/PlotLine/Data/AppearanceRepository.cs index e340a242..00e1f8d3 100644 --- a/PlotLine/Data/AppearanceRepository.cs +++ b/PlotLine/Data/AppearanceRepository.cs @@ -7,6 +7,7 @@ public interface IAppearanceRepository { Task GetAsync(int userId); Task SaveThemeAsync(int userId, string themeKey, bool onlyIfUnset = false); + Task SaveToastPositionAsync(int userId, string position); Task SaveRibbonAsync(int userId, bool collapsed); Task SaveApplicationBarAsync(int userId, bool showProjectContextMenu, bool showBookContextMenu); } @@ -22,6 +23,11 @@ public sealed class AppearanceRepository(ISqlConnectionFactory connections) : IA using var connection = connections.CreateConnection(); await connection.ExecuteAsync("dbo.UserAppearance_SaveTheme", new { UserID = userId, ThemeKey = themeKey, OnlyIfUnset = onlyIfUnset }, commandType: CommandType.StoredProcedure); } + public async Task SaveToastPositionAsync(int userId, string position) + { + using var connection = connections.CreateConnection(); + await connection.ExecuteAsync("dbo.UserAppearance_SaveToastPosition", new { UserID = userId, Position = position }, commandType: CommandType.StoredProcedure); + } public async Task SaveRibbonAsync(int userId, bool collapsed) { using var connection = connections.CreateConnection(); diff --git a/PlotLine/Services/ApplicationAppearance.cs b/PlotLine/Services/ApplicationAppearance.cs index 7d6add4d..f1ffeacf 100644 --- a/PlotLine/Services/ApplicationAppearance.cs +++ b/PlotLine/Services/ApplicationAppearance.cs @@ -2,6 +2,8 @@ namespace PlotLine.Services; public sealed class ApplicationAppearance { + public string ToastPosition { get; set; } = "bottom-left"; + public static bool IsValidToastPosition(string? position) => position is "bottom-left" or "bottom-right"; public const string DefaultTheme = "plotdirector"; public string? ThemeKey { get; set; } public bool RibbonCollapsed { get; set; } diff --git a/PlotLine/Sql/295_UserToastPosition.sql b/PlotLine/Sql/295_UserToastPosition.sql new file mode 100644 index 00000000..9f418d01 --- /dev/null +++ b/PlotLine/Sql/295_UserToastPosition.sql @@ -0,0 +1,27 @@ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +IF COL_LENGTH(N'dbo.AppUser', N'ToastPosition') IS NULL + ALTER TABLE dbo.AppUser ADD ToastPosition varchar(12) NOT NULL + CONSTRAINT DF_AppUser_ToastPosition DEFAULT 'bottom-left' + CONSTRAINT CK_AppUser_ToastPosition CHECK (ToastPosition IN ('bottom-left','bottom-right')); +GO +CREATE OR ALTER PROCEDURE dbo.UserAppearance_Get @UserID int +AS +BEGIN + SET NOCOUNT ON; + SELECT ApplicationThemeKey AS ThemeKey, RibbonCollapsed, + ShowProjectContextMenu, ShowBookContextMenu, ToastPosition + FROM dbo.AppUser WHERE UserID = @UserID; +END; +GO +CREATE OR ALTER PROCEDURE dbo.UserAppearance_SaveToastPosition @UserID int, @Position varchar(32) +AS +BEGIN + SET NOCOUNT ON; + IF @Position IS NULL OR @Position NOT IN ('bottom-left','bottom-right') + THROW 50001, 'Unknown toast position', 1; + UPDATE dbo.AppUser SET ToastPosition = @Position WHERE UserID = @UserID; +END; +GO diff --git a/PlotLine/Views/Shared/_ApplicationToolbar.cshtml b/PlotLine/Views/Shared/_ApplicationToolbar.cshtml index 0d6f804b..a4756f57 100644 --- a/PlotLine/Views/Shared/_ApplicationToolbar.cshtml +++ b/PlotLine/Views/Shared/_ApplicationToolbar.cshtml @@ -62,6 +62,16 @@ +
+

Notifications

+ + +

Toast position changes save immediately.

+

+
diff --git a/PlotLine/Views/Shared/_Layout.cshtml b/PlotLine/Views/Shared/_Layout.cshtml index 56e82160..dfd57b37 100644 --- a/PlotLine/Views/Shared/_Layout.cshtml +++ b/PlotLine/Views/Shared/_Layout.cshtml @@ -337,7 +337,7 @@ } -
+ diff --git a/PlotLine/Views/Shared/_ToastHost.cshtml b/PlotLine/Views/Shared/_ToastHost.cshtml new file mode 100644 index 00000000..12cdf45a --- /dev/null +++ b/PlotLine/Views/Shared/_ToastHost.cshtml @@ -0,0 +1,3 @@ +@using System.Security.Claims +@model ApplicationAppearance +
diff --git a/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml b/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml index 0c2cdd2c..c946df77 100644 --- a/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml +++ b/PlotLine/Views/Shared/_WritingCompanionLayout.cshtml @@ -5,4 +5,4 @@ var appearance=userID>0?await AppearancePreferences.GetAsync(userID):new ApplicationAppearance(); } @ViewData["Title"] · PlotDirector -
PlotDirector
@RenderBody()
@await RenderSectionAsync("Scripts",required:false) +
PlotDirector
@RenderBody()@await RenderSectionAsync("Scripts",required:false) diff --git a/PlotLine/Views/WordCompanionHost/Index.cshtml b/PlotLine/Views/WordCompanionHost/Index.cshtml index 99ce7a8a..9f6fce6a 100644 --- a/PlotLine/Views/WordCompanionHost/Index.cshtml +++ b/PlotLine/Views/WordCompanionHost/Index.cshtml @@ -1,6 +1,9 @@ @model PlotLine.ViewModels.WordCompanionHostViewModel +@using System.Security.Claims +@inject PlotLine.Data.IAppearanceRepository AppearancePreferences @{ Layout = null; + var appearance = int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier), out var toastUser) ? await AppearancePreferences.GetAsync(toastUser) : new ApplicationAppearance(); var statusText = Model.IsAuthenticated ? "Connected" : "Not signed in"; } @@ -618,7 +621,7 @@ { } -
+ diff --git a/PlotLine/wwwroot/css/notifications.css b/PlotLine/wwwroot/css/notifications.css index b555e404..9192405b 100644 --- a/PlotLine/wwwroot/css/notifications.css +++ b/PlotLine/wwwroot/css/notifications.css @@ -1,4 +1,7 @@ -.pd-toast-host { position: fixed; z-index: 1090; top: max(1rem, env(safe-area-inset-top)); right: max(1rem, env(safe-area-inset-right)); width: min(26rem, calc(100vw - 2rem)); display: grid; gap: .65rem; pointer-events: none; max-height: calc(100dvh - 2rem); overflow-y: auto; } +.pd-toast-host { position: fixed; z-index: 1090; bottom: calc(max(1rem, env(safe-area-inset-bottom)) + var(--pd-toast-bottom-offset, 0px)); left: max(1rem, env(safe-area-inset-left)); right: auto; width: min(26rem, calc(100vw - max(1rem, env(safe-area-inset-left)) - max(1rem, env(safe-area-inset-right)))); display: flex; flex-direction: column-reverse; gap: .65rem; pointer-events: none; max-height: 60dvh; overflow-y: auto; } +.pd-toast-host[data-toast-position="bottom-right"] { left: auto; right: max(1rem, env(safe-area-inset-right)); } +.pd-toast { flex-shrink: 0; } +@media (max-width: 767px) { .pd-toast-host { bottom: calc(max(4.5rem, 72px, env(safe-area-inset-bottom) + 1rem) + var(--pd-toast-bottom-offset, 0px)); } } .pd-toast { display: flex; align-items: start; gap: .75rem; padding: .9rem 1rem; border: 1px solid var(--bs-border-color, #888); border-left: .3rem solid var(--toast-accent); border-radius: .5rem; background: var(--plotline-surface-elevated, var(--bs-body-bg, white)); color: var(--plotline-text, var(--bs-body-color, #212529)); box-shadow: 0 .25rem 1rem #0003; pointer-events: auto; overflow-wrap: anywhere; } .pd-toast--success { --toast-accent: #198754; } .pd-toast--info { --toast-accent: #0d6efd; } diff --git a/PlotLine/wwwroot/js/notifications.js b/PlotLine/wwwroot/js/notifications.js index a039f4eb..8b63c69c 100644 --- a/PlotLine/wwwroot/js/notifications.js +++ b/PlotLine/wwwroot/js/notifications.js @@ -4,6 +4,42 @@ if (pd.toast) return; const host = document.querySelector('[data-toast-host]'); if (!host) return; + const validPositions = new Set(['bottom-left', 'bottom-right']); + const storageKey = 'plotdirector.toastPosition.' + (host.dataset.toastUser || 'anonymous'); + const applyPosition = position => { + host.dataset.toastPosition = validPositions.has(position) ? position : 'bottom-left'; + document.querySelectorAll('[data-toast-position-choice]').forEach(choice => choice.value = host.dataset.toastPosition); + }; + applyPosition(host.dataset.toastPosition); + window.addEventListener('storage', event => { + if (event.key === storageKey && validPositions.has(event.newValue)) applyPosition(event.newValue); + }); + document.addEventListener('change', async event => { + const choice = event.target.closest('[data-toast-position-choice]'); + if (!choice || !validPositions.has(choice.value)) return; + const previous = host.dataset.toastPosition; + applyPosition(choice.value); + choice.disabled = true; + const status = document.querySelector('[data-toast-position-status]'); + if (status) status.textContent = 'Saving toast position…'; + try { + const body = new FormData(); + body.set('position', choice.value); + body.set('__RequestVerificationToken', document.querySelector('[data-appearance-form] [name="__RequestVerificationToken"]').value); + const response = await fetch(host.dataset.toastPositionUrl, {method:'POST', body, headers:{'X-Requested-With':'XMLHttpRequest'}}); + if (!response.ok || response.redirected) throw new Error(); + const saved = await response.json(); + if (!validPositions.has(saved.toastPosition)) throw new Error(); + applyPosition(saved.toastPosition); + try { localStorage.setItem(storageKey, saved.toastPosition); } catch { } + if (status) status.textContent = 'Toast position saved'; + } catch { + applyPosition(previous); + if (status) status.textContent = 'Could not save toast position. Please try again.'; + pd.toast.error('Could not save toast position. Please try again.'); + } finally { choice.disabled = false; } + }); + let sequence = 0; const regions = {}; for (const priority of ['polite', 'assertive']) { const region = document.createElement('div'); @@ -25,6 +61,7 @@ if (active.size >= 4) active.values().next().value(); const node = document.createElement('div'); node.className = 'pd-toast pd-toast--' + type; + node.style.order = String(sequence++); node.setAttribute('role', type === 'error' || type === 'warning' ? 'alert' : 'status'); node.setAttribute('aria-atomic', 'true'); const content = document.createElement('span');