diff --git a/src/Febe.Web/wwwroot/js/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js index 4bbed4e..19866a6 100644 --- a/src/Febe.Web/wwwroot/js/core/shell.js +++ b/src/Febe.Web/wwwroot/js/core/shell.js @@ -356,7 +356,7 @@ async function render() { if (current) { current.frame.destroy(); current = null; - document.dispatchEvent(new Event('febe:pagina')); // what lies over the page (the viewer) goes with it + document.dispatchEvent(new Event('febe:pagina')); // what lies over the page (the viewer, a dialog) goes with it } for (const [key, link] of Object.entries(navLinks)) { const here = route && route.nav === key; diff --git a/src/Febe.Web/wwwroot/js/core/ui.js b/src/Febe.Web/wwwroot/js/core/ui.js index 18d9a24..ffc0b4a 100644 --- a/src/Febe.Web/wwwroot/js/core/ui.js +++ b/src/Febe.Web/wwwroot/js/core/ui.js @@ -37,7 +37,8 @@ const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:n * Opens a modal dialog over the whole window. build(close) returns { header?, body, footer? } or a node; close(value) * resolves the returned promise. Esc and the veil close with undefined. Focus is trapped and restored. * build may also return onEscape (called first on Esc: returning true means the dialog handled it, say by closing a - * list of suggestions, and stays open) and onClose (called once, however the dialog closes). + * list of suggestions, and stays open) and onClose (called once, however the dialog closes). A change of the page under + * it (a link of a short notice, Back) takes it away as dismissed: its buttons are for what is no longer shown. */ export function dialog({ title, className = '', build, labelledBy, dismissable = true }) { return new Promise((resolve) => { @@ -49,6 +50,7 @@ export function dialog({ title, className = '', build, labelledBy, dismissable = closed = true; veil.remove(); document.removeEventListener('keydown', onKey, true); + document.removeEventListener('febe:pagina', onPage); if (parts && typeof parts.onClose === 'function') { try { parts.onClose(); @@ -94,7 +96,9 @@ export function dialog({ title, className = '', build, labelledBy, dismissable = } } }; + const onPage = () => close(undefined); document.addEventListener('keydown', onKey, true); + document.addEventListener('febe:pagina', onPage); document.body.append(veil); const autofocus = box.querySelector('[autofocus]') || box.querySelector('.contenuto ' + FOCUSABLE) || box.querySelector(FOCUSABLE); if (autofocus) autofocus.focus(); diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.StillVideos.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.StillVideos.cs index abadd48..da09c19 100644 --- a/tests/Febe.Tests/Web/ExportInterfaceTests.StillVideos.cs +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.StillVideos.cs @@ -16,7 +16,8 @@ namespace Febe.Tests.Web; /// Tappa E4 in a real browser, on the demo (spec §4.10 «Video fermi», §10.3): the chip, the row and the buttons of a still /// video in the viewer, «Salva il fotogramma» («Scarica» and «Nella cartella delle copie»), «È un video fermo?» and /// «Analizza di nuovo», the filter «Video fermi», the confirmation of «Cerca i video fermi» with its counts, its end, its -/// card in the Dashboard with the reason it waits and «Interrompi». Analyses are only ever on request: what each video is +/// card in the Dashboard with the reason it waits and «Interrompi», what a change of the page takes away, the «fermi» events +/// of the stream (which the demo does not have: the tests open one of their own). Analyses are only ever on request: what each video is /// before the test asks is read from the database and the API, never assumed from how the demo is built (it places its /// entries by the hour, #72). /// @@ -203,6 +204,7 @@ public sealed partial class ExportInterfaceTests using var temp = new TempFolder("fermi-cerca-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); await RecordNoticesAsync(ui); + await ui.AddInitScriptAsync(UiBrowser.Requests); var chosen = await ChooseVideosAsync(ui, demo); var body = $"{{ \"entryIds\": {JsonSerializer.Serialize(chosen)} }}"; @@ -256,6 +258,13 @@ public sealed partial class ExportInterfaceTests Assert.AreEqual("/libreria?tipo=fermi", (await ui.EvalAsync("(() => { const u = new URL(document.querySelector('.ricerca-fermi .riga-conteggi a').href); return u.pathname + u.search; })()")).GetString()); var left = await ui.EvalAsync(Post("/api/still-videos/plan", body)); Assert.AreEqual(0, left.GetProperty("toAnalyse").GetInt32(), left.ToString()); + + // The card is read again every few seconds: its link keeps the focus of the keyboard. + const string Asked = "window.__asked.filter((r) => r.includes('/api/still-videos/progress')).length"; + await ui.EvalAsync("(() => { window.__link = document.querySelector('.ricerca-fermi .riga-conteggi a'); window.__link.focus(); return true; })()"); + var polls = (await ui.EvalAsync(Asked)).GetInt32(); + await ui.WaitAsync($"{Asked} >= {polls + 3}", "l'avanzamento riletto"); + Assert.IsTrue((await ui.EvalAsync("window.__link.isConnected && document.activeElement === window.__link")).GetBoolean(), "the focus stays on «Mostra i video fermi»"); } [TestMethod] @@ -277,6 +286,12 @@ public sealed partial class ExportInterfaceTests Assert.AreEqual(StillVideoText.LongWork, (await ui.EvalAsync($"{Dialog}.querySelector('.avviso.ambra').textContent.trim()")).GetString()); await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()"); await ui.WaitAsync($"{Dialog} === null && {Shown("Ricerca dei video fermi avviata")}", "la ricerca parte " + ui.Report()); + + // The same videos again, while they wait: they are queued already, and nothing says that others were started. + await OpenSearchAsync(ui); + await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()"); + await ui.WaitAsync($"{Dialog} === null && {Shown("I video scelti sono già in coda.")}", "i video già in coda " + ui.Report()); + Assert.AreEqual(1, (await ui.EvalAsync("window.__notices.filter((n) => n.text.includes('Ricerca dei video fermi avviata')).length")).GetInt32()); await ui.EvalAsync(FollowNoticeLink); // Dashboard → Esportazione: nothing done yet, the reason, «Interrompi». @@ -302,8 +317,149 @@ public sealed partial class ExportInterfaceTests Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), ui.Report()); } + [TestMethod] + public async Task AChangeOfThePageTakesAwayTheViewerAndTheDialogsOverIt() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("fermi-pagina-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + await RecordNoticesAsync(ui); + var (still, _) = await DemoVideoAsync(demo, a => a?.Outcome == VideoAnalysisOutcome.Still); + + // The notice of the end of a search lies above everything, wherever it comes from. + const string FollowNotice = "import('/js/core/ui.js').then((m) => { m.toast('Analizzati 2 video: 1 fermo, 1 in movimento.', '', { label: 'Mostra i video fermi', href: '/libreria?tipo=fermi' }); const links = document.querySelectorAll('.brevi .breve a.breve-link'); links[links.length - 1].click(); return true; })"; + const string Arrived = "location.pathname === '/libreria' && new URLSearchParams(location.search).get('tipo') === 'fermi' && document.querySelector('.strumenti .filtri button.qui')?.textContent.trim() === 'Video fermi' && document.querySelector('.mosaico .tess') !== null"; + const string Nothing = "document.querySelector('.vis') === null && document.querySelector('.velo.finestra') === null"; + + // A dialog of the page itself with Back: the one of the selection, which counts as dismissed. + await ui.OpenAsync(new Uri(demo.Address, "/dashboard")); + await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .attivita') !== null", "la Dashboard"); + await ChooseVideosInPageAsync(ui, demo); + await OpenSearchAsync(ui); + await ui.EvalAsync("(() => { history.back(); return true; })()"); + await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .attivita') !== null", "Indietro " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync(Nothing)).GetBoolean(), "the dialog goes with its page"); + Assert.AreEqual(0, (await ui.EvalAsync(Get("/api/still-videos/progress"))).GetProperty("total").GetInt32(), "nothing was started"); + + await OpenInViewerAsync(ui, demo, still.Id, "docker"); + await ui.EvalAsync(FollowNotice); + await ui.WaitAsync(Arrived, "la Libreria dei video fermi " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync(Nothing)).GetBoolean(), "the viewer goes with its page"); + + // Also what was opened from it: «Salva il fotogramma» of a video that is no longer shown. + await OpenInViewerAsync(ui, demo, still.Id, "docker"); + await ui.WaitAsync("document.querySelector('.vis .azione-salva-fotogramma') !== null", "«Salva il fotogramma»"); + await ui.EvalAsync("document.querySelector('.vis .azione-salva-fotogramma').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.fotogrammi .istante-mostrato') !== null", "il dialogo «Salva il fotogramma»"); + await ui.EvalAsync(FollowNotice); + await ui.WaitAsync(Arrived, "la Libreria dei video fermi, di nuovo " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync(Nothing)).GetBoolean(), "the dialog goes with the viewer"); + Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), ui.Report()); + } + + [TestMethod] + public async Task TheViewerFollowsTheAnalysesMadeElsewhereAndOnlyTheLastReadingCounts() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("fermi-eventi-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + await ui.AddInitScriptAsync(UiBrowser.Requests); + var (video, _) = await DemoVideoAsync(demo, a => a is null); + var entry = (await demo.Storage.Entries.GetAsync(video.EntryId))!; + await OpenInViewerAsync(ui, demo, video.Id, "docker"); + await ui.WaitAsync("document.querySelector('.vis .azione-video-fermo') !== null", "«È un video fermo?» " + ui.Report()); + await OpenStreamAsync(ui); + + // From here the answers for the entry come when the test says, with what the test says. + await ui.EvalAsync($$""" + (() => { + const real = window.fetch; + window.__answers = []; + window.fetch = (input, init) => (new URL(String(input), location.href).pathname === '/api/entries/{{video.EntryId}}' + ? new Promise((resolve) => window.__answers.push((json) => resolve(new Response(JSON.stringify(json), { status: 200, headers: { 'Content-Type': 'application/json' } })))) + : real(input, init)); + window.__real = real; + return true; + })() + """); + + // An analysis made under another account: the outcome belongs to the file, which may be here too. + var change = $"{{ reason: 'fermi', accountId: {entry.AccountId + 1000}, at: 0 }}"; + await ui.EvalAsync($"window.__stream('libreria', {change})"); + await ui.WaitAsync("window.__answers.length === 1", "l'elemento riletto"); + await ui.EvalAsync($"window.__stream('libreria', {change})"); + await ui.WaitAsync("window.__answers.length === 2", "l'elemento riletto ancora"); + + // The second answer comes first; the first, older, must not bring back what was before. + await ui.EvalAsync($"window.__real('/api/entries/{video.EntryId}', {{ headers: {{ Accept: 'application/json' }} }}).then((r) => r.json()).then((j) => {{ window.__older = j; window.__newer = structuredClone(j); window.__newer.media.find((m) => m.id === {video.Id}).still = {{ outcome: 'moving', note: null, frameAtMs: null, frameLabel: null, current: true }}; return true; }})"); + await ui.EvalAsync("(() => { window.__answers[1](window.__newer); return true; })()"); + await ui.WaitAsync("document.querySelector('.vis .riga-fermo span')?.textContent === \"No: l'immagine cambia\"", "l'esito nella scheda " + ui.Report()); + await ui.EvalAsync("(() => { window.__answers[0](window.__older); return new Promise((resolve) => setTimeout(resolve, 100)); })()"); + Assert.AreEqual("No: l'immagine cambia", (await ui.EvalAsync("document.querySelector('.vis .riga-fermo span')?.textContent ?? ''")).GetString(), "an older answer does not count"); + await CloseViewerAsync(ui); + } + + [TestMethod] + public async Task AnAnalysisReloadsNeitherTheAccountsNorTheDashboard() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("fermi-ricariche-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + await ui.AddInitScriptAsync(UiBrowser.Requests); + foreach (var (path, request, ready) in new[] + { + ("/account", "GET /api/accounts", "document.querySelector('a[href^=\"/account/\"]') !== null"), + ("/dashboard", "GET /api/alerts", "document.querySelector('main .attivita') !== null"), + }) + { + var asked = $"window.__asked.filter((r) => r.split('?')[0] === {Js(request)}).length"; + await ui.OpenAsync(new Uri(demo.Address, path)); + await ui.WaitAsync($"{ready} && {asked} > 0", path + " " + ui.Report()); + await ui.WaitForQuietAsync("richieste della pagina finite"); + await OpenStreamAsync(ui); + await ui.WaitForQuietAsync("richieste della pagina finite"); + var before = (await ui.EvalAsync(asked)).GetInt32(); + + // The pages wait at most 600 ms before they read again: past a second and a half what had to be asked was. + await ui.EvalAsync("(() => { window.__stream('libreria', { reason: 'fermi', accountId: 1, at: 0 }); return new Promise((resolve) => setTimeout(resolve, 1500)); })()"); + Assert.AreEqual(before, (await ui.EvalAsync(asked)).GetInt32(), $"{path}: an analysis changes nothing here"); + + // Any other change of the library does. + await ui.EvalAsync("(() => { window.__stream('libreria', { reason: 'import', accountId: 1, at: 0 }); return true; })()"); + await ui.WaitAsync($"{asked} > {before}", $"{path}: riletta dopo un altro cambio"); + } + } + // ------------------------------------------------------------------------------------------------- support + /// + /// Opens the event stream of the interface (the demo has none) on one the test writes: window.__stream(name, data) + /// brings an event. + /// + private static async Task OpenStreamAsync(UiBrowser ui) => await ui.EvalAsync(""" + (async () => { + const streams = []; + window.EventSource = class extends EventTarget { + constructor() { + super(); + this.readyState = 1; + streams.push(this); + } + }; + window.__stream = (name, data) => { + for (const stream of streams) stream.dispatchEvent(new MessageEvent(name, { data: JSON.stringify(data) })); + return true; + }; + const context = await import('/js/core/context.js'); + const engine = await import('/js/core/engine.js'); + context.setCapabilities({ demo: false }); + engine.startEvents(); + context.setCapabilities({ demo: true }); + if (streams.length !== 1) throw new Error('il flusso degli eventi non è stato aperto'); + return true; + })() + """); + /// /// The newest video of @marta.demo whose analysis (null: never analysed) is the one looked for. Read from the database: /// which of the demo's videos they are depends on the hour it is built. @@ -341,6 +497,20 @@ public sealed partial class ExportInterfaceTests { var marta = (await demo.Storage.Accounts.ListAsync()).Single(a => a.Username == DemoStillVideos.StillAccount).Id; await ui.OpenAsync(new Uri(demo.Address, string.Create(CultureInfo.InvariantCulture, $"/libreria?account={marta}"))); + return await ChooseAsync(ui); + } + + /// As , going to the Libreria inside the page that is open. + private static async Task ChooseVideosInPageAsync(UiBrowser ui, DemoHost demo) + { + var marta = (await demo.Storage.Accounts.ListAsync()).Single(a => a.Username == DemoStillVideos.StillAccount).Id; + await ui.NavigateAsync(string.Create(CultureInfo.InvariantCulture, $"/libreria?account={marta}")); + await ui.WaitAsync("location.pathname === '/libreria'", "la Libreria"); + await ChooseAsync(ui); + } + + private static async Task ChooseAsync(UiBrowser ui) + { await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 4 && [...document.querySelectorAll('.mosaico .tess')].every((t) => t.dataset.id)", "il mosaico di marta.demo"); Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean()); return await ui.EvalAsync(