D1, prima parte: Dashboard al posto di Attività e «Cosa scaricare prima» generale

Richiesta di Alberto (#59): decidere cosa scaricare prima, una Dashboard compatta come
pagina iniziale da guardare mentre il motore lavora, e le miniature di ciò che è arrivato.

- Dashboard (§7.9, §10.2): /dashboard è la pagina iniziale e la prima voce della barra;
  /, /attivita, «Ho finito» del browser, il riquadro di stato e il ritorno dopo l'accesso
  portano lì. In alto l'anteprima del browser sempre visibile, chiesta ogni secondo mentre
  il motore lavora (LiveBrowserPreview cattura al più un fotogramma al secondo), accanto
  cosa sta facendo e i quattro tetti; poi la striscia più bassa, la cronologia con le
  miniature e la coda ridotta alle prime righe con «Mostra tutta». Sotto i 1000 px una
  colonna sola.
- Miniature della cronologia: /api/activity/arrived dà gli elementi che una ricetta ha
  salvato (account, inizio e fine della ricetta), chiesti solo quando la riga entra in
  vista, al più otto con «+N». Un clic apre un'anteprima leggera con foto o video senza
  audio, frecce fra i file della riga, Esc, «Apri nella Libreria» e «Apri l'account».
- «Cosa scaricare prima» (§7.2, §6.5): ordine generale dei tipi in Impostazioni → Limiti
  e comportamento (trascinare, «Su» e «Giù», nota sulle storie che scadono), predefinito
  storie, evidenza, post, reel, taggati. Dopo il giro, il lavoro dovuto si estrae con il
  peso dell'account per il peso del tipo (16, 8, 4, 2, 1): pesa, non rende fisso. La coda
  dei file segue lo stesso ordine.
- Prove: DownloadOrderTests (ordine, pesi, coda, motore con seme fisso: il primo tipo
  viene più spesso ma non sempre, il giro resta primo, un tipo senza lavoro non si
  visita), DashboardApiTests, una prova dell'interfaccia per / e /attivita.

Non ancora fatto: ordine per account e segno del reel (serve una migrazione da concordare
con E1), «Raggruppa i post» / «Tutte le foto», confronto con i mockup, revisione del
resto della guida che nomina ancora Attività.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 14:53:03 +01:00
1 parent 2068dd28f3
commit d6c0ef851d
38 files changed
+1468 -479

No files matched your search

+47 -1
View File
@@ -654,7 +654,53 @@ a.stato:hover{border-color:var(--bordo-forte)}
/* ---------- attività ---------- */
.attivita{display:flex;flex-direction:column;gap:24px;padding-bottom:8px}
.attivita > div:empty{display:none}
[data-pagina=attivita] .arresto .riprendi-arresto{display:none}
[data-pagina=dashboard] .arresto .riprendi-arresto{display:none}
/* Dashboard (spec §7.9, tappa D1): compact, preview always visible at the top with what is happening and the budgets */
.dashboard{gap:18px}
.cruscotto{display:flex;align-items:stretch;gap:20px;padding:14px 16px}
.cruscotto .anteprima{width:420px}
.cruscotto .anteprima .quadro{height:236px}
.cruscotto-lato{flex:1;min-width:0;display:flex;flex-direction:column;justify-content:space-between;gap:14px}
.cruscotto-lato .ora-testo .cosa{margin-top:8px}
.blocco-tetti .testa-blocco{margin-bottom:6px}
.blocco-tetti h2{margin:0;font-size:14px;font-weight:650}
.blocco-tetti .tetti{border:1px solid var(--bordo);border-radius:8px}
.blocco-tetti .tetto{padding:9px 12px 10px;gap:5px}
.blocco-tetti .tetto .valore b{font-size:17px}
.oggi-basso .striscia{height:22px}
.storia-coda{grid-template-columns:minmax(0,1.6fr) minmax(0,1fr)}
.elenco-attivita.stretto li{min-height:46px;padding:8px 14px}
.storia-righe li{align-items:flex-start}
.piede-elenco{display:block;width:100%;padding:9px 14px;text-align:left;border-top:1px solid var(--bordo)}
.miniature{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px;min-height:44px}
.miniatura{position:relative;width:44px;height:44px;padding:0;border:0;border-radius:3px;overflow:hidden;background:var(--rialzo);cursor:zoom-in;flex:none}
.miniatura img{display:block;width:100%;height:100%;object-fit:cover}
.miniatura .vuota{display:flex;width:100%;height:100%;align-items:center;justify-content:center;color:var(--testo-3)}
.miniatura .segni{position:absolute;top:2px;right:2px;display:flex;gap:2px;color:#fff;font-size:9.5px;text-shadow:0 0 3px rgba(0,0,0,.7)}
.miniatura .anello svg.ic{width:11px;height:11px}
.miniatura:focus-visible{outline:2px solid var(--accento);outline-offset:1px}
.miniature-altre{display:inline-flex;align-items:center;justify-content:center;width:44px;height:44px;border-radius:3px;background:var(--rialzo);color:var(--testo-2);font-size:12px}
.anteprima-cronologia{width:min(860px,calc(100vw - 32px));border-radius:14px}
.anteprima-scena{display:flex;align-items:center;gap:10px}
.anteprima-palco{flex:1;min-width:0;height:min(62vh,560px);display:flex;align-items:center;justify-content:center;background:#161616;border-radius:8px;overflow:hidden}
.anteprima-palco img,.anteprima-palco video{max-width:100%;max-height:100%;object-fit:contain}
.anteprima-neutra{display:flex;flex-direction:column;align-items:center;gap:8px;color:rgba(255,255,255,.7);font-size:13px}
.anteprima-dida{display:flex;flex-wrap:wrap;gap:6px 12px;margin-top:10px;font-size:13px}
.btn.tondo{width:36px;height:36px;padding:0;border-radius:50%;justify-content:center;flex:none}
/* «Cosa scaricare prima» (spec §7.2) */
.ordine-tipi{list-style:none;margin:0;padding:0}
.riga-ordine{display:flex;align-items:center;gap:12px;padding:8px 12px;border-bottom:1px solid var(--bordo);background:var(--superficie)}
.riga-ordine:last-child{border-bottom:0}
.riga-ordine.trascinata{opacity:.55}
.riga-ordine .maniglia{cursor:grab;color:var(--testo-3);display:inline-flex}
.riga-ordine .posizione{width:16px;color:var(--testo-2)}
.riga-ordine .destra{margin-left:auto;display:flex;gap:4px}
.riga-sotto{display:flex;align-items:center;gap:12px;margin-top:8px}
@media (max-width:1000px){
.cruscotto{flex-direction:column}
.cruscotto .anteprima{width:100%}
.storia-coda{grid-template-columns:minmax(0,1fr)}
}
.ora-pannello{display:flex;align-items:center;gap:24px;padding:18px 18px 18px 24px;min-height:142px}
.ora-testo{flex:1;min-width:0}
.ora-testo .riga{display:flex;align-items:center;gap:10px}
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6.5 14.5 12 9 17.5 14.5"/>
</svg>

After

Width:  |  Height:  |  Size: 216 B

@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<line x1="9" y1="6" x2="9" y2="6.01"/>
<line x1="15" y1="6" x2="15" y2="6.01"/>
<line x1="9" y1="12" x2="9" y2="12.01"/>
<line x1="15" y1="12" x2="15" y2="12.01"/>
<line x1="9" y1="18" x2="9" y2="18.01"/>
<line x1="15" y1="18" x2="15" y2="18.01"/>
</svg>

After

Width:  |  Height:  |  Size: 429 B

+2 -2
View File
@@ -6,9 +6,9 @@
const SAFE = /^\/(?![\/\\])[^\\\s\u0000-\u001f\u007f-\u009f]*$/;
export const DEFAULT_PAGE = '/libreria';
export const DEFAULT_PAGE = '/dashboard';
/** The absolute address to open after the login, on <origin> only; the library when <value> is missing or unsafe. */
/** The absolute address to open after the login, on <origin> only; the Dashboard when <value> is missing or unsafe. */
export function returnAddress(value, origin) {
const fallback = new URL(DEFAULT_PAGE, origin).href;
if (typeof value !== 'string' || value.length > 2048 || !SAFE.test(value)) {
+6 -6
View File
@@ -1,5 +1,5 @@
// 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,
// The frame of every page (spec §10.2): fixed 228 px sidebar with brand, Dashboard (the start page, tappa D1), Libreria,
// Account, 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.
@@ -12,9 +12,9 @@ import { avatar, showError, toast, closeMenu } from './ui.js';
import { routes } from '../routes.js';
const NAV = [
{ key: 'dashboard', href: '/dashboard', icon: 'activity' },
{ 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' },
@@ -37,13 +37,13 @@ export function buildShell(root) {
navLinks[item.key] = a;
return a;
});
statusBox = h('a.stato', { href: withCarried('/attivita'), 'aria-label': t('stato.riquadro') });
statusBox = h('a.stato', { href: withCarried('/dashboard'), '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('a.marchio', { href: withCarried('/dashboard') }, brand(), h('b', t('app.nome'))),
h('nav.nav', { 'aria-label': t('nav.principale') }, links),
h('div.molla'),
statusBox),
@@ -82,7 +82,7 @@ function renderStatus(state) {
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;
const attention = navLinks.dashboard;
if (attention) {
const dot = attention.querySelector('.punto');
if (s.banner && !dot) attention.append(h('span.punto', { role: 'img', 'aria-label': t('nav.fermo') }));
-395
View File
@@ -1,395 +0,0 @@
// Attività (mockups 06 and 11, spec §7.9): what the engine is doing now with a still frame of the browser every few
// seconds, the strip of the day, «Limiti di oggi» with the four main budgets and «Tutti i tetti», the queue with
// «verso le» times, «Appena fatto» with the outcomes, the stops of the last days and the alerts (spec §13.3: also the
// ones that are not stops, like a backfill completed or a disk almost full). It updates by itself from the event
// stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
import { api, download, withCarried } from '../core/api.js';
import { h, icon, fill } from '../core/dom.js';
import { dotOf, refreshEngine } from '../core/engine.js';
import { openBrowser } from '../core/shell.js';
import { t, at, capitalize } from '../core/text.js';
import { dialog, label, showError, toast } from '../core/ui.js';
import { dayStrip } from './day-strip.js';
const STOPPED = ['StoppedForVerification', 'Disconnected'];
export default {
async mount(page) {
page.title(t('attivita.titolo'));
const notice = h('div');
const now = h('section.ora-pannello.pannello');
const preview = previewBox(page);
const today = h('section.blocco');
const budgets = h('section.blocco');
const lists = h('div.due-colonne');
const suspended = h('div');
const incidents = h('section.blocco');
const alerts = h('section.blocco', { hidden: true });
// On this page «Riprendi» is in the title row: the red strip keeps only «Apri il browser» (mockup 11).
page.root.dataset.pagina = 'attivita';
fill(page.body, h('div.attivita', now, suspended, today, budgets, lists, notice, incidents, alerts));
let latest = null;
page.onEngine((state) => {
latest = state;
drawActions(page, state);
drawNow(now, preview, state);
drawToday(today, state);
drawBudgets(budgets, state);
drawLists(lists, state);
drawSuspended(suspended, state);
preview.update(state);
});
async function loadSide() {
try {
const [counts, history, recent] = await Promise.all([
api('/api/duplicates/count', { signal: page.signal }),
api('/api/engine/incidents', { signal: page.signal }),
api('/api/alerts', { signal: page.signal }),
]);
drawNotice(notice, counts);
drawIncidents(incidents, history);
drawAlerts(alerts, recent);
} catch (error) {
if (error.name !== 'AbortError') showError(error);
}
}
await loadSide();
if (page.signal.aborted) return;
page.onLibrary(() => loadSide());
const timer = setInterval(() => {
if (latest && document.visibilityState === 'visible') loadSide();
}, 60000);
page.onLeave(() => clearInterval(timer));
},
};
// ------------------------------------------------------------------------------------------------- title actions
function drawActions(page, state) {
const s = state.snapshot;
const resume = async () => {
try {
const result = await api('/api/engine/resume', { method: 'POST' });
toast(result.message, result.resumed ? '' : 'errore');
refreshEngine();
} catch (error) {
showError(error);
}
};
const pause = async () => {
try {
const result = await api('/api/engine/pause', { method: 'POST' });
toast(result.message);
refreshEngine();
} catch (error) {
showError(error);
}
};
const needsResume = s.mode === 'Paused' || (s.banner && s.banner.needsResume);
const first = needsResume
? h('button.btn', {
type: 'button', onclick: resume, disabled: s.mode !== 'Paused' && !state.canResume,
title: s.mode !== 'Paused' && !state.canResume ? t('arresto.riprendiSpento') : null, 'aria-label': t('attivita.riprendi'),
}, icon('rotate-cw'), h('span.testo-btn', t('attivita.riprendi')))
: h('button.btn', {
type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'),
}, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
page.actions(
first,
h('button.btn', { type: 'button', onclick: () => openBrowser(), 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
diagnosticsButton(),
);
}
// True while a report is being exported. The title row is rebuilt at every engine update, so the button of the click
// may be gone by the end: the flag, not the button, says whether an export is running.
let exporting = false;
/** «Diagnostica»: the report of the last two weeks of sessions, with no name in it, to send after a test gone wrong (#39). */
function diagnosticsButton() {
const button = h('button.btn', {
type: 'button', title: t('attivita.esportaDiagnostica'), 'aria-label': t('attivita.esportaDiagnostica'), disabled: exporting,
}, icon('file-down'), h('span.testo-btn', t('attivita.diagnostica')));
button.onclick = async () => {
if (exporting) return;
exporting = true;
button.disabled = true;
try {
await download('/api/engine/diagnostica', null, 'febe-diagnostica.json');
toast(t('attivita.diagnosticaEsportata'));
} catch (error) {
showError(error);
} finally {
exporting = false;
// The button on the page now, which may not be this one.
for (const shown of document.querySelectorAll('[data-diagnostica]')) shown.disabled = false;
}
};
button.dataset.diagnostica = '';
return button;
}
// ------------------------------------------------------------------------------------------------- now
function drawNow(box, preview, state) {
const s = state.snapshot;
const dot = dotOf(s.mode);
const [first, ...rest] = s.details || [];
fill(box,
h('div.ora-testo',
h('div.riga', h(`span.spia${dot ? '.' + dot : ''}`, { 'aria-hidden': 'true' }), h('b', s.headline)),
first ? h('p.cosa', first) : null,
rest.length ? h('p.dettaglio', rest.join(' ')) : null,
s.reductionNote ? h('p.dettaglio', s.reductionNote) : null),
preview.element);
}
/** The still frame of the browser: one image every few seconds, never a video (mockup 06). */
function previewBox(page) {
const address = h('span.indirizzo.dati');
const image = h('img', { alt: t('attivita.anteprima'), hidden: true });
const placeholder = h('div.segnaposto-anteprima');
const element = h('figure.anteprima', h('figcaption', icon('lock', 'xs'), address), h('div.quadro', image, placeholder));
let mode = null;
let frameUrl = null;
let timer = 0;
let stopped = false;
function placeholderFor(m) {
if (m === 'StoppedForVerification') return ['shield-alert', t('attivita.anteprimaVerifica'), 'https://www.instagram.com/challenge/'];
if (m === 'Disconnected' || m === 'NotConnected') return ['user', t('attivita.anteprimaAccesso'), null];
if (m === 'Off') return ['square', t('attivita.anteprimaSpenta'), null];
if (m === 'InSession' || m === 'UserDriving') return ['hourglass', t('attivita.anteprimaAttesa'), null];
return ['moon', t('attivita.anteprimaVuota'), 'about:blank'];
}
async function load() {
clearTimeout(timer);
if (stopped) return;
try {
const result = await api('/api/browser/preview', { signal: page.signal });
if (result.hasFrame && result.frame) {
if (result.frame !== frameUrl) {
frameUrl = result.frame;
image.src = withCarried(result.frame);
}
image.hidden = false;
placeholder.hidden = true;
address.textContent = shortUrl(result.url);
} else {
showPlaceholder();
}
} catch (error) {
if (error.name === 'AbortError') return;
showPlaceholder();
}
const busy = ['InSession', 'UserDriving', ...STOPPED].includes(mode);
timer = setTimeout(load, busy ? 5000 : 30000);
}
function showPlaceholder() {
frameUrl = null;
image.hidden = true;
image.removeAttribute('src');
const [name, text, url] = placeholderFor(mode);
fill(placeholder, icon(name, 'l'), h('span', text));
placeholder.hidden = false;
address.textContent = url ? shortUrl(url) : '';
}
page.onLeave(() => {
stopped = true;
clearTimeout(timer);
});
return {
element,
update(state) {
const changed = state.snapshot.mode !== mode;
mode = state.snapshot.mode;
if (changed) load();
},
};
}
function shortUrl(url) {
if (!url) return '';
return url.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '');
}
// ------------------------------------------------------------------------------------------------- strip
function drawToday(box, state) {
const s = state.snapshot;
const { strip, hours, legend } = dayStrip(s.today, { stopOpen: STOPPED.includes(s.mode) });
fill(box,
h('div.testa-blocco', h('h2', t('attivita.oggi')), h('span.muto', s.today.summary), legend),
strip, hours);
}
// ------------------------------------------------------------------------------------------------- budgets
function drawBudgets(box, state) {
const s = state.snapshot;
const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
const profile = frozen ? t('attivita.congelati', { profilo: s.profileLine }) : s.profileLine;
fill(box,
h('div.testa-blocco',
h('h2', t('attivita.limiti')),
h('span.muto', profile),
s.reductionNote ? label(s.reductionNote, 'ambra') : null,
h('button.btn.collegamento.destra', { type: 'button', onclick: () => allBudgets(state) }, t('attivita.tuttiTetti'))),
h('div.tetti.pannello', s.mainBudgets.map((b) => budgetCard(b, frozen))));
}
function budgetCard(b, frozen) {
const meterClass = frozen && b.kind !== 'DataDownload' ? '.grigio' : b.amber ? '.ambra' : '';
return h('div.tetto',
h('span.nome', b.label),
h('div.valore', h('b.dati', b.usedText), h('span', b.limitText)),
h(`div.misura${meterClass}`, {
role: 'meter', 'aria-label': b.label, 'aria-valuemin': '0', 'aria-valuemax': String(b.limitToday), 'aria-valuenow': String(b.usedToday),
}, h('i', { style: { width: `${Math.max(0, Math.min(1, b.ratio)) * 100}%` } })),
h('span.nota', b.amber ? h('span', icon('triangle-alert', 'xs'), ' ', b.note) : b.note));
}
function allBudgets(state) {
const s = state.snapshot;
const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
const cell = (used, limit, text, ratio, amber) => h('td',
h('div.cella-tetto',
h('span.dati', text),
limit != null ? h(`div.misura.fine${frozen ? '.grigio' : amber ? '.ambra' : ''}`, h('i', { style: { width: `${Math.max(0, Math.min(1, ratio)) * 100}%` } })) : null));
dialog({
title: t('attivita.tetti.titolo'),
className: 'tutti-tetti',
build: (close) => ({
body: h('div.contenuto',
h('p.aiuto', t('attivita.tetti.aiuto')),
h('table.tab',
h('thead', h('tr', h('th', t('attivita.tetti.categoria')), h('th', t('attivita.tetti.ora')), h('th', t('attivita.tetti.giorno')))),
h('tbody', s.allBudgets.map((b) => h('tr',
h('td', h('b', b.label), b.amber ? h('div', label(b.note, 'ambra')) : b.note.startsWith(t('attivita.tetti.ora')) ? null : h('div.muto.piccolo', b.note)),
b.limitPerHour == null
? h('td.muto', '—')
: cell(b.usedLastHour, b.limitPerHour, t('attivita.tetti.di', { usati: b.usedLastHour, limite: b.limitPerHour }), b.limitPerHour ? b.usedLastHour / b.limitPerHour : 0, b.limitPerHour && b.usedLastHour / b.limitPerHour >= 0.8),
cell(b.usedToday, b.limitToday, `${b.usedText} ${b.limitText}`, b.ratio, b.ratio >= 0.8)))))),
footer: h('footer',
h('a.btn.nudo', { href: withCarried('/impostazioni/limiti'), onclick: () => close() }, icon('sliders-horizontal'), t('attivita.tetti.cambia')),
h('div.destra', h('button.btn.primo', { type: 'button', onclick: () => close() }, t('comune.chiudi')))),
}),
});
}
// ------------------------------------------------------------------------------------------------- queue and latest actions
function badgeKind(text) {
const v = String(text || '').toLowerCase();
if (v.includes('in corso')) return 'accento';
if (v.includes('scaricat') || v.includes('nuov')) return 'verde';
if (v.includes('tutto fermo') || v.includes('verifica') || v.includes('non riuscit')) return 'rosso';
if (v.includes('fermo') || v.includes('rallent') || v.includes('tetto')) return 'ambra';
return '';
}
function drawLists(box, state) {
const s = state.snapshot;
const queue = s.queue.length
? h('ul.elenco-attivita', s.queue.map((q) => h('li',
h('span.quando.dati', q.when),
h('div.chi-cosa', h('b', q.title), h('span', q.detail)),
q.suspended ? label(t('account.sospeso')) : q.isManual ? label(t('attivita.chiesto'), 'accento') : null)))
: h('p.vuoto-elenco', t('attivita.codaVuota'));
const recent = s.recentActions.length
? h('ul.elenco-attivita', s.recentActions.map((r) => h('li',
h('span.quando.dati', r.time),
h('div.chi-cosa', h('b', r.title), h('span', r.detail)),
r.badge ? label(r.badge, badgeKind(r.badge)) : null)))
: h('p.vuoto-elenco', t('attivita.fattoVuoto'));
fill(box,
h('section', h('h2', t('attivita.coda')), h('div.pannello', queue)),
h('section', h('h2', t('attivita.fatto')), h('div.pannello', recent)));
}
// ------------------------------------------------------------------------------------------------- side information
function drawNotice(box, counts) {
if (!counts || !counts.download) {
box.replaceChildren();
return;
}
fill(box, h('div.avviso.ambra.avviso-azione', icon('layers', 's'),
h('span', t('attivita.doppioni', { n: counts.download })),
h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi'))));
}
/** Recipes suspended after three problems in a row (unknown formats, targets not found): what to do, «Riattiva». */
function drawSuspended(box, state) {
const items = state.snapshot.suspendedRecipes || [];
if (!items.length) {
box.replaceChildren();
return;
}
fill(box, items.map((r) => h('div.avviso.rosso.avviso-azione', { style: { marginBottom: '10px' } },
icon('octagon-alert', 's'),
h('span', t('attivita.sospesa', { nome: r.name })),
h('button.btn.piccolo', {
type: 'button',
onclick: async () => {
try {
const result = await api(`/api/engine/recipes/${encodeURIComponent(r.recipe)}/resume`, { method: 'POST' });
toast(result.message, result.resumed ? '' : 'errore');
refreshEngine();
} catch (error) {
showError(error);
}
},
}, t('attivita.riattiva')))));
}
const ALERT_LOOK = {
error: { icon: 'octagon-alert', label: 'rosso' },
warning: { icon: 'triangle-alert', label: 'ambra' },
success: { icon: 'circle-check', label: 'verde' },
info: { icon: 'bell', label: '' },
};
/** «Avvisi»: every alert of the last days, the same ones Telegram and Windows get. Hidden while there are none. */
function drawAlerts(box, recent) {
const items = (recent && recent.items) || [];
box.hidden = !items.length;
if (!items.length) {
box.replaceChildren();
return;
}
fill(box,
h('div.testa-blocco', h('h2', t('attivita.avvisi')), h('span.muto', t('attivita.avvisiAiuto', { giorni: recent.days }))),
h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => {
const look = ALERT_LOOK[i.level] || ALERT_LOOK.info;
return h('li',
h('span.quando.dati', capitalize(at(i.at))),
h('div.chi-cosa', h('b', i.title), h('span', i.message)),
label(t(`attivita.livelliAvviso.${i.level}`), look.label, look.icon));
}))));
}
function drawIncidents(box, history) {
const items = history.items || [];
fill(box,
h('div.testa-blocco', h('h2', t('attivita.arresti')), h('span.muto', t('attivita.arrestiAiuto'))),
history.advice ? h('div.avviso.ambra', { style: { marginBottom: '10px' } }, icon('triangle-alert', 's'), h('span', history.advice)) : null,
items.length
? h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => h('li',
h('span.quando.dati', capitalize(at(i.at))),
h('div.chi-cosa',
h('b', i.title, ' ', h('span.codice.dati', i.signal)),
h('span', [i.note, i.url ? i.url.replace(/^https?:\/\/(www\.)?/, '') : null].filter(Boolean).join(' · '))),
i.open
? label(t('attivita.aperto'), i.level === 'throttle' ? 'ambra' : 'rosso')
: h('span.muto.piccolo', i.resolvedAt ? t('attivita.risolto', { quando: at(i.resolvedAt) }) : i.stoppedUntil ? t('attivita.fermoFino', { quando: at(i.stoppedUntil) }) : '')))))
: h('p.vuoto-elenco.pannello', t('attivita.arrestiVuoti')));
}
+1 -1
View File
@@ -37,7 +37,7 @@ export default {
// «Ho finito» gives the browser back on the server whatever the answer.
lease.settled();
toast(result.message, result.connected ? '' : 'errore');
if (result.connected) navigate('/attivita');
if (result.connected) navigate('/dashboard');
else fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message)));
};
page.saveBar(h('div', { style: { display: 'contents' } },
+672
View File
@@ -0,0 +1,672 @@
// Dashboard (spec §7.9, §10.2, tappa D1; before it was Attività, mockups 06 and 11): the start page, where Alberto stays
// while the engine works. Compact, to fit the top of a 1440 × 900 window without scrolling: at the top the preview of
// the browser, always visible and refreshed at every new frame (at most one a second), with beside it what the engine
// is doing now and the four main budgets in one row («Tutti i tetti» for the others); then the strip of the day, lower;
// then in two columns the history with the thumbnails of what arrived (loaded only when the line is in view, at most
// eight with «+N»; a click opens a light enlarged preview) and the queue with «verso le» times, cut to the first rows
// with «Mostra tutta». Below: the stops of the last days and the alerts (spec §13.3). It updates by itself from the
// event stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
import { api, download, withCarried } from '../core/api.js';
import { h, icon, fill } from '../core/dom.js';
import { dotOf, refreshEngine } from '../core/engine.js';
import { openBrowser } from '../core/shell.js';
import { t, at, capitalize, dayName, duration } from '../core/text.js';
import { dialog, label, showError, toast } from '../core/ui.js';
import { dayStrip } from './day-strip.js';
import { openViewer } from './viewer.js';
const STOPPED = ['StoppedForVerification', 'Disconnected'];
// Rows of the queue shown before «Mostra tutta»; thumbnails of a line of the history before «+N» (spec §7.9).
const QUEUE_ROWS = 5;
const THUMBS = 8;
export default {
async mount(page) {
page.title(t('attivita.titolo'));
const notice = h('div');
const now = h('div.ora-testo');
const preview = previewBox(page);
const today = h('section.blocco.oggi-basso');
const budgets = h('section.blocco-tetti');
const history = historyBox(page);
const queue = queueBox();
const suspended = h('div');
const incidents = h('section.blocco');
const alerts = h('section.blocco', { hidden: true });
// On this page «Riprendi» is in the title row: the red strip keeps only «Apri il browser» (mockup 11).
page.root.dataset.pagina = 'dashboard';
fill(page.body, h('div.attivita.dashboard',
h('section.cruscotto.pannello', preview.element, h('div.cruscotto-lato', now, budgets)),
suspended, today,
h('div.due-colonne.storia-coda', history.element, queue.element),
notice, incidents, alerts));
let latest = null;
page.onEngine((state) => {
latest = state;
drawActions(page, state);
drawNow(now, state);
drawToday(today, state);
drawBudgets(budgets, state);
history.draw(state);
queue.draw(state);
drawSuspended(suspended, state);
preview.update(state);
});
async function loadSide() {
try {
const [counts, history, recent] = await Promise.all([
api('/api/duplicates/count', { signal: page.signal }),
api('/api/engine/incidents', { signal: page.signal }),
api('/api/alerts', { signal: page.signal }),
]);
drawNotice(notice, counts);
drawIncidents(incidents, history);
drawAlerts(alerts, recent);
} catch (error) {
if (error.name !== 'AbortError') showError(error);
}
}
await loadSide();
if (page.signal.aborted) return;
page.onLibrary(() => loadSide());
const timer = setInterval(() => {
if (latest && document.visibilityState === 'visible') loadSide();
}, 60000);
page.onLeave(() => clearInterval(timer));
},
};
// ------------------------------------------------------------------------------------------------- title actions
function drawActions(page, state) {
const s = state.snapshot;
const resume = async () => {
try {
const result = await api('/api/engine/resume', { method: 'POST' });
toast(result.message, result.resumed ? '' : 'errore');
refreshEngine();
} catch (error) {
showError(error);
}
};
const pause = async () => {
try {
const result = await api('/api/engine/pause', { method: 'POST' });
toast(result.message);
refreshEngine();
} catch (error) {
showError(error);
}
};
const needsResume = s.mode === 'Paused' || (s.banner && s.banner.needsResume);
const first = needsResume
? h('button.btn', {
type: 'button', onclick: resume, disabled: s.mode !== 'Paused' && !state.canResume,
title: s.mode !== 'Paused' && !state.canResume ? t('arresto.riprendiSpento') : null, 'aria-label': t('attivita.riprendi'),
}, icon('rotate-cw'), h('span.testo-btn', t('attivita.riprendi')))
: h('button.btn', {
type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'),
}, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
page.actions(
first,
h('button.btn', { type: 'button', onclick: () => openBrowser(), 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
diagnosticsButton(),
);
}
// True while a report is being exported. The title row is rebuilt at every engine update, so the button of the click
// may be gone by the end: the flag, not the button, says whether an export is running.
let exporting = false;
/** «Diagnostica»: the report of the last two weeks of sessions, with no name in it, to send after a test gone wrong (#39). */
function diagnosticsButton() {
const button = h('button.btn', {
type: 'button', title: t('attivita.esportaDiagnostica'), 'aria-label': t('attivita.esportaDiagnostica'), disabled: exporting,
}, icon('file-down'), h('span.testo-btn', t('attivita.diagnostica')));
button.onclick = async () => {
if (exporting) return;
exporting = true;
button.disabled = true;
try {
await download('/api/engine/diagnostica', null, 'febe-diagnostica.json');
toast(t('attivita.diagnosticaEsportata'));
} catch (error) {
showError(error);
} finally {
exporting = false;
// The button on the page now, which may not be this one.
for (const shown of document.querySelectorAll('[data-diagnostica]')) shown.disabled = false;
}
};
button.dataset.diagnostica = '';
return button;
}
// ------------------------------------------------------------------------------------------------- now
function drawNow(box, state) {
const s = state.snapshot;
const dot = dotOf(s.mode);
const [first, ...rest] = s.details || [];
fill(box,
h('div.riga', h(`span.spia${dot ? '.' + dot : ''}`, { 'aria-hidden': 'true' }), h('b', s.headline)),
first ? h('p.cosa', first) : null,
rest.length ? h('p.dettaglio', rest.join(' ')) : null,
s.reductionNote ? h('p.dettaglio', s.reductionNote) : null);
}
/**
* The preview of the browser, always visible (spec §7.9): the page the browser of Febe is looking at, frames and never
* a video. While the engine works it asks every second and swaps the picture only when the frame is new (the server
* takes at most one a second, however many pages ask); otherwise every 30 seconds. Out of a session it says why it
* is still. A hidden tab asks nothing.
*/
function previewBox(page) {
const address = h('span.indirizzo.dati');
const image = h('img', { alt: t('attivita.anteprima'), hidden: true });
const placeholder = h('div.segnaposto-anteprima');
const element = h('figure.anteprima', h('figcaption', icon('lock', 'xs'), address), h('div.quadro', image, placeholder));
let mode = null;
let frameUrl = null;
let timer = 0;
let stopped = false;
function placeholderFor(m) {
if (m === 'StoppedForVerification') return ['shield-alert', t('attivita.anteprimaVerifica'), 'https://www.instagram.com/challenge/'];
if (m === 'Disconnected' || m === 'NotConnected') return ['user', t('attivita.anteprimaAccesso'), null];
if (m === 'Off') return ['square', t('attivita.anteprimaSpenta'), null];
if (m === 'InSession' || m === 'UserDriving') return ['hourglass', t('attivita.anteprimaAttesa'), null];
return ['moon', t('attivita.anteprimaVuota'), 'about:blank'];
}
async function load() {
clearTimeout(timer);
if (stopped) return;
try {
const result = await api('/api/browser/preview', { signal: page.signal });
if (result.hasFrame && result.frame) {
if (result.frame !== frameUrl) {
frameUrl = result.frame;
image.src = withCarried(result.frame);
}
image.hidden = false;
placeholder.hidden = true;
address.textContent = shortUrl(result.url);
} else {
showPlaceholder();
}
} catch (error) {
if (error.name === 'AbortError') return;
showPlaceholder();
}
const busy = ['InSession', 'UserDriving', ...STOPPED].includes(mode);
timer = setTimeout(() => {
if (document.visibilityState === 'visible') load();
else waiting = true;
}, busy ? 1000 : 30000);
}
// Back to a visible tab: at once, instead of after the next interval.
let waiting = false;
const onVisible = () => {
if (document.visibilityState === 'visible' && waiting) {
waiting = false;
load();
}
};
document.addEventListener('visibilitychange', onVisible);
function showPlaceholder() {
frameUrl = null;
image.hidden = true;
image.removeAttribute('src');
const [name, text, url] = placeholderFor(mode);
fill(placeholder, icon(name, 'l'), h('span', text));
placeholder.hidden = false;
address.textContent = url ? shortUrl(url) : '';
}
page.onLeave(() => {
stopped = true;
clearTimeout(timer);
document.removeEventListener('visibilitychange', onVisible);
});
return {
element,
update(state) {
const changed = state.snapshot.mode !== mode;
mode = state.snapshot.mode;
if (changed) load();
},
};
}
function shortUrl(url) {
if (!url) return '';
return url.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '');
}
// ------------------------------------------------------------------------------------------------- strip
function drawToday(box, state) {
const s = state.snapshot;
const { strip, hours, legend } = dayStrip(s.today, { stopOpen: STOPPED.includes(s.mode) });
fill(box,
h('div.testa-blocco', h('h2', t('attivita.oggi')), h('span.muto', s.today.summary), legend),
strip, hours);
}
// ------------------------------------------------------------------------------------------------- budgets
function drawBudgets(box, state) {
const s = state.snapshot;
const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
const profile = frozen ? t('attivita.congelati', { profilo: s.profileLine }) : s.profileLine;
fill(box,
h('div.testa-blocco',
h('h2', t('attivita.limiti')),
h('span.muto', profile),
h('button.btn.collegamento.destra', { type: 'button', onclick: () => allBudgets(state) }, t('attivita.tuttiTetti'))),
h('div.tetti', s.mainBudgets.map((b) => budgetCard(b, frozen))));
}
function budgetCard(b, frozen) {
const meterClass = frozen && b.kind !== 'DataDownload' ? '.grigio' : b.amber ? '.ambra' : '';
return h('div.tetto',
h('span.nome', b.label),
h('div.valore', h('b.dati', b.usedText), h('span', b.limitText)),
h(`div.misura${meterClass}`, {
role: 'meter', 'aria-label': b.label, 'aria-valuemin': '0', 'aria-valuemax': String(b.limitToday), 'aria-valuenow': String(b.usedToday),
}, h('i', { style: { width: `${Math.max(0, Math.min(1, b.ratio)) * 100}%` } })),
h('span.nota', b.amber ? h('span', icon('triangle-alert', 'xs'), ' ', b.note) : b.note));
}
function allBudgets(state) {
const s = state.snapshot;
const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
const cell = (used, limit, text, ratio, amber) => h('td',
h('div.cella-tetto',
h('span.dati', text),
limit != null ? h(`div.misura.fine${frozen ? '.grigio' : amber ? '.ambra' : ''}`, h('i', { style: { width: `${Math.max(0, Math.min(1, ratio)) * 100}%` } })) : null));
dialog({
title: t('attivita.tetti.titolo'),
className: 'tutti-tetti',
build: (close) => ({
body: h('div.contenuto',
h('p.aiuto', t('attivita.tetti.aiuto')),
h('table.tab',
h('thead', h('tr', h('th', t('attivita.tetti.categoria')), h('th', t('attivita.tetti.ora')), h('th', t('attivita.tetti.giorno')))),
h('tbody', s.allBudgets.map((b) => h('tr',
h('td', h('b', b.label), b.amber ? h('div', label(b.note, 'ambra')) : b.note.startsWith(t('attivita.tetti.ora')) ? null : h('div.muto.piccolo', b.note)),
b.limitPerHour == null
? h('td.muto', '—')
: cell(b.usedLastHour, b.limitPerHour, t('attivita.tetti.di', { usati: b.usedLastHour, limite: b.limitPerHour }), b.limitPerHour ? b.usedLastHour / b.limitPerHour : 0, b.limitPerHour && b.usedLastHour / b.limitPerHour >= 0.8),
cell(b.usedToday, b.limitToday, `${b.usedText} ${b.limitText}`, b.ratio, b.ratio >= 0.8)))))),
footer: h('footer',
h('a.btn.nudo', { href: withCarried('/impostazioni/limiti'), onclick: () => close() }, icon('sliders-horizontal'), t('attivita.tetti.cambia')),
h('div.destra', h('button.btn.primo', { type: 'button', onclick: () => close() }, t('comune.chiudi')))),
}),
});
}
// ------------------------------------------------------------------------------------------------- queue and latest actions
function badgeKind(text) {
const v = String(text || '').toLowerCase();
if (v.includes('in corso')) return 'accento';
if (v.includes('scaricat') || v.includes('nuov')) return 'verde';
if (v.includes('tutto fermo') || v.includes('verifica') || v.includes('non riuscit')) return 'rosso';
if (v.includes('fermo') || v.includes('rallent') || v.includes('tetto')) return 'ambra';
return '';
}
/** The queue with «verso le» times, cut to the first rows; «Mostra tutta» opens it whole until the page is left. */
function queueBox() {
const element = h('section.coda');
let whole = false;
let last = null;
function draw(state) {
last = state;
const items = state.snapshot.queue;
const shown = whole ? items : items.slice(0, QUEUE_ROWS);
const list = items.length
? h('ul.elenco-attivita.stretto', shown.map((q) => h('li',
h('span.quando.dati', q.when),
h('div.chi-cosa', h('b', q.title), h('span', q.detail)),
q.suspended ? label(t('account.sospeso')) : q.isManual ? label(t('attivita.chiesto'), 'accento') : null)))
: h('p.vuoto-elenco', t('attivita.codaVuota'));
const more = items.length > QUEUE_ROWS
? h('button.btn.collegamento.piede-elenco', {
type: 'button',
'aria-expanded': String(whole),
onclick: () => {
whole = !whole;
draw(last);
},
}, whole ? t('attivita.mostraMeno') : t('attivita.mostraTutta', { n: items.length }))
: null;
fill(element, h('h2', t('attivita.coda')), h('div.pannello', list, more));
}
return { element, draw };
}
/**
* The history of the activity (spec §7.9): the last recipe runs with their outcome; a line that saved something shows
* the thumbnails of what arrived, asked to the server only when the line comes into view and kept while the page is
* open, so that the engine updates never ask again for the same line.
*/
function historyBox(page) {
const element = h('section.storia');
const arrived = new Map();
const watcher = 'IntersectionObserver' in window
? new IntersectionObserver((entries) => {
for (const e of entries) {
if (!e.isIntersecting) continue;
watcher.unobserve(e.target);
loadThumbs(e.target);
}
}, { rootMargin: '200px 0px' })
: null;
page.onLeave(() => watcher && watcher.disconnect());
function keyOf(r) {
return `${r.accountId}|${r.from}|${r.at}`;
}
async function loadThumbs(holder) {
const key = holder.dataset.chiave;
const known = arrived.get(key);
if (known && known.result) {
paint(holder, known);
return;
}
if (known && known.loading) return;
const item = { loading: true, result: null, line: holder.line };
arrived.set(key, item);
try {
const query = new URLSearchParams({ account: String(holder.line.accountId), from: holder.line.from, to: holder.line.at, limit: String(THUMBS) });
item.result = await api(`/api/activity/arrived?${query}`, { signal: page.signal });
} catch (error) {
if (error.name === 'AbortError') return;
item.result = { tiles: [], total: 0 };
} finally {
item.loading = false;
}
// The line may have been drawn again meanwhile: paint the holder that is on the page now.
const shown = element.querySelector(`[data-chiave="${CSS.escape(key)}"]`);
if (shown) paint(shown, item);
}
function paint(holder, item) {
const { tiles, total } = item.result;
// The holder keeps the room of a row of thumbnails while it waits (an element with no size is never in view).
if (!tiles.length) {
holder.replaceChildren();
holder.hidden = true;
return;
}
const rest = Math.max(0, total - tiles.length);
fill(holder,
tiles.map((tile, i) => thumb(tile, () => openPreview(page, item.line, tiles, total, i))),
rest > 0 ? h('span.miniature-altre.dati', { title: t('attivita.altreArrivate', { n: rest }) }, `+${rest}`) : null);
}
function draw(state) {
const items = state.snapshot.recentActions;
if (!items.length) {
fill(element, h('h2', t('attivita.fatto')), h('div.pannello', h('p.vuoto-elenco', t('attivita.fattoVuoto'))));
return;
}
const list = h('ul.elenco-attivita.storia-righe', items.map((r) => {
let holder = null;
if (r.accountId && r.from && r.newEntries > 0) {
holder = h('div.miniature', { dataset: { chiave: keyOf(r) }, 'aria-label': t('attivita.arrivate', { n: r.newEntries }), role: 'group' });
holder.line = r;
const known = arrived.get(keyOf(r));
if (known && known.result) paint(holder, known);
else if (watcher) watcher.observe(holder);
else loadThumbs(holder);
}
return h('li',
h('span.quando.dati', r.time),
h('div.chi-cosa', h('b', r.title), r.detail ? h('span', r.detail) : null, holder),
r.badge ? label(r.badge, badgeKind(r.badge)) : null);
}));
fill(element, h('h2', t('attivita.fatto')), h('div.pannello', list));
// Lines no longer shown are forgotten, so that a long day does not keep every answer.
const keys = new Set(items.filter((r) => r.accountId && r.from).map(keyOf));
for (const key of arrived.keys()) if (!keys.has(key)) arrived.delete(key);
}
return { element, draw };
}
/** A small tile of the history: the thumbnail of §8.4 with the marks of the mosaic (video length, ring of stories). */
function thumb(tile, onOpen) {
const cover = tile.cover;
const marks = [];
if (tile.kind === 'story') marks.push(h('span.anello', icon('circle-dashed', 'xs')));
if (cover && cover.kind === 'video') marks.push(h('span.durata', duration(cover.duration || 0)));
const what = t(`libreria.tipiTessera.${tile.kind}`);
return h('button.miniatura', {
type: 'button',
onclick: onOpen,
'aria-label': t('attivita.apriAnteprima', { tipo: what, account: tile.username }),
title: `${what}, @${tile.username}`,
},
cover && cover.thumb
? h('img', { src: `/api/thumbnails/${cover.thumb}`, alt: '', loading: 'lazy', decoding: 'async', draggable: 'false' })
: h('span.vuota', icon('image', 'xs')),
marks.length ? h('span.segni', marks) : null);
}
/**
* The enlarged preview of a line of the history (spec §7.9): a light dialog over the page, without leaving it. The
* photo or the video (without sound), account, kind, date, arrows between the files of that line, Esc that closes;
* «Apri nella Libreria» opens the viewer of §4.6 on that entry, «Apri l'account» its tab. A damaged or incomplete file
* shows the neutral tile. The files of an entry are asked only when the arrows reach it.
*/
async function openPreview(page, line, firstTiles, total, startIndex) {
let tiles = firstTiles;
// More entries than the thumbnails: the arrows walk all of them (up to the server's limit).
if (total > firstTiles.length) {
try {
const query = new URLSearchParams({ account: String(line.accountId), from: line.from, to: line.at, limit: '60' });
const all = await api(`/api/activity/arrived?${query}`, { signal: page.signal });
if (all.tiles.length) tiles = all.tiles;
} catch (error) {
if (error.name === 'AbortError') return;
}
}
const entries = new Map();
let entryIndex = Math.max(0, tiles.findIndex((x) => x.id === firstTiles[startIndex].id));
let fileIndex = 0;
let token = 0;
const stage = h('div.anteprima-palco');
const caption = h('div.anteprima-dida');
const position = h('span.dati.muto');
const prev = h('button.btn.nudo.tondo', { type: 'button', 'aria-label': t('vis.precedente'), onclick: () => step(-1) }, icon('chevron-left'));
const next = h('button.btn.nudo.tondo', { type: 'button', 'aria-label': t('vis.successivo'), onclick: () => step(1) }, icon('chevron-right'));
let closeDialog = null;
async function entryOf(i) {
const id = tiles[i].id;
if (!entries.has(id)) entries.set(id, api(`/api/entries/${id}`, { signal: page.signal }).catch(() => null));
return entries.get(id);
}
async function show() {
const mine = ++token;
const tile = tiles[entryIndex];
const entry = await entryOf(entryIndex);
if (mine !== token) return;
const media = entry && entry.media.length ? entry.media[Math.min(fileIndex, entry.media.length - 1)] : null;
const thumbUrl = media && media.thumb ? `/api/thumbnails/${media.thumb}` : tile.cover && tile.cover.thumb ? `/api/thumbnails/${tile.cover.thumb}` : null;
if (!media || media.damaged || !media.available) {
fill(stage, h('div.anteprima-neutra', icon('image', 'l'),
media && media.damaged ? h('p', t('vis.danneggiato')) : media && !media.available ? h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante')) : null));
} else if (media.kind === 'video') {
const video = h('video', { src: `/api/media/${media.id}/file`, poster: thumbUrl, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata' });
video.muted = true; // spec §10.3: videos start without sound
fill(stage, video);
} else {
fill(stage, h('img', { src: `/api/media/${media.id}/file`, alt: `@${tile.username}` }));
}
const files = entry ? entry.media.length : 1;
fill(caption,
h('b', `@${tile.username}`),
h('span', t(`libreria.tipiTessera.${tile.kind}`)),
h('span.muto', `${capitalize(dayName(tile.day, ''))}, ${tile.time}`),
files > 1 ? h('span.muto', t('attivita.fileDi', { n: fileIndex + 1, di: files })) : null);
position.textContent = t('attivita.elementoDi', { n: entryIndex + 1, di: tiles.length });
prev.disabled = entryIndex === 0 && fileIndex === 0;
next.disabled = entryIndex === tiles.length - 1 && fileIndex >= files - 1;
}
async function step(delta) {
const entry = await entryOf(entryIndex);
const files = entry ? entry.media.length : 1;
if (delta > 0) {
if (fileIndex < files - 1) fileIndex += 1;
else if (entryIndex < tiles.length - 1) {
entryIndex += 1;
fileIndex = 0;
} else return;
} else if (fileIndex > 0) fileIndex -= 1;
else if (entryIndex > 0) {
entryIndex -= 1;
const before = await entryOf(entryIndex);
fileIndex = before ? Math.max(0, before.media.length - 1) : 0;
} else return;
show();
}
function onKey(event) {
if (event.key === 'ArrowLeft') {
event.preventDefault();
step(-1);
} else if (event.key === 'ArrowRight') {
event.preventDefault();
step(1);
}
}
const list = {
position: (id) => {
const i = tiles.findIndex((x) => x.id === id);
return i < 0 ? null : { index: i, total: tiles.length };
},
neighbor: async (id, delta) => {
const i = tiles.findIndex((x) => x.id === id);
return i < 0 ? null : tiles[i + delta] || null;
},
};
dialog({
title: t('attivita.anteprimaTitolo'),
className: 'anteprima-cronologia',
build: (close) => {
closeDialog = close;
return {
body: h('div.contenuto', { onkeydown: onKey }, h('div.anteprima-scena', prev, stage, next), caption),
footer: h('footer',
position,
h('div.destra',
h('a.btn', { href: withCarried(`/account/${tiles[entryIndex].accountId}/contenuti`), onclick: () => closeDialog() }, icon('user'), t('attivita.apriAccount')),
h('button.btn.primo', {
type: 'button',
onclick: () => {
const tile = tiles[entryIndex];
closeDialog();
openViewer({ tile, source: list, origin: t('nav.libreria') });
},
}, icon('layout-grid'), t('attivita.apriLibreria')))),
};
},
});
show();
}
// ------------------------------------------------------------------------------------------------- side information
function drawNotice(box, counts) {
if (!counts || !counts.download) {
box.replaceChildren();
return;
}
fill(box, h('div.avviso.ambra.avviso-azione', icon('layers', 's'),
h('span', t('attivita.doppioni', { n: counts.download })),
h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi'))));
}
/** Recipes suspended after three problems in a row (unknown formats, targets not found): what to do, «Riattiva». */
function drawSuspended(box, state) {
const items = state.snapshot.suspendedRecipes || [];
if (!items.length) {
box.replaceChildren();
return;
}
fill(box, items.map((r) => h('div.avviso.rosso.avviso-azione', { style: { marginBottom: '10px' } },
icon('octagon-alert', 's'),
h('span', t('attivita.sospesa', { nome: r.name })),
h('button.btn.piccolo', {
type: 'button',
onclick: async () => {
try {
const result = await api(`/api/engine/recipes/${encodeURIComponent(r.recipe)}/resume`, { method: 'POST' });
toast(result.message, result.resumed ? '' : 'errore');
refreshEngine();
} catch (error) {
showError(error);
}
},
}, t('attivita.riattiva')))));
}
const ALERT_LOOK = {
error: { icon: 'octagon-alert', label: 'rosso' },
warning: { icon: 'triangle-alert', label: 'ambra' },
success: { icon: 'circle-check', label: 'verde' },
info: { icon: 'bell', label: '' },
};
/** «Avvisi»: every alert of the last days, the same ones Telegram and Windows get. Hidden while there are none. */
function drawAlerts(box, recent) {
const items = (recent && recent.items) || [];
box.hidden = !items.length;
if (!items.length) {
box.replaceChildren();
return;
}
fill(box,
h('div.testa-blocco', h('h2', t('attivita.avvisi')), h('span.muto', t('attivita.avvisiAiuto', { giorni: recent.days }))),
h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => {
const look = ALERT_LOOK[i.level] || ALERT_LOOK.info;
return h('li',
h('span.quando.dati', capitalize(at(i.at))),
h('div.chi-cosa', h('b', i.title), h('span', i.message)),
label(t(`attivita.livelliAvviso.${i.level}`), look.label, look.icon));
}))));
}
function drawIncidents(box, history) {
const items = history.items || [];
fill(box,
h('div.testa-blocco', h('h2', t('attivita.arresti')), h('span.muto', t('attivita.arrestiAiuto'))),
history.advice ? h('div.avviso.ambra', { style: { marginBottom: '10px' } }, icon('triangle-alert', 's'), h('span', history.advice)) : null,
items.length
? h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => h('li',
h('span.quando.dati', capitalize(at(i.at))),
h('div.chi-cosa',
h('b', i.title, ' ', h('span.codice.dati', i.signal)),
h('span', [i.note, i.url ? i.url.replace(/^https?:\/\/(www\.)?/, '') : null].filter(Boolean).join(' · '))),
i.open
? label(t('attivita.aperto'), i.level === 'throttle' ? 'ambra' : 'rosso')
: h('span.muto.piccolo', i.resolvedAt ? t('attivita.risolto', { quando: at(i.resolvedAt) }) : i.stoppedUntil ? t('attivita.fermoFino', { quando: at(i.stoppedUntil) }) : '')))))
: h('p.vuoto-elenco.pannello', t('attivita.arrestiVuoti')));
}
@@ -12,11 +12,13 @@ import { checkbox, confirmDialog, label, showError, toast, toggle } from '../cor
import { guardChanges, heading } from './settings.js';
const PACES = ['slow', 'natural', 'brisk'];
// «Cosa scaricare prima» (spec §7.2): the default order of the kinds, the one the server also uses.
const DEFAULT_ORDER = ['storie', 'evidenza', 'post', 'reel', 'taggati'];
const DAY_ORDER = [1, 2, 3, 4, 5, 6, 0]; // Monday first; the API counts from Sunday = 0
export default async function limits(page, box) {
let data = await api('/api/settings/limits', { signal: page.signal });
const snapshot = () => JSON.stringify({ profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays].sort() });
const snapshot = () => JSON.stringify({ profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays].sort(), order: form.order });
let form = fromData(data);
let original = snapshot();
const dirty = () => snapshot() !== original;
@@ -32,9 +34,83 @@ export default async function limits(page, box) {
gradualStart: d.gradualStart,
activeDays: new Set(d.activeDays),
jitterOn: d.current.jitterMinutes > 0,
order: Array.isArray(d.downloadOrder) && d.downloadOrder.length ? [...d.downloadOrder] : [...DEFAULT_ORDER],
};
}
// ------------------------------------------------------------------------------------------- download order
// The rows move by dragging (mouse) or with «Su» and «Giù» (keyboard); the order is saved with the save bar.
const orderList = h('ol.ordine-tipi', { 'aria-label': t('impostazioni.limiti.ordine') });
const orderStatus = h('span.vh', { 'aria-live': 'polite' });
let dragged = null;
function move(from, to, focus) {
if (to < 0 || to >= form.order.length || from === to) return;
const [kind] = form.order.splice(from, 1);
form.order.splice(to, 0, kind);
drawOrder();
drawSaveBar();
orderStatus.textContent = t('impostazioni.limiti.ordineSpostato', { tipo: t(`impostazioni.limiti.tipi.${kind}`), n: to + 1 });
if (focus) {
const again = orderList.querySelector(`[data-tipo="${kind}"] [data-verso="${focus}"]`);
if (again && !again.disabled) again.focus();
else orderList.querySelector(`[data-tipo="${kind}"] button:not([disabled])`)?.focus();
}
}
function drawOrder() {
fill(orderList, form.order.map((kind, i) => {
const name = t(`impostazioni.limiti.tipi.${kind}`);
const row = h('li.riga-ordine', { draggable: 'true', dataset: { tipo: kind } },
h('span.maniglia', { title: t('impostazioni.limiti.ordineManiglia'), 'aria-hidden': 'true' }, icon('grip-vertical', 's')),
h('span.posizione.dati', String(i + 1)),
h('b', name),
kind === 'storie' && i > 0 ? h('span.muto.piccolo', icon('clock', 'xs'), ' ', t('impostazioni.limiti.ordineStorie')) : null,
h('div.destra',
h('button.btn.piccolo.nudo', {
type: 'button', disabled: i === 0, dataset: { verso: 'su' }, 'aria-label': t('impostazioni.limiti.ordineSuDi', { tipo: name }), onclick: () => move(i, i - 1, 'su'),
}, icon('chevron-up', 's'), h('span.testo-btn', t('impostazioni.limiti.ordineSu'))),
h('button.btn.piccolo.nudo', {
type: 'button', disabled: i === form.order.length - 1, dataset: { verso: 'giu' }, 'aria-label': t('impostazioni.limiti.ordineGiuDi', { tipo: name }), onclick: () => move(i, i + 1, 'giu'),
}, icon('chevron-down', 's'), h('span.testo-btn', t('impostazioni.limiti.ordineGiu')))));
row.addEventListener('dragstart', (event) => {
dragged = i;
row.classList.add('trascinata');
try {
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData('text/plain', kind);
} catch {
// Some browsers refuse data on a drag: the index above is enough.
}
});
row.addEventListener('dragend', () => {
dragged = null;
row.classList.remove('trascinata');
});
row.addEventListener('dragover', (event) => {
if (dragged === null) return;
event.preventDefault();
});
row.addEventListener('drop', (event) => {
if (dragged === null) return;
event.preventDefault();
const from = dragged;
dragged = null;
move(from, i, null);
});
return row;
}));
}
const orderReset = h('button.btn.collegamento', {
type: 'button',
onclick: () => {
form.order = [...DEFAULT_ORDER];
drawOrder();
drawSaveBar();
},
}, t('impostazioni.limiti.ordineMetti'));
/** Any edit turns the profile into «Su misura» (spec §7.5). */
function edited() {
form.profile = 'custom';
@@ -363,7 +439,7 @@ export default async function limits(page, box) {
try {
data = await api('/api/settings/limits', {
method: 'PUT',
body: { profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays] },
body: { profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays], downloadOrder: form.order },
});
form = fromData(data);
original = snapshot();
@@ -381,6 +457,7 @@ export default async function limits(page, box) {
drawWindow();
drawPace();
drawTable();
drawOrder();
drawSaveBar();
}
@@ -411,7 +488,11 @@ export default async function limits(page, box) {
heading(t('impostazioni.limiti.tetti'), t('impostazioni.limiti.tettiAiuto')),
h('div.pannello.tabella-tetti', h('table.tab',
h('thead', h('tr', h('th', t('impostazioni.limiti.colonne.attivita')), h('th', t('impostazioni.limiti.colonne.ora')), h('th', t('impostazioni.limiti.colonne.giorno')))),
table))));
table))),
h('div.sezione',
heading(t('impostazioni.limiti.ordine'), t('impostazioni.limiti.ordineAiuto')),
h('div.pannello', orderList),
h('div.riga-sotto', orderReset, orderStatus)));
}
function toInt(text) {
+6 -4
View File
@@ -3,18 +3,20 @@
// so a new page needs only a line here and its module in js/pages/ (see src/Febe.Web/LEGGIMI.md).
export const routes = [
{ pattern: /^\/$/, redirect: '/libreria' },
// The Dashboard is the start page (spec §7.9, §10.2, tappa D1); the old address of Attività leads there too.
{ pattern: /^\/$/, redirect: '/dashboard' },
{ pattern: /^\/dashboard\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') },
{ pattern: /^\/attivita\/?$/, redirect: '/dashboard' },
{ 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: () => import('./pages/activity.js') },
{ pattern: /^\/importa\/?$/, nav: 'importa', page: () => import('./pages/import.js') },
{ pattern: /^\/doppioni\/?$/, nav: 'attivita', page: () => import('./pages/duplicates.js') },
{ pattern: /^\/doppioni\/?$/, nav: 'dashboard', page: () => import('./pages/duplicates.js') },
{ pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' },
{
pattern: /^\/impostazioni\/(?<section>generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/,
nav: 'impostazioni',
page: () => import('./pages/settings.js'),
},
{ pattern: /^\/browser\/?$/, nav: 'attivita', page: () => import('./pages/browser.js') },
{ pattern: /^\/browser\/?$/, nav: 'dashboard', page: () => import('./pages/browser.js') },
];
+24 -3
View File
@@ -8,9 +8,9 @@
},
"nav": {
"principale": "Navigazione principale",
"dashboard": "Dashboard",
"libreria": "Libreria",
"account": "Account",
"attivita": "Attività",
"importa": "Importa",
"impostazioni": "Impostazioni",
"fermo": "Serve il tuo intervento"
@@ -520,7 +520,7 @@
"uscita": "Esci"
},
"attivita": {
"titolo": "Attività",
"titolo": "Dashboard",
"pausa": "Metti in pausa",
"riprendi": "Riprendi",
"apriBrowser": "Apri il browser",
@@ -558,8 +558,18 @@
},
"coda": "In coda",
"codaVuota": "La coda è vuota.",
"fatto": "Appena fatto",
"mostraTutta": "Mostra tutta ({n})",
"mostraMeno": "Mostra meno",
"fatto": "Cronologia dell'attività",
"fattoVuoto": "Nessuna azione nelle ultime ore.",
"arrivate": "1 elemento arrivato|{n} elementi arrivati",
"altreArrivate": "e 1 altro|e altri {n}",
"apriAnteprima": "Ingrandisci: {tipo} di @{account}",
"anteprimaTitolo": "Anteprima",
"fileDi": "file {n} di {di}",
"elementoDi": "{n} di {di}",
"apriAccount": "Apri l'account",
"apriLibreria": "Apri nella Libreria",
"arresti": "Arresti e rallentamenti",
"arrestiAiuto": "Gli ultimi 14 giorni. Le durate dei fermi sono fisse: 1 ora, 6 ore, 24 ore.",
"arrestiVuoti": "Nessun arresto negli ultimi 14 giorni.",
@@ -673,6 +683,17 @@
"arrestiTesto": "1 ora la prima volta, 6 ore la seconda nelle 24 ore, 24 ore la terza; poi tetti dimezzati per 48 ore.",
"arrestiFissi": "Non si modificano",
"salvati": "Limiti salvati: valgono da subito.",
"ordine": "Cosa scaricare prima",
"ordineAiuto": "Dopo il giro dei profili che segui, Febe sceglie più spesso il tipo che sta più in alto, e scarica prima i suoi file. Non aggiunge controlli e non scavalca tetti, pause e frequenze. Trascina le righe o usa «Su» e «Giù».",
"ordineStorie": "Le storie scadono dopo 24 ore: più in basso stanno, più è facile che scadano prima di essere scaricate.",
"ordineMetti": "Ripristina l'ordine predefinito",
"ordineManiglia": "Trascina per spostare",
"ordineSu": "Su",
"ordineGiu": "Giù",
"ordineSuDi": "Sposta su: {tipo}",
"ordineGiuDi": "Sposta giù: {tipo}",
"ordineSpostato": "{tipo}: posizione {n} di 5",
"tipi": { "storie": "Storie", "evidenza": "In evidenza", "post": "Post", "reel": "Reel", "taggati": "Taggati" },
"errori": {
"pausa": "La pausa minima non può scendere sotto i {n} minuti.",
"sessione": "Una sessione non può durare più di {n} minuti.",