Interfaccia, parte 2: Attività, Impostazioni, collegamento, Importa, doppioni, primo avvio ed errori di configurazione
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
90 files changed
+7825
-49
No files matched your search
@@ -1,12 +1,13 @@
|
||||
// Start of the interface: texts, icons, capabilities of the shell, theme, frame, events, router.
|
||||
|
||||
import { api, initCarried, setAccess } from './core/api.js';
|
||||
import { setCapabilities } from './core/context.js';
|
||||
import { caps, setCapabilities } from './core/context.js';
|
||||
import { loadIcons, h, fill } from './core/dom.js';
|
||||
import { startEvents } from './core/engine.js';
|
||||
import { buildShell, startRouter } from './core/shell.js';
|
||||
import { loadTexts, t } from './core/text.js';
|
||||
import { initTheme } from './core/theme.js';
|
||||
import { showProblems } from './pages/problems.js';
|
||||
|
||||
async function boot() {
|
||||
initCarried();
|
||||
@@ -26,6 +27,13 @@ async function boot() {
|
||||
// the defaults describe a plain browser
|
||||
}
|
||||
initTheme();
|
||||
const problems = caps().problems || [];
|
||||
if (problems.length) {
|
||||
// Spec §8.2, §11: with a configuration problem the interface shows only the page that explains it.
|
||||
showProblems(root, problems);
|
||||
document.documentElement.removeAttribute('aria-busy');
|
||||
return;
|
||||
}
|
||||
buildShell(root);
|
||||
startEvents();
|
||||
startRouter();
|
||||
|
||||
@@ -17,6 +17,7 @@ let capabilities = {
|
||||
scenes: [],
|
||||
now: Date.now(),
|
||||
today: '',
|
||||
problems: [],
|
||||
};
|
||||
|
||||
let skew = 0;
|
||||
|
||||
@@ -213,7 +213,7 @@ function renderBanner(frame, state) {
|
||||
return;
|
||||
}
|
||||
const isError = banner.level === 'Error';
|
||||
const resume = h('button.btn', {
|
||||
const resume = h('button.btn.riprendi-arresto', {
|
||||
type: 'button',
|
||||
disabled: !state.canResume,
|
||||
title: state.canResume ? null : t('arresto.riprendiSpento'),
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
// 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, and the stops of the last days. 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, 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 incidents = h('section.blocco');
|
||||
// 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, today, budgets, lists, notice, incidents));
|
||||
|
||||
let latest = null;
|
||||
page.onEngine((state) => {
|
||||
latest = state;
|
||||
drawActions(page, state);
|
||||
drawNow(now, preview, state);
|
||||
drawToday(today, state);
|
||||
drawBudgets(budgets, state);
|
||||
drawLists(lists, state);
|
||||
preview.update(state);
|
||||
});
|
||||
|
||||
async function loadSide() {
|
||||
try {
|
||||
const [counts, history] = await Promise.all([
|
||||
api('/api/duplicates/count', { signal: page.signal }),
|
||||
api('/api/engine/incidents', { signal: page.signal }),
|
||||
]);
|
||||
drawNotice(notice, counts);
|
||||
drawIncidents(incidents, history);
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
}
|
||||
}
|
||||
await loadSide();
|
||||
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'))));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- 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'))));
|
||||
}
|
||||
|
||||
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')));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the
|
||||
// server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the
|
||||
// engine is still; «Ho finito» lets «Riprendi» become active after a verification.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { navigate } from '../core/shell.js';
|
||||
import { t } from '../core/text.js';
|
||||
import { toast } from '../core/ui.js';
|
||||
import { beginDriving, finishDriving, passwordNote, windowPanel } from './connection.js';
|
||||
import { remoteView } from './remote-view.js';
|
||||
|
||||
export default {
|
||||
async mount(page) {
|
||||
page.title(t('browser.titolo'));
|
||||
const windows = caps().browserWindow;
|
||||
let status = null;
|
||||
try {
|
||||
status = await api('/api/connection', { signal: page.signal });
|
||||
} catch {
|
||||
// the view says whether the browser answers
|
||||
}
|
||||
beginDriving(false);
|
||||
const message = h('div', { 'aria-live': 'polite' });
|
||||
const done = async () => {
|
||||
const result = await finishDriving();
|
||||
if (!result) return;
|
||||
toast(result.message, result.connected ? '' : 'errore');
|
||||
if (result.connected) navigate('/attivita');
|
||||
else fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message)));
|
||||
};
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', t('browser.aiuto')),
|
||||
h('div.destra', h('button.btn.primo.grande', { type: 'button', onclick: done }, t('impostazioni.collegamento.hoFinito')))));
|
||||
fill(page.body, h('div.pagina-browser',
|
||||
message,
|
||||
windows ? windowPanel() : remoteView(page, { url: status && status.currentUrl, login: status && status.state === 'notConnected' }).element,
|
||||
passwordNote(windows)));
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,142 @@
|
||||
// The comparison of a probable duplicate (mockup 09, right column; spec §9.3, §9.5): the two files side by side with
|
||||
// sizes, dates and accounts, the «Più grande» badge, the three choices and «Fai lo stesso per gli altri». Nothing is
|
||||
// chosen in advance. Used by Importa (decisions applied by the copy) and by the review after a download (decisions
|
||||
// applied at once, so that one asks for an explicit «Applica la scelta»).
|
||||
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { t, bytes, shortDay } from '../core/text.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { checkbox, label, radio } from '../core/ui.js';
|
||||
|
||||
const CHOICES = [
|
||||
{ value: 'keepLarger', key: 'tieniGrande' },
|
||||
{ value: 'keepExisting', key: 'tieniLibreria' },
|
||||
{ value: 'keepBoth', key: 'tieniEntrambi' },
|
||||
];
|
||||
|
||||
/**
|
||||
* A comparison panel over a list of cases loaded page by page.
|
||||
* options: load(after) → Promise<{ cases, pending }>; decide(caseItem, decision, applyAll) → Promise<{ pending, reload }>;
|
||||
* labels: { existing, existingInSource, candidate } texts; confirm: true to ask for «Applica la scelta» before deciding.
|
||||
*/
|
||||
export function comparePanel({ load, decide, labels, confirm = false, empty }) {
|
||||
const counter = h('span.muto.dati');
|
||||
const prev = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('importa.doppioni.precedente'), title: t('importa.doppioni.precedente'), onclick: () => go(-1) }, icon('chevron-left'));
|
||||
const next = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('importa.doppioni.successivo'), title: t('importa.doppioni.successivo'), onclick: () => go(1) }, icon('chevron-right'));
|
||||
const body = h('div.confronto-corpo', { 'aria-live': 'polite' });
|
||||
const element = h('section.confronto',
|
||||
h('div.testa-blocco', h('h2', t('importa.doppioni.titolo')), h('div.destra.navigazione', counter, prev, next)),
|
||||
h('div.pannello', body));
|
||||
let cases = [];
|
||||
let index = 0;
|
||||
let pending = 0;
|
||||
let total = 0;
|
||||
let more = true;
|
||||
let applyAll = false;
|
||||
|
||||
async function fetchMore() {
|
||||
if (!more) return;
|
||||
const after = cases.length ? cases[cases.length - 1].pairId : 0;
|
||||
const page = await load(after);
|
||||
if (page.cases.length === 0) more = false;
|
||||
cases = cases.concat(page.cases);
|
||||
pending = page.pending;
|
||||
total = Math.max(total, cases.length, pending + cases.filter((c) => c.decision !== 'pending').length);
|
||||
}
|
||||
|
||||
async function go(step) {
|
||||
const target = index + step;
|
||||
if (target >= cases.length && more) await fetchMore();
|
||||
if (target < 0 || target >= cases.length) return;
|
||||
index = target;
|
||||
draw();
|
||||
}
|
||||
|
||||
function side(s, title, larger) {
|
||||
const image = s.image
|
||||
? h('img', { src: s.image, alt: '', loading: 'lazy' })
|
||||
: h('div.senza-anteprima', icon(s.kind === 'video' ? 'clapperboard' : 'image', 'l'), h('span', t('importa.doppioni.senzaAnteprima')));
|
||||
const size = s.width && s.height ? t('importa.doppioni.misure', { l: s.width, a: s.height, peso: bytes(s.bytes || 0) }) : bytes(s.bytes || 0);
|
||||
const where = [s.username, s.date ? shortDay(s.date.day, caps().today) : null].filter(Boolean).join(', ');
|
||||
return h('figure.lato',
|
||||
h('figcaption.titolo-lato', h('b', title), larger ? label(t('importa.doppioni.piuGrande'), 'verde') : null),
|
||||
h('div.immagine-lato', image),
|
||||
h('div.dati-lato', h('span.dati', size), where ? h('span.muto', where) : null, s.path ? h('span.percorso.dati', { title: s.path }, s.path) : null));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
prev.disabled = index <= 0;
|
||||
next.disabled = index >= cases.length - 1 && !more;
|
||||
if (!cases.length) {
|
||||
counter.textContent = '';
|
||||
fill(body, h('p.vuoto-elenco', empty || t('importa.doppioni.nessuno')));
|
||||
return;
|
||||
}
|
||||
const c = cases[index];
|
||||
counter.textContent = t('importa.doppioni.diN', { n: index + 1, totale: total });
|
||||
const name = `scelta-${c.pairId}`;
|
||||
let chosen = c.decision !== 'pending' ? c.decision : null;
|
||||
const apply = h('button.btn.primo', { type: 'button', disabled: true, onclick: () => submit(chosen) }, t('doppioni.conferma'));
|
||||
const radios = CHOICES.map((choice) => radio({
|
||||
name,
|
||||
value: choice.value,
|
||||
checked: c.decision === choice.value,
|
||||
label: t(`importa.doppioni.${choice.key}`),
|
||||
onchange: (v) => {
|
||||
chosen = v;
|
||||
if (confirm) apply.disabled = false;
|
||||
else submit(v);
|
||||
},
|
||||
}));
|
||||
const others = Math.max(0, pending - (c.decision === 'pending' ? 1 : 0));
|
||||
const all = others > 0
|
||||
? checkbox({ checked: applyAll, label: others === 1 ? t('importa.doppioni.applicaUno') : t('importa.doppioni.applicaTutti', { n: others }), onchange: (v) => { applyAll = v; } })
|
||||
: null;
|
||||
fill(body,
|
||||
h('div.lati',
|
||||
side(c.existing, c.existing.inLibrary ? labels.existing : labels.existingInSource, !c.candidateIsLarger && sizeKnown(c)),
|
||||
side(c.candidate, labels.candidate, c.candidateIsLarger)),
|
||||
h('p.motivo.muto.piccolo', icon('info', 'xs'), ' ', t(`importa.doppioni.motivi.${c.reason}`)),
|
||||
h('div.scelte-doppione', { role: 'radiogroup', 'aria-label': t('importa.doppioni.titolo') }, radios),
|
||||
all ? h('div.applica-tutti', all) : null,
|
||||
confirm ? h('div.riga-azione', apply) : null,
|
||||
pending === 0 ? h('p.muto.piccolo', icon('circle-check', 'xs'), ' ', t('importa.doppioni.fatti')) : null);
|
||||
}
|
||||
|
||||
function sizeKnown(c) {
|
||||
return Boolean(c.existing.width && c.candidate.width) && !c.candidateIsLarger && (c.existing.width * c.existing.height > c.candidate.width * c.candidate.height || (c.existing.bytes || 0) > (c.candidate.bytes || 0));
|
||||
}
|
||||
|
||||
async function submit(decision) {
|
||||
if (!decision) return;
|
||||
const c = cases[index];
|
||||
const result = await decide(c, decision, applyAll);
|
||||
if (!result) return;
|
||||
pending = result.pending;
|
||||
if (result.reload) {
|
||||
cases = [];
|
||||
more = true;
|
||||
index = 0;
|
||||
total = 0;
|
||||
await fetchMore();
|
||||
} else {
|
||||
c.decision = decision;
|
||||
if (index < cases.length - 1) index += 1;
|
||||
}
|
||||
applyAll = false;
|
||||
draw();
|
||||
}
|
||||
|
||||
return {
|
||||
element,
|
||||
async start() {
|
||||
await fetchMore();
|
||||
const firstPending = cases.findIndex((c) => c.decision === 'pending');
|
||||
index = firstPending >= 0 ? firstPending : 0;
|
||||
draw();
|
||||
},
|
||||
get pending() {
|
||||
return pending;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// Collegamento a Instagram (mockup 10, spec §4.1, §10.3). Docker: the large remote view of the server's browser with
|
||||
// the steps «Come collegarti», the note that the password goes only to Instagram (keys pass through the server without
|
||||
// being recorded), the risk note, Annulla and «Ho finito». Windows: the browser is the separate window «Browser di
|
||||
// Febe» and the large area says so, with «Portalo in primo piano». When connected: the account, «Usa il browser» and
|
||||
// «Scollega» with its confirmation. While Alberto uses the browser the engine is still.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { refreshEngine } from '../core/engine.js';
|
||||
import { navigate } from '../core/shell.js';
|
||||
import { t } from '../core/text.js';
|
||||
import { avatar, confirmDialog, label, showError, toast } from '../core/ui.js';
|
||||
import { remoteView } from './remote-view.js';
|
||||
|
||||
const STATE_KIND = { notConnected: 'ambra', connected: 'verde', verificationRequired: 'rosso', browserUnavailable: '' };
|
||||
|
||||
/** Starts using the browser (the engine is still); with openLogin the real login page is loaded. */
|
||||
export async function beginDriving(openLogin) {
|
||||
try {
|
||||
await api('/api/connection/begin', { method: 'POST', body: { openLogin } });
|
||||
return true;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The area that replaces the remote view on Windows: the browser is its own window. */
|
||||
export function windowPanel() {
|
||||
return h('div.vista.vista-finestra',
|
||||
h('div.vista-segnaposto',
|
||||
icon('app-window', 'l'),
|
||||
h('h2', t('impostazioni.collegamento.finestra')),
|
||||
h('p', t('impostazioni.collegamento.finestraTesto')),
|
||||
h('button.btn.primo', { type: 'button', onclick: () => beginDriving(false) }, icon('app-window', 's'), t('impostazioni.collegamento.primoPiano'))));
|
||||
}
|
||||
|
||||
/** «Ho finito»: Febe checks the session and hides the browser. Returns the answer of the server. */
|
||||
export async function finishDriving() {
|
||||
try {
|
||||
const result = await api('/api/connection/finish', { method: 'POST' });
|
||||
refreshEngine();
|
||||
return result;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function mountConnection(page) {
|
||||
page.back(t('pagine.impostazioni'), '/impostazioni');
|
||||
page.title(t('impostazioni.collegamento.titolo'));
|
||||
const stateLabel = h('span');
|
||||
page.head.insertBefore(stateLabel, page.head.children[1] || null);
|
||||
const left = h('div.collega-sinistra');
|
||||
const right = h('div.collega-destra');
|
||||
fill(page.body, h('div.pagina-collegamento', left, right));
|
||||
const windows = caps().browserWindow;
|
||||
|
||||
let status = await api('/api/connection', { signal: page.signal });
|
||||
async function draw() {
|
||||
fill(stateLabel, label(t(`impostazioni.collegamento.stati.${status.state}`), STATE_KIND[status.state] || ''));
|
||||
if (status.state === 'connected') drawConnected();
|
||||
else if (status.state === 'browserUnavailable') drawUnavailable();
|
||||
else drawLogin();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- login or verification
|
||||
function drawLogin() {
|
||||
const verification = status.state === 'verificationRequired';
|
||||
beginDriving(!verification);
|
||||
fill(left, windows ? windowPanel() : remoteView(page, { url: status.currentUrl, login: !verification }).element);
|
||||
const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi');
|
||||
const message = h('div', { 'aria-live': 'polite' });
|
||||
fill(right,
|
||||
verification
|
||||
? h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', h('b', t('impostazioni.collegamento.verificaTitolo')), ' ', t('impostazioni.collegamento.verificaTesto')))
|
||||
: h('div',
|
||||
h('h2.sez', t('impostazioni.collegamento.come')),
|
||||
h('ol.passi-collegamento', (Array.isArray(steps) ? steps : []).map((s, i) => h('li', h('span.numero', String(i + 1)), h('div', h('b', s.titolo), h('p', s.testo)))))),
|
||||
passwordNote(windows),
|
||||
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
|
||||
message,
|
||||
h('div.molla'),
|
||||
h('div.bottoni-collegamento',
|
||||
h('button.btn.grande', { type: 'button', onclick: cancel }, t('impostazioni.collegamento.annulla')),
|
||||
h('button.btn.primo.grande', { type: 'button', onclick: () => finish(message) }, t('impostazioni.collegamento.hoFinito'))));
|
||||
}
|
||||
|
||||
async function cancel() {
|
||||
try {
|
||||
await api('/api/connection/cancel', { method: 'POST' });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
navigate('/impostazioni');
|
||||
}
|
||||
|
||||
async function finish(message) {
|
||||
const result = await finishDriving();
|
||||
if (!result) return;
|
||||
if (result.connected) {
|
||||
toast(result.message);
|
||||
status = await api('/api/connection', { signal: page.signal });
|
||||
draw();
|
||||
} else {
|
||||
fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message)));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- connected
|
||||
function drawConnected() {
|
||||
fill(left, h('div.pannello.collegato',
|
||||
h('div.chi-collegato', avatar(status.username || '', 'g'),
|
||||
h('div', h('h2', t('impostazioni.collegamento.collegatoCome', { nome: status.username || '' })), status.displayName ? h('span.muto', status.displayName) : null)),
|
||||
h('p', t('impostazioni.collegamento.collegatoTesto')),
|
||||
h('div.azioni-collegato',
|
||||
h('button.btn', { type: 'button', onclick: useBrowser }, icon('app-window', 's'), t('impostazioni.collegamento.usaBrowser')),
|
||||
h('button.btn.pericolo', { type: 'button', onclick: disconnect }, icon('log-out', 's'), t('impostazioni.collegamento.scollega'))),
|
||||
h('p.aiuto.piccolo', t('impostazioni.collegamento.usaBrowserTesto'))));
|
||||
fill(right,
|
||||
passwordNote(windows),
|
||||
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
|
||||
h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))));
|
||||
}
|
||||
|
||||
async function useBrowser() {
|
||||
if (windows) {
|
||||
await beginDriving(false);
|
||||
} else {
|
||||
navigate('/browser');
|
||||
}
|
||||
}
|
||||
|
||||
async function disconnect() {
|
||||
const choice = await confirmDialog({
|
||||
title: t('impostazioni.collegamento.scollegaTitolo'),
|
||||
text: t('impostazioni.collegamento.scollegaTesto'),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: 'no', kind: 'nudo', autofocus: true },
|
||||
{ label: t('impostazioni.collegamento.usaPrima'), value: 'browser', kind: '' },
|
||||
{ label: t('impostazioni.collegamento.scollegaConferma'), value: 'yes', kind: 'pericolo' },
|
||||
],
|
||||
});
|
||||
if (choice === 'browser') {
|
||||
useBrowser();
|
||||
return;
|
||||
}
|
||||
if (choice !== 'yes') return;
|
||||
try {
|
||||
await api('/api/connection/disconnect', { method: 'POST' });
|
||||
toast(t('impostazioni.collegamento.scollegato'));
|
||||
refreshEngine();
|
||||
status = await api('/api/connection', { signal: page.signal });
|
||||
draw();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- unavailable
|
||||
function drawUnavailable() {
|
||||
fill(left, h('div.vista.vista-finestra', h('div.vista-segnaposto',
|
||||
icon('octagon-alert', 'l'),
|
||||
h('h2', t('impostazioni.collegamento.nonDisponibileTitolo')),
|
||||
h('p', t('impostazioni.collegamento.nonDisponibileTesto')))));
|
||||
fill(right, passwordNote(windows), h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))));
|
||||
}
|
||||
|
||||
await draw();
|
||||
}
|
||||
|
||||
/** «La password va solo a Instagram», with the true wording of each shell (spec §10.3). */
|
||||
export function passwordNote(windows) {
|
||||
return h('div.avviso.nota-password', icon('shield-check', 's'),
|
||||
h('span', h('b', t('impostazioni.collegamento.passwordTitolo')), ' ', t(windows ? 'impostazioni.collegamento.passwordWindows' : 'impostazioni.collegamento.passwordDocker')));
|
||||
}
|
||||
|
||||
export default {
|
||||
mount: (page) => mountConnection(page),
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
// The strip of the day (spec §10.1, §7.9; mockups 06 and 11): a 24-hour bar with the sessions as irregular strokes,
|
||||
// the current session highlighted, the planned ones dashed (indicative), night and outside-window hatched, throttles
|
||||
// in amber, stops as a red hatch, the «adesso» line, hour ticks and a legend. Every stretch keeps its Italian label
|
||||
// from the server as a tooltip; a hidden list repeats them for screen readers.
|
||||
|
||||
import { h } from '../core/dom.js';
|
||||
import { t } from '../core/text.js';
|
||||
|
||||
const HOURS = [0, 3, 6, 9, 12, 15, 18, 21, 24];
|
||||
|
||||
/** Milliseconds of a time from the API (ISO text or number). */
|
||||
export function ms(value) {
|
||||
return typeof value === 'number' ? value : Date.parse(value);
|
||||
}
|
||||
|
||||
/** A small deterministic wobble (0..1) from a number: strokes look drawn by hand but stay put between updates. */
|
||||
function wobble(n) {
|
||||
const x = Math.sin(n * 12.9898) * 43758.5453;
|
||||
return x - Math.floor(x);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the strip of a DayStrip. Options: stopOpen (an open stop runs to the end of the day, mockup 11).
|
||||
* Returns { strip, hours, legend } so the page can place the legend in its header row.
|
||||
*/
|
||||
export function dayStrip(day, { stopOpen = false } = {}) {
|
||||
const start = ms(day.start);
|
||||
const end = ms(day.end);
|
||||
const now = ms(day.now);
|
||||
const span = Math.max(1, end - start);
|
||||
const pos = (value) => Math.min(100, Math.max(0, ((ms(value) - start) / span) * 100));
|
||||
const bar = h('div.striscia', { role: 'img', 'aria-label': `${t('attivita.striscia')}: ${day.summary}` });
|
||||
for (const hour of HOURS.slice(1, -1)) bar.append(h('span.tacca', { style: { left: `${(hour / 24) * 100}%` } }));
|
||||
|
||||
const kinds = new Set();
|
||||
const spoken = [];
|
||||
for (const s of day.spans) {
|
||||
const left = pos(s.start);
|
||||
let right = pos(s.end);
|
||||
if (s.kind === 'Stop' && stopOpen && ms(s.end) >= now - 60000) right = 100;
|
||||
const width = Math.max(0, right - left);
|
||||
const style = { left: `${left}%`, width: `${width}%` };
|
||||
let el = null;
|
||||
switch (s.kind) {
|
||||
case 'OutsideWindow':
|
||||
el = h('span.notte', { style });
|
||||
kinds.add('riposo');
|
||||
break;
|
||||
case 'Session':
|
||||
case 'CurrentSession':
|
||||
case 'PlannedSession': {
|
||||
const w = wobble(ms(s.start) / 60000);
|
||||
const inset = 6 + Math.round(w * 4);
|
||||
el = h(`span.sess${s.kind === 'CurrentSession' ? '.ora' : ''}${s.kind === 'PlannedSession' ? '.prev' : ''}`,
|
||||
{ style: { ...style, top: `${inset}px`, bottom: `${6 + Math.round((1 - w) * 4)}px` } });
|
||||
kinds.add(s.kind === 'PlannedSession' ? 'prossime' : 'sessione');
|
||||
break;
|
||||
}
|
||||
case 'Throttle':
|
||||
el = h('span.freno', { style });
|
||||
kinds.add('rallentamento');
|
||||
break;
|
||||
case 'Stop':
|
||||
el = h('span.fermo', { style });
|
||||
kinds.add('fermo');
|
||||
break;
|
||||
default:
|
||||
break; // rest between sessions is the plain background
|
||||
}
|
||||
if (el) {
|
||||
el.title = s.label;
|
||||
bar.append(el);
|
||||
if (s.kind !== 'OutsideWindow') spoken.push(s.label);
|
||||
}
|
||||
}
|
||||
if (now >= start && now <= end) {
|
||||
bar.append(h('span.adesso', { style: { left: `${pos(now)}%` }, title: t('attivita.adesso') }));
|
||||
}
|
||||
bar.append(h('ul.vh', spoken.map((label) => h('li', label))));
|
||||
|
||||
const hours = h('div.ore', { 'aria-hidden': 'true' }, HOURS.map((hour) => h('span', { style: { left: `${(hour / 24) * 100}%` } }, String(hour))));
|
||||
const items = [
|
||||
['sessione', h('i.l-sess')],
|
||||
['prossime', h('i.l-prev')],
|
||||
['rallentamento', h('i.l-freno')],
|
||||
['fermo', h('i.l-fermo')],
|
||||
['riposo', h('i.l-notte')],
|
||||
].filter(([key]) => key === 'sessione' || kinds.has(key));
|
||||
const legend = h('div.legenda', items.map(([key, swatch]) => h('span', swatch, t(`attivita.legenda.${key}`))));
|
||||
return { strip: bar, hours, legend };
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Doppioni da decidere (spec §9.5, §10.3): after a download, a photo that looks like one already in the same account
|
||||
// waits here for Alberto, with the same comparison as mockup 09. Both files stay until he chooses; the choice is
|
||||
// applied at once (so it asks for «Applica la scelta»), and what he discards is remembered and never downloaded again.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { refreshEngine } from '../core/engine.js';
|
||||
import { t } from '../core/text.js';
|
||||
import { showError, toast } from '../core/ui.js';
|
||||
import { comparePanel } from './compare.js';
|
||||
|
||||
export default {
|
||||
async mount(page) {
|
||||
page.title(t('doppioni.titolo'));
|
||||
const panel = comparePanel({
|
||||
load: (after) => api(`/api/duplicates?after=${after}`, { signal: page.signal }),
|
||||
decide: async (c, decision, applyAll) => {
|
||||
try {
|
||||
const result = await api(`/api/duplicates/${c.pairId}`, { method: 'POST', body: { decision, applyToAll: applyAll } });
|
||||
toast(result.message, result.problems.length ? 'errore' : '');
|
||||
refreshEngine();
|
||||
return { pending: result.pending, reload: true };
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
labels: { existing: t('doppioni.esistente'), existingInSource: t('doppioni.esistente'), candidate: t('doppioni.nuovo') },
|
||||
confirm: true,
|
||||
empty: t('doppioni.nessunoTesto'),
|
||||
});
|
||||
fill(page.body, h('div.pagina-doppioni', h('p.aiuto', icon('info', 'xs'), ' ', t('doppioni.aiuto')), panel.element));
|
||||
await panel.start();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,515 @@
|
||||
// Importa (mockup 09; spec §9.1, §9.3, §9.4): the four steps in the header (Sorgente, Analisi, Revisione, Copia).
|
||||
// 1 a folder (desktop: native picker; Docker: the subfolders of /importa); 2 the read-only analysis with a progress
|
||||
// bar, «Interrompi» and «Riprendi»; 3 the review: counters, folders → accounts (a folder without account blocks only its
|
||||
// files), the comparison of probable duplicates with nothing chosen in advance, Copia/Sposta («Sposta» hidden for a
|
||||
// read-only source), «Importa N file» with the «N restano fuori» line; 4 the copy, then the report with the CSV.
|
||||
// Addresses: /importa (the import in progress, or step 1), /importa?passo=1 (a new source), ?passo=3 (the review of
|
||||
// the latest import), ?id=N (a given import).
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { navigate, setQuery } from '../core/shell.js';
|
||||
import { t, number, bytes, at, capitalize } from '../core/text.js';
|
||||
import { checkbox, confirmDialog, dialog, segmented, showError, toast } from '../core/ui.js';
|
||||
import { comparePanel } from './compare.js';
|
||||
|
||||
const STEPS = ['sorgente', 'analisi', 'revisione', 'copia'];
|
||||
const STEP_OF = { analyzing: 2, analysisInterrupted: 2, reviewing: 3, copying: 4, copyInterrupted: 4, completed: 4, cancelled: 1 };
|
||||
|
||||
export default {
|
||||
async mount(page, route) {
|
||||
page.title(t('importa.titolo'));
|
||||
const steps = h('ol.passi-import', { 'aria-label': t('importa.passiEtichetta') });
|
||||
page.actions(steps);
|
||||
const overview = await api('/api/import', { signal: page.signal });
|
||||
const wanted = route.query.get('passo');
|
||||
const id = Number(route.query.get('id')) || null;
|
||||
let run = id ? overview.runs.find((r) => r.id === id) : null;
|
||||
if (!run && wanted !== '1') {
|
||||
run = overview.runs.find((r) => r.running)
|
||||
|| (wanted === '3' ? overview.runs.find((r) => r.state === 'reviewing') : null)
|
||||
|| overview.runs.find((r) => ['analyzing', 'analysisInterrupted', 'reviewing', 'copying', 'copyInterrupted'].includes(r.state));
|
||||
}
|
||||
|
||||
const ctx = { page, overview, steps };
|
||||
if (!run) return sourceStep(ctx);
|
||||
return showRun(ctx, run, wanted);
|
||||
},
|
||||
};
|
||||
|
||||
function drawSteps(ctx, current) {
|
||||
fill(ctx.steps, STEPS.map((key, i) => {
|
||||
const n = i + 1;
|
||||
const done = n < current || (n === 4 && current === 5);
|
||||
const here = n === current;
|
||||
return h(`li${done ? '.fatto' : ''}${here ? '.qui' : ''}`, { 'aria-current': here ? 'step' : null },
|
||||
h('span.cerchio', done ? icon('check', 'xs') : String(n)),
|
||||
h('span.nome', t(`importa.passi.${key}`)),
|
||||
done ? h('span.vh', t('importa.fatto')) : null);
|
||||
}));
|
||||
}
|
||||
|
||||
function showRun(ctx, run, wanted) {
|
||||
const step = STEP_OF[run.state] || 1;
|
||||
if (step === 2) return analysisStep(ctx, run);
|
||||
if (step === 3) return reviewStep(ctx, run);
|
||||
if (step === 4) return copyStep(ctx, run, wanted);
|
||||
return sourceStep(ctx);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- step 1: source
|
||||
|
||||
async function sourceStep(ctx) {
|
||||
const { page, overview } = ctx;
|
||||
drawSteps(ctx, 1);
|
||||
page.saveBar(null);
|
||||
const chosen = h('div.sorgente-scelta', { 'aria-live': 'polite' });
|
||||
let info = null;
|
||||
let stogram = false;
|
||||
|
||||
async function inspect(path) {
|
||||
try {
|
||||
info = await api('/api/import/inspect', { method: 'POST', body: { path }, signal: page.signal });
|
||||
stogram = false;
|
||||
drawChosen();
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function drawChosen() {
|
||||
if (!info) {
|
||||
chosen.replaceChildren();
|
||||
return;
|
||||
}
|
||||
fill(chosen, h('div.pannello.scelta-cartella',
|
||||
h('div.riga-cartella', h('div.campo.sola', icon('folder', 's'), h('span.val.dati', info.displayPath))),
|
||||
info.readOnly ? h('p.aiuto.piccolo', icon('lock', 'xs'), ' ', t('importa.sorgente.solaLettura')) : null,
|
||||
info.looksLikeFebeLibrary ? h('div.avviso', icon('info', 's'), h('span', t('importa.sorgente.febe'))) : null,
|
||||
info.looksLikeStogram ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.sorgente.stogramAiuto'))) : null,
|
||||
info.looksLikeStogram ? checkbox({ checked: false, label: t('importa.sorgente.stogram'), onchange: (v) => { stogram = v; } }) : null,
|
||||
h('div.riga-azione', h('button.btn.primo', { type: 'button', onclick: start }, icon('search', 's'), t('importa.sorgente.analizza')))));
|
||||
}
|
||||
|
||||
async function start() {
|
||||
try {
|
||||
const run = await api('/api/import/start', { method: 'POST', body: { path: info.path, stogram } });
|
||||
setQuery({ passo: null, id: String(run.id) }, { replace: true });
|
||||
analysisStep(ctx, run);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
// Docker: the subfolders of the root; desktop: the native picker.
|
||||
const picker = h('div');
|
||||
if (overview.sourceRoot) {
|
||||
const browse = async (path) => {
|
||||
try {
|
||||
const list = await api(`/api/import/sources${path ? `?path=${encodeURIComponent(path)}` : ''}`, { signal: page.signal });
|
||||
fill(picker, h('div.pannello.sfoglia',
|
||||
h('div.sfoglia-testa', icon('folder-open', 's'), h('span.dati', list.displayPath),
|
||||
list.parent != null ? h('button.btn.nudo.piccolo.destra', { type: 'button', onclick: () => browse(list.parent || null) }, icon('arrow-left', 's'), t('importa.sorgente.su')) : null),
|
||||
list.folders.length
|
||||
? h('ul.sfoglia-elenco', list.folders.map((f) => h('li',
|
||||
h('button.sfoglia-voce', { type: 'button', onclick: () => inspect(f.path) }, icon('folder', 's'), h('span', f.name)),
|
||||
f.hasSubfolders ? h('button.btn.nudo.solo', { type: 'button', 'aria-label': `${t('importa.sorgente.apri')} ${f.name}`, onclick: () => browse(f.path) }, icon('chevron-right', 's')) : null)))
|
||||
: h('p.vuoto-elenco', t('importa.sorgente.vuota'))));
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
}
|
||||
};
|
||||
await browse(null);
|
||||
} else {
|
||||
fill(picker, h('div.riga-azione', h('button.btn.primo.grande', {
|
||||
type: 'button',
|
||||
disabled: !overview.pickFolder,
|
||||
onclick: async () => {
|
||||
try {
|
||||
const result = await api('/api/import/pick-folder', { method: 'POST' });
|
||||
if (result.path) inspect(result.path);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
},
|
||||
}, icon('folder-open', 's'), t('importa.sorgente.scegli'))));
|
||||
}
|
||||
|
||||
const previous = overview.runs.length
|
||||
? h('div.sezione',
|
||||
h('h2.sez', t('importa.sorgente.precedenti')),
|
||||
h('div.pannello', h('ul.elenco-attivita', overview.runs.map((r) => h('li',
|
||||
h('span.quando.dati', capitalize(at(r.started))),
|
||||
h('div.chi-cosa', h('b.dati', r.displayPath), h('span', t(`importa.sorgente.stati.${r.state}`))),
|
||||
h('a.btn.piccolo', { href: withCarried(`/importa?id=${r.id}`) }, t('importa.sorgente.apri')))))))
|
||||
: null;
|
||||
|
||||
fill(page.body, h('div.importa-sorgente',
|
||||
h('div.sezione',
|
||||
h('h2.sez', t('importa.sorgente.titolo')),
|
||||
h('p.aiuto', t('importa.sorgente.aiuto')),
|
||||
overview.sourceRoot ? h('p.aiuto', t('importa.sorgente.aiutoDocker', { radice: overview.sourceRoot })) : null,
|
||||
picker,
|
||||
chosen),
|
||||
previous));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- step 2: analysis
|
||||
|
||||
function progressCard(ctx, run, { title, help, counting, interruptedText, resumeLabel }) {
|
||||
const { page } = ctx;
|
||||
const bar = h('div.misura.grande-misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100' }, h('i'));
|
||||
const count = h('p.conteggio.dati');
|
||||
const current = h('p.aiuto.piccolo.file-corrente');
|
||||
const found = h('p.aiuto');
|
||||
const buttons = h('div.riga-azione');
|
||||
const card = h('div.pannello.avanzamento-import', h('h2.sez', title), h('p.aiuto', help), bar, count, current, found, buttons);
|
||||
fill(page.body, h('div.importa-avanzamento', h('div.riga-sorgente', icon('folder', 's'), h('b.dati', run.displayPath)), card));
|
||||
let timer = 0;
|
||||
let stopped = false;
|
||||
page.onLeave(() => {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
});
|
||||
|
||||
return async function poll(onDone) {
|
||||
if (stopped) return;
|
||||
let progress;
|
||||
try {
|
||||
progress = await api(`/api/import/${run.id}/progress`, { signal: page.signal });
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
return;
|
||||
}
|
||||
const percent = Math.round(progress.fraction * 100);
|
||||
bar.firstChild.style.width = `${percent}%`;
|
||||
bar.setAttribute('aria-valuenow', String(percent));
|
||||
count.textContent = progress.phase === 'listing' ? t('importa.analisi.elenco') : counting(progress);
|
||||
current.textContent = progress.currentFile ? t('importa.analisi.ora', { file: progress.currentFile }) : '';
|
||||
const o = progress.outcomes;
|
||||
found.textContent = t('importa.analisi.trovati', { nuovi: number(o.new), gia: number(o.alreadyInLibrary + o.identicalInSource), doppioni: number(o.probableDuplicates), altri: number(o.unrecognized) });
|
||||
const interrupted = progress.state === 'analysisInterrupted' || progress.state === 'copyInterrupted';
|
||||
if (progress.running) {
|
||||
fill(buttons, h('button.btn', { type: 'button', onclick: interrupt }, icon('pause', 's'), t('importa.analisi.interrompi')));
|
||||
} else if (interrupted) {
|
||||
fill(buttons,
|
||||
h('p.avviso.ambra', icon('pause', 's'), h('span', interruptedText)),
|
||||
h('button.btn.primo', { type: 'button', onclick: resume }, icon('play', 's'), resumeLabel),
|
||||
h('button.btn.nudo', { type: 'button', onclick: discard }, t('importa.analisi.annulla')));
|
||||
}
|
||||
if (progress.error && !progress.running) fill(current, h('span.errore-testo', progress.error));
|
||||
if (!progress.running && !interrupted) {
|
||||
onDone(progress);
|
||||
return;
|
||||
}
|
||||
timer = setTimeout(() => poll(onDone), progress.running ? 1000 : 5000);
|
||||
};
|
||||
|
||||
async function interrupt() {
|
||||
try {
|
||||
const result = await api(`/api/import/${run.id}/interrupt`, { method: 'POST' });
|
||||
toast(result.message);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function resume() {
|
||||
try {
|
||||
await api(`/api/import/${run.id}/resume`, { method: 'POST' });
|
||||
navigate(`/importa?id=${run.id}`, { replace: true });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function discard() {
|
||||
const ok = await confirmDialog({
|
||||
title: t('importa.analisi.annullaTitolo'),
|
||||
text: t('importa.analisi.annullaTesto'),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
|
||||
{ label: t('importa.analisi.annulla'), value: true, kind: 'pericolo' },
|
||||
],
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const result = await api(`/api/import/${run.id}/discard`, { method: 'POST' });
|
||||
toast(result.message);
|
||||
navigate('/importa?passo=1', { replace: true });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function analysisStep(ctx, run) {
|
||||
drawSteps(ctx, 2);
|
||||
ctx.page.saveBar(null);
|
||||
const poll = progressCard(ctx, run, {
|
||||
title: t('importa.analisi.titolo'),
|
||||
help: t('importa.analisi.aiuto'),
|
||||
counting: (p) => t('importa.analisi.conteggio', { fatti: number(p.filesDone), totale: number(p.filesTotal) }),
|
||||
interruptedText: t('importa.analisi.interrotta'),
|
||||
resumeLabel: t('importa.analisi.riprendi'),
|
||||
});
|
||||
poll(() => reviewStep(ctx, run));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- step 3: review
|
||||
|
||||
async function reviewStep(ctx, run) {
|
||||
const { page } = ctx;
|
||||
drawSteps(ctx, 3);
|
||||
let review;
|
||||
try {
|
||||
review = await api(`/api/import/${run.id}/review`, { signal: page.signal });
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
return;
|
||||
}
|
||||
|
||||
const counters = h('div.contatori.pannello');
|
||||
const table = h('tbody');
|
||||
const notes = h('div');
|
||||
const compare = comparePanel({
|
||||
load: (after) => api(`/api/import/${run.id}/duplicates?all=true&after=${after}`, { signal: page.signal }),
|
||||
decide: async (c, decision, applyAll) => {
|
||||
try {
|
||||
const result = await api(`/api/import/${run.id}/duplicates/${c.pairId}`, { method: 'POST', body: { decision, applyToAll: applyAll } });
|
||||
review = await api(`/api/import/${run.id}/review`, { signal: page.signal });
|
||||
drawCounters();
|
||||
drawBar();
|
||||
return { pending: result.pending, reload: applyAll };
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
labels: { existing: t('importa.doppioni.inLibreria'), existingInSource: t('importa.doppioni.nellaSorgente'), candidate: t('importa.doppioni.daImportare') },
|
||||
});
|
||||
|
||||
function counter(kind, value, key) {
|
||||
return h('div.contatore', h('div.riga', h(`span.spia${kind ? '.' + kind : ''}`, { 'aria-hidden': 'true' }), h('b.dati', number(value))),
|
||||
h('span.nome', t(`importa.revisione.contatori.${key}.titolo`)), h('span.muto', t(`importa.revisione.contatori.${key}.testo`)));
|
||||
}
|
||||
|
||||
function drawCounters() {
|
||||
const o = review.outcomes;
|
||||
fill(counters,
|
||||
counter('verde', o.new, 'new'),
|
||||
counter('', o.alreadyInLibrary + o.identicalInSource, 'already'),
|
||||
counter('ambra', o.probableDuplicates, 'dup'),
|
||||
counter('grigio', o.unrecognized, 'unrec'));
|
||||
}
|
||||
|
||||
function targetSelect(folder) {
|
||||
const select = h('select', { 'aria-label': `${t('importa.revisione.colonne.va')}: ${folder.displayName || review.displayPath}` });
|
||||
const target = folder.target;
|
||||
const proposed = target.kind === 'newArchiveAccount' ? target.username
|
||||
: folder.probableAccount && !review.accounts.some((a) => a.username === folder.probableAccount) ? folder.probableAccount : null;
|
||||
select.append(h('option', { value: 'none' }, t('importa.revisione.scegli')));
|
||||
if (proposed) select.append(h('option', { value: `new:${proposed}`, title: `@${proposed}` }, t('importa.revisione.nuovo')));
|
||||
select.append(h('option', { value: 'ask' }, t('importa.revisione.nuovoAltro')));
|
||||
select.append(h('optgroup', { label: t('importa.revisione.esistenti') }, review.accounts.map((a) => h('option', { value: `id:${a.id}` }, `@${a.username}`))));
|
||||
select.value = target.kind === 'existing' ? `id:${target.accountId}` : target.kind === 'newArchiveAccount' ? `new:${target.username}` : 'none';
|
||||
select.addEventListener('change', async () => {
|
||||
const v = select.value;
|
||||
let body;
|
||||
if (v === 'none') body = { folder: folder.folder, kind: 'none' };
|
||||
else if (v.startsWith('id:')) body = { folder: folder.folder, kind: 'existing', accountId: Number(v.slice(3)) };
|
||||
else if (v.startsWith('new:')) body = { folder: folder.folder, kind: 'newArchiveAccount', username: v.slice(4) };
|
||||
else {
|
||||
const name = await askName(proposed || folder.displayName || '');
|
||||
if (!name) {
|
||||
drawTable();
|
||||
return;
|
||||
}
|
||||
body = { folder: folder.folder, kind: 'newArchiveAccount', username: name };
|
||||
}
|
||||
try {
|
||||
review = await api(`/api/import/${run.id}/folders`, { method: 'PUT', body });
|
||||
drawAll();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
drawTable();
|
||||
}
|
||||
});
|
||||
const blocked = folder.blocked && folder.files > folder.unrecognized;
|
||||
return h(`label.campo.scelta${blocked ? '.errore' : ''}`, { title: target.kind === 'newArchiveAccount' ? t('importa.revisione.nuovoNome', { nome: target.username }) : null }, select, icon('chevron-down', 's'));
|
||||
}
|
||||
|
||||
function drawTable() {
|
||||
fill(table, review.folders.map((f) => h('tr',
|
||||
h('td', h('b', f.displayName || review.displayPath), f.blocked && !f.probableAccount ? h('div.muto.piccolo', t('importa.revisione.nessunNome')) : null),
|
||||
h('td.num.dati', { 'data-etichetta': t('importa.revisione.colonne.file') }, number(f.files)),
|
||||
h('td.col-va', targetSelect(f)),
|
||||
h('td.num.dati', { 'data-etichetta': t('importa.revisione.colonne.nuovi') }, number(f.new)),
|
||||
h('td.num.dati', { 'data-etichetta': t('importa.revisione.colonne.presenti') }, number(f.alreadyInLibrary)))));
|
||||
}
|
||||
|
||||
function drawNotes() {
|
||||
fill(notes,
|
||||
review.recognized > 0 ? h('div.avviso', icon('info', 's'), h('span', t('importa.revisione.riconosciuti', { n: number(review.recognized) }))) : null,
|
||||
review.stogramHypothesis ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.revisione.stogram'))) : null);
|
||||
}
|
||||
|
||||
// The fixed bar: Copia/Sposta, what stays out, CSV, «Importa N file».
|
||||
let mode = review.plan.mode;
|
||||
function drawBar() {
|
||||
const plan = review.plan;
|
||||
const modes = review.canMove
|
||||
? segmented({
|
||||
label: t('importa.barra.modo'),
|
||||
value: mode,
|
||||
options: [{ value: 'copy', label: t('importa.barra.copia') }, { value: 'move', label: t('importa.barra.sposta') }],
|
||||
onchange: async (v) => {
|
||||
try {
|
||||
review.plan = await api(`/api/import/${run.id}/mode`, { method: 'PUT', body: { mode: v } });
|
||||
mode = v;
|
||||
drawBar();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
},
|
||||
})
|
||||
: h('div.gruppo', h('span.qui', t('importa.barra.copia')));
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
modes,
|
||||
h('span.nota.importa-barra-modo', t(mode === 'move' ? 'importa.barra.spostaAiuto' : 'importa.barra.copiaAiuto')),
|
||||
h('div.destra',
|
||||
plan.leftOutLabel ? h('span.nota.fuori', plan.leftOutLabel) : null,
|
||||
h('a.btn.esporta-csv', { href: `/api/import/${run.id}/report.csv`, download: '', title: t('importa.barra.esporta') }, icon('file-down', 's'), h('span.testo-csv', t('importa.barra.esporta'))),
|
||||
h('button.btn.primo', { type: 'button', disabled: plan.toImport === 0, onclick: startCopy }, plan.buttonLabel))));
|
||||
}
|
||||
|
||||
async function startCopy() {
|
||||
if (mode === 'move') {
|
||||
const ok = await confirmDialog({
|
||||
title: t('importa.sposta.titolo'),
|
||||
text: t('importa.sposta.testo'),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
|
||||
{ label: t('importa.sposta.conferma'), value: true, kind: 'primo' },
|
||||
],
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
try {
|
||||
const updated = await api(`/api/import/${run.id}/copy`, { method: 'POST', body: { mode } });
|
||||
copyStep(ctx, updated);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function drawAll() {
|
||||
drawCounters();
|
||||
drawTable();
|
||||
drawNotes();
|
||||
drawBar();
|
||||
}
|
||||
|
||||
drawAll();
|
||||
fill(page.body, h('div.importa-revisione',
|
||||
h('div.riga-sorgente', icon('folder', 's'), h('b.dati', review.displayPath), h('span.muto', review.headline),
|
||||
h('a.btn.collegamento.destra', { href: withCarried('/importa?passo=1') }, t('importa.revisione.cambia'))),
|
||||
counters,
|
||||
h('div.revisione-colonne',
|
||||
h('section.cartelle-account',
|
||||
h('h2', t('importa.revisione.cartelle')),
|
||||
h('div.pannello', h('table.tab',
|
||||
h('thead', h('tr',
|
||||
h('th', t('importa.revisione.colonne.cartella')),
|
||||
h('th.num', t('importa.revisione.colonne.file')),
|
||||
h('th', t('importa.revisione.colonne.va')),
|
||||
h('th.num', t('importa.revisione.colonne.nuovi')),
|
||||
h('th.num', t('importa.revisione.colonne.presenti')))),
|
||||
table)),
|
||||
notes),
|
||||
compare.element)));
|
||||
await compare.start();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- step 4: copy and report
|
||||
|
||||
function copyStep(ctx, run) {
|
||||
if (run.state === 'completed' || run.state === 'cancelled') return reportStep(ctx, run);
|
||||
drawSteps(ctx, 4);
|
||||
ctx.page.saveBar(null);
|
||||
const poll = progressCard(ctx, run, {
|
||||
title: t('importa.copia.titolo'),
|
||||
help: t('importa.copia.aiuto'),
|
||||
counting: (p) => t('importa.copia.conteggio', { fatti: number(p.filesDone), totale: number(p.filesTotal), copiati: number(p.copied) }),
|
||||
interruptedText: t('importa.copia.interrotta'),
|
||||
resumeLabel: t('importa.copia.riprendi'),
|
||||
});
|
||||
poll(async () => {
|
||||
const latest = await api(`/api/import/${run.id}/progress`, { signal: ctx.page.signal });
|
||||
reportStep(ctx, { ...run, state: latest.state });
|
||||
});
|
||||
}
|
||||
|
||||
async function reportStep(ctx, run) {
|
||||
const { page } = ctx;
|
||||
drawSteps(ctx, 5);
|
||||
page.saveBar(null);
|
||||
let report;
|
||||
try {
|
||||
report = await api(`/api/import/${run.id}/report`, { signal: page.signal });
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
return;
|
||||
}
|
||||
const big = (value, key, kind = '') => h('div.contatore', h('div.riga', kind ? h(`span.spia.${kind}`, { 'aria-hidden': 'true' }) : null, h('b.dati', number(value))), h('span.nome', t(`importa.resoconto.${key}`)));
|
||||
const accounts = (items) => items.length
|
||||
? h('ul.elenco-semplice', items.map((a) => h('li', h('span', `@${a.username}`), h('span.dati', number(a.files)))))
|
||||
: h('p.muto', t('importa.resoconto.nessuno'));
|
||||
const done = report.run.completed ? at(report.run.completed) : '';
|
||||
fill(page.body, h('div.importa-resoconto',
|
||||
h('div.riga-sorgente', icon('folder', 's'), h('b.dati', report.displayPath),
|
||||
h('span.muto', report.run.state === 'cancelled' ? t('importa.resoconto.annullata') : t('importa.resoconto.completata', { quando: done }))),
|
||||
h('div.contatori.pannello',
|
||||
big(report.copied, 'copiati', 'verde'),
|
||||
big(report.skipped, 'saltati'),
|
||||
big(report.leftOut, 'fuori', report.leftOut ? 'ambra' : ''),
|
||||
big(report.failed, 'falliti', report.failed ? 'rosso' : '')),
|
||||
report.moved || report.replaced
|
||||
? h('p.aiuto', [report.moved ? `${t('importa.resoconto.spostati')}: ${number(report.moved)}` : null, report.replaced ? `${t('importa.resoconto.sostituiti')}: ${number(report.replaced)}` : null].filter(Boolean).join(' · '), ` · ${bytes(report.bytesCopied)}`)
|
||||
: h('p.aiuto', bytes(report.bytesCopied)),
|
||||
h('div.due-colonne',
|
||||
h('section', h('h2', t('importa.resoconto.perAccount')), h('div.pannello', accounts(report.importedByAccount))),
|
||||
h('section', h('h2', t('importa.resoconto.giaPerAccount')), h('div.pannello', accounts(report.alreadyInLibraryByAccount)))),
|
||||
report.unrecognized.length ? h('section.blocco', h('h2', t('importa.resoconto.nonRiconosciuti')),
|
||||
h('div.pannello', h('ul.elenco-semplice', report.unrecognized.map((u) => h('li.dati', u))))) : null,
|
||||
report.problems.length ? h('section.blocco', h('h2', t('importa.resoconto.problemi')),
|
||||
h('div.pannello', h('ul.elenco-semplice', report.problems.map((p) => h('li', h('span.dati', p.path), h('span.muto', p.note)))))) : null,
|
||||
h('div.riga-azione',
|
||||
h('a.btn', { href: `/api/import/${run.id}/report.csv`, download: '' }, icon('file-down', 's'), t('importa.barra.esporta')),
|
||||
report.leftOut > 0 && report.run.state === 'completed' ? h('button.btn', { type: 'button', onclick: () => reviewStep(ctx, report.run) }, t('importa.resoconto.rimasti')) : null,
|
||||
h('a.btn', { href: withCarried('/importa?passo=1') }, icon('plus', 's'), t('importa.resoconto.nuova')),
|
||||
h('a.btn.primo', { href: withCarried('/libreria?provenienza=importati') }, icon('layout-grid', 's'), t('importa.resoconto.libreria')))));
|
||||
}
|
||||
|
||||
/** The name of a new «Solo archivio» account (a user name: letters, digits, dots and underscores). */
|
||||
function askName(proposed) {
|
||||
return dialog({
|
||||
title: t('importa.revisione.nuovoChiedi'),
|
||||
className: 'piccolo',
|
||||
build: (close) => {
|
||||
const input = h('input.dati', { type: 'text', value: proposed, autocomplete: 'off', spellcheck: 'false', id: 'nuovo-account' });
|
||||
const ok = () => {
|
||||
const name = input.value.trim().replace(/^@/, '');
|
||||
if (/^[A-Za-z0-9._]{1,30}$/.test(name)) close(name);
|
||||
else input.parentElement.classList.add('errore');
|
||||
};
|
||||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') ok(); });
|
||||
return {
|
||||
body: h('div.contenuto', h('label.etichetta', { for: 'nuovo-account' }, t('importa.revisione.nuovoChiedi')), h('label.campo', input), h('p.aiuto.piccolo', t('importa.revisione.nomeRegole'))),
|
||||
footer: h('footer', h('div.destra',
|
||||
h('button.btn.nudo', { type: 'button', onclick: () => close(null) }, t('comune.annulla')),
|
||||
h('button.btn.primo', { type: 'button', onclick: ok }, t('importa.revisione.nuovo')))),
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
// Libreria (mockup 01, spec §4.6): every entry by publication day, filters by kind, account, period and provenance,
|
||||
// search by account name and caption, tile size, multiple selection to export or delete, viewer on click.
|
||||
|
||||
import { api, download } from '../core/api.js';
|
||||
import { api, download, withCarried } from '../core/api.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { h, icon, fill, later, local } from '../core/dom.js';
|
||||
import { setQuery } from '../core/shell.js';
|
||||
import { t, number, shortDay, parseDay } from '../core/text.js';
|
||||
import { menu, showError, toast, confirmDialog } from '../core/ui.js';
|
||||
import { engineState } from '../core/engine.js';
|
||||
import { Mosaic } from './mosaic.js';
|
||||
import { welcome } from './welcome.js';
|
||||
import { openViewer } from './viewer.js';
|
||||
|
||||
const KINDS = [
|
||||
@@ -89,11 +91,19 @@ export default {
|
||||
const size = local.get('libreria.tessere', 160);
|
||||
const slider = h('input.cursore', { type: 'range', min: '96', max: '300', step: '4', value: String(size), 'aria-label': t('libreria.grandezza') });
|
||||
const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona')));
|
||||
// Probable duplicates after a download wait for Alberto (spec §9.5): a short link to their review.
|
||||
const duplicates = h('a.btn.nudo.piccolo.doppioni-link', { href: withCarried('/doppioni'), hidden: true });
|
||||
api('/api/duplicates/count', { signal: page.signal }).then((counts) => {
|
||||
if (!counts.download) return;
|
||||
fill(duplicates, icon('layers', 's'), t('libreria.doppioni', { n: counts.download }));
|
||||
duplicates.hidden = false;
|
||||
}).catch(() => {});
|
||||
page.tools(h('div', { style: { display: 'contents' } },
|
||||
chips,
|
||||
h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton),
|
||||
filtersButton,
|
||||
h('div.destra',
|
||||
duplicates,
|
||||
h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')),
|
||||
selectButton)));
|
||||
|
||||
@@ -323,7 +333,9 @@ export default {
|
||||
onEmpty: () => fill(host, filtersActive()
|
||||
? h('div.vuoto-pagina', icon('list-filter'), h('h2', t('libreria.nessuno')), h('p', t('libreria.nessunoTesto')),
|
||||
h('button.btn', { type: 'button', onclick: () => { Object.assign(state, readState(new URLSearchParams())); search.value = ''; apply(); } }, t('libreria.togliFiltri')))
|
||||
: h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')))),
|
||||
: notConnected()
|
||||
? welcome()
|
||||
: h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')))),
|
||||
});
|
||||
try {
|
||||
await mosaic.start();
|
||||
@@ -371,3 +383,9 @@ export async function confirmDelete(ids) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** First start (spec §10.3): not connected to Instagram, so the empty library offers the two ways to begin. */
|
||||
function notConnected() {
|
||||
const state = engineState();
|
||||
return Boolean(state && state.connection && state.connection.state === 'notConnected');
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
// Pages that arrive with the second part of the interface (Attività, Importa, Impostazioni, Browser), and the page for
|
||||
// unknown addresses. The next agent replaces each route of js/routes.js with its own module.
|
||||
// The page for unknown addresses («Pagina non trovata»).
|
||||
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { withCarried } from '../core/api.js';
|
||||
@@ -14,8 +13,6 @@ export default {
|
||||
h('a.btn', { href: withCarried('/libreria') }, t('pagine.vaiLibreria'))));
|
||||
return;
|
||||
}
|
||||
const title = route.params.section ? `${t('pagine.impostazioni')}: ${t(`pagine.sezioni.${route.params.section}`)}` : t(`pagine.${key}`);
|
||||
page.title(title);
|
||||
fill(page.body, h('div.vuoto-pagina.prossimamente', icon('hourglass'), h('h2', title), h('p', t('pagine.prossimamente'))));
|
||||
page.title(t(`pagine.${key}`));
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
// The configuration error page (spec §8.2, §11): when GET /api/capabilities lists problems (missing FEBE_PASSWORD,
|
||||
// Data folder not writable or on a network share, WebView2 missing) the engine does not start and the interface shows
|
||||
// only this page: for each problem what is wrong, what Febe did and what to do.
|
||||
|
||||
import { h, icon, fill, brand } from '../core/dom.js';
|
||||
import { t } from '../core/text.js';
|
||||
|
||||
export function showProblems(root, problems) {
|
||||
document.title = t('app.titoloPagina', { pagina: t('problemi.titolo') });
|
||||
fill(root, h('main.pagina-problemi', { id: 'contenuto' },
|
||||
h('div.problemi-testa', h('span.marchio-piccolo', brand()), h('b', t('app.nome'))),
|
||||
h('h1', t('problemi.titolo')),
|
||||
h('p.aiuto', t('problemi.aiuto', { n: problems.length })),
|
||||
problems.map((p) => h('section.pannello.problema', { 'data-codice': p.code },
|
||||
h('h2', icon('octagon-alert', 'l'), h('span', p.title)),
|
||||
h('h3', t('problemi.cosa')),
|
||||
h('p', p.message),
|
||||
h('h3', t('problemi.rimedio')),
|
||||
h('p.rimedio', p.remedy))),
|
||||
h('div.riga-azione', h('button.btn.primo', { type: 'button', onclick: () => location.reload() }, icon('refresh-cw', 's'), t('problemi.ricarica'))),
|
||||
h('p.aiuto.piccolo', t('problemi.guida'))));
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// The remote view of Febe's browser (Docker; spec §4.1, §11, mockup 10; protocol in src/Febe.Web/Connection/PROTOCOLLO.md):
|
||||
// JPEG frames from the WebSocket /api/vista drawn on a canvas, mouse and keyboard sent back as relative coordinates and
|
||||
// key messages. Keys are never logged or kept here: they go straight to the socket. The page of Instagram is never
|
||||
// redrawn or imitated: without a browser (demo, or the server not answering) the area shows a neutral placeholder.
|
||||
|
||||
import { caps } from '../core/context.js';
|
||||
import { h, icon, fill, perFrame } from '../core/dom.js';
|
||||
import { t } from '../core/text.js';
|
||||
import { label } from '../core/ui.js';
|
||||
|
||||
const BUTTONS = ['left', 'middle', 'right'];
|
||||
|
||||
/** Modifier bits of the DevTools protocol: Alt 1, Ctrl 2, Meta 4, Shift 8. */
|
||||
function modifiers(e) {
|
||||
return (e.altKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.metaKey ? 4 : 0) | (e.shiftKey ? 8 : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the remote view. options: url (address to show before the first frame), login (the placeholder speaks of the
|
||||
* login page). Returns { element, close }. The socket closes when the page is left.
|
||||
*/
|
||||
export function remoteView(page, { url = null, login = false } = {}) {
|
||||
const address = h('span.dati');
|
||||
const back = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.indietro'), title: t('browser.indietro'), onclick: () => send({ type: 'navigate', action: 'back' }) }, icon('arrow-left'));
|
||||
const reload = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.ricarica'), title: t('browser.ricarica'), onclick: () => send({ type: 'navigate', action: 'reload' }) }, icon('rotate-cw'));
|
||||
const bar = h('div.vista-barra',
|
||||
back, reload,
|
||||
h('div.vista-indirizzo', { 'aria-label': t('browser.indirizzo') }, icon('lock', 's'), address),
|
||||
label(t('browser.vista')));
|
||||
const canvas = h('canvas.vista-schermo', { tabindex: '0', 'aria-label': t('browser.schermo'), hidden: true, width: '1280', height: '900' });
|
||||
const status = h('div.vista-stato');
|
||||
const area = h('div.vista-area', canvas, status);
|
||||
const element = h('div.vista', bar, area);
|
||||
const context = canvas.getContext('2d');
|
||||
let socket = null;
|
||||
let closed = false;
|
||||
let frames = 0;
|
||||
|
||||
function showAddress(value) {
|
||||
if (!value) {
|
||||
address.replaceChildren();
|
||||
return;
|
||||
}
|
||||
const clean = String(value).replace(/^https?:\/\//, '');
|
||||
const slash = clean.indexOf('/');
|
||||
fill(address, h('b', slash < 0 ? clean : clean.slice(0, slash)), slash < 0 ? '' : clean.slice(slash));
|
||||
}
|
||||
|
||||
/** The neutral placeholder of mockup 10: never a drawing of Instagram's page. */
|
||||
function placeholder() {
|
||||
canvas.hidden = true;
|
||||
fill(status, h('div.vista-segnaposto',
|
||||
h('div.scheletro', { 'aria-hidden': 'true' }, h('i.s1'), h('i.s2'), h('i.s2'), h('i.s3'), h('i.s4')),
|
||||
h('p', t(login ? 'browser.segnapostoAccesso' : 'browser.segnaposto'))));
|
||||
status.hidden = false;
|
||||
}
|
||||
|
||||
function failure() {
|
||||
canvas.hidden = true;
|
||||
fill(status, h('div.vista-segnaposto',
|
||||
icon('triangle-alert', 'l'),
|
||||
h('p', t('browser.nonRisponde')),
|
||||
h('button.btn', { type: 'button', onclick: connect }, icon('refresh-cw', 's'), t('browser.riprova'))));
|
||||
status.hidden = false;
|
||||
}
|
||||
|
||||
function send(message) {
|
||||
if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (closed) return;
|
||||
if (caps().demo) {
|
||||
placeholder();
|
||||
return;
|
||||
}
|
||||
fill(status, h('div.vista-segnaposto', icon('hourglass', 'l'), h('p', t('browser.collegamento'))));
|
||||
status.hidden = false;
|
||||
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
try {
|
||||
socket = new WebSocket(`${scheme}://${location.host}/api/vista`);
|
||||
} catch {
|
||||
failure();
|
||||
return;
|
||||
}
|
||||
socket.binaryType = 'blob';
|
||||
socket.addEventListener('message', async (e) => {
|
||||
if (typeof e.data === 'string') {
|
||||
try {
|
||||
const meta = JSON.parse(e.data);
|
||||
if (meta.type === 'meta') {
|
||||
if (meta.width && meta.height && (canvas.width !== meta.width || canvas.height !== meta.height)) {
|
||||
canvas.width = meta.width;
|
||||
canvas.height = meta.height;
|
||||
}
|
||||
showAddress(meta.url);
|
||||
}
|
||||
} catch {
|
||||
// not a message of the protocol
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const bitmap = await createImageBitmap(e.data);
|
||||
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
||||
bitmap.close();
|
||||
frames += 1;
|
||||
if (frames === 1) {
|
||||
canvas.hidden = false;
|
||||
status.hidden = true;
|
||||
}
|
||||
} catch {
|
||||
// a frame that cannot be decoded is skipped
|
||||
}
|
||||
});
|
||||
socket.addEventListener('close', () => {
|
||||
socket = null;
|
||||
if (!closed) failure();
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- input
|
||||
function point(e) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
return {
|
||||
x: Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width)),
|
||||
y: Math.min(1, Math.max(0, (e.clientY - rect.top) / rect.height)),
|
||||
};
|
||||
}
|
||||
const move = perFrame((e) => send({ type: 'mouse', action: 'move', ...point(e), button: 'left', deltaX: 0, deltaY: 0, clickCount: 0 }));
|
||||
canvas.addEventListener('mousemove', move);
|
||||
canvas.addEventListener('mousedown', (e) => {
|
||||
canvas.focus();
|
||||
e.preventDefault();
|
||||
send({ type: 'mouse', action: 'down', ...point(e), button: BUTTONS[e.button] || 'left', deltaX: 0, deltaY: 0, clickCount: e.detail || 1 });
|
||||
});
|
||||
canvas.addEventListener('mouseup', (e) => {
|
||||
e.preventDefault();
|
||||
send({ type: 'mouse', action: 'up', ...point(e), button: BUTTONS[e.button] || 'left', deltaX: 0, deltaY: 0, clickCount: e.detail || 1 });
|
||||
});
|
||||
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
|
||||
canvas.addEventListener('wheel', (e) => {
|
||||
e.preventDefault();
|
||||
const scale = e.deltaMode === 1 ? 40 : e.deltaMode === 2 ? 800 : 1;
|
||||
send({ type: 'mouse', action: 'wheel', ...point(e), button: 'left', deltaX: Math.round(e.deltaX * scale), deltaY: Math.round(e.deltaY * scale), clickCount: 0 });
|
||||
}, { passive: false });
|
||||
canvas.addEventListener('keydown', (e) => {
|
||||
// Ctrl/Cmd+V goes through the paste event below (the clipboard is Alberto's, not the server's).
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') return;
|
||||
e.preventDefault();
|
||||
const printable = e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey;
|
||||
send({ type: 'key', action: 'down', key: e.key, code: e.code, text: printable ? e.key : '', modifiers: modifiers(e) });
|
||||
});
|
||||
canvas.addEventListener('keyup', (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') return;
|
||||
e.preventDefault();
|
||||
send({ type: 'key', action: 'up', key: e.key, code: e.code, text: '', modifiers: modifiers(e) });
|
||||
});
|
||||
const onPaste = (e) => {
|
||||
if (document.activeElement !== canvas) return;
|
||||
e.preventDefault();
|
||||
const text = (e.clipboardData && e.clipboardData.getData('text')) || '';
|
||||
for (const ch of text) send({ type: 'key', action: 'char', key: ch, code: '', text: ch, modifiers: 0 });
|
||||
};
|
||||
document.addEventListener('paste', onPaste);
|
||||
|
||||
function close() {
|
||||
closed = true;
|
||||
document.removeEventListener('paste', onPaste);
|
||||
if (socket) socket.close();
|
||||
socket = null;
|
||||
}
|
||||
page.onLeave(close);
|
||||
|
||||
showAddress(url);
|
||||
connect();
|
||||
return { element, close, showAddress };
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Impostazioni, Informazioni: version and shell, where the guide is (the wiki of the repository), the folders, the
|
||||
// statement on the risk for the account (spec §1, §15 «che cosa la guida deve dire»), the licenses of what Febe
|
||||
// carries inside (Archivo OFL, Lucide ISC, SQLite, SkiaSharp, .NET, WebView2).
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill, brand } from '../core/dom.js';
|
||||
import { t } from '../core/text.js';
|
||||
import { heading } from './settings.js';
|
||||
|
||||
export default async function about(page, box) {
|
||||
const data = await api('/api/about', { signal: page.signal });
|
||||
const components = t('impostazioni.informazioni.componenti');
|
||||
fill(box,
|
||||
h('div.sezione.informazioni',
|
||||
h('div.marchio-grande', brand(), h('div', h('b', t('app.nome')), h('span.muto', `${t('impostazioni.informazioni.versione')} ${data.version} · ${t(`impostazioni.informazioni.vesti.${data.edition}`)}`)))),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.informazioni.guida'), t('impostazioni.informazioni.guidaTesto')),
|
||||
h('a.btn', { href: data.guide, target: '_blank', rel: 'noopener noreferrer' }, icon('external-link', 's'), t('impostazioni.informazioni.apriGuida'))),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.informazioni.cartelle')),
|
||||
h('dl.dati-db',
|
||||
h('dt', t('impostazioni.informazioni.cartellaLibreria')), h('dd.dati', data.libraryFolder),
|
||||
h('dt', t('impostazioni.informazioni.cartellaDati')), h('dd.dati', data.dataFolder))),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.informazioni.rischioTitolo')),
|
||||
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.informazioni.rischio')))),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.informazioni.licenze'), t('impostazioni.informazioni.licenzeAiuto')),
|
||||
h('ul.licenze', (Array.isArray(components) ? components : []).map((c) => h('li',
|
||||
h('b', c.nome), h('span.muto', ` — ${c.testo}`),
|
||||
c.file ? h('a', { href: c.file, target: '_blank', rel: 'noopener' }, t('impostazioni.informazioni.leggiLicenza')) : null)))));
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// Impostazioni, Dati e copie di sicurezza (spec §8.2, §8.5): the Data folder with its size and the warning that whoever
|
||||
// has it (or a copy) has the Instagram session; the seven daily copies of the database with «Fai una copia adesso»;
|
||||
// «Ricostruisci il database dalla libreria» with a strong confirmation (the word typed by Alberto), progress and report.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { t, bytes, number, at, dayName } from '../core/text.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { dialog, showError, toast } from '../core/ui.js';
|
||||
import { heading } from './settings.js';
|
||||
|
||||
export default async function dataSettings(page, box) {
|
||||
let data = await api('/api/settings/data', { signal: page.signal });
|
||||
let timer = 0;
|
||||
page.onLeave(() => clearTimeout(timer));
|
||||
|
||||
const folder = h('div');
|
||||
const backups = h('div');
|
||||
const rebuild = h('div');
|
||||
|
||||
function drawFolder() {
|
||||
const d = data.data;
|
||||
const space = d.usedBytes == null
|
||||
? t('impostazioni.dati.spazioMisura')
|
||||
: t('impostazioni.dati.spazio', { usati: bytes(d.usedBytes), liberi: d.freeBytes == null ? '—' : bytes(d.freeBytes) });
|
||||
fill(folder,
|
||||
h('div.riga-cartella', h('div.campo.sola', { title: d.path }, icon('folder', 's'), h('span.val.dati', d.path)), h('span.spazio.dati', space)),
|
||||
h('dl.dati-db',
|
||||
h('dt', t('impostazioni.dati.database')), h('dd.dati', data.database, data.databaseBytes != null ? ` · ${bytes(data.databaseBytes)}` : '')),
|
||||
h('div.avviso.ambra', { style: { marginTop: '14px' } }, icon('shield-alert', 's'), h('span', t('impostazioni.dati.sessione'))));
|
||||
}
|
||||
|
||||
function drawBackups() {
|
||||
const rows = data.backups.map((b) => h('tr',
|
||||
h('td', dayName(b.day, caps().today)),
|
||||
h('td.dati', b.name),
|
||||
h('td.dati.num', bytes(b.bytes)),
|
||||
h('td.muto', at(b.modified))));
|
||||
fill(backups,
|
||||
h('p.aiuto', t('impostazioni.dati.copieAiuto', { cartella: data.backupsFolder, n: data.keepDays })),
|
||||
h('div.riga-azione', h('button.btn', { type: 'button', onclick: backupNow }, icon('copy', 's'), t('impostazioni.dati.faiCopia'))),
|
||||
rows.length
|
||||
? h('div.pannello', h('table.tab',
|
||||
h('thead', h('tr', h('th', t('impostazioni.dati.colonne.giorno')), h('th', t('impostazioni.dati.colonne.file')), h('th.num', t('impostazioni.dati.colonne.peso')), h('th', t('impostazioni.dati.colonne.fatta')))),
|
||||
h('tbody', rows)))
|
||||
: h('p.vuoto-elenco.pannello', t('impostazioni.dati.nessunaCopia')));
|
||||
}
|
||||
|
||||
function drawRebuild() {
|
||||
const r = data.rebuild;
|
||||
const status = [];
|
||||
if (r.running) {
|
||||
const ratio = r.foldersTotal ? r.foldersDone / r.foldersTotal : 0;
|
||||
status.push(h('div.avanzamento-blocco',
|
||||
h('p', t('impostazioni.dati.inCorso', { fatte: number(r.foldersDone), totale: number(r.foldersTotal), file: number(r.filesChecked) })),
|
||||
h('div.misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': String(r.foldersTotal || 1), 'aria-valuenow': String(r.foldersDone) }, h('i', { style: { width: `${ratio * 100}%` } })),
|
||||
r.folder ? h('p.aiuto.piccolo', t('impostazioni.dati.inCorsoCartella', { cartella: r.folder })) : null));
|
||||
} else if (r.error) {
|
||||
status.push(h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', r.error)));
|
||||
} else if (r.finishedAt) {
|
||||
status.push(h('div.pannello.resoconto-ricostruzione',
|
||||
h('b', t('impostazioni.dati.finita', { quando: at(r.finishedAt) })),
|
||||
h('ul', r.lines.map((line) => h('li', line)))));
|
||||
}
|
||||
fill(rebuild,
|
||||
h('p.aiuto', t('impostazioni.dati.ricostruisciAiuto')),
|
||||
h('div.riga-azione', h('button.btn.pericolo', { type: 'button', disabled: r.running, onclick: confirmRebuild }, icon('history', 's'), t('impostazioni.dati.ricostruisciBtn'))),
|
||||
status);
|
||||
clearTimeout(timer);
|
||||
if (r.running) timer = setTimeout(reload, 1500);
|
||||
else if (data.data.usedBytes == null) timer = setTimeout(reload, 1000); // the size is still being measured
|
||||
}
|
||||
|
||||
async function reload() {
|
||||
try {
|
||||
data = await api('/api/settings/data', { signal: page.signal });
|
||||
drawFolder();
|
||||
drawBackups();
|
||||
drawRebuild();
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function backupNow() {
|
||||
try {
|
||||
const result = await api('/api/settings/backups', { method: 'POST' });
|
||||
toast(result.message);
|
||||
await reload();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmRebuild() {
|
||||
const word = t('impostazioni.dati.confParola');
|
||||
const ok = await dialog({
|
||||
title: t('impostazioni.dati.confTitolo'),
|
||||
className: 'piccolo',
|
||||
build: (close) => {
|
||||
const input = h('input', { type: 'text', id: 'conferma-ricostruzione', autocomplete: 'off', spellcheck: 'false' });
|
||||
const go = h('button.btn.pericolo.pieno', { type: 'button', disabled: true, onclick: () => close(true) }, t('impostazioni.dati.confBtn'));
|
||||
input.addEventListener('input', () => { go.disabled = input.value.trim().toLowerCase() !== word; });
|
||||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !go.disabled) close(true); });
|
||||
return {
|
||||
body: h('div.contenuto',
|
||||
h('p', t('impostazioni.dati.confTesto')),
|
||||
h('label.etichetta', { for: 'conferma-ricostruzione' }, t('impostazioni.dati.confScrivi')),
|
||||
h('label.campo', input)),
|
||||
footer: h('footer', h('div.destra',
|
||||
h('button.btn.nudo', { type: 'button', onclick: () => close(false), autofocus: true }, t('comune.annulla')),
|
||||
go)),
|
||||
};
|
||||
},
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const result = await api('/api/settings/rebuild', { method: 'POST', body: { confirm: word } });
|
||||
toast(result.message);
|
||||
await reload();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
drawFolder();
|
||||
drawBackups();
|
||||
drawRebuild();
|
||||
fill(box,
|
||||
h('div.sezione', heading(t('impostazioni.dati.cartella'), t('impostazioni.dati.contiene')), folder),
|
||||
h('div.sezione', heading(t('impostazioni.dati.copie')), backups),
|
||||
h('div.sezione', heading(t('impostazioni.dati.ricostruisci')), rebuild));
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
// Impostazioni, Generali (mockup 08, spec §4.7, §10.5, §12): the Libreria and Dati folders with «Cambia…» (desktop:
|
||||
// native picker; Docker: read-only with the note), free and used space; the two naming schemes with the live «Risultato»
|
||||
// tree, the placeholders and the errors; «Imposta la data del file a quella di pubblicazione»; theme and language;
|
||||
// the «Avvio» block on Windows only.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill, later } from '../core/dom.js';
|
||||
import { t, bytes } from '../core/text.js';
|
||||
import { saveTheme, themeChoice } from '../core/theme.js';
|
||||
import { checkbox, confirmDialog, label, segmented, showError, toast, toggle } from '../core/ui.js';
|
||||
import { guardChanges, heading } from './settings.js';
|
||||
|
||||
export default async function general(page, box) {
|
||||
let data = await api('/api/settings/general', { signal: page.signal });
|
||||
let saved = { naming: data.namingScheme, highlight: data.highlightScheme, setFileTime: data.setFileTime };
|
||||
const form = { ...saved };
|
||||
const dirty = () => form.naming !== saved.naming || form.highlight !== saved.highlight || form.setFileTime !== saved.setFileTime;
|
||||
guardChanges(page, dirty);
|
||||
|
||||
// ------------------------------------------------------------------------------------------- folders
|
||||
const folders = h('div');
|
||||
function drawFolders() {
|
||||
const row = (title, help, folder, side, onChange, canChange) => h('div.cartella-impostazioni',
|
||||
h('b.titolo-campo', title),
|
||||
h('p.aiuto', help),
|
||||
h('div.riga-cartella',
|
||||
h('div.campo.sola', { title: folder.path }, icon('folder', 's'), h('span.val.dati', folder.path)),
|
||||
canChange ? h('button.btn', { type: 'button', onclick: onChange }, t('impostazioni.generali.cambia')) : null,
|
||||
h('span.spazio.dati', side)));
|
||||
const free = data.library.freeBytes != null ? t('impostazioni.generali.liberi', { n: bytes(data.library.freeBytes) }) : '';
|
||||
const used = data.data.usedBytes != null ? t('impostazioni.generali.usati', { n: bytes(data.data.usedBytes) }) : data.data.measuring ? t('impostazioni.generali.misura') : '';
|
||||
fill(folders,
|
||||
row(t('impostazioni.generali.libreria'), t('impostazioni.generali.libreriaAiuto'), data.library, free, changeLibrary, !data.foldersReadOnly && data.canPickFolder),
|
||||
row(t('impostazioni.generali.dati'), t('impostazioni.generali.datiAiuto'), data.data, used, changeData, data.canChangeDataFolder),
|
||||
data.foldersReadOnly ? h('div.avviso', { style: { marginTop: '12px' } }, icon('info', 's'), h('span', t('impostazioni.generali.dockerNota'))) : null);
|
||||
}
|
||||
|
||||
async function pick(which) {
|
||||
try {
|
||||
const result = await api('/api/settings/pick-folder', { method: 'POST', body: { which } });
|
||||
return result.path || null;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function changeLibrary() {
|
||||
const path = await pick('library');
|
||||
if (!path) return;
|
||||
const ok = await confirmDialog({
|
||||
title: t('impostazioni.generali.nuovaLibreria'),
|
||||
text: t('impostazioni.generali.nuovaLibreriaTesto', { percorso: path }),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo' },
|
||||
{ label: t('impostazioni.generali.usaCartella'), value: true, kind: 'primo', autofocus: true },
|
||||
],
|
||||
});
|
||||
if (!ok) return;
|
||||
await put({ libraryFolder: path });
|
||||
}
|
||||
|
||||
async function changeData() {
|
||||
const path = await pick('data');
|
||||
if (!path) return;
|
||||
const ok = await confirmDialog({
|
||||
title: t('impostazioni.generali.nuoviDati'),
|
||||
text: t('impostazioni.generali.nuoviDatiTesto', { percorso: path }),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo' },
|
||||
{ label: t('impostazioni.generali.usaCartella'), value: true, kind: 'primo', autofocus: true },
|
||||
],
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const result = await api('/api/settings/data-folder', { method: 'POST', body: { path } });
|
||||
toast(result.message);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves with the stored naming values plus the given changes (folders and switches act at once). */
|
||||
async function put(changes, { withForm = false } = {}) {
|
||||
const body = {
|
||||
libraryFolder: null,
|
||||
namingScheme: withForm ? form.naming : saved.naming,
|
||||
highlightScheme: withForm ? form.highlight : saved.highlight,
|
||||
setFileTime: withForm ? form.setFileTime : saved.setFileTime,
|
||||
autostart: null,
|
||||
keepInTray: null,
|
||||
...changes,
|
||||
};
|
||||
try {
|
||||
data = await api('/api/settings/general', { method: 'PUT', body });
|
||||
saved = { naming: data.namingScheme, highlight: data.highlightScheme, setFileTime: data.setFileTime };
|
||||
if (withForm) Object.assign(form, saved);
|
||||
drawFolders();
|
||||
drawSaveBar();
|
||||
toast(t('impostazioni.salvate'));
|
||||
return true;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- naming
|
||||
const naming = h('input.dati', { type: 'text', value: form.naming, id: 'schema', spellcheck: 'false', autocomplete: 'off' });
|
||||
const highlight = h('input.dati', { type: 'text', value: form.highlight, id: 'schema-evidenza', spellcheck: 'false', autocomplete: 'off' });
|
||||
const namingField = h('label.campo', naming);
|
||||
const highlightField = h('label.campo', highlight);
|
||||
const problems = h('div.problemi-schema', { 'aria-live': 'polite' });
|
||||
const tree = h('div.albero.pannello', { 'aria-label': t('impostazioni.generali.risultato') });
|
||||
const setTime = checkbox({ checked: form.setFileTime, label: t('impostazioni.generali.dataFile'), onchange: (v) => { form.setFileTime = v; drawSaveBar(); } });
|
||||
|
||||
function drawTree(preview) {
|
||||
const errors = preview.errors || [];
|
||||
namingField.classList.toggle('errore', errors.some((e) => e.startsWith('Schema:')));
|
||||
highlightField.classList.toggle('errore', errors.some((e) => !e.startsWith('Schema:')));
|
||||
fill(problems,
|
||||
errors.map((e) => h('p.errore-testo', icon('octagon-alert', 'xs'), ' ', e)),
|
||||
(preview.warnings || []).map((w) => h('p.avviso-testo', icon('triangle-alert', 'xs'), ' ', w)));
|
||||
fill(tree,
|
||||
h('div.ramo.radice', icon('folder', 's'), h('b', preview.accountFolder)),
|
||||
preview.folders.map((f) => [
|
||||
f.path.length ? h('div.ramo.livello-1', icon('folder', 's'), h('span', f.path.join(' \\ '))) : null,
|
||||
f.files.map((file) => h(`div.ramo.${f.path.length ? 'livello-2' : 'livello-1'}`, icon(file.kind === 'video' ? 'clapperboard' : 'image', 's'), h('span.dati', file.name))),
|
||||
]));
|
||||
}
|
||||
|
||||
const refresh = later(async () => {
|
||||
try {
|
||||
drawTree(await api('/api/settings/naming-preview', { method: 'POST', body: { namingScheme: form.naming, highlightScheme: form.highlight }, signal: page.signal }));
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
}
|
||||
}, 150);
|
||||
page.onLeave(() => refresh.cancel());
|
||||
naming.addEventListener('input', () => { form.naming = naming.value; drawSaveBar(); refresh(); });
|
||||
highlight.addEventListener('input', () => { form.highlight = highlight.value; drawSaveBar(); refresh(); });
|
||||
|
||||
// ------------------------------------------------------------------------------------------- save bar
|
||||
function drawSaveBar() {
|
||||
if (!dirty()) {
|
||||
page.saveBar(null);
|
||||
return;
|
||||
}
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', t('impostazioni.modifiche')),
|
||||
h('div.destra',
|
||||
h('button.btn', { type: 'button', onclick: discard }, t('impostazioni.annulla')),
|
||||
h('button.btn.primo', { type: 'button', onclick: () => put({}, { withForm: true }) }, icon('check'), t('impostazioni.salva')))));
|
||||
}
|
||||
|
||||
function discard() {
|
||||
Object.assign(form, saved);
|
||||
naming.value = form.naming;
|
||||
highlight.value = form.highlight;
|
||||
setTime.input.checked = form.setFileTime;
|
||||
drawSaveBar();
|
||||
refresh();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- appearance and start
|
||||
const theme = segmented({
|
||||
label: t('impostazioni.generali.tema'),
|
||||
value: themeChoice(),
|
||||
options: [
|
||||
{ value: 'chiaro', label: t('impostazioni.generali.temi.chiaro'), icon: 'sun' },
|
||||
{ value: 'scuro', label: t('impostazioni.generali.temi.scuro'), icon: 'moon' },
|
||||
{ value: 'sistema', label: t('impostazioni.generali.temi.sistema'), icon: 'monitor' },
|
||||
],
|
||||
onchange: async (v) => {
|
||||
try {
|
||||
await saveTheme(v);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
},
|
||||
});
|
||||
const language = h('label.campo.scelta.lingua', h('select', { id: 'lingua', 'aria-describedby': 'lingua-nota' }, h('option', { value: 'it', selected: true }, t('impostazioni.generali.italiano'))), icon('chevron-down', 's'));
|
||||
|
||||
const start = data.autostart == null ? null : h('div.sezione',
|
||||
h('div.testa-sez', h('h2.sez', t('impostazioni.generali.avvio'), ' ', label(t('impostazioni.generali.soloWindows')))),
|
||||
h('div.leve',
|
||||
toggle({ checked: data.autostart, label: t('impostazioni.generali.accensione'), onchange: (v) => put({ autostart: v }) }),
|
||||
toggle({ checked: data.keepInTray, label: t('impostazioni.generali.area'), onchange: (v) => put({ keepInTray: v }) })));
|
||||
|
||||
drawFolders();
|
||||
drawTree(data.preview);
|
||||
fill(box,
|
||||
h('div.sezione', heading(t('impostazioni.generali.cartelle')), folders),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.generali.nomi'), t('impostazioni.generali.nomiAiuto')),
|
||||
h('div.nomi-file',
|
||||
h('div.colonna-nomi',
|
||||
h('label.etichetta', { for: 'schema' }, t('impostazioni.generali.schema')), namingField,
|
||||
h('label.etichetta', { for: 'schema-evidenza' }, t('impostazioni.generali.schemaEvidenza')), highlightField,
|
||||
h('p.aiuto.segnaposto', t('impostazioni.generali.segnaposto', { elenco: data.placeholders.join(', ') })),
|
||||
problems,
|
||||
h('div.data-file', setTime)),
|
||||
h('div.colonna-albero', h('span.etichetta', t('impostazioni.generali.risultato')), tree))),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.generali.aspetto')),
|
||||
h('div.aspetto',
|
||||
h('div', h('span.etichetta', t('impostazioni.generali.tema')), theme),
|
||||
h('div', h('label.etichetta', { for: 'lingua' }, t('impostazioni.generali.lingua')), language,
|
||||
h('p.aiuto.piccolo', { id: 'lingua-nota' }, t('impostazioni.generali.linguaNota'))))),
|
||||
start);
|
||||
|
||||
// The used size of the Data folder is measured in the background: ask again once.
|
||||
if (data.data.measuring && data.data.usedBytes == null) {
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const again = await api('/api/settings/general', { signal: page.signal });
|
||||
data = { ...data, data: again.data, library: again.library };
|
||||
drawFolders();
|
||||
} catch {
|
||||
// keep «calcolo…»
|
||||
}
|
||||
}, 1000);
|
||||
page.onLeave(() => clearTimeout(timer));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
// Impostazioni, Limiti e comportamento (mockup 07, spec §7.2, §7.5, §7.7): the honest note on the values, the profile
|
||||
// cards (Prudente, Equilibrato, Rapido with confirmation and «Più rischio», Su misura when Alberto changes a value),
|
||||
// the active window with its daily shift and the active days as initials, session and pause ranges, the gesture
|
||||
// pace, every budget of §7.5, the gradual start, the fixed stops (informative), and the fixed save bar. The limits
|
||||
// of §7.5 are checked here with Italian messages and again by the server.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { refreshEngine } from '../core/engine.js';
|
||||
import { t, list, number, decimal } from '../core/text.js';
|
||||
import { checkbox, confirmDialog, label, showError, toast, toggle } from '../core/ui.js';
|
||||
import { guardChanges, heading } from './settings.js';
|
||||
|
||||
const PACES = ['slow', 'natural', 'brisk'];
|
||||
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() });
|
||||
let form = fromData(data);
|
||||
let original = snapshot();
|
||||
const dirty = () => snapshot() !== original;
|
||||
guardChanges(page, dirty);
|
||||
const rules = data.rules;
|
||||
let errors = {};
|
||||
|
||||
function fromData(d) {
|
||||
return {
|
||||
profile: d.profile,
|
||||
values: structuredClone(d.current),
|
||||
pace: d.pace,
|
||||
gradualStart: d.gradualStart,
|
||||
activeDays: new Set(d.activeDays),
|
||||
jitterOn: d.current.jitterMinutes > 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Any edit turns the profile into «Su misura» (spec §7.5). */
|
||||
function edited() {
|
||||
form.profile = 'custom';
|
||||
form.values.kind = 'custom';
|
||||
validate();
|
||||
drawCards();
|
||||
drawWindow();
|
||||
drawSaveBar();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- profile cards
|
||||
const cards = h('div.profili', { role: 'radiogroup', 'aria-label': t('impostazioni.limiti.profilo') });
|
||||
const customCard = h('div');
|
||||
function drawCards() {
|
||||
fill(cards, data.presets.map((p) => {
|
||||
const input = h('input.vh', { type: 'radio', name: 'profilo', value: p.kind, checked: form.profile === p.kind });
|
||||
input.addEventListener('change', () => choose(p));
|
||||
const budget = (kind) => p.budgets.find((b) => b.kind === kind)?.perDay ?? 0;
|
||||
return h(`label.profilo${form.profile === p.kind ? '.scelto' : ''}`,
|
||||
input,
|
||||
h('div.testa-profilo', h('span.tondo', { 'aria-hidden': 'true' }), h('b', p.name),
|
||||
p.kind === 'prudent' ? label(t('impostazioni.limiti.consigliato'), 'accento') : null,
|
||||
p.kind === 'fast' ? label(t('impostazioni.limiti.piuRischio'), 'ambra') : null),
|
||||
h('p', t(`impostazioni.limiti.profili.${p.kind}`)),
|
||||
h('p.riassunto', riassunto(budget('ProfileOpen'), budget('StoryView'), budget('BackfillPage'))));
|
||||
}));
|
||||
fill(customCard, form.profile === 'custom'
|
||||
? h('div.profilo.scelto.su-misura', h('div.testa-profilo', h('span.tondo.si', { 'aria-hidden': 'true' }), h('b', t('impostazioni.limiti.suMisura'))),
|
||||
h('p', t('impostazioni.limiti.suMisuraTesto')))
|
||||
: null);
|
||||
}
|
||||
|
||||
function riassunto(profiles, stories, history) {
|
||||
const text = t('impostazioni.limiti.riassunto', { profili: '\u0001', storie: '\u0002', storico: '\u0003' });
|
||||
return text.split(/([\u0001-\u0003])/).map((part) => part === '\u0001' ? h('b', number(profiles)) : part === '\u0002' ? h('b', number(stories)) : part === '\u0003' ? h('b', number(history)) : part);
|
||||
}
|
||||
|
||||
async function choose(preset) {
|
||||
if (preset.kind === 'fast' && form.profile !== 'fast') {
|
||||
const ok = await confirmDialog({
|
||||
title: t('impostazioni.limiti.rapidoTitolo'),
|
||||
text: t('impostazioni.limiti.rapidoTesto'),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
|
||||
{ label: t('impostazioni.limiti.rapidoConferma'), value: true, kind: 'primo' },
|
||||
],
|
||||
});
|
||||
if (!ok) {
|
||||
drawCards();
|
||||
return;
|
||||
}
|
||||
}
|
||||
form.profile = preset.kind;
|
||||
form.values = structuredClone(preset);
|
||||
form.jitterOn = preset.jitterMinutes > 0;
|
||||
drawAll();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- window and days
|
||||
const windowBar = h('div.fascia-barra');
|
||||
// Text fields with 24-hour times (a time input would follow the browser's locale, possibly with AM/PM).
|
||||
const timeField = (id) => h('input.dati', { type: 'text', id, inputmode: 'numeric', maxlength: '5', placeholder: '07:30', autocomplete: 'off', spellcheck: 'false' });
|
||||
const startInput = timeField('fascia-inizio');
|
||||
const endInput = timeField('fascia-fine');
|
||||
const readTime = (input, key) => {
|
||||
const value = input.value.trim().replace('.', ':');
|
||||
const m = /^(\d{1,2}):?(\d{2})$/.exec(value);
|
||||
form.values[key] = m && Number(m[1]) <= 24 && Number(m[2]) < 60 ? `${m[1].padStart(2, '0')}:${m[2]}` : value;
|
||||
edited();
|
||||
};
|
||||
startInput.addEventListener('change', () => readTime(startInput, 'windowStart'));
|
||||
endInput.addEventListener('change', () => readTime(endInput, 'windowEnd'));
|
||||
const days = h('div.giorni', { role: 'group', 'aria-label': t('impostazioni.limiti.giorni') });
|
||||
const jitterInput = h('input.dati', { type: 'number', min: '0', max: String(rules.maxJitterMinutes), step: '5', id: 'sposta', inputmode: 'numeric' });
|
||||
jitterInput.addEventListener('input', () => { form.values.jitterMinutes = toInt(jitterInput.value); edited(); });
|
||||
const jitterBox = checkbox({
|
||||
checked: form.jitterOn,
|
||||
labelNode: h('span', t('impostazioni.limiti.sposta')),
|
||||
onchange: (v) => {
|
||||
form.jitterOn = v;
|
||||
form.values.jitterMinutes = v ? Math.max(5, toInt(jitterInput.value) || 30) : 0;
|
||||
jitterInput.value = form.values.jitterMinutes;
|
||||
jitterInput.disabled = !v;
|
||||
edited();
|
||||
},
|
||||
});
|
||||
const windowError = h('p.errore-testo', { hidden: true });
|
||||
|
||||
function minutesOf(text) {
|
||||
const m = /^(\d{1,2}):(\d{2})$/.exec(String(text || ''));
|
||||
if (!m || Number(m[1]) > 24 || Number(m[2]) > 59) return null;
|
||||
return (Number(m[1]) * 60 + Number(m[2])) % 1440;
|
||||
}
|
||||
function textOf(minutes) {
|
||||
const v = ((Math.round(minutes) % 1440) + 1440) % 1440;
|
||||
return `${String(Math.floor(v / 60)).padStart(2, '0')}:${String(v % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function drawWindow() {
|
||||
const start = minutesOf(form.values.windowStart) ?? 0;
|
||||
let end = minutesOf(form.values.windowEnd) ?? start;
|
||||
if (end === 0) end = 1440;
|
||||
const bands = end > start ? [[start, end]] : [[start, 1440], [0, end]];
|
||||
const pct = (m) => `${(m / 1440) * 100}%`;
|
||||
fill(windowBar,
|
||||
[3, 6, 9, 12, 15, 18, 21].map((hour) => h('span.tacca', { style: { left: pct(hour * 60) } })),
|
||||
bands.map(([a, b]) => h('span.banda', { style: { left: pct(a), width: pct(b - a) } })),
|
||||
handle('inizio', start), handle('fine', end % 1440 === 0 && end === 1440 ? 1440 : end));
|
||||
if (document.activeElement !== startInput) startInput.value = minutesOf(form.values.windowStart) == null ? form.values.windowStart : textOf(start);
|
||||
if (document.activeElement !== endInput) endInput.value = minutesOf(form.values.windowEnd) == null ? form.values.windowEnd : textOf(end);
|
||||
jitterInput.value = form.values.jitterMinutes;
|
||||
jitterInput.disabled = !form.jitterOn;
|
||||
jitterBox.input.checked = form.jitterOn;
|
||||
fill(days, DAY_ORDER.map((day, i) => {
|
||||
const on = form.activeDays.has(day);
|
||||
return h(`button.cerchio-giorno${on ? '.si' : ''}`, {
|
||||
type: 'button', 'aria-pressed': String(on), 'aria-label': list('impostazioni.limiti.nomiGiorni')[i], title: list('impostazioni.limiti.nomiGiorni')[i],
|
||||
onclick: () => {
|
||||
if (on) form.activeDays.delete(day);
|
||||
else form.activeDays.add(day);
|
||||
edited();
|
||||
},
|
||||
}, list('impostazioni.limiti.iniziali')[i]);
|
||||
}));
|
||||
const message = errors.window || errors.days || errors.jitter;
|
||||
windowError.hidden = !message;
|
||||
windowError.textContent = message || '';
|
||||
startInput.parentElement?.classList.toggle('errore', Boolean(errors.window));
|
||||
endInput.parentElement?.classList.toggle('errore', Boolean(errors.window));
|
||||
}
|
||||
|
||||
/** A draggable handle of the window bar (15-minute steps); the time fields stay the precise way. */
|
||||
function handle(which, minutes) {
|
||||
const el = h('span.maniglia', { style: { left: `${(minutes / 1440) * 100}%` }, 'aria-hidden': 'true' });
|
||||
el.addEventListener('pointerdown', (e) => {
|
||||
e.preventDefault();
|
||||
el.setPointerCapture(e.pointerId);
|
||||
const rect = windowBar.getBoundingClientRect();
|
||||
const move = (ev) => {
|
||||
const ratio = Math.min(1, Math.max(0, (ev.clientX - rect.left) / rect.width));
|
||||
const value = Math.round((ratio * 1440) / 15) * 15;
|
||||
if (which === 'inizio') form.values.windowStart = textOf(value);
|
||||
else form.values.windowEnd = textOf(value);
|
||||
edited();
|
||||
};
|
||||
const up = () => {
|
||||
el.removeEventListener('pointermove', move);
|
||||
el.removeEventListener('pointerup', up);
|
||||
};
|
||||
el.addEventListener('pointermove', move);
|
||||
el.addEventListener('pointerup', up);
|
||||
});
|
||||
return el;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- sessions, pauses, pace
|
||||
const sessionRange = rangePair('sessione', 1, rules.maxSessionMinutes, () => [form.values.sessionMinMinutes, form.values.sessionMaxMinutes], (a, b) => {
|
||||
form.values.sessionMinMinutes = a;
|
||||
form.values.sessionMaxMinutes = b;
|
||||
edited();
|
||||
});
|
||||
const pauseRange = rangePair('pausa', rules.minPauseMinutes, 180, () => [form.values.pauseMinMinutes, form.values.pauseMaxMinutes], (a, b) => {
|
||||
form.values.pauseMinMinutes = a;
|
||||
form.values.pauseMaxMinutes = b;
|
||||
edited();
|
||||
});
|
||||
const paceInput = h('input.cursore.lungo', { type: 'range', min: '0', max: '2', step: '1', id: 'ritmo', 'aria-valuetext': '' });
|
||||
const paceText = h('span.valore-cursore');
|
||||
paceInput.addEventListener('input', () => {
|
||||
form.pace = PACES[Number(paceInput.value)];
|
||||
validate();
|
||||
drawPace();
|
||||
drawSaveBar();
|
||||
});
|
||||
function drawPace() {
|
||||
paceInput.value = String(PACES.indexOf(form.pace));
|
||||
paceText.textContent = t(`impostazioni.limiti.ritmi.${form.pace}`);
|
||||
paceInput.setAttribute('aria-valuetext', paceText.textContent);
|
||||
paceInput.style.setProperty('--pieno', `${(PACES.indexOf(form.pace) / 2) * 100}%`);
|
||||
}
|
||||
|
||||
/** Two thumbs on one track (minimum and maximum), with the text «da 2 a 10 minuti». */
|
||||
function rangePair(name, min, max, get, set) {
|
||||
const low = h('input.cursore', { type: 'range', min: String(min), max: String(max), step: '1', 'aria-label': `${t(`impostazioni.limiti.${name === 'sessione' ? 'durata' : 'pausa'}`)}, ${t('impostazioni.limiti.minimo')}` });
|
||||
const high = h('input.cursore', { type: 'range', min: String(min), max: String(max), step: '1', 'aria-label': `${t(`impostazioni.limiti.${name === 'sessione' ? 'durata' : 'pausa'}`)}, ${t('impostazioni.limiti.massimo')}` });
|
||||
const fillBar = h('span.tratto');
|
||||
const text = h('span.valore-cursore');
|
||||
const error = h('p.errore-testo', { hidden: true });
|
||||
const track = h('div.doppio', h('span.binario'), fillBar, low, high);
|
||||
const sync = () => {
|
||||
const [a, b] = get();
|
||||
low.value = String(Math.max(min, Math.min(max, a)));
|
||||
high.value = String(Math.max(min, Math.min(max, b)));
|
||||
const left = ((Number(low.value) - min) / (max - min)) * 100;
|
||||
const right = ((Number(high.value) - min) / (max - min)) * 100;
|
||||
fillBar.style.left = `${left}%`;
|
||||
fillBar.style.width = `${Math.max(0, right - left)}%`;
|
||||
text.textContent = t('impostazioni.limiti.daA', { a, b });
|
||||
low.setAttribute('aria-valuetext', `${a} ${t('impostazioni.limiti.minuti')}`);
|
||||
high.setAttribute('aria-valuetext', `${b} ${t('impostazioni.limiti.minuti')}`);
|
||||
const message = errors[name];
|
||||
error.hidden = !message;
|
||||
error.textContent = message || '';
|
||||
};
|
||||
low.addEventListener('input', () => {
|
||||
const a = Number(low.value);
|
||||
const [, b] = get();
|
||||
set(a, Math.max(a, b));
|
||||
});
|
||||
high.addEventListener('input', () => {
|
||||
const b = Number(high.value);
|
||||
const [a] = get();
|
||||
set(Math.min(a, b), b);
|
||||
});
|
||||
return { track, text, error, sync };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- budgets table
|
||||
const table = h('tbody');
|
||||
const cells = new Map();
|
||||
function paintErrors() {
|
||||
for (const [key, ref] of cells) {
|
||||
ref.field.classList.toggle('errore', Boolean(errors[key]));
|
||||
ref.message.hidden = !errors[key];
|
||||
ref.message.textContent = errors[key] || '';
|
||||
}
|
||||
}
|
||||
function drawTable() {
|
||||
cells.clear();
|
||||
const v = form.values;
|
||||
const numberCell = (value, max, onInput, key, unit) => {
|
||||
const input = h('input.dati', { type: 'number', min: '0', max: String(max), step: unit === 'gb' ? '0.5' : '1', value: String(value), inputmode: unit === 'gb' ? 'decimal' : 'numeric', 'aria-label': key });
|
||||
input.addEventListener('input', () => onInput(input.value));
|
||||
const field = h('label.campo.numero', input, unit ? h('span.unita', t(`impostazioni.limiti.${unit}`)) : null);
|
||||
const message = h('div.errore-testo', { hidden: true });
|
||||
cells.set(key, { field, message });
|
||||
return h('td', field, message);
|
||||
};
|
||||
const rows = v.budgets.map((b) => h('tr',
|
||||
h('td', b.label),
|
||||
numberCell(b.perHour, b.maxPerHour, (x) => { b.perHour = toInt(x); edited(); }, `${b.kind}-ora`),
|
||||
numberCell(b.perDay, b.maxPerDay, (x) => { b.perDay = toInt(x); edited(); }, `${b.kind}-giorno`)));
|
||||
rows.push(h('tr',
|
||||
h('td', t('impostazioni.limiti.dati')),
|
||||
h('td.muto', '—'),
|
||||
numberCell(decimal(v.dataPerDayGb, 2).replace(',', '.'), rules.maxDataPerDayGb, (x) => { v.dataPerDayGb = String(x).trim() === '' ? NaN : Number(String(x).replace(',', '.')); edited(); }, 'dati', 'gb')));
|
||||
rows.push(h('tr',
|
||||
h('td', t('impostazioni.limiti.storico'), h('div.muto.piccolo', t('impostazioni.limiti.storicoNota'))),
|
||||
h('td.muto', '—'),
|
||||
numberCell(v.backfillPerAccount, rules.maxBackfillPerAccount, (x) => { v.backfillPerAccount = toInt(x); edited(); }, 'storico', 'post')));
|
||||
const gradual = toggle({ checked: form.gradualStart, label: t('impostazioni.limiti.graduale'), onchange: (on) => { form.gradualStart = on; validate(); drawTable(); drawSaveBar(); } });
|
||||
rows.push(h('tr.riga-graduale',
|
||||
h('td', gradual, h('div.muto.piccolo', t('impostazioni.limiti.gradualeAiuto'))),
|
||||
h('td.muto', '—'),
|
||||
form.gradualStart ? numberCell(v.rampUpDays, rules.maxRampUpDays, (x) => { v.rampUpDays = toInt(x); edited(); }, 'graduale', 'giorniGraduale') : h('td.muto', '—')));
|
||||
rows.push(h('tr.informativa',
|
||||
h('td', h('span', icon('lock', 'xs'), ' ', t('impostazioni.limiti.arresti')), h('div.muto.piccolo', t('impostazioni.limiti.arrestiTesto'))),
|
||||
h('td.muto', data.stops.join(' · ')),
|
||||
h('td.muto', t('impostazioni.limiti.arrestiFissi'))));
|
||||
fill(table, rows);
|
||||
paintErrors();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- validation
|
||||
function validate() {
|
||||
const v = form.values;
|
||||
const e = {};
|
||||
const start = minutesOf(v.windowStart);
|
||||
const end = minutesOf(v.windowEnd);
|
||||
if (start == null || end == null) e.window = t('impostazioni.limiti.errori.ora');
|
||||
else {
|
||||
let length = end - start;
|
||||
if (length <= 0) length += 1440;
|
||||
if (length > rules.maxWindowHours * 60) e.window = t('impostazioni.limiti.errori.fascia', { n: rules.maxWindowHours });
|
||||
}
|
||||
if (form.activeDays.size === 0) e.days = t('impostazioni.limiti.errori.giorni');
|
||||
if (!(v.jitterMinutes >= 0 && v.jitterMinutes <= rules.maxJitterMinutes)) e.jitter = t('impostazioni.limiti.errori.sposta', { n: rules.maxJitterMinutes });
|
||||
if (v.sessionMaxMinutes > rules.maxSessionMinutes) e.sessione = t('impostazioni.limiti.errori.sessione', { n: rules.maxSessionMinutes });
|
||||
else if (v.sessionMinMinutes < 1) e.sessione = t('impostazioni.limiti.errori.sessioneMin');
|
||||
else if (v.sessionMinMinutes > v.sessionMaxMinutes) e.sessione = t('impostazioni.limiti.errori.minMax');
|
||||
if (v.pauseMinMinutes < rules.minPauseMinutes) e.pausa = t('impostazioni.limiti.errori.pausa', { n: rules.minPauseMinutes });
|
||||
else if (v.pauseMinMinutes > v.pauseMaxMinutes) e.pausa = t('impostazioni.limiti.errori.minMax');
|
||||
for (const b of v.budgets) {
|
||||
if (!Number.isInteger(b.perHour) || b.perHour < 0) e[`${b.kind}-ora`] = t('impostazioni.limiti.errori.numero');
|
||||
else if (b.perHour > b.maxPerHour) e[`${b.kind}-ora`] = t('impostazioni.limiti.errori.tetto', { max: number(b.maxPerHour) });
|
||||
if (!Number.isInteger(b.perDay) || b.perDay < 0) e[`${b.kind}-giorno`] = t('impostazioni.limiti.errori.numero');
|
||||
else if (b.perDay > b.maxPerDay) e[`${b.kind}-giorno`] = t('impostazioni.limiti.errori.tetto', { max: number(b.maxPerDay) });
|
||||
}
|
||||
if (!(v.dataPerDayGb >= 0)) e.dati = t('impostazioni.limiti.errori.numero');
|
||||
else if (v.dataPerDayGb > rules.maxDataPerDayGb) e.dati = t('impostazioni.limiti.errori.tetto', { max: `${decimal(rules.maxDataPerDayGb, 1)} GB` });
|
||||
if (!Number.isInteger(v.backfillPerAccount) || v.backfillPerAccount < 0) e.storico = t('impostazioni.limiti.errori.numero');
|
||||
else if (v.backfillPerAccount > rules.maxBackfillPerAccount) e.storico = t('impostazioni.limiti.errori.tetto', { max: `${number(rules.maxBackfillPerAccount)} post` });
|
||||
if (form.gradualStart && !(Number.isInteger(v.rampUpDays) && v.rampUpDays >= 0 && v.rampUpDays <= rules.maxRampUpDays)) e.graduale = t('impostazioni.limiti.errori.graduale', { n: rules.maxRampUpDays });
|
||||
errors = e;
|
||||
sessionRange.sync();
|
||||
pauseRange.sync();
|
||||
paintErrors();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- save bar
|
||||
function drawSaveBar() {
|
||||
const changed = dirty();
|
||||
const invalid = Object.keys(errors).length > 0;
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', invalid ? h('span.errore-testo', icon('octagon-alert', 'xs'), ' ', t('impostazioni.limiti.errori.correggi')) : t(changed ? 'impostazioni.modifiche' : 'impostazioni.nessunaModifica')),
|
||||
h('div.destra',
|
||||
h('button.btn', { type: 'button', disabled: !changed, onclick: discard }, t('impostazioni.annulla')),
|
||||
h('button.btn.primo', { type: 'button', disabled: !changed || invalid, onclick: save }, icon('check'), t('impostazioni.salva')))));
|
||||
}
|
||||
|
||||
function discard() {
|
||||
form = fromData(data);
|
||||
drawAll();
|
||||
}
|
||||
|
||||
async function save() {
|
||||
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] },
|
||||
});
|
||||
form = fromData(data);
|
||||
original = snapshot();
|
||||
drawAll();
|
||||
toast(t('impostazioni.limiti.salvati'));
|
||||
refreshEngine();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function drawAll() {
|
||||
validate();
|
||||
drawCards();
|
||||
drawWindow();
|
||||
drawPace();
|
||||
drawTable();
|
||||
drawSaveBar();
|
||||
}
|
||||
|
||||
drawAll();
|
||||
original = snapshot();
|
||||
drawSaveBar();
|
||||
|
||||
fill(box,
|
||||
h('div.avviso.ambra.avviso-limiti', icon('triangle-alert', 's'), h('span', t('impostazioni.limiti.avviso'))),
|
||||
h('div.sezione', heading(t('impostazioni.limiti.profilo'), t('impostazioni.limiti.profiloAiuto')), cards, customCard),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.limiti.orari'), t('impostazioni.limiti.orariAiuto')),
|
||||
windowBar,
|
||||
h('div.ore', { 'aria-hidden': 'true' }, [0, 3, 6, 9, 12, 15, 18, 21, 24].map((hour) => h('span', { style: { left: `${(hour / 24) * 100}%` } }, String(hour)))),
|
||||
h('div.riga-fascia',
|
||||
h('label.etichetta-riga', { for: 'fascia-inizio' }, t('impostazioni.limiti.dalle')), h('span.campo.ora', startInput),
|
||||
h('label.etichetta-riga', { for: 'fascia-fine' }, t('impostazioni.limiti.alle')), h('span.campo.ora', endInput),
|
||||
h('span.etichetta-riga.giorni-etichetta', t('impostazioni.limiti.giorni')), days),
|
||||
h('div.riga-sposta', jitterBox, h('span.campo.numero.corto', jitterInput), h('span.muto', t('impostazioni.limiti.minuti'))),
|
||||
windowError),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.limiti.sessioni'), t('impostazioni.limiti.sessioniAiuto')),
|
||||
h('div.cursori',
|
||||
h('span.etichetta-riga', t('impostazioni.limiti.durata')), sessionRange.track, sessionRange.text, sessionRange.error,
|
||||
h('span.etichetta-riga', t('impostazioni.limiti.pausa')), pauseRange.track, pauseRange.text, pauseRange.error,
|
||||
h('label.etichetta-riga', { for: 'ritmo' }, t('impostazioni.limiti.ritmo')), h('div.singolo', paceInput), paceText)),
|
||||
h('div.sezione',
|
||||
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))));
|
||||
}
|
||||
|
||||
function toInt(text) {
|
||||
const trimmed = String(text).trim();
|
||||
if (trimmed === '') return NaN;
|
||||
const n = Number(trimmed);
|
||||
return Number.isFinite(n) ? Math.round(n) : NaN;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// Impostazioni, Notifiche (spec §13.3): which events notify, Windows notifications (desktop only), Telegram with the
|
||||
// bot token (masked, never shown again once saved, never logged) and the chat identifier, and «Invia una prova».
|
||||
// The Telegram sender arrives with milestone M8: until then the server answers plainly that nothing was sent.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { t } from '../core/text.js';
|
||||
import { label, showError, toast, toggle } from '../core/ui.js';
|
||||
import { guardChanges, heading } from './settings.js';
|
||||
|
||||
const EVENTS = ['verification', 'disconnection', 'throttle', 'backfillDone', 'diskLow', 'unknownFormat'];
|
||||
|
||||
export default async function notifications(page, box) {
|
||||
let data = await api('/api/settings/notifications', { signal: page.signal });
|
||||
let form = fromData(data);
|
||||
let original = JSON.stringify(form);
|
||||
const dirty = () => JSON.stringify(form) !== original;
|
||||
guardChanges(page, dirty);
|
||||
|
||||
function fromData(d) {
|
||||
return { events: { ...d.events }, windows: d.windows, chat: d.telegramChatId || '', token: '', removeToken: false };
|
||||
}
|
||||
|
||||
const tokenInput = h('input.dati', { type: 'password', id: 'gettone', autocomplete: 'off', spellcheck: 'false' });
|
||||
const chatInput = h('input.dati', { type: 'text', id: 'chat', autocomplete: 'off', spellcheck: 'false', inputmode: 'text' });
|
||||
tokenInput.addEventListener('input', () => { form.token = tokenInput.value; form.removeToken = false; drawSaveBar(); drawTokenNote(); });
|
||||
chatInput.addEventListener('input', () => { form.chat = chatInput.value; drawSaveBar(); });
|
||||
const tokenNote = h('p.aiuto.piccolo');
|
||||
const removeButton = h('button.btn.nudo.piccolo', { type: 'button', onclick: () => { form.removeToken = true; form.token = ''; tokenInput.value = ''; drawSaveBar(); drawTokenNote(); } }, icon('x', 's'), t('impostazioni.notifiche.togliGettone'));
|
||||
|
||||
function drawTokenNote() {
|
||||
tokenInput.placeholder = data.telegramTokenSet && !form.removeToken ? t('impostazioni.notifiche.gettoneSalvato') : t('impostazioni.notifiche.gettoneVuoto');
|
||||
removeButton.hidden = !data.telegramTokenSet || form.removeToken;
|
||||
tokenNote.textContent = form.removeToken ? t('impostazioni.notifiche.gettoneTolto') : t('impostazioni.notifiche.gettoneNota');
|
||||
}
|
||||
|
||||
async function test(channel) {
|
||||
try {
|
||||
const result = await api('/api/settings/notifications/test', { method: 'POST', body: { channel } });
|
||||
toast(result.message, result.sent ? '' : 'errore');
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function drawSaveBar() {
|
||||
if (!dirty()) {
|
||||
page.saveBar(null);
|
||||
return;
|
||||
}
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', t('impostazioni.modifiche')),
|
||||
h('div.destra',
|
||||
h('button.btn', { type: 'button', onclick: () => { form = fromData(data); draw(); } }, t('impostazioni.annulla')),
|
||||
h('button.btn.primo', { type: 'button', onclick: save }, icon('check'), t('impostazioni.salva')))));
|
||||
}
|
||||
|
||||
async function save() {
|
||||
try {
|
||||
data = await api('/api/settings/notifications', {
|
||||
method: 'PUT',
|
||||
body: { events: form.events, windows: form.windows, telegramChatId: form.chat.trim() || null, telegramToken: form.token.trim() || null, removeTelegramToken: form.removeToken },
|
||||
});
|
||||
form = fromData(data);
|
||||
original = JSON.stringify(form);
|
||||
draw();
|
||||
toast(t('impostazioni.salvate'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function draw() {
|
||||
tokenInput.value = form.token;
|
||||
chatInput.value = form.chat;
|
||||
drawTokenNote();
|
||||
fill(box,
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.notifiche.quando'), t('impostazioni.notifiche.quandoAiuto')),
|
||||
h('div.elenco-leve', EVENTS.map((key) => h('div.leva-riga',
|
||||
toggle({ checked: form.events[key], label: t(`impostazioni.notifiche.eventi.${key}`), onchange: (v) => { form.events[key] = v; drawSaveBar(); } }),
|
||||
h('p.aiuto.piccolo', t(`impostazioni.notifiche.eventiAiuto.${key}`)))))),
|
||||
h('div.sezione',
|
||||
h('div.testa-sez', h('h2.sez', t('impostazioni.notifiche.windows'), ' ', data.windowsAvailable ? null : label(t('impostazioni.notifiche.soloWindows'))),
|
||||
h('p.aiuto', t('impostazioni.notifiche.windowsTesto'))),
|
||||
h('div.riga-azione',
|
||||
toggle({ checked: form.windows && data.windowsAvailable, disabled: !data.windowsAvailable, label: t('impostazioni.notifiche.windows'), onchange: (v) => { form.windows = v; drawSaveBar(); } }),
|
||||
data.windowsAvailable ? h('button.btn.piccolo', { type: 'button', onclick: () => test('windows') }, icon('bell', 's'), t('impostazioni.notifiche.prova')) : null)),
|
||||
h('div.sezione',
|
||||
heading(t('impostazioni.notifiche.telegram'), t('impostazioni.notifiche.telegramAiuto')),
|
||||
data.telegramAvailable ? null : h('div.avviso', { style: { marginBottom: '14px' } }, icon('info', 's'), h('span', t('impostazioni.notifiche.nonAncora'))),
|
||||
h('div.campi-telegram',
|
||||
h('div', h('label.etichetta', { for: 'gettone' }, t('impostazioni.notifiche.gettone')), h('div.riga-campo', h('label.campo', icon('key-round', 's'), tokenInput), removeButton), tokenNote),
|
||||
h('div', h('label.etichetta', { for: 'chat' }, t('impostazioni.notifiche.chat')), h('label.campo', chatInput), h('p.aiuto.piccolo', t('impostazioni.notifiche.chatEsempio')))),
|
||||
h('div.riga-azione', h('button.btn', { type: 'button', onclick: () => test('telegram') }, icon('bell', 's'), t('impostazioni.notifiche.prova')))));
|
||||
chatInput.placeholder = t('impostazioni.notifiche.chatEsempio');
|
||||
drawSaveBar();
|
||||
}
|
||||
|
||||
draw();
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// Impostazioni (spec §10.3; mockups 07, 08, 10): the left sub-menu (Generali, Limiti e comportamento, Collegamento a
|
||||
// Instagram, Notifiche, Dati e copie di sicurezza, Informazioni) and the section on the right. «Collegamento a
|
||||
// Instagram» is a page of its own (mockup 10: back link, no sub-menu).
|
||||
|
||||
import { withCarried } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { confirmDialog } from '../core/ui.js';
|
||||
import { t } from '../core/text.js';
|
||||
|
||||
export const SECTIONS = [
|
||||
{ key: 'generali', icon: 'sliders-horizontal', load: () => import('./settings-general.js') },
|
||||
{ key: 'limiti', icon: 'gauge', load: () => import('./settings-limits.js') },
|
||||
{ key: 'collegamento', icon: 'key-round', load: null },
|
||||
{ key: 'notifiche', icon: 'bell', load: () => import('./settings-notifications.js') },
|
||||
{ key: 'dati', icon: 'database', load: () => import('./settings-data.js') },
|
||||
{ key: 'informazioni', icon: 'info', load: () => import('./settings-about.js') },
|
||||
];
|
||||
|
||||
export default {
|
||||
async mount(page, route) {
|
||||
const key = route.params.section;
|
||||
if (key === 'collegamento') {
|
||||
const connection = await import('./connection.js');
|
||||
return connection.mountConnection(page, route);
|
||||
}
|
||||
const section = SECTIONS.find((s) => s.key === key) || SECTIONS[0];
|
||||
page.title(t('impostazioni.titolo'));
|
||||
document.title = t('app.titoloPagina', { pagina: `${t(`pagine.sezioni.${section.key}`)} · ${t('impostazioni.titolo')}` });
|
||||
const nav = h('nav.sotto-menu', { 'aria-label': t('impostazioni.sezioni') }, SECTIONS.map((s) => h(`a${s.key === section.key ? '.qui' : ''}`, {
|
||||
href: withCarried(`/impostazioni/${s.key}`), 'aria-current': s.key === section.key ? 'page' : null,
|
||||
}, icon(s.icon), h('span', t(`pagine.sezioni.${s.key}`)))));
|
||||
const content = h('div.cont');
|
||||
fill(page.body, h('div.imp', nav, content));
|
||||
const module = await section.load();
|
||||
return module.default(page, content, route);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Unsaved changes: asks before leaving the page (and before closing the tab). isDirty() → boolean.
|
||||
* Returns allow(): call it after saving or discarding so the next navigation does not ask.
|
||||
*/
|
||||
export function guardChanges(page, isDirty) {
|
||||
let allowed = false;
|
||||
page.guard(async () => {
|
||||
if (allowed || !isDirty()) return true;
|
||||
const choice = await confirmDialog({
|
||||
title: t('impostazioni.modifiche'),
|
||||
text: t('impostazioni.esci'),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
|
||||
{ label: t('impostazioni.lascia'), value: true, kind: 'pericolo' },
|
||||
],
|
||||
});
|
||||
if (choice) allowed = true;
|
||||
return Boolean(choice);
|
||||
});
|
||||
const beforeUnload = (e) => {
|
||||
if (!allowed && isDirty()) {
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', beforeUnload);
|
||||
page.onLeave(() => window.removeEventListener('beforeunload', beforeUnload));
|
||||
return () => {
|
||||
allowed = true;
|
||||
};
|
||||
}
|
||||
|
||||
/** A section heading with its help line. */
|
||||
export function heading(title, help, ...extra) {
|
||||
return h('div.testa-sez', h('h2.sez', title, ...extra), help ? h('p.aiuto', help) : null);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Primo avvio (spec §10.3: «la schermata vuota del mockup 13 con i due pulsanti»): when Febe is not connected to
|
||||
// Instagram and the library is empty, the library shows this instead of an empty mosaic.
|
||||
|
||||
import { withCarried } from '../core/api.js';
|
||||
import { h, icon, brand } from '../core/dom.js';
|
||||
import { t } from '../core/text.js';
|
||||
|
||||
export function welcome() {
|
||||
return h('div.benvenuto',
|
||||
h('div.marchio-benvenuto', brand()),
|
||||
h('h2', t('benvenuto.titolo')),
|
||||
h('p', t('benvenuto.testo')),
|
||||
h('div.bottoni-benvenuto',
|
||||
h('a.btn.primo.grande', { href: withCarried('/impostazioni/collegamento') }, icon('key-round', 's'), t('benvenuto.collegati')),
|
||||
h('a.btn.grande', { href: withCarried('/importa?passo=1') }, icon('folder-input', 's'), t('benvenuto.importa'))),
|
||||
h('p.nota-benvenuto', icon('triangle-alert', 'xs'), ' ', t('benvenuto.nota')));
|
||||
}
|
||||
@@ -2,21 +2,19 @@
|
||||
// module that draws it (loaded on demand). The server answers every address without an extension with index.html,
|
||||
// so a new page needs only a line here and its module in js/pages/ (see src/Febe.Web/LEGGIMI.md).
|
||||
|
||||
const placeholder = () => import('./pages/placeholder.js');
|
||||
|
||||
export const routes = [
|
||||
{ pattern: /^\/$/, redirect: '/libreria' },
|
||||
{ pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') },
|
||||
{ pattern: /^\/account\/?$/, nav: 'account', page: () => import('./pages/accounts.js') },
|
||||
{ pattern: /^\/account\/(?<id>\d+)(?:\/(?<tab>contenuti|impostazioni|cronologia))?\/?$/, nav: 'account', page: () => import('./pages/account.js') },
|
||||
{ pattern: /^\/attivita\/?$/, nav: 'attivita', page: placeholder, data: { key: 'attivita' } },
|
||||
{ pattern: /^\/importa\/?$/, nav: 'importa', page: placeholder, data: { key: 'importa' } },
|
||||
{ pattern: /^\/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: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' },
|
||||
{
|
||||
pattern: /^\/impostazioni\/(?<section>generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/,
|
||||
nav: 'impostazioni',
|
||||
page: placeholder,
|
||||
data: { key: 'impostazioni' },
|
||||
page: () => import('./pages/settings.js'),
|
||||
},
|
||||
{ pattern: /^\/browser\/?$/, nav: 'attivita', page: placeholder, data: { key: 'browser' } },
|
||||
{ pattern: /^\/browser\/?$/, nav: 'attivita', page: () => import('./pages/browser.js') },
|
||||
];
|
||||
Reference in new issue
Block a user