Interfaccia web, parte 1: ospite, sicurezza, API, modalità dimostrativa, libreria, visualizzatore e account
Febe.Web: AddFebeWeb/UseFebe/FebeWebHost per le due vesti, interfaccia incorporata con IFileProvider proprio, indirizzi italiani, API JSON con contesto generato, eventi SSE, controlli di Host/Origin, gettone del desktop e password con blocco (§13.1), INativeShell e capacità per veste. Modalità --demo con 38 account e circa 18.000 elementi finti e scene del motore. Pagine Libreria, Visualizzatore, Account, Aggiungi account e Scheda account (contenuti, impostazioni con piano, cronologia); schermate in docs/schermate con le differenze dai mockup; prove delle API, della sicurezza, dell'esportazione CSV e dei dati dimostrativi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
76 files changed
+12503
-17
No files matched your search
@@ -0,0 +1,523 @@
|
||||
// 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).
|
||||
|
||||
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 } from './library.js';
|
||||
import { Mosaic, justify, tileElement, defaultDayLabel } from './mosaic.js';
|
||||
import { openViewer } from './viewer.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}`);
|
||||
drawHeader(header, detail, async () => {
|
||||
detail = await api(`/api/accounts/${id}`, { signal: page.signal });
|
||||
drawHeader(header, detail);
|
||||
});
|
||||
|
||||
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 mosaic = null;
|
||||
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 selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona')));
|
||||
page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, h('div.destra', 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'));
|
||||
selectButton.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();
|
||||
}));
|
||||
|
||||
function query() {
|
||||
const q = new URLSearchParams({ accounts: String(detail.account.id), kind: kind.api });
|
||||
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;
|
||||
}
|
||||
const n = selected.size;
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', n ? t('selezione.scelti', { n }) : t('selezione.nessuno')),
|
||||
h('div.destra',
|
||||
h('button.btn.nudo', { type: 'button', onclick: () => setSelecting(false) }, t('selezione.annulla')),
|
||||
h('button.btn', { type: 'button', disabled: !n, onclick: async () => {
|
||||
try {
|
||||
await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv');
|
||||
toast(t('selezione.esportato'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
} }, icon('file-down'), t('selezione.esporta')),
|
||||
h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: async () => {
|
||||
const removed = await confirmDelete([...mosaic.selected]);
|
||||
if (removed) {
|
||||
mosaic.removeTiles(removed);
|
||||
setSelecting(false);
|
||||
}
|
||||
} }, icon('trash-2'), t('selezione.elimina', { n })))));
|
||||
}
|
||||
|
||||
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() {
|
||||
drawTools();
|
||||
if (mosaic) mosaic.destroy();
|
||||
mosaic = null;
|
||||
page.saveBar(null);
|
||||
page.body.scrollTop = 0;
|
||||
if (kind.key === 'evidenza') {
|
||||
await showHighlights(host, detail, page);
|
||||
return;
|
||||
}
|
||||
const rowHeight = local.get('libreria.tessere', 160);
|
||||
mosaic = new Mosaic({
|
||||
scroller: page.body,
|
||||
host,
|
||||
query: query(),
|
||||
mode: kind.grid ? 'grid' : 'justified',
|
||||
rowHeight,
|
||||
signal: page.signal,
|
||||
dayLabel: 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);
|
||||
page.onLibrary((change) => {
|
||||
if (!change.accountId || change.accountId === detail.account.id) onChange();
|
||||
});
|
||||
page.onLeave(() => {
|
||||
onChange.cancel();
|
||||
if (mosaic) mosaic.destroy();
|
||||
});
|
||||
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). */
|
||||
async function showHighlights(host, detail, page) {
|
||||
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;
|
||||
}
|
||||
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 });
|
||||
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 observer = new ResizeObserver(later(draw, 150));
|
||||
observer.observe(host);
|
||||
page.onLeave(() => observer.disconnect());
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- 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();
|
||||
}
|
||||
|
||||
// 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;
|
||||
}));
|
||||
|
||||
// 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.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)));
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- 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;
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
// Account (mockup 03, spec §4.2): table with avatar, name and labels, the five «Raccoglie» icons, state with its
|
||||
// second line and the history progress, last and next check, entries in the library, «Tieni aggiornato» acting at
|
||||
// once, the row menu; filter chips with counts, search, sort, «Aggiungi account». A click on a row opens the card.
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { caps, serverNow } from '../core/context.js';
|
||||
import { h, icon, fill, later, local } from '../core/dom.js';
|
||||
import { refreshEngine, engineState } from '../core/engine.js';
|
||||
import { navigate, setQuery } from '../core/shell.js';
|
||||
import { t, number, ago, around, shortDay } from '../core/text.js';
|
||||
import { avatar, label, menu, toggle, toast, showError, confirmDialog, dialog, radio } from '../core/ui.js';
|
||||
import { openAddAccounts } from './add-accounts.js';
|
||||
|
||||
const FILTERS = ['tutti', 'upToDate', 'backfilling', 'paused', 'archiveOnly', 'needsAttention'];
|
||||
const SORTS = ['ultimo', 'prossimo', 'nome', 'libreria', 'aggiunta'];
|
||||
const TYPES = [
|
||||
{ key: 'photos', icon: 'image' },
|
||||
{ key: 'videos', icon: 'clapperboard' },
|
||||
{ key: 'stories', icon: 'circle-dashed' },
|
||||
{ key: 'highlights', icon: 'star' },
|
||||
{ key: 'tagged', icon: 'square-user' },
|
||||
];
|
||||
|
||||
/** Labels under the name: «Tu», «Privato», «Pubblico», «Seguito», «Non seguito», «Solo archivio». */
|
||||
export function accountLabels(a) {
|
||||
if (a.isMine) return [label(t('account.etichette.tu'), 'accento')];
|
||||
if (a.state === 'archiveOnly') return [label(t('account.etichette.archivio'))];
|
||||
return [
|
||||
a.isPrivate ? label(t('account.etichette.privato'), '', 'lock') : label(t('account.etichette.pubblico')),
|
||||
a.isFollowed ? label(t('account.etichette.seguito')) : label(t('account.etichette.nonSeguito')),
|
||||
];
|
||||
}
|
||||
|
||||
/** True while the engine does not work (stopped, paused, not connected): «Prossimo» says «Sospeso». */
|
||||
function suspended() {
|
||||
const state = engineState();
|
||||
return Boolean(state && ['StoppedForVerification', 'Disconnected', 'NotConnected', 'Paused', 'Throttled', 'Off'].includes(state.snapshot.mode));
|
||||
}
|
||||
|
||||
/** Dot colour of an account state. */
|
||||
export function stateDot(state) {
|
||||
return { upToDate: 'verde', backfilling: 'accento', unreachable: 'ambra' }[state] || '';
|
||||
}
|
||||
|
||||
/** The second line of the state: news of today, history progress, why paused or unreachable. */
|
||||
export function stateLine(a) {
|
||||
switch (a.state) {
|
||||
case 'backfilling': {
|
||||
const text = a.postCount ? t('account.sotto.storico', { fatti: number(a.posts), totale: number(a.postCount) }) : t('account.sotto.storicoSenzaTotale', { fatti: number(a.posts) });
|
||||
return a.backfillResumesTomorrow ? t('account.sotto.riprendeDomani', { testo: text }) : text;
|
||||
}
|
||||
case 'paused':
|
||||
return a.stateChanged ? t('account.sotto.pausa', { giorno: shortDay(a.stateChanged.day, caps().today) }) : t('account.sotto.pausaSenzaData');
|
||||
case 'unreachable':
|
||||
return t(`account.sotto.${a.unreachableReason || 'privateNotFollowed'}`);
|
||||
case 'archiveOnly':
|
||||
return t('account.sotto.maiContattato');
|
||||
default: {
|
||||
if (a.notices.includes('renamed') && a.previousUsername) return t('account.sotto.rinominato', { nome: a.previousUsername });
|
||||
if (a.notices.includes('unrecognizedFormat')) return t('account.sotto.formato');
|
||||
if (a.newPostsToday && a.newStoriesToday) {
|
||||
return t('account.sotto.nuoviEntrambi', { post: t('account.sotto.post', { n: a.newPostsToday }), storie: t('account.sotto.storie', { n: a.newStoriesToday }) });
|
||||
}
|
||||
if (a.newPostsToday) return t('account.sotto.nuoviPost', { n: a.newPostsToday });
|
||||
if (a.newStoriesToday) return t('account.sotto.nuoveStorie', { n: a.newStoriesToday });
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** «Controlla ora» (spec §7.8): outside the active window Febe asks for a confirmation and then does that one check. */
|
||||
export async function checkNow(account, token = null) {
|
||||
try {
|
||||
const result = await api(`/api/accounts/${account.id}/check-now`, { method: 'POST', body: token ? { token } : {} });
|
||||
if (result.status === 'needsConfirmation') {
|
||||
const ok = await confirmDialog({
|
||||
title: t('account.controlla.titolo'),
|
||||
text: result.message,
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: false, kind: 'nudo' },
|
||||
{ label: t('account.controlla.conferma', { nome: account.username }), value: true, kind: 'primo', autofocus: true },
|
||||
],
|
||||
});
|
||||
if (ok) await checkNow(account, result.token);
|
||||
return;
|
||||
}
|
||||
toast(result.message, result.status === 'refused' ? 'errore' : '');
|
||||
refreshEngine();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** «Rimuovi»: always asks whether to keep or delete the files; keeping them (the default) makes it «Solo archivio». */
|
||||
export async function removeAccount(account) {
|
||||
let choice = 'tieni';
|
||||
const confirmButton = h('button.btn.primo', { type: 'button' }, t('account.rimuovi.confermaTieni'));
|
||||
const result = await dialog({
|
||||
title: t('account.rimuovi.titolo', { nome: account.username }),
|
||||
className: 'piccolo',
|
||||
build: (close) => {
|
||||
const set = (value) => {
|
||||
choice = value;
|
||||
confirmButton.className = value === 'elimina' ? 'btn pericolo pieno' : 'btn primo';
|
||||
confirmButton.textContent = t(value === 'elimina' ? 'account.rimuovi.confermaElimina' : 'account.rimuovi.confermaTieni');
|
||||
};
|
||||
confirmButton.addEventListener('click', () => close(choice));
|
||||
return {
|
||||
body: h('div.contenuto', h('p', t('account.rimuovi.testo')), h('div.scelte',
|
||||
radio({ name: 'rimuovi', value: 'tieni', checked: true, onchange: set, labelNode: h('span', h('b', t('account.rimuovi.tieni')), h('small', t('account.rimuovi.tieniSpiega'))) }),
|
||||
radio({ name: 'rimuovi', value: 'elimina', onchange: set, labelNode: h('span', h('b', t('account.rimuovi.elimina')), h('small', t('account.rimuovi.eliminaSpiega', { elementi: t('comune.elementi', { n: account.inLibrary }) }))) }))),
|
||||
footer: h('footer', h('div.destra', h('button.btn.nudo', { type: 'button', onclick: () => close(undefined) }, t('comune.annulla')), confirmButton)),
|
||||
};
|
||||
},
|
||||
});
|
||||
if (!result) return false;
|
||||
try {
|
||||
const answer = await api(`/api/accounts/${account.id}/remove`, { method: 'POST', body: { deleteFiles: result === 'elimina' } });
|
||||
toast(answer.message, answer.problems ? 'errore' : '');
|
||||
return answer.outcome;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The menu of a row (and of the account card). */
|
||||
export function accountMenu(anchor, account, after) {
|
||||
const items = [
|
||||
{ label: t('account.menu.controlla'), value: 'check', icon: 'refresh-cw', disabled: account.state === 'archiveOnly' || account.unreachableReason === 'privateNotFollowed' },
|
||||
account.state === 'paused'
|
||||
? { label: t('account.menu.riattiva'), value: 'resume', icon: 'play' }
|
||||
: { label: t('account.menu.pausa'), value: 'pause', icon: 'pause', disabled: account.state === 'archiveOnly' },
|
||||
{ label: t('account.menu.apri'), value: 'open', icon: 'external-link' },
|
||||
];
|
||||
if (!account.isMine) items.push('hr', { label: t('account.menu.rimuovi'), value: 'remove', icon: 'trash-2', danger: true });
|
||||
menu(anchor, items, async (value) => {
|
||||
try {
|
||||
if (value === 'check') await checkNow(account);
|
||||
if (value === 'pause' || value === 'resume') {
|
||||
const result = await api(`/api/accounts/${account.id}/${value}`, { method: 'POST' });
|
||||
toast(result.message);
|
||||
refreshEngine();
|
||||
}
|
||||
if (value === 'open') openProfile(account);
|
||||
if (value === 'remove') {
|
||||
const outcome = await removeAccount(account);
|
||||
if (outcome && after) after(outcome);
|
||||
return;
|
||||
}
|
||||
if (after) after(value);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}, { align: 'right' });
|
||||
}
|
||||
|
||||
/** The profile in Alberto's own browser. */
|
||||
export function openProfile(account) {
|
||||
const url = `https://www.instagram.com/${encodeURIComponent(account.username)}/`;
|
||||
if (caps().openUrlNative) api(`/api/accounts/${account.id}/open-on-instagram`, { method: 'POST' }).catch(showError);
|
||||
else window.open(url, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
|
||||
export default {
|
||||
async mount(page, route) {
|
||||
let data = null;
|
||||
let filter = FILTERS.includes(route.query.get('filtro')) ? route.query.get('filtro') : 'tutti';
|
||||
let sort = local.get('account.ordine', 'ultimo');
|
||||
if (!SORTS.includes(sort)) sort = 'ultimo';
|
||||
let term = '';
|
||||
|
||||
page.title(t('account.titolo'), '');
|
||||
const search = h('input', { type: 'search', placeholder: t('account.cerca'), 'aria-label': t('account.cerca') });
|
||||
const addButton = h('button.btn.primo', { type: 'button', onclick: () => add() }, icon('plus'), t('account.aggiungi'));
|
||||
page.actions(h('label.campo.cerca', { style: { width: '240px' } }, icon('search'), search), addButton);
|
||||
|
||||
const chips = h('div.filtri', { role: 'group', 'aria-label': t('account.colonne.stato') });
|
||||
const sortButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '240px' } });
|
||||
page.tools(h('div', { style: { display: 'contents' } }, chips, h('div.destra', sortButton)));
|
||||
const tbody = h('tbody');
|
||||
const table = h('div.pannello.tabella-account', h('table.tab',
|
||||
h('thead', h('tr',
|
||||
h('th', { scope: 'col' }, t('account.colonne.account')),
|
||||
h('th.col-raccoglie', { scope: 'col' }, t('account.colonne.raccoglie')),
|
||||
h('th.col-stato', { scope: 'col' }, t('account.colonne.stato')),
|
||||
h('th.col-ultimo', { scope: 'col' }, t('account.colonne.ultimo')),
|
||||
h('th.col-prossimo', { scope: 'col' }, t('account.colonne.prossimo')),
|
||||
h('th.col-libreria.num', { scope: 'col' }, t('account.colonne.libreria')),
|
||||
h('th.col-tieni', { scope: 'col' }, t('account.colonne.tieni')),
|
||||
h('th', { scope: 'col' }, h('span.vh', t('account.colonne.azioni'))))),
|
||||
tbody));
|
||||
fill(page.body, table);
|
||||
|
||||
function drawChips() {
|
||||
const counts = data.counts;
|
||||
const value = { tutti: counts.all, upToDate: counts.upToDate, backfilling: counts.backfilling, paused: counts.paused, archiveOnly: counts.archiveOnly, needsAttention: counts.needsAttention };
|
||||
fill(chips, FILTERS.map((f) => h(`button${f === filter ? '.qui' : ''}`, {
|
||||
type: 'button', 'aria-pressed': String(f === filter),
|
||||
onclick: () => {
|
||||
filter = f;
|
||||
setQuery({ filtro: f === 'tutti' ? null : f });
|
||||
draw();
|
||||
},
|
||||
}, t(`account.filtri.${f}`), h('i', number(value[f])))));
|
||||
fill(sortButton, h('span.val', t(`account.ordina.${sort}`)), icon('chevron-down', 's'));
|
||||
}
|
||||
|
||||
function sorted(list) {
|
||||
const by = {
|
||||
ultimo: (a, b) => (b.lastCheck || 0) - (a.lastCheck || 0),
|
||||
prossimo: (a, b) => (a.nextCheck ? a.nextCheck.ms : Infinity) - (b.nextCheck ? b.nextCheck.ms : Infinity),
|
||||
nome: (a, b) => a.username.localeCompare(b.username),
|
||||
libreria: (a, b) => b.inLibrary - a.inLibrary,
|
||||
aggiunta: (a, b) => b.addedAt - a.addedAt,
|
||||
}[sort];
|
||||
return [...list].sort((a, b) => (b.isMine - a.isMine) || by(a, b) || a.username.localeCompare(b.username));
|
||||
}
|
||||
|
||||
function visible() {
|
||||
const q = term.toLowerCase().replace(/^@/, '');
|
||||
return sorted(data.accounts.filter((a) => {
|
||||
if (filter === 'needsAttention' ? !a.needsAttention : filter !== 'tutti' && a.state !== filter) return false;
|
||||
return !q || a.username.includes(q) || (a.displayName || '').toLowerCase().includes(q);
|
||||
}));
|
||||
}
|
||||
|
||||
function rowOf(a) {
|
||||
const types = TYPES.map((x) => {
|
||||
const on = a.types[x.key];
|
||||
const name = t(`account.raccoglie.${x.key}`);
|
||||
const svg = icon(x.icon, 's');
|
||||
if (!on) svg.classList.add('spento');
|
||||
return h('span', { title: t(on ? 'account.raccoglie.attivo' : 'account.raccoglie.spento', { tipo: name }), role: 'img', 'aria-label': t(on ? 'account.raccoglie.attivo' : 'account.raccoglie.spento', { tipo: name }) }, svg);
|
||||
});
|
||||
const line = stateLine(a);
|
||||
const progress = a.state === 'backfilling' && a.postCount
|
||||
? h('div.misura.fine', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': String(a.postCount), 'aria-valuenow': String(a.posts), 'aria-label': t('account.stati.backfilling') },
|
||||
h('i', { style: { width: `${Math.min(100, (a.posts / a.postCount) * 100)}%` } }))
|
||||
: null;
|
||||
const sw = toggle({
|
||||
checked: a.keptUpdated,
|
||||
label: t('account.tieniEtichetta', { nome: a.username }),
|
||||
hiddenLabel: true,
|
||||
disabled: a.state === 'archiveOnly',
|
||||
onchange: async (value, input) => {
|
||||
try {
|
||||
const result = await api(`/api/accounts/${a.id}/keep-updated`, { method: 'POST', body: { value } });
|
||||
toast(result.message);
|
||||
await reload();
|
||||
refreshEngine();
|
||||
} catch (error) {
|
||||
input.checked = !value;
|
||||
showError(error);
|
||||
}
|
||||
},
|
||||
});
|
||||
if (a.state === 'archiveOnly') sw.querySelector('.int').classList.add('fermo');
|
||||
const more = h('button.btn.nudo.solo', { type: 'button', 'aria-label': `${t('comune.menu')}: @${a.username}`, 'aria-haspopup': 'true' }, icon('ellipsis'));
|
||||
more.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
accountMenu(more, a, () => reload());
|
||||
});
|
||||
const href = withCarried(`/account/${a.id}`);
|
||||
const tr = h('tr', { dataset: { id: String(a.id) } },
|
||||
h('td', h('div.nome', avatar(a.username, '', a.avatar), h('div',
|
||||
h('b', h('a', { href, style: { color: 'inherit', textDecoration: 'none' } }, `@${a.username}`)),
|
||||
h('div.sotto', a.isMine ? t('account.sotto.tuo') : a.displayName, accountLabels(a))))),
|
||||
h('td.col-raccoglie', h('div.raccoglie', types)),
|
||||
h('td.col-stato', h('div.condizione', h('div.riga', h(`span.spia${stateDot(a.state) ? '.' + stateDot(a.state) : ''}`, { 'aria-hidden': 'true' }), t(`account.stati.${a.state}`)),
|
||||
line ? h('div.sotto', line) : null, progress)),
|
||||
h('td.col-ultimo.dati.muto-cella', a.lastCheck ? ago(a.lastCheck, serverNow(), caps().today) : ''),
|
||||
h('td.col-prossimo.dati.muto-cella', a.nextCheck ? (suspended() ? t('account.sospeso') : around(a.nextCheck)) : ''),
|
||||
h('td.col-libreria.num.dati', number(a.inLibrary)),
|
||||
h('td.col-tieni', sw),
|
||||
h('td.menu-riga', more));
|
||||
tr.addEventListener('click', (e) => {
|
||||
if (e.target.closest('a,button,label,input')) return;
|
||||
navigate(`/account/${a.id}`);
|
||||
});
|
||||
return tr;
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (!data) return;
|
||||
page.count(t('account.quanti', { account: t('comune.account', { n: data.counts.all }), tenuti: number(data.counts.keptUpdated) }));
|
||||
drawChips();
|
||||
const rows = visible();
|
||||
if (!data.accounts.length) {
|
||||
fill(page.body, h('div.vuoto-pagina', icon('users'), h('h2', t('account.vuoto')), h('p', t('account.vuotoTesto')),
|
||||
h('button.btn.primo', { type: 'button', onclick: () => add() }, icon('plus'), t('account.aggiungi'))));
|
||||
return;
|
||||
}
|
||||
if (!table.isConnected) fill(page.body, table);
|
||||
fill(tbody, rows.length ? rows.map(rowOf) : h('tr', h('td', { colspan: '8' }, h('div.caricamento', t('account.nessunoFiltro')))));
|
||||
}
|
||||
|
||||
let loadedAt = 0;
|
||||
async function reload() {
|
||||
loadedAt = Date.now();
|
||||
try {
|
||||
data = await api('/api/accounts', { signal: page.signal });
|
||||
draw();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function add() {
|
||||
const added = await openAddAccounts();
|
||||
setQuery({ dialogo: null });
|
||||
if (added) await reload();
|
||||
}
|
||||
|
||||
sortButton.addEventListener('click', () => menu(sortButton,
|
||||
SORTS.map((s) => ({ label: t(`account.ordina.${s}`), value: s, checked: s === sort, radio: true })),
|
||||
(value) => {
|
||||
sort = value;
|
||||
local.set('account.ordine', sort);
|
||||
draw();
|
||||
}, { align: 'right' }));
|
||||
const onSearch = later(() => {
|
||||
term = search.value.trim();
|
||||
draw();
|
||||
}, 150);
|
||||
search.addEventListener('input', onSearch);
|
||||
const onChange = later(reload, 600);
|
||||
page.onLibrary(onChange);
|
||||
page.onLeave(() => {
|
||||
onSearch.cancel();
|
||||
onChange.cancel();
|
||||
});
|
||||
// «Ultimo controllo» and «verso le» stay current: the engine pushes its state at least every minute.
|
||||
page.onEngine(() => {
|
||||
if (Date.now() - loadedAt > 55000) reload();
|
||||
});
|
||||
|
||||
await reload();
|
||||
if (route.query.get('dialogo') === 'aggiungi') add();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,233 @@
|
||||
// «Aggiungi account» (mockup 04, spec §4.2): from the local copy of the list of followed profiles (with its reading
|
||||
// date and progress; it is read again only on request) or by user name, one per line; the three starting points on
|
||||
// the right; the button says how many accounts it adds.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill, later } from '../core/dom.js';
|
||||
import { t, number, shortDay } from '../core/text.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { avatar, checkbox, dialog, label, showError, toast } from '../core/ui.js';
|
||||
|
||||
const STARTS = ['everything', 'newOnly', 'storiesOnly'];
|
||||
const DEPTHS = [
|
||||
{ key: 'all', depth: 'all' },
|
||||
{ key: 'last50', depth: 'lastPosts', lastPosts: 50 },
|
||||
{ key: 'last200', depth: 'lastPosts', lastPosts: 200 },
|
||||
{ key: 'last1000', depth: 'lastPosts', lastPosts: 1000 },
|
||||
{ key: 'year', depth: 'fromDate' },
|
||||
];
|
||||
|
||||
/** Opens the dialog; resolves to true when accounts were added. */
|
||||
export function openAddAccounts() {
|
||||
return dialog({
|
||||
title: t('aggiungi.titolo'),
|
||||
className: 'aggiungi',
|
||||
build: (close) => build(close),
|
||||
});
|
||||
}
|
||||
|
||||
function build(close) {
|
||||
let tab = 'seguiti';
|
||||
let following = null;
|
||||
let parsed = { names: [], problems: [] };
|
||||
const chosen = new Set();
|
||||
let start = 'everything';
|
||||
let depth = 'all';
|
||||
|
||||
const tabFollowed = h('button', { type: 'button', role: 'tab', class: 'qui', 'aria-selected': 'true' }, t('aggiungi.seguiti'), h('i'));
|
||||
const tabNames = h('button', { type: 'button', role: 'tab', 'aria-selected': 'false' }, t('aggiungi.perNome'));
|
||||
const tabs = h('div.linguette', { role: 'tablist' }, tabFollowed, tabNames);
|
||||
const left = h('div.sinistra', { role: 'tabpanel' });
|
||||
const right = h('div.destra-dialogo');
|
||||
const footerLeft = h('div', { style: { display: 'flex', alignItems: 'center', gap: '12px', fontSize: '13px', color: 'var(--testo-2)' } });
|
||||
const addButton = h('button.btn.primo', { type: 'button', disabled: true, onclick: submit });
|
||||
|
||||
// ---------------------------------------------------------------------------- left: followed profiles
|
||||
const search = h('input', { type: 'search', placeholder: t('aggiungi.cerca'), 'aria-label': t('aggiungi.cerca') });
|
||||
const allButton = h('button.btn', { type: 'button' }, t('aggiungi.selezionaTutti'));
|
||||
const list = h('div.elenco', { role: 'group', 'aria-label': t('aggiungi.seguiti') });
|
||||
const progress = h('div.avanzamento', { role: 'status' });
|
||||
const followedPanel = h('div', { style: { display: 'contents' } }, h('div.cerca-riga', h('label.campo', icon('search'), search), allButton), list, progress);
|
||||
|
||||
// ---------------------------------------------------------------------------- left: by user name
|
||||
const area = h('textarea', { rows: '8', spellcheck: 'false', autocapitalize: 'off', 'aria-describedby': 'aiuto-nomi', placeholder: 'marta.demo\n@luca.viaggi.demo\ninstagram.com/studio.lumen.demo' });
|
||||
const parsedInfo = h('div.riconosciuti', { role: 'status' });
|
||||
const problems = h('div.problemi');
|
||||
const namesPanel = h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px', paddingBottom: '14px', overflow: 'auto' } },
|
||||
h('label.etichetta', t('aggiungi.area')),
|
||||
h('label.campo.area', area),
|
||||
h('p.aiuto', { id: 'aiuto-nomi' }, t('aggiungi.areaAiuto')),
|
||||
parsedInfo, problems);
|
||||
|
||||
function present(p) {
|
||||
return p.accountId != null;
|
||||
}
|
||||
|
||||
function drawList() {
|
||||
if (!following) {
|
||||
fill(list, h('div.caricamento', t('comune.caricamento')));
|
||||
return;
|
||||
}
|
||||
const term = search.value.trim().toLowerCase().replace(/^@/, '');
|
||||
const shown = following.profiles.filter((p) => !term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term));
|
||||
if (!shown.length) {
|
||||
fill(list, h('div.caricamento', following.profiles.length ? t('aggiungi.nessunSeguito') : t('aggiungi.maiLetto')));
|
||||
return;
|
||||
}
|
||||
fill(list, shown.map((p) => {
|
||||
const isPresent = present(p);
|
||||
const box = checkbox({
|
||||
checked: isPresent || chosen.has(p.username),
|
||||
disabled: isPresent,
|
||||
labelNode: h('span', { style: { display: 'contents' } },
|
||||
avatar(p.username, 'm'),
|
||||
h('span.chi-nome', h('b', `@${p.username}`), p.displayName ? h('small', p.displayName) : null),
|
||||
isPresent ? label(t('aggiungi.giaPresente')) : p.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
|
||||
onchange: (on) => {
|
||||
if (on) chosen.add(p.username);
|
||||
else chosen.delete(p.username);
|
||||
drawRight();
|
||||
},
|
||||
});
|
||||
box.classList.toggle('presente', isPresent);
|
||||
return box;
|
||||
}));
|
||||
}
|
||||
|
||||
function drawProgress() {
|
||||
if (!following) return;
|
||||
progress.hidden = !following.inProgress;
|
||||
fill(progress, following.inProgress
|
||||
? [icon('hourglass', 's'), following.readSoFar ? t('aggiungi.avanzamento', { n: number(following.readSoFar) }) : t('aggiungi.inAttesa')]
|
||||
: []);
|
||||
fill(footerLeft,
|
||||
h('span', following.readDay ? t('aggiungi.lettoIl', { giorno: shortDay(following.readDay, caps().today) }) : t('aggiungi.maiLetto')),
|
||||
h('button.btn.collegamento', { type: 'button', disabled: following.inProgress, onclick: reread, title: t('aggiungi.rilettura') },
|
||||
icon('refresh-cw', 's'), following.readDay ? t('aggiungi.rileggi') : t('aggiungi.leggi')));
|
||||
const count = tabFollowed.querySelector('i');
|
||||
count.textContent = number(following.total);
|
||||
}
|
||||
|
||||
async function loadFollowing() {
|
||||
try {
|
||||
following = await api('/api/following');
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
following = { profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 };
|
||||
}
|
||||
drawList();
|
||||
drawProgress();
|
||||
drawRight();
|
||||
}
|
||||
|
||||
async function reread() {
|
||||
try {
|
||||
following = await api('/api/following/read', { method: 'POST' });
|
||||
drawProgress();
|
||||
drawList();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
allButton.addEventListener('click', () => {
|
||||
if (!following) return;
|
||||
const term = search.value.trim().toLowerCase().replace(/^@/, '');
|
||||
const shown = following.profiles.filter((p) => !present(p) && (!term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term)));
|
||||
const all = shown.every((p) => chosen.has(p.username));
|
||||
for (const p of shown) {
|
||||
if (all) chosen.delete(p.username);
|
||||
else chosen.add(p.username);
|
||||
}
|
||||
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
|
||||
drawList();
|
||||
drawRight();
|
||||
});
|
||||
search.addEventListener('input', later(drawList, 120));
|
||||
|
||||
const parse = later(async () => {
|
||||
try {
|
||||
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text: area.value } });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
}
|
||||
const ready = parsed.names.filter((n) => !n.present);
|
||||
const already = parsed.names.length - ready.length;
|
||||
fill(parsedInfo, area.value.trim() ? [t('aggiungi.riconosciuti', { n: ready.length }), already ? ` · ${t('aggiungi.presenti', { n: already })}` : ''] : '');
|
||||
fill(problems, parsed.problems.map((p) => h('div', t('aggiungi.riga', { n: p.line, motivo: `«${p.text}»: ${p.reason}` }))));
|
||||
drawRight();
|
||||
}, 250);
|
||||
area.addEventListener('input', parse);
|
||||
|
||||
// ---------------------------------------------------------------------------- right: starting point
|
||||
function selection() {
|
||||
return tab === 'seguiti' ? [...chosen] : parsed.names.filter((n) => !n.present).map((n) => n.username);
|
||||
}
|
||||
|
||||
function drawRight() {
|
||||
const n = selection().length;
|
||||
const perDay = following && following.backfillPerDay ? following.backfillPerDay : 300;
|
||||
const startInputs = STARTS.map((s) => {
|
||||
const input = h('input.vh', { type: 'radio', name: 'partenza', value: s, checked: s === start });
|
||||
input.addEventListener('change', () => {
|
||||
start = s;
|
||||
drawRight();
|
||||
});
|
||||
return h('label', input, h('span.tondo', { 'aria-hidden': 'true' }),
|
||||
h('span', h('b', t(`aggiungi.partenze.${s}`)), h('small', t(`aggiungi.partenze.${s}Spiega`))));
|
||||
});
|
||||
const select = h('select', { 'aria-label': t('aggiungi.quanto') }, DEPTHS.map((d) => h('option', { value: d.key, selected: d.key === depth }, t(`aggiungi.profondita.${d.key}`))));
|
||||
select.addEventListener('change', () => {
|
||||
depth = select.value;
|
||||
});
|
||||
fill(right,
|
||||
h('h2.sez', n ? t('aggiungi.perScelti', { n }) : t('aggiungi.perNessuno')),
|
||||
h('p.aiuto', t('aggiungi.potraiCambiare')),
|
||||
h('div.partenza', { role: 'radiogroup', 'aria-label': t('aggiungi.potraiCambiare') }, startInputs),
|
||||
start === 'everything' ? [h('label.etichetta', { for: 'profondita' }, t('aggiungi.quanto')), h('label.campo.scelta', select, icon('chevron-down', 's'))] : null,
|
||||
h('div.avviso', { style: { marginTop: '14px' } }, icon('info', 's'),
|
||||
h('span', start === 'everything' ? t('aggiungi.info', { n: number(perDay) }) : t('aggiungi.infoNovita'))));
|
||||
select.id = 'profondita';
|
||||
addButton.disabled = n === 0;
|
||||
addButton.textContent = t('aggiungi.conferma', { n });
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const usernames = selection();
|
||||
if (!usernames.length) return;
|
||||
const d = DEPTHS.find((x) => x.key === depth) || DEPTHS[0];
|
||||
addButton.disabled = true;
|
||||
try {
|
||||
const result = await api('/api/accounts', { method: 'POST', body: { usernames, start, depth: start === 'everything' ? d.depth : null, lastPosts: d.lastPosts || null } });
|
||||
toast(result.message);
|
||||
close(result.added > 0);
|
||||
} catch (error) {
|
||||
addButton.disabled = false;
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function setTab(value) {
|
||||
tab = value;
|
||||
tabFollowed.classList.toggle('qui', value === 'seguiti');
|
||||
tabNames.classList.toggle('qui', value === 'nomi');
|
||||
tabFollowed.setAttribute('aria-selected', String(value === 'seguiti'));
|
||||
tabNames.setAttribute('aria-selected', String(value === 'nomi'));
|
||||
fill(left, value === 'seguiti' ? followedPanel : namesPanel);
|
||||
footerLeft.hidden = value !== 'seguiti';
|
||||
drawRight();
|
||||
(value === 'seguiti' ? search : area).focus();
|
||||
}
|
||||
tabFollowed.addEventListener('click', () => setTab('seguiti'));
|
||||
tabNames.addEventListener('click', () => setTab('nomi'));
|
||||
|
||||
fill(left, followedPanel);
|
||||
drawList();
|
||||
drawRight();
|
||||
loadFollowing();
|
||||
return {
|
||||
body: h('div', { style: { display: 'contents' } }, tabs, h('div.corpo-dialogo', left, right)),
|
||||
footer: h('footer', footerLeft, h('div.destra', h('button.btn', { type: 'button', onclick: () => close(false) }, t('comune.annulla')), addButton)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
// 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 { 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 { Mosaic } from './mosaic.js';
|
||||
import { openViewer } from './viewer.js';
|
||||
|
||||
const KINDS = [
|
||||
{ key: 'tutto', api: 'all', label: 'libreria.tipi.all' },
|
||||
{ key: 'foto', api: 'photos', label: 'libreria.tipi.photos' },
|
||||
{ key: 'video', api: 'videos', label: 'libreria.tipi.videos' },
|
||||
{ key: 'storie', api: 'stories', label: 'libreria.tipi.stories' },
|
||||
{ key: 'evidenza', api: 'highlights', label: 'libreria.tipi.highlights' },
|
||||
{ key: 'taggati', api: 'tagged', label: 'libreria.tipi.tagged' },
|
||||
];
|
||||
|
||||
const PERIODS = ['settimana', 'mese', 'anno', 'annoScorso'];
|
||||
|
||||
/** The filter of the page address (Italian names) as the query of the API. */
|
||||
export function apiQuery(state, today) {
|
||||
const q = new URLSearchParams();
|
||||
const kind = KINDS.find((k) => k.key === state.tipo);
|
||||
if (kind && kind.api !== 'all') q.set('kind', kind.api);
|
||||
if (state.account) q.set('accounts', state.account);
|
||||
const range = periodRange(state, today);
|
||||
if (range.from) q.set('from', range.from);
|
||||
if (range.to) q.set('to', range.to);
|
||||
if (state.provenienza === 'importati') q.set('provenance', 'imported');
|
||||
if (state.provenienza === 'scaricati') q.set('provenance', 'downloaded');
|
||||
if (state.q) q.set('q', state.q);
|
||||
return q.toString();
|
||||
}
|
||||
|
||||
function addDays(day, n) {
|
||||
return new Date(Date.parse(`${day}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function periodRange(state, today) {
|
||||
if (state.dal || state.al) return { from: state.dal || null, to: state.al || null };
|
||||
const year = today ? parseDay(today).y : new Date().getFullYear();
|
||||
switch (state.periodo) {
|
||||
case 'settimana': return { from: addDays(today, -6), to: today };
|
||||
case 'mese': return { from: addDays(today, -29), to: today };
|
||||
case 'anno': return { from: `${year}-01-01`, to: today };
|
||||
case 'annoScorso': return { from: `${year - 1}-01-01`, to: `${year - 1}-12-31` };
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
function readState(query) {
|
||||
return {
|
||||
tipo: query.get('tipo') || 'tutto',
|
||||
account: query.get('account') || '',
|
||||
periodo: query.get('periodo') || '',
|
||||
dal: query.get('dal') || '',
|
||||
al: query.get('al') || '',
|
||||
provenienza: query.get('provenienza') || '',
|
||||
q: query.get('q') || '',
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
async mount(page, route) {
|
||||
const state = readState(route.query);
|
||||
const today = () => caps().today || new Date().toISOString().slice(0, 10);
|
||||
let accounts = null;
|
||||
let mosaic = null;
|
||||
|
||||
page.title(t('libreria.titolo'), '');
|
||||
const search = h('input', { type: 'search', placeholder: t('libreria.cerca'), 'aria-label': t('libreria.cerca'), value: state.q });
|
||||
// In a narrow window the field is short: the placeholder becomes «Cerca» (the accessible name stays complete).
|
||||
const narrow = window.matchMedia('(max-width: 1000px)');
|
||||
const placeholder = () => { search.placeholder = t(narrow.matches ? 'libreria.cercaBreve' : 'libreria.cerca'); };
|
||||
placeholder();
|
||||
narrow.addEventListener('change', placeholder, { signal: page.signal });
|
||||
page.actions(h('label.campo.cerca', icon('search'), search));
|
||||
|
||||
// Tools: kind chips, the three menus, tile size, selection.
|
||||
const chips = h('div.filtri', { role: 'group', 'aria-label': t('libreria.filtriTipo') });
|
||||
const accountButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '118px' } });
|
||||
const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '111px' } });
|
||||
const provenanceButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '141px' } });
|
||||
const filtersButton = h('button.btn.solo-stretto', { type: 'button', 'aria-haspopup': 'true' }, icon('list-filter'), t('libreria.filtri'));
|
||||
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')));
|
||||
page.tools(h('div', { style: { display: 'contents' } },
|
||||
chips,
|
||||
h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton),
|
||||
filtersButton,
|
||||
h('div.destra',
|
||||
h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')),
|
||||
selectButton)));
|
||||
|
||||
const host = h('div');
|
||||
fill(page.body, host);
|
||||
|
||||
function filtersActive() {
|
||||
return state.tipo !== 'tutto' || state.account || state.periodo || state.dal || state.al || state.provenienza || state.q;
|
||||
}
|
||||
|
||||
function drawChips() {
|
||||
fill(chips, KINDS.map((k) => h(`button${k.key === state.tipo ? '.qui' : ''}`, {
|
||||
type: 'button',
|
||||
'aria-pressed': String(k.key === state.tipo),
|
||||
onclick: () => {
|
||||
state.tipo = k.key;
|
||||
apply();
|
||||
},
|
||||
}, t(k.label))));
|
||||
}
|
||||
|
||||
function menuLabel(button, text, chosen) {
|
||||
fill(button, h('span.val', text), icon('chevron-down', 's'));
|
||||
button.classList.toggle('attivo', Boolean(chosen));
|
||||
}
|
||||
|
||||
function drawMenus() {
|
||||
// A menu shows the name of its filter until a value is chosen (spec §10.3).
|
||||
const ids = state.account ? state.account.split(',') : [];
|
||||
let accountText = t('libreria.menuAccount');
|
||||
if (ids.length === 1 && accounts) {
|
||||
const a = accounts.find((x) => String(x.id) === ids[0]);
|
||||
accountText = a ? `@${a.username}` : t('libreria.accountScelti', { n: 1 });
|
||||
} else if (ids.length) accountText = t('libreria.accountScelti', { n: ids.length });
|
||||
menuLabel(accountButton, accountText, ids.length);
|
||||
let periodText = t('libreria.menuPeriodo');
|
||||
if (state.dal || state.al) periodText = t('libreria.periodi.date', { dal: state.dal ? shortDay(state.dal, today()) : '…', al: state.al ? shortDay(state.al, today()) : '…' });
|
||||
else if (state.periodo) periodText = t(`libreria.periodi.${state.periodo}`);
|
||||
menuLabel(periodButton, periodText, state.periodo || state.dal || state.al);
|
||||
menuLabel(provenanceButton, state.provenienza ? t(`libreria.provenienze.${state.provenienza === 'importati' ? 'imported' : 'downloaded'}`) : t('libreria.menuProvenienza'), state.provenienza);
|
||||
filtersButton.classList.toggle('primo', Boolean(state.account || state.periodo || state.dal || state.al || state.provenienza));
|
||||
}
|
||||
|
||||
async function loadAccounts() {
|
||||
if (!accounts) accounts = (await api('/api/accounts', { signal: page.signal })).accounts;
|
||||
return accounts;
|
||||
}
|
||||
|
||||
async function openAccounts(anchor) {
|
||||
try {
|
||||
await loadAccounts();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
}
|
||||
const chosen = new Set(state.account ? state.account.split(',') : []);
|
||||
const field = h('input', { type: 'search', placeholder: t('libreria.cercaAccount'), 'aria-label': t('libreria.cercaAccount') });
|
||||
const list = h('div');
|
||||
const header = h('div.cerca-menu', h('label.campo', icon('search', 's'), field));
|
||||
const drawList = () => {
|
||||
const term = field.value.trim().toLowerCase().replace(/^@/, '');
|
||||
const items = [
|
||||
h('button', { type: 'button', role: 'menuitemcheckbox', 'aria-checked': String(chosen.size === 0), onclick: () => { chosen.clear(); commit(); } },
|
||||
h('span', t('libreria.tuttiGliAccount')), icon('check', 's segno')),
|
||||
h('hr'),
|
||||
];
|
||||
const shown = accounts.filter((a) => !term || a.username.includes(term) || (a.displayName || '').toLowerCase().includes(term));
|
||||
for (const a of shown) {
|
||||
items.push(h('button', {
|
||||
type: 'button', role: 'menuitemcheckbox', 'aria-checked': String(chosen.has(String(a.id))),
|
||||
onclick: (e) => {
|
||||
const id = String(a.id);
|
||||
if (chosen.has(id)) chosen.delete(id);
|
||||
else chosen.add(id);
|
||||
e.currentTarget.setAttribute('aria-checked', String(chosen.has(id)));
|
||||
commit(false);
|
||||
},
|
||||
}, h('span', `@${a.username}`), icon('check', 's segno')));
|
||||
}
|
||||
if (!shown.length) items.push(h('div.vuoto', t('libreria.nessunAccount')));
|
||||
fill(list, items);
|
||||
};
|
||||
const commit = (close = true) => {
|
||||
state.account = [...chosen].join(',');
|
||||
if (close) handle.close();
|
||||
apply();
|
||||
};
|
||||
field.addEventListener('input', drawList);
|
||||
drawList();
|
||||
const handle = menu(anchor, [header, list], () => {}, { width: 280 });
|
||||
}
|
||||
|
||||
function openPeriod(anchor) {
|
||||
const from = h('input', { type: 'date', value: state.dal, 'aria-label': t('libreria.periodi.dal'), max: today() });
|
||||
const to = h('input', { type: 'date', value: state.al, 'aria-label': t('libreria.periodi.al'), max: today() });
|
||||
const items = [
|
||||
{ label: t('libreria.periodi.qualsiasi'), value: '', checked: !state.periodo && !state.dal && !state.al, radio: true },
|
||||
...PERIODS.map((p) => ({ label: t(`libreria.periodi.${p}`), value: p, checked: state.periodo === p, radio: true })),
|
||||
'hr',
|
||||
h('div.date', h('span', t('libreria.periodi.dal')), h('label.campo', from), h('span', t('libreria.periodi.al')), h('label.campo', to)),
|
||||
h('div', { style: { padding: '2px 6px 4px' } }, h('button.btn.piccolo', {
|
||||
type: 'button',
|
||||
onclick: () => {
|
||||
state.periodo = '';
|
||||
state.dal = from.value;
|
||||
state.al = to.value;
|
||||
handle.close();
|
||||
apply();
|
||||
},
|
||||
}, t('libreria.periodi.applica'))),
|
||||
];
|
||||
const handle = menu(anchor, items, (value) => {
|
||||
state.periodo = value;
|
||||
state.dal = '';
|
||||
state.al = '';
|
||||
apply();
|
||||
}, { width: 300 });
|
||||
}
|
||||
|
||||
function openProvenance(anchor) {
|
||||
menu(anchor, [
|
||||
{ label: t('libreria.provenienze.tutte'), value: '', checked: !state.provenienza, radio: true },
|
||||
{ label: t('libreria.provenienze.downloaded'), value: 'scaricati', checked: state.provenienza === 'scaricati', radio: true },
|
||||
{ label: t('libreria.provenienze.imported'), value: 'importati', checked: state.provenienza === 'importati', radio: true },
|
||||
], (value) => {
|
||||
state.provenienza = value;
|
||||
apply();
|
||||
});
|
||||
}
|
||||
|
||||
function openFilters(anchor) {
|
||||
// Narrow window: the three menus behind one button.
|
||||
menu(anchor, [
|
||||
{ label: accountButton.textContent, value: 'account', icon: 'users' },
|
||||
{ label: periodButton.textContent, value: 'periodo', icon: 'calendar' },
|
||||
{ label: provenanceButton.textContent, value: 'provenienza', icon: 'folder-input' },
|
||||
], (value) => {
|
||||
if (value === 'account') openAccounts(anchor);
|
||||
if (value === 'periodo') openPeriod(anchor);
|
||||
if (value === 'provenienza') openProvenance(anchor);
|
||||
});
|
||||
}
|
||||
|
||||
accountButton.addEventListener('click', () => openAccounts(accountButton));
|
||||
periodButton.addEventListener('click', () => openPeriod(periodButton));
|
||||
provenanceButton.addEventListener('click', () => openProvenance(provenanceButton));
|
||||
filtersButton.addEventListener('click', () => openFilters(filtersButton));
|
||||
slider.addEventListener('input', () => {
|
||||
const value = Number(slider.value);
|
||||
local.set('libreria.tessere', value);
|
||||
if (mosaic) mosaic.setRowHeight(value);
|
||||
});
|
||||
const onSearch = later(() => {
|
||||
state.q = search.value.trim();
|
||||
apply();
|
||||
}, 300);
|
||||
search.addEventListener('input', onSearch);
|
||||
page.onLeave(() => onSearch.cancel());
|
||||
|
||||
// Selection bar.
|
||||
function drawSelection(selected) {
|
||||
if (!mosaic || !mosaic.selecting) {
|
||||
page.saveBar(null);
|
||||
return;
|
||||
}
|
||||
const n = selected.size;
|
||||
page.saveBar(h('div', { style: { display: 'contents' } },
|
||||
h('span.nota', n ? t('selezione.scelti', { n }) : t('selezione.nessuno')),
|
||||
h('div.destra',
|
||||
h('button.btn.nudo', { type: 'button', onclick: () => setSelecting(false) }, t('selezione.annulla')),
|
||||
h('button.btn', { type: 'button', disabled: !n, onclick: () => exportSelected() }, icon('file-down'), t('selezione.esporta')),
|
||||
h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: () => deleteSelected() }, icon('trash-2'), t('selezione.elimina', { n })))));
|
||||
}
|
||||
|
||||
function setSelecting(on) {
|
||||
if (!mosaic) return;
|
||||
mosaic.setSelecting(on);
|
||||
selectButton.setAttribute('aria-pressed', String(on));
|
||||
fill(selectButton, icon(on ? 'check' : 'circle-check'), h('span', t(on ? 'libreria.fine' : 'libreria.seleziona')));
|
||||
drawSelection(mosaic.selected);
|
||||
}
|
||||
|
||||
selectButton.addEventListener('click', () => setSelecting(!mosaic.selecting));
|
||||
|
||||
async function exportSelected() {
|
||||
try {
|
||||
await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv');
|
||||
toast(t('selezione.esportato'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSelected() {
|
||||
const ids = [...mosaic.selected];
|
||||
const removed = await confirmDelete(ids);
|
||||
if (removed) {
|
||||
mosaic.removeTiles(removed);
|
||||
setSelecting(false);
|
||||
}
|
||||
}
|
||||
|
||||
// The mosaic.
|
||||
async function apply() {
|
||||
setQuery({
|
||||
tipo: state.tipo === 'tutto' ? null : state.tipo,
|
||||
account: state.account || null,
|
||||
periodo: state.periodo || null,
|
||||
dal: state.dal || null,
|
||||
al: state.al || null,
|
||||
provenienza: state.provenienza || null,
|
||||
q: state.q || null,
|
||||
});
|
||||
drawChips();
|
||||
drawMenus();
|
||||
if (mosaic) mosaic.destroy();
|
||||
page.body.scrollTop = 0;
|
||||
mosaic = new Mosaic({
|
||||
scroller: page.body,
|
||||
host,
|
||||
query: apiQuery(state, today()),
|
||||
rowHeight: Number(slider.value),
|
||||
signal: page.signal,
|
||||
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }),
|
||||
onSelection: drawSelection,
|
||||
onTotals: ({ entries, accounts: n }) => page.count(t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })),
|
||||
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')))),
|
||||
});
|
||||
try {
|
||||
await mosaic.start();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
drawSelection(mosaic.selected);
|
||||
}
|
||||
|
||||
const onLibraryChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 400);
|
||||
page.onLibrary(onLibraryChange);
|
||||
page.onLeave(() => {
|
||||
onLibraryChange.cancel();
|
||||
if (mosaic) mosaic.destroy();
|
||||
});
|
||||
loadAccounts().then(drawMenus).catch(() => {});
|
||||
await apply();
|
||||
void number;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* «Elimina dalla libreria» with the confirmation of spec §4.6: by default the choice is remembered (state «eliminato»,
|
||||
* never downloaded again); «Eliminalo e lascia che torni» forgets the entry. Returns the deleted keys, or null.
|
||||
*/
|
||||
export async function confirmDelete(ids) {
|
||||
const n = ids.length;
|
||||
const mode = await confirmDialog({
|
||||
title: t('elimina.titolo', { n }),
|
||||
text: t('elimina.testo', { n }),
|
||||
extra: h('p.aiuto', t('elimina.tornaSpiega')),
|
||||
buttons: [
|
||||
{ label: t('comune.annulla'), value: undefined, kind: 'nudo' },
|
||||
{ label: t('elimina.torna', { n }), value: 'allowReturn' },
|
||||
{ label: t('elimina.conferma'), value: 'remember', kind: 'pericolo pieno', autofocus: true },
|
||||
],
|
||||
});
|
||||
if (!mode) return null;
|
||||
try {
|
||||
const result = await api('/api/entries/delete', { method: 'POST', body: { ids, mode } });
|
||||
toast(result.message, result.problems.length ? 'errore' : '');
|
||||
return ids;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
// The mosaic of the library (mockup 01) and of the account tabs (mockup 12): entries grouped by day, justified rows
|
||||
// that keep the proportions of the pictures with 4 px between tiles, or a regular 9:16 grid for stories.
|
||||
// Fluid with 200,000 entries: the page knows only how many entries each day has (one cheap query); a day group is
|
||||
// fetched (keyset windows) and drawn only when it comes near the visible area, and emptied again when it goes far,
|
||||
// keeping its height. Changes of height above the visible area are compensated, so nothing moves under the eyes.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill, perFrame } from '../core/dom.js';
|
||||
import { t, dayName, duration, capitalize } from '../core/text.js';
|
||||
import { avatar } from '../core/ui.js';
|
||||
|
||||
const GAP = 4;
|
||||
const NEAR = '1400px 0px';
|
||||
const FAR = '7000px 0px';
|
||||
|
||||
function aspectOf(tile) {
|
||||
const c = tile.cover;
|
||||
if (!c || !c.width || !c.height) return 1;
|
||||
return Math.min(2.2, Math.max(0.5, c.width / c.height));
|
||||
}
|
||||
|
||||
function older(a, b) {
|
||||
// true when tile a comes after tile b in display order (published earlier, or same time and smaller id)
|
||||
return a.publishedAt < b.publishedAt || (a.publishedAt === b.publishedAt && a.id < b.id);
|
||||
}
|
||||
|
||||
export function cursorOf(tile) {
|
||||
return `${tile.publishedAt}.${tile.id}`;
|
||||
}
|
||||
|
||||
/** Justified rows: every full row exactly fills the width; the last row keeps the target height. */
|
||||
export function justify(tiles, width, target) {
|
||||
const rows = [];
|
||||
let row = [];
|
||||
let sum = 0;
|
||||
for (const tile of tiles) {
|
||||
const ar = aspectOf(tile);
|
||||
row.push({ tile, ar });
|
||||
sum += ar;
|
||||
const full = sum * target + GAP * (row.length - 1);
|
||||
if (full >= width) {
|
||||
const withLast = (width - GAP * (row.length - 1)) / sum;
|
||||
const withoutLast = row.length > 1 ? (width - GAP * (row.length - 2)) / (sum - ar) : Infinity;
|
||||
if (row.length > 1 && Math.abs(withoutLast - target) < Math.abs(withLast - target) && withoutLast < target * 1.4) {
|
||||
const last = row.pop();
|
||||
rows.push({ items: row, height: withoutLast, full: true });
|
||||
row = [last];
|
||||
sum = last.ar;
|
||||
} else {
|
||||
rows.push({ items: row, height: withLast, full: true });
|
||||
row = [];
|
||||
sum = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (row.length) rows.push({ items: row, height: target, full: false });
|
||||
for (const r of rows) {
|
||||
let used = 0;
|
||||
r.items.forEach((item, i) => {
|
||||
item.width = Math.max(24, Math.round(item.ar * r.height));
|
||||
used += item.width + (i > 0 ? GAP : 0);
|
||||
});
|
||||
if (r.full && r.items.length) r.items[r.items.length - 1].width += width - used;
|
||||
r.height = Math.round(r.height);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** A tile: thumbnail, marks top-right, on hover account and time, selection circle. */
|
||||
export function tileElement(tile, width, height, { selected = false, today = '', ring = true } = {}) {
|
||||
const cover = tile.cover;
|
||||
const marks = [];
|
||||
if (tile.kind === 'story' && ring) marks.push(h('span.anello', { title: t('libreria.tipiTessera.story') }, icon('circle-dashed')));
|
||||
if (cover && cover.kind === 'video') marks.push(h('span', icon('play'), duration(cover.duration || 0)));
|
||||
if (tile.files > 1) marks.push(h('span', icon('layers'), String(tile.files)));
|
||||
const when = tile.day === today ? `${t('tempo.oggi')}, ${tile.time}` : `${dayName(tile.day, today)}, ${tile.time}`;
|
||||
const description = [t('libreria.tessera', { tipo: t(`libreria.tipiTessera.${tile.kind}`), account: tile.username, quando: when })];
|
||||
if (tile.files > 1) description.push(t('libreria.tesseraFile', { n: tile.files }));
|
||||
if (cover && cover.kind === 'video') description.push(t('libreria.tesseraDurata', { durata: duration(cover.duration || 0) }));
|
||||
const el = h(`button.tess${selected ? '.scelta' : ''}`, {
|
||||
type: 'button',
|
||||
style: { width: `${width}px`, height: `${height}px` },
|
||||
dataset: { id: String(tile.id) },
|
||||
'aria-label': description.join(', '),
|
||||
'aria-pressed': selected ? 'true' : null,
|
||||
},
|
||||
cover && cover.thumb
|
||||
? h('img', { src: `/api/thumbnails/${cover.thumb}`, alt: '', loading: 'lazy', decoding: 'async', draggable: 'false' })
|
||||
: h('span.tess.vuota', { style: { width: '100%', height: '100%' } }, icon('image')),
|
||||
marks.length ? h('span.segno', marks) : null,
|
||||
h('span.sel', { role: 'checkbox', 'aria-checked': String(selected), 'aria-label': t('libreria.scegliTessera'), title: t('libreria.scegliTessera') }, icon('check')),
|
||||
h('span.chi', avatar(tile.username, 'p'), h('span', `@${tile.username}`), h('small', tile.day === today ? `${t('tempo.oggi')}, ${tile.time}` : tile.time)));
|
||||
return el;
|
||||
}
|
||||
|
||||
/** The default day header: «Oggi martedì 13 ottobre, 14 nuovi elementi». */
|
||||
export function defaultDayLabel(day, count, today) {
|
||||
const name = dayName(day, today);
|
||||
if (day === today) return [t('tempo.Oggi'), t('libreria.giornoNuovi', { giorno: name, n: t('libreria.nuoviOggi', { n: count }) })];
|
||||
const yesterday = new Date(Date.parse(`${today}T12:00:00Z`) - 86400000).toISOString().slice(0, 10);
|
||||
if (day === yesterday) return [t('tempo.Ieri'), t('libreria.giornoNuovi', { giorno: name, n: t('libreria.elementiGiorno', { n: count }) })];
|
||||
return [capitalize(name), t('libreria.elementiGiorno', { n: count })];
|
||||
}
|
||||
|
||||
export class Mosaic {
|
||||
/**
|
||||
* scroller: the scrolling element (.corpo); host: where the groups go; query: filter as a query string;
|
||||
* mode: 'justified' or 'grid' (9:16 stories); rowHeight: target height of the rows;
|
||||
* onOpen(tile), onSelection(set), onTotals({ entries, accounts, today }), onEmpty(), dayLabel(day, count, today).
|
||||
*/
|
||||
constructor(options) {
|
||||
this.scroller = options.scroller;
|
||||
this.host = options.host;
|
||||
this.query = options.query || '';
|
||||
this.mode = options.mode || 'justified';
|
||||
this.rowHeight = options.rowHeight || 160;
|
||||
this.onOpen = options.onOpen || (() => {});
|
||||
this.onSelection = options.onSelection || (() => {});
|
||||
this.onTotals = options.onTotals || (() => {});
|
||||
this.onEmpty = options.onEmpty || (() => {});
|
||||
this.dayLabel = options.dayLabel || defaultDayLabel;
|
||||
this.signal = options.signal;
|
||||
this.sections = [];
|
||||
this.byDay = new Map();
|
||||
this.selected = new Set();
|
||||
this.selecting = false;
|
||||
this.today = '';
|
||||
this.avgAspect = this.mode === 'grid' ? 0.5625 : 0.95;
|
||||
this.width = 0;
|
||||
this.pendingNew = 0;
|
||||
this.root = h('div.mosaico');
|
||||
this.pill = h('div.nuovi-in-cima', { hidden: true });
|
||||
fill(this.host, this.pill, this.root);
|
||||
this.near = new IntersectionObserver((entries) => this.onNear(entries), { root: this.scroller, rootMargin: NEAR });
|
||||
this.far = new IntersectionObserver((entries) => this.onFar(entries), { root: this.scroller, rootMargin: FAR });
|
||||
this.resize = new ResizeObserver(perFrame(() => this.onResize()));
|
||||
this.resize.observe(this.root);
|
||||
this.root.addEventListener('click', (e) => this.onClick(e));
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.near.disconnect();
|
||||
this.far.disconnect();
|
||||
this.resize.disconnect();
|
||||
}
|
||||
|
||||
/** Loads the days of the filter and draws the groups that are visible. */
|
||||
async start() {
|
||||
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
|
||||
this.today = data.today;
|
||||
this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today });
|
||||
this.width = this.root.clientWidth || this.host.clientWidth || 800;
|
||||
for (const section of this.sections) this.unobserve(section);
|
||||
this.sections = [];
|
||||
this.byDay.clear();
|
||||
this.root.replaceChildren();
|
||||
for (const day of data.days) this.root.append(this.createSection(day).el);
|
||||
if (!data.days.length) this.onEmpty();
|
||||
}
|
||||
|
||||
createSection(day) {
|
||||
const section = { day: day.day, count: day.count, cursor: day.cursor, tiles: [], complete: false, loading: null, rendered: false, near: false, stale: false };
|
||||
const [bold, rest] = this.dayLabel(day.day, day.count, this.today);
|
||||
section.header = h('header.giorno', h('b', bold), rest ? h('span', rest) : null);
|
||||
section.rows = h('div.righe', { style: { height: `${this.estimate(day.count)}px` } });
|
||||
section.el = h('section.gruppo-giorno', { dataset: { day: day.day }, 'aria-label': `${bold} ${rest || ''}` }, section.header, section.rows);
|
||||
this.byDay.set(day.day, section);
|
||||
this.sections.push(section);
|
||||
this.near.observe(section.el);
|
||||
this.far.observe(section.el);
|
||||
return section;
|
||||
}
|
||||
|
||||
unobserve(section) {
|
||||
this.near.unobserve(section.el);
|
||||
this.far.unobserve(section.el);
|
||||
}
|
||||
|
||||
estimate(count) {
|
||||
const width = Math.max(200, this.width || 800);
|
||||
if (this.mode === 'grid') {
|
||||
const tileHeight = Math.round(this.rowHeight * 1.25);
|
||||
const perRow = Math.max(1, Math.floor((width + GAP) / (Math.round(tileHeight * 0.5625) + GAP)));
|
||||
return Math.ceil(count / perRow) * (tileHeight + GAP);
|
||||
}
|
||||
const rows = Math.max(1, Math.ceil((count * this.avgAspect * this.rowHeight) / width));
|
||||
return rows * (this.rowHeight * 0.96 + GAP);
|
||||
}
|
||||
|
||||
onNear(entries) {
|
||||
for (const entry of entries) {
|
||||
const section = this.sections.find((s) => s.el === entry.target);
|
||||
if (!section) continue;
|
||||
section.near = entry.isIntersecting;
|
||||
if (entry.isIntersecting) this.wake(section);
|
||||
}
|
||||
}
|
||||
|
||||
onFar(entries) {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) continue;
|
||||
const section = this.sections.find((s) => s.el === entry.target);
|
||||
if (section && section.rendered) this.unrender(section);
|
||||
}
|
||||
}
|
||||
|
||||
async wake(section) {
|
||||
try {
|
||||
while (!section.complete && section.near) await this.load(section);
|
||||
if (section.near && !section.rendered && section.el.isConnected) this.render(section);
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetches the next window from where a group is, and hands the tiles to every group they belong to. */
|
||||
load(section) {
|
||||
if (section.loading) return section.loading;
|
||||
const missing = section.count - section.tiles.length;
|
||||
const limit = Math.min(600, Math.max(120, missing + 40));
|
||||
const cursor = section.tiles.length ? cursorOf(section.tiles[section.tiles.length - 1]) : section.cursor;
|
||||
section.loading = api(`/api/library?${this.query}${this.query ? '&' : ''}cursor=${encodeURIComponent(cursor)}&limit=${limit}`, { signal: this.signal })
|
||||
.then((page) => {
|
||||
const touched = new Set();
|
||||
for (const tile of page.tiles) {
|
||||
const target = this.byDay.get(tile.day);
|
||||
if (!target || target.complete) continue;
|
||||
const last = target.tiles[target.tiles.length - 1];
|
||||
if (last && !older(tile, last)) continue;
|
||||
target.tiles.push(tile);
|
||||
touched.add(target);
|
||||
}
|
||||
if (!page.older) {
|
||||
const index = this.sections.indexOf(section);
|
||||
for (const s of this.sections.slice(index)) s.complete = true;
|
||||
}
|
||||
for (const s of touched) {
|
||||
if (s.tiles.length >= s.count) s.complete = true;
|
||||
this.learn(s.tiles);
|
||||
}
|
||||
if (!touched.has(section) && !section.complete) section.complete = true; // nothing more for this day
|
||||
for (const s of touched) if (s !== section && s.near && s.complete && !s.rendered) this.render(s);
|
||||
})
|
||||
.finally(() => {
|
||||
section.loading = null;
|
||||
});
|
||||
return section.loading;
|
||||
}
|
||||
|
||||
learn(tiles) {
|
||||
if (this.mode === 'grid' || !tiles.length) return;
|
||||
const sample = tiles.slice(0, 200);
|
||||
const mean = sample.reduce((a, tile) => a + aspectOf(tile), 0) / sample.length;
|
||||
this.avgAspect = this.avgAspect * 0.7 + mean * 0.3;
|
||||
}
|
||||
|
||||
/** Runs fn and keeps what is visible in place when a group above the visible area changes height. */
|
||||
keepView(section, fn) {
|
||||
const scrollerTop = this.scroller.getBoundingClientRect().top;
|
||||
const rect = section.el.getBoundingClientRect();
|
||||
const above = rect.bottom <= scrollerTop + 1;
|
||||
const before = section.el.offsetHeight;
|
||||
fn();
|
||||
const after = section.el.offsetHeight;
|
||||
if (above && after !== before) this.scroller.scrollTop += after - before;
|
||||
}
|
||||
|
||||
render(section) {
|
||||
const width = this.root.clientWidth || this.width;
|
||||
this.width = width;
|
||||
const rows = this.layout(section.tiles, width);
|
||||
const nodes = rows.map((row) => h(this.mode === 'grid' ? 'div.griglia-storie' : 'div.fila',
|
||||
row.items.map((item) => tileElement(item.tile, item.width, row.height, { selected: this.selected.has(item.tile.id), today: this.today, ring: this.mode !== 'grid' }))));
|
||||
this.keepView(section, () => {
|
||||
section.rows.style.height = '';
|
||||
fill(section.rows, nodes);
|
||||
section.rendered = true;
|
||||
section.renderedWidth = width;
|
||||
});
|
||||
}
|
||||
|
||||
layout(tiles, width) {
|
||||
if (this.mode !== 'grid') return justify(tiles, width, this.rowHeight);
|
||||
const height = Math.round(this.rowHeight * 1.25);
|
||||
const w = Math.round(height * 0.5625);
|
||||
const perRow = Math.max(1, Math.floor((width + GAP) / (w + GAP)));
|
||||
const rows = [];
|
||||
for (let i = 0; i < tiles.length; i += perRow) rows.push({ height, items: tiles.slice(i, i + perRow).map((tile) => ({ tile, width: w })) });
|
||||
return rows;
|
||||
}
|
||||
|
||||
unrender(section) {
|
||||
const height = section.rows.offsetHeight;
|
||||
section.rows.style.height = `${height}px`;
|
||||
section.rows.replaceChildren();
|
||||
section.rendered = false;
|
||||
}
|
||||
|
||||
onResize() {
|
||||
const width = this.root.clientWidth;
|
||||
if (!width || Math.abs(width - this.width) < 2) return;
|
||||
this.relayout(width);
|
||||
}
|
||||
|
||||
/** Lays everything out again (new width or new tile size), keeping the group at the top of the view in place. */
|
||||
relayout(width = this.root.clientWidth) {
|
||||
const anchor = this.topSection();
|
||||
const offset = anchor ? this.scroller.scrollTop - anchor.el.offsetTop : 0;
|
||||
const ratio = anchor && anchor.el.offsetHeight ? offset / anchor.el.offsetHeight : 0;
|
||||
this.width = width;
|
||||
for (const section of this.sections) {
|
||||
if (section.rendered) this.render(section);
|
||||
else section.rows.style.height = `${this.estimate(section.count)}px`;
|
||||
}
|
||||
if (anchor) this.scroller.scrollTop = anchor.el.offsetTop + ratio * anchor.el.offsetHeight;
|
||||
}
|
||||
|
||||
setRowHeight(height) {
|
||||
this.rowHeight = height;
|
||||
this.relayout();
|
||||
}
|
||||
|
||||
topSection() {
|
||||
const top = this.scroller.getBoundingClientRect().top;
|
||||
return this.sections.find((s) => s.el.getBoundingClientRect().bottom > top + 1) || null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- selection and clicks
|
||||
|
||||
setSelecting(on) {
|
||||
this.selecting = on;
|
||||
this.root.classList.toggle('scegli', on);
|
||||
if (!on) this.clearSelection();
|
||||
}
|
||||
|
||||
clearSelection() {
|
||||
this.selected.clear();
|
||||
for (const el of this.root.querySelectorAll('.tess.scelta')) this.markTile(el, false);
|
||||
this.onSelection(this.selected);
|
||||
}
|
||||
|
||||
markTile(el, on) {
|
||||
el.classList.toggle('scelta', on);
|
||||
el.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||||
const sel = el.querySelector('.sel');
|
||||
if (sel) sel.setAttribute('aria-checked', String(on));
|
||||
}
|
||||
|
||||
toggle(id, el) {
|
||||
const on = !this.selected.has(id);
|
||||
if (on) this.selected.add(id);
|
||||
else this.selected.delete(id);
|
||||
if (el) this.markTile(el, on);
|
||||
if (!this.selecting && on) this.setSelecting(true);
|
||||
this.onSelection(this.selected);
|
||||
}
|
||||
|
||||
onClick(e) {
|
||||
const el = e.target.closest('.tess[data-id]');
|
||||
if (!el) return;
|
||||
const id = Number(el.dataset.id);
|
||||
if (e.target.closest('.sel') || this.selecting) {
|
||||
e.preventDefault();
|
||||
this.toggle(id, el);
|
||||
return;
|
||||
}
|
||||
const tile = this.findTile(id);
|
||||
if (tile) this.onOpen(tile);
|
||||
}
|
||||
|
||||
findTile(id) {
|
||||
for (const s of this.sections) {
|
||||
const tile = s.tiles.find((x) => x.id === id);
|
||||
if (tile) return tile;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- viewer navigation
|
||||
|
||||
/** Position of an entry among all the entries of the filter (1-based) and the total. */
|
||||
position(id) {
|
||||
let before = 0;
|
||||
for (const s of this.sections) {
|
||||
const i = s.tiles.findIndex((x) => x.id === id);
|
||||
if (i >= 0) return { index: before + i + 1, total: this.sections.reduce((a, x) => a + x.count, 0) };
|
||||
before += s.count;
|
||||
}
|
||||
return { index: 0, total: this.sections.reduce((a, x) => a + x.count, 0) };
|
||||
}
|
||||
|
||||
/** The entry before (delta −1) or after (+1) an entry, loading the next group when needed. */
|
||||
async neighbor(id, delta) {
|
||||
let si = this.sections.findIndex((s) => s.tiles.some((x) => x.id === id));
|
||||
if (si < 0) return null;
|
||||
let i = this.sections[si].tiles.findIndex((x) => x.id === id) + delta;
|
||||
for (;;) {
|
||||
const s = this.sections[si];
|
||||
if (i >= 0 && i < s.tiles.length) return s.tiles[i];
|
||||
if (delta > 0 && !s.complete) {
|
||||
await this.load(s);
|
||||
continue;
|
||||
}
|
||||
si += delta;
|
||||
if (si < 0 || si >= this.sections.length) return null;
|
||||
const next = this.sections[si];
|
||||
if (!next.complete && next.tiles.length === 0) await this.load(next);
|
||||
i = delta > 0 ? 0 : next.tiles.length - 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Scrolls so that an entry is visible (after the viewer moved far). */
|
||||
reveal(id) {
|
||||
const el = this.root.querySelector(`.tess[data-id="${id}"]`);
|
||||
if (el) el.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- changes
|
||||
|
||||
/** Removes entries (after a deletion) and updates the counts of their days. */
|
||||
removeTiles(ids) {
|
||||
const set = new Set(ids);
|
||||
for (const s of [...this.sections]) {
|
||||
const before = s.tiles.length;
|
||||
s.tiles = s.tiles.filter((x) => !set.has(x.id));
|
||||
const removed = before - s.tiles.length;
|
||||
if (!removed) continue;
|
||||
s.count -= removed;
|
||||
for (const id of ids) this.selected.delete(id);
|
||||
if (s.count <= 0) {
|
||||
this.unobserve(s);
|
||||
this.keepView(s, () => s.el.remove());
|
||||
this.sections.splice(this.sections.indexOf(s), 1);
|
||||
this.byDay.delete(s.day);
|
||||
continue;
|
||||
}
|
||||
const [bold, rest] = this.dayLabel(s.day, s.count, this.today);
|
||||
fill(s.header, h('b', bold), rest ? h('span', rest) : null);
|
||||
if (s.rendered) this.render(s);
|
||||
}
|
||||
this.onSelection(this.selected);
|
||||
}
|
||||
|
||||
/**
|
||||
* The library changed: new days appear at the top and changed days are reloaded, without moving what is on screen.
|
||||
* A group being looked at is not redrawn under the eyes: «N nuovi elementi in cima» offers to show them.
|
||||
*/
|
||||
async refresh() {
|
||||
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
|
||||
this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today });
|
||||
const todayChanged = data.today !== this.today;
|
||||
this.today = data.today;
|
||||
const wanted = new Map(data.days.map((d) => [d.day, d]));
|
||||
let added = 0;
|
||||
for (const s of [...this.sections]) {
|
||||
if (!wanted.has(s.day)) {
|
||||
this.unobserve(s);
|
||||
this.keepView(s, () => s.el.remove());
|
||||
this.sections.splice(this.sections.indexOf(s), 1);
|
||||
this.byDay.delete(s.day);
|
||||
}
|
||||
}
|
||||
let previous = null;
|
||||
for (const day of data.days) {
|
||||
let s = this.byDay.get(day.day);
|
||||
if (!s) {
|
||||
s = this.createSection(day);
|
||||
this.sections.splice(previous ? this.sections.indexOf(previous) + 1 : 0, 0, ...this.sections.splice(this.sections.indexOf(s), 1));
|
||||
const anchor = previous ? previous.el.nextSibling : this.root.firstChild;
|
||||
this.keepView(s, () => this.root.insertBefore(s.el, anchor));
|
||||
added += day.count;
|
||||
} else if (s.count !== day.count || todayChanged) {
|
||||
const grew = day.count - s.count;
|
||||
if (s.rendered && this.isVisible(s)) {
|
||||
s.stale = day;
|
||||
if (grew > 0) added += grew;
|
||||
} else {
|
||||
this.reset(s, day);
|
||||
}
|
||||
}
|
||||
previous = s;
|
||||
}
|
||||
if (added > 0) this.showPill(added);
|
||||
if (!this.sections.length) this.onEmpty();
|
||||
}
|
||||
|
||||
reset(s, day) {
|
||||
s.count = day.count;
|
||||
s.cursor = day.cursor;
|
||||
s.tiles = [];
|
||||
s.complete = false;
|
||||
s.stale = false;
|
||||
const [bold, rest] = this.dayLabel(s.day, s.count, this.today);
|
||||
fill(s.header, h('b', bold), rest ? h('span', rest) : null);
|
||||
if (s.rendered) {
|
||||
this.keepView(s, () => {
|
||||
s.rows.style.height = `${this.estimate(s.count)}px`;
|
||||
s.rows.replaceChildren();
|
||||
s.rendered = false;
|
||||
});
|
||||
}
|
||||
if (s.near) this.wake(s);
|
||||
}
|
||||
|
||||
isVisible(s) {
|
||||
const top = this.scroller.getBoundingClientRect();
|
||||
const rect = s.el.getBoundingClientRect();
|
||||
return rect.bottom > top.top && rect.top < top.bottom;
|
||||
}
|
||||
|
||||
showPill(count) {
|
||||
if (this.scroller.scrollTop < 4 && !this.sections.some((s) => s.stale)) return;
|
||||
this.pendingNew += count;
|
||||
fill(this.pill, h('button.btn', {
|
||||
type: 'button',
|
||||
onclick: () => {
|
||||
for (const s of this.sections) if (s.stale) this.reset(s, s.stale);
|
||||
this.pendingNew = 0;
|
||||
this.pill.hidden = true;
|
||||
this.scroller.scrollTo({ top: 0 });
|
||||
},
|
||||
}, icon('arrow-left', 's'), t('libreria.nuoviInCima', { n: this.pendingNew })));
|
||||
this.pill.querySelector('svg').style.transform = 'rotate(90deg)';
|
||||
this.pill.hidden = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// 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.
|
||||
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { withCarried } from '../core/api.js';
|
||||
import { t } from '../core/text.js';
|
||||
|
||||
export default {
|
||||
mount(page, route) {
|
||||
const key = route.params.key;
|
||||
if (key === 'nonTrovata') {
|
||||
page.title(t('pagine.nonTrovata'));
|
||||
fill(page.body, h('div.vuoto-pagina', icon('info'), h('h2', t('pagine.nonTrovata')), h('p', t('pagine.nonTrovataTesto')),
|
||||
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'))));
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,265 @@
|
||||
// Visualizzatore (mockup 02, spec §4.6): covers the whole window; arrows and arrow keys move through the files of the
|
||||
// series and then to the next entry; Esc closes; videos start muted. The side panel shows the data, the files and the
|
||||
// provenance, and the actions: «Mostra nella cartella» (desktop) or «Scarica» (browser), «Apri su Instagram» (in
|
||||
// Alberto's own browser, never in Febe's), «Elimina dalla libreria».
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { caps, serverNow } from '../core/context.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { t, dayName, capitalize, bytes, duration, number, ago, shortDay } from '../core/text.js';
|
||||
import { avatar, label, showError, toast } from '../core/ui.js';
|
||||
import { confirmDelete } from './library.js';
|
||||
|
||||
const KIND_ICON = { post: 'image', story: 'circle-dashed', highlight: 'star', tagged: 'square-user', profile: 'circle-user' };
|
||||
|
||||
/**
|
||||
* Opens the viewer on a tile. source: { position(id), neighbor(id, delta), reveal(id) } (the mosaic, or a plain list).
|
||||
* origin: «Libreria» or the account name. onDeleted(ids): called after a deletion.
|
||||
*/
|
||||
export function openViewer({ tile, source, origin, onDeleted }) {
|
||||
const opener = document.activeElement;
|
||||
let entry = null;
|
||||
let fileIndex = 0;
|
||||
let zoomed = false;
|
||||
let token = 0;
|
||||
|
||||
const where = h('span.dove');
|
||||
const closeButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.chiudi'), title: t('vis.chiudi'), onclick: close }, icon('x'));
|
||||
const zoomButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.ingrandisci'), title: t('vis.ingrandisci'), onclick: () => setZoom(!zoomed) }, icon('zoom-in'));
|
||||
const fullButton = h('button.tondino', {
|
||||
type: 'button', 'aria-label': t('vis.schermoIntero'), title: t('vis.schermoIntero'),
|
||||
onclick: () => (document.fullscreenElement ? document.exitFullscreen() : box.requestFullscreen && box.requestFullscreen().catch(() => {})),
|
||||
}, icon('maximize'));
|
||||
const prev = h('button.freccia.sx', { type: 'button', 'aria-label': t('vis.precedente'), onclick: () => step(-1) }, icon('chevron-left'));
|
||||
const next = h('button.freccia.dx', { type: 'button', 'aria-label': t('vis.successivo'), onclick: () => step(1) }, icon('chevron-right'));
|
||||
const stage = h('div.scena');
|
||||
const strip = h('div.serie', { role: 'group', 'aria-label': t('vis.serie') });
|
||||
const panelTop = h('div.alto');
|
||||
const panelBottom = h('div.basso');
|
||||
const box = h('div.vis', { role: 'dialog', 'aria-modal': 'true', 'aria-label': t('vis.etichetta') },
|
||||
h('div.palco',
|
||||
h('div.palco-testa', closeButton, where, h('div.destra', zoomButton, fullButton)),
|
||||
h('div', { style: { position: 'relative', flex: '1', minHeight: '0', display: 'flex' } }, prev, stage, next),
|
||||
strip),
|
||||
h('aside.scheda', panelTop, panelBottom));
|
||||
|
||||
function onKey(e) {
|
||||
if (document.querySelector('.velo.finestra, .menu')) return; // a dialog or a menu over the viewer has the keys
|
||||
if (e.target.closest && e.target.closest('input,textarea,select,video')) {
|
||||
if (e.key !== 'Escape') return;
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
if (document.fullscreenElement) return;
|
||||
e.preventDefault();
|
||||
close();
|
||||
} else if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
step(-1);
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
step(1);
|
||||
} else if (e.key === 'Tab') {
|
||||
const items = [...box.querySelectorAll('button:not([disabled]),a[href],video')].filter((el) => el.offsetParent !== null);
|
||||
if (!items.length) return;
|
||||
if (e.shiftKey && document.activeElement === items[0]) {
|
||||
items[items.length - 1].focus();
|
||||
e.preventDefault();
|
||||
} else if (!e.shiftKey && document.activeElement === items[items.length - 1]) {
|
||||
items[0].focus();
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function close() {
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
for (const v of box.querySelectorAll('video')) v.pause();
|
||||
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
|
||||
box.remove();
|
||||
document.body.style.overflow = '';
|
||||
if (entry && source && source.reveal) source.reveal(entry.id);
|
||||
if (opener && document.contains(opener)) opener.focus();
|
||||
}
|
||||
|
||||
function setZoom(on) {
|
||||
zoomed = on;
|
||||
stage.classList.toggle('ingrandita', on);
|
||||
zoomButton.setAttribute('aria-pressed', String(on));
|
||||
}
|
||||
|
||||
async function load(id, index = 0) {
|
||||
const mine = ++token;
|
||||
try {
|
||||
const data = await api(`/api/entries/${id}`);
|
||||
if (mine !== token) return;
|
||||
entry = data;
|
||||
fileIndex = index < 0 ? entry.media.length - 1 : Math.min(index, entry.media.length - 1);
|
||||
draw();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function step(delta) {
|
||||
if (!entry) return;
|
||||
const target = fileIndex + delta;
|
||||
if (target >= 0 && target < entry.media.length) {
|
||||
fileIndex = target;
|
||||
drawMedia();
|
||||
drawStrip();
|
||||
drawPanel();
|
||||
return;
|
||||
}
|
||||
if (!source || !source.neighbor) return;
|
||||
const other = await source.neighbor(entry.id, delta);
|
||||
if (other) await load(other.id, delta > 0 ? 0 : -1);
|
||||
}
|
||||
|
||||
function draw() {
|
||||
drawWhere();
|
||||
drawMedia();
|
||||
drawStrip();
|
||||
drawPanel();
|
||||
}
|
||||
|
||||
function drawWhere() {
|
||||
if (source && source.position) {
|
||||
const p = source.position(entry.id);
|
||||
where.textContent = p.index ? t('vis.dove', { origine: origin, n: number(p.index), totale: number(p.total) }) : origin;
|
||||
} else where.textContent = origin;
|
||||
}
|
||||
|
||||
function drawMedia() {
|
||||
setZoom(false);
|
||||
for (const v of stage.querySelectorAll('video')) v.pause();
|
||||
const media = entry.media[fileIndex];
|
||||
if (!media) {
|
||||
fill(stage, h('div.mancante', icon('info', 'l'), h('p', t('vis.eliminato'))));
|
||||
return;
|
||||
}
|
||||
const thumb = media.thumb ? `/api/thumbnails/${media.thumb}` : null;
|
||||
if (!media.available) {
|
||||
fill(stage, h('div.mancante', thumb ? h('img', { src: thumb, alt: '' }) : icon('image', 'l'),
|
||||
h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante'))));
|
||||
return;
|
||||
}
|
||||
const src = `/api/media/${media.id}/file`;
|
||||
if (media.kind === 'video') {
|
||||
fill(stage, h('video', { src, poster: thumb, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata', 'aria-label': t('libreria.tipiTessera.' + entry.kind) }));
|
||||
const video = stage.querySelector('video');
|
||||
video.muted = true; // spec §10.3: videos start without sound
|
||||
} else {
|
||||
const img = h('img', { src, alt: entry.caption ? entry.caption.slice(0, 140) : `@${entry.account.username}` });
|
||||
img.addEventListener('click', () => setZoom(!zoomed));
|
||||
fill(stage, img);
|
||||
}
|
||||
prev.disabled = false;
|
||||
next.disabled = false;
|
||||
}
|
||||
|
||||
function drawStrip() {
|
||||
if (entry.media.length < 2) {
|
||||
strip.hidden = true;
|
||||
strip.replaceChildren();
|
||||
return;
|
||||
}
|
||||
strip.hidden = false;
|
||||
fill(strip, entry.media.map((m, i) => h(`button${i === fileIndex ? '.qui' : ''}`, {
|
||||
type: 'button',
|
||||
'aria-label': t('vis.fileN', { n: i + 1, totale: entry.media.length }),
|
||||
'aria-current': i === fileIndex ? 'true' : null,
|
||||
onclick: () => {
|
||||
fileIndex = i;
|
||||
drawMedia();
|
||||
drawStrip();
|
||||
drawPanel();
|
||||
},
|
||||
}, m.thumb ? h('img', { src: `/api/thumbnails/${m.thumb}`, alt: '', loading: 'lazy' }) : null, m.kind === 'video' ? icon('play') : null)));
|
||||
}
|
||||
|
||||
function row(term, value) {
|
||||
return value == null || value === '' ? null : [h('dt', term), h('dd', value)];
|
||||
}
|
||||
|
||||
function drawPanel() {
|
||||
const a = entry.account;
|
||||
const media = entry.media[fileIndex];
|
||||
const today = caps().today;
|
||||
const kindText = t(`libreria.tipiTessera.${entry.kind}`);
|
||||
const mediaText = media ? t(media.kind === 'video' ? 'comune.video' : 'comune.foto') : '';
|
||||
const typeLabel = entry.media.length > 1
|
||||
? t('vis.tipoFile', { tipo: kindText, media: mediaText, n: fileIndex + 1, totale: entry.media.length })
|
||||
: t('vis.tipoSingolo', { tipo: kindText, media: mediaText });
|
||||
const published = `${capitalize(dayName(entry.publishedDay))} ${entry.publishedDay.slice(0, 4)}, ${entry.publishedTime}`;
|
||||
const downloaded = entry.downloaded ? `${shortDay(entry.downloaded.day)} ${entry.downloaded.day.slice(0, 4)}, ${entry.downloaded.clock}` : null;
|
||||
fill(panelTop,
|
||||
h('div.chi-vis', avatar(a.username, 'm', a.avatar), h('div', h('b', `@${a.username}`), a.displayName ? h('span', a.displayName) : null),
|
||||
a.isFollowed ? label(t('vis.seguito'), 'accento', 'user-check') : null),
|
||||
h('div.etichette', label(typeLabel, '', KIND_ICON[entry.kind] || 'image'), a.isPrivate ? label(t('vis.privato'), '', 'lock') : null),
|
||||
h('div.quando', h('b', published), h('span', t('vis.pubblicato', { quando: ago(entry.publishedAt, serverNow(), today, entry.publishedDay) }))),
|
||||
h('section', h('h3', t('vis.didascalia')), entry.caption ? h('p.didascalia', entry.caption) : h('p.didascalia.muto', t('vis.senzaDidascalia'))),
|
||||
h('section', h('h3', t('vis.file')), h('dl',
|
||||
media ? row(t('vis.nome'), media.fileName) : null,
|
||||
media && media.width && media.height ? row(t('vis.dimensioni'), t('vis.pixel', { l: number(media.width), a: number(media.height) })) : null,
|
||||
media && media.bytes ? row(t('vis.peso'), bytes(media.bytes)) : null,
|
||||
media && media.duration ? row(t('vis.durata'), duration(media.duration)) : null,
|
||||
media ? row(t('vis.cartella'), media.folder) : null,
|
||||
row(t('vis.codice'), entry.code || entry.instagramId),
|
||||
entry.author ? row(t('vis.autore'), `@${entry.author}`) : null,
|
||||
entry.media.length > 1 ? row(t('vis.posizione'), t('vis.posizioneDi', { n: fileIndex + 1, totale: entry.media.length })) : null,
|
||||
entry.highlights.length ? row(t('vis.raccolte'), entry.highlights.join(', ')) : null)),
|
||||
h('section', h('h3', t('vis.provenienza')), h('dl',
|
||||
row(t('vis.origine'), t(entry.provenance === 'imported' ? 'vis.importato' : 'vis.scaricato')),
|
||||
row(t('vis.quando'), downloaded))));
|
||||
|
||||
const c = caps();
|
||||
const actions = [];
|
||||
if (media && media.available) {
|
||||
actions.push(c.showInFolder
|
||||
? h('button.btn', { type: 'button', onclick: () => showInFolder(media.id) }, icon('folder-open'), t('vis.mostra'))
|
||||
: h('a.btn', { href: `/api/media/${media.id}/file?download=1`, download: media.fileName || '' }, icon('download'), t('vis.scarica')));
|
||||
}
|
||||
if (entry.instagramUrl) {
|
||||
actions.push(c.openUrlNative
|
||||
? h('button.btn', { type: 'button', onclick: () => openNative(entry.id) }, icon('external-link'), t('vis.apri'))
|
||||
: h('a.btn', { href: entry.instagramUrl, target: '_blank', rel: 'noopener noreferrer' }, icon('external-link'), t('vis.apri')));
|
||||
}
|
||||
if (entry.state !== 'deleted') {
|
||||
actions.push(h('button.btn.nudo.pericolo', { type: 'button', onclick: remove }, icon('trash-2'), t('vis.elimina')));
|
||||
}
|
||||
fill(panelBottom, actions);
|
||||
}
|
||||
|
||||
async function showInFolder(mediaId) {
|
||||
try {
|
||||
const result = await api('/api/media/show-in-folder', { method: 'POST', body: { mediaId } });
|
||||
toast(result.message);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function openNative(id) {
|
||||
try {
|
||||
await api(`/api/entries/${id}/open-on-instagram`, { method: 'POST' });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
const id = entry.id;
|
||||
const following = source && source.neighbor ? (await source.neighbor(id, 1)) || (await source.neighbor(id, -1)) : null;
|
||||
const removed = await confirmDelete([id]);
|
||||
if (!removed) return;
|
||||
if (onDeleted) onDeleted(removed);
|
||||
if (following) await load(following.id, 0);
|
||||
else close();
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
document.body.append(box);
|
||||
closeButton.focus();
|
||||
load(tile.id, 0);
|
||||
void withCarried;
|
||||
}
|
||||
Reference in new issue
Block a user