Otto schermate nuove in docs/schermate (Impostazioni → Esportazione anche in Docker, finestra della destinazione, blocco «Copie esterne» della scheda account, «Copia in…», Libreria con il filtro «Copie» e il menu dell'icona CSV, righe delle copie nel visualizzatore, scheda «Esportazione» della Dashboard), con le voci e i passi del programma delle schermate, perché §10.7 chiede di confrontare ogni schermata con i mockup da cui nasce. Dal confronto, piccole correzioni dell'interfaccia: la riga dei tipi sotto la cartella generale e le note in Docker non stanno più attaccate, la scheda della Dashboard ha spazio sotto le linguette, il tipo di cartella del blocco dell'account va sopra il campo così il percorso non si taglia, «Copia di nuovo» è allineato ai valori e le icone dei pulsanti dentro un avviso non prendono più il colore dell'avviso. differenze.md elenca la composizione di ogni schermata e le differenze: niente formati né conversione (E3), niente «Automatica» (E5), niente «Fotogrammi…» né «È un video fermo?», il segno sulla tessera, le schede «Motore» ed «Esportazione». Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
755 lines
36 KiB
JavaScript
755 lines
36 KiB
JavaScript
// Scheda account (mockups 05 and 12, spec §4.4, §4.6): header with avatar, name, labels, counts, «Controlla ora» and
|
|
// the link to the profile; tabs Contenuti (Post, Storie as a regular 9:16 grid, In evidenza grouped by collection,
|
|
// Taggati, Profilo when there is more than one picture), Impostazioni (with «Con queste impostazioni» recomputed at
|
|
// every change and the fixed save bar) and Cronologia (the checks with their outcome).
|
|
// Copies to external folders (spec §4.10, tappa E2): in Contenuti the menu of the CSV icon, «Copia in…» in the
|
|
// selection bar and the «Copie» filter; in Impostazioni the block «Copie esterne» under «Cartella», with «Esporta
|
|
// questo account» (on unless switched off), the folder of the copies and «312 su 1.204 non ancora copiati».
|
|
|
|
import { api, download, withCarried } from '../core/api.js';
|
|
import { caps, serverNow } from '../core/context.js';
|
|
import { h, icon, fill, later, local } from '../core/dom.js';
|
|
import { refreshEngine } from '../core/engine.js';
|
|
import { navigate, setQuery } from '../core/shell.js';
|
|
import { t, number, decimal, dayName, shortDay, capitalize } from '../core/text.js';
|
|
import { avatar, checkbox, confirmDialog, menu, segmented, showError, toast, toggle } from '../core/ui.js';
|
|
import { accountLabels, accountMenu, checkNow, openProfile } from './accounts.js';
|
|
import { confirmDelete, selectionBar } from './library.js';
|
|
import { Mosaic, justify, tileElement, defaultDayLabel, filesDayLabel, modeSwitch, storedMode } from './mosaic.js';
|
|
import { kindName, orderEditor, orderOrDefault } from './download-order.js';
|
|
import { openViewer } from './viewer.js';
|
|
import { copiesApi, copiesLabel, copiesMenu, copyDialog, destinationDialog, exportButton, exportMenu, separator } from './export-dialogs.js';
|
|
|
|
const KINDS = [
|
|
{ key: 'post', api: 'posts', stat: 'posts', label: 'scheda.tipi.posts' },
|
|
{ key: 'storie', api: 'stories', stat: 'stories', label: 'scheda.tipi.stories', grid: true },
|
|
{ key: 'evidenza', api: 'highlights', stat: 'highlightItems', label: 'scheda.tipi.highlights' },
|
|
{ key: 'taggati', api: 'tagged', stat: 'tagged', label: 'scheda.tipi.tagged' },
|
|
{ key: 'profilo', api: 'profile', stat: 'profilePictures', label: 'scheda.tipi.profile' },
|
|
];
|
|
|
|
const TYPE_FIELDS = [
|
|
{ key: 'photos', icon: 'image' },
|
|
{ key: 'videos', icon: 'clapperboard' },
|
|
{ key: 'stories', icon: 'circle-dashed' },
|
|
{ key: 'highlights', icon: 'star' },
|
|
{ key: 'tagged', icon: 'square-user' },
|
|
{ key: 'profilePicture', icon: 'circle-user' },
|
|
];
|
|
|
|
const PLAN_ICONS = { posts: 'clock', stories: 'circle-dashed', backfill: 'history', load: 'gauge', checks: 'info' };
|
|
|
|
export default {
|
|
async mount(page, route) {
|
|
const id = Number(route.params.id);
|
|
const tab = route.params.tab || 'contenuti';
|
|
let detail;
|
|
try {
|
|
detail = await api(`/api/accounts/${id}`, { signal: page.signal });
|
|
} catch (error) {
|
|
if (error.name === 'AbortError') return;
|
|
page.back(t('scheda.indietro'), '/account');
|
|
page.title(t('scheda.nonTrovato'));
|
|
fill(page.body, h('div.vuoto-pagina', icon('users'), h('h2', t('scheda.nonTrovato')), h('p', error.message || t('scheda.nonTrovatoTesto'))));
|
|
return;
|
|
}
|
|
|
|
page.back(t('scheda.indietro'), '/account');
|
|
const header = h('header.scheda-testa');
|
|
page.header(header, `@${detail.account.username}`);
|
|
// The menu of the header redraws it after every action, with the same reload each time.
|
|
const reload = async () => {
|
|
detail = await api(`/api/accounts/${id}`, { signal: page.signal });
|
|
drawHeader(header, detail, reload);
|
|
};
|
|
drawHeader(header, detail, reload);
|
|
|
|
const base = `/account/${id}`;
|
|
page.tabs(h('nav.linguette', { 'aria-label': `@${detail.account.username}` },
|
|
h(`a${tab === 'contenuti' ? '.qui' : ''}`, { href: withCarried(base), 'aria-current': tab === 'contenuti' ? 'page' : null },
|
|
t('scheda.linguette.contenuti'), h('i', number(detail.stats.entries))),
|
|
h(`a${tab === 'impostazioni' ? '.qui' : ''}`, { href: withCarried(`${base}/impostazioni`), 'aria-current': tab === 'impostazioni' ? 'page' : null }, t('scheda.linguette.impostazioni')),
|
|
h(`a${tab === 'cronologia' ? '.qui' : ''}`, { href: withCarried(`${base}/cronologia`), 'aria-current': tab === 'cronologia' ? 'page' : null }, t('scheda.linguette.cronologia'))));
|
|
|
|
if (tab === 'impostazioni') return settingsTab(page, detail);
|
|
if (tab === 'cronologia') return historyTab(page, detail);
|
|
return contentsTab(page, route, detail);
|
|
},
|
|
};
|
|
|
|
// --------------------------------------------------------------------------------------------- header
|
|
|
|
function drawHeader(header, detail, reload) {
|
|
const a = detail.account;
|
|
const s = detail.stats;
|
|
const postsBlock = a.state === 'backfilling' && a.postCount
|
|
? h('div', h('b', t('scheda.numeri.postDi', { fatti: number(a.posts), totale: number(a.postCount) })), h('span', t('scheda.numeri.postScaricati')))
|
|
: h('div', h('b', number(s.posts)), h('span', t('scheda.numeri.post')));
|
|
const check = h('button.btn', { type: 'button', disabled: a.state === 'archiveOnly', onclick: () => checkNow(a) }, icon('refresh-cw'), t('account.menu.controlla'));
|
|
const link = detail.instagramUrl
|
|
? h('button.btn.solo', { type: 'button', title: t('scheda.apriProfilo'), 'aria-label': t('scheda.apriProfilo'), onclick: () => openProfile(a) }, icon('external-link'))
|
|
: null;
|
|
const more = h('button.btn.solo', { type: 'button', 'aria-label': t('comune.menu'), 'aria-haspopup': 'true' }, icon('ellipsis'));
|
|
more.addEventListener('click', () => accountMenu(more, a, (outcome) => {
|
|
if (outcome === 'removed') navigate('/account');
|
|
else if (reload) reload().catch(showError);
|
|
}));
|
|
fill(header,
|
|
avatar(a.username, 'g', a.avatar),
|
|
h('div.nomi', h('h1', `@${a.username}`), h('div.sotto', a.isMine ? t('account.sotto.tuo') : a.displayName, accountLabels(a))),
|
|
h('div.numeri',
|
|
h('div', h('b', number(s.entries)), h('span', t('scheda.numeri.elementi'))),
|
|
postsBlock,
|
|
h('div', h('b', number(s.stories)), h('span', t('scheda.numeri.storie'))),
|
|
h('div', h('b', number(s.collections)), h('span', t('scheda.numeri.raccolte')))),
|
|
h('div.azioni', check, link, more));
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------------- contents
|
|
|
|
async function contentsTab(page, route, detail) {
|
|
const s = detail.stats;
|
|
const available = KINDS.filter((k) => k.key !== 'profilo' || s.profilePictures > 1);
|
|
let kind = available.find((k) => k.key === route.query.get('tipo')) || available.find((k) => s[k.stat] > 0) || available[0];
|
|
let period = route.query.get('periodo') || '';
|
|
let copies = copiesApi(route.query.get('copie')) ? route.query.get('copie') : '';
|
|
// The «Copie» filter and «Copia in…» make sense once this account has a folder of the copies.
|
|
const hasDestination = Boolean(detail.export && detail.export.destination);
|
|
let mosaic = null;
|
|
// «Raggruppa i post» / «Tutte le foto» (spec §4.6): one choice for the views of every account, apart from the Libreria.
|
|
let mode = storedMode('account');
|
|
const modes = modeSwitch('account', (value) => {
|
|
mode = value;
|
|
show();
|
|
});
|
|
// «In evidenza» is drawn by its own code: its listeners go when another chip is chosen. The token tells a view
|
|
// still loading that another one took its place.
|
|
let highlightCleanup = null;
|
|
let showToken = 0;
|
|
const chips = h('div.filtri', { role: 'group', 'aria-label': t('scheda.linguette.contenuti') });
|
|
const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '150px' } });
|
|
const copiesButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', hidden: !hasDestination && !copies, style: { minWidth: '96px' } });
|
|
const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona')));
|
|
const csvButton = exportButton();
|
|
page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, copiesButton, h('div.destra', csvButton, modes, selectButton)));
|
|
const host = h('div');
|
|
fill(page.body, host);
|
|
|
|
function drawTools() {
|
|
fill(chips, available.map((k) => h(`button${k === kind ? '.qui' : ''}`, {
|
|
type: 'button', 'aria-pressed': String(k === kind),
|
|
onclick: () => {
|
|
kind = k;
|
|
setQuery({ tipo: k.key });
|
|
show();
|
|
},
|
|
}, t(k.label), h('i', number(s[k.stat])))));
|
|
fill(periodButton, h('span.val', period ? t(`libreria.periodi.${period}`) : t('libreria.periodi.qualsiasi')), icon('chevron-down', 's'));
|
|
fill(copiesButton, h('span.val', copiesLabel(copies)), icon('chevron-down', 's'));
|
|
copiesButton.classList.toggle('attivo', Boolean(copies));
|
|
selectButton.hidden = kind.key === 'evidenza';
|
|
// «In evidenza» is drawn by collection, one tile per item (almost always a single story): no switch there.
|
|
modes.hidden = kind.key === 'evidenza';
|
|
}
|
|
|
|
periodButton.addEventListener('click', () => menu(periodButton,
|
|
['', 'settimana', 'mese', 'anno', 'annoScorso'].map((p) => ({ label: t(p ? `libreria.periodi.${p}` : 'libreria.periodi.qualsiasi'), value: p, checked: p === period, radio: true })),
|
|
(value) => {
|
|
period = value;
|
|
setQuery({ periodo: value || null });
|
|
show();
|
|
}));
|
|
|
|
copiesButton.addEventListener('click', () => copiesMenu(copiesButton, copies, (value) => {
|
|
copies = value;
|
|
setQuery({ copie: value || null });
|
|
show();
|
|
}));
|
|
csvButton.addEventListener('click', () => exportMenu(csvButton, {
|
|
hasDestinations: hasDestination,
|
|
csv: async () => {
|
|
try {
|
|
await download('/api/entries/export', { query: query() }, 'febe-elementi.csv');
|
|
toast(t('libreria.esportatoFiltro'));
|
|
} catch (error) {
|
|
showError(error);
|
|
}
|
|
},
|
|
copy: () => copyDialog({ query: query(), mode: mode === 'files' ? 'files' : 'grouped' }),
|
|
}));
|
|
|
|
function query() {
|
|
const q = new URLSearchParams({ accounts: String(detail.account.id), kind: kind.api });
|
|
const copiesFilter = copiesApi(copies);
|
|
if (copiesFilter) q.set('copies', copiesFilter);
|
|
const today = caps().today;
|
|
const add = (n) => new Date(Date.parse(`${today}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10);
|
|
const year = Number(today.slice(0, 4));
|
|
const range = { settimana: [add(-6), today], mese: [add(-29), today], anno: [`${year}-01-01`, today], annoScorso: [`${year - 1}-01-01`, `${year - 1}-12-31`] }[period];
|
|
if (range) {
|
|
q.set('from', range[0]);
|
|
q.set('to', range[1]);
|
|
}
|
|
return q.toString();
|
|
}
|
|
|
|
function drawSelection(selected) {
|
|
if (!mosaic || !mosaic.selecting) {
|
|
page.saveBar(null);
|
|
return;
|
|
}
|
|
page.saveBar(selectionBar(mosaic, selected, {
|
|
cancel: () => setSelecting(false),
|
|
exportSelected: async () => {
|
|
try {
|
|
await download('/api/entries/export', { ids: mosaic.selectedEntries().ids }, 'febe-elementi.csv');
|
|
toast(t('selezione.esportato'));
|
|
} catch (error) {
|
|
showError(error);
|
|
}
|
|
},
|
|
copySelected: hasDestination
|
|
? () => copyDialog(mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids })
|
|
: null,
|
|
deleteSelected: async () => {
|
|
const { ids, files } = mosaic.selectedEntries();
|
|
const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null);
|
|
if (removed) {
|
|
mosaic.removeTiles(removed);
|
|
setSelecting(false);
|
|
}
|
|
},
|
|
}));
|
|
}
|
|
|
|
function setSelecting(on) {
|
|
if (!mosaic) return;
|
|
mosaic.setSelecting(on);
|
|
fill(selectButton, icon(on ? 'check' : 'circle-check'), h('span', t(on ? 'libreria.fine' : 'libreria.seleziona')));
|
|
selectButton.setAttribute('aria-pressed', String(on));
|
|
drawSelection(mosaic.selected);
|
|
}
|
|
selectButton.addEventListener('click', () => mosaic && setSelecting(!mosaic.selecting));
|
|
|
|
async function show() {
|
|
const token = ++showToken;
|
|
drawTools();
|
|
if (mosaic) mosaic.destroy();
|
|
mosaic = null;
|
|
if (highlightCleanup) highlightCleanup();
|
|
highlightCleanup = null;
|
|
page.saveBar(null);
|
|
page.body.scrollTop = 0;
|
|
if (kind.key === 'evidenza') {
|
|
const cleanup = await showHighlights(host, detail, page, () => token === showToken);
|
|
if (token === showToken) highlightCleanup = cleanup;
|
|
else if (cleanup) cleanup();
|
|
return;
|
|
}
|
|
const rowHeight = local.get('libreria.tessere', 160);
|
|
mosaic = new Mosaic({
|
|
scroller: page.body,
|
|
host,
|
|
query: query(),
|
|
mode: kind.grid ? 'grid' : 'justified',
|
|
files: mode === 'files',
|
|
rowHeight,
|
|
signal: page.signal,
|
|
dayLabel: mode === 'files' ? filesDayLabel : kind.grid ? storiesDayLabel : defaultDayLabel,
|
|
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: `@${detail.account.username}`, onDeleted: (ids) => mosaic.removeTiles(ids) }),
|
|
onSelection: drawSelection,
|
|
onEmpty: () => fill(host, h('div.vuoto-pagina', icon(kind.grid ? 'circle-dashed' : 'image'), h('p', t('scheda.nessunContenuto')))),
|
|
});
|
|
try {
|
|
await mosaic.start();
|
|
} catch (error) {
|
|
showError(error);
|
|
}
|
|
}
|
|
|
|
const onChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 500);
|
|
const onMarks = later(() => mosaic && mosaic.refreshMarks().catch(() => {}), 600);
|
|
page.onLibrary((change) => {
|
|
if (!change.accountId || change.accountId === detail.account.id) {
|
|
onChange();
|
|
if (change.reason === 'export') onMarks();
|
|
}
|
|
});
|
|
page.onLeave(() => {
|
|
onChange.cancel();
|
|
onMarks.cancel();
|
|
if (mosaic) mosaic.destroy();
|
|
if (highlightCleanup) highlightCleanup();
|
|
});
|
|
await show();
|
|
}
|
|
|
|
/** Day header of the stories: «Oggi martedì 13 ottobre, 2 storie», «Sabato 10 ottobre 9 storie». */
|
|
function storiesDayLabel(day, count, today) {
|
|
const [bold] = defaultDayLabel(day, count, today);
|
|
const name = dayName(day, today);
|
|
const n = t('libreria.storieGiorno', { n: count });
|
|
if (bold === t('tempo.Oggi') || bold === t('tempo.Ieri')) return [bold, `${name}, ${n}`];
|
|
return [capitalize(name), n];
|
|
}
|
|
|
|
/**
|
|
* «In evidenza»: the mosaic grouped under the titles of the collections (mockup 12). current() is false once another
|
|
* chip took the place of this view (nothing is drawn then). Returns the function that removes its listeners, or null.
|
|
*/
|
|
async function showHighlights(host, detail, page, current) {
|
|
const collections = detail.highlights.filter((c) => c.count > 0);
|
|
if (!collections.length) {
|
|
fill(host, h('div.vuoto-pagina', icon('star'), h('p', t('scheda.nessunContenuto'))));
|
|
return null;
|
|
}
|
|
fill(host, h('div.caricamento', t('comune.caricamento')));
|
|
const ids = [...new Set(collections.flatMap((c) => c.entryIds))];
|
|
const tiles = new Map();
|
|
for (let i = 0; i < ids.length; i += 1000) {
|
|
const page2 = await api(`/api/library/tiles?ids=${ids.slice(i, i + 1000).join(',')}`, { signal: page.signal });
|
|
if (!current()) return null;
|
|
for (const tile of page2.tiles) tiles.set(tile.id, tile);
|
|
}
|
|
const flat = [];
|
|
const groups = collections.map((c) => {
|
|
const list = c.entryIds.map((x) => tiles.get(x)).filter(Boolean);
|
|
flat.push(...list);
|
|
return { c, list };
|
|
});
|
|
const source = {
|
|
position: (entryId) => ({ index: flat.findIndex((x) => x.id === entryId) + 1, total: flat.length }),
|
|
neighbor: async (entryId, delta) => flat[flat.findIndex((x) => x.id === entryId) + delta] || null,
|
|
reveal: () => {},
|
|
};
|
|
const draw = () => {
|
|
const width = host.clientWidth || 800;
|
|
const rowHeight = local.get('libreria.tessere', 160);
|
|
fill(host, groups.map(({ c, list }) => h('section',
|
|
h('div.raccolta-titolo', h('b', c.title), h('span', [t('comune.contenuti', { n: list.length }), c.removed ? ` · ${t('scheda.raccoltaTolta')}` : ''].join(''))),
|
|
justify(list, width, rowHeight).map((row) => h('div.fila', row.items.map((item) => tileElement(item.tile, item.width, row.height, { today: caps().today })))))));
|
|
};
|
|
draw();
|
|
host.onclick = (e) => {
|
|
const el = e.target.closest('.tess[data-id]');
|
|
if (!el) return;
|
|
const tile = flat.find((x) => x.id === Number(el.dataset.id));
|
|
if (tile) openViewer({ tile, source, origin: `@${detail.account.username}`, onDeleted: () => draw() });
|
|
};
|
|
const redraw = later(draw, 150);
|
|
const observer = new ResizeObserver(redraw);
|
|
observer.observe(host);
|
|
return () => {
|
|
observer.disconnect();
|
|
redraw.cancel();
|
|
host.onclick = null;
|
|
};
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------------- settings
|
|
|
|
function settingsTab(page, detail) {
|
|
page.body.style.paddingTop = '16px';
|
|
const c = caps();
|
|
const original = JSON.stringify(detail.settings);
|
|
let form = JSON.parse(original);
|
|
let plan = detail.plan;
|
|
const account = detail.account;
|
|
const planBox = h('div.piano', { 'aria-live': 'polite' });
|
|
const left = h('div.colonna');
|
|
fill(page.body, h('div.imp-account', left, planBox));
|
|
|
|
const dirty = () => JSON.stringify(form) !== original;
|
|
const recompute = later(async () => {
|
|
try {
|
|
plan = await api(`/api/accounts/${account.id}/plan`, { method: 'POST', body: form, signal: page.signal });
|
|
drawPlan();
|
|
frequencyNote.textContent = plan.frequencyHint;
|
|
} catch (error) {
|
|
if (error.name !== 'AbortError' && error.status === 400) planBox.prepend(h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message)));
|
|
}
|
|
}, 200);
|
|
|
|
function changed() {
|
|
drawSaveBar();
|
|
recompute();
|
|
drawOrder();
|
|
}
|
|
|
|
// Tieni aggiornato.
|
|
const keep = toggle({ checked: form.keepUpdated, label: t('impAccount.tieni'), onchange: (v) => { form.keepUpdated = v; changed(); } });
|
|
keep.querySelector('span:last-child').style.fontWeight = '650';
|
|
|
|
// Frequenza.
|
|
const frequencyNote = h('span.nota', plan.frequencyHint);
|
|
const customFields = h('div.riga-campi');
|
|
const postHours = h('input', { type: 'number', min: '1', max: '48', step: '0.5', value: form.customPostHours ?? '', inputmode: 'decimal', id: 'ore-post' });
|
|
const storyHours = h('input', { type: 'number', min: '1', max: '24', step: '0.5', value: form.customStoryHours ?? '', inputmode: 'decimal', id: 'ore-storie' });
|
|
postHours.addEventListener('input', () => { form.customPostHours = postHours.value === '' ? null : Number(postHours.value); changed(); });
|
|
storyHours.addEventListener('input', () => { form.customStoryHours = storyHours.value === '' ? null : Number(storyHours.value); changed(); });
|
|
fill(customFields,
|
|
h('div', h('label.etichetta', { for: 'ore-post' }, t('impAccount.suMisuraPost')), h('label.campo', postHours, h('span.unita', t('impAccount.ore')))),
|
|
h('div', h('label.etichetta', { for: 'ore-storie' }, t('impAccount.suMisuraStorie')), h('label.campo', storyHours, h('span.unita', t('impAccount.ore')))));
|
|
customFields.hidden = form.frequency !== 'custom';
|
|
const frequency = segmented({
|
|
label: t('impAccount.frequenza'),
|
|
value: form.frequency,
|
|
options: ['low', 'normal', 'high', 'custom'].map((f) => ({ value: f, label: t(`impAccount.frequenze.${f}`) })),
|
|
onchange: (v) => {
|
|
form.frequency = v;
|
|
customFields.hidden = v !== 'custom';
|
|
changed();
|
|
},
|
|
});
|
|
|
|
// Cosa scaricare.
|
|
const types = h('div.tipi', TYPE_FIELDS.map((f) => {
|
|
const box = checkbox({ checked: form.types[f.key], labelNode: h('span.testo', t(`impAccount.tipi.${f.key}`)), onchange: (v) => { form.types[f.key] = v; changed(); } });
|
|
box.classList.add('tipo');
|
|
box.append(icon(f.icon, 's'));
|
|
return box;
|
|
}));
|
|
|
|
// Cosa scaricare prima (spec §4.4, §7.2): «Come le impostazioni generali» or an order of its own, which starts from the
|
|
// general one. The kinds switched off in «Cosa scaricare» stay in the list, attenuated.
|
|
const general = orderOrDefault(detail.generalDownloadOrder);
|
|
const KIND_TYPES = { storie: ['stories'], evidenza: ['highlights'], post: ['photos', 'videos'], reel: ['videos'], taggati: ['tagged'] };
|
|
const orderBox = h('div.ordine-account');
|
|
const order = orderEditor({
|
|
read: () => form.downloadOrder,
|
|
write: (next) => { form.downloadOrder = next; },
|
|
changed,
|
|
off: (kind) => !(KIND_TYPES[kind] || []).some((key) => form.types[key]),
|
|
label: t('impAccount.ordineScelta'),
|
|
});
|
|
const orderChoice = segmented({
|
|
// The list is «Ordine dei tipi per questo account»; the two-way choice has the name of the section.
|
|
label: t('impAccount.ordine'),
|
|
value: Array.isArray(form.downloadOrder) && form.downloadOrder.length ? 'own' : 'general',
|
|
options: [{ value: 'general', label: t('impAccount.ordineGenerale') }, { value: 'own', label: t('impAccount.ordineSuo') }],
|
|
onchange: (v) => {
|
|
form.downloadOrder = v === 'own' ? [...general] : null;
|
|
changed();
|
|
},
|
|
});
|
|
function drawOrder() {
|
|
if (Array.isArray(form.downloadOrder) && form.downloadOrder.length) {
|
|
order.draw();
|
|
fill(orderBox, h('div.pannello', order.list), order.status);
|
|
} else {
|
|
fill(orderBox, h('p.nota', t('impAccount.ordineOra', { ordine: general.map(kindName).join(', ') })));
|
|
}
|
|
}
|
|
drawOrder();
|
|
// Limiti.
|
|
const depth = h('select', { id: 'profondita' }, ['all', 'lastPosts', 'fromDate'].map((d) => h('option', { value: d, selected: form.depth === d }, t(`impAccount.profondita.${d}`))));
|
|
const lastPosts = h('input', { type: 'number', min: '1', step: '1', value: form.lastPosts ?? 100, id: 'ultimi', inputmode: 'numeric' });
|
|
const fromDate = h('input', { type: 'date', value: form.fromDate ?? caps().today, id: 'dal', max: caps().today });
|
|
const depthExtra = h('div');
|
|
function drawDepthExtra() {
|
|
if (form.depth === 'lastPosts') {
|
|
if (form.lastPosts == null) form.lastPosts = Number(lastPosts.value) || 100;
|
|
fill(depthExtra, h('label.etichetta', { for: 'ultimi' }, t('impAccount.quantiPost')), h('label.campo', lastPosts, h('span.unita', t('impAccount.post'))));
|
|
} else if (form.depth === 'fromDate') {
|
|
if (!form.fromDate) form.fromDate = fromDate.value;
|
|
fill(depthExtra, h('label.etichetta', { for: 'dal' }, t('impAccount.dalGiorno')), h('label.campo', fromDate));
|
|
} else depthExtra.replaceChildren();
|
|
depthExtra.hidden = form.depth === 'all';
|
|
}
|
|
depth.addEventListener('change', () => { form.depth = depth.value; drawDepthExtra(); changed(); });
|
|
lastPosts.addEventListener('input', () => { form.lastPosts = lastPosts.value === '' ? null : Number(lastPosts.value); changed(); });
|
|
fromDate.addEventListener('input', () => { form.fromDate = fromDate.value || null; changed(); });
|
|
const perDay = h('input', { type: 'number', min: '1', max: String(detail.maxBackfillPerDay), step: '1', value: form.backfillPerDay, id: 'al-giorno', inputmode: 'numeric' });
|
|
perDay.addEventListener('input', () => { form.backfillPerDay = Number(perDay.value) || 0; changed(); });
|
|
const maxVideo = h('input', { type: 'number', min: '1', step: '1', value: form.maxVideoMb ?? '', placeholder: t('impAccount.nessunLimite'), id: 'video-oltre', inputmode: 'decimal' });
|
|
maxVideo.addEventListener('input', () => { form.maxVideoMb = maxVideo.value === '' ? null : Number(maxVideo.value); changed(); });
|
|
const storyVideos = toggle({ checked: form.storyVideos, label: t('impAccount.videoStorie'), onchange: (v) => { form.storyVideos = v; changed(); } });
|
|
drawDepthExtra();
|
|
|
|
// Cartella.
|
|
const folderValue = h('span.val', detail.folder);
|
|
const folderActions = h('div', { style: { display: 'contents' } });
|
|
function drawFolder(path) {
|
|
folderValue.textContent = path;
|
|
const items = [];
|
|
if (!c.foldersReadOnly && c.pickFolder) {
|
|
items.push(h('button.btn', { type: 'button', onclick: pickFolder }, t('impAccount.cambia')));
|
|
if (form.folder) items.push(h('button.btn.nudo', { type: 'button', onclick: () => { form.folder = null; drawFolder(t('impAccount.predefinita')); changed(); } }, t('impAccount.predefinita')));
|
|
}
|
|
fill(folderActions, items);
|
|
}
|
|
async function pickFolder() {
|
|
try {
|
|
const result = await api(`/api/accounts/${account.id}/pick-folder`, { method: 'POST' });
|
|
if (result.message) {
|
|
form.folder = result.message;
|
|
drawFolder(result.message);
|
|
changed();
|
|
}
|
|
} catch (error) {
|
|
showError(error);
|
|
}
|
|
}
|
|
drawFolder(detail.folder);
|
|
|
|
fill(left,
|
|
account.state === 'archiveOnly' ? h('div.avviso', { style: { marginBottom: '12px' } }, icon('archive', 's'), h('span', t('impAccount.archivio'))) : null,
|
|
h('div.sezione', keep, h('p.aiuto', { style: { margin: '6px 0 0 46px' } }, t('impAccount.tieniAiuto'))),
|
|
h('div.sezione', h('h2.sez', t('impAccount.frequenza')), h('div.frequenza', frequency, frequencyNote), customFields),
|
|
h('div.sezione', h('h2.sez', t('impAccount.cosa')), h('p.aiuto', t('impAccount.cosaAiuto')), types),
|
|
h('div.sezione', h('h2.sez', t('impAccount.ordine')), h('p.aiuto', t('impAccount.ordineAiuto')), orderChoice, orderBox),
|
|
h('div.sezione', h('h2.sez', t('impAccount.limiti')), h('p.aiuto', t('impAccount.limitiAiuto')),
|
|
h('div.riga-campi',
|
|
h('div', h('label.etichetta', { for: 'profondita' }, t('impAccount.quanto')), h('label.campo.scelta', depth, icon('chevron-down', 's'))),
|
|
h('div', h('label.etichetta', { for: 'al-giorno' }, t('impAccount.storicoGiorno')), h('label.campo', perDay, h('span.unita', t('impAccount.post')))),
|
|
h('div', h('label.etichetta', { for: 'video-oltre' }, t('impAccount.saltaVideo')), h('label.campo', maxVideo, h('span.unita', t('impAccount.mb'))))),
|
|
h('div.riga-campi', depthExtra),
|
|
h('div', { style: { marginTop: '14px' } }, storyVideos)),
|
|
h('div.sezione', h('h2.sez', t('impAccount.cartella')), h('p.aiuto', t(c.foldersReadOnly ? 'impAccount.cartellaDocker' : 'impAccount.cartellaAiuto')),
|
|
h('div.cartella', h('div.campo.sola', icon('folder', 's'), folderValue), folderActions)),
|
|
copiesBlock(page, detail));
|
|
|
|
function drawPlan() {
|
|
const lines = plan.lines.map((l) => {
|
|
const body = h('div', h('b', l.title), ' ', l.text);
|
|
if (l.key === 'load') {
|
|
const ratio = Math.min(1, plan.share || 0);
|
|
body.append(h('div.misura', { role: 'meter', 'aria-valuemin': '0', 'aria-valuemax': String(plan.dailyBudget), 'aria-valuenow': String(Math.round(plan.opensPerDay)), 'aria-label': l.title },
|
|
h('i', { style: { width: `${Math.max(2, ratio * 100)}%` } })),
|
|
h('small', t('impAccount.caricoMisura', { usati: decimal(plan.opensPerDay, plan.opensPerDay < 10 ? 1 : 0), totale: number(plan.dailyBudget) })));
|
|
body.classList.add('carico');
|
|
}
|
|
return h('div.voce-piano', icon(PLAN_ICONS[l.key] || 'info', 's'), body);
|
|
});
|
|
fill(planBox,
|
|
h('div.pannello', h('h2', t('impAccount.piano')), lines),
|
|
plan.warnings.map((w) => h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', w))),
|
|
plan.note ? h('div.avviso', icon('info', 's'), h('span', plan.note)) : null);
|
|
}
|
|
drawPlan();
|
|
|
|
function drawSaveBar() {
|
|
if (!dirty()) {
|
|
page.saveBar(null);
|
|
return;
|
|
}
|
|
page.saveBar(h('div', { style: { display: 'contents' } },
|
|
h('span.nota', t('impAccount.modifiche')),
|
|
h('div.destra',
|
|
h('button.btn', { type: 'button', onclick: () => { leaveAllowed = true; navigate(location.pathname + location.search, { replace: true }); } }, t('impAccount.annulla')),
|
|
h('button.btn.primo', { type: 'button', onclick: save }, icon('check'), t('impAccount.salva')))));
|
|
}
|
|
|
|
async function save() {
|
|
try {
|
|
const updated = await api(`/api/accounts/${account.id}/settings`, { method: 'PUT', body: form });
|
|
toast(t('impAccount.salvate', { nome: account.username }));
|
|
leaveAllowed = true;
|
|
refreshEngine();
|
|
navigate(location.pathname + location.search, { replace: true });
|
|
void updated;
|
|
} catch (error) {
|
|
showError(error);
|
|
}
|
|
}
|
|
|
|
let leaveAllowed = false;
|
|
page.guard(async () => {
|
|
if (leaveAllowed || !dirty()) return true;
|
|
const choice = await confirmDialog({
|
|
title: t('impAccount.modifiche'),
|
|
text: t('impAccount.esci'),
|
|
buttons: [
|
|
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
|
|
{ label: t('impAccount.lascia'), value: true, kind: 'pericolo' },
|
|
],
|
|
});
|
|
if (choice) leaveAllowed = true;
|
|
return Boolean(choice);
|
|
});
|
|
const beforeUnload = (e) => {
|
|
if (dirty() && !leaveAllowed) {
|
|
e.preventDefault();
|
|
e.returnValue = '';
|
|
}
|
|
};
|
|
window.addEventListener('beforeunload', beforeUnload);
|
|
page.onLeave(() => {
|
|
recompute.cancel();
|
|
window.removeEventListener('beforeunload', beforeUnload);
|
|
});
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------------- copie esterne
|
|
|
|
/**
|
|
* «Copie esterne» (spec §4.10, mockup 05): «Esporta questo account», which acts at once and is not part of the form
|
|
* (decision D1: on unless switched off), where the copies go, how many files are still to copy and «Copia in…».
|
|
*/
|
|
function copiesBlock(page, detail) {
|
|
const account = detail.account;
|
|
const box = h('div.sezione.copie-esterne');
|
|
let data = detail.export || { enabled: true, hasOwnFolder: false, destination: null, due: 0, notCopied: 0, removedOrSuperseded: 0, failed: 0 };
|
|
const body = h('div.copie-corpo');
|
|
const toggleBox = toggle({
|
|
checked: data.enabled,
|
|
label: t('esportazione.account.interruttore'),
|
|
onchange: async (value, input) => {
|
|
input.disabled = true;
|
|
try {
|
|
const result = await api(`/api/accounts/${account.id}/export-enabled`, { method: 'POST', body: { value } });
|
|
toast(result.message);
|
|
await reload();
|
|
} catch (error) {
|
|
input.checked = !value;
|
|
showError(error);
|
|
} finally {
|
|
input.disabled = false;
|
|
}
|
|
},
|
|
});
|
|
|
|
async function reload() {
|
|
try {
|
|
const fresh = await api(`/api/accounts/${account.id}`, { signal: page.signal });
|
|
data = fresh.export || data;
|
|
toggleBox.input.checked = data.enabled;
|
|
draw();
|
|
} catch (error) {
|
|
if (error.name !== 'AbortError') showError(error);
|
|
}
|
|
}
|
|
|
|
async function chooseOwn() {
|
|
const saved = await destinationDialog({ scope: 'account', accountId: account.id, username: account.username, destination: data.hasOwnFolder ? data.destination : null });
|
|
if (saved) await reload();
|
|
}
|
|
|
|
async function useGeneral() {
|
|
const general = data.hasOwnFolder && data.destination;
|
|
if (!general) return;
|
|
// Is there a general folder to fall back to? The overview says so.
|
|
let overview = null;
|
|
try {
|
|
overview = await api('/api/export');
|
|
} catch (error) {
|
|
showError(error);
|
|
return;
|
|
}
|
|
const fallback = Boolean(overview.general);
|
|
const ok = await confirmDialog({
|
|
title: t(fallback ? 'esportazione.account.usaGeneraleTitolo' : 'esportazione.account.togliTitolo', { nome: account.username }),
|
|
text: t(fallback ? 'esportazione.account.usaGeneraleTesto' : 'esportazione.account.togliTesto'),
|
|
buttons: [
|
|
{ label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
|
|
{ label: t(fallback ? 'esportazione.account.usaGenerale' : 'esportazione.togliSi'), value: true, kind: fallback ? 'primo' : 'pericolo' },
|
|
],
|
|
});
|
|
if (!ok) return;
|
|
try {
|
|
const result = await api(`/api/export/destinations/${data.destination.id}`, { method: 'DELETE' });
|
|
toast(result.message);
|
|
await reload();
|
|
} catch (error) {
|
|
showError(error);
|
|
}
|
|
}
|
|
|
|
function draw() {
|
|
const d = data.destination;
|
|
const rows = [];
|
|
if (d) {
|
|
const where = data.hasOwnFolder ? d.display : `${d.display}${separator(d.display)}${account.username}`;
|
|
// The kind of folder goes above the field, like the labels of mockup 08: the path keeps the whole width.
|
|
rows.push(h('span.etichetta.etichetta-copie', t(data.hasOwnFolder ? 'esportazione.account.sua' : 'esportazione.account.generale')));
|
|
rows.push(h('div.cartella',
|
|
h('div.campo.sola', { title: where }, icon('hard-drive', 's'), h('span.val.dati', where)),
|
|
data.hasOwnFolder
|
|
? [h('button.btn', { type: 'button', onclick: chooseOwn }, t('esportazione.modifica')),
|
|
h('button.btn.nudo', { type: 'button', onclick: useGeneral }, t('esportazione.account.usaGenerale'))]
|
|
: h('button.btn', { type: 'button', onclick: chooseOwn }, t('esportazione.account.scegliSua'))));
|
|
if (d.pausedAt || d.problem) {
|
|
rows.push(h('div.avviso.ambra', { style: { marginTop: '10px' } }, icon('pause', 's'), h('span', t('esportazione.pausa', { problema: d.problem || '' }))));
|
|
}
|
|
} else {
|
|
rows.push(h('div.cartella',
|
|
h('div.campo.sola', icon('folder', 's'), h('span.val.tenue', t('esportazione.nessunaCartella'))),
|
|
h('button.btn', { type: 'button', onclick: chooseOwn }, t('esportazione.account.scegliSua'))),
|
|
h('p.aiuto', { style: { marginTop: '8px' } }, t('esportazione.account.nessuna')));
|
|
}
|
|
if (!data.enabled) {
|
|
rows.push(h('p.aiuto.conteggio-copie', icon('info', 'xs'), ' ', t('esportazione.account.spento')));
|
|
} else if (d) {
|
|
let count;
|
|
if (!data.due) count = t('esportazione.account.nessunFile');
|
|
else if (!data.notCopied) count = t('esportazione.account.tuttiCopiati', { n: data.due });
|
|
else count = t('esportazione.account.conteggio', { n: data.notCopied, totale: data.due });
|
|
const extra = [];
|
|
if (data.removedOrSuperseded) extra.push(t('esportazione.account.tolti', { n: data.removedOrSuperseded }));
|
|
if (data.failed) extra.push(t('esportazione.account.falliti', { n: data.failed }));
|
|
rows.push(h('div.riga-conteggi.conteggio-copie',
|
|
h('span', h('b', count), extra.length ? ` · ${extra.join(' · ')}` : ''),
|
|
h('button.btn', { type: 'button', onclick: () => copyDialog({ accountId: account.id }, { title: t('esportazione.copia.titolo') }) }, icon('copy'), t('esportazione.account.copiaIn'))));
|
|
}
|
|
fill(body, rows);
|
|
}
|
|
|
|
draw();
|
|
fill(box,
|
|
h('h2.sez', t('esportazione.account.titolo')),
|
|
h('p.aiuto', t('esportazione.account.aiuto')),
|
|
h('div', { style: { margin: '12px 0 4px' } }, toggleBox),
|
|
body);
|
|
const onChange = later(() => reload(), 600);
|
|
page.onLibrary((change) => {
|
|
if (change.reason === 'export' && (!change.accountId || change.accountId === account.id)) onChange();
|
|
});
|
|
page.onLeave(() => onChange.cancel());
|
|
return box;
|
|
}
|
|
|
|
// --------------------------------------------------------------------------------------------- history
|
|
|
|
async function historyTab(page, detail) {
|
|
page.body.style.paddingTop = '16px';
|
|
const tbody = h('tbody');
|
|
const more = h('button.btn', { type: 'button', hidden: true }, t('cronologia.altri'));
|
|
fill(page.body, h('div.cronologia',
|
|
h('div.pannello', h('table.tab', h('caption.vh', t('cronologia.titolo')), tbody)),
|
|
h('div', { style: { marginTop: '14px' } }, more)));
|
|
let before = null;
|
|
const today = caps().today;
|
|
function when(local) {
|
|
if (local.dayDelta === 0) return `${t('tempo.oggi')}, ${local.clock}`;
|
|
if (local.dayDelta === -1) return `${t('tempo.ieri')}, ${local.clock}`;
|
|
return `${shortDay(local.day, today)}, ${local.clock}`;
|
|
}
|
|
async function load() {
|
|
try {
|
|
const data = await api(`/api/accounts/${detail.account.id}/history${before ? `?before=${before}` : ''}`, { signal: page.signal });
|
|
if (!data.items.length && !before) {
|
|
fill(page.body, h('div.vuoto-pagina', icon('history'), h('p', t('cronologia.vuota'))));
|
|
return;
|
|
}
|
|
for (const item of data.items) {
|
|
const split = item.message.indexOf(': ');
|
|
const text = split > 0 ? item.message.slice(split + 2) : item.message;
|
|
const code = item.code.startsWith('ricetta.') ? item.code.slice('ricetta.'.length) : item.code === 'account.pausa' ? 'pausa' : 'altro';
|
|
const kindLabel = t(`cronologia.ricette.${code}`) === `cronologia.ricette.${code}` ? t('cronologia.ricette.altro') : t(`cronologia.ricette.${code}`);
|
|
const outcome = { success: ['verde', 'circle-check'], warning: ['ambra', 'triangle-alert'], error: ['rosso', 'octagon-alert'], info: ['', 'check'] }[item.severity] || ['', 'check'];
|
|
tbody.append(h('tr',
|
|
h('td.quando-cella.dati', when(item.at)),
|
|
h('td', h('b', { style: { fontWeight: '600' } }, kindLabel), h('div.muto', { style: { fontSize: '13px' } }, capitalize(text))),
|
|
h('td', { style: { textAlign: 'right' } }, h(`span.et${outcome[0] ? '.' + outcome[0] : ''}`, icon(outcome[1]), t(`cronologia.esiti.${item.severity}`)))));
|
|
}
|
|
before = data.before;
|
|
more.hidden = !before;
|
|
} catch (error) {
|
|
showError(error);
|
|
}
|
|
}
|
|
more.addEventListener('click', load);
|
|
await load();
|
|
void serverNow;
|
|
}
|