// 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. // «Esporta l'elenco» in the tools row exports what the filter shows (spec §4.8: CSV with «;», UTF-8 with BOM). import { api, download, withCarried } from '../core/api.js'; import { caps } from '../core/context.js'; import { h, icon, fill, later, local } from '../core/dom.js'; import { setQuery } from '../core/shell.js'; import { t, number, shortDay, parseDay } from '../core/text.js'; import { menu, showError, toast, confirmDialog } from '../core/ui.js'; import { engineState } from '../core/engine.js'; import { Mosaic } from './mosaic.js'; import { welcome } from './welcome.js'; import { openViewer } from './viewer.js'; const KINDS = [ { 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'))); // Icon only, like the tile size: the row of the mockup has no room for one more label. const exportButton = h('button.btn.nudo.piccolo.solo-icona.solo-largo', { type: 'button', title: t('libreria.esportaAiuto'), 'aria-label': t('libreria.esporta') }, icon('file-down')); // Probable duplicates after a download wait for Alberto (spec §9.5): a short link to their review. const duplicates = h('a.btn.nudo.piccolo.doppioni-link', { href: withCarried('/doppioni'), hidden: true }); api('/api/duplicates/count', { signal: page.signal }).then((counts) => { if (!counts.download) return; fill(duplicates, icon('layers', 's'), t('libreria.doppioni', { n: counts.download })); duplicates.hidden = false; }).catch(() => {}); page.tools(h('div', { style: { display: 'contents' } }, chips, h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton), filtersButton, h('div.destra', duplicates, exportButton, 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)); exportButton.addEventListener('click', () => exportFiltered()); 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 exportFiltered() { exportButton.disabled = true; try { await download('/api/entries/export', { query: apiQuery(state, today()) }, 'febe-elementi.csv'); toast(t(filtersActive() ? 'libreria.esportatoFiltro' : 'libreria.esportato')); } catch (error) { showError(error); } finally { exportButton.disabled = false; } } async function deleteSelected() { const ids = [...mosaic.selected]; const removed = await confirmDelete(ids); if (removed) { mosaic.removeTiles(removed); setSelecting(false); } } // The empty state: no results of a filter, the first start (spec §10.3: not connected, the two ways to begin) or an // empty library. Whether Febe is connected comes with the engine, which may answer after the library: until then // the page stays blank, as the mosaic does while it loads, rather than guess. The empty state follows the engine // while it is on screen, and is drawn again only when it changes kind. let empty = null; function drawEmpty() { const kind = filtersActive() ? 'filtro' : !engineState() ? 'attesa' : notConnected() ? 'benvenuto' : 'vuota'; if (empty && empty.kind === kind && empty.node.isConnected) return; let node; if (kind === 'attesa') { node = h('div', { 'aria-busy': 'true' }); } else if (kind === 'filtro') { node = 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'))); } else if (kind === 'benvenuto') { node = welcome(); } else { node = h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto'))); } fill(host, node); empty = { kind, node }; } page.onEngine(() => { if (empty && empty.node.isConnected) drawEmpty(); }); // 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: drawEmpty, }); 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; } } /** First start (spec §10.3): not connected to Instagram, so the empty library offers the two ways to begin. */ function notConnected() { const state = engineState(); return Boolean(state && state.connection && state.connection.state === 'notConnected'); }