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)
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
27 files changed
+1365
-59
No files matched your search
@@ -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
|
||||
/// <summary>Largest «Storico, massimo al giorno» the form accepts: twice the «Rapido» value (spec §7.5).</summary>
|
||||
public static int MaxBackfillPerDay => CautionProfile.Fast.BackfillPostsPerAccountPerDay * 2;
|
||||
|
||||
public static AccountSettingsDto ToDto(Account account)
|
||||
/// <summary>The form of an account.</summary>
|
||||
/// <param name="account">The stored account.</param>
|
||||
/// <param name="zone">
|
||||
/// Alberto's zone: «Da una data» is stored as the first instant of a local day (<see cref="LocalCalendar.StartOfDay"/>),
|
||||
/// so it is shown as that local day, which <see cref="Apply"/> turns back into the same instant.
|
||||
/// </param>
|
||||
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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)));
|
||||
|
||||
@@ -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')),
|
||||
|
||||
@@ -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]));
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user