Files
Febe/src/Febe.Web/wwwroot/js/core/shell.js
T
Alby96andClaude Opus 5.5 c49df4ca7b Browser mai bianco né muto: pagina iniziale, finestra che resta, fotogrammi che ripartono (#52)
Il browser di Febe a volte era bianco o non mostrava nulla. Le cause erano
diverse e si correggono insieme.

- Pagina iniziale. Se il browser è a riposo su about:blank e Alberto lo apre
  («Usa il browser», «Apri il browser»), Febe lo porta sulla home del sito
  quando è collegato, altrimenti sulla pagina di accesso. È un'azione di
  Alberto, sotto il suo permesso di guida, non del motore: Febe aspetta che
  la sessione finisca e prende il turno della pagina.
  Il nuovo pulsante «Pagina iniziale» sta nella barra della finestra di
  Windows e nella vista remota. Su about:blank la barra dice «Il browser è a
  riposo su una pagina vuota». «Indietro» non torna più sulla pagina di
  riposo.
- Disconnessione. «Apri il browser» nella striscia rossa apre la pagina di
  accesso. Con --accesso-di-prova il primo controllo all'avvio non segnala
  più una disconnessione finta.
- Windows: la finestra resta.
  - Lasciare una pagina di Febe non nasconde più la finestra «Browser di
    Febe» e non la rimette a riposo: finisce solo il permesso tenuto dalla
    pagina (cancel con pageLeft, IConnectionService.ReleaseAsync).
  - Sullo schermo la finestra ha il suo pulsante nella barra delle
    applicazioni, così ridurla a icona non la fa sparire. Dopo 2 minuti
    ridotta a icona torna fuori vista (S2).
  - Se lo schermo è troppo piccolo, la finestra si restringe all'area di
    lavoro e la pagina si rimpicciolisce con ZoomFactor, con le stesse misure
    CSS.
  - I bordi della pagina si riapplicano, con NotifyParentWindowPositionChanged,
    quando la finestra si mostra, si sposta o riparte il processo GPU.
  - Una pagina che non risponde mentre Alberto guida resta com'è.
  - IBrowserWindow.ShowAsync lascia il posto a
    IConnectionService.ShowBrowserAsync.
- Docker: fotogrammi che ripartono. La vista remota ha un watchdog. Riavvia
  i fotogrammi dopo una pagina nuova caricata senza fotogrammi e dopo circa
  2 s di silenzio. L'attesa raddoppia fino a 30 s finché la pagina resta
  ferma. Se il riavvio non porta nulla, la vista riceve un'immagine ferma
  (Page.captureScreenshot, già fra i comandi ammessi).
  RemoteViewSession ha ora un registro vero: avvii, riavvii e silenzi vanno
  a livello Info, categoria «vista», senza indirizzi.
  Se dopo 8 s non arriva nessuna immagine, l'interfaccia mostra «Nessuna
  immagine dal browser» con «Riprova».

Nessun comando CDP nuovo e nessuna dipendenza nuova. Aggiornati PROTOCOLLO.md
e la guida (Primo collegamento, Attività e arresti, Installazione Windows,
Problemi comuni).

Prove nuove:
- ScreencastWatchdogTests, RemoteViewFramesTests (Chromium vero, solo CI
  Linux)
- Home e Indietro in RemoteViewStartTests
- RemoteViewSocketTests
- ConnectionApiTests
- BrowserStartPageTests
- BrowserWindowDecisionTests e BrowserWindowTests (WebView2 vero)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:51:12 +01:00

389 lines
14 KiB
JavaScript

// The frame of every page (spec §10.2): fixed 228 px sidebar with brand, Libreria, Account, Attività, Importa,
// separator, Impostazioni, and the status box always visible at the bottom; on the right the page: title row,
// optional tools row, scrolling content, fixed bar for the actions that save. The red strip (mockup 11) appears under
// the title of every page while the engine is stopped and needs Alberto. Also the router of the addresses.
import { api, withCarried } from './api.js';
import { caps } from './context.js';
import { h, icon, brand, fill } from './dom.js';
import { dotOf, onEngine, onLibrary, refreshEngine, engineState } from './engine.js';
import { t } from './text.js';
import { avatar, showError, toast, closeMenu } from './ui.js';
import { routes } from '../routes.js';
const NAV = [
{ key: 'libreria', href: '/libreria', icon: 'layout-grid' },
{ key: 'account', href: '/account', icon: 'users' },
{ key: 'attivita', href: '/attivita', icon: 'activity' },
{ key: 'importa', href: '/importa', icon: 'folder-input' },
'stacco',
{ key: 'impostazioni', href: '/impostazioni', icon: 'settings' },
];
let main;
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) {
const links = NAV.map((item) => {
if (item === 'stacco') return h('div.stacco', { role: 'separator' });
const a = h('a', { href: withCarried(item.href), dataset: { nav: item.key } }, icon(item.icon), h('span', t(`nav.${item.key}`)));
navLinks[item.key] = a;
return a;
});
statusBox = h('a.stato', { href: withCarried('/attivita'), 'aria-label': t('stato.riquadro') });
main = h('main.pagina', { id: 'contenuto', tabindex: '-1' });
fill(root,
h('a.salta', { href: '#contenuto' }, t('app.salta')),
h('div.app',
h('aside.barra',
h('a.marchio', { href: withCarried('/libreria') }, brand(), h('b', t('app.nome'))),
h('nav.nav', { 'aria-label': t('nav.principale') }, links),
h('div.molla'),
statusBox),
main));
onEngine(renderStatus);
renderStatus(null);
}
// ------------------------------------------------------------------------------------------------- status box
function renderStatus(state) {
if (!statusBox) return;
if (!state) {
fill(statusBox, h('div.riga', h('span.spia'), h('span', t('comune.caricamento'))));
return;
}
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'))))
: 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)),
h('div.sotto', s.sidebarLine),
h(`div.misura${meter.amber ? '.ambra' : ''}`, { role: 'meter', 'aria-valuemin': '0', 'aria-valuemax': String(meter.limitToday), 'aria-valuenow': String(meter.usedToday), 'aria-label': t('stato.profiliOggi') },
h('i', { style: { width: `${ratio * 100}%` } })),
h('div.conto', h('span', t('stato.profiliOggi')), h('span', `${meter.usedText} ${meter.limitText}`)),
who);
statusBox.title = s.details && s.details.length ? s.details.join(' ') : s.headline;
const attention = navLinks.attivita;
if (attention) {
const dot = attention.querySelector('.punto');
if (s.banner && !dot) attention.append(h('span.punto', { role: 'img', 'aria-label': t('nav.fermo') }));
if (!s.banner && dot) dot.remove();
}
}
// ------------------------------------------------------------------------------------------------- page frame
/** What a page module receives to draw itself (see LEGGIMI.md). */
class PageFrame {
constructor(route) {
this.route = route;
this.controller = new AbortController();
this.cleanups = [];
this.guards = [];
this.backSlot = h('div', { hidden: true });
this.head = h('header.testa');
this.bannerSlot = h('div', { hidden: true });
this.tabsSlot = h('div', { hidden: true });
this.toolsSlot = h('div.strumenti', { hidden: true });
this.body = h('div.corpo');
this.saveSlot = h('div.salva', { hidden: true });
this.root = h('div', { style: { display: 'contents' } }, this.backSlot, this.head, this.bannerSlot, this.tabsSlot, this.toolsSlot, this.body, this.saveSlot);
}
/** Aborted when the page is left: pass it to fetch calls. */
get signal() {
return this.controller.signal;
}
/** Title row: «Libreria» with «48.212 elementi di 38 account» beside it. */
title(text, count = null) {
this.titleText = text;
document.title = t('app.titoloPagina', { pagina: text });
const h1 = h('h1', text);
this.countEl = count == null ? null : h('span.quanti', count);
this.actionsEl = h('div.destra');
fill(this.head, h1, this.countEl, this.actionsEl);
this.head.hidden = false;
return this;
}
/** Updates the text beside the title. */
count(text) {
if (this.countEl) this.countEl.textContent = text;
return this;
}
/** Buttons and fields at the right of the title row. */
actions(...nodes) {
if (!this.actionsEl) this.title(this.titleText || '');
fill(this.actionsEl, ...nodes);
return this;
}
/** Replaces the whole title row with a custom header (the account card); keeps the document title. */
header(node, documentTitle) {
if (documentTitle) document.title = t('app.titoloPagina', { pagina: documentTitle });
this.head.replaceWith(node);
this.head = node;
return this;
}
/** «← Account» above the title. */
back(text, href) {
this.backSlot.replaceWith(this.backSlot = h('a.indietro', { href: withCarried(href) }, icon('arrow-left', 's'), text));
return this;
}
/** A row of tabs (.linguette) under the header. */
tabs(node) {
this.tabsSlot.replaceWith(node);
this.tabsSlot = node;
return this;
}
/** The tools row (filters, menus); null hides it. */
tools(node) {
fill(this.toolsSlot, node);
this.toolsSlot.hidden = !node;
return this;
}
/** The fixed bar at the bottom (save, selection); null hides it. */
saveBar(node) {
fill(this.saveSlot, node);
this.saveSlot.hidden = !node;
return this;
}
/** 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. 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);
}
/** guard() → Promise<boolean>: asked before leaving (unsaved changes). */
guard(fn) {
this.guards.push(fn);
}
async mayLeave() {
for (const g of this.guards) {
if (!(await g())) return false;
}
return true;
}
destroy() {
this.controller.abort();
for (const fn of this.cleanups) {
try {
fn();
} catch (error) {
console.error(error);
}
}
}
}
function renderBanner(frame, state) {
const banner = state && state.snapshot.banner;
if (!banner) {
frame.bannerSlot.hidden = true;
frame.bannerSlot.replaceChildren();
return;
}
const isError = banner.level === 'Error';
const resume = h('button.btn.riprendi-arresto', {
type: 'button',
disabled: !state.canResume,
title: state.canResume ? null : t('arresto.riprendiSpento'),
onclick: async () => {
try {
const result = await api('/api/engine/resume', { method: 'POST' });
toast(result.message);
refreshEngine();
} catch (error) {
showError(error);
}
},
}, icon('rotate-cw'), t('arresto.riprendi'));
// After a disconnection the browser opens on the login page (issue #52); after a verification it stays as it is.
const disconnected = Boolean(state.connection && state.connection.state === 'disconnected');
const open = h('button.btn.primo', { type: 'button', onclick: () => openBrowser({ login: disconnected }) }, icon('app-window'), t('arresto.apriBrowser'));
const box = h(`div.arresto${isError ? '' : '.ambra'}`, { role: 'alert' },
icon(isError ? 'octagon-alert' : 'triangle-alert', 'l'),
h('div.testo', h('b', banner.title), h('span', banner.message)),
h('div.azioni', banner.needsResume ? resume : null, isError ? open : null));
frame.bannerSlot.hidden = false;
fill(frame.bannerSlot, box);
}
/**
* «Apri il browser»: on Windows the window comes to the front; in Docker the Browser page with the remote view. A
* browser at rest opens its start page; with login (the red strip of a disconnection) the login page.
*/
export async function openBrowser({ login = false } = {}) {
const openLogin = login === true;
if (caps().browserWindow) {
try {
const result = await api('/api/browser/show', { method: 'POST', body: { openLogin } });
toast(result.message);
refreshEngine();
} catch (error) {
showError(error);
}
} else {
navigate(openLogin ? '/browser?accesso=1' : '/browser');
}
}
// ------------------------------------------------------------------------------------------------- router
/** Goes to an internal address (carried demo parameters kept). */
export async function navigate(path, { replace = false } = {}) {
if (current && !(await current.frame.mayLeave())) return;
const target = withCarried(path);
if (replace) history.replaceState(null, '', target);
else history.pushState(null, '', target);
await render();
}
/** Changes the query of the current address without reloading the page (filters, tabs). */
export function setQuery(params, { replace = true } = {}) {
const url = new URL(location.href);
for (const [key, value] of Object.entries(params)) {
if (value == null || value === '') url.searchParams.delete(key);
else url.searchParams.set(key, value);
}
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. */
export function startRouter() {
document.addEventListener('click', (e) => {
const a = e.target.closest && e.target.closest('a[href]');
if (!a || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
if (a.target && a.target !== '_self') return;
if (a.hasAttribute('download')) return;
const url = new URL(a.href, location.href);
if (url.origin !== location.origin || url.pathname.startsWith('/api/') || /\.\w+$/.test(url.pathname)) return;
if (a.getAttribute('href').startsWith('#')) return;
e.preventDefault();
navigate(url.pathname + url.search);
});
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();
}
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));
return render();
}
if (current) {
current.frame.destroy();
current = null;
}
for (const [key, link] of Object.entries(navLinks)) {
const here = route && route.nav === key;
link.classList.toggle('qui', here);
if (here) link.setAttribute('aria-current', 'page');
else link.removeAttribute('aria-current');
}
const match = route ? path.match(route.pattern) : null;
const params = { ...(route && route.data), ...(match && match.groups) };
const query = new URLSearchParams(location.search);
const frame = new PageFrame({ path, params, query });
fill(main, frame.root);
current = { frame };
frame.onEngine((state) => renderBanner(frame, state));
try {
const module = route ? await route.page() : await import('../pages/placeholder.js');
if (token !== renderToken) return;
const page = module.default;
const cleanup = await page.mount(frame, route ? { path, params, query } : { path, params: { key: 'nonTrovata' }, query });
if (typeof cleanup === 'function') frame.onLeave(cleanup);
} catch (error) {
if (error && error.name === 'AbortError') return;
console.error(error);
frame.title(t('comune.erroreTitolo'));
fill(frame.body, h('div.vuoto-pagina', icon('octagon-alert'), h('p', error && error.message ? error.message : t('comune.errore'))));
}
}
/** The engine state now (for pages that need it once). */
export { engineState };