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:
76 files changed
+12503
-17
No files matched your search
@@ -0,0 +1,51 @@
|
||||
// The login page of the Docker interface (spec §13.1): one password, an HttpOnly SameSite=Strict session cookie set
|
||||
// by the server, lockout after repeated failures. Nothing is stored by this page.
|
||||
|
||||
import { h, fill, brand } from './core/dom.js';
|
||||
import { loadTexts, t } from './core/text.js';
|
||||
|
||||
async function boot() {
|
||||
await loadTexts('it');
|
||||
const root = document.getElementById('app');
|
||||
const password = h('input', { type: 'password', id: 'password', autocomplete: 'current-password', required: true, autofocus: true });
|
||||
const message = h('p.aiuto', { role: 'alert', style: { color: 'var(--rosso)', minHeight: '20px' } });
|
||||
const button = h('button.btn.primo.grande', { type: 'submit', style: { width: '100%', justifyContent: 'center' } }, t('accesso.entra'));
|
||||
const form = h('form.pannello', { style: { width: 'min(360px, calc(100vw - 32px))', padding: '28px', display: 'flex', flexDirection: 'column', gap: '12px' } },
|
||||
h('div.marchio', { style: { padding: '0 0 6px' } }, brand(), h('b', t('app.nome'))),
|
||||
h('h1', { style: { margin: '0', fontSize: '20px', fontWeight: '650' } }, t('accesso.titolo')),
|
||||
h('label.etichetta', { for: 'password' }, t('accesso.password')),
|
||||
h('div.campo', password),
|
||||
h('p.aiuto', t('accesso.aiuto')),
|
||||
message,
|
||||
button);
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
button.disabled = true;
|
||||
message.textContent = '';
|
||||
try {
|
||||
const response = await fetch('/api/accesso', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ password: password.value }),
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (response.ok && data.ok) {
|
||||
const back = new URLSearchParams(location.search).get('torna');
|
||||
location.href = back && back.startsWith('/') && !back.startsWith('//') ? back : '/libreria';
|
||||
return;
|
||||
}
|
||||
message.textContent = data.message || t('accesso.sbagliata');
|
||||
password.value = '';
|
||||
password.focus();
|
||||
} catch {
|
||||
message.textContent = t('comune.errore');
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
root.style.cssText = 'min-height:100vh;display:flex;align-items:center;justify-content:center;padding:16px';
|
||||
fill(root, form);
|
||||
}
|
||||
|
||||
boot();
|
||||
@@ -0,0 +1,39 @@
|
||||
// Start of the interface: texts, icons, capabilities of the shell, theme, frame, events, router.
|
||||
|
||||
import { api, initCarried, setAccess } from './core/api.js';
|
||||
import { setCapabilities } from './core/context.js';
|
||||
import { loadIcons, h, fill } from './core/dom.js';
|
||||
import { startEvents } from './core/engine.js';
|
||||
import { buildShell, startRouter } from './core/shell.js';
|
||||
import { loadTexts, t } from './core/text.js';
|
||||
import { initTheme } from './core/theme.js';
|
||||
|
||||
async function boot() {
|
||||
initCarried();
|
||||
const root = document.getElementById('app');
|
||||
try {
|
||||
await Promise.all([loadTexts(document.documentElement.lang || 'it'), loadIcons()]);
|
||||
} catch {
|
||||
fill(root, h('p', { style: { padding: '24px' } }, 'Febe non riesce a caricare i testi dell\'interfaccia. Ricarica la pagina.'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const capabilities = await api('/api/capabilities');
|
||||
setCapabilities(capabilities);
|
||||
setAccess(capabilities.access);
|
||||
if (capabilities.demo) document.documentElement.dataset.dimostrazione = '';
|
||||
} catch {
|
||||
// the defaults describe a plain browser
|
||||
}
|
||||
initTheme();
|
||||
buildShell(root);
|
||||
startEvents();
|
||||
startRouter();
|
||||
document.documentElement.removeAttribute('aria-busy');
|
||||
window.addEventListener('unhandledrejection', (e) => {
|
||||
if (e.reason && e.reason.name === 'AbortError') e.preventDefault();
|
||||
});
|
||||
void t;
|
||||
}
|
||||
|
||||
boot();
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -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 '';
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
@@ -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) });
|
||||
}
|
||||
@@ -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 } });
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
// Scheda account (mockups 05 and 12, spec §4.4, §4.6): header with avatar, name, labels, counts, «Controlla ora» and
|
||||
// the link to the profile; tabs Contenuti (Post, Storie as a regular 9:16 grid, In evidenza grouped by collection,
|
||||
// Taggati, Profilo when there is more than one picture), Impostazioni (with «Con queste impostazioni» recomputed at
|
||||
// every change and the fixed save bar) and Cronologia (the checks with their outcome).
|
||||
|
||||
import { api, download, withCarried } from '../core/api.js';
|
||||
import { caps, serverNow } from '../core/context.js';
|
||||
import { h, icon, fill, later, local } from '../core/dom.js';
|
||||
import { refreshEngine } from '../core/engine.js';
|
||||
import { navigate, setQuery } from '../core/shell.js';
|
||||
import { t, number, decimal, dayName, shortDay, capitalize } from '../core/text.js';
|
||||
import { avatar, checkbox, confirmDialog, menu, segmented, showError, toast, toggle } from '../core/ui.js';
|
||||
import { accountLabels, accountMenu, checkNow, openProfile } from './accounts.js';
|
||||
import { confirmDelete } from './library.js';
|
||||
import { Mosaic, justify, tileElement, defaultDayLabel } from './mosaic.js';
|
||||
import { openViewer } from './viewer.js';
|
||||
|
||||
const KINDS = [
|
||||
{ key: 'post', api: 'posts', stat: 'posts', label: 'scheda.tipi.posts' },
|
||||
{ key: 'storie', api: 'stories', stat: 'stories', label: 'scheda.tipi.stories', grid: true },
|
||||
{ key: 'evidenza', api: 'highlights', stat: 'highlightItems', label: 'scheda.tipi.highlights' },
|
||||
{ key: 'taggati', api: 'tagged', stat: 'tagged', label: 'scheda.tipi.tagged' },
|
||||
{ key: 'profilo', api: 'profile', stat: 'profilePictures', label: 'scheda.tipi.profile' },
|
||||
];
|
||||
|
||||
const TYPE_FIELDS = [
|
||||
{ key: 'photos', icon: 'image' },
|
||||
{ key: 'videos', icon: 'clapperboard' },
|
||||
{ key: 'stories', icon: 'circle-dashed' },
|
||||
{ key: 'highlights', icon: 'star' },
|
||||
{ key: 'tagged', icon: 'square-user' },
|
||||
{ key: 'profilePicture', icon: 'circle-user' },
|
||||
];
|
||||
|
||||
const PLAN_ICONS = { posts: 'clock', stories: 'circle-dashed', backfill: 'history', load: 'gauge', checks: 'info' };
|
||||
|
||||
export default {
|
||||
async mount(page, route) {
|
||||
const id = Number(route.params.id);
|
||||
const tab = route.params.tab || 'contenuti';
|
||||
let detail;
|
||||
try {
|
||||
detail = await api(`/api/accounts/${id}`, { signal: page.signal });
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') return;
|
||||
page.back(t('scheda.indietro'), '/account');
|
||||
page.title(t('scheda.nonTrovato'));
|
||||
fill(page.body, h('div.vuoto-pagina', icon('users'), h('h2', t('scheda.nonTrovato')), h('p', error.message || t('scheda.nonTrovatoTesto'))));
|
||||
return;
|
||||
}
|
||||
|
||||
page.back(t('scheda.indietro'), '/account');
|
||||
const header = h('header.scheda-testa');
|
||||
page.header(header, `@${detail.account.username}`);
|
||||
drawHeader(header, detail, async () => {
|
||||
detail = await api(`/api/accounts/${id}`, { signal: page.signal });
|
||||
drawHeader(header, detail);
|
||||
});
|
||||
|
||||
const base = `/account/${id}`;
|
||||
page.tabs(h('nav.linguette', { 'aria-label': `@${detail.account.username}` },
|
||||
h(`a${tab === 'contenuti' ? '.qui' : ''}`, { href: withCarried(base), 'aria-current': tab === 'contenuti' ? 'page' : null },
|
||||
t('scheda.linguette.contenuti'), h('i', number(detail.stats.entries))),
|
||||
h(`a${tab === 'impostazioni' ? '.qui' : ''}`, { href: withCarried(`${base}/impostazioni`), 'aria-current': tab === 'impostazioni' ? 'page' : null }, t('scheda.linguette.impostazioni')),
|
||||
h(`a${tab === 'cronologia' ? '.qui' : ''}`, { href: withCarried(`${base}/cronologia`), 'aria-current': tab === 'cronologia' ? 'page' : null }, t('scheda.linguette.cronologia'))));
|
||||
|
||||
if (tab === 'impostazioni') return settingsTab(page, detail);
|
||||
if (tab === 'cronologia') return historyTab(page, detail);
|
||||
return contentsTab(page, route, detail);
|
||||
},
|
||||
};
|
||||
|
||||
// --------------------------------------------------------------------------------------------- header
|
||||
|
||||
function drawHeader(header, detail, reload) {
|
||||
const a = detail.account;
|
||||
const s = detail.stats;
|
||||
const postsBlock = a.state === 'backfilling' && a.postCount
|
||||
? h('div', h('b', t('scheda.numeri.postDi', { fatti: number(a.posts), totale: number(a.postCount) })), h('span', t('scheda.numeri.postScaricati')))
|
||||
: h('div', h('b', number(s.posts)), h('span', t('scheda.numeri.post')));
|
||||
const check = h('button.btn', { type: 'button', disabled: a.state === 'archiveOnly', onclick: () => checkNow(a) }, icon('refresh-cw'), t('account.menu.controlla'));
|
||||
const link = detail.instagramUrl
|
||||
? h('button.btn.solo', { type: 'button', title: t('scheda.apriProfilo'), 'aria-label': t('scheda.apriProfilo'), onclick: () => openProfile(a) }, icon('external-link'))
|
||||
: null;
|
||||
const more = h('button.btn.solo', { type: 'button', 'aria-label': t('comune.menu'), 'aria-haspopup': 'true' }, icon('ellipsis'));
|
||||
more.addEventListener('click', () => accountMenu(more, a, (outcome) => {
|
||||
if (outcome === 'removed') navigate('/account');
|
||||
else if (reload) reload().catch(showError);
|
||||
}));
|
||||
fill(header,
|
||||
avatar(a.username, 'g', a.avatar),
|
||||
h('div.nomi', h('h1', `@${a.username}`), h('div.sotto', a.isMine ? t('account.sotto.tuo') : a.displayName, accountLabels(a))),
|
||||
h('div.numeri',
|
||||
h('div', h('b', number(s.entries)), h('span', t('scheda.numeri.elementi'))),
|
||||
postsBlock,
|
||||
h('div', h('b', number(s.stories)), h('span', t('scheda.numeri.storie'))),
|
||||
h('div', h('b', number(s.collections)), h('span', t('scheda.numeri.raccolte')))),
|
||||
h('div.azioni', check, link, more));
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- contents
|
||||
|
||||
async function contentsTab(page, route, detail) {
|
||||
const s = detail.stats;
|
||||
const available = KINDS.filter((k) => k.key !== 'profilo' || s.profilePictures > 1);
|
||||
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;
|
||||
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')));
|
||||
page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, h('div.destra', selectButton)));
|
||||
const host = h('div');
|
||||
fill(page.body, host);
|
||||
|
||||
function drawTools() {
|
||||
fill(chips, available.map((k) => h(`button${k === kind ? '.qui' : ''}`, {
|
||||
type: 'button', 'aria-pressed': String(k === kind),
|
||||
onclick: () => {
|
||||
kind = k;
|
||||
setQuery({ tipo: k.key });
|
||||
show();
|
||||
},
|
||||
}, t(k.label), h('i', number(s[k.stat])))));
|
||||
fill(periodButton, h('span.val', period ? t(`libreria.periodi.${period}`) : t('libreria.periodi.qualsiasi')), icon('chevron-down', 's'));
|
||||
selectButton.hidden = kind.key === 'evidenza';
|
||||
}
|
||||
|
||||
periodButton.addEventListener('click', () => menu(periodButton,
|
||||
['', 'settimana', 'mese', 'anno', 'annoScorso'].map((p) => ({ label: t(p ? `libreria.periodi.${p}` : 'libreria.periodi.qualsiasi'), value: p, checked: p === period, radio: true })),
|
||||
(value) => {
|
||||
period = value;
|
||||
setQuery({ periodo: value || null });
|
||||
show();
|
||||
}));
|
||||
|
||||
function query() {
|
||||
const q = new URLSearchParams({ accounts: String(detail.account.id), kind: kind.api });
|
||||
const today = caps().today;
|
||||
const add = (n) => new Date(Date.parse(`${today}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10);
|
||||
const year = Number(today.slice(0, 4));
|
||||
const range = { settimana: [add(-6), today], mese: [add(-29), today], anno: [`${year}-01-01`, today], annoScorso: [`${year - 1}-01-01`, `${year - 1}-12-31`] }[period];
|
||||
if (range) {
|
||||
q.set('from', range[0]);
|
||||
q.set('to', range[1]);
|
||||
}
|
||||
return q.toString();
|
||||
}
|
||||
|
||||
function drawSelection(selected) {
|
||||
if (!mosaic || !mosaic.selecting) {
|
||||
page.saveBar(null);
|
||||
return;
|
||||
}
|
||||
const n = selected.size;
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', n ? t('selezione.scelti', { n }) : t('selezione.nessuno')),
|
||||
h('div.destra',
|
||||
h('button.btn.nudo', { type: 'button', onclick: () => setSelecting(false) }, t('selezione.annulla')),
|
||||
h('button.btn', { type: 'button', disabled: !n, onclick: async () => {
|
||||
try {
|
||||
await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv');
|
||||
toast(t('selezione.esportato'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
} }, icon('file-down'), t('selezione.esporta')),
|
||||
h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: async () => {
|
||||
const removed = await confirmDelete([...mosaic.selected]);
|
||||
if (removed) {
|
||||
mosaic.removeTiles(removed);
|
||||
setSelecting(false);
|
||||
}
|
||||
} }, icon('trash-2'), t('selezione.elimina', { n })))));
|
||||
}
|
||||
|
||||
function setSelecting(on) {
|
||||
if (!mosaic) return;
|
||||
mosaic.setSelecting(on);
|
||||
fill(selectButton, icon(on ? 'check' : 'circle-check'), h('span', t(on ? 'libreria.fine' : 'libreria.seleziona')));
|
||||
selectButton.setAttribute('aria-pressed', String(on));
|
||||
drawSelection(mosaic.selected);
|
||||
}
|
||||
selectButton.addEventListener('click', () => mosaic && setSelecting(!mosaic.selecting));
|
||||
|
||||
async function show() {
|
||||
drawTools();
|
||||
if (mosaic) mosaic.destroy();
|
||||
mosaic = null;
|
||||
page.saveBar(null);
|
||||
page.body.scrollTop = 0;
|
||||
if (kind.key === 'evidenza') {
|
||||
await showHighlights(host, detail, page);
|
||||
return;
|
||||
}
|
||||
const rowHeight = local.get('libreria.tessere', 160);
|
||||
mosaic = new Mosaic({
|
||||
scroller: page.body,
|
||||
host,
|
||||
query: query(),
|
||||
mode: kind.grid ? 'grid' : 'justified',
|
||||
rowHeight,
|
||||
signal: page.signal,
|
||||
dayLabel: kind.grid ? storiesDayLabel : defaultDayLabel,
|
||||
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: `@${detail.account.username}`, onDeleted: (ids) => mosaic.removeTiles(ids) }),
|
||||
onSelection: drawSelection,
|
||||
onEmpty: () => fill(host, h('div.vuoto-pagina', icon(kind.grid ? 'circle-dashed' : 'image'), h('p', t('scheda.nessunContenuto')))),
|
||||
});
|
||||
try {
|
||||
await mosaic.start();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
const onChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 500);
|
||||
page.onLibrary((change) => {
|
||||
if (!change.accountId || change.accountId === detail.account.id) onChange();
|
||||
});
|
||||
page.onLeave(() => {
|
||||
onChange.cancel();
|
||||
if (mosaic) mosaic.destroy();
|
||||
});
|
||||
await show();
|
||||
}
|
||||
|
||||
/** Day header of the stories: «Oggi martedì 13 ottobre, 2 storie», «Sabato 10 ottobre 9 storie». */
|
||||
function storiesDayLabel(day, count, today) {
|
||||
const [bold] = defaultDayLabel(day, count, today);
|
||||
const name = dayName(day, today);
|
||||
const n = t('libreria.storieGiorno', { n: count });
|
||||
if (bold === t('tempo.Oggi') || bold === t('tempo.Ieri')) return [bold, `${name}, ${n}`];
|
||||
return [capitalize(name), n];
|
||||
}
|
||||
|
||||
/** «In evidenza»: the mosaic grouped under the titles of the collections (mockup 12). */
|
||||
async function showHighlights(host, detail, page) {
|
||||
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;
|
||||
}
|
||||
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 });
|
||||
for (const tile of page2.tiles) tiles.set(tile.id, tile);
|
||||
}
|
||||
const flat = [];
|
||||
const groups = collections.map((c) => {
|
||||
const list = c.entryIds.map((x) => tiles.get(x)).filter(Boolean);
|
||||
flat.push(...list);
|
||||
return { c, list };
|
||||
});
|
||||
const source = {
|
||||
position: (entryId) => ({ index: flat.findIndex((x) => x.id === entryId) + 1, total: flat.length }),
|
||||
neighbor: async (entryId, delta) => flat[flat.findIndex((x) => x.id === entryId) + delta] || null,
|
||||
reveal: () => {},
|
||||
};
|
||||
const draw = () => {
|
||||
const width = host.clientWidth || 800;
|
||||
const rowHeight = local.get('libreria.tessere', 160);
|
||||
fill(host, groups.map(({ c, list }) => h('section',
|
||||
h('div.raccolta-titolo', h('b', c.title), h('span', [t('comune.contenuti', { n: list.length }), c.removed ? ` · ${t('scheda.raccoltaTolta')}` : ''].join(''))),
|
||||
justify(list, width, rowHeight).map((row) => h('div.fila', row.items.map((item) => tileElement(item.tile, item.width, row.height, { today: caps().today })))))));
|
||||
};
|
||||
draw();
|
||||
host.onclick = (e) => {
|
||||
const el = e.target.closest('.tess[data-id]');
|
||||
if (!el) return;
|
||||
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));
|
||||
observer.observe(host);
|
||||
page.onLeave(() => observer.disconnect());
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- settings
|
||||
|
||||
function settingsTab(page, detail) {
|
||||
page.body.style.paddingTop = '16px';
|
||||
const c = caps();
|
||||
const original = JSON.stringify(detail.settings);
|
||||
let form = JSON.parse(original);
|
||||
let plan = detail.plan;
|
||||
const account = detail.account;
|
||||
const planBox = h('div.piano', { 'aria-live': 'polite' });
|
||||
const left = h('div.colonna');
|
||||
fill(page.body, h('div.imp-account', left, planBox));
|
||||
|
||||
const dirty = () => JSON.stringify(form) !== original;
|
||||
const recompute = later(async () => {
|
||||
try {
|
||||
plan = await api(`/api/accounts/${account.id}/plan`, { method: 'POST', body: form, signal: page.signal });
|
||||
drawPlan();
|
||||
frequencyNote.textContent = plan.frequencyHint;
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError' && error.status === 400) planBox.prepend(h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message)));
|
||||
}
|
||||
}, 200);
|
||||
|
||||
function changed() {
|
||||
drawSaveBar();
|
||||
recompute();
|
||||
}
|
||||
|
||||
// Tieni aggiornato.
|
||||
const keep = toggle({ checked: form.keepUpdated, label: t('impAccount.tieni'), onchange: (v) => { form.keepUpdated = v; changed(); } });
|
||||
keep.querySelector('span:last-child').style.fontWeight = '650';
|
||||
|
||||
// Frequenza.
|
||||
const frequencyNote = h('span.nota', plan.frequencyHint);
|
||||
const customFields = h('div.riga-campi');
|
||||
const postHours = h('input', { type: 'number', min: '1', max: '48', step: '0.5', value: form.customPostHours ?? '', inputmode: 'decimal', id: 'ore-post' });
|
||||
const storyHours = h('input', { type: 'number', min: '1', max: '24', step: '0.5', value: form.customStoryHours ?? '', inputmode: 'decimal', id: 'ore-storie' });
|
||||
postHours.addEventListener('input', () => { form.customPostHours = postHours.value === '' ? null : Number(postHours.value); changed(); });
|
||||
storyHours.addEventListener('input', () => { form.customStoryHours = storyHours.value === '' ? null : Number(storyHours.value); changed(); });
|
||||
fill(customFields,
|
||||
h('div', h('label.etichetta', { for: 'ore-post' }, t('impAccount.suMisuraPost')), h('label.campo', postHours, h('span.unita', t('impAccount.ore')))),
|
||||
h('div', h('label.etichetta', { for: 'ore-storie' }, t('impAccount.suMisuraStorie')), h('label.campo', storyHours, h('span.unita', t('impAccount.ore')))));
|
||||
customFields.hidden = form.frequency !== 'custom';
|
||||
const frequency = segmented({
|
||||
label: t('impAccount.frequenza'),
|
||||
value: form.frequency,
|
||||
options: ['low', 'normal', 'high', 'custom'].map((f) => ({ value: f, label: t(`impAccount.frequenze.${f}`) })),
|
||||
onchange: (v) => {
|
||||
form.frequency = v;
|
||||
customFields.hidden = v !== 'custom';
|
||||
changed();
|
||||
},
|
||||
});
|
||||
|
||||
// Cosa scaricare.
|
||||
const types = h('div.tipi', TYPE_FIELDS.map((f) => {
|
||||
const box = checkbox({ checked: form.types[f.key], labelNode: h('span.testo', t(`impAccount.tipi.${f.key}`)), onchange: (v) => { form.types[f.key] = v; changed(); } });
|
||||
box.classList.add('tipo');
|
||||
box.append(icon(f.icon, 's'));
|
||||
return box;
|
||||
}));
|
||||
|
||||
// Limiti.
|
||||
const depth = h('select', { id: 'profondita' }, ['all', 'lastPosts', 'fromDate'].map((d) => h('option', { value: d, selected: form.depth === d }, t(`impAccount.profondita.${d}`))));
|
||||
const lastPosts = h('input', { type: 'number', min: '1', step: '1', value: form.lastPosts ?? 100, id: 'ultimi', inputmode: 'numeric' });
|
||||
const fromDate = h('input', { type: 'date', value: form.fromDate ?? caps().today, id: 'dal', max: caps().today });
|
||||
const depthExtra = h('div');
|
||||
function drawDepthExtra() {
|
||||
if (form.depth === 'lastPosts') {
|
||||
if (form.lastPosts == null) form.lastPosts = Number(lastPosts.value) || 100;
|
||||
fill(depthExtra, h('label.etichetta', { for: 'ultimi' }, t('impAccount.quantiPost')), h('label.campo', lastPosts, h('span.unita', t('impAccount.post'))));
|
||||
} else if (form.depth === 'fromDate') {
|
||||
if (!form.fromDate) form.fromDate = fromDate.value;
|
||||
fill(depthExtra, h('label.etichetta', { for: 'dal' }, t('impAccount.dalGiorno')), h('label.campo', fromDate));
|
||||
} else depthExtra.replaceChildren();
|
||||
depthExtra.hidden = form.depth === 'all';
|
||||
}
|
||||
depth.addEventListener('change', () => { form.depth = depth.value; drawDepthExtra(); changed(); });
|
||||
lastPosts.addEventListener('input', () => { form.lastPosts = lastPosts.value === '' ? null : Number(lastPosts.value); changed(); });
|
||||
fromDate.addEventListener('input', () => { form.fromDate = fromDate.value || null; changed(); });
|
||||
const perDay = h('input', { type: 'number', min: '1', max: String(detail.maxBackfillPerDay), step: '1', value: form.backfillPerDay, id: 'al-giorno', inputmode: 'numeric' });
|
||||
perDay.addEventListener('input', () => { form.backfillPerDay = Number(perDay.value) || 0; changed(); });
|
||||
const maxVideo = h('input', { type: 'number', min: '1', step: '1', value: form.maxVideoMb ?? '', placeholder: t('impAccount.nessunLimite'), id: 'video-oltre', inputmode: 'decimal' });
|
||||
maxVideo.addEventListener('input', () => { form.maxVideoMb = maxVideo.value === '' ? null : Number(maxVideo.value); changed(); });
|
||||
const storyVideos = toggle({ checked: form.storyVideos, label: t('impAccount.videoStorie'), onchange: (v) => { form.storyVideos = v; changed(); } });
|
||||
drawDepthExtra();
|
||||
|
||||
// Cartella.
|
||||
const folderValue = h('span.val', detail.folder);
|
||||
const folderActions = h('div', { style: { display: 'contents' } });
|
||||
function drawFolder(path) {
|
||||
folderValue.textContent = path;
|
||||
const items = [];
|
||||
if (!c.foldersReadOnly && c.pickFolder) {
|
||||
items.push(h('button.btn', { type: 'button', onclick: pickFolder }, t('impAccount.cambia')));
|
||||
if (form.folder) items.push(h('button.btn.nudo', { type: 'button', onclick: () => { form.folder = null; drawFolder(t('impAccount.predefinita')); changed(); } }, t('impAccount.predefinita')));
|
||||
}
|
||||
fill(folderActions, items);
|
||||
}
|
||||
async function pickFolder() {
|
||||
try {
|
||||
const result = await api(`/api/accounts/${account.id}/pick-folder`, { method: 'POST' });
|
||||
if (result.message) {
|
||||
form.folder = result.message;
|
||||
drawFolder(result.message);
|
||||
changed();
|
||||
}
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
drawFolder(detail.folder);
|
||||
|
||||
fill(left,
|
||||
account.state === 'archiveOnly' ? h('div.avviso', { style: { marginBottom: '12px' } }, icon('archive', 's'), h('span', t('impAccount.archivio'))) : null,
|
||||
h('div.sezione', keep, h('p.aiuto', { style: { margin: '6px 0 0 46px' } }, t('impAccount.tieniAiuto'))),
|
||||
h('div.sezione', h('h2.sez', t('impAccount.frequenza')), h('div.frequenza', frequency, frequencyNote), customFields),
|
||||
h('div.sezione', h('h2.sez', t('impAccount.cosa')), h('p.aiuto', t('impAccount.cosaAiuto')), types),
|
||||
h('div.sezione', h('h2.sez', t('impAccount.limiti')), h('p.aiuto', t('impAccount.limitiAiuto')),
|
||||
h('div.riga-campi',
|
||||
h('div', h('label.etichetta', { for: 'profondita' }, t('impAccount.quanto')), h('label.campo.scelta', depth, icon('chevron-down', 's'))),
|
||||
h('div', h('label.etichetta', { for: 'al-giorno' }, t('impAccount.storicoGiorno')), h('label.campo', perDay, h('span.unita', t('impAccount.post')))),
|
||||
h('div', h('label.etichetta', { for: 'video-oltre' }, t('impAccount.saltaVideo')), h('label.campo', maxVideo, h('span.unita', t('impAccount.mb'))))),
|
||||
h('div.riga-campi', depthExtra),
|
||||
h('div', { style: { marginTop: '14px' } }, storyVideos)),
|
||||
h('div.sezione', h('h2.sez', t('impAccount.cartella')), h('p.aiuto', t(c.foldersReadOnly ? 'impAccount.cartellaDocker' : 'impAccount.cartellaAiuto')),
|
||||
h('div.cartella', h('div.campo.sola', icon('folder', 's'), folderValue), folderActions)));
|
||||
|
||||
function drawPlan() {
|
||||
const lines = plan.lines.map((l) => {
|
||||
const body = h('div', h('b', l.title), ' ', l.text);
|
||||
if (l.key === 'load') {
|
||||
const ratio = Math.min(1, plan.share || 0);
|
||||
body.append(h('div.misura', { role: 'meter', 'aria-valuemin': '0', 'aria-valuemax': String(plan.dailyBudget), 'aria-valuenow': String(Math.round(plan.opensPerDay)), 'aria-label': l.title },
|
||||
h('i', { style: { width: `${Math.max(2, ratio * 100)}%` } })),
|
||||
h('small', t('impAccount.caricoMisura', { usati: decimal(plan.opensPerDay, plan.opensPerDay < 10 ? 1 : 0), totale: number(plan.dailyBudget) })));
|
||||
body.classList.add('carico');
|
||||
}
|
||||
return h('div.voce-piano', icon(PLAN_ICONS[l.key] || 'info', 's'), body);
|
||||
});
|
||||
fill(planBox,
|
||||
h('div.pannello', h('h2', t('impAccount.piano')), lines),
|
||||
plan.warnings.map((w) => h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', w))),
|
||||
plan.note ? h('div.avviso', icon('info', 's'), h('span', plan.note)) : null);
|
||||
}
|
||||
drawPlan();
|
||||
|
||||
function drawSaveBar() {
|
||||
if (!dirty()) {
|
||||
page.saveBar(null);
|
||||
return;
|
||||
}
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', t('impAccount.modifiche')),
|
||||
h('div.destra',
|
||||
h('button.btn', { type: 'button', onclick: () => { leaveAllowed = true; navigate(location.pathname + location.search, { replace: true }); } }, t('impAccount.annulla')),
|
||||
h('button.btn.primo', { type: 'button', onclick: save }, icon('check'), t('impAccount.salva')))));
|
||||
}
|
||||
|
||||
async function save() {
|
||||
try {
|
||||
const updated = await api(`/api/accounts/${account.id}/settings`, { method: 'PUT', body: form });
|
||||
toast(t('impAccount.salvate', { nome: account.username }));
|
||||
leaveAllowed = true;
|
||||
refreshEngine();
|
||||
navigate(location.pathname + location.search, { replace: true });
|
||||
void updated;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
let leaveAllowed = false;
|
||||
page.guard(async () => {
|
||||
if (leaveAllowed || !dirty()) return true;
|
||||
const choice = await confirmDialog({
|
||||
title: t('impAccount.modifiche'),
|
||||
text: t('impAccount.esci'),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
|
||||
{ label: t('impAccount.lascia'), value: true, kind: 'pericolo' },
|
||||
],
|
||||
});
|
||||
if (choice) leaveAllowed = true;
|
||||
return Boolean(choice);
|
||||
});
|
||||
const beforeUnload = (e) => {
|
||||
if (dirty() && !leaveAllowed) {
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', beforeUnload);
|
||||
page.onLeave(() => {
|
||||
recompute.cancel();
|
||||
window.removeEventListener('beforeunload', beforeUnload);
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- history
|
||||
|
||||
async function historyTab(page, detail) {
|
||||
page.body.style.paddingTop = '16px';
|
||||
const tbody = h('tbody');
|
||||
const more = h('button.btn', { type: 'button', hidden: true }, t('cronologia.altri'));
|
||||
fill(page.body, h('div.cronologia',
|
||||
h('div.pannello', h('table.tab', h('caption.vh', t('cronologia.titolo')), tbody)),
|
||||
h('div', { style: { marginTop: '14px' } }, more)));
|
||||
let before = null;
|
||||
const today = caps().today;
|
||||
function when(local) {
|
||||
if (local.dayDelta === 0) return `${t('tempo.oggi')}, ${local.clock}`;
|
||||
if (local.dayDelta === -1) return `${t('tempo.ieri')}, ${local.clock}`;
|
||||
return `${shortDay(local.day, today)}, ${local.clock}`;
|
||||
}
|
||||
async function load() {
|
||||
try {
|
||||
const data = await api(`/api/accounts/${detail.account.id}/history${before ? `?before=${before}` : ''}`, { signal: page.signal });
|
||||
if (!data.items.length && !before) {
|
||||
fill(page.body, h('div.vuoto-pagina', icon('history'), h('p', t('cronologia.vuota'))));
|
||||
return;
|
||||
}
|
||||
for (const item of data.items) {
|
||||
const split = item.message.indexOf(': ');
|
||||
const text = split > 0 ? item.message.slice(split + 2) : item.message;
|
||||
const code = item.code.startsWith('ricetta.') ? item.code.slice('ricetta.'.length) : item.code === 'account.pausa' ? 'pausa' : 'altro';
|
||||
const kindLabel = t(`cronologia.ricette.${code}`) === `cronologia.ricette.${code}` ? t('cronologia.ricette.altro') : t(`cronologia.ricette.${code}`);
|
||||
const outcome = { success: ['verde', 'circle-check'], warning: ['ambra', 'triangle-alert'], error: ['rosso', 'octagon-alert'], info: ['', 'check'] }[item.severity] || ['', 'check'];
|
||||
tbody.append(h('tr',
|
||||
h('td.quando-cella.dati', when(item.at)),
|
||||
h('td', h('b', { style: { fontWeight: '600' } }, kindLabel), h('div.muto', { style: { fontSize: '13px' } }, capitalize(text))),
|
||||
h('td', { style: { textAlign: 'right' } }, h(`span.et${outcome[0] ? '.' + outcome[0] : ''}`, icon(outcome[1]), t(`cronologia.esiti.${item.severity}`)))));
|
||||
}
|
||||
before = data.before;
|
||||
more.hidden = !before;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
more.addEventListener('click', load);
|
||||
await load();
|
||||
void serverNow;
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
// Account (mockup 03, spec §4.2): table with avatar, name and labels, the five «Raccoglie» icons, state with its
|
||||
// second line and the history progress, last and next check, entries in the library, «Tieni aggiornato» acting at
|
||||
// once, the row menu; filter chips with counts, search, sort, «Aggiungi account». A click on a row opens the card.
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { caps, serverNow } from '../core/context.js';
|
||||
import { h, icon, fill, later, local } from '../core/dom.js';
|
||||
import { refreshEngine, engineState } from '../core/engine.js';
|
||||
import { navigate, setQuery } from '../core/shell.js';
|
||||
import { t, number, ago, around, shortDay } from '../core/text.js';
|
||||
import { avatar, label, menu, toggle, toast, showError, confirmDialog, dialog, radio } from '../core/ui.js';
|
||||
import { openAddAccounts } from './add-accounts.js';
|
||||
|
||||
const FILTERS = ['tutti', 'upToDate', 'backfilling', 'paused', 'archiveOnly', 'needsAttention'];
|
||||
const SORTS = ['ultimo', 'prossimo', 'nome', 'libreria', 'aggiunta'];
|
||||
const TYPES = [
|
||||
{ key: 'photos', icon: 'image' },
|
||||
{ key: 'videos', icon: 'clapperboard' },
|
||||
{ key: 'stories', icon: 'circle-dashed' },
|
||||
{ key: 'highlights', icon: 'star' },
|
||||
{ key: 'tagged', icon: 'square-user' },
|
||||
];
|
||||
|
||||
/** Labels under the name: «Tu», «Privato», «Pubblico», «Seguito», «Non seguito», «Solo archivio». */
|
||||
export function accountLabels(a) {
|
||||
if (a.isMine) return [label(t('account.etichette.tu'), 'accento')];
|
||||
if (a.state === 'archiveOnly') return [label(t('account.etichette.archivio'))];
|
||||
return [
|
||||
a.isPrivate ? label(t('account.etichette.privato'), '', 'lock') : label(t('account.etichette.pubblico')),
|
||||
a.isFollowed ? label(t('account.etichette.seguito')) : label(t('account.etichette.nonSeguito')),
|
||||
];
|
||||
}
|
||||
|
||||
/** True while the engine does not work (stopped, paused, not connected): «Prossimo» says «Sospeso». */
|
||||
function suspended() {
|
||||
const state = engineState();
|
||||
return Boolean(state && ['StoppedForVerification', 'Disconnected', 'NotConnected', 'Paused', 'Throttled', 'Off'].includes(state.snapshot.mode));
|
||||
}
|
||||
|
||||
/** Dot colour of an account state. */
|
||||
export function stateDot(state) {
|
||||
return { upToDate: 'verde', backfilling: 'accento', unreachable: 'ambra' }[state] || '';
|
||||
}
|
||||
|
||||
/** The second line of the state: news of today, history progress, why paused or unreachable. */
|
||||
export function stateLine(a) {
|
||||
switch (a.state) {
|
||||
case 'backfilling': {
|
||||
const text = a.postCount ? t('account.sotto.storico', { fatti: number(a.posts), totale: number(a.postCount) }) : t('account.sotto.storicoSenzaTotale', { fatti: number(a.posts) });
|
||||
return a.backfillResumesTomorrow ? t('account.sotto.riprendeDomani', { testo: text }) : text;
|
||||
}
|
||||
case 'paused':
|
||||
return a.stateChanged ? t('account.sotto.pausa', { giorno: shortDay(a.stateChanged.day, caps().today) }) : t('account.sotto.pausaSenzaData');
|
||||
case 'unreachable':
|
||||
return t(`account.sotto.${a.unreachableReason || 'privateNotFollowed'}`);
|
||||
case 'archiveOnly':
|
||||
return t('account.sotto.maiContattato');
|
||||
default: {
|
||||
if (a.notices.includes('renamed') && a.previousUsername) return t('account.sotto.rinominato', { nome: a.previousUsername });
|
||||
if (a.notices.includes('unrecognizedFormat')) return t('account.sotto.formato');
|
||||
if (a.newPostsToday && a.newStoriesToday) {
|
||||
return t('account.sotto.nuoviEntrambi', { post: t('account.sotto.post', { n: a.newPostsToday }), storie: t('account.sotto.storie', { n: a.newStoriesToday }) });
|
||||
}
|
||||
if (a.newPostsToday) return t('account.sotto.nuoviPost', { n: a.newPostsToday });
|
||||
if (a.newStoriesToday) return t('account.sotto.nuoveStorie', { n: a.newStoriesToday });
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** «Controlla ora» (spec §7.8): outside the active window Febe asks for a confirmation and then does that one check. */
|
||||
export async function checkNow(account, token = null) {
|
||||
try {
|
||||
const result = await api(`/api/accounts/${account.id}/check-now`, { method: 'POST', body: token ? { token } : {} });
|
||||
if (result.status === 'needsConfirmation') {
|
||||
const ok = await confirmDialog({
|
||||
title: t('account.controlla.titolo'),
|
||||
text: result.message,
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo' },
|
||||
{ label: t('account.controlla.conferma', { nome: account.username }), value: true, kind: 'primo', autofocus: true },
|
||||
],
|
||||
});
|
||||
if (ok) await checkNow(account, result.token);
|
||||
return;
|
||||
}
|
||||
toast(result.message, result.status === 'refused' ? 'errore' : '');
|
||||
refreshEngine();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** «Rimuovi»: always asks whether to keep or delete the files; keeping them (the default) makes it «Solo archivio». */
|
||||
export async function removeAccount(account) {
|
||||
let choice = 'tieni';
|
||||
const confirmButton = h('button.btn.primo', { type: 'button' }, t('account.rimuovi.confermaTieni'));
|
||||
const result = await dialog({
|
||||
title: t('account.rimuovi.titolo', { nome: account.username }),
|
||||
className: 'piccolo',
|
||||
build: (close) => {
|
||||
const set = (value) => {
|
||||
choice = value;
|
||||
confirmButton.className = value === 'elimina' ? 'btn pericolo pieno' : 'btn primo';
|
||||
confirmButton.textContent = t(value === 'elimina' ? 'account.rimuovi.confermaElimina' : 'account.rimuovi.confermaTieni');
|
||||
};
|
||||
confirmButton.addEventListener('click', () => close(choice));
|
||||
return {
|
||||
body: h('div.contenuto', h('p', t('account.rimuovi.testo')), h('div.scelte',
|
||||
radio({ name: 'rimuovi', value: 'tieni', checked: true, onchange: set, labelNode: h('span', h('b', t('account.rimuovi.tieni')), h('small', t('account.rimuovi.tieniSpiega'))) }),
|
||||
radio({ name: 'rimuovi', value: 'elimina', onchange: set, labelNode: h('span', h('b', t('account.rimuovi.elimina')), h('small', t('account.rimuovi.eliminaSpiega', { elementi: t('comune.elementi', { n: account.inLibrary }) }))) }))),
|
||||
footer: h('footer', h('div.destra', h('button.btn.nudo', { type: 'button', onclick: () => close(undefined) }, t('comune.annulla')), confirmButton)),
|
||||
};
|
||||
},
|
||||
});
|
||||
if (!result) return false;
|
||||
try {
|
||||
const answer = await api(`/api/accounts/${account.id}/remove`, { method: 'POST', body: { deleteFiles: result === 'elimina' } });
|
||||
toast(answer.message, answer.problems ? 'errore' : '');
|
||||
return answer.outcome;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The menu of a row (and of the account card). */
|
||||
export function accountMenu(anchor, account, after) {
|
||||
const items = [
|
||||
{ label: t('account.menu.controlla'), value: 'check', icon: 'refresh-cw', disabled: account.state === 'archiveOnly' || account.unreachableReason === 'privateNotFollowed' },
|
||||
account.state === 'paused'
|
||||
? { label: t('account.menu.riattiva'), value: 'resume', icon: 'play' }
|
||||
: { label: t('account.menu.pausa'), value: 'pause', icon: 'pause', disabled: account.state === 'archiveOnly' },
|
||||
{ label: t('account.menu.apri'), value: 'open', icon: 'external-link' },
|
||||
];
|
||||
if (!account.isMine) items.push('hr', { label: t('account.menu.rimuovi'), value: 'remove', icon: 'trash-2', danger: true });
|
||||
menu(anchor, items, async (value) => {
|
||||
try {
|
||||
if (value === 'check') await checkNow(account);
|
||||
if (value === 'pause' || value === 'resume') {
|
||||
const result = await api(`/api/accounts/${account.id}/${value}`, { method: 'POST' });
|
||||
toast(result.message);
|
||||
refreshEngine();
|
||||
}
|
||||
if (value === 'open') openProfile(account);
|
||||
if (value === 'remove') {
|
||||
const outcome = await removeAccount(account);
|
||||
if (outcome && after) after(outcome);
|
||||
return;
|
||||
}
|
||||
if (after) after(value);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}, { align: 'right' });
|
||||
}
|
||||
|
||||
/** The profile in Alberto's own browser. */
|
||||
export function openProfile(account) {
|
||||
const url = `https://www.instagram.com/${encodeURIComponent(account.username)}/`;
|
||||
if (caps().openUrlNative) api(`/api/accounts/${account.id}/open-on-instagram`, { method: 'POST' }).catch(showError);
|
||||
else window.open(url, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
|
||||
export default {
|
||||
async mount(page, route) {
|
||||
let data = null;
|
||||
let filter = FILTERS.includes(route.query.get('filtro')) ? route.query.get('filtro') : 'tutti';
|
||||
let sort = local.get('account.ordine', 'ultimo');
|
||||
if (!SORTS.includes(sort)) sort = 'ultimo';
|
||||
let term = '';
|
||||
|
||||
page.title(t('account.titolo'), '');
|
||||
const search = h('input', { type: 'search', placeholder: t('account.cerca'), 'aria-label': t('account.cerca') });
|
||||
const addButton = h('button.btn.primo', { type: 'button', onclick: () => add() }, icon('plus'), t('account.aggiungi'));
|
||||
page.actions(h('label.campo.cerca', { style: { width: '240px' } }, icon('search'), search), addButton);
|
||||
|
||||
const chips = h('div.filtri', { role: 'group', 'aria-label': t('account.colonne.stato') });
|
||||
const sortButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '240px' } });
|
||||
page.tools(h('div', { style: { display: 'contents' } }, chips, h('div.destra', sortButton)));
|
||||
const tbody = h('tbody');
|
||||
const table = h('div.pannello.tabella-account', h('table.tab',
|
||||
h('thead', h('tr',
|
||||
h('th', { scope: 'col' }, t('account.colonne.account')),
|
||||
h('th.col-raccoglie', { scope: 'col' }, t('account.colonne.raccoglie')),
|
||||
h('th.col-stato', { scope: 'col' }, t('account.colonne.stato')),
|
||||
h('th.col-ultimo', { scope: 'col' }, t('account.colonne.ultimo')),
|
||||
h('th.col-prossimo', { scope: 'col' }, t('account.colonne.prossimo')),
|
||||
h('th.col-libreria.num', { scope: 'col' }, t('account.colonne.libreria')),
|
||||
h('th.col-tieni', { scope: 'col' }, t('account.colonne.tieni')),
|
||||
h('th', { scope: 'col' }, h('span.vh', t('account.colonne.azioni'))))),
|
||||
tbody));
|
||||
fill(page.body, table);
|
||||
|
||||
function drawChips() {
|
||||
const counts = data.counts;
|
||||
const value = { tutti: counts.all, upToDate: counts.upToDate, backfilling: counts.backfilling, paused: counts.paused, archiveOnly: counts.archiveOnly, needsAttention: counts.needsAttention };
|
||||
fill(chips, FILTERS.map((f) => h(`button${f === filter ? '.qui' : ''}`, {
|
||||
type: 'button', 'aria-pressed': String(f === filter),
|
||||
onclick: () => {
|
||||
filter = f;
|
||||
setQuery({ filtro: f === 'tutti' ? null : f });
|
||||
draw();
|
||||
},
|
||||
}, t(`account.filtri.${f}`), h('i', number(value[f])))));
|
||||
fill(sortButton, h('span.val', t(`account.ordina.${sort}`)), icon('chevron-down', 's'));
|
||||
}
|
||||
|
||||
function sorted(list) {
|
||||
const by = {
|
||||
ultimo: (a, b) => (b.lastCheck || 0) - (a.lastCheck || 0),
|
||||
prossimo: (a, b) => (a.nextCheck ? a.nextCheck.ms : Infinity) - (b.nextCheck ? b.nextCheck.ms : Infinity),
|
||||
nome: (a, b) => a.username.localeCompare(b.username),
|
||||
libreria: (a, b) => b.inLibrary - a.inLibrary,
|
||||
aggiunta: (a, b) => b.addedAt - a.addedAt,
|
||||
}[sort];
|
||||
return [...list].sort((a, b) => (b.isMine - a.isMine) || by(a, b) || a.username.localeCompare(b.username));
|
||||
}
|
||||
|
||||
function visible() {
|
||||
const q = term.toLowerCase().replace(/^@/, '');
|
||||
return sorted(data.accounts.filter((a) => {
|
||||
if (filter === 'needsAttention' ? !a.needsAttention : filter !== 'tutti' && a.state !== filter) return false;
|
||||
return !q || a.username.includes(q) || (a.displayName || '').toLowerCase().includes(q);
|
||||
}));
|
||||
}
|
||||
|
||||
function rowOf(a) {
|
||||
const types = TYPES.map((x) => {
|
||||
const on = a.types[x.key];
|
||||
const name = t(`account.raccoglie.${x.key}`);
|
||||
const svg = icon(x.icon, 's');
|
||||
if (!on) svg.classList.add('spento');
|
||||
return h('span', { title: t(on ? 'account.raccoglie.attivo' : 'account.raccoglie.spento', { tipo: name }), role: 'img', 'aria-label': t(on ? 'account.raccoglie.attivo' : 'account.raccoglie.spento', { tipo: name }) }, svg);
|
||||
});
|
||||
const line = stateLine(a);
|
||||
const progress = a.state === 'backfilling' && a.postCount
|
||||
? h('div.misura.fine', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': String(a.postCount), 'aria-valuenow': String(a.posts), 'aria-label': t('account.stati.backfilling') },
|
||||
h('i', { style: { width: `${Math.min(100, (a.posts / a.postCount) * 100)}%` } }))
|
||||
: null;
|
||||
const sw = toggle({
|
||||
checked: a.keptUpdated,
|
||||
label: t('account.tieniEtichetta', { nome: a.username }),
|
||||
hiddenLabel: true,
|
||||
disabled: a.state === 'archiveOnly',
|
||||
onchange: async (value, input) => {
|
||||
try {
|
||||
const result = await api(`/api/accounts/${a.id}/keep-updated`, { method: 'POST', body: { value } });
|
||||
toast(result.message);
|
||||
await reload();
|
||||
refreshEngine();
|
||||
} catch (error) {
|
||||
input.checked = !value;
|
||||
showError(error);
|
||||
}
|
||||
},
|
||||
});
|
||||
if (a.state === 'archiveOnly') sw.querySelector('.int').classList.add('fermo');
|
||||
const more = h('button.btn.nudo.solo', { type: 'button', 'aria-label': `${t('comune.menu')}: @${a.username}`, 'aria-haspopup': 'true' }, icon('ellipsis'));
|
||||
more.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
accountMenu(more, a, () => reload());
|
||||
});
|
||||
const href = withCarried(`/account/${a.id}`);
|
||||
const tr = h('tr', { dataset: { id: String(a.id) } },
|
||||
h('td', h('div.nome', avatar(a.username, '', a.avatar), h('div',
|
||||
h('b', h('a', { href, style: { color: 'inherit', textDecoration: 'none' } }, `@${a.username}`)),
|
||||
h('div.sotto', a.isMine ? t('account.sotto.tuo') : a.displayName, accountLabels(a))))),
|
||||
h('td.col-raccoglie', h('div.raccoglie', types)),
|
||||
h('td.col-stato', h('div.condizione', h('div.riga', h(`span.spia${stateDot(a.state) ? '.' + stateDot(a.state) : ''}`, { 'aria-hidden': 'true' }), t(`account.stati.${a.state}`)),
|
||||
line ? h('div.sotto', line) : null, progress)),
|
||||
h('td.col-ultimo.dati.muto-cella', a.lastCheck ? ago(a.lastCheck, serverNow(), caps().today) : ''),
|
||||
h('td.col-prossimo.dati.muto-cella', a.nextCheck ? (suspended() ? t('account.sospeso') : around(a.nextCheck)) : ''),
|
||||
h('td.col-libreria.num.dati', number(a.inLibrary)),
|
||||
h('td.col-tieni', sw),
|
||||
h('td.menu-riga', more));
|
||||
tr.addEventListener('click', (e) => {
|
||||
if (e.target.closest('a,button,label,input')) return;
|
||||
navigate(`/account/${a.id}`);
|
||||
});
|
||||
return tr;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (!data) return;
|
||||
page.count(t('account.quanti', { account: t('comune.account', { n: data.counts.all }), tenuti: number(data.counts.keptUpdated) }));
|
||||
drawChips();
|
||||
const rows = visible();
|
||||
if (!data.accounts.length) {
|
||||
fill(page.body, h('div.vuoto-pagina', icon('users'), h('h2', t('account.vuoto')), h('p', t('account.vuotoTesto')),
|
||||
h('button.btn.primo', { type: 'button', onclick: () => add() }, icon('plus'), t('account.aggiungi'))));
|
||||
return;
|
||||
}
|
||||
if (!table.isConnected) fill(page.body, table);
|
||||
fill(tbody, rows.length ? rows.map(rowOf) : h('tr', h('td', { colspan: '8' }, h('div.caricamento', t('account.nessunoFiltro')))));
|
||||
}
|
||||
|
||||
let loadedAt = 0;
|
||||
async function reload() {
|
||||
loadedAt = Date.now();
|
||||
try {
|
||||
data = await api('/api/accounts', { signal: page.signal });
|
||||
draw();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function add() {
|
||||
const added = await openAddAccounts();
|
||||
setQuery({ dialogo: null });
|
||||
if (added) await reload();
|
||||
}
|
||||
|
||||
sortButton.addEventListener('click', () => menu(sortButton,
|
||||
SORTS.map((s) => ({ label: t(`account.ordina.${s}`), value: s, checked: s === sort, radio: true })),
|
||||
(value) => {
|
||||
sort = value;
|
||||
local.set('account.ordine', sort);
|
||||
draw();
|
||||
}, { align: 'right' }));
|
||||
const onSearch = later(() => {
|
||||
term = search.value.trim();
|
||||
draw();
|
||||
}, 150);
|
||||
search.addEventListener('input', onSearch);
|
||||
const onChange = later(reload, 600);
|
||||
page.onLibrary(onChange);
|
||||
page.onLeave(() => {
|
||||
onSearch.cancel();
|
||||
onChange.cancel();
|
||||
});
|
||||
// «Ultimo controllo» and «verso le» stay current: the engine pushes its state at least every minute.
|
||||
page.onEngine(() => {
|
||||
if (Date.now() - loadedAt > 55000) reload();
|
||||
});
|
||||
|
||||
await reload();
|
||||
if (route.query.get('dialogo') === 'aggiungi') add();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,233 @@
|
||||
// «Aggiungi account» (mockup 04, spec §4.2): from the local copy of the list of followed profiles (with its reading
|
||||
// date and progress; it is read again only on request) or by user name, one per line; the three starting points on
|
||||
// the right; the button says how many accounts it adds.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill, later } from '../core/dom.js';
|
||||
import { t, number, shortDay } from '../core/text.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { avatar, checkbox, dialog, label, showError, toast } from '../core/ui.js';
|
||||
|
||||
const STARTS = ['everything', 'newOnly', 'storiesOnly'];
|
||||
const DEPTHS = [
|
||||
{ key: 'all', depth: 'all' },
|
||||
{ key: 'last50', depth: 'lastPosts', lastPosts: 50 },
|
||||
{ key: 'last200', depth: 'lastPosts', lastPosts: 200 },
|
||||
{ key: 'last1000', depth: 'lastPosts', lastPosts: 1000 },
|
||||
{ key: 'year', depth: 'fromDate' },
|
||||
];
|
||||
|
||||
/** Opens the dialog; resolves to true when accounts were added. */
|
||||
export function openAddAccounts() {
|
||||
return dialog({
|
||||
title: t('aggiungi.titolo'),
|
||||
className: 'aggiungi',
|
||||
build: (close) => build(close),
|
||||
});
|
||||
}
|
||||
|
||||
function build(close) {
|
||||
let tab = 'seguiti';
|
||||
let following = null;
|
||||
let parsed = { names: [], problems: [] };
|
||||
const chosen = new Set();
|
||||
let start = 'everything';
|
||||
let depth = 'all';
|
||||
|
||||
const tabFollowed = h('button', { type: 'button', role: 'tab', class: 'qui', 'aria-selected': 'true' }, t('aggiungi.seguiti'), h('i'));
|
||||
const tabNames = h('button', { type: 'button', role: 'tab', 'aria-selected': 'false' }, t('aggiungi.perNome'));
|
||||
const tabs = h('div.linguette', { role: 'tablist' }, tabFollowed, tabNames);
|
||||
const left = h('div.sinistra', { role: 'tabpanel' });
|
||||
const right = h('div.destra-dialogo');
|
||||
const footerLeft = h('div', { style: { display: 'flex', alignItems: 'center', gap: '12px', fontSize: '13px', color: 'var(--testo-2)' } });
|
||||
const addButton = h('button.btn.primo', { type: 'button', disabled: true, onclick: submit });
|
||||
|
||||
// ---------------------------------------------------------------------------- left: followed profiles
|
||||
const search = h('input', { type: 'search', placeholder: t('aggiungi.cerca'), 'aria-label': t('aggiungi.cerca') });
|
||||
const allButton = h('button.btn', { type: 'button' }, t('aggiungi.selezionaTutti'));
|
||||
const list = h('div.elenco', { role: 'group', 'aria-label': t('aggiungi.seguiti') });
|
||||
const progress = h('div.avanzamento', { role: 'status' });
|
||||
const followedPanel = h('div', { style: { display: 'contents' } }, h('div.cerca-riga', h('label.campo', icon('search'), search), allButton), list, progress);
|
||||
|
||||
// ---------------------------------------------------------------------------- left: by user name
|
||||
const area = h('textarea', { rows: '8', spellcheck: 'false', autocapitalize: 'off', 'aria-describedby': 'aiuto-nomi', placeholder: 'marta.demo\n@luca.viaggi.demo\ninstagram.com/studio.lumen.demo' });
|
||||
const parsedInfo = h('div.riconosciuti', { role: 'status' });
|
||||
const problems = h('div.problemi');
|
||||
const namesPanel = h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px', paddingBottom: '14px', overflow: 'auto' } },
|
||||
h('label.etichetta', t('aggiungi.area')),
|
||||
h('label.campo.area', area),
|
||||
h('p.aiuto', { id: 'aiuto-nomi' }, t('aggiungi.areaAiuto')),
|
||||
parsedInfo, problems);
|
||||
|
||||
function present(p) {
|
||||
return p.accountId != null;
|
||||
}
|
||||
|
||||
function drawList() {
|
||||
if (!following) {
|
||||
fill(list, h('div.caricamento', t('comune.caricamento')));
|
||||
return;
|
||||
}
|
||||
const term = search.value.trim().toLowerCase().replace(/^@/, '');
|
||||
const shown = following.profiles.filter((p) => !term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term));
|
||||
if (!shown.length) {
|
||||
fill(list, h('div.caricamento', following.profiles.length ? t('aggiungi.nessunSeguito') : t('aggiungi.maiLetto')));
|
||||
return;
|
||||
}
|
||||
fill(list, shown.map((p) => {
|
||||
const isPresent = present(p);
|
||||
const box = checkbox({
|
||||
checked: isPresent || chosen.has(p.username),
|
||||
disabled: isPresent,
|
||||
labelNode: h('span', { style: { display: 'contents' } },
|
||||
avatar(p.username, 'm'),
|
||||
h('span.chi-nome', h('b', `@${p.username}`), p.displayName ? h('small', p.displayName) : null),
|
||||
isPresent ? label(t('aggiungi.giaPresente')) : p.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
|
||||
onchange: (on) => {
|
||||
if (on) chosen.add(p.username);
|
||||
else chosen.delete(p.username);
|
||||
drawRight();
|
||||
},
|
||||
});
|
||||
box.classList.toggle('presente', isPresent);
|
||||
return box;
|
||||
}));
|
||||
}
|
||||
|
||||
function drawProgress() {
|
||||
if (!following) return;
|
||||
progress.hidden = !following.inProgress;
|
||||
fill(progress, following.inProgress
|
||||
? [icon('hourglass', 's'), following.readSoFar ? t('aggiungi.avanzamento', { n: number(following.readSoFar) }) : t('aggiungi.inAttesa')]
|
||||
: []);
|
||||
fill(footerLeft,
|
||||
h('span', following.readDay ? t('aggiungi.lettoIl', { giorno: shortDay(following.readDay, caps().today) }) : t('aggiungi.maiLetto')),
|
||||
h('button.btn.collegamento', { type: 'button', disabled: following.inProgress, onclick: reread, title: t('aggiungi.rilettura') },
|
||||
icon('refresh-cw', 's'), following.readDay ? t('aggiungi.rileggi') : t('aggiungi.leggi')));
|
||||
const count = tabFollowed.querySelector('i');
|
||||
count.textContent = number(following.total);
|
||||
}
|
||||
|
||||
async function loadFollowing() {
|
||||
try {
|
||||
following = await api('/api/following');
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
following = { profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 };
|
||||
}
|
||||
drawList();
|
||||
drawProgress();
|
||||
drawRight();
|
||||
}
|
||||
|
||||
async function reread() {
|
||||
try {
|
||||
following = await api('/api/following/read', { method: 'POST' });
|
||||
drawProgress();
|
||||
drawList();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
allButton.addEventListener('click', () => {
|
||||
if (!following) return;
|
||||
const term = search.value.trim().toLowerCase().replace(/^@/, '');
|
||||
const shown = following.profiles.filter((p) => !present(p) && (!term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term)));
|
||||
const all = shown.every((p) => chosen.has(p.username));
|
||||
for (const p of shown) {
|
||||
if (all) chosen.delete(p.username);
|
||||
else chosen.add(p.username);
|
||||
}
|
||||
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
|
||||
drawList();
|
||||
drawRight();
|
||||
});
|
||||
search.addEventListener('input', later(drawList, 120));
|
||||
|
||||
const parse = later(async () => {
|
||||
try {
|
||||
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text: area.value } });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
}
|
||||
const ready = parsed.names.filter((n) => !n.present);
|
||||
const already = parsed.names.length - ready.length;
|
||||
fill(parsedInfo, area.value.trim() ? [t('aggiungi.riconosciuti', { n: ready.length }), already ? ` · ${t('aggiungi.presenti', { n: already })}` : ''] : '');
|
||||
fill(problems, parsed.problems.map((p) => h('div', t('aggiungi.riga', { n: p.line, motivo: `«${p.text}»: ${p.reason}` }))));
|
||||
drawRight();
|
||||
}, 250);
|
||||
area.addEventListener('input', parse);
|
||||
|
||||
// ---------------------------------------------------------------------------- right: starting point
|
||||
function selection() {
|
||||
return tab === 'seguiti' ? [...chosen] : parsed.names.filter((n) => !n.present).map((n) => n.username);
|
||||
}
|
||||
|
||||
function drawRight() {
|
||||
const n = selection().length;
|
||||
const perDay = following && following.backfillPerDay ? following.backfillPerDay : 300;
|
||||
const startInputs = STARTS.map((s) => {
|
||||
const input = h('input.vh', { type: 'radio', name: 'partenza', value: s, checked: s === start });
|
||||
input.addEventListener('change', () => {
|
||||
start = s;
|
||||
drawRight();
|
||||
});
|
||||
return h('label', input, h('span.tondo', { 'aria-hidden': 'true' }),
|
||||
h('span', h('b', t(`aggiungi.partenze.${s}`)), h('small', t(`aggiungi.partenze.${s}Spiega`))));
|
||||
});
|
||||
const select = h('select', { 'aria-label': t('aggiungi.quanto') }, DEPTHS.map((d) => h('option', { value: d.key, selected: d.key === depth }, t(`aggiungi.profondita.${d.key}`))));
|
||||
select.addEventListener('change', () => {
|
||||
depth = select.value;
|
||||
});
|
||||
fill(right,
|
||||
h('h2.sez', n ? t('aggiungi.perScelti', { n }) : t('aggiungi.perNessuno')),
|
||||
h('p.aiuto', t('aggiungi.potraiCambiare')),
|
||||
h('div.partenza', { role: 'radiogroup', 'aria-label': t('aggiungi.potraiCambiare') }, startInputs),
|
||||
start === 'everything' ? [h('label.etichetta', { for: 'profondita' }, t('aggiungi.quanto')), h('label.campo.scelta', select, icon('chevron-down', 's'))] : null,
|
||||
h('div.avviso', { style: { marginTop: '14px' } }, icon('info', 's'),
|
||||
h('span', start === 'everything' ? t('aggiungi.info', { n: number(perDay) }) : t('aggiungi.infoNovita'))));
|
||||
select.id = 'profondita';
|
||||
addButton.disabled = n === 0;
|
||||
addButton.textContent = t('aggiungi.conferma', { n });
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const usernames = selection();
|
||||
if (!usernames.length) return;
|
||||
const d = DEPTHS.find((x) => x.key === depth) || DEPTHS[0];
|
||||
addButton.disabled = true;
|
||||
try {
|
||||
const result = await api('/api/accounts', { method: 'POST', body: { usernames, start, depth: start === 'everything' ? d.depth : null, lastPosts: d.lastPosts || null } });
|
||||
toast(result.message);
|
||||
close(result.added > 0);
|
||||
} catch (error) {
|
||||
addButton.disabled = false;
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function setTab(value) {
|
||||
tab = value;
|
||||
tabFollowed.classList.toggle('qui', value === 'seguiti');
|
||||
tabNames.classList.toggle('qui', value === 'nomi');
|
||||
tabFollowed.setAttribute('aria-selected', String(value === 'seguiti'));
|
||||
tabNames.setAttribute('aria-selected', String(value === 'nomi'));
|
||||
fill(left, value === 'seguiti' ? followedPanel : namesPanel);
|
||||
footerLeft.hidden = value !== 'seguiti';
|
||||
drawRight();
|
||||
(value === 'seguiti' ? search : area).focus();
|
||||
}
|
||||
tabFollowed.addEventListener('click', () => setTab('seguiti'));
|
||||
tabNames.addEventListener('click', () => setTab('nomi'));
|
||||
|
||||
fill(left, followedPanel);
|
||||
drawList();
|
||||
drawRight();
|
||||
loadFollowing();
|
||||
return {
|
||||
body: h('div', { style: { display: 'contents' } }, tabs, h('div.corpo-dialogo', left, right)),
|
||||
footer: h('footer', footerLeft, h('div.destra', h('button.btn', { type: 'button', onclick: () => close(false) }, t('comune.annulla')), addButton)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
// Libreria (mockup 01, spec §4.6): every entry by publication day, filters by kind, account, period and provenance,
|
||||
// search by account name and caption, tile size, multiple selection to export or delete, viewer on click.
|
||||
|
||||
import { api, download } from '../core/api.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { h, icon, fill, later, local } from '../core/dom.js';
|
||||
import { setQuery } from '../core/shell.js';
|
||||
import { t, number, shortDay, parseDay } from '../core/text.js';
|
||||
import { menu, showError, toast, confirmDialog } from '../core/ui.js';
|
||||
import { Mosaic } from './mosaic.js';
|
||||
import { openViewer } from './viewer.js';
|
||||
|
||||
const KINDS = [
|
||||
{ key: 'tutto', api: 'all', label: 'libreria.tipi.all' },
|
||||
{ key: 'foto', api: 'photos', label: 'libreria.tipi.photos' },
|
||||
{ key: 'video', api: 'videos', label: 'libreria.tipi.videos' },
|
||||
{ key: 'storie', api: 'stories', label: 'libreria.tipi.stories' },
|
||||
{ key: 'evidenza', api: 'highlights', label: 'libreria.tipi.highlights' },
|
||||
{ key: 'taggati', api: 'tagged', label: 'libreria.tipi.tagged' },
|
||||
];
|
||||
|
||||
const PERIODS = ['settimana', 'mese', 'anno', 'annoScorso'];
|
||||
|
||||
/** The filter of the page address (Italian names) as the query of the API. */
|
||||
export function apiQuery(state, today) {
|
||||
const q = new URLSearchParams();
|
||||
const kind = KINDS.find((k) => k.key === state.tipo);
|
||||
if (kind && kind.api !== 'all') q.set('kind', kind.api);
|
||||
if (state.account) q.set('accounts', state.account);
|
||||
const range = periodRange(state, today);
|
||||
if (range.from) q.set('from', range.from);
|
||||
if (range.to) q.set('to', range.to);
|
||||
if (state.provenienza === 'importati') q.set('provenance', 'imported');
|
||||
if (state.provenienza === 'scaricati') q.set('provenance', 'downloaded');
|
||||
if (state.q) q.set('q', state.q);
|
||||
return q.toString();
|
||||
}
|
||||
|
||||
function addDays(day, n) {
|
||||
return new Date(Date.parse(`${day}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function periodRange(state, today) {
|
||||
if (state.dal || state.al) return { from: state.dal || null, to: state.al || null };
|
||||
const year = today ? parseDay(today).y : new Date().getFullYear();
|
||||
switch (state.periodo) {
|
||||
case 'settimana': return { from: addDays(today, -6), to: today };
|
||||
case 'mese': return { from: addDays(today, -29), to: today };
|
||||
case 'anno': return { from: `${year}-01-01`, to: today };
|
||||
case 'annoScorso': return { from: `${year - 1}-01-01`, to: `${year - 1}-12-31` };
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
function readState(query) {
|
||||
return {
|
||||
tipo: query.get('tipo') || 'tutto',
|
||||
account: query.get('account') || '',
|
||||
periodo: query.get('periodo') || '',
|
||||
dal: query.get('dal') || '',
|
||||
al: query.get('al') || '',
|
||||
provenienza: query.get('provenienza') || '',
|
||||
q: query.get('q') || '',
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
async mount(page, route) {
|
||||
const state = readState(route.query);
|
||||
const today = () => caps().today || new Date().toISOString().slice(0, 10);
|
||||
let accounts = null;
|
||||
let mosaic = null;
|
||||
|
||||
page.title(t('libreria.titolo'), '');
|
||||
const search = h('input', { type: 'search', placeholder: t('libreria.cerca'), 'aria-label': t('libreria.cerca'), value: state.q });
|
||||
// In a narrow window the field is short: the placeholder becomes «Cerca» (the accessible name stays complete).
|
||||
const narrow = window.matchMedia('(max-width: 1000px)');
|
||||
const placeholder = () => { search.placeholder = t(narrow.matches ? 'libreria.cercaBreve' : 'libreria.cerca'); };
|
||||
placeholder();
|
||||
narrow.addEventListener('change', placeholder, { signal: page.signal });
|
||||
page.actions(h('label.campo.cerca', icon('search'), search));
|
||||
|
||||
// Tools: kind chips, the three menus, tile size, selection.
|
||||
const chips = h('div.filtri', { role: 'group', 'aria-label': t('libreria.filtriTipo') });
|
||||
const accountButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '118px' } });
|
||||
const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '111px' } });
|
||||
const provenanceButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '141px' } });
|
||||
const filtersButton = h('button.btn.solo-stretto', { type: 'button', 'aria-haspopup': 'true' }, icon('list-filter'), t('libreria.filtri'));
|
||||
const size = local.get('libreria.tessere', 160);
|
||||
const slider = h('input.cursore', { type: 'range', min: '96', max: '300', step: '4', value: String(size), 'aria-label': t('libreria.grandezza') });
|
||||
const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona')));
|
||||
page.tools(h('div', { style: { display: 'contents' } },
|
||||
chips,
|
||||
h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton),
|
||||
filtersButton,
|
||||
h('div.destra',
|
||||
h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')),
|
||||
selectButton)));
|
||||
|
||||
const host = h('div');
|
||||
fill(page.body, host);
|
||||
|
||||
function filtersActive() {
|
||||
return state.tipo !== 'tutto' || state.account || state.periodo || state.dal || state.al || state.provenienza || state.q;
|
||||
}
|
||||
|
||||
function drawChips() {
|
||||
fill(chips, KINDS.map((k) => h(`button${k.key === state.tipo ? '.qui' : ''}`, {
|
||||
type: 'button',
|
||||
'aria-pressed': String(k.key === state.tipo),
|
||||
onclick: () => {
|
||||
state.tipo = k.key;
|
||||
apply();
|
||||
},
|
||||
}, t(k.label))));
|
||||
}
|
||||
|
||||
function menuLabel(button, text, chosen) {
|
||||
fill(button, h('span.val', text), icon('chevron-down', 's'));
|
||||
button.classList.toggle('attivo', Boolean(chosen));
|
||||
}
|
||||
|
||||
function drawMenus() {
|
||||
// A menu shows the name of its filter until a value is chosen (spec §10.3).
|
||||
const ids = state.account ? state.account.split(',') : [];
|
||||
let accountText = t('libreria.menuAccount');
|
||||
if (ids.length === 1 && accounts) {
|
||||
const a = accounts.find((x) => String(x.id) === ids[0]);
|
||||
accountText = a ? `@${a.username}` : t('libreria.accountScelti', { n: 1 });
|
||||
} else if (ids.length) accountText = t('libreria.accountScelti', { n: ids.length });
|
||||
menuLabel(accountButton, accountText, ids.length);
|
||||
let periodText = t('libreria.menuPeriodo');
|
||||
if (state.dal || state.al) periodText = t('libreria.periodi.date', { dal: state.dal ? shortDay(state.dal, today()) : '…', al: state.al ? shortDay(state.al, today()) : '…' });
|
||||
else if (state.periodo) periodText = t(`libreria.periodi.${state.periodo}`);
|
||||
menuLabel(periodButton, periodText, state.periodo || state.dal || state.al);
|
||||
menuLabel(provenanceButton, state.provenienza ? t(`libreria.provenienze.${state.provenienza === 'importati' ? 'imported' : 'downloaded'}`) : t('libreria.menuProvenienza'), state.provenienza);
|
||||
filtersButton.classList.toggle('primo', Boolean(state.account || state.periodo || state.dal || state.al || state.provenienza));
|
||||
}
|
||||
|
||||
async function loadAccounts() {
|
||||
if (!accounts) accounts = (await api('/api/accounts', { signal: page.signal })).accounts;
|
||||
return accounts;
|
||||
}
|
||||
|
||||
async function openAccounts(anchor) {
|
||||
try {
|
||||
await loadAccounts();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
}
|
||||
const chosen = new Set(state.account ? state.account.split(',') : []);
|
||||
const field = h('input', { type: 'search', placeholder: t('libreria.cercaAccount'), 'aria-label': t('libreria.cercaAccount') });
|
||||
const list = h('div');
|
||||
const header = h('div.cerca-menu', h('label.campo', icon('search', 's'), field));
|
||||
const drawList = () => {
|
||||
const term = field.value.trim().toLowerCase().replace(/^@/, '');
|
||||
const items = [
|
||||
h('button', { type: 'button', role: 'menuitemcheckbox', 'aria-checked': String(chosen.size === 0), onclick: () => { chosen.clear(); commit(); } },
|
||||
h('span', t('libreria.tuttiGliAccount')), icon('check', 's segno')),
|
||||
h('hr'),
|
||||
];
|
||||
const shown = accounts.filter((a) => !term || a.username.includes(term) || (a.displayName || '').toLowerCase().includes(term));
|
||||
for (const a of shown) {
|
||||
items.push(h('button', {
|
||||
type: 'button', role: 'menuitemcheckbox', 'aria-checked': String(chosen.has(String(a.id))),
|
||||
onclick: (e) => {
|
||||
const id = String(a.id);
|
||||
if (chosen.has(id)) chosen.delete(id);
|
||||
else chosen.add(id);
|
||||
e.currentTarget.setAttribute('aria-checked', String(chosen.has(id)));
|
||||
commit(false);
|
||||
},
|
||||
}, h('span', `@${a.username}`), icon('check', 's segno')));
|
||||
}
|
||||
if (!shown.length) items.push(h('div.vuoto', t('libreria.nessunAccount')));
|
||||
fill(list, items);
|
||||
};
|
||||
const commit = (close = true) => {
|
||||
state.account = [...chosen].join(',');
|
||||
if (close) handle.close();
|
||||
apply();
|
||||
};
|
||||
field.addEventListener('input', drawList);
|
||||
drawList();
|
||||
const handle = menu(anchor, [header, list], () => {}, { width: 280 });
|
||||
}
|
||||
|
||||
function openPeriod(anchor) {
|
||||
const from = h('input', { type: 'date', value: state.dal, 'aria-label': t('libreria.periodi.dal'), max: today() });
|
||||
const to = h('input', { type: 'date', value: state.al, 'aria-label': t('libreria.periodi.al'), max: today() });
|
||||
const items = [
|
||||
{ label: t('libreria.periodi.qualsiasi'), value: '', checked: !state.periodo && !state.dal && !state.al, radio: true },
|
||||
...PERIODS.map((p) => ({ label: t(`libreria.periodi.${p}`), value: p, checked: state.periodo === p, radio: true })),
|
||||
'hr',
|
||||
h('div.date', h('span', t('libreria.periodi.dal')), h('label.campo', from), h('span', t('libreria.periodi.al')), h('label.campo', to)),
|
||||
h('div', { style: { padding: '2px 6px 4px' } }, h('button.btn.piccolo', {
|
||||
type: 'button',
|
||||
onclick: () => {
|
||||
state.periodo = '';
|
||||
state.dal = from.value;
|
||||
state.al = to.value;
|
||||
handle.close();
|
||||
apply();
|
||||
},
|
||||
}, t('libreria.periodi.applica'))),
|
||||
];
|
||||
const handle = menu(anchor, items, (value) => {
|
||||
state.periodo = value;
|
||||
state.dal = '';
|
||||
state.al = '';
|
||||
apply();
|
||||
}, { width: 300 });
|
||||
}
|
||||
|
||||
function openProvenance(anchor) {
|
||||
menu(anchor, [
|
||||
{ label: t('libreria.provenienze.tutte'), value: '', checked: !state.provenienza, radio: true },
|
||||
{ label: t('libreria.provenienze.downloaded'), value: 'scaricati', checked: state.provenienza === 'scaricati', radio: true },
|
||||
{ label: t('libreria.provenienze.imported'), value: 'importati', checked: state.provenienza === 'importati', radio: true },
|
||||
], (value) => {
|
||||
state.provenienza = value;
|
||||
apply();
|
||||
});
|
||||
}
|
||||
|
||||
function openFilters(anchor) {
|
||||
// Narrow window: the three menus behind one button.
|
||||
menu(anchor, [
|
||||
{ label: accountButton.textContent, value: 'account', icon: 'users' },
|
||||
{ label: periodButton.textContent, value: 'periodo', icon: 'calendar' },
|
||||
{ label: provenanceButton.textContent, value: 'provenienza', icon: 'folder-input' },
|
||||
], (value) => {
|
||||
if (value === 'account') openAccounts(anchor);
|
||||
if (value === 'periodo') openPeriod(anchor);
|
||||
if (value === 'provenienza') openProvenance(anchor);
|
||||
});
|
||||
}
|
||||
|
||||
accountButton.addEventListener('click', () => openAccounts(accountButton));
|
||||
periodButton.addEventListener('click', () => openPeriod(periodButton));
|
||||
provenanceButton.addEventListener('click', () => openProvenance(provenanceButton));
|
||||
filtersButton.addEventListener('click', () => openFilters(filtersButton));
|
||||
slider.addEventListener('input', () => {
|
||||
const value = Number(slider.value);
|
||||
local.set('libreria.tessere', value);
|
||||
if (mosaic) mosaic.setRowHeight(value);
|
||||
});
|
||||
const onSearch = later(() => {
|
||||
state.q = search.value.trim();
|
||||
apply();
|
||||
}, 300);
|
||||
search.addEventListener('input', onSearch);
|
||||
page.onLeave(() => onSearch.cancel());
|
||||
|
||||
// Selection bar.
|
||||
function drawSelection(selected) {
|
||||
if (!mosaic || !mosaic.selecting) {
|
||||
page.saveBar(null);
|
||||
return;
|
||||
}
|
||||
const n = selected.size;
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', n ? t('selezione.scelti', { n }) : t('selezione.nessuno')),
|
||||
h('div.destra',
|
||||
h('button.btn.nudo', { type: 'button', onclick: () => setSelecting(false) }, t('selezione.annulla')),
|
||||
h('button.btn', { type: 'button', disabled: !n, onclick: () => exportSelected() }, icon('file-down'), t('selezione.esporta')),
|
||||
h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: () => deleteSelected() }, icon('trash-2'), t('selezione.elimina', { n })))));
|
||||
}
|
||||
|
||||
function setSelecting(on) {
|
||||
if (!mosaic) return;
|
||||
mosaic.setSelecting(on);
|
||||
selectButton.setAttribute('aria-pressed', String(on));
|
||||
fill(selectButton, icon(on ? 'check' : 'circle-check'), h('span', t(on ? 'libreria.fine' : 'libreria.seleziona')));
|
||||
drawSelection(mosaic.selected);
|
||||
}
|
||||
|
||||
selectButton.addEventListener('click', () => setSelecting(!mosaic.selecting));
|
||||
|
||||
async function exportSelected() {
|
||||
try {
|
||||
await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv');
|
||||
toast(t('selezione.esportato'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSelected() {
|
||||
const ids = [...mosaic.selected];
|
||||
const removed = await confirmDelete(ids);
|
||||
if (removed) {
|
||||
mosaic.removeTiles(removed);
|
||||
setSelecting(false);
|
||||
}
|
||||
}
|
||||
|
||||
// The mosaic.
|
||||
async function apply() {
|
||||
setQuery({
|
||||
tipo: state.tipo === 'tutto' ? null : state.tipo,
|
||||
account: state.account || null,
|
||||
periodo: state.periodo || null,
|
||||
dal: state.dal || null,
|
||||
al: state.al || null,
|
||||
provenienza: state.provenienza || null,
|
||||
q: state.q || null,
|
||||
});
|
||||
drawChips();
|
||||
drawMenus();
|
||||
if (mosaic) mosaic.destroy();
|
||||
page.body.scrollTop = 0;
|
||||
mosaic = new Mosaic({
|
||||
scroller: page.body,
|
||||
host,
|
||||
query: apiQuery(state, today()),
|
||||
rowHeight: Number(slider.value),
|
||||
signal: page.signal,
|
||||
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }),
|
||||
onSelection: drawSelection,
|
||||
onTotals: ({ entries, accounts: n }) => page.count(t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })),
|
||||
onEmpty: () => fill(host, filtersActive()
|
||||
? h('div.vuoto-pagina', icon('list-filter'), h('h2', t('libreria.nessuno')), h('p', t('libreria.nessunoTesto')),
|
||||
h('button.btn', { type: 'button', onclick: () => { Object.assign(state, readState(new URLSearchParams())); search.value = ''; apply(); } }, t('libreria.togliFiltri')))
|
||||
: h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')))),
|
||||
});
|
||||
try {
|
||||
await mosaic.start();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
drawSelection(mosaic.selected);
|
||||
}
|
||||
|
||||
const onLibraryChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 400);
|
||||
page.onLibrary(onLibraryChange);
|
||||
page.onLeave(() => {
|
||||
onLibraryChange.cancel();
|
||||
if (mosaic) mosaic.destroy();
|
||||
});
|
||||
loadAccounts().then(drawMenus).catch(() => {});
|
||||
await apply();
|
||||
void number;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* «Elimina dalla libreria» with the confirmation of spec §4.6: by default the choice is remembered (state «eliminato»,
|
||||
* never downloaded again); «Eliminalo e lascia che torni» forgets the entry. Returns the deleted keys, or null.
|
||||
*/
|
||||
export async function confirmDelete(ids) {
|
||||
const n = ids.length;
|
||||
const mode = await confirmDialog({
|
||||
title: t('elimina.titolo', { n }),
|
||||
text: t('elimina.testo', { n }),
|
||||
extra: h('p.aiuto', t('elimina.tornaSpiega')),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: undefined, kind: 'nudo' },
|
||||
{ label: t('elimina.torna', { n }), value: 'allowReturn' },
|
||||
{ label: t('elimina.conferma'), value: 'remember', kind: 'pericolo pieno', autofocus: true },
|
||||
],
|
||||
});
|
||||
if (!mode) return null;
|
||||
try {
|
||||
const result = await api('/api/entries/delete', { method: 'POST', body: { ids, mode } });
|
||||
toast(result.message, result.problems.length ? 'errore' : '');
|
||||
return ids;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
// The mosaic of the library (mockup 01) and of the account tabs (mockup 12): entries grouped by day, justified rows
|
||||
// that keep the proportions of the pictures with 4 px between tiles, or a regular 9:16 grid for stories.
|
||||
// Fluid with 200,000 entries: the page knows only how many entries each day has (one cheap query); a day group is
|
||||
// fetched (keyset windows) and drawn only when it comes near the visible area, and emptied again when it goes far,
|
||||
// keeping its height. Changes of height above the visible area are compensated, so nothing moves under the eyes.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill, perFrame } from '../core/dom.js';
|
||||
import { t, dayName, duration, capitalize } from '../core/text.js';
|
||||
import { avatar } from '../core/ui.js';
|
||||
|
||||
const GAP = 4;
|
||||
const NEAR = '1400px 0px';
|
||||
const FAR = '7000px 0px';
|
||||
|
||||
function aspectOf(tile) {
|
||||
const c = tile.cover;
|
||||
if (!c || !c.width || !c.height) return 1;
|
||||
return Math.min(2.2, Math.max(0.5, c.width / c.height));
|
||||
}
|
||||
|
||||
function older(a, b) {
|
||||
// true when tile a comes after tile b in display order (published earlier, or same time and smaller id)
|
||||
return a.publishedAt < b.publishedAt || (a.publishedAt === b.publishedAt && a.id < b.id);
|
||||
}
|
||||
|
||||
export function cursorOf(tile) {
|
||||
return `${tile.publishedAt}.${tile.id}`;
|
||||
}
|
||||
|
||||
/** Justified rows: every full row exactly fills the width; the last row keeps the target height. */
|
||||
export function justify(tiles, width, target) {
|
||||
const rows = [];
|
||||
let row = [];
|
||||
let sum = 0;
|
||||
for (const tile of tiles) {
|
||||
const ar = aspectOf(tile);
|
||||
row.push({ tile, ar });
|
||||
sum += ar;
|
||||
const full = sum * target + GAP * (row.length - 1);
|
||||
if (full >= width) {
|
||||
const withLast = (width - GAP * (row.length - 1)) / sum;
|
||||
const withoutLast = row.length > 1 ? (width - GAP * (row.length - 2)) / (sum - ar) : Infinity;
|
||||
if (row.length > 1 && Math.abs(withoutLast - target) < Math.abs(withLast - target) && withoutLast < target * 1.4) {
|
||||
const last = row.pop();
|
||||
rows.push({ items: row, height: withoutLast, full: true });
|
||||
row = [last];
|
||||
sum = last.ar;
|
||||
} else {
|
||||
rows.push({ items: row, height: withLast, full: true });
|
||||
row = [];
|
||||
sum = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (row.length) rows.push({ items: row, height: target, full: false });
|
||||
for (const r of rows) {
|
||||
let used = 0;
|
||||
r.items.forEach((item, i) => {
|
||||
item.width = Math.max(24, Math.round(item.ar * r.height));
|
||||
used += item.width + (i > 0 ? GAP : 0);
|
||||
});
|
||||
if (r.full && r.items.length) r.items[r.items.length - 1].width += width - used;
|
||||
r.height = Math.round(r.height);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** A tile: thumbnail, marks top-right, on hover account and time, selection circle. */
|
||||
export function tileElement(tile, width, height, { selected = false, today = '', ring = true } = {}) {
|
||||
const cover = tile.cover;
|
||||
const marks = [];
|
||||
if (tile.kind === 'story' && ring) marks.push(h('span.anello', { title: t('libreria.tipiTessera.story') }, icon('circle-dashed')));
|
||||
if (cover && cover.kind === 'video') marks.push(h('span', icon('play'), duration(cover.duration || 0)));
|
||||
if (tile.files > 1) marks.push(h('span', icon('layers'), String(tile.files)));
|
||||
const when = tile.day === today ? `${t('tempo.oggi')}, ${tile.time}` : `${dayName(tile.day, today)}, ${tile.time}`;
|
||||
const description = [t('libreria.tessera', { tipo: t(`libreria.tipiTessera.${tile.kind}`), account: tile.username, quando: when })];
|
||||
if (tile.files > 1) description.push(t('libreria.tesseraFile', { n: tile.files }));
|
||||
if (cover && cover.kind === 'video') description.push(t('libreria.tesseraDurata', { durata: duration(cover.duration || 0) }));
|
||||
const el = h(`button.tess${selected ? '.scelta' : ''}`, {
|
||||
type: 'button',
|
||||
style: { width: `${width}px`, height: `${height}px` },
|
||||
dataset: { id: String(tile.id) },
|
||||
'aria-label': description.join(', '),
|
||||
'aria-pressed': selected ? 'true' : null,
|
||||
},
|
||||
cover && cover.thumb
|
||||
? h('img', { src: `/api/thumbnails/${cover.thumb}`, alt: '', loading: 'lazy', decoding: 'async', draggable: 'false' })
|
||||
: h('span.tess.vuota', { style: { width: '100%', height: '100%' } }, icon('image')),
|
||||
marks.length ? h('span.segno', marks) : null,
|
||||
h('span.sel', { role: 'checkbox', 'aria-checked': String(selected), 'aria-label': t('libreria.scegliTessera'), title: t('libreria.scegliTessera') }, icon('check')),
|
||||
h('span.chi', avatar(tile.username, 'p'), h('span', `@${tile.username}`), h('small', tile.day === today ? `${t('tempo.oggi')}, ${tile.time}` : tile.time)));
|
||||
return el;
|
||||
}
|
||||
|
||||
/** The default day header: «Oggi martedì 13 ottobre, 14 nuovi elementi». */
|
||||
export function defaultDayLabel(day, count, today) {
|
||||
const name = dayName(day, today);
|
||||
if (day === today) return [t('tempo.Oggi'), t('libreria.giornoNuovi', { giorno: name, n: t('libreria.nuoviOggi', { n: count }) })];
|
||||
const yesterday = new Date(Date.parse(`${today}T12:00:00Z`) - 86400000).toISOString().slice(0, 10);
|
||||
if (day === yesterday) return [t('tempo.Ieri'), t('libreria.giornoNuovi', { giorno: name, n: t('libreria.elementiGiorno', { n: count }) })];
|
||||
return [capitalize(name), t('libreria.elementiGiorno', { n: count })];
|
||||
}
|
||||
|
||||
export class Mosaic {
|
||||
/**
|
||||
* scroller: the scrolling element (.corpo); host: where the groups go; query: filter as a query string;
|
||||
* mode: 'justified' or 'grid' (9:16 stories); rowHeight: target height of the rows;
|
||||
* onOpen(tile), onSelection(set), onTotals({ entries, accounts, today }), onEmpty(), dayLabel(day, count, today).
|
||||
*/
|
||||
constructor(options) {
|
||||
this.scroller = options.scroller;
|
||||
this.host = options.host;
|
||||
this.query = options.query || '';
|
||||
this.mode = options.mode || 'justified';
|
||||
this.rowHeight = options.rowHeight || 160;
|
||||
this.onOpen = options.onOpen || (() => {});
|
||||
this.onSelection = options.onSelection || (() => {});
|
||||
this.onTotals = options.onTotals || (() => {});
|
||||
this.onEmpty = options.onEmpty || (() => {});
|
||||
this.dayLabel = options.dayLabel || defaultDayLabel;
|
||||
this.signal = options.signal;
|
||||
this.sections = [];
|
||||
this.byDay = new Map();
|
||||
this.selected = new Set();
|
||||
this.selecting = false;
|
||||
this.today = '';
|
||||
this.avgAspect = this.mode === 'grid' ? 0.5625 : 0.95;
|
||||
this.width = 0;
|
||||
this.pendingNew = 0;
|
||||
this.root = h('div.mosaico');
|
||||
this.pill = h('div.nuovi-in-cima', { hidden: true });
|
||||
fill(this.host, this.pill, this.root);
|
||||
this.near = new IntersectionObserver((entries) => this.onNear(entries), { root: this.scroller, rootMargin: NEAR });
|
||||
this.far = new IntersectionObserver((entries) => this.onFar(entries), { root: this.scroller, rootMargin: FAR });
|
||||
this.resize = new ResizeObserver(perFrame(() => this.onResize()));
|
||||
this.resize.observe(this.root);
|
||||
this.root.addEventListener('click', (e) => this.onClick(e));
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.near.disconnect();
|
||||
this.far.disconnect();
|
||||
this.resize.disconnect();
|
||||
}
|
||||
|
||||
/** 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 });
|
||||
this.today = data.today;
|
||||
this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today });
|
||||
this.width = this.root.clientWidth || this.host.clientWidth || 800;
|
||||
for (const section of this.sections) this.unobserve(section);
|
||||
this.sections = [];
|
||||
this.byDay.clear();
|
||||
this.root.replaceChildren();
|
||||
for (const day of data.days) this.root.append(this.createSection(day).el);
|
||||
if (!data.days.length) this.onEmpty();
|
||||
}
|
||||
|
||||
createSection(day) {
|
||||
const section = { day: day.day, count: day.count, cursor: day.cursor, tiles: [], complete: false, loading: null, rendered: false, near: false, stale: false };
|
||||
const [bold, rest] = this.dayLabel(day.day, day.count, this.today);
|
||||
section.header = h('header.giorno', h('b', bold), rest ? h('span', rest) : null);
|
||||
section.rows = h('div.righe', { style: { height: `${this.estimate(day.count)}px` } });
|
||||
section.el = h('section.gruppo-giorno', { dataset: { day: day.day }, 'aria-label': `${bold} ${rest || ''}` }, section.header, section.rows);
|
||||
this.byDay.set(day.day, section);
|
||||
this.sections.push(section);
|
||||
this.near.observe(section.el);
|
||||
this.far.observe(section.el);
|
||||
return section;
|
||||
}
|
||||
|
||||
unobserve(section) {
|
||||
this.near.unobserve(section.el);
|
||||
this.far.unobserve(section.el);
|
||||
}
|
||||
|
||||
estimate(count) {
|
||||
const width = Math.max(200, this.width || 800);
|
||||
if (this.mode === 'grid') {
|
||||
const tileHeight = Math.round(this.rowHeight * 1.25);
|
||||
const perRow = Math.max(1, Math.floor((width + GAP) / (Math.round(tileHeight * 0.5625) + GAP)));
|
||||
return Math.ceil(count / perRow) * (tileHeight + GAP);
|
||||
}
|
||||
const rows = Math.max(1, Math.ceil((count * this.avgAspect * this.rowHeight) / width));
|
||||
return rows * (this.rowHeight * 0.96 + GAP);
|
||||
}
|
||||
|
||||
onNear(entries) {
|
||||
for (const entry of entries) {
|
||||
const section = this.sections.find((s) => s.el === entry.target);
|
||||
if (!section) continue;
|
||||
section.near = entry.isIntersecting;
|
||||
if (entry.isIntersecting) this.wake(section);
|
||||
}
|
||||
}
|
||||
|
||||
onFar(entries) {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) continue;
|
||||
const section = this.sections.find((s) => s.el === entry.target);
|
||||
if (section && section.rendered) this.unrender(section);
|
||||
}
|
||||
}
|
||||
|
||||
async wake(section) {
|
||||
try {
|
||||
while (!section.complete && section.near) await this.load(section);
|
||||
if (section.near && !section.rendered && section.el.isConnected) this.render(section);
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetches the next window from where a group is, and hands the tiles to every group they belong to. */
|
||||
load(section) {
|
||||
if (section.loading) return section.loading;
|
||||
const missing = section.count - section.tiles.length;
|
||||
const limit = Math.min(600, Math.max(120, missing + 40));
|
||||
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) => {
|
||||
const touched = new Set();
|
||||
for (const tile of page.tiles) {
|
||||
const target = this.byDay.get(tile.day);
|
||||
if (!target || target.complete) continue;
|
||||
const last = target.tiles[target.tiles.length - 1];
|
||||
if (last && !older(tile, last)) continue;
|
||||
target.tiles.push(tile);
|
||||
touched.add(target);
|
||||
}
|
||||
if (!page.older) {
|
||||
const index = this.sections.indexOf(section);
|
||||
for (const s of this.sections.slice(index)) s.complete = true;
|
||||
}
|
||||
for (const s of touched) {
|
||||
if (s.tiles.length >= s.count) s.complete = true;
|
||||
this.learn(s.tiles);
|
||||
}
|
||||
if (!touched.has(section) && !section.complete) section.complete = true; // nothing more for this day
|
||||
for (const s of touched) if (s !== section && s.near && s.complete && !s.rendered) this.render(s);
|
||||
})
|
||||
.finally(() => {
|
||||
section.loading = null;
|
||||
});
|
||||
return section.loading;
|
||||
}
|
||||
|
||||
learn(tiles) {
|
||||
if (this.mode === 'grid' || !tiles.length) return;
|
||||
const sample = tiles.slice(0, 200);
|
||||
const mean = sample.reduce((a, tile) => a + aspectOf(tile), 0) / sample.length;
|
||||
this.avgAspect = this.avgAspect * 0.7 + mean * 0.3;
|
||||
}
|
||||
|
||||
/** Runs fn and keeps what is visible in place when a group above the visible area changes height. */
|
||||
keepView(section, fn) {
|
||||
const scrollerTop = this.scroller.getBoundingClientRect().top;
|
||||
const rect = section.el.getBoundingClientRect();
|
||||
const above = rect.bottom <= scrollerTop + 1;
|
||||
const before = section.el.offsetHeight;
|
||||
fn();
|
||||
const after = section.el.offsetHeight;
|
||||
if (above && after !== before) this.scroller.scrollTop += after - before;
|
||||
}
|
||||
|
||||
render(section) {
|
||||
const width = this.root.clientWidth || this.width;
|
||||
this.width = width;
|
||||
const rows = this.layout(section.tiles, width);
|
||||
const nodes = rows.map((row) => h(this.mode === 'grid' ? 'div.griglia-storie' : 'div.fila',
|
||||
row.items.map((item) => tileElement(item.tile, item.width, row.height, { selected: this.selected.has(item.tile.id), today: this.today, ring: this.mode !== 'grid' }))));
|
||||
this.keepView(section, () => {
|
||||
section.rows.style.height = '';
|
||||
fill(section.rows, nodes);
|
||||
section.rendered = true;
|
||||
section.renderedWidth = width;
|
||||
});
|
||||
}
|
||||
|
||||
layout(tiles, width) {
|
||||
if (this.mode !== 'grid') return justify(tiles, width, this.rowHeight);
|
||||
const height = Math.round(this.rowHeight * 1.25);
|
||||
const w = Math.round(height * 0.5625);
|
||||
const perRow = Math.max(1, Math.floor((width + GAP) / (w + GAP)));
|
||||
const rows = [];
|
||||
for (let i = 0; i < tiles.length; i += perRow) rows.push({ height, items: tiles.slice(i, i + perRow).map((tile) => ({ tile, width: w })) });
|
||||
return rows;
|
||||
}
|
||||
|
||||
unrender(section) {
|
||||
const height = section.rows.offsetHeight;
|
||||
section.rows.style.height = `${height}px`;
|
||||
section.rows.replaceChildren();
|
||||
section.rendered = false;
|
||||
}
|
||||
|
||||
onResize() {
|
||||
const width = this.root.clientWidth;
|
||||
if (!width || Math.abs(width - this.width) < 2) return;
|
||||
this.relayout(width);
|
||||
}
|
||||
|
||||
/** Lays everything out again (new width or new tile size), keeping the group at the top of the view in place. */
|
||||
relayout(width = this.root.clientWidth) {
|
||||
const anchor = this.topSection();
|
||||
const offset = anchor ? this.scroller.scrollTop - anchor.el.offsetTop : 0;
|
||||
const ratio = anchor && anchor.el.offsetHeight ? offset / anchor.el.offsetHeight : 0;
|
||||
this.width = width;
|
||||
for (const section of this.sections) {
|
||||
if (section.rendered) this.render(section);
|
||||
else section.rows.style.height = `${this.estimate(section.count)}px`;
|
||||
}
|
||||
if (anchor) this.scroller.scrollTop = anchor.el.offsetTop + ratio * anchor.el.offsetHeight;
|
||||
}
|
||||
|
||||
setRowHeight(height) {
|
||||
this.rowHeight = height;
|
||||
this.relayout();
|
||||
}
|
||||
|
||||
topSection() {
|
||||
const top = this.scroller.getBoundingClientRect().top;
|
||||
return this.sections.find((s) => s.el.getBoundingClientRect().bottom > top + 1) || null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- selection and clicks
|
||||
|
||||
setSelecting(on) {
|
||||
this.selecting = on;
|
||||
this.root.classList.toggle('scegli', on);
|
||||
if (!on) this.clearSelection();
|
||||
}
|
||||
|
||||
clearSelection() {
|
||||
this.selected.clear();
|
||||
for (const el of this.root.querySelectorAll('.tess.scelta')) this.markTile(el, false);
|
||||
this.onSelection(this.selected);
|
||||
}
|
||||
|
||||
markTile(el, on) {
|
||||
el.classList.toggle('scelta', on);
|
||||
el.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||||
const sel = el.querySelector('.sel');
|
||||
if (sel) sel.setAttribute('aria-checked', String(on));
|
||||
}
|
||||
|
||||
toggle(id, el) {
|
||||
const on = !this.selected.has(id);
|
||||
if (on) this.selected.add(id);
|
||||
else this.selected.delete(id);
|
||||
if (el) this.markTile(el, on);
|
||||
if (!this.selecting && on) this.setSelecting(true);
|
||||
this.onSelection(this.selected);
|
||||
}
|
||||
|
||||
onClick(e) {
|
||||
const el = e.target.closest('.tess[data-id]');
|
||||
if (!el) return;
|
||||
const id = Number(el.dataset.id);
|
||||
if (e.target.closest('.sel') || this.selecting) {
|
||||
e.preventDefault();
|
||||
this.toggle(id, el);
|
||||
return;
|
||||
}
|
||||
const tile = this.findTile(id);
|
||||
if (tile) this.onOpen(tile);
|
||||
}
|
||||
|
||||
findTile(id) {
|
||||
for (const s of this.sections) {
|
||||
const tile = s.tiles.find((x) => x.id === id);
|
||||
if (tile) return tile;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- viewer navigation
|
||||
|
||||
/** Position of an entry among all the entries of the filter (1-based) and the total. */
|
||||
position(id) {
|
||||
let before = 0;
|
||||
for (const s of this.sections) {
|
||||
const i = s.tiles.findIndex((x) => x.id === id);
|
||||
if (i >= 0) return { index: before + i + 1, total: this.sections.reduce((a, x) => a + x.count, 0) };
|
||||
before += s.count;
|
||||
}
|
||||
return { index: 0, total: this.sections.reduce((a, x) => a + x.count, 0) };
|
||||
}
|
||||
|
||||
/** The entry before (delta −1) or after (+1) an entry, loading the next group when needed. */
|
||||
async neighbor(id, delta) {
|
||||
let si = this.sections.findIndex((s) => s.tiles.some((x) => x.id === id));
|
||||
if (si < 0) return null;
|
||||
let i = this.sections[si].tiles.findIndex((x) => x.id === id) + delta;
|
||||
for (;;) {
|
||||
const s = this.sections[si];
|
||||
if (i >= 0 && i < s.tiles.length) return s.tiles[i];
|
||||
if (delta > 0 && !s.complete) {
|
||||
await this.load(s);
|
||||
continue;
|
||||
}
|
||||
si += delta;
|
||||
if (si < 0 || si >= this.sections.length) return null;
|
||||
const next = this.sections[si];
|
||||
if (!next.complete && next.tiles.length === 0) await this.load(next);
|
||||
i = delta > 0 ? 0 : next.tiles.length - 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Scrolls so that an entry is visible (after the viewer moved far). */
|
||||
reveal(id) {
|
||||
const el = this.root.querySelector(`.tess[data-id="${id}"]`);
|
||||
if (el) el.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- changes
|
||||
|
||||
/** Removes entries (after a deletion) and updates the counts of their days. */
|
||||
removeTiles(ids) {
|
||||
const set = new Set(ids);
|
||||
for (const s of [...this.sections]) {
|
||||
const before = s.tiles.length;
|
||||
s.tiles = s.tiles.filter((x) => !set.has(x.id));
|
||||
const removed = before - s.tiles.length;
|
||||
if (!removed) continue;
|
||||
s.count -= removed;
|
||||
for (const id of ids) this.selected.delete(id);
|
||||
if (s.count <= 0) {
|
||||
this.unobserve(s);
|
||||
this.keepView(s, () => s.el.remove());
|
||||
this.sections.splice(this.sections.indexOf(s), 1);
|
||||
this.byDay.delete(s.day);
|
||||
continue;
|
||||
}
|
||||
const [bold, rest] = this.dayLabel(s.day, s.count, this.today);
|
||||
fill(s.header, h('b', bold), rest ? h('span', rest) : null);
|
||||
if (s.rendered) this.render(s);
|
||||
}
|
||||
this.onSelection(this.selected);
|
||||
}
|
||||
|
||||
/**
|
||||
* The library changed: new days appear at the top and changed days are reloaded, without moving what is on screen.
|
||||
* A group being looked at is not redrawn under the eyes: «N nuovi elementi in cima» offers to show them.
|
||||
*/
|
||||
async refresh() {
|
||||
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
|
||||
this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today });
|
||||
const todayChanged = data.today !== this.today;
|
||||
this.today = data.today;
|
||||
const wanted = new Map(data.days.map((d) => [d.day, d]));
|
||||
let added = 0;
|
||||
for (const s of [...this.sections]) {
|
||||
if (!wanted.has(s.day)) {
|
||||
this.unobserve(s);
|
||||
this.keepView(s, () => s.el.remove());
|
||||
this.sections.splice(this.sections.indexOf(s), 1);
|
||||
this.byDay.delete(s.day);
|
||||
}
|
||||
}
|
||||
let previous = null;
|
||||
for (const day of data.days) {
|
||||
let s = this.byDay.get(day.day);
|
||||
if (!s) {
|
||||
s = this.createSection(day);
|
||||
this.sections.splice(previous ? this.sections.indexOf(previous) + 1 : 0, 0, ...this.sections.splice(this.sections.indexOf(s), 1));
|
||||
const anchor = previous ? previous.el.nextSibling : this.root.firstChild;
|
||||
this.keepView(s, () => this.root.insertBefore(s.el, anchor));
|
||||
added += day.count;
|
||||
} else if (s.count !== day.count || todayChanged) {
|
||||
const grew = day.count - s.count;
|
||||
if (s.rendered && this.isVisible(s)) {
|
||||
s.stale = day;
|
||||
if (grew > 0) added += grew;
|
||||
} else {
|
||||
this.reset(s, day);
|
||||
}
|
||||
}
|
||||
previous = s;
|
||||
}
|
||||
if (added > 0) this.showPill(added);
|
||||
if (!this.sections.length) this.onEmpty();
|
||||
}
|
||||
|
||||
reset(s, day) {
|
||||
s.count = day.count;
|
||||
s.cursor = day.cursor;
|
||||
s.tiles = [];
|
||||
s.complete = false;
|
||||
s.stale = false;
|
||||
const [bold, rest] = this.dayLabel(s.day, s.count, this.today);
|
||||
fill(s.header, h('b', bold), rest ? h('span', rest) : null);
|
||||
if (s.rendered) {
|
||||
this.keepView(s, () => {
|
||||
s.rows.style.height = `${this.estimate(s.count)}px`;
|
||||
s.rows.replaceChildren();
|
||||
s.rendered = false;
|
||||
});
|
||||
}
|
||||
if (s.near) this.wake(s);
|
||||
}
|
||||
|
||||
isVisible(s) {
|
||||
const top = this.scroller.getBoundingClientRect();
|
||||
const rect = s.el.getBoundingClientRect();
|
||||
return rect.bottom > top.top && rect.top < top.bottom;
|
||||
}
|
||||
|
||||
showPill(count) {
|
||||
if (this.scroller.scrollTop < 4 && !this.sections.some((s) => s.stale)) return;
|
||||
this.pendingNew += count;
|
||||
fill(this.pill, h('button.btn', {
|
||||
type: 'button',
|
||||
onclick: () => {
|
||||
for (const s of this.sections) if (s.stale) this.reset(s, s.stale);
|
||||
this.pendingNew = 0;
|
||||
this.pill.hidden = true;
|
||||
this.scroller.scrollTo({ top: 0 });
|
||||
},
|
||||
}, icon('arrow-left', 's'), t('libreria.nuoviInCima', { n: this.pendingNew })));
|
||||
this.pill.querySelector('svg').style.transform = 'rotate(90deg)';
|
||||
this.pill.hidden = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Pages that arrive with the second part of the interface (Attività, Importa, Impostazioni, Browser), and the page for
|
||||
// unknown addresses. The next agent replaces each route of js/routes.js with its own module.
|
||||
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { withCarried } from '../core/api.js';
|
||||
import { t } from '../core/text.js';
|
||||
|
||||
export default {
|
||||
mount(page, route) {
|
||||
const key = route.params.key;
|
||||
if (key === 'nonTrovata') {
|
||||
page.title(t('pagine.nonTrovata'));
|
||||
fill(page.body, h('div.vuoto-pagina', icon('info'), h('h2', t('pagine.nonTrovata')), h('p', t('pagine.nonTrovataTesto')),
|
||||
h('a.btn', { href: withCarried('/libreria') }, t('pagine.vaiLibreria'))));
|
||||
return;
|
||||
}
|
||||
const title = route.params.section ? `${t('pagine.impostazioni')}: ${t(`pagine.sezioni.${route.params.section}`)}` : t(`pagine.${key}`);
|
||||
page.title(title);
|
||||
fill(page.body, h('div.vuoto-pagina.prossimamente', icon('hourglass'), h('h2', title), h('p', t('pagine.prossimamente'))));
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,265 @@
|
||||
// Visualizzatore (mockup 02, spec §4.6): covers the whole window; arrows and arrow keys move through the files of the
|
||||
// series and then to the next entry; Esc closes; videos start muted. The side panel shows the data, the files and the
|
||||
// provenance, and the actions: «Mostra nella cartella» (desktop) or «Scarica» (browser), «Apri su Instagram» (in
|
||||
// Alberto's own browser, never in Febe's), «Elimina dalla libreria».
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { caps, serverNow } from '../core/context.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { t, dayName, capitalize, bytes, duration, number, ago, shortDay } from '../core/text.js';
|
||||
import { avatar, label, showError, toast } from '../core/ui.js';
|
||||
import { confirmDelete } from './library.js';
|
||||
|
||||
const KIND_ICON = { post: 'image', story: 'circle-dashed', highlight: 'star', tagged: 'square-user', profile: 'circle-user' };
|
||||
|
||||
/**
|
||||
* Opens the viewer on a tile. source: { position(id), neighbor(id, delta), reveal(id) } (the mosaic, or a plain list).
|
||||
* origin: «Libreria» or the account name. onDeleted(ids): called after a deletion.
|
||||
*/
|
||||
export function openViewer({ tile, source, origin, onDeleted }) {
|
||||
const opener = document.activeElement;
|
||||
let entry = null;
|
||||
let fileIndex = 0;
|
||||
let zoomed = false;
|
||||
let token = 0;
|
||||
|
||||
const where = h('span.dove');
|
||||
const closeButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.chiudi'), title: t('vis.chiudi'), onclick: close }, icon('x'));
|
||||
const zoomButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.ingrandisci'), title: t('vis.ingrandisci'), onclick: () => setZoom(!zoomed) }, icon('zoom-in'));
|
||||
const fullButton = h('button.tondino', {
|
||||
type: 'button', 'aria-label': t('vis.schermoIntero'), title: t('vis.schermoIntero'),
|
||||
onclick: () => (document.fullscreenElement ? document.exitFullscreen() : box.requestFullscreen && box.requestFullscreen().catch(() => {})),
|
||||
}, icon('maximize'));
|
||||
const prev = h('button.freccia.sx', { type: 'button', 'aria-label': t('vis.precedente'), onclick: () => step(-1) }, icon('chevron-left'));
|
||||
const next = h('button.freccia.dx', { type: 'button', 'aria-label': t('vis.successivo'), onclick: () => step(1) }, icon('chevron-right'));
|
||||
const stage = h('div.scena');
|
||||
const strip = h('div.serie', { role: 'group', 'aria-label': t('vis.serie') });
|
||||
const panelTop = h('div.alto');
|
||||
const panelBottom = h('div.basso');
|
||||
const box = h('div.vis', { role: 'dialog', 'aria-modal': 'true', 'aria-label': t('vis.etichetta') },
|
||||
h('div.palco',
|
||||
h('div.palco-testa', closeButton, where, h('div.destra', zoomButton, fullButton)),
|
||||
h('div', { style: { position: 'relative', flex: '1', minHeight: '0', display: 'flex' } }, prev, stage, next),
|
||||
strip),
|
||||
h('aside.scheda', panelTop, panelBottom));
|
||||
|
||||
function onKey(e) {
|
||||
if (document.querySelector('.velo.finestra, .menu')) return; // a dialog or a menu over the viewer has the keys
|
||||
if (e.target.closest && e.target.closest('input,textarea,select,video')) {
|
||||
if (e.key !== 'Escape') return;
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
if (document.fullscreenElement) return;
|
||||
e.preventDefault();
|
||||
close();
|
||||
} else if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
step(-1);
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
step(1);
|
||||
} else if (e.key === 'Tab') {
|
||||
const items = [...box.querySelectorAll('button:not([disabled]),a[href],video')].filter((el) => el.offsetParent !== null);
|
||||
if (!items.length) return;
|
||||
if (e.shiftKey && document.activeElement === items[0]) {
|
||||
items[items.length - 1].focus();
|
||||
e.preventDefault();
|
||||
} else if (!e.shiftKey && document.activeElement === items[items.length - 1]) {
|
||||
items[0].focus();
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function close() {
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
for (const v of box.querySelectorAll('video')) v.pause();
|
||||
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
|
||||
box.remove();
|
||||
document.body.style.overflow = '';
|
||||
if (entry && source && source.reveal) source.reveal(entry.id);
|
||||
if (opener && document.contains(opener)) opener.focus();
|
||||
}
|
||||
|
||||
function setZoom(on) {
|
||||
zoomed = on;
|
||||
stage.classList.toggle('ingrandita', on);
|
||||
zoomButton.setAttribute('aria-pressed', String(on));
|
||||
}
|
||||
|
||||
async function load(id, index = 0) {
|
||||
const mine = ++token;
|
||||
try {
|
||||
const data = await api(`/api/entries/${id}`);
|
||||
if (mine !== token) return;
|
||||
entry = data;
|
||||
fileIndex = index < 0 ? entry.media.length - 1 : Math.min(index, entry.media.length - 1);
|
||||
draw();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function step(delta) {
|
||||
if (!entry) return;
|
||||
const target = fileIndex + delta;
|
||||
if (target >= 0 && target < entry.media.length) {
|
||||
fileIndex = target;
|
||||
drawMedia();
|
||||
drawStrip();
|
||||
drawPanel();
|
||||
return;
|
||||
}
|
||||
if (!source || !source.neighbor) return;
|
||||
const other = await source.neighbor(entry.id, delta);
|
||||
if (other) await load(other.id, delta > 0 ? 0 : -1);
|
||||
}
|
||||
|
||||
function draw() {
|
||||
drawWhere();
|
||||
drawMedia();
|
||||
drawStrip();
|
||||
drawPanel();
|
||||
}
|
||||
|
||||
function drawWhere() {
|
||||
if (source && source.position) {
|
||||
const p = source.position(entry.id);
|
||||
where.textContent = p.index ? t('vis.dove', { origine: origin, n: number(p.index), totale: number(p.total) }) : origin;
|
||||
} else where.textContent = origin;
|
||||
}
|
||||
|
||||
function drawMedia() {
|
||||
setZoom(false);
|
||||
for (const v of stage.querySelectorAll('video')) v.pause();
|
||||
const media = entry.media[fileIndex];
|
||||
if (!media) {
|
||||
fill(stage, h('div.mancante', icon('info', 'l'), h('p', t('vis.eliminato'))));
|
||||
return;
|
||||
}
|
||||
const thumb = media.thumb ? `/api/thumbnails/${media.thumb}` : null;
|
||||
if (!media.available) {
|
||||
fill(stage, h('div.mancante', thumb ? h('img', { src: thumb, alt: '' }) : icon('image', 'l'),
|
||||
h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante'))));
|
||||
return;
|
||||
}
|
||||
const src = `/api/media/${media.id}/file`;
|
||||
if (media.kind === 'video') {
|
||||
fill(stage, h('video', { src, poster: thumb, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata', 'aria-label': t('libreria.tipiTessera.' + entry.kind) }));
|
||||
const video = stage.querySelector('video');
|
||||
video.muted = true; // spec §10.3: videos start without sound
|
||||
} else {
|
||||
const img = h('img', { src, alt: entry.caption ? entry.caption.slice(0, 140) : `@${entry.account.username}` });
|
||||
img.addEventListener('click', () => setZoom(!zoomed));
|
||||
fill(stage, img);
|
||||
}
|
||||
prev.disabled = false;
|
||||
next.disabled = false;
|
||||
}
|
||||
|
||||
function drawStrip() {
|
||||
if (entry.media.length < 2) {
|
||||
strip.hidden = true;
|
||||
strip.replaceChildren();
|
||||
return;
|
||||
}
|
||||
strip.hidden = false;
|
||||
fill(strip, entry.media.map((m, i) => h(`button${i === fileIndex ? '.qui' : ''}`, {
|
||||
type: 'button',
|
||||
'aria-label': t('vis.fileN', { n: i + 1, totale: entry.media.length }),
|
||||
'aria-current': i === fileIndex ? 'true' : null,
|
||||
onclick: () => {
|
||||
fileIndex = i;
|
||||
drawMedia();
|
||||
drawStrip();
|
||||
drawPanel();
|
||||
},
|
||||
}, m.thumb ? h('img', { src: `/api/thumbnails/${m.thumb}`, alt: '', loading: 'lazy' }) : null, m.kind === 'video' ? icon('play') : null)));
|
||||
}
|
||||
|
||||
function row(term, value) {
|
||||
return value == null || value === '' ? null : [h('dt', term), h('dd', value)];
|
||||
}
|
||||
|
||||
function drawPanel() {
|
||||
const a = entry.account;
|
||||
const media = entry.media[fileIndex];
|
||||
const today = caps().today;
|
||||
const kindText = t(`libreria.tipiTessera.${entry.kind}`);
|
||||
const mediaText = media ? t(media.kind === 'video' ? 'comune.video' : 'comune.foto') : '';
|
||||
const typeLabel = entry.media.length > 1
|
||||
? t('vis.tipoFile', { tipo: kindText, media: mediaText, n: fileIndex + 1, totale: entry.media.length })
|
||||
: t('vis.tipoSingolo', { tipo: kindText, media: mediaText });
|
||||
const published = `${capitalize(dayName(entry.publishedDay))} ${entry.publishedDay.slice(0, 4)}, ${entry.publishedTime}`;
|
||||
const downloaded = entry.downloaded ? `${shortDay(entry.downloaded.day)} ${entry.downloaded.day.slice(0, 4)}, ${entry.downloaded.clock}` : null;
|
||||
fill(panelTop,
|
||||
h('div.chi-vis', avatar(a.username, 'm', a.avatar), h('div', h('b', `@${a.username}`), a.displayName ? h('span', a.displayName) : null),
|
||||
a.isFollowed ? label(t('vis.seguito'), 'accento', 'user-check') : null),
|
||||
h('div.etichette', label(typeLabel, '', KIND_ICON[entry.kind] || 'image'), a.isPrivate ? label(t('vis.privato'), '', 'lock') : null),
|
||||
h('div.quando', h('b', published), h('span', t('vis.pubblicato', { quando: ago(entry.publishedAt, serverNow(), today, entry.publishedDay) }))),
|
||||
h('section', h('h3', t('vis.didascalia')), entry.caption ? h('p.didascalia', entry.caption) : h('p.didascalia.muto', t('vis.senzaDidascalia'))),
|
||||
h('section', h('h3', t('vis.file')), h('dl',
|
||||
media ? row(t('vis.nome'), media.fileName) : null,
|
||||
media && media.width && media.height ? row(t('vis.dimensioni'), t('vis.pixel', { l: number(media.width), a: number(media.height) })) : null,
|
||||
media && media.bytes ? row(t('vis.peso'), bytes(media.bytes)) : null,
|
||||
media && media.duration ? row(t('vis.durata'), duration(media.duration)) : null,
|
||||
media ? row(t('vis.cartella'), media.folder) : null,
|
||||
row(t('vis.codice'), entry.code || entry.instagramId),
|
||||
entry.author ? row(t('vis.autore'), `@${entry.author}`) : null,
|
||||
entry.media.length > 1 ? row(t('vis.posizione'), t('vis.posizioneDi', { n: fileIndex + 1, totale: entry.media.length })) : null,
|
||||
entry.highlights.length ? row(t('vis.raccolte'), entry.highlights.join(', ')) : null)),
|
||||
h('section', h('h3', t('vis.provenienza')), h('dl',
|
||||
row(t('vis.origine'), t(entry.provenance === 'imported' ? 'vis.importato' : 'vis.scaricato')),
|
||||
row(t('vis.quando'), downloaded))));
|
||||
|
||||
const c = caps();
|
||||
const actions = [];
|
||||
if (media && media.available) {
|
||||
actions.push(c.showInFolder
|
||||
? h('button.btn', { type: 'button', onclick: () => showInFolder(media.id) }, icon('folder-open'), t('vis.mostra'))
|
||||
: h('a.btn', { href: `/api/media/${media.id}/file?download=1`, download: media.fileName || '' }, icon('download'), t('vis.scarica')));
|
||||
}
|
||||
if (entry.instagramUrl) {
|
||||
actions.push(c.openUrlNative
|
||||
? h('button.btn', { type: 'button', onclick: () => openNative(entry.id) }, icon('external-link'), t('vis.apri'))
|
||||
: h('a.btn', { href: entry.instagramUrl, target: '_blank', rel: 'noopener noreferrer' }, icon('external-link'), t('vis.apri')));
|
||||
}
|
||||
if (entry.state !== 'deleted') {
|
||||
actions.push(h('button.btn.nudo.pericolo', { type: 'button', onclick: remove }, icon('trash-2'), t('vis.elimina')));
|
||||
}
|
||||
fill(panelBottom, actions);
|
||||
}
|
||||
|
||||
async function showInFolder(mediaId) {
|
||||
try {
|
||||
const result = await api('/api/media/show-in-folder', { method: 'POST', body: { mediaId } });
|
||||
toast(result.message);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function openNative(id) {
|
||||
try {
|
||||
await api(`/api/entries/${id}/open-on-instagram`, { method: 'POST' });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
const id = entry.id;
|
||||
const following = source && source.neighbor ? (await source.neighbor(id, 1)) || (await source.neighbor(id, -1)) : null;
|
||||
const removed = await confirmDelete([id]);
|
||||
if (!removed) return;
|
||||
if (onDeleted) onDeleted(removed);
|
||||
if (following) await load(following.id, 0);
|
||||
else close();
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
document.body.append(box);
|
||||
closeButton.focus();
|
||||
load(tile.id, 0);
|
||||
void withCarried;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// The pages of Febe. Each entry: a pattern on the Italian address, the item of the sidebar it lights up, and the
|
||||
// module that draws it (loaded on demand). The server answers every address without an extension with index.html,
|
||||
// so a new page needs only a line here and its module in js/pages/ (see src/Febe.Web/LEGGIMI.md).
|
||||
|
||||
const placeholder = () => import('./pages/placeholder.js');
|
||||
|
||||
export const routes = [
|
||||
{ pattern: /^\/$/, redirect: '/libreria' },
|
||||
{ pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') },
|
||||
{ pattern: /^\/account\/?$/, nav: 'account', page: () => import('./pages/accounts.js') },
|
||||
{ pattern: /^\/account\/(?<id>\d+)(?:\/(?<tab>contenuti|impostazioni|cronologia))?\/?$/, nav: 'account', page: () => import('./pages/account.js') },
|
||||
{ pattern: /^\/attivita\/?$/, nav: 'attivita', page: placeholder, data: { key: 'attivita' } },
|
||||
{ pattern: /^\/importa\/?$/, nav: 'importa', page: placeholder, data: { key: 'importa' } },
|
||||
{ pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' },
|
||||
{
|
||||
pattern: /^\/impostazioni\/(?<section>generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/,
|
||||
nav: 'impostazioni',
|
||||
page: placeholder,
|
||||
data: { key: 'impostazioni' },
|
||||
},
|
||||
{ pattern: /^\/browser\/?$/, nav: 'attivita', page: placeholder, data: { key: 'browser' } },
|
||||
];
|
||||
@@ -0,0 +1,18 @@
|
||||
// Applies the theme before the first paint (classic script, loaded in <head>): no flash of the wrong colours.
|
||||
(function () {
|
||||
var forced = null;
|
||||
var saved = null;
|
||||
try {
|
||||
forced = new URLSearchParams(location.search).get('tema') || sessionStorage.getItem('febe.tema');
|
||||
} catch (e) {
|
||||
forced = null;
|
||||
}
|
||||
try {
|
||||
saved = localStorage.getItem('febe.tema');
|
||||
} catch (e) {
|
||||
saved = null;
|
||||
}
|
||||
var choice = forced === 'chiaro' || forced === 'scuro' ? forced : saved || 'sistema';
|
||||
var dark = choice === 'scuro' || (choice === 'sistema' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
document.documentElement.setAttribute('data-tema', dark ? 'scuro' : 'chiaro');
|
||||
})();
|
||||
Reference in new issue
Block a user