// 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((change) => { if (change.reason !== 'fermi') onChange(); // an analysis («Cerca i video fermi») changes nothing here }); 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(); }, };