From 0ceffffe5052f794c6a8b286ec7c184cc86deedb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 01:38:13 +0000 Subject: [PATCH] Interfaccia: correzioni della revisione (web-1, web-2, web-3, web-4, web-5, web-6, web-7, web-9, web-10, web-11, web-12, web-13, web-14, web-15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il browser preso dalle pagine Browser e Collegamento si restituisce uscendo senza «Ho finito» (anche chiudendo o ricaricando la scheda); dopo «Ho finito» la vista remota si chiude e non si riprende il browser. Vista remota: AltGr/Option come testo, pulsante rilasciato anche fuori dalla vista. Mosaico e scheda account senza risposte vecchie né viste sovrascritte; nuovi elementi dopo la libreria vuota; intestazione sempre aggiornata. Indietro del browser con la richiesta delle modifiche non salvate; nulla resta registrato da una pagina lasciata mentre caricava; maniglie della fascia trascinabili. «Da una data» come giorno locale; niente «@null» nel riquadro di stato; orari futuri dei fermi «verso le». Prove nel browser vero (InterfaceTests). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA --- docs/guida/Primo-collegamento.md | 4 +- src/Febe.Core/Engine/CircuitBreaker.cs | 6 +- src/Febe.Core/Engine/EngineHost.cs | 2 +- src/Febe.Core/Engine/Governor.cs | 2 +- src/Febe.Core/Engine/Monitor.cs | 4 +- src/Febe.Core/Engine/MonitorModels.cs | 2 +- src/Febe.Web/Api/AccountSettingsMapper.cs | 12 +- src/Febe.Web/Api/AccountsApi.cs | 4 +- src/Febe.Web/Connection/PROTOCOLLO.md | 4 + src/Febe.Web/Demo/DemoSeeder.cs | 4 +- src/Febe.Web/LEGGIMI.md | 4 +- src/Febe.Web/wwwroot/js/core/api.js | 7 +- src/Febe.Web/wwwroot/js/core/shell.js | 55 +- src/Febe.Web/wwwroot/js/pages/account.js | 39 +- src/Febe.Web/wwwroot/js/pages/activity.js | 1 + src/Febe.Web/wwwroot/js/pages/browser.js | 11 +- src/Febe.Web/wwwroot/js/pages/connection.js | 118 +++- src/Febe.Web/wwwroot/js/pages/mosaic.js | 21 +- src/Febe.Web/wwwroot/js/pages/remote-view.js | 67 ++- .../wwwroot/js/pages/settings-limits.js | 21 +- src/Febe.Web/wwwroot/testi/it.json | 5 +- tests/Febe.Tests/Alerts/AlertServiceTests.cs | 2 +- tests/Febe.Tests/Engine/EngineMonitorTests.cs | 11 + tests/Febe.Tests/Web/AccountsApiTests.cs | 39 ++ tests/Febe.Tests/Web/InterfaceTests.cs | 537 ++++++++++++++++++ .../Web/Part2Support/Part2Helpers.cs | 33 +- tests/Febe.Tests/Web/Support/UiBrowser.cs | 409 +++++++++++++ 27 files changed, 1365 insertions(+), 59 deletions(-) create mode 100644 tests/Febe.Tests/Web/InterfaceTests.cs create mode 100644 tests/Febe.Tests/Web/Support/UiBrowser.cs diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md index 6fa606c..e53a506 100644 --- a/docs/guida/Primo-collegamento.md +++ b/docs/guida/Primo-collegamento.md @@ -63,7 +63,9 @@ Poi aggiungi gli account da seguire: [Account e impostazioni](Account-e-impostaz Da collegato, **«Usa il browser»** apre il browser di Febe (in Docker la pagina «Browser», con la vista remota e i comandi «Indietro» e «Ricarica»; su Windows la finestra). Serve per controllare qualcosa a mano. Mentre lo usi il -motore resta fermo; quando hai finito premi «Ho finito». +motore resta fermo; quando hai finito premi «Ho finito». Se lasci la pagina Browser, o la pagina Collegamento mentre +accedi, senza premere «Ho finito» (un'altra pagina, la scheda chiusa o ricaricata), vale come «Annulla»: il browser +torna sulla pagina vuota e il motore può lavorare di nuovo. ## Scollegarsi diff --git a/src/Febe.Core/Engine/CircuitBreaker.cs b/src/Febe.Core/Engine/CircuitBreaker.cs index dfc4767..3a665bd 100644 --- a/src/Febe.Core/Engine/CircuitBreaker.cs +++ b/src/Febe.Core/Engine/CircuitBreaker.cs @@ -269,8 +269,8 @@ public sealed class CircuitBreaker : ICircuitBreaker await _events.WriteAsync( EventSeverity.Warning, EngineEventCodes.ThrottleStop, - $"Instagram ha chiesto di rallentare (segnale {signal.Code}). Ho chiuso la sessione e mi fermo per {ItalianText.Duration(stop)}, " - + $"fino {ItalianText.AtDay(until, now, zone)}. Poi i tetti restano dimezzati per 48 ore.", + $"Instagram ha chiesto di rallentare (segnale {signal.Code}). Ho chiuso la sessione e mi fermo per {ItalianText.Duration(stop)}: " + + $"riparto {ItalianText.Around(until, now, zone)}. Poi i tetti restano dimezzati per 48 ore.", sessionId: sessionId, ct: ct).ConfigureAwait(false); @@ -332,7 +332,7 @@ public sealed class CircuitBreaker : ICircuitBreaker } var tail = halvedUntil is { } h - ? $" Riprendo con i tetti dimezzati fino {ItalianText.AtDay(h, until, _clock.LocalZone)}." + ? $" Riprendo con i tetti dimezzati, di nuovo pieni {ItalianText.Around(h, until, _clock.LocalZone)}." : " Riprendo con i tetti normali."; await _events.WriteAsync(EventSeverity.Info, EngineEventCodes.ThrottleEnd, "Fine del fermo per rallentamento." + tail, ct: ct).ConfigureAwait(false); } diff --git a/src/Febe.Core/Engine/EngineHost.cs b/src/Febe.Core/Engine/EngineHost.cs index 9c2cc0c..2714823 100644 --- a/src/Febe.Core/Engine/EngineHost.cs +++ b/src/Febe.Core/Engine/EngineHost.cs @@ -203,7 +203,7 @@ public sealed class EngineHost : IAsyncDisposable breaker = _s.Breaker.State; if (breaker.Status == BreakerStatus.Throttled && breaker.Until is { } until) { - messages.Add($"Il fermo per rallentamento dura fino {ItalianText.AtDay(until, _s.Clock.Now, _s.Clock.LocalZone)} e non si accorcia."); + messages.Add($"Il fermo per rallentamento non si accorcia: Febe riparte {ItalianText.Around(until, _s.Clock.Now, _s.Clock.LocalZone)}."); } else if (resumed) { diff --git a/src/Febe.Core/Engine/Governor.cs b/src/Febe.Core/Engine/Governor.cs index 6c2a4fb..11f18ac 100644 --- a/src/Febe.Core/Engine/Governor.cs +++ b/src/Febe.Core/Engine/Governor.cs @@ -401,7 +401,7 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci internal static string BreakerMessage(BreakerState state, DateTimeOffset now, TimeZoneInfo zone) => state.Status switch { BreakerStatus.Throttled when state.Until is { } until => - $"Instagram ha chiesto di rallentare: Febe è fermo fino {ItalianText.AtDay(until, now, zone)}.", + $"Instagram ha chiesto di rallentare: Febe è fermo e riparte {ItalianText.Around(until, now, zone)}.", BreakerStatus.Challenge => "Instagram chiede una verifica: Febe è fermo finché non la completi nel browser e premi «Riprendi».", BreakerStatus.Disconnected => "La sessione di Instagram è chiusa: Febe è fermo finché non accedi di nuovo nel browser e premi «Riprendi».", _ => "Febe è fermo.", diff --git a/src/Febe.Core/Engine/Monitor.cs b/src/Febe.Core/Engine/Monitor.cs index cd6c116..92c2d07 100644 --- a/src/Febe.Core/Engine/Monitor.cs +++ b/src/Febe.Core/Engine/Monitor.cs @@ -211,7 +211,7 @@ public sealed class EngineMonitor : IEngineMonitor BreakerStatus.Throttled when breaker.Until is { } until => new StopBanner( BannerLevel.Warning, "Instagram ha chiesto di rallentare", - $"Ho chiuso la sessione e mi fermo fino {ItalianText.AtDay(until, now, zone)}; poi riparto da solo con i tetti dimezzati per 48 ore.", + $"Ho chiuso la sessione e riparto da solo {ItalianText.Around(until, now, zone)}, con i tetti dimezzati per 48 ore.", false), _ => null, }; @@ -223,7 +223,7 @@ public sealed class EngineMonitor : IEngineMonitor $"Avvio graduale: tetti al {ItalianText.Number((long)Math.Round(budgets.Factor * 100))}%" + (budgets.Until is { } u ? $", pieni {ItalianText.Around(u, now, zone)}" : string.Empty) + ".", BudgetReduction.HalvedAfterThrottle => - "Tetti dimezzati dopo un rallentamento" + (budgets.Until is { } h ? $" fino {ItalianText.AtDay(h, now, zone)}" : string.Empty) + ".", + "Tetti dimezzati dopo un rallentamento" + (budgets.Until is { } h ? $", di nuovo pieni {ItalianText.Around(h, now, zone)}" : string.Empty) + ".", _ => null, }; diff --git a/src/Febe.Core/Engine/MonitorModels.cs b/src/Febe.Core/Engine/MonitorModels.cs index 6c6cf6d..25d7ad0 100644 --- a/src/Febe.Core/Engine/MonitorModels.cs +++ b/src/Febe.Core/Engine/MonitorModels.cs @@ -169,7 +169,7 @@ public sealed record EngineSnapshot /// «Profilo «Prudente»» with the reduction in force, if any. public required string ProfileLine { get; init; } - /// «Avvio graduale: tetti al 64%» or «Tetti dimezzati fino a giovedì alle 17:32»; null without reductions. + /// «Avvio graduale: tetti al 64%» or «Tetti dimezzati dopo un rallentamento, di nuovo pieni giovedì verso le 17:32»; null without reductions. public string? ReductionNote { get; init; } public required DayStrip Today { get; init; } diff --git a/src/Febe.Web/Api/AccountSettingsMapper.cs b/src/Febe.Web/Api/AccountSettingsMapper.cs index cc8f412..40c0a51 100644 --- a/src/Febe.Web/Api/AccountSettingsMapper.cs +++ b/src/Febe.Web/Api/AccountSettingsMapper.cs @@ -1,4 +1,3 @@ -using System.Globalization; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Library; @@ -16,9 +15,16 @@ public static class AccountSettingsMapper /// Largest «Storico, massimo al giorno» the form accepts: twice the «Rapido» value (spec §7.5). public static int MaxBackfillPerDay => CautionProfile.Fast.BackfillPostsPerAccountPerDay * 2; - public static AccountSettingsDto ToDto(Account account) + /// The form of an account. + /// The stored account. + /// + /// Alberto's zone: «Da una data» is stored as the first instant of a local day (), + /// so it is shown as that local day, which turns back into the same instant. + /// + public static AccountSettingsDto ToDto(Account account, TimeZoneInfo zone) { ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(zone); var reference = account with { IsFollowed = false, Frequency = account.Frequency == Frequency.Custom ? Frequency.Custom : account.Frequency }; return new AccountSettingsDto( account.KeepUpdated, @@ -28,7 +34,7 @@ public static class AccountSettingsMapper ApiMapping.Types(account.ContentTypes), ApiMapping.Depth(account.Limits.Depth), account.Limits.LastPosts, - account.Limits.FromDate is { } from ? from.UtcDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) : null, + account.Limits.FromDate is { } from ? ApiMapping.Day(LocalCalendar.Today(from, zone)) : null, account.Limits.BackfillPostsPerDay, account.Limits.MaxVideoBytes is { } bytes ? Math.Round(bytes / 1024d / 1024d, 1) : null, account.Limits.StoryVideos, diff --git a/src/Febe.Web/Api/AccountsApi.cs b/src/Febe.Web/Api/AccountsApi.cs index d328c24..0728c43 100644 --- a/src/Febe.Web/Api/AccountsApi.cs +++ b/src/Febe.Web/Api/AccountsApi.cs @@ -57,7 +57,7 @@ public static class AccountsApi throw new BadRequestException($"{ItalianText.Handle(account.Username)} è «Solo archivio»: Febe non lo contatta."); } - var edited = AccountSettingsMapper.Apply(account, AccountSettingsMapper.ToDto(account) with { KeepUpdated = body.Value }, clock.LocalZone, clock.Now, account.Folder); + var edited = AccountSettingsMapper.Apply(account, AccountSettingsMapper.ToDto(account, clock.LocalZone) with { KeepUpdated = body.Value }, clock.LocalZone, clock.Now, account.Folder); await storage.Accounts.UpdateAsync(edited, ct).ConfigureAwait(false); await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false); changes.Publish(new LibraryChange(clock.Now, id, "account")); @@ -303,7 +303,7 @@ public static class AccountsApi return new AccountDetailDto( Row(account, summary, avatar, resumesTomorrow, now, zone), new AccountStatsDto(stats.EntriesInLibrary, stats.Posts, stats.Stories, stats.HighlightItems, stats.Tagged, stats.ProfilePictures, stats.HighlightCollections, stats.Bytes, stats.PendingFiles), - AccountSettingsMapper.ToDto(account), + AccountSettingsMapper.ToDto(account, zone), await PlanAsync(storage, account, now, ct).ConfigureAwait(false), library.Layout.AccountFolder(account), account.Folder is null, diff --git a/src/Febe.Web/Connection/PROTOCOLLO.md b/src/Febe.Web/Connection/PROTOCOLLO.md index 2a18ee5..78ebb8c 100644 --- a/src/Febe.Web/Connection/PROTOCOLLO.md +++ b/src/Febe.Web/Connection/PROTOCOLLO.md @@ -15,6 +15,10 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`. +L'interfaccia manda `cancel` anche quando Alberto lascia la pagina Browser, o la pagina Collegamento mentre accede, +senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch` con `keepalive`, che porta +l'`Origin` dell'interfaccia). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`. + ## Vista remota (`/api/vista`, solo veste Docker) WebSocket sullo stesso host dell'interfaccia; si apre solo da una sessione autenticata e con `Origin` uguale diff --git a/src/Febe.Web/Demo/DemoSeeder.cs b/src/Febe.Web/Demo/DemoSeeder.cs index 890b183..f0c0b11 100644 --- a/src/Febe.Web/Demo/DemoSeeder.cs +++ b/src/Febe.Web/Demo/DemoSeeder.cs @@ -497,9 +497,9 @@ public static class DemoSeeder var throttle = LocalCalendar.StartOfDay(today.AddDays(-3), zone) + TimeSpan.FromHours(18.4); var throttleEnd = throttle + TimeSpan.FromHours(1); events.Add(Event(throttle, EventSeverity.Warning, Core.Engine.EngineEventCodes.ThrottleStop, - $"Instagram ha chiesto di rallentare (segnale http-429). Ho chiuso la sessione e mi fermo per 1 ora, fino {Core.Engine.ItalianText.AtDay(throttleEnd, throttle, zone)}. Poi i tetti restano dimezzati per 48 ore.", null)); + $"Instagram ha chiesto di rallentare (segnale http-429). Ho chiuso la sessione e mi fermo per 1 ora: riparto {Core.Engine.ItalianText.Around(throttleEnd, throttle, zone)}. Poi i tetti restano dimezzati per 48 ore.", null)); events.Add(Event(throttleEnd, EventSeverity.Info, Core.Engine.EngineEventCodes.ThrottleEnd, - $"Fine del fermo per rallentamento. Riprendo con i tetti dimezzati fino {Core.Engine.ItalianText.AtDay(throttleEnd + TimeSpan.FromHours(48), throttleEnd, zone)}.", null)); + $"Fine del fermo per rallentamento. Riprendo con i tetti dimezzati, di nuovo pieni {Core.Engine.ItalianText.Around(throttleEnd + TimeSpan.FromHours(48), throttleEnd, zone)}.", null)); foreach (var (spec, account) in accounts.Where(a => a.Account.BackfillCompletedAt is { } done && done > now - TimeSpan.FromDays(14) && done < now)) { events.Add(Event(account.BackfillCompletedAt!.Value, EventSeverity.Success, Core.Engine.EngineEventCodes.BackfillCompleted, diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index 0e411c4..e26269e 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -177,7 +177,9 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da - `page.tabs(nodo)`, `page.tools(nodo)`: linguette e riga degli strumenti; `page.body`: contenuto che scorre; - `page.saveBar(nodo)`: barra fissa in basso (`null` la toglie); `page.guard(async () => bool)` prima di uscire; - `page.signal`: da passare a `api()` (le richieste si annullano uscendo); `page.onEngine(fn)`, `page.onLibrary(fn)`, - `page.onLeave(fn)`. + `page.onLeave(fn)`. Una pagina lasciata mentre `mount` attendeva una risposta non registra più nulla: + `onEngine`/`onLibrary` non si iscrivono e `onLeave` esegue subito la funzione. Dopo un `await` controlla + `page.signal.aborted` prima di prendere risorse che durano (il browser, una vista remota, un timer). La striscia rossa di arresto (mockup 11) la mette la cornice su ogni pagina, da sola. 4. Pagine della seconda parte: `pages/activity.js` (`/attivita`, con `day-strip.js` per la striscia del giorno), `pages/settings.js` (`/impostazioni/{generali|limiti|collegamento|notifiche|dati|informazioni}`, un modulo diff --git a/src/Febe.Web/wwwroot/js/core/api.js b/src/Febe.Web/wwwroot/js/core/api.js index f98ca09..55480ac 100644 --- a/src/Febe.Web/wwwroot/js/core/api.js +++ b/src/Febe.Web/wwwroot/js/core/api.js @@ -53,15 +53,18 @@ function headers(extra) { /** * Calls the API and returns the JSON answer. Errors become ApiError with the message to show. - * options: method, body (object → JSON), signal, raw (returns the Response). + * options: method, body (object → JSON), signal, raw (returns the Response), keepalive (the request outlives the + * page: closing or reloading the tab). A keepalive fetch, unlike a beacon, keeps the Origin of the interface that the + * server checks on every command (spec §13.1; with «Referrer-Policy: no-referrer» a beacon would say «null»). */ export async function api(path, options = {}) { - const { method = 'GET', body, signal, raw = false } = options; + const { method = 'GET', body, signal, raw = false, keepalive = false } = options; let response; try { response = await fetch(path, { method, signal, + keepalive, credentials: 'same-origin', headers: headers(body !== undefined ? { 'Content-Type': 'application/json' } : {}), body: body !== undefined ? JSON.stringify(body) : undefined, diff --git a/src/Febe.Web/wwwroot/js/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js index 3aeb286..9866cae 100644 --- a/src/Febe.Web/wwwroot/js/core/shell.js +++ b/src/Febe.Web/wwwroot/js/core/shell.js @@ -25,6 +25,9 @@ let navLinks = {}; let statusBox; let current = null; let renderToken = 0; +// Address of the page drawn last (path and query) and whether the history guard is waiting for Alberto. +let shownUrl = ''; +let asking = false; /** Builds the sidebar and the page area inside root. */ export function buildShell(root) { @@ -60,11 +63,16 @@ function renderStatus(state) { const s = state.snapshot; const meter = s.profilesOpenedToday; const connection = state.connection; + const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : 'stato.collegato'); + // The own account is known only after the first sweep (a verification can come before it): no «@null». const who = connection.state === 'notConnected' ? h('div.chi', h('span.av.segnaposto', icon('user', 's')), h('div', h('b', t('stato.nessunAccount')), h('span', t('stato.daCollegare')))) - : h('div.chi', avatar(connection.username || ''), - h('div', h('b', `@${connection.username}`), h('span', t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : 'stato.collegato')))); + : connection.username + ? h('div.chi', avatar(connection.username), + h('div', h('b', `@${connection.username}`), h('span', linkState))) + : h('div.chi', h('span.av.segnaposto', icon('user', 's')), + h('div', h('b', linkState), h('span', t('stato.accountDaLeggere')))); const ratio = Math.max(0, Math.min(1, meter.ratio || 0)); fill(statusBox, h('div.riga', h(`span.spia${dotOf(s.mode) ? '.' + dotOf(s.mode) : ''}`, { 'aria-hidden': 'true' }), h('span', s.headline)), @@ -168,16 +176,29 @@ class PageFrame { /** Engine changes while the page is open. */ onEngine(fn) { + if (this.signal.aborted) return; this.cleanups.push(onEngine(fn)); } /** Library changes while the page is open. */ onLibrary(fn) { + if (this.signal.aborted) return; this.cleanups.push(onLibrary(fn)); } - /** Runs fn when the page is left. */ + /** + * Runs fn when the page is left. A page left while it was still loading (its mount went on after an await) runs it + * at once: nothing registered late may outlive the page. + */ onLeave(fn) { + if (this.signal.aborted) { + try { + fn(); + } catch (error) { + console.error(error); + } + return; + } this.cleanups.push(fn); } @@ -272,6 +293,8 @@ export function setQuery(params, { replace = true } = {}) { const target = url.pathname + url.search + url.hash; if (replace) history.replaceState(null, '', target); else history.pushState(null, '', target); + // The page already shows this address. + shownUrl = url.pathname + url.search; } /** Starts the router: link clicks, back and forward buttons. */ @@ -287,7 +310,30 @@ export function startRouter() { e.preventDefault(); navigate(url.pathname + url.search); }); - window.addEventListener('popstate', () => render()); + window.addEventListener('popstate', onHistory); + render(); +} + +/** + * Back and forward buttons: the address has already changed, so a page with unsaved changes is asked first (like a + * link) and, when Alberto stays, its address is put back. A change of the fragment alone (the skip link) is no new page. + */ +async function onHistory() { + if (location.pathname + location.search === shownUrl) return; + if (asking) return; + if (current) { + asking = true; + let leave; + try { + leave = await current.frame.mayLeave(); + } finally { + asking = false; + } + if (!leave) { + history.pushState(null, '', shownUrl); + return; + } + } render(); } @@ -295,6 +341,7 @@ async function render() { closeMenu(); const token = ++renderToken; const path = location.pathname; + shownUrl = path + location.search; const route = routes.find((r) => r.pattern.test(path)); if (route && route.redirect) { history.replaceState(null, '', withCarried(route.redirect)); diff --git a/src/Febe.Web/wwwroot/js/pages/account.js b/src/Febe.Web/wwwroot/js/pages/account.js index 36ae43b..8c25139 100644 --- a/src/Febe.Web/wwwroot/js/pages/account.js +++ b/src/Febe.Web/wwwroot/js/pages/account.js @@ -52,10 +52,12 @@ export default { page.back(t('scheda.indietro'), '/account'); const header = h('header.scheda-testa'); page.header(header, `@${detail.account.username}`); - drawHeader(header, detail, async () => { + // The menu of the header redraws it after every action, with the same reload each time. + const reload = async () => { detail = await api(`/api/accounts/${id}`, { signal: page.signal }); - drawHeader(header, detail); - }); + drawHeader(header, detail, reload); + }; + drawHeader(header, detail, reload); const base = `/account/${id}`; page.tabs(h('nav.linguette', { 'aria-label': `@${detail.account.username}` }, @@ -106,6 +108,10 @@ async function contentsTab(page, route, detail) { let kind = available.find((k) => k.key === route.query.get('tipo')) || available.find((k) => s[k.stat] > 0) || available[0]; let period = route.query.get('periodo') || ''; let mosaic = null; + // «In evidenza» is drawn by its own code: its listeners go when another chip is chosen. The token tells a view + // still loading that another one took its place. + let highlightCleanup = null; + let showToken = 0; const chips = h('div.filtri', { role: 'group', 'aria-label': t('scheda.linguette.contenuti') }); const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '150px' } }); const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona'))); @@ -184,13 +190,18 @@ async function contentsTab(page, route, detail) { selectButton.addEventListener('click', () => mosaic && setSelecting(!mosaic.selecting)); async function show() { + const token = ++showToken; drawTools(); if (mosaic) mosaic.destroy(); mosaic = null; + if (highlightCleanup) highlightCleanup(); + highlightCleanup = null; page.saveBar(null); page.body.scrollTop = 0; if (kind.key === 'evidenza') { - await showHighlights(host, detail, page); + const cleanup = await showHighlights(host, detail, page, () => token === showToken); + if (token === showToken) highlightCleanup = cleanup; + else if (cleanup) cleanup(); return; } const rowHeight = local.get('libreria.tessere', 160); @@ -220,6 +231,7 @@ async function contentsTab(page, route, detail) { page.onLeave(() => { onChange.cancel(); if (mosaic) mosaic.destroy(); + if (highlightCleanup) highlightCleanup(); }); await show(); } @@ -233,18 +245,22 @@ function storiesDayLabel(day, count, today) { return [capitalize(name), n]; } -/** «In evidenza»: the mosaic grouped under the titles of the collections (mockup 12). */ -async function showHighlights(host, detail, page) { +/** + * «In evidenza»: the mosaic grouped under the titles of the collections (mockup 12). current() is false once another + * chip took the place of this view (nothing is drawn then). Returns the function that removes its listeners, or null. + */ +async function showHighlights(host, detail, page, current) { const collections = detail.highlights.filter((c) => c.count > 0); if (!collections.length) { fill(host, h('div.vuoto-pagina', icon('star'), h('p', t('scheda.nessunContenuto')))); - return; + return null; } fill(host, h('div.caricamento', t('comune.caricamento'))); const ids = [...new Set(collections.flatMap((c) => c.entryIds))]; const tiles = new Map(); for (let i = 0; i < ids.length; i += 1000) { const page2 = await api(`/api/library/tiles?ids=${ids.slice(i, i + 1000).join(',')}`, { signal: page.signal }); + if (!current()) return null; for (const tile of page2.tiles) tiles.set(tile.id, tile); } const flat = []; @@ -272,9 +288,14 @@ async function showHighlights(host, detail, page) { const tile = flat.find((x) => x.id === Number(el.dataset.id)); if (tile) openViewer({ tile, source, origin: `@${detail.account.username}`, onDeleted: () => draw() }); }; - const observer = new ResizeObserver(later(draw, 150)); + const redraw = later(draw, 150); + const observer = new ResizeObserver(redraw); observer.observe(host); - page.onLeave(() => observer.disconnect()); + return () => { + observer.disconnect(); + redraw.cancel(); + host.onclick = null; + }; } // --------------------------------------------------------------------------------------------- settings diff --git a/src/Febe.Web/wwwroot/js/pages/activity.js b/src/Febe.Web/wwwroot/js/pages/activity.js index dff5235..bea5a24 100644 --- a/src/Febe.Web/wwwroot/js/pages/activity.js +++ b/src/Febe.Web/wwwroot/js/pages/activity.js @@ -57,6 +57,7 @@ export default { } } await loadSide(); + if (page.signal.aborted) return; page.onLibrary(() => loadSide()); const timer = setInterval(() => { if (latest && document.visibilityState === 'visible') loadSide(); diff --git a/src/Febe.Web/wwwroot/js/pages/browser.js b/src/Febe.Web/wwwroot/js/pages/browser.js index 70aefe7..79a11de 100644 --- a/src/Febe.Web/wwwroot/js/pages/browser.js +++ b/src/Febe.Web/wwwroot/js/pages/browser.js @@ -1,6 +1,7 @@ // Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the // server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the -// engine is still; «Ho finito» lets «Riprendi» become active after a verification. +// engine is still; «Ho finito» lets «Riprendi» become active after a verification. Leaving the page without «Ho finito» +// (another page, a reload, closing the tab) gives the browser back, like «Annulla». import { api } from '../core/api.js'; import { caps } from '../core/context.js'; @@ -8,7 +9,7 @@ import { h, icon, fill } from '../core/dom.js'; import { navigate } from '../core/shell.js'; import { t } from '../core/text.js'; import { toast } from '../core/ui.js'; -import { beginDriving, finishDriving, passwordNote, windowPanel } from './connection.js'; +import { drivingLease, finishDriving, passwordNote, windowPanel } from './connection.js'; import { remoteView } from './remote-view.js'; export default { @@ -21,11 +22,15 @@ export default { } catch { // the view says whether the browser answers } - beginDriving(false); + if (page.signal.aborted) return; + const lease = drivingLease(page); + lease.begin(false); const message = h('div', { 'aria-live': 'polite' }); const done = async () => { const result = await finishDriving(); if (!result) return; + // «Ho finito» gives the browser back on the server whatever the answer. + lease.settled(); toast(result.message, result.connected ? '' : 'errore'); if (result.connected) navigate('/attivita'); else fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message))); diff --git a/src/Febe.Web/wwwroot/js/pages/connection.js b/src/Febe.Web/wwwroot/js/pages/connection.js index 5df7973..3959399 100644 --- a/src/Febe.Web/wwwroot/js/pages/connection.js +++ b/src/Febe.Web/wwwroot/js/pages/connection.js @@ -7,7 +7,7 @@ import { api } from '../core/api.js'; import { caps } from '../core/context.js'; import { h, icon, fill } from '../core/dom.js'; -import { refreshEngine } from '../core/engine.js'; +import { engineState, refreshEngine } from '../core/engine.js'; import { navigate } from '../core/shell.js'; import { t } from '../core/text.js'; import { avatar, confirmDialog, label, showError, toast } from '../core/ui.js'; @@ -15,8 +15,19 @@ import { remoteView } from './remote-view.js'; const STATE_KIND = { notConnected: 'ambra', connected: 'verde', verificationRequired: 'rosso', browserUnavailable: '' }; +/** True while the engine waits for «Riprendi» (the stop strip of a verification or a disconnection). */ +function waitsForResume(state) { + const banner = state && state.snapshot && state.snapshot.banner; + return Boolean(banner && banner.needsResume); +} + +// The last «give the browser back» sent by a page that was left: the next «begin» waits for it, so that the server +// never sees the new page's begin before the old page's release. +let releasing = Promise.resolve(); + /** Starts using the browser (the engine is still); with openLogin the real login page is loaded. */ export async function beginDriving(openLogin) { + await releasing; try { await api('/api/connection/begin', { method: 'POST', body: { openLogin } }); return true; @@ -26,6 +37,39 @@ export async function beginDriving(openLogin) { } } +/** + * The browser as a page uses it (spec §4.1, §10.3: the engine is still only while Alberto uses the browser). begin() + * takes it; «Ho finito», «Annulla» and «Scollega» give it back on the server, and the page calls settled(). Leaving the + * page in any other way — another page, a reload, closing the tab — counts as «Annulla»: the browser goes back to the + * empty page and the engine may work again. + */ +export function drivingLease(page) { + let held = false; + const release = (keepalive) => { + if (!held) return; + held = false; + releasing = api('/api/connection/cancel', { method: 'POST', keepalive }).then(() => {}, () => {}); + }; + const onHide = () => release(true); + window.addEventListener('pagehide', onHide); + page.onLeave(() => { + window.removeEventListener('pagehide', onHide); + release(false); + }); + return { + /** Takes the browser (nothing when the page was already left). */ + begin(openLogin) { + if (page.signal.aborted) return Promise.resolve(false); + held = true; + return beginDriving(openLogin); + }, + /** The server already gave the browser back («Ho finito», «Annulla», «Scollega»). */ + settled() { + held = false; + }, + }; +} + /** The area that replaces the remote view on Windows: the browser is its own window. */ export function windowPanel() { return h('div.vista.vista-finestra', @@ -57,6 +101,18 @@ export async function mountConnection(page) { const right = h('div.collega-destra'); fill(page.body, h('div.pagina-collegamento', left, right)); const windows = caps().browserWindow; + const lease = drivingLease(page); + // The remote view drawn now (Docker): open, it keeps the engine still, so it closes as soon as it is not shown. + let view = null; + // «Ho finito» went well but the engine still waits for «Riprendi» (verification or disconnection); stopSeen: the + // engine was seen stopped since then, so the end of the stop is «Riprendi». + let waitingResume = false; + let stopSeen = false; + + function closeView() { + if (view) view.close(); + view = null; + } let status = await api('/api/connection', { signal: page.signal }); async function draw() { @@ -66,11 +122,39 @@ export async function mountConnection(page) { else drawLogin(); } + // After «Riprendi» (in the red strip of this page) the page shows the connection as it is now. It never takes the + // browser again by itself: still waiting for the verification, the panel stays. + page.onEngine((state) => { + if (!waitingResume) return; + if (waitsForResume(state)) { + stopSeen = true; + return; + } + if (!stopSeen) return; + waitingResume = false; + api('/api/connection', { signal: page.signal }).then((answer) => { + status = answer; + if (status.state !== 'verificationRequired') { + draw(); + return; + } + waitingResume = true; + stopSeen = false; + }).catch(showError); + }); + // ------------------------------------------------------------------------------------------- login or verification function drawLogin() { const verification = status.state === 'verificationRequired'; - beginDriving(!verification); - fill(left, windows ? windowPanel() : remoteView(page, { url: status.currentUrl, login: !verification }).element); + waitingResume = false; + closeView(); + lease.begin(!verification); + if (windows) { + fill(left, windowPanel()); + } else { + view = remoteView(page, { url: status.currentUrl, login: !verification }); + fill(left, view.element); + } const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi'); const message = h('div', { 'aria-live': 'polite' }); fill(right, @@ -93,6 +177,7 @@ export async function mountConnection(page) { async function cancel() { try { await api('/api/connection/cancel', { method: 'POST' }); + lease.settled(); } catch (error) { showError(error); } @@ -102,17 +187,39 @@ export async function mountConnection(page) { async function finish(message) { const result = await finishDriving(); if (!result) return; + // «Ho finito» gives the browser back on the server whatever the answer. + lease.settled(); if (result.connected) { toast(result.message); + closeView(); status = await api('/api/connection', { signal: page.signal }); - draw(); + // Still stopped for the verification: «Riprendi» is next, the browser is not taken again. + if (status.state === 'verificationRequired') drawFinished(result.message); + else draw(); } else { fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message))); } } + /** After «Ho finito» during a verification: what is left is «Riprendi»; the browser can be opened again. */ + function drawFinished(text) { + waitingResume = true; + stopSeen = waitsForResume(engineState()); + closeView(); + fill(left, h('div.vista.vista-finestra', h('div.vista-segnaposto', + icon('circle-check', 'l'), + h('h2', t('impostazioni.collegamento.finitoTitolo')), + h('p', text), + h('button.btn.riapri-browser', { type: 'button', onclick: () => drawLogin() }, icon('app-window', 's'), t('impostazioni.collegamento.riapri'))))); + fill(right, + passwordNote(windows), + h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio')))); + } + // ------------------------------------------------------------------------------------------- connected function drawConnected() { + waitingResume = false; + closeView(); fill(left, h('div.pannello.collegato', h('div.chi-collegato', avatar(status.username || '', 'g'), h('div', h('h2', t('impostazioni.collegamento.collegatoCome', { nome: status.username || '' })), status.displayName ? h('span.muto', status.displayName) : null)), @@ -152,6 +259,7 @@ export async function mountConnection(page) { if (choice !== 'yes') return; try { await api('/api/connection/disconnect', { method: 'POST' }); + lease.settled(); toast(t('impostazioni.collegamento.scollegato')); refreshEngine(); status = await api('/api/connection', { signal: page.signal }); @@ -163,6 +271,8 @@ export async function mountConnection(page) { // ------------------------------------------------------------------------------------------- unavailable function drawUnavailable() { + waitingResume = false; + closeView(); fill(left, h('div.vista.vista-finestra', h('div.vista-segnaposto', icon('octagon-alert', 'l'), h('h2', t('impostazioni.collegamento.nonDisponibileTitolo')), diff --git a/src/Febe.Web/wwwroot/js/pages/mosaic.js b/src/Febe.Web/wwwroot/js/pages/mosaic.js index 204f3cf..e0fe72e 100644 --- a/src/Febe.Web/wwwroot/js/pages/mosaic.js +++ b/src/Febe.Web/wwwroot/js/pages/mosaic.js @@ -119,7 +119,15 @@ export class Mosaic { this.onTotals = options.onTotals || (() => {}); this.onEmpty = options.onEmpty || (() => {}); this.dayLabel = options.dayLabel || defaultDayLabel; - this.signal = options.signal; + // Its own requests stop with the page and with destroy(): a mosaic replaced by a new filter never answers late + // over the new one (totals, empty state, sections). + this.controller = new AbortController(); + this.destroyed = false; + if (options.signal) { + if (options.signal.aborted) this.controller.abort(); + else options.signal.addEventListener('abort', () => this.controller.abort(), { once: true, signal: this.controller.signal }); + } + this.signal = this.controller.signal; this.sections = []; this.byDay = new Map(); this.selected = new Set(); @@ -139,6 +147,8 @@ export class Mosaic { } destroy() { + this.destroyed = true; + this.controller.abort(); this.near.disconnect(); this.far.disconnect(); this.resize.disconnect(); @@ -147,6 +157,7 @@ export class Mosaic { /** Loads the days of the filter and draws the groups that are visible. */ async start() { const data = await api(`/api/library/days?${this.query}`, { signal: this.signal }); + if (this.destroyed) return; this.today = data.today; this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today }); this.width = this.root.clientWidth || this.host.clientWidth || 800; @@ -221,6 +232,7 @@ export class Mosaic { const cursor = section.tiles.length ? cursorOf(section.tiles[section.tiles.length - 1]) : section.cursor; section.loading = api(`/api/library?${this.query}${this.query ? '&' : ''}cursor=${encodeURIComponent(cursor)}&limit=${limit}`, { signal: this.signal }) .then((page) => { + if (this.destroyed) return; const touched = new Set(); for (const tile of page.tiles) { const target = this.byDay.get(tile.day); @@ -447,7 +459,14 @@ export class Mosaic { */ async refresh() { const data = await api(`/api/library/days?${this.query}`, { signal: this.signal }); + if (this.destroyed) return; this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today }); + // The empty state of the page took the place of the mosaic: the first new entries bring it back. + if (data.days.length && !this.root.isConnected) { + this.pendingNew = 0; + this.pill.hidden = true; + fill(this.host, this.pill, this.root); + } const todayChanged = data.today !== this.today; this.today = data.today; const wanted = new Map(data.days.map((d) => [d.day, d])); diff --git a/src/Febe.Web/wwwroot/js/pages/remote-view.js b/src/Febe.Web/wwwroot/js/pages/remote-view.js index 64cda1d..8dcb2a4 100644 --- a/src/Febe.Web/wwwroot/js/pages/remote-view.js +++ b/src/Febe.Web/wwwroot/js/pages/remote-view.js @@ -9,10 +9,31 @@ import { t } from '../core/text.js'; import { label } from '../core/ui.js'; const BUTTONS = ['left', 'middle', 'right']; +const MAC = /Mac|iPhone|iPad/.test(navigator.platform || ''); -/** Modifier bits of the DevTools protocol: Alt 1, Ctrl 2, Meta 4, Shift 8. */ +function altGraph(e) { + return Boolean(e.getModifierState && e.getModifierState('AltGraph')); +} + +/** + * Modifier bits of the DevTools protocol: Alt 1, Ctrl 2, Meta 4, Shift 8. AltGr is not Ctrl+Alt (Windows reports it + * so): with AltGraph active those two bits are left out. + */ function modifiers(e) { - return (e.altKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.metaKey ? 4 : 0) | (e.shiftKey ? 8 : 0); + const graph = altGraph(e); + return (e.altKey && !graph ? 1 : 0) | (e.ctrlKey && !graph ? 2 : 0) | (e.metaKey ? 4 : 0) | (e.shiftKey ? 8 : 0); +} + +/** + * The character a key composes with AltGr (Windows, Linux: «@» is AltGr+ò on an Italian keyboard) or with Option on a + * Mac, else null. Those keys go as text: as Ctrl+Alt shortcuts the remote page would insert nothing. Alt alone on + * Windows and Linux stays a shortcut. + */ +function composed(e) { + if (e.key.length !== 1 || e.metaKey) return null; + if (altGraph(e)) return e.key; + if (MAC && e.altKey && !e.ctrlKey) return e.key; + return null; } /** @@ -128,32 +149,65 @@ export function remoteView(page, { url = null, login = false } = {}) { }; } const move = perFrame((e) => send({ type: 'mouse', action: 'move', ...point(e), button: 'left', deltaX: 0, deltaY: 0, clickCount: 0 })); + // Buttons pressed on the view: the server keeps them pressed until an «up», so every press gets its release, also + // when the button is let go outside the view (the pointer is captured) or the window loses the focus. + const pressed = new Map(); + let lastPoint = { x: 0.5, y: 0.5 }; canvas.addEventListener('mousemove', move); + canvas.addEventListener('pointerdown', (e) => { + try { + canvas.setPointerCapture(e.pointerId); + } catch { + // the pointer is already gone + } + }); canvas.addEventListener('mousedown', (e) => { canvas.focus(); e.preventDefault(); - send({ type: 'mouse', action: 'down', ...point(e), button: BUTTONS[e.button] || 'left', deltaX: 0, deltaY: 0, clickCount: e.detail || 1 }); + const button = BUTTONS[e.button] || 'left'; + lastPoint = point(e); + pressed.set(button, e.detail || 1); + send({ type: 'mouse', action: 'down', ...lastPoint, button, deltaX: 0, deltaY: 0, clickCount: e.detail || 1 }); }); canvas.addEventListener('mouseup', (e) => { e.preventDefault(); - send({ type: 'mouse', action: 'up', ...point(e), button: BUTTONS[e.button] || 'left', deltaX: 0, deltaY: 0, clickCount: e.detail || 1 }); + const button = BUTTONS[e.button] || 'left'; + lastPoint = point(e); + pressed.delete(button); + send({ type: 'mouse', action: 'up', ...lastPoint, button, deltaX: 0, deltaY: 0, clickCount: e.detail || 1 }); }); + const releaseAll = () => { + for (const [button, clickCount] of pressed) send({ type: 'mouse', action: 'up', ...lastPoint, button, deltaX: 0, deltaY: 0, clickCount }); + pressed.clear(); + }; + // The capture ends after the release, or earlier when the view goes away: what is still pressed is released then. + canvas.addEventListener('lostpointercapture', () => setTimeout(releaseAll, 0)); + window.addEventListener('blur', releaseAll); canvas.addEventListener('contextmenu', (e) => e.preventDefault()); canvas.addEventListener('wheel', (e) => { e.preventDefault(); const scale = e.deltaMode === 1 ? 40 : e.deltaMode === 2 ? 800 : 1; send({ type: 'mouse', action: 'wheel', ...point(e), button: 'left', deltaX: Math.round(e.deltaX * scale), deltaY: Math.round(e.deltaY * scale), clickCount: 0 }); }, { passive: false }); + // Keys that went as composed text: their release is not sent (no key went down on the remote page). + const asText = new Set(); canvas.addEventListener('keydown', (e) => { // Ctrl/Cmd+V goes through the paste event below (the clipboard is Alberto's, not the server's). - if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') return; + if ((e.ctrlKey || e.metaKey) && !altGraph(e) && e.key.toLowerCase() === 'v') return; e.preventDefault(); + const text = composed(e); + if (text) { + asText.add(e.code); + send({ type: 'key', action: 'char', key: text, code: '', text, modifiers: 0 }); + return; + } const printable = e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey; send({ type: 'key', action: 'down', key: e.key, code: e.code, text: printable ? e.key : '', modifiers: modifiers(e) }); }); canvas.addEventListener('keyup', (e) => { - if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') return; + if ((e.ctrlKey || e.metaKey) && !altGraph(e) && e.key.toLowerCase() === 'v') return; e.preventDefault(); + if (asText.delete(e.code)) return; send({ type: 'key', action: 'up', key: e.key, code: e.code, text: '', modifiers: modifiers(e) }); }); const onPaste = (e) => { @@ -167,6 +221,7 @@ export function remoteView(page, { url = null, login = false } = {}) { function close() { closed = true; document.removeEventListener('paste', onPaste); + window.removeEventListener('blur', releaseAll); if (socket) socket.close(); socket = null; } diff --git a/src/Febe.Web/wwwroot/js/pages/settings-limits.js b/src/Febe.Web/wwwroot/js/pages/settings-limits.js index d92e82c..c1a52fe 100644 --- a/src/Febe.Web/wwwroot/js/pages/settings-limits.js +++ b/src/Febe.Web/wwwroot/js/pages/settings-limits.js @@ -94,7 +94,13 @@ export default async function limits(page, box) { } // ------------------------------------------------------------------------------------------- window and days + // The ticks and the two handles stay the same elements: a handle being dragged holds the pointer capture, and + // replacing it would end the drag after the first step. Only the bands are drawn again. const windowBar = h('div.fascia-barra'); + const startHandle = handle('inizio'); + const endHandle = handle('fine'); + let bandEls = []; + windowBar.append(...[3, 6, 9, 12, 15, 18, 21].map((hour) => h('span.tacca', { style: { left: `${((hour * 60) / 1440) * 100}%` } })), startHandle, endHandle); // Text fields with 24-hour times (a time input would follow the browser's locale, possibly with AM/PM). const timeField = (id) => h('input.dati', { type: 'text', id, inputmode: 'numeric', maxlength: '5', placeholder: '07:30', autocomplete: 'off', spellcheck: 'false' }); const startInput = timeField('fascia-inizio'); @@ -139,10 +145,11 @@ export default async function limits(page, box) { if (end === 0) end = 1440; const bands = end > start ? [[start, end]] : [[start, 1440], [0, end]]; const pct = (m) => `${(m / 1440) * 100}%`; - fill(windowBar, - [3, 6, 9, 12, 15, 18, 21].map((hour) => h('span.tacca', { style: { left: pct(hour * 60) } })), - bands.map(([a, b]) => h('span.banda', { style: { left: pct(a), width: pct(b - a) } })), - handle('inizio', start), handle('fine', end % 1440 === 0 && end === 1440 ? 1440 : end)); + for (const band of bandEls) band.remove(); + bandEls = bands.map(([a, b]) => h('span.banda', { style: { left: pct(a), width: pct(b - a) } })); + startHandle.before(...bandEls); + startHandle.style.left = pct(start); + endHandle.style.left = pct(end); if (document.activeElement !== startInput) startInput.value = minutesOf(form.values.windowStart) == null ? form.values.windowStart : textOf(start); if (document.activeElement !== endInput) endInput.value = minutesOf(form.values.windowEnd) == null ? form.values.windowEnd : textOf(end); jitterInput.value = form.values.jitterMinutes; @@ -167,8 +174,8 @@ export default async function limits(page, box) { } /** A draggable handle of the window bar (15-minute steps); the time fields stay the precise way. */ - function handle(which, minutes) { - const el = h('span.maniglia', { style: { left: `${(minutes / 1440) * 100}%` }, 'aria-hidden': 'true' }); + function handle(which) { + const el = h('span.maniglia', { 'aria-hidden': 'true' }); el.addEventListener('pointerdown', (e) => { e.preventDefault(); el.setPointerCapture(e.pointerId); @@ -183,9 +190,11 @@ export default async function limits(page, box) { const up = () => { el.removeEventListener('pointermove', move); el.removeEventListener('pointerup', up); + el.removeEventListener('lostpointercapture', up); }; el.addEventListener('pointermove', move); el.addEventListener('pointerup', up); + el.addEventListener('lostpointercapture', up); }); return el; } diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index 22941b7..92945e4 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -24,6 +24,7 @@ "nessunAccount": "Nessun account", "verifica": "Verifica richiesta", "scollegato": "Sessione chiusa", + "accountDaLeggere": "Nome non ancora noto", "nonDisponibile": "Stato del motore non disponibile" }, "arresto": { @@ -704,7 +705,9 @@ "verificaTesto": "Completala a mano nella pagina qui accanto, poi premi «Ho finito» e infine «Riprendi».", "nonDisponibileTitolo": "Il browser di Febe non è disponibile", "nonDisponibileTesto": "Febe non ha avviato il suo browser, quindi per ora non ci si può collegare. Controlla il registro e riavvia Febe; se il problema resta, guarda la pagina dei problemi comuni nella guida.", - "fermoMentre": "Mentre usi il browser il motore resta fermo." + "fermoMentre": "Mentre usi il browser il motore resta fermo.", + "finitoTitolo": "Hai finito con il browser", + "riapri": "Riapri il browser" }, "notifiche": { "quando": "Quando avvisarti", diff --git a/tests/Febe.Tests/Alerts/AlertServiceTests.cs b/tests/Febe.Tests/Alerts/AlertServiceTests.cs index 40c8c1b..1128f8e 100644 --- a/tests/Febe.Tests/Alerts/AlertServiceTests.cs +++ b/tests/Febe.Tests/Alerts/AlertServiceTests.cs @@ -103,7 +103,7 @@ public sealed class AlertServiceTests Assert.AreEqual("Instagram ha chiesto di rallentare", banner.Title); var stop = bed.Telegram.Requests.Single().Text; StringAssert.StartsWith(stop, "Febe · Instagram ha chiesto di rallentare\n"); - StringAssert.Contains(stop, "mi fermo per 1 ora, fino alle 13:00"); + StringAssert.Contains(stop, "mi fermo per 1 ora: riparto verso le 13:00"); StringAssert.Contains(stop, "Non devi fare nulla: riparto da solo."); // After the hour the breaker reopens by itself: «…e ripresa». diff --git a/tests/Febe.Tests/Engine/EngineMonitorTests.cs b/tests/Febe.Tests/Engine/EngineMonitorTests.cs index a2ed6ac..15b0243 100644 --- a/tests/Febe.Tests/Engine/EngineMonitorTests.cs +++ b/tests/Febe.Tests/Engine/EngineMonitorTests.cs @@ -81,6 +81,17 @@ public sealed class EngineMonitorTests Assert.IsTrue(snapshot.Today.Spans.Any(s => s.Kind == StripSpanKind.Throttle)); StringAssert.StartsWith(snapshot.ProfilesOpenedToday.Note, "Fermo dalle "); StringAssert.Contains(snapshot.ReductionNote!, "Tetti dimezzati"); + + // Future engine times are always «verso le» (spec §10.4): the strip agrees with the status box. + var resumes = ItalianText.Around(bed.Breaker.State.Until!.Value, bed.Clock.Now, bed.Clock.LocalZone); + StringAssert.Contains(snapshot.Banner.Message, "riparto da solo " + resumes); + StringAssert.Contains(snapshot.SidebarLine, resumes); + StringAssert.Contains(snapshot.ReductionNote!, "verso l"); + foreach (var text in new[] { snapshot.Banner.Message, snapshot.ReductionNote! }) + { + Assert.DoesNotContain(" alle ", text); + Assert.DoesNotContain(" all'", text); + } } [TestMethod] diff --git a/tests/Febe.Tests/Web/AccountsApiTests.cs b/tests/Febe.Tests/Web/AccountsApiTests.cs index 4cafc69..26b3c51 100644 --- a/tests/Febe.Tests/Web/AccountsApiTests.cs +++ b/tests/Febe.Tests/Web/AccountsApiTests.cs @@ -136,6 +136,45 @@ public sealed class AccountsApiTests "in Docker (the default shell of the tests) folders are read-only"); } + [TestMethod] + public void FromDateIsTheLocalDayAndSurvivesARoundTrip() + { + // «Solo i nuovi da oggi» in Rome: local midnight of 13 October is 12 October 22:00 UTC. + var rome = TestZones.Rome; + var account = Account.Create("marta.demo", StartingPoint.OnlyNewFromToday, Make.T0, rome); + Assert.AreEqual(new DateTimeOffset(2026, 10, 12, 22, 0, 0, TimeSpan.Zero), account.Limits.FromDate); + + var form = Febe.Web.Api.AccountSettingsMapper.ToDto(account, rome); + Assert.AreEqual("2026-10-13", form.FromDate, "the form shows the day Alberto chose"); + var again = Febe.Web.Api.AccountSettingsMapper.Apply(account, form, rome, Make.T0, account.Folder); + Assert.AreEqual(account.Limits.FromDate, again.Limits.FromDate, "saving the form as it is changes nothing"); + } + + [TestMethod] + public async Task TheKeepUpdatedSwitchAndSavingDoNotMoveTheStartingDay() + { + await using var server = await WebTestServer.StartAsync(); + var account = await server.Db.Accounts.AddAsync(Account.Create("anna.demo", StartingPoint.OnlyNewFromToday, Make.T0, server.Clock.LocalZone)); + var from = account.Limits.FromDate; + Assert.IsNotNull(from); + + var detail = await server.GetJsonAsync($"/api/accounts/{account.Id}"); + Assert.AreEqual("2026-10-13", detail.GetProperty("settings").Str("fromDate")); + foreach (var value in new[] { false, true, false, true }) + { + var (status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/keep-updated", new { value }); + Assert.AreEqual(HttpStatusCode.OK, status); + } + + Assert.AreEqual(from, (await server.Db.Accounts.GetAsync(account.Id))!.Limits.FromDate, "«Tieni aggiornato» does not move «Da una data»"); + + var settings = JsonSerializer.Deserialize>((await server.GetJsonAsync($"/api/accounts/{account.Id}")).GetProperty("settings").GetRawText())!; + var (saveStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", settings); + Assert.AreEqual(HttpStatusCode.OK, saveStatus); + Assert.AreEqual("2026-10-13", saved.GetProperty("settings").Str("fromDate")); + Assert.AreEqual(from, (await server.Db.Accounts.GetAsync(account.Id))!.Limits.FromDate, "saving the settings as they are does not move it either"); + } + [TestMethod] public async Task AccountsAreAddedFromTheFollowedListOrByNameWithAStartingPoint() { diff --git a/tests/Febe.Tests/Web/InterfaceTests.cs b/tests/Febe.Tests/Web/InterfaceTests.cs new file mode 100644 index 0000000..5a6c268 --- /dev/null +++ b/tests/Febe.Tests/Web/InterfaceTests.cs @@ -0,0 +1,537 @@ +using System.Runtime.CompilerServices; +using System.Text.Json.Nodes; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; +using Febe.Tests.Server.Support; +using Febe.Tests.Support; +using Febe.Tests.Web.Part2Support; +using Febe.Tests.Web.Support; +using Febe.Web; +using Febe.Web.Connection; +using Febe.Web.Engine; +using Febe.Web.Library; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Tests.Web; + +/// +/// The interface itself in a real (headless) Chromium against a test server: what only shows when the scripts run. +/// The «driving» lease of the Browser and Collegamento pages (spec §4.1, §10.3: the engine is still only while Alberto +/// uses the browser), the remote view's keyboard and mouse, the mosaic and the account card when filters change, +/// the unsaved-changes guard on the browser's Back button, the window bar of Limiti, the sidebar status box. +/// +[TestClass] +[DoNotParallelize] +public sealed class InterfaceTests +{ + private static readonly ConnectionStatus Connected = new(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null); + + private static readonly ConnectionStatus Verification = new(ConnectionState.VerificationRequired, "tuo.profilo", "Il tuo profilo", false, "https://www.instagram.com/challenge/"); + + // ------------------------------------------------------------------------------------------ the driving lease + + [TestMethod] + public async Task LeavingTheBrowserPageWithoutHoFinitoGivesTheBrowserBack() + { + var connection = new RecordingConnection { Status = Connected }; + var view = new FakeRemoteViewHost(); + await using var server = await DockerAsync(connection, view); + await using var ui = await UiBrowser.StartAsync(); + + await ui.OpenAsync(new Uri(server.Address, "/browser")); + await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "il browser in uso con la vista aperta"); + + // Another page from the sidebar: the view closes and the lease of «begin» goes too (like «Annulla»). + await ui.EvalAsync("document.querySelector('a[data-nav=libreria]').click()"); + await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito lasciando la pagina"); + await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); + CollectionAssert.AreEqual(new[] { "begin:False", "cancel" }, connection.Snapshot()); + } + + [TestMethod] + public async Task ClosingOrReloadingTheTabGivesTheBrowserBack() + { + var connection = new RecordingConnection { Status = Connected }; + var view = new FakeRemoteViewHost(); + await using var server = await DockerAsync(connection, view); + await using var ui = await UiBrowser.StartAsync(); + + await ui.OpenAsync(new Uri(server.Address, "/browser")); + await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso"); + + // The document goes away (tab closed, reload, another site): only the page-hide event is left to say so. + await ui.SendAsync("Page.navigate", new JsonObject { ["url"] = "about:blank" }); + await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito chiudendo la scheda"); + } + + [TestMethod] + public async Task ABrowserPageLeftWhileLoadingNeverTakesTheBrowser() + { + var connection = new RecordingConnection { Status = Connected }; + var view = new FakeRemoteViewHost(); + await using var server = await DockerAsync(connection, view); + await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.OpenAsync(new Uri(server.Address, "/libreria")); + + // The status of the connection answers late; Alberto is already elsewhere. + await ui.EvalAsync(""" + import('/js/core/shell.js').then((m) => { + window.__delays.push({ match: '/api/connection', ms: 600 }); + m.navigate('/browser'); + setTimeout(() => m.navigate('/libreria'), 150); + return true; + }) + """); + await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + await ui.WaitAsync("window.__done['/api/connection'] >= 1", "risposta in ritardo arrivata"); + await Task.Delay(300); + Assert.IsEmpty(connection.Snapshot(), "nothing taken by a page that is gone"); + Assert.IsEmpty(view.Opened); + } + + [TestMethod] + public async Task AfterHoFinitoLeavingTheBrowserPageChangesNothingMore() + { + var connection = new RecordingConnection { Status = Connected }; + var view = new FakeRemoteViewHost(); + await using var server = await DockerAsync(connection, view); + await using var ui = await UiBrowser.StartAsync(); + + await ui.OpenAsync(new Uri(server.Address, "/browser")); + await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso"); + await ui.EvalAsync("document.querySelector('.salva .btn.primo').click()"); + await ui.WaitAsync("location.pathname === '/attivita'", "Attività dopo «Ho finito»"); + await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); + await ui.NavigateAsync("/libreria"); + await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + await Task.Delay(500); + CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "«Ho finito» already gave the browser back"); + } + + [TestMethod] + public async Task HoFinitoOnCollegamentoClosesTheRemoteView() + { + var connection = new RecordingConnection(); + var view = new FakeRemoteViewHost(); + await using var server = await DockerAsync(connection, view); + await using var ui = await UiBrowser.StartAsync(); + + await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento")); + await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:True") && view.Opened.Count == 1, "pagina di accesso nella vista remota"); + await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()"); + await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato"); + + // The view held the engine still for as long as the page stayed open (PROTOCOLLO.md: closing it frees it). + await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»"); + await ui.NavigateAsync("/libreria"); + await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + await Task.Delay(500); + CollectionAssert.AreEqual(new[] { "begin:True", "finish" }, connection.Snapshot()); + Assert.HasCount(1, view.Opened); + } + + [TestMethod] + public async Task HoFinitoDuringAVerificationDoesNotTakeTheBrowserAgain() + { + var connection = new RecordingConnection { Status = Verification, StatusAfterFinish = Verification }; + var view = new FakeRemoteViewHost(); + await using var server = await DockerAsync(connection, view, new FixedMonitor(EngineMode.StoppedForVerification)); + await using var ui = await UiBrowser.StartAsync(); + + await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento")); + await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "verifica nella vista remota"); + await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()"); + await ui.WaitAsync("document.querySelector('.riapri-browser') !== null", "«Ho finito» fatto, in attesa di «Riprendi»"); + await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»"); + await Task.Delay(500); + CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "no new lease after «Ho finito»"); + Assert.HasCount(1, view.Opened, "no new view after «Ho finito»"); + + // «Riapri il browser» takes it again; leaving the page then gives it back. + await ui.EvalAsync("document.querySelector('.riapri-browser').click()"); + await ui.WaitForAsync(() => connection.Snapshot().Length == 3 && view.Opened.Count == 2, "browser riaperto"); + await ui.NavigateAsync("/libreria"); + await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + await ui.WaitForAsync(() => connection.Snapshot().Length == 4, "il browser restituito lasciando la pagina"); + CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot()); + await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); + } + + [TestMethod] + public async Task AfterRiprendiCollegamentoShowsTheConnectionWithoutTakingTheBrowser() + { + var connection = new RecordingConnection { Status = Verification, StatusAfterFinish = Verification }; + var view = new FakeRemoteViewHost(); + var engine = new FixedMonitor(EngineMode.StoppedForVerification); + await using var server = await DockerAsync(connection, view, engine); + await using var ui = await UiBrowser.StartAsync(); + + await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento")); + await ui.WaitAsync("document.querySelector('.arresto') !== null", "striscia rossa della verifica"); + await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "verifica nella vista remota"); + await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()"); + await ui.WaitAsync("document.querySelector('.riapri-browser') !== null", "in attesa di «Riprendi»"); + + // «Riprendi»: the engine works again and the session is there. + engine.Mode = EngineMode.Resting; + connection.Status = Connected; + await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)"); + await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato dopo «Riprendi»"); + await Task.Delay(300); + CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot()); + Assert.IsTrue(view.Opened.All(v => v.Disposed)); + } + + // ------------------------------------------------------------------------------------------ remote view input + + [TestMethod] + public async Task AltGrCharactersReachTheRemotePageAsText() + { + var connection = new RecordingConnection { Status = Connected }; + var view = new FakeRemoteViewHost(); + await using var server = await DockerAsync(connection, view); + await using var ui = await UiBrowser.StartAsync(); + await ui.OpenAsync(new Uri(server.Address, "/browser")); + await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta"); + await ui.WaitAsync("document.querySelector('canvas.vista-schermo') !== null", "schermo della vista"); + await Task.Delay(300); + + // Italian layout on Windows: AltGr+ò is «@», reported as Ctrl+Alt with the AltGraph modifier. + Assert.IsTrue((await ui.EvalAsync("new KeyboardEvent('keydown', { key: '@', modifierAltGraph: true }).getModifierState('AltGraph')")).GetBoolean()); + await ui.EvalAsync(""" + (() => { + const c = document.querySelector('canvas.vista-schermo'); + const key = (type, init) => c.dispatchEvent(new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init })); + const altGr = { ctrlKey: true, altKey: true, modifierAltGraph: true }; + key('keydown', { key: '@', code: 'Semicolon', ...altGr }); + key('keyup', { key: '@', code: 'Semicolon', ...altGr }); + key('keydown', { key: 'a', code: 'KeyA' }); + key('keyup', { key: 'a', code: 'KeyA' }); + key('keydown', { key: 'f', code: 'KeyF', altKey: true }); + key('keyup', { key: 'f', code: 'KeyF', altKey: true }); + return true; + })() + """); + var connectionView = view.Opened.Single(); + await ui.WaitForAsync(() => Keys(connectionView).Any(k => k.Action == RemoteViewKeyAction.Up && k.Key == "f"), "tasti arrivati"); + var keys = Keys(connectionView); + Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Char, Text: "@", Modifiers: 0 }), "AltGr+ò types «@»: " + Describe(keys)); + Assert.IsFalse(keys.Any(k => k.Key == "@" && k.Action != RemoteViewKeyAction.Char), "no Ctrl+Alt shortcut for «@»: " + Describe(keys)); + Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Down, Key: "a", Text: "a", Modifiers: 0 }), "a plain key keeps its text"); + Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Down, Key: "f", Text: null, Modifiers: 1 }), "Alt+F on Windows stays a shortcut: " + Describe(keys)); + } + + [TestMethod] + public async Task ReleasingTheMouseOutsideTheViewReleasesTheRemoteButton() + { + var connection = new RecordingConnection { Status = Connected }; + var view = new FakeRemoteViewHost(); + await using var server = await DockerAsync(connection, view); + await using var ui = await UiBrowser.StartAsync(); + await ui.OpenAsync(new Uri(server.Address, "/browser")); + await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta"); + var remote = view.Opened.Single(); + await Task.Delay(300); + remote.Write(new RemoteViewMeta(320, 225, "https://www.instagram.com/")); + remote.Write(new RemoteViewFrame(TestFile.PhotoBytes(3, 320, 225))); + await ui.WaitAsync("!document.querySelector('canvas.vista-schermo').hidden", "primo fotogramma"); + + var (x, y, _, _) = await ui.BoxAsync("canvas.vista-schermo"); + await ui.MouseAsync("mouseMoved", x, y); + await ui.MouseAsync("mousePressed", x, y, buttons: 1); + await ui.MouseAsync("mouseMoved", x + 20, y + 10, buttons: 1); + await ui.MouseAsync("mouseMoved", 60, 60, buttons: 1); + await ui.MouseAsync("mouseReleased", 60, 60); + await ui.WaitForAsync(() => Mice(remote).Any(m => m.Action == RemoteViewMouseAction.Up), "pulsante rilasciato anche fuori dalla vista"); + Assert.AreEqual(RemoteViewButton.Left, Mice(remote).Single(m => m.Action == RemoteViewMouseAction.Up).Button); + } + + // ------------------------------------------------------------------------------------------ mosaic and account card + + [TestMethod] + public async Task AfterInEvidenzaTheOtherTabsStayTheirs() + { + await using var server = await WebTestServer.StartAsync(); + var account = await server.AddAccountWithEntriesAsync("marta.prova", 6, Make.T0, TimeSpan.FromHours(20)); + var stories = await server.Db.Entries.AddManyAsync([.. Enumerable.Range(0, 3).Select(i => new NewEntry( + Make.Entry(account.Id, $"storia-{i}", Make.T0 - TimeSpan.FromDays(3 + i), EntryKind.Story) with { State = EntryState.Downloaded }, + [Make.Stored(Make.Photo(), Make.Sha(9000 + i), $"storie/storia-{i}.jpg")]))]); + var summer = await server.Db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "h1", Title = "Estate", Position = 0, DiscoveredAt = Make.T0 }); + foreach (var story in stories) + { + await server.Db.Highlights.AddItemAsync(summer.Id, story.Stored.Entry.Id); + } + + await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}?tipo=evidenza")); + await ui.WaitAsync("document.querySelector('main .raccolta-titolo') !== null", "raccolte in evidenza"); + + // «Post» after «In evidenza»: the posts stay, also when the area changes size. + await ui.EvalAsync("document.querySelectorAll('.strumenti .filtri button')[0].click()"); + await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post"); + await Task.Delay(500); + await ui.SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject { ["width"] = 1100, ["height"] = 900, ["deviceScaleFactor"] = 1, ["mobile"] = false }); + await Task.Delay(600); + await AssertPostsShownAsync(ui); + + // «In evidenza» and at once «Post», while the tiles of the collections are still loading. + await ui.EvalAsync(""" + (() => { + window.__delays.push({ match: '/api/library/tiles', ms: 600 }); + const chips = document.querySelectorAll('.strumenti .filtri button'); + chips[2].click(); + chips[0].click(); + return true; + })() + """); + await ui.WaitAsync("window.__done['/api/library/tiles'] >= 1", "tessere delle raccolte arrivate in ritardo"); + await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post"); + await Task.Delay(400); + await AssertPostsShownAsync(ui); + } + + [TestMethod] + public async Task AStaleAnswerOfTheLibraryDoesNotHideTheNewFilter() + { + await using var server = await WebTestServer.StartAsync(); + await server.AddAccountWithEntriesAsync("anna.prova", 5, Make.T0, TimeSpan.FromHours(30)); + await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.OpenAsync(new Uri(server.Address, "/libreria")); + await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "mosaico"); + + // «Storie» (nothing: an empty answer, late) and at once «Foto». + await ui.EvalAsync(""" + (() => { + window.__delays.push({ match: 'kind=stories', ms: 700 }); + const chips = document.querySelectorAll('.strumenti .filtri button'); + chips[3].click(); + chips[1].click(); + return true; + })() + """); + await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "foto"); + await ui.WaitAsync("window.__done['kind=stories'] >= 1", "risposta delle storie arrivata in ritardo"); + await Task.Delay(300); + Assert.IsTrue((await ui.EvalAsync("location.search.includes('tipo=foto')")).GetBoolean()); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null")).GetBoolean(), "the photos are shown " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina') === null")).GetBoolean(), "no empty state over the results"); + StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.testa .quanti').textContent")).GetString(), "5 "); + } + + [TestMethod] + public async Task NewEntriesAppearAfterTheEmptyLibrary() + { + await using var server = await WebTestServer.StartAsync(); + await using var ui = await UiBrowser.StartAsync(); + await ui.OpenAsync(new Uri(server.Address, "/libreria")); + await ui.WaitAsync("document.querySelector('main .vuoto-pagina, main .benvenuto') !== null", "libreria vuota (primo avvio)"); + + var account = await server.AddAccountWithEntriesAsync("primo.prova", 4, Make.T0, TimeSpan.FromHours(10)); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + var shown = false; + while (!shown && DateTime.UtcNow < deadline) + { + server.Changes.Publish(new LibraryChange(server.Clock.Now, account.Id, "stored")); + await Task.Delay(700); + shown = (await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null")).GetBoolean(); + } + + Assert.IsTrue(shown, "the new entries appear at the top (spec §10.3) " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina, main .benvenuto') === null")).GetBoolean(), "the empty state goes away"); + await ui.WaitAsync("document.querySelector('main .mosaico .tess') !== null", "tessere disegnate"); + } + + [TestMethod] + public async Task TheAccountHeaderFollowsEveryMenuAction() + { + await using var server = await WebTestServer.StartAsync(); + var account = await server.AddAccountWithEntriesAsync("luca.prova", 2, Make.T0, TimeSpan.FromHours(10)); + await using var ui = await UiBrowser.StartAsync(); + await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}")); + await ui.WaitAsync("document.querySelector('.scheda-testa h1') !== null", "scheda"); + + foreach (var (choice, next) in new[] { ("Metti in pausa", "Riattiva"), ("Riattiva", "Metti in pausa"), ("Metti in pausa", "Riattiva") }) + { + await ui.EvalAsync("document.querySelector('.scheda-testa .azioni button[aria-haspopup]').click()"); + await ui.WaitAsync("document.querySelector('.menu') !== null", "menu"); + await ui.EvalAsync($$""" + (() => { + const item = [...document.querySelectorAll('.menu button')].find((b) => b.textContent.trim() === '{{choice}}'); + if (!item) throw new Error('voce mancante: {{choice}} in ' + document.querySelector('.menu').textContent); + item.click(); + return true; + })() + """); + // The header (and its menu) is drawn again with the new state of the account. + await ui.WaitAsync( + $$""" + (async () => { + document.querySelector('.scheda-testa .azioni button[aria-haspopup]').click(); + const menu = document.querySelector('.menu'); + const ok = Boolean(menu) && [...menu.querySelectorAll('button')].some((b) => b.textContent.trim() === '{{next}}'); + (await import('/js/core/ui.js')).closeMenu(); + return ok; + })() + """, + $"intestazione aggiornata dopo «{choice}»"); + await Task.Delay(200); + } + } + + // ------------------------------------------------------------------------------------------ shell + + [TestMethod] + public async Task TheBackButtonAsksBeforeLosingUnsavedChanges() + { + await using var server = await WebTestServer.StartAsync(); + await using var ui = await UiBrowser.StartAsync(); + await ui.OpenAsync(new Uri(server.Address, "/libreria")); + await ui.NavigateAsync("/impostazioni/limiti"); + await ui.WaitAsync("document.querySelector('.cerchio-giorno') !== null", "Limiti"); + await ui.EvalAsync("document.querySelector('.cerchio-giorno').click()"); + await ui.WaitAsync("!document.querySelector('.salva').hidden", "modifiche da salvare"); + + await ui.EvalAsync("history.back()"); + await ui.WaitAsync("document.querySelector('.dialogo') !== null", "«Modifiche non salvate» con il pulsante Indietro"); + await ui.EvalAsync("[...document.querySelectorAll('.dialogo footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync("document.querySelector('.dialogo') === null", "dialogo chiuso"); + Assert.AreEqual("/impostazioni/limiti", (await ui.EvalAsync("location.pathname")).GetString()); + Assert.IsTrue((await ui.EvalAsync("!document.querySelector('.salva').hidden && document.querySelector('.cerchio-giorno') !== null")).GetBoolean(), "the edits are still there"); + + await ui.EvalAsync("history.back()"); + await ui.WaitAsync("document.querySelector('.dialogo') !== null", "di nuovo il dialogo"); + await ui.EvalAsync("[...document.querySelectorAll('.dialogo footer button')].find((b) => b.textContent === 'Lascia le modifiche').click()"); + await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .vuoto-pagina, main .mosaico') !== null", "Libreria"); + } + + [TestMethod] + public async Task APageLeftWhileLoadingLeavesNothingBehind() + { + await using var server = await WebTestServer.StartAsync(); + await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.AddInitScriptAsync(""" + (() => { + const live = new Map(); + const set = window.setInterval.bind(window); + const clear = window.clearInterval.bind(window); + window.setInterval = (fn, ms, ...rest) => { const id = set(fn, ms, ...rest); live.set(id, ms); return id; }; + window.clearInterval = (id) => { live.delete(id); clear(id); }; + window.__intervals = (ms) => [...live.values()].filter((v) => v === ms).length; + })(); + """); + await ui.OpenAsync(new Uri(server.Address, "/libreria")); + await ui.EvalAsync(""" + import('/js/core/shell.js').then((m) => { + window.__delays.push({ match: '/api/alerts', ms: 600 }); + m.navigate('/attivita'); + setTimeout(() => m.navigate('/libreria'), 200); + return true; + }) + """); + await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + await ui.WaitAsync("window.__done['/api/alerts'] >= 1", "risposta in ritardo arrivata"); + await Task.Delay(300); + Assert.AreEqual(0, (await ui.EvalAsync("window.__intervals(60000)")).GetInt32(), "the minute timer of Attività is gone with its page"); + + // The page that stays open still works as usual. + await ui.NavigateAsync("/attivita"); + await ui.WaitAsync("window.__intervals(60000) === 1", "Attività aperta"); + await ui.NavigateAsync("/libreria"); + await ui.WaitAsync("window.__intervals(60000) === 0", "Attività lasciata"); + } + + [TestMethod] + public async Task TheWindowBarHandleFollowsTheWholeDrag() + { + await using var server = await WebTestServer.StartAsync(); + await using var ui = await UiBrowser.StartAsync(); + await ui.OpenAsync(new Uri(server.Address, "/impostazioni/limiti")); + await ui.WaitAsync("document.querySelector('.fascia-barra .maniglia') !== null", "barra della fascia"); + + var (barX, barY, barWidth, _) = await ui.BoxAsync(".fascia-barra"); + var handle = await ui.EvalAsync("(() => { const r = document.querySelector('.fascia-barra .maniglia').getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; })()"); + var (handleX, handleY) = (handle[0].GetDouble(), handle[1].GetDouble()); + var left = barX - (barWidth / 2); + await ui.MouseAsync("mouseMoved", handleX, handleY); + await ui.MouseAsync("mousePressed", handleX, handleY, buttons: 1); + var x = handleX; + foreach (var ratio in new[] { 0.30, 0.34, 0.38, 0.42, 0.46 }) + { + x = left + (barWidth * ratio); + await ui.MouseAsync("mouseMoved", x, barY, buttons: 1); + await Task.Delay(60); + } + + await ui.MouseAsync("mouseReleased", x, barY); + var minutes = (int)(Math.Round((x - left) / barWidth * 1440 / 15) * 15); + var expected = $"{minutes / 60:00}:{minutes % 60:00}"; + await ui.WaitAsync($"document.querySelector('#fascia-inizio').value === '{expected}'", $"inizio della fascia a {expected}"); + } + + [TestMethod] + public async Task TheStatusBoxDoesNotShowANameItDoesNotKnow() + { + var monitor = new FixedMonitor(EngineMode.StoppedForVerification); + await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton(monitor)); + await using var ui = await UiBrowser.StartAsync(); + await ui.OpenAsync(new Uri(server.Address, "/libreria")); + await ui.WaitAsync("document.querySelector('.stato .chi') !== null", "riquadro di stato"); + var text = (await ui.EvalAsync("document.querySelector('.stato .chi').textContent")).GetString()!; + Assert.DoesNotContain("@", text, "no handle before the first sweep learns it: " + text); + StringAssert.Contains(text, "Verifica richiesta"); + } + + // ------------------------------------------------------------------------------------------ helpers + + private static Task DockerAsync(RecordingConnection connection, FakeRemoteViewHost view, IEngineMonitor? engine = null) => + Part2.StartAsync(FebeEdition.Docker, s => + { + s.AddSingleton(connection); + s.AddSingleton(view); + if (engine is not null) + { + s.AddSingleton(engine); + } + }); + + private static List Keys(FakeRemoteViewConnection view) => [.. view.Inputs.OfType()]; + + private static List Mice(FakeRemoteViewConnection view) => [.. view.Inputs.OfType()]; + + private static string Describe(IEnumerable keys) => + string.Join(", ", keys.Select(k => $"{k.Action}:{k.Key}:{k.Text ?? "∅"}:{k.Modifiers}")); + + private static async Task AssertPostsShownAsync(UiBrowser ui) + { + Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .raccolta-titolo') === null")).GetBoolean(), "the collections are gone " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null")).GetBoolean(), "the posts are shown " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('.strumenti .filtri button[aria-pressed=true]').textContent.startsWith('Post')")).GetBoolean()); + } + + /// An engine in the mode the test sets; stopped for a verification it shows the red strip. + private sealed class FixedMonitor(EngineMode mode) : IEngineMonitor + { + public EngineMode Mode { get; set; } = mode; + + public Task GetSnapshotAsync(CancellationToken ct = default) + { + var snapshot = SnapshotParts.Build(new ManualClock(Make.T0), Mode, "Fermo", ["In attesa che tu completi la verifica"], "Serve il tuo intervento", CautionProfile.Prudent); + return Task.FromResult(Mode == EngineMode.StoppedForVerification + ? snapshot with { Banner = new StopBanner(BannerLevel.Error, "Instagram chiede una verifica", "Ho fermato tutto e non riparto da solo.", true) } + : snapshot); + } + + public async IAsyncEnumerable SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default) + { + await Task.Delay(Timeout.Infinite, ct); + yield break; + } + } +} diff --git a/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs b/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs index 2aa4ae3..b8b198d 100644 --- a/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs +++ b/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs @@ -68,36 +68,59 @@ internal sealed class FixedProblems(params ConfigurationProblem[] problems) : IC /// A connection service that records what the API asks. internal sealed class RecordingConnection : IConnectionService { + private readonly Lock _gate = new(); + public List Calls { get; } = []; public ConnectionStatus Status { get; set; } = new(ConnectionState.NotConnected, null, null, false, "https://www.instagram.com/accounts/login/"); + /// The status after «Ho finito» (connected by default; a verification still pending is the other case). + public ConnectionStatus StatusAfterFinish { get; set; } = new(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null); + + /// The calls so far, safe to read while the interface keeps sending. + public string[] Snapshot() + { + lock (_gate) + { + return [.. Calls]; + } + } + public Task GetStatusAsync(CancellationToken ct) => Task.FromResult(Status); public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) { - Calls.Add("begin:" + openLogin); + Record("begin:" + openLogin); Status = Status with { UserIsDriving = true }; return Task.CompletedTask; } public Task FinishAsync(CancellationToken ct) { - Calls.Add("finish"); - Status = new ConnectionStatus(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null); + Record("finish"); + Status = StatusAfterFinish; return Task.FromResult(new FinishResult(true, "Sei collegato come @tuo.profilo.")); } public Task CancelAsync(CancellationToken ct) { - Calls.Add("cancel"); + Record("cancel"); + Status = Status with { UserIsDriving = false }; return Task.CompletedTask; } public Task DisconnectAsync(CancellationToken ct) { - Calls.Add("disconnect"); + Record("disconnect"); Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null); return Task.CompletedTask; } + + private void Record(string call) + { + lock (_gate) + { + Calls.Add(call); + } + } } diff --git a/tests/Febe.Tests/Web/Support/UiBrowser.cs b/tests/Febe.Tests/Web/Support/UiBrowser.cs new file mode 100644 index 0000000..ac5db16 --- /dev/null +++ b/tests/Febe.Tests/Web/Support/UiBrowser.cs @@ -0,0 +1,409 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using Febe.Tests.Browser.TestSupport; + +namespace Febe.Tests.Web.Support; + +/// +/// A headless Chromium that drives Febe's own interface, like tools/schermate: only addresses on 127.0.0.1, never +/// Instagram (spec §2). It speaks the DevTools protocol directly, without the command policy of Febe's own client, +/// because here the tests click, type and run scripts in Febe's pages. Inconclusive when Chromium is missing. +/// +internal sealed class UiBrowser : IAsyncDisposable +{ + /// + /// Installed before the page scripts: window.__delays holds { match, ms } rules that hold back a matching + /// fetch, so that a test can make one answer arrive late (stale answers, slow pages); window.__done[match] + /// counts the held-back requests that are over (answered, failed or aborted). + /// + public const string FetchDelays = """ + (() => { + const original = window.fetch.bind(window); + window.__delays = []; + window.__done = {}; + window.fetch = async (input, init) => { + const url = typeof input === 'string' ? input : input.url; + const rule = window.__delays.find((d) => url.includes(d.match)); + if (!rule) return original(input, init); + try { + await new Promise((resolve) => setTimeout(resolve, rule.ms)); + return await original(input, init); + } finally { + // After the page's own continuation of this answer has run. + setTimeout(() => { window.__done[rule.match] = (window.__done[rule.match] || 0) + 1; }, 50); + } + }; + })(); + """; + + private readonly Process _process; + private readonly ClientWebSocket _socket; + private readonly string _profile; + private readonly ConcurrentDictionary> _pending = new(); + private readonly CancellationTokenSource _stop = new(); + private readonly SemaphoreSlim _send = new(1, 1); + private readonly Task _reader; + private int _id; + + private UiBrowser(Process process, ClientWebSocket socket, string profile) + { + _process = process; + _socket = socket; + _profile = profile; + _reader = Task.Run(ReadLoopAsync); + } + + /// Uncaught exceptions and console errors of the pages (shown when a test fails). + public ConcurrentQueue Problems { get; } = new(); + + public static async Task StartAsync(int width = 1280, int height = 900) + { + if (!OperatingSystem.IsLinux() || RealBrowser.ChromiumPath() is not { } chromium) + { + Assert.Inconclusive("Chromium non trovato (impostare FEBE_CHROMIUM): le prove dell'interfaccia nel browser non girano."); + throw new UnreachableException(); + } + + var profile = Path.Combine(Path.GetTempPath(), "febe-interfaccia-" + Guid.NewGuid().ToString("N")); + var port = LocalTestSite.FreePort(); + var info = new ProcessStartInfo(chromium) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in new[] + { + "--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", + "--disable-extensions", "--disable-background-networking", "--disable-component-update", "--no-proxy-server", + "--mute-audio", $"--window-size={width},{height}", $"--user-data-dir={profile}", + $"--remote-debugging-port={port}", "--remote-debugging-address=127.0.0.1", "about:blank", + }) + { + info.ArgumentList.Add(argument); + } + + if (RealBrowser.IsRoot) + { + info.ArgumentList.Add("--no-sandbox"); + } + + foreach (var (key, value) in RealBrowser.BrowserEnvironment) + { + if (value is null) + { + info.Environment.Remove(key); + } + else + { + info.Environment[key] = value; + } + } + + var process = Process.Start(info) ?? throw new InvalidOperationException("Chromium non parte."); + process.OutputDataReceived += (_, _) => { }; + process.ErrorDataReceived += (_, _) => { }; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + + try + { + using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(2) }; + string? debugger = null; + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(20); + while (debugger is null && DateTime.UtcNow < deadline) + { + try + { + using var list = JsonDocument.Parse(await http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list"))); + debugger = list.RootElement.EnumerateArray() + .Where(t => t.GetProperty("type").GetString() == "page") + .Select(t => t.GetProperty("webSocketDebuggerUrl").GetString()) + .FirstOrDefault(); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException) + { + // Chromium is still starting. + } + + if (debugger is null) + { + await Task.Delay(100); + } + } + + if (debugger is null) + { + throw new TimeoutException("Chromium non risponde sulla porta di debug."); + } + + var socket = new ClientWebSocket(); + socket.Options.Proxy = null; + await socket.ConnectAsync(new Uri(debugger), CancellationToken.None); + var browser = new UiBrowser(process, socket, profile); + await browser.SendAsync("Runtime.enable"); + await browser.SendAsync("Page.enable"); + await browser.SendAsync("Log.enable"); + return browser; + } + catch + { + Kill(process); + RealBrowser.TryDelete(profile); + throw; + } + } + + /// One command of the DevTools protocol; its result (an error of the protocol fails the test). + public async Task SendAsync(string method, JsonObject? parameters = null) + { + var id = Interlocked.Increment(ref _id); + var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pending[id] = answer; + var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters ?? new JsonObject() }; + await _send.WaitAsync(); + try + { + await _socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None); + } + finally + { + _send.Release(); + } + + return await answer.Task.WaitAsync(TimeSpan.FromSeconds(30)); + } + + /// Runs a script in the page (promises awaited) and returns its value; an exception fails the test. + public async Task EvalAsync(string expression) + { + var result = await SendAsync("Runtime.evaluate", new JsonObject + { + ["expression"] = expression, + ["awaitPromise"] = true, + ["returnByValue"] = true, + }); + if (result.TryGetProperty("exceptionDetails", out var details)) + { + var text = details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d) ? d.GetString() : details.GetProperty("text").GetString(); + throw new AssertFailedException($"Errore nella pagina: {text}\n{Report()}"); + } + + return result.GetProperty("result").TryGetProperty("value", out var value) ? value.Clone() : default; + } + + public async Task EvalAsync(string expression) => (await EvalAsync(expression)).Deserialize(WebTestServer.Json)!; + + /// + /// Polls until a condition of the page holds (an expression, or a promise of one; errors while the page changes + /// count as «not yet»). + /// + public async Task WaitAsync(string condition, string what, int milliseconds = 10_000) + { + var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(milliseconds); + string? last = null; + while (DateTime.UtcNow < deadline) + { + try + { + if ((await EvalAsync($"(async () => Boolean(await ({condition})))()")).ValueKind == JsonValueKind.True) + { + return; + } + } + catch (AssertFailedException ex) + { + last = ex.Message; + } + + await Task.Delay(50); + } + + Assert.Fail($"timeout: {what}{(last is null ? string.Empty : "\n" + last)}\n{Report()}"); + } + + /// Polls a condition of the test (the server side) while the page works. + public async Task WaitForAsync(Func condition, string what, int milliseconds = 10_000) + { + var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(milliseconds); + while (DateTime.UtcNow < deadline) + { + if (condition()) + { + return; + } + + await Task.Delay(50); + } + + Assert.Fail($"timeout: {what}\n{Report()}"); + } + + /// A script that runs in every new document before its own scripts. + public Task AddInitScriptAsync(string source) => + SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = source }); + + /// Loads an address of the interface and waits until the frame and the first page are drawn. + public async Task OpenAsync(Uri address) + { + await SendAsync("Page.navigate", new JsonObject { ["url"] = address.AbsoluteUri }); + await WaitAsync( + $"location.href.startsWith({JsonSerializer.Serialize(address.GetLeftPart(UriPartial.Authority))}) && document.readyState === 'complete' && !document.documentElement.hasAttribute('aria-busy') && document.querySelector('main.pagina .corpo') !== null", + $"apertura di {address}"); + } + + /// Goes to an internal address the way a link of the interface does (unsaved-changes guard included). + public Task NavigateAsync(string path) => + EvalAsync($"import('/js/core/shell.js').then((m) => {{ m.navigate({JsonSerializer.Serialize(path)}); return true; }})"); + + /// Centre of the first element matching the selector, in viewport pixels (scrolled into view first). + public async Task<(double X, double Y, double Width, double Height)> BoxAsync(string selector) + { + var box = await EvalAsync($$""" + (() => { + const el = document.querySelector({{JsonSerializer.Serialize(selector)}}); + if (!el) return null; + el.scrollIntoView({ block: 'center', inline: 'center' }); + const r = el.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2, width: r.width, height: r.height }; + })() + """); + Assert.AreEqual(JsonValueKind.Object, box.ValueKind, $"elemento non trovato: {selector}"); + return (box.GetProperty("x").GetDouble(), box.GetProperty("y").GetDouble(), box.GetProperty("width").GetDouble(), box.GetProperty("height").GetDouble()); + } + + /// A real mouse event (Input.dispatchMouseEvent): «mousePressed», «mouseMoved», «mouseReleased». + public Task MouseAsync(string type, double x, double y, int buttons = 0) => + SendAsync("Input.dispatchMouseEvent", new JsonObject + { + ["type"] = type, + ["x"] = x, + ["y"] = y, + ["button"] = type == "mouseMoved" && buttons == 0 ? "none" : "left", + ["buttons"] = buttons, + ["clickCount"] = type == "mouseMoved" ? 0 : 1, + }); + + /// What went wrong in the pages so far, for failure messages. + public string Report() => Problems.IsEmpty ? string.Empty : "Pagina: " + string.Join(" | ", Problems); + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)); + await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "fine", timeout.Token); + } + catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException) + { + } + + Kill(_process); + try + { + await _reader.WaitAsync(TimeSpan.FromSeconds(5)); + } + catch (Exception ex) when (ex is TimeoutException or WebSocketException or OperationCanceledException) + { + } + + _socket.Dispose(); + _process.Dispose(); + _stop.Dispose(); + _send.Dispose(); + RealBrowser.TryDelete(_profile); + } + + private static void Kill(Process process) + { + try + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + process.WaitForExit(5000); + } + } + catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception) + { + } + } + + private async Task ReadLoopAsync() + { + var buffer = new byte[64 * 1024]; + using var message = new MemoryStream(); + try + { + while (!_stop.IsCancellationRequested && _socket.State == WebSocketState.Open) + { + message.SetLength(0); + WebSocketReceiveResult result; + do + { + result = await _socket.ReceiveAsync(buffer, _stop.Token); + if (result.MessageType == WebSocketMessageType.Close) + { + return; + } + + message.Write(buffer, 0, result.Count); + } + while (!result.EndOfMessage); + + Dispatch(message.ToArray()); + } + } + catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException) + { + } + finally + { + foreach (var pending in _pending.Values) + { + pending.TrySetException(new InvalidOperationException("Chromium si è chiuso.")); + } + } + } + + private void Dispatch(byte[] data) + { + using var document = JsonDocument.Parse(data); + var root = document.RootElement; + if (root.TryGetProperty("id", out var idElement) && _pending.TryRemove(idElement.GetInt32(), out var answer)) + { + if (root.TryGetProperty("error", out var error)) + { + answer.TrySetException(new InvalidOperationException("DevTools: " + error.GetRawText())); + } + else + { + answer.TrySetResult(root.GetProperty("result").Clone()); + } + + return; + } + + if (!root.TryGetProperty("method", out var method)) + { + return; + } + + var parameters = root.GetProperty("params"); + switch (method.GetString()) + { + case "Runtime.exceptionThrown": + var details = parameters.GetProperty("exceptionDetails"); + Problems.Enqueue("eccezione: " + (details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d) ? d.GetString() : details.GetProperty("text").GetString())); + break; + case "Runtime.consoleAPICalled" when parameters.GetProperty("type").GetString() == "error": + Problems.Enqueue("console: " + string.Join(' ', parameters.GetProperty("args").EnumerateArray().Select(a => a.TryGetProperty("value", out var v) ? v.ToString() : a.TryGetProperty("description", out var s) ? s.GetString() : "?"))); + break; + } + } +}