«Copia di nuovo» di un _fotogramma lo rifaceva come _t…, e un lavoro in attesa prendeva un istante del file vecchio. Un'analisi copriva l'evento di una copia finita; il visualizzatore restava sopra la pagina nuova e poteva mostrare un esito superato; la scheda Esportazione perdeva il fuoco a ogni rilettura. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
773 lines
33 KiB
JavaScript
773 lines
33 KiB
JavaScript
// 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';
|
||
import { compactWelcome } from './welcome.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, route) {
|
||
page.title(t('attivita.titolo'));
|
||
const tab = route && route.params && route.params.scheda === 'esportazione' ? 'esportazione' : 'motore';
|
||
page.tabs(dashboardTabs(tab));
|
||
// The tab «Esportazione» (spec §7.9, §10.3, tappa E2): the copies to external folders, not the engine.
|
||
if (tab === 'esportazione') {
|
||
const module = await import('./dashboard-export.js');
|
||
return module.mountExport(page);
|
||
}
|
||
const notice = h('div');
|
||
const exportNotice = 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 });
|
||
const first = firstStart(page);
|
||
// 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',
|
||
first.element,
|
||
h('section.cruscotto.pannello', preview.element, h('div.cruscotto-lato', now, budgets)),
|
||
suspended, today,
|
||
h('div.due-colonne.storia-coda', history.element, queue.element),
|
||
exportNotice, 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);
|
||
first.draw(state);
|
||
});
|
||
|
||
async function loadSide() {
|
||
first.check();
|
||
try {
|
||
const [counts, history, recent, exports] = await Promise.all([
|
||
api('/api/duplicates/count', { signal: page.signal }),
|
||
api('/api/engine/incidents', { signal: page.signal }),
|
||
api('/api/alerts', { signal: page.signal }),
|
||
// The copies are not the engine: without an answer the notice is simply not there.
|
||
api('/api/export', { signal: page.signal }).catch((error) => {
|
||
if (error.name === 'AbortError') throw error;
|
||
return null;
|
||
}),
|
||
]);
|
||
drawExportNotice(exportNotice, exports);
|
||
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((change) => {
|
||
if (change.reason !== 'fermi') loadSide(); // an analysis («Cerca i video fermi») changes nothing here
|
||
});
|
||
const timer = setInterval(() => {
|
||
if (latest && document.visibilityState === 'visible') loadSide();
|
||
}, 60000);
|
||
page.onLeave(() => clearInterval(timer));
|
||
},
|
||
};
|
||
|
||
// ------------------------------------------------------------------------------------------------- tabs
|
||
|
||
/** «Motore» and «Esportazione» under the title (spec §7.9: the export has its own tab, never the red strip). */
|
||
function dashboardTabs(tab) {
|
||
const link = (key, href) => h(`a${tab === key ? '.qui' : ''}`, { href: withCarried(href), 'aria-current': tab === key ? 'page' : null }, t(`esportazione.dashboard.${key}`));
|
||
return h('nav.linguette.linguette-dashboard', { 'aria-label': t('esportazione.dashboard.linguette') },
|
||
link('motore', '/dashboard'), link('esportazione', '/dashboard/esportazione'));
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------- first start
|
||
|
||
/**
|
||
* The first start (spec §7.9, §10.3): / opens the Dashboard, so while there is no account a compact welcome sits above
|
||
* the cockpit with the ways to begin of the Library's welcome. Asked again with the side information (every minute,
|
||
* and when the library changes) only while it is shown, so that it goes away once an account is there.
|
||
*/
|
||
function firstStart(page) {
|
||
const element = h('div');
|
||
let empty = null; // unknown until the accounts answer
|
||
let state = null;
|
||
let shown = null;
|
||
|
||
function draw(latest) {
|
||
if (latest) state = latest;
|
||
const kind = !empty || !state ? null : state.connection && state.connection.state === 'notConnected' ? 'collegati' : 'aggiungi';
|
||
if (kind === shown) return;
|
||
shown = kind;
|
||
if (kind) fill(element, compactWelcome(kind === 'aggiungi'));
|
||
else element.replaceChildren();
|
||
}
|
||
|
||
async function check() {
|
||
if (empty === false) return;
|
||
try {
|
||
const result = await api('/api/accounts', { signal: page.signal });
|
||
empty = !(result.accounts && result.accounts.length);
|
||
} catch (error) {
|
||
if (error.name === 'AbortError') return;
|
||
}
|
||
draw(null);
|
||
}
|
||
|
||
return { element, draw, check };
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------- 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 {
|
||
item.result = await api(`/api/activity/arrived?${arrivedQuery(holder.line, THUMBS)}`, { 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.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.from).map(keyOf));
|
||
for (const key of arrived.keys()) if (!keys.has(key)) arrived.delete(key);
|
||
}
|
||
|
||
return { element, draw };
|
||
}
|
||
|
||
/**
|
||
* The question for what a line of the history saved: the recipe's account and time; a line without an account (the
|
||
* Giro dei seguiti saves posts of many accounts) asks for what arrived of every account in that time.
|
||
*/
|
||
function arrivedQuery(line, limit) {
|
||
const query = new URLSearchParams({ from: line.from, to: line.at, limit: String(limit) });
|
||
if (line.accountId) query.set('account', String(line.accountId));
|
||
return query;
|
||
}
|
||
|
||
/** 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 all = await api(`/api/activity/arrived?${arrivedQuery(line, 60)}`, { 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;
|
||
// «Apri l'account» follows the arrows: a line of the Giro dei seguiti holds entries of many accounts.
|
||
const accountLink = h('a.btn', { onclick: () => closeDialog() }, icon('user'), t('attivita.apriAccount'));
|
||
|
||
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];
|
||
accountLink.href = withCarried(`/account/${tile.accountId}/contenuti`);
|
||
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;
|
||
// The arrows walk the files wherever the focus is in the dialog (also on its buttons); Esc is the dialog's.
|
||
document.addEventListener('keydown', onKey);
|
||
return {
|
||
onClose: () => {
|
||
token += 1; // an entry still loading draws nothing any more
|
||
document.removeEventListener('keydown', onKey);
|
||
},
|
||
body: h('div.contenuto', h('div.anteprima-scena', prev, stage, next), caption),
|
||
footer: h('footer',
|
||
position,
|
||
h('div.destra',
|
||
accountLink,
|
||
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'))));
|
||
}
|
||
|
||
/**
|
||
* A destination of the copies in pause, or copies left to resume (spec §4.10): an amber notice with the way to the tab
|
||
* «Esportazione». Never the red strip, which stays the engine's.
|
||
*/
|
||
function drawExportNotice(box, overview) {
|
||
if (!overview) {
|
||
box.replaceChildren();
|
||
return;
|
||
}
|
||
const paused = [overview.general, ...(overview.own || [])].filter((d) => d && (d.pausedAt || d.problem));
|
||
const items = paused.map((d) => t('esportazione.dashboard.cartellaInPausa', { cartella: d.label, problema: d.problem || t('esportazione.inPausa') }));
|
||
if (!paused.length && overview.unfinishedRuns) items.push(t('esportazione.dashboard.avvisoDaRiprendere', { n: overview.unfinishedRuns }));
|
||
fill(box, items.map((text) => h('div.avviso.ambra.avviso-azione', { style: { marginBottom: '10px' } }, icon('pause', 's'),
|
||
h('span', text),
|
||
h('a.btn.piccolo', { href: withCarried('/dashboard/esportazione') }, t('esportazione.apriEsportazione')))));
|
||
}
|
||
|
||
/** 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')));
|
||
}
|
||
|