Interfaccia web, parte 1: ospite, sicurezza, API, modalità dimostrativa, libreria, visualizzatore e account

Febe.Web: AddFebeWeb/UseFebe/FebeWebHost per le due vesti, interfaccia incorporata con IFileProvider proprio, indirizzi italiani, API JSON con contesto generato, eventi SSE, controlli di Host/Origin, gettone del desktop e password con blocco (§13.1), INativeShell e capacità per veste. Modalità --demo con 38 account e circa 18.000 elementi finti e scene del motore. Pagine Libreria, Visualizzatore, Account, Aggiungi account e Scheda account (contenuti, impostazioni con piano, cronologia); schermate in docs/schermate con le differenze dai mockup; prove delle API, della sicurezza, dell'esportazione CSV e dei dati dimostrativi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 19:14:35 +00:00
1 parent 6ff11ac8e3
commit e33540246e
76 files changed
+12503 -17

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
// Calls to the API of Febe. In the demo the scene (scena) and the imitated shell (veste) chosen in the address are
// carried on every call and on every internal link, so that the whole interface stays in the chosen scene.
import { t } from './text.js';
/** Query parameters that travel with every page and call (demo and screenshots). */
export const CARRIED = ['scena', 'veste', 'tema'];
const carried = {};
/** Reads the carried parameters from the address (and from the previous pages of this tab). */
export function initCarried() {
const query = new URLSearchParams(location.search);
for (const key of CARRIED) {
let value = query.get(key);
try {
if (value) sessionStorage.setItem(`febe.${key}`, value);
else value = sessionStorage.getItem(`febe.${key}`);
} catch {
// no session storage: the address is the only source
}
if (value) carried[key] = value;
}
}
export function carriedValue(key) {
return carried[key];
}
/** Adds the carried parameters to an internal address. */
export function withCarried(url) {
const u = new URL(url, location.origin);
for (const [key, value] of Object.entries(carried)) {
if (!u.searchParams.has(key)) u.searchParams.set(key, value);
}
return u.pathname + u.search + u.hash;
}
/** An API error with the Italian message given by the server. */
export class ApiError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
function headers(extra) {
const h = { Accept: 'application/json', ...extra };
if (carried.scena) h['X-Febe-Scena'] = carried.scena;
if (carried.veste) h['X-Febe-Veste'] = carried.veste;
return h;
}
/**
* 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).
*/
export async function api(path, options = {}) {
const { method = 'GET', body, signal, raw = false } = options;
let response;
try {
response = await fetch(path, {
method,
signal,
credentials: 'same-origin',
headers: headers(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
body: body !== undefined ? JSON.stringify(body) : undefined,
});
} catch (error) {
if (error.name === 'AbortError') throw error;
throw new ApiError(0, t('comune.errore'));
}
if (response.status === 401 && access === 'password') {
// Password mode: the session ended; go back to the login page.
location.href = `/accesso?torna=${encodeURIComponent(location.pathname)}`;
}
if (!response.ok) {
let message = t('comune.errore');
try {
const data = await response.json();
if (data && data.message) message = data.message;
} catch {
// not JSON
}
throw new ApiError(response.status, message);
}
if (raw) return response;
if (response.status === 204) return null;
return response.json();
}
let access;
/** Remembers the access mode from the capabilities (password, token, none). */
export function setAccess(mode) {
access = mode;
}
/** The address of the event stream, with the carried parameters (EventSource cannot send headers). */
export function eventsUrl() {
return withCarried('/api/eventi');
}
/** Downloads an answer as a file (CSV export). */
export async function download(path, body, fallbackName) {
const response = await api(path, { method: 'POST', body, raw: true });
const blob = await response.blob();
const disposition = response.headers.get('Content-Disposition') || '';
const match = /filename="?([^";]+)"?/.exec(disposition);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = match ? match[1] : fallbackName;
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 10000);
}
+39
View File
@@ -0,0 +1,39 @@
// What the shell can do (GET /api/capabilities): Docker or desktop, demo, native functions. Pages read it to show
// «Mostra nella cartella» or «Scarica», read-only folders in Docker, the Windows-only «Avvio» block.
let capabilities = {
edition: 'docker',
demo: false,
access: 'none',
showInFolder: false,
pickFolder: false,
openUrlNative: false,
foldersReadOnly: true,
autostart: false,
browserWindow: false,
notifications: false,
version: '',
scene: null,
scenes: [],
now: Date.now(),
today: '',
};
let skew = 0;
export function setCapabilities(value) {
if (value) capabilities = { ...capabilities, ...value };
if (value && value.now) skew = value.now - Date.now();
}
/** The server's clock now (milliseconds), for «8 min fa». */
export function serverNow() {
return Date.now() + skew;
}
/** The capabilities of this shell (see CapabilitiesDto). */
export function caps() {
return capabilities;
}
export const isDesktop = () => capabilities.edition === 'desktop';
+126
View File
@@ -0,0 +1,126 @@
// Small DOM helpers: no framework, no build. Text is always set as text (never as HTML), so captions and names from
// Instagram can never become markup.
const SVG = 'http://www.w3.org/2000/svg';
/**
* Creates an element: h('button.btn.primo', { type: 'button', onclick }, 'Salva').
* Attributes: class, style (object), dataset (object), on<event> (function), boolean true → empty attribute,
* null/false/undefined → skipped. Children: nodes, strings, numbers, arrays (flattened), null (skipped).
*/
export function h(tag, attrs, ...children) {
const [name, ...classes] = tag.split('.');
const el = document.createElement(name || 'div');
if (classes.length) el.className = classes.join(' ');
if (attrs && (attrs instanceof Node || typeof attrs !== 'object' || Array.isArray(attrs))) {
children.unshift(attrs);
attrs = null;
}
for (const [key, value] of Object.entries(attrs || {})) {
if (value == null || value === false) continue;
if (key === 'class') el.className = [el.className, value].filter(Boolean).join(' ');
else if (key === 'style' && typeof value === 'object') Object.assign(el.style, value);
else if (key === 'dataset') Object.assign(el.dataset, value);
else if (key.startsWith('on') && typeof value === 'function') el.addEventListener(key.slice(2), value);
else if (key === 'value' && 'value' in el) el.value = value;
else if (key === 'checked' || key === 'disabled' || key === 'selected') el[key] = Boolean(value);
else el.setAttribute(key, value === true ? '' : String(value));
}
append(el, children);
return el;
}
export function append(el, children) {
for (const child of children.flat(Infinity)) {
if (child == null || child === false) continue;
el.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return el;
}
/** Replaces all children. */
export function fill(el, ...children) {
el.replaceChildren();
return append(el, children);
}
/** An icon from the sprite (wwwroot/icone, Lucide, stroke 1.75): <svg class="ic"><use href="#i-name"/></svg>. */
export function icon(name, size = '') {
const svg = document.createElementNS(SVG, 'svg');
svg.setAttribute('class', `ic${size ? ' ' + size : ''}`);
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
const use = document.createElementNS(SVG, 'use');
use.setAttribute('href', `#i-${name}`);
svg.append(use);
return svg;
}
/** The brand mark (appendix C), inline. */
export function brand() {
const svg = document.createElementNS(SVG, 'svg');
svg.setAttribute('viewBox', '0 0 32 32');
svg.setAttribute('aria-hidden', 'true');
svg.innerHTML = '<rect width="32" height="32" rx="8" fill="#0F5C8C"/><circle cx="14.5" cy="17.5" r="7.4" fill="none" stroke="#FFFFFF" stroke-width="2.6"/><circle cx="23.2" cy="8.8" r="3.1" fill="#FFFFFF"/>';
return svg;
}
/** Inlines the icon sprite once (hidden), so every <use href="#i-…"> works offline and with currentColor. */
export async function loadIcons() {
const response = await fetch('/icone/tutte.svg');
if (!response.ok) return;
const holder = document.createElement('div');
holder.hidden = true;
holder.innerHTML = await response.text();
document.body.prepend(holder);
}
let ids = 0;
/** A unique id for aria attributes. */
export function uid(prefix = 'f') {
ids += 1;
return `${prefix}-${ids}`;
}
/** Calls fn at most once per animation frame. */
export function perFrame(fn) {
let queued = false;
return (...args) => {
if (queued) return;
queued = true;
requestAnimationFrame(() => {
queued = false;
fn(...args);
});
};
}
/** Debounce. */
export function later(fn, ms) {
let timer = 0;
const wrapped = (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
wrapped.cancel = () => clearTimeout(timer);
return wrapped;
}
/** Saved per-viewer preferences (tile size, sort order). Never required: storage may be missing. */
export const local = {
get(key, fallback) {
try {
const v = localStorage.getItem(`febe.${key}`);
return v == null ? fallback : JSON.parse(v);
} catch {
return fallback;
}
},
set(key, value) {
try {
localStorage.setItem(`febe.${key}`, JSON.stringify(value));
} catch {
// private window or blocked storage: the preference lasts until the page closes
}
},
};
+102
View File
@@ -0,0 +1,102 @@
// The engine and the library as seen by the pages: one event stream (/api/eventi) for the whole interface.
// «motore» carries the snapshot (sidebar, stop strip, Attività); «libreria» says the library changed.
import { api, eventsUrl } from './api.js';
import { caps } from './context.js';
const engineListeners = new Set();
const libraryListeners = new Set();
let latest = null;
let source = null;
let poll = 0;
/** The latest engine state (EngineDto), or null before the first answer. */
export function engineState() {
return latest;
}
/** Calls fn now (if known) and at every change. Returns the function that stops listening. */
export function onEngine(fn) {
engineListeners.add(fn);
if (latest) fn(latest);
return () => engineListeners.delete(fn);
}
/** Calls fn at every library change ({ at, accountId, reason }). */
export function onLibrary(fn) {
libraryListeners.add(fn);
return () => libraryListeners.delete(fn);
}
function publish(state) {
latest = state;
for (const fn of [...engineListeners]) {
try {
fn(state);
} catch (error) {
console.error(error);
}
}
}
/** Asks the server for the engine now (after a command). */
export async function refreshEngine() {
try {
publish(await api('/api/engine'));
} catch {
// the stream will bring it
}
}
/** Opens the event stream; when it is not available, falls back to asking every 30 seconds. */
export function startEvents() {
refreshEngine();
// The demo engine is static: asking every 30 seconds is enough, and no connection stays open, so headless
// screenshots with --virtual-time-budget (spec §10.7) finish.
if (!('EventSource' in window) || caps().demo) {
poll = setInterval(refreshEngine, 30000);
return;
}
source = new EventSource(eventsUrl());
source.addEventListener('motore', (e) => {
try {
publish(JSON.parse(e.data));
} catch {
// malformed line: ignore
}
});
source.addEventListener('libreria', (e) => {
let change = {};
try {
change = JSON.parse(e.data);
} catch {
// keep the empty change
}
for (const fn of [...libraryListeners]) fn(change);
});
source.addEventListener('error', () => {
// EventSource reconnects by itself (retry: 3000); meanwhile ask once in a while.
if (!poll) poll = setInterval(() => (source.readyState === 1 ? (clearInterval(poll), (poll = 0)) : refreshEngine()), 15000);
});
}
/** Spia (dot) colour of an engine mode. */
export function dotOf(mode) {
switch (mode) {
case 'InSession':
case 'UserDriving':
return 'accento';
case 'Resting':
case 'Starting':
case 'OutsideWindow':
return 'verde';
case 'Throttled':
case 'NotConnected':
return 'ambra';
case 'StoppedForVerification':
case 'Disconnected':
return 'rosso';
default:
return '';
}
}
+335
View File
@@ -0,0 +1,335 @@
// 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;
/** 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 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'))));
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) {
this.cleanups.push(onEngine(fn));
}
/** Library changes while the page is open. */
onLibrary(fn) {
this.cleanups.push(onLibrary(fn));
}
/** Runs fn when the page is left. */
onLeave(fn) {
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', {
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'));
const open = h('button.btn.primo', { type: 'button', onclick: openBrowser }, 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. */
export async function openBrowser() {
if (caps().browserWindow) {
try {
const result = await api('/api/browser/show', { method: 'POST' });
toast(result.message);
refreshEngine();
} catch (error) {
showError(error);
}
} else {
navigate('/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);
}
/** 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', () => render());
render();
}
async function render() {
closeMenu();
const token = ++renderToken;
const path = location.pathname;
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 };
+166
View File
@@ -0,0 +1,166 @@
// Texts and number/date formats. Every string the user reads comes from testi/<lingua>.json (spec §3: adding a
// language must not touch the code). Numbers use dot for thousands and comma for decimals (spec §10.4); future engine
// times are always «verso le».
let texts = {};
/** Loads the text resource (once, at start). */
export async function loadTexts(language = 'it') {
const response = await fetch(`/testi/${language}.json`, { headers: { Accept: 'application/json' } });
if (!response.ok) throw new Error('testi');
texts = await response.json();
}
function lookup(key) {
let node = texts;
for (const part of key.split('.')) {
if (node == null) return undefined;
node = node[part];
}
return node;
}
/**
* The text of a key. Values with «|» are «singular|plural» chosen by vars.n; {name} placeholders are filled from vars.
* A missing key shows the key itself, so a gap is visible instead of silently empty.
*/
export function t(key, vars) {
let value = lookup(key);
if (value == null) return key;
if (typeof value !== 'string') return value;
if (value.includes('|')) {
const [one, many] = value.split('|');
value = vars && Number(vars.n) === 1 ? one : many;
}
if (vars) {
value = value.replace(/\{(\w+)\}/g, (match, name) => {
if (!(name in vars)) return match;
const v = vars[name];
return typeof v === 'number' ? number(v) : String(v);
});
}
return value;
}
/** A list of texts (weekday and month names). */
export function list(key) {
const value = lookup(key);
return Array.isArray(value) ? value : [];
}
/** Whole number with dots for thousands: 48.212 (also for four digits: 1.284). */
export function number(value) {
const n = Math.round(Number(value) || 0);
const digits = Math.abs(n).toString();
let out = '';
for (let i = 0; i < digits.length; i++) {
if (i > 0 && (digits.length - i) % 3 === 0) out += '.';
out += digits[i];
}
return (n < 0 ? '-' : '') + out;
}
/** Decimal with a comma: 1,3. Trailing zeros dropped. */
export function decimal(value, decimals = 1) {
const factor = 10 ** decimals;
const rounded = Math.round(Number(value) * factor) / factor;
const whole = Math.trunc(rounded);
let fraction = Math.round(Math.abs(rounded - whole) * factor).toString().padStart(decimals, '0').replace(/0+$/, '');
const head = (rounded < 0 && whole === 0 ? '-' : '') + number(whole);
return fraction ? `${head},${fraction}` : head;
}
/** «412 kB», «1,3 GB». */
export function bytes(value) {
const b = Number(value) || 0;
const KB = 1024, MB = KB * 1024, GB = MB * 1024;
if (b >= GB) return t('unita.GB', { n: decimal(b / GB, 1) });
if (b >= MB) return t('unita.MB', { n: decimal(b / MB, b >= 100 * MB ? 0 : 1) });
if (b >= KB) return t('unita.kB', { n: number(b / KB) });
return t('unita.byte', { n: number(b) });
}
/** Video duration: «0:24», «1:02», «1:02:03». */
export function duration(seconds) {
const s = Math.max(0, Math.round(Number(seconds) || 0));
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), r = s % 60;
const ss = String(r).padStart(2, '0');
return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`;
}
/** Parses «2026-10-13» as a calendar day (no time zone involved). */
export function parseDay(day) {
const [y, m, d] = String(day).split('-').map(Number);
return { y, m, d, weekday: new Date(Date.UTC(y, m - 1, d)).getUTCDay(), number: Date.UTC(y, m - 1, d) / 86400000 };
}
/** «martedì 13 ottobre» (with the year when it is not the year of «today»). */
export function dayName(day, today) {
const p = parseDay(day);
const base = `${list('tempo.giorni')[p.weekday]} ${p.d} ${list('tempo.mesi')[p.m - 1]}`;
return today && parseDay(today).y !== p.y ? `${base} ${p.y}` : base;
}
/** «13 ottobre» (or «13 ottobre 2025» in another year). */
export function shortDay(day, today) {
const p = parseDay(day);
const base = `${p.d} ${list('tempo.mesi')[p.m - 1]}`;
return today && parseDay(today).y !== p.y ? `${base} ${p.y}` : base;
}
/** Days between two calendar days (b − a). */
export function daysBetween(a, b) {
return Math.round(parseDay(b).number - parseDay(a).number);
}
export function capitalize(text) {
return text ? text[0].toUpperCase() + text.slice(1) : text;
}
/** «verso le 16:10», «domani verso le 7:42», «giovedì verso le 7:42», «il 21 ottobre verso le 7:42». */
export function around(local) {
if (!local) return '';
const hour = Number(String(local.clock).split(':')[0]);
const time = t(hour === 1 ? 'tempo.versoUna' : 'tempo.verso', { ora: local.clock });
const prefix = dayPrefix(local);
return prefix ? `${prefix} ${time}` : time;
}
/** «alle 16:10», «ieri alle 7:42». */
export function at(local) {
if (!local) return '';
const hour = Number(String(local.clock).split(':')[0]);
const time = t(hour === 1 ? 'tempo.allUna' : 'tempo.alle', { ora: local.clock });
if (local.dayDelta === 0) return time;
if (local.dayDelta === -1) return `${t('tempo.ieri')} ${time}`;
const prefix = dayPrefix(local);
return prefix ? `${prefix} ${time}` : `${t('tempo.il', { giorno: shortDay(local.day) })} ${time}`;
}
function dayPrefix(local) {
const d = local.dayDelta;
if (d <= 0) return '';
if (d === 1) return t('tempo.domani');
if (d < 7) return list('tempo.giorni')[parseDay(local.day).weekday];
return t('tempo.il', { giorno: shortDay(local.day) });
}
/** «8 min fa», «1 ora fa», «ieri», «11 giorni fa» relative to the server's now (milliseconds). */
export function ago(ms, nowMs, today, day) {
const minutes = Math.max(0, Math.floor((nowMs - ms) / 60000));
if (minutes < 1) return t('tempo.adesso');
if (minutes < 60) return t('tempo.minutiFa', { n: minutes });
const hours = Math.floor(minutes / 60);
if (day && today) {
const days = daysBetween(day, today);
if (days === 1 && hours >= 6) return t('tempo.ieri');
if (days >= 2 && days < 14) return t('tempo.giorniFa', { n: days });
}
if (hours < 24) return t('tempo.oreFa', { n: hours });
const days = Math.floor(hours / 24);
if (days === 1) return t('tempo.ieri');
if (days < 14) return t('tempo.giorniFa', { n: days });
if (days < 60) return t('tempo.settimaneFa', { n: Math.floor(days / 7) });
if (days < 365) return t('tempo.mesiFa', { n: Math.floor(days / 30) });
return t('tempo.anniFa', { n: Math.floor(days / 365) });
}
+56
View File
@@ -0,0 +1,56 @@
// Light, dark or as the system (spec §10.5). The choice is stored on the server (Impostazioni, Generali) and kept in
// this browser too, so the page does not flash at start (js/tema.js applies it before the first paint).
// In the demo «?tema=chiaro|scuro» wins for the whole tab without changing the stored choice.
import { api, carriedValue } from './api.js';
const media = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
let choice = 'sistema';
function paint() {
const forced = carriedValue('tema');
const effective = forced === 'chiaro' || forced === 'scuro'
? forced
: choice === 'sistema' ? (media && media.matches ? 'scuro' : 'chiaro') : choice;
document.documentElement.setAttribute('data-tema', effective);
document.documentElement.setAttribute('data-scelta-tema', choice);
}
/** The stored choice: «chiaro», «scuro» or «sistema». */
export function themeChoice() {
return choice;
}
/** Applies a choice locally (no server call). */
export function applyTheme(value) {
choice = value === 'chiaro' || value === 'scuro' ? value : 'sistema';
try {
localStorage.setItem('febe.tema', choice);
} catch {
// storage blocked: the choice still applies to this page
}
paint();
}
/** At start: local choice first, then the server's. */
export async function initTheme() {
try {
choice = localStorage.getItem('febe.tema') || 'sistema';
} catch {
choice = 'sistema';
}
paint();
if (media && media.addEventListener) media.addEventListener('change', paint);
try {
const prefs = await api('/api/preferences');
if (prefs && prefs.theme && prefs.theme !== choice) applyTheme(prefs.theme);
} catch {
// keep the local choice
}
}
/** Stores a new choice on the server and applies it («Tema» in Impostazioni, Generali). */
export async function saveTheme(value) {
applyTheme(value);
await api('/api/preferences', { method: 'PUT', body: { theme: choice } });
}
+287
View File
@@ -0,0 +1,287 @@
// Components of the style sheet (appendix B, mockup 13) as functions: dialogs, menus, short notices, switches,
// check boxes, avatars. Keyboard first: every control is a real button or input, focus is always visible.
import { h, icon, uid } from './dom.js';
import { t } from './text.js';
// ------------------------------------------------------------------------------------------------- short notices
let toasts;
/** A short notice at the bottom («Impostazioni salvate.»); errors stay longer. */
export function toast(message, kind = '') {
if (!toasts) {
toasts = h('div.brevi', { role: 'status', 'aria-live': 'polite' });
document.body.append(toasts);
}
const item = h(`div.breve${kind ? '.' + kind : ''}`, kind === 'errore' ? icon('octagon-alert', 's') : icon('circle-check', 's'), h('span', message));
toasts.append(item);
setTimeout(() => item.remove(), kind === 'errore' ? 8000 : 4000);
}
/** Shows the message of an error (ApiError or anything else). */
export function showError(error) {
if (error && error.name === 'AbortError') return;
toast(error && error.message ? error.message : t('comune.errore'), 'errore');
}
// ------------------------------------------------------------------------------------------------- dialogs
const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
/**
* Opens a modal dialog over the whole window. build(close) returns { header?, body, footer? } or a node; close(value)
* resolves the returned promise. Esc and the veil close with undefined. Focus is trapped and restored.
*/
export function dialog({ title, className = '', build, labelledBy, dismissable = true }) {
return new Promise((resolve) => {
const opener = document.activeElement;
const titleId = labelledBy || uid('dlg');
let closed = false;
const close = (value) => {
if (closed) return;
closed = true;
veil.remove();
document.removeEventListener('keydown', onKey, true);
if (opener && opener.focus && document.contains(opener)) opener.focus();
resolve(value);
};
const parts = build(close);
const box = h(`div.dialogo${className ? '.' + className : ''}`, { role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId });
if (title) {
box.append(h('header', h('h2', { id: titleId }, title),
dismissable ? h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('comune.chiudi'), onclick: () => close(undefined) }, icon('x')) : null));
}
if (parts instanceof Node) box.append(parts);
else {
if (parts.body) box.append(parts.body);
if (parts.footer) box.append(parts.footer);
}
const veil = h('div.velo.finestra', box);
veil.addEventListener('mousedown', (e) => {
if (e.target === veil && dismissable) close(undefined);
});
const onKey = (e) => {
if (e.key === 'Escape' && dismissable) {
e.stopPropagation();
close(undefined);
} else if (e.key === 'Tab') {
const items = [...box.querySelectorAll(FOCUSABLE)].filter((el) => el.offsetParent !== null);
if (!items.length) return;
const first = items[0], last = items[items.length - 1];
if (e.shiftKey && document.activeElement === first) {
last.focus();
e.preventDefault();
} else if (!e.shiftKey && document.activeElement === last) {
first.focus();
e.preventDefault();
}
}
};
document.addEventListener('keydown', onKey, true);
document.body.append(veil);
const autofocus = box.querySelector('[autofocus]') || box.querySelector('.contenuto ' + FOCUSABLE) || box.querySelector(FOCUSABLE);
if (autofocus) autofocus.focus();
});
}
/**
* A confirmation with explicit buttons that say what happens (spec §10.4). Returns the value of the chosen button,
* or undefined when dismissed. buttons: [{ label, value, kind: 'primo'|'pericolo'|'' }].
*/
export function confirmDialog({ title, text, extra, buttons }) {
return dialog({
title,
className: 'piccolo',
build: (close) => ({
body: h('div.contenuto', text ? h('p', text) : null, extra || null),
footer: h('footer', h('div.destra',
buttons.map((b) => h(`button.btn${b.kind ? '.' + b.kind : ''}`, { type: 'button', onclick: () => close(b.value), autofocus: b.autofocus || null }, b.label)))),
}),
});
}
// ------------------------------------------------------------------------------------------------- menus
let openMenu = null;
/** Closes the open menu, if any. */
export function closeMenu() {
if (openMenu) openMenu();
}
/**
* Opens a menu under an anchor. items: [{ label, icon, value, checked, danger, disabled }] or nodes (a search field,
* a separator 'hr'). onPick(value) is called with the chosen value. Arrows move, Esc closes, focus returns to the anchor.
*/
export function menu(anchor, items, onPick, { role = 'menu', align = 'left', width } = {}) {
closeMenu();
const box = h('div.menu', { role, style: width ? { width: `${width}px` } : null });
const entries = [];
for (const item of items) {
if (item === 'hr') {
box.append(h('hr'));
continue;
}
if (item instanceof Node) {
box.append(item);
continue;
}
const itemRole = item.checked === undefined ? 'menuitem' : item.radio ? 'menuitemradio' : 'menuitemcheckbox';
const button = h(`button${item.danger ? '.pericolo' : ''}`, {
type: 'button', role: itemRole, disabled: item.disabled || null,
'aria-checked': item.checked === undefined ? null : String(Boolean(item.checked)),
onclick: () => {
if (!item.keepOpen) close();
onPick(item.value, button);
},
}, item.icon ? icon(item.icon, 's') : null, h('span', item.label), item.checked === undefined ? null : icon('check', 's segno'));
entries.push(button);
box.append(button);
}
document.body.append(box);
const rect = anchor.getBoundingClientRect();
const boxWidth = box.offsetWidth;
let left = align === 'right' ? rect.right - boxWidth : rect.left;
left = Math.max(8, Math.min(left, window.innerWidth - boxWidth - 8));
let top = rect.bottom + 6;
if (top + box.offsetHeight > window.innerHeight - 8) top = Math.max(8, rect.top - box.offsetHeight - 6);
box.style.left = `${left}px`;
box.style.top = `${top}px`;
anchor.setAttribute('aria-expanded', 'true');
const onDown = (e) => {
if (!box.contains(e.target) && !anchor.contains(e.target)) close();
};
const onKey = (e) => {
const focusables = [...box.querySelectorAll('button:not([disabled]),input')];
const index = focusables.indexOf(document.activeElement);
if (e.key === 'Escape') {
e.stopPropagation();
close();
anchor.focus();
} else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
const next = e.key === 'ArrowDown' ? index + 1 : index - 1;
const target = focusables[(next + focusables.length) % focusables.length];
if (target) target.focus();
} else if (e.key === 'Tab') {
close();
}
};
const onScroll = (e) => {
if (!box.contains(e.target)) close();
};
function close() {
if (!box.isConnected) return;
box.remove();
anchor.setAttribute('aria-expanded', 'false');
document.removeEventListener('mousedown', onDown, true);
document.removeEventListener('keydown', onKey, true);
document.removeEventListener('scroll', onScroll, true);
window.removeEventListener('resize', close);
if (openMenu === close) openMenu = null;
}
setTimeout(() => {
document.addEventListener('mousedown', onDown, true);
document.addEventListener('scroll', onScroll, true);
});
document.addEventListener('keydown', onKey, true);
window.addEventListener('resize', close);
openMenu = close;
const first = box.querySelector('input') || box.querySelector('[aria-checked=true]') || entries[0];
if (first) first.focus();
return { box, close };
}
// ------------------------------------------------------------------------------------------------- form controls
/** A switch («interruttore»): a real checkbox with role switch, styled as .int. */
export function toggle({ checked, label, hiddenLabel = false, disabled = false, onchange }) {
const input = h('input.vh', { type: 'checkbox', role: 'switch', checked, disabled, 'aria-label': hiddenLabel ? label : null });
if (onchange) input.addEventListener('change', () => onchange(input.checked, input));
const el = h('label.leva', input, h('span.int', { 'aria-hidden': 'true' }), hiddenLabel ? null : h('span', label));
el.input = input;
return el;
}
/** A check box («spunta»). */
export function checkbox({ checked, label, disabled = false, onchange, labelNode }) {
const input = h('input.vh', { type: 'checkbox', checked, disabled });
if (onchange) input.addEventListener('change', () => onchange(input.checked, input));
const el = h('label.voce', input, h('span.spunta', { 'aria-hidden': 'true' }, icon('check')), labelNode || (label ? h('span', label) : null));
el.input = input;
return el;
}
/** A radio button («tondo»). */
export function radio({ name, value, checked, label, labelNode, onchange }) {
const input = h('input.vh', { type: 'radio', name, value, checked });
if (onchange) input.addEventListener('change', () => input.checked && onchange(value, input));
const el = h('label.voce', input, h('span.tondo', { 'aria-hidden': 'true' }), labelNode || (label ? h('span', label) : null));
el.input = input;
return el;
}
/** A segmented control («gruppo»): [{ value, label, icon }]. */
export function segmented({ options, value, label, onchange }) {
const group = h('div.gruppo', { role: 'radiogroup', 'aria-label': label });
const buttons = options.map((o) => {
const b = h('button', {
type: 'button', role: 'radio', 'aria-checked': String(o.value === value), class: o.value === value ? 'qui' : null,
tabindex: o.value === value ? '0' : '-1',
onclick: () => select(o.value, true),
}, o.icon ? icon(o.icon, 's') : null, o.label);
b.dataset.value = o.value;
return b;
});
function select(v, notify) {
for (const b of buttons) {
const on = b.dataset.value === v;
b.classList.toggle('qui', on);
b.setAttribute('aria-checked', String(on));
b.tabIndex = on ? 0 : -1;
if (on && notify) b.focus();
}
if (notify && onchange) onchange(v);
}
group.addEventListener('keydown', (e) => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
const index = buttons.findIndex((b) => b.classList.contains('qui'));
const next = buttons[(index + (e.key === 'ArrowRight' ? 1 : -1) + buttons.length) % buttons.length];
select(next.dataset.value, true);
e.preventDefault();
});
group.append(...buttons);
group.select = (v) => select(v, false);
return group;
}
// ------------------------------------------------------------------------------------------------- avatars and labels
const AVATAR_COLORS = ['#2F6B45', '#2E5E78', '#7A5426', '#8A2E4B', '#5A4699', '#3D6B1F', '#7B3F8C', '#1F6670', '#8C4A2F', '#4B5A8C'];
/** «MD» for marta.demo, «LV» for luca.viaggi.demo, «E2» for estate.2019.demo. */
export function initials(username) {
const parts = String(username || '?').replace(/^@/, '').split(/[._]/).filter(Boolean);
if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
return (parts[0] || '?').slice(0, 2).toUpperCase();
}
function colorOf(username) {
let hash = 0;
for (const c of String(username)) hash = (hash * 31 + c.charCodeAt(0)) >>> 0;
return AVATAR_COLORS[hash % AVATAR_COLORS.length];
}
/** An avatar: the latest profile picture when there is one, otherwise initials on a colour from the name. */
export function avatar(username, size = '', thumb = null) {
const el = h(`span.av${size ? '.' + size : ''}`, { 'aria-hidden': 'true', style: { background: colorOf(username) } });
if (thumb) el.append(h('img', { src: `/api/thumbnails/${thumb}`, alt: '', loading: 'lazy' }));
else el.textContent = initials(username);
return el;
}
/** A label («etichetta»): et(text, 'accento', 'lock'). */
export function label(text, kind = '', iconName = null) {
return h(`span.et${kind ? '.' + kind : ''}`, iconName ? icon(iconName) : null, text);
}