// 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'))); }