Ricerca dei profili con suggerimenti e foto (#37)
«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono subito i suggerimenti locali, poi i profili di Instagram con la foto, come chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima il fuoco, legge la risposta della pagina e non clicca mai un risultato. La ricerca ha una categoria propria nel Governatore, con tetti larghi che non consumano quelli della raccolta, e si dà il turno con il motore sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le foto passano dal CDN con un permesso ciascuna e restano solo in memoria. Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli search-open e search-box saranno raccolti dal vivo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5e417c666d
commit
9941a2fa1f
98 files changed
+8021
-229
No files matched your search
@@ -561,12 +561,39 @@ a.stato:hover{border-color:var(--bordo-forte)}
|
||||
|
||||
/* dialogo «Aggiungi account» */
|
||||
.aggiungi{width:min(900px,calc(100vw - 32px));height:min(660px,calc(100vh - 32px))}
|
||||
.aggiungi .linguette{padding:0 22px;margin-top:6px}
|
||||
.aggiungi .corpo-dialogo{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 316px}
|
||||
.aggiungi .sinistra{display:flex;flex-direction:column;min-height:0;padding:14px 18px 0 22px;border-right:1px solid var(--bordo)}
|
||||
.aggiungi .corpo-dialogo{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 316px;border-top:1px solid var(--bordo)}
|
||||
.aggiungi .sinistra{display:flex;flex-direction:column;min-height:0;padding:16px 18px 0 22px;border-right:1px solid var(--bordo)}
|
||||
.aggiungi .destra-dialogo{padding:16px 18px;overflow:auto;background:var(--superficie)}
|
||||
.aggiungi .cerca-riga{display:flex;gap:10px;margin-bottom:6px}
|
||||
.aggiungi .cerca-riga .campo{flex:1}
|
||||
/* ricerca unica con i suggerimenti mentre si scrive (#37) */
|
||||
.aggiungi .cerca-zona{position:relative;flex:none;margin-bottom:12px}
|
||||
.aggiungi .cerca-zona .campo{height:40px}
|
||||
.aggiungi .suggerimenti{position:absolute;left:0;right:0;top:calc(100% + 4px);z-index:5;max-height:min(420px,60vh);overflow:auto;background:var(--superficie);border:1px solid var(--bordo);border-radius:var(--r-pannello);box-shadow:var(--ombra-menu);padding:4px 6px 6px}
|
||||
.aggiungi .suggerimenti[hidden]{display:none}
|
||||
.aggiungi .sezione-titolo{display:flex;gap:6px;align-items:baseline;padding:9px 8px 5px;font-size:12px;font-weight:600;color:var(--testo-3)}
|
||||
.aggiungi .sezione-titolo .per{font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
|
||||
.aggiungi .stato-remoto{display:flex;gap:8px;align-items:flex-start;padding:4px 8px 8px;font-size:12.5px;line-height:1.4;color:var(--testo-2)}
|
||||
.aggiungi .stato-remoto .ic{flex:none;margin-top:1px}
|
||||
.aggiungi .stato-remoto.allarme{color:var(--ambra)}
|
||||
.aggiungi .opzione{display:flex;align-items:center;gap:12px;padding:6px 8px;border-radius:6px;cursor:pointer;min-height:52px}
|
||||
.aggiungi .opzione:hover{background:var(--rialzo)}
|
||||
.aggiungi .opzione[aria-selected=true]{background:var(--accento-tinta)}
|
||||
.aggiungi .opzione.presente{cursor:default}
|
||||
.aggiungi .opzione.presente .chi-nome,.aggiungi .opzione.presente .av{opacity:.6}
|
||||
.aggiungi .opzione .chi-nome,.aggiungi .voce.scelto .chi-nome{flex:1;min-width:0}
|
||||
.aggiungi .opzione b,.aggiungi .voce.scelto b{display:block;font-weight:600;font-size:13.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.aggiungi .opzione small,.aggiungi .voce.scelto small{display:block;color:var(--testo-2);font-size:12.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.aggiungi .opzione .verificato{display:inline-flex;vertical-align:-2px;margin-left:4px;color:var(--accento)}
|
||||
.aggiungi .etichette{display:flex;gap:6px;flex:none}
|
||||
.aggiungi .opzione .btn{flex:none;min-width:96px;justify-content:center}
|
||||
.aggiungi .opzione .btn.scelto{background:var(--accento-tinta);border-color:var(--accento-bordo);color:var(--accento-scuro)}
|
||||
.aggiungi .opzione.azione .av{color:var(--testo-2)}
|
||||
.aggiungi .scelti-testa{display:flex;align-items:center;gap:10px;flex:none;padding:2px 0 6px;border-bottom:1px solid var(--bordo)}
|
||||
.aggiungi .scelti-testa h3{margin:0;font-size:13.5px;font-weight:650;display:flex;gap:7px;align-items:baseline}
|
||||
.aggiungi .scelti-testa h3 i{font-style:normal;font-size:12px;color:var(--testo-3);font-weight:500}
|
||||
.aggiungi .scelti-testa > .btn.collegamento{margin-left:auto;font-size:13px}
|
||||
.aggiungi .vuoto-scelti{display:flex;gap:10px;align-items:flex-start;padding:16px 2px;color:var(--testo-2);font-size:13px;line-height:1.45}
|
||||
.aggiungi .vuoto-scelti .ic{flex:none;margin-top:2px}
|
||||
.aggiungi .elenco .voce.scelto{cursor:default}
|
||||
.aggiungi .elenco{flex:1;overflow:auto;margin:0 -18px 0 -4px;padding:0 18px 0 4px}
|
||||
.aggiungi .elenco .voce{padding:9px 2px;border-bottom:1px solid var(--bordo);gap:12px}
|
||||
.aggiungi .elenco .voce.presente{opacity:.5}
|
||||
@@ -582,6 +609,7 @@ a.stato:hover{border-color:var(--bordo-forte)}
|
||||
.aggiungi .partenza .tondo{margin-top:2px}
|
||||
.aggiungi .problemi{margin-top:10px;font-size:12.5px;color:var(--rosso);display:flex;flex-direction:column;gap:3px}
|
||||
.aggiungi .riconosciuti{margin-top:10px;font-size:12.5px;color:var(--testo-2)}
|
||||
.aggiungi .riconosciuti:empty,.aggiungi .problemi:empty{display:none}
|
||||
|
||||
/* ==========================================================================
|
||||
Parte 2 dell'interfaccia: Attività, Impostazioni, Collegamento, Browser,
|
||||
@@ -970,8 +998,15 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento
|
||||
.tabella-account .tab td.menu-riga{position:absolute;right:4px;top:12px;width:auto}
|
||||
.tabella-account .nome .sotto{flex-wrap:wrap;white-space:normal}
|
||||
.tipi{grid-template-columns:1fr 1fr}
|
||||
.aggiungi .corpo-dialogo{grid-template-columns:1fr;overflow:auto}
|
||||
.aggiungi .corpo-dialogo{grid-template-columns:minmax(0,1fr);overflow:auto}
|
||||
.aggiungi footer{flex-wrap:wrap;row-gap:10px}
|
||||
.aggiungi footer .destra{margin-left:auto}
|
||||
.aggiungi .sinistra{border-right:0;min-height:320px}
|
||||
.aggiungi .opzione{flex-wrap:wrap;row-gap:4px}
|
||||
.aggiungi .opzione .chi-nome{flex:1 1 0}
|
||||
.aggiungi .opzione .btn{min-width:0}
|
||||
.aggiungi .opzione .etichette{order:3;flex-basis:100%;padding-left:52px;flex-wrap:wrap}
|
||||
.aggiungi .opzione .etichette:empty{display:none}
|
||||
.salva{padding:10px 16px;flex-wrap:wrap}
|
||||
.brevi{bottom:72px}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:n
|
||||
/**
|
||||
* Opens a modal dialog over the whole window. build(close) returns { header?, body, footer? } or a node; close(value)
|
||||
* resolves the returned promise. Esc and the veil close with undefined. Focus is trapped and restored.
|
||||
* build may also return onEscape (called first on Esc: returning true means the dialog handled it, say by closing a
|
||||
* list of suggestions, and stays open) and onClose (called once, however the dialog closes).
|
||||
*/
|
||||
export function dialog({ title, className = '', build, labelledBy, dismissable = true }) {
|
||||
return new Promise((resolve) => {
|
||||
@@ -42,6 +44,13 @@ export function dialog({ title, className = '', build, labelledBy, dismissable =
|
||||
closed = true;
|
||||
veil.remove();
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
if (parts && typeof parts.onClose === 'function') {
|
||||
try {
|
||||
parts.onClose();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
if (opener && opener.focus && document.contains(opener)) opener.focus();
|
||||
resolve(value);
|
||||
};
|
||||
@@ -61,7 +70,10 @@ export function dialog({ title, className = '', build, labelledBy, dismissable =
|
||||
if (e.target === veil && dismissable) close(undefined);
|
||||
});
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape' && dismissable) {
|
||||
if (e.key === 'Escape' && parts && typeof parts.onEscape === 'function' && parts.onEscape()) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
} else if (e.key === 'Escape' && dismissable) {
|
||||
e.stopPropagation();
|
||||
close(undefined);
|
||||
} else if (e.key === 'Tab') {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
// «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.
|
||||
// «Aggiungi account» (mockup 04, spec §4.2, issue #37): one search box. While Alberto types, the list under it shows
|
||||
// at once the profiles he follows and the accounts already in Febe, then the profiles Instagram finds, with their
|
||||
// photo, user name, full name and the labels «Seguito», «Privato», «Già in Febe». Febe's browser searches on the site
|
||||
// and fetches the photos (the page asks only Febe: /api/ricerca, /api/ricerca/foto, /api/thumbnails). Several names or
|
||||
// profile addresses can be pasted in the same box. The chosen profiles go to «Da aggiungere»; the three starting
|
||||
// points stay on the right; the button says how many accounts it adds. «Scegli fra tutti i profili che segui» opens
|
||||
// the whole list of followed profiles with check boxes.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill, later } from '../core/dom.js';
|
||||
import { h, icon, fill, later, uid } from '../core/dom.js';
|
||||
import { t, number, shortDay } from '../core/text.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { engineState, onEngine } from '../core/engine.js';
|
||||
import { avatar, checkbox, dialog, label, showError, toast } from '../core/ui.js';
|
||||
|
||||
const STARTS = ['everything', 'newOnly', 'storiesOnly'];
|
||||
@@ -17,6 +22,31 @@ const DEPTHS = [
|
||||
{ key: 'year', depth: 'fromDate' },
|
||||
];
|
||||
|
||||
/** Local suggestions shown at most. */
|
||||
const MAX_LOCAL = 8;
|
||||
/** Pause after the last key before the text goes to Febe (the local suggestions do not wait). */
|
||||
const DEBOUNCE_MS = 150;
|
||||
/** Asking for the results: often at first, then less. Never stops while Febe is still searching. */
|
||||
const FAST_POLL_MS = 400;
|
||||
const SLOW_POLL_MS = 2000;
|
||||
const FAST_FOR_MS = 10000;
|
||||
/** How long to keep asking only for photos still on their way. */
|
||||
const PHOTOS_FOR_MS = 60000;
|
||||
/** Longest text the server accepts (SearchText.MaxRawLength). */
|
||||
const MAX_TEXT = 60;
|
||||
/** States of the search while Febe still works on the text. */
|
||||
const WORKING = ['attesa', 'cerca'];
|
||||
/**
|
||||
* States the search leaves by itself (Alberto lets go of the browser, the pause or the stop ends, the active window
|
||||
* opens, the cap frees up): the window keeps asking, slowly, and at once when the engine changes.
|
||||
*/
|
||||
const RESUMING = ['non-possibile', 'fuori-fascia', 'ferma'];
|
||||
/**
|
||||
* First path segments of instagram.com that are pages, not profiles (UsernameParser.ReservedPaths, SearchText): an
|
||||
* address of a post, a reel or a story is never taken for the account «p», «reel» or «stories».
|
||||
*/
|
||||
const RESERVED_PATHS = new Set(['p', 'reel', 'reels', 'tv', 'stories', 'explore', 'accounts', 'direct', 'about', 'legal', 'developer', 'web', 'challenge', 'emails', 'session']);
|
||||
|
||||
/** Opens the dialog; resolves to true when accounts were added. */
|
||||
export function openAddAccounts() {
|
||||
return dialog({
|
||||
@@ -26,75 +56,594 @@ export function openAddAccounts() {
|
||||
});
|
||||
}
|
||||
|
||||
/** Lowercase text without accents (the server folds the same way, SearchText.Fold). */
|
||||
export function fold(text) {
|
||||
return String(text || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
|
||||
}
|
||||
|
||||
/** True for an instagram.com address of a post, a reel, a story or another page that is not a profile. */
|
||||
export function isPageAddress(raw) {
|
||||
const address = /instagram\.com\/([^/?#\s]+)/i.exec(String(raw || ''));
|
||||
return Boolean(address && RESERVED_PATHS.has(address[1].toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* What the box asks for: a profile address becomes its user name, a leading @ goes, single spaces. The address of a
|
||||
* post or another page gives nothing: it is not a profile.
|
||||
*/
|
||||
export function searchTerm(raw) {
|
||||
let text = String(raw || '').trim();
|
||||
const address = /instagram\.com\/([^/?#\s]+)/i.exec(text);
|
||||
if (address) {
|
||||
if (RESERVED_PATHS.has(address[1].toLowerCase())) return '';
|
||||
text = address[1];
|
||||
}
|
||||
return fold(text.replace(/^@/, '')).replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
/** True for a text holding several names: a line break, a comma, a semicolon or more than one profile address. */
|
||||
export function isSeveralNames(raw) {
|
||||
const text = String(raw || '');
|
||||
return /[\r\n,;]/.test(text) || (text.match(/instagram\.com\//gi) || []).length > 1;
|
||||
}
|
||||
|
||||
/** One name per line, for /api/accounts/parse (which reads one per line). */
|
||||
export function namesPerLine(raw) {
|
||||
return String(raw || '')
|
||||
.split(/[\r\n,;]+/)
|
||||
.flatMap((part) => ((part.match(/instagram\.com\//gi) || []).length > 1 ? part.trim().split(/\s+/) : [part]))
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
/** A user name Instagram accepts (UsernameParser.IsValid). */
|
||||
function validName(name) {
|
||||
return /^[a-z0-9._]{1,30}$/.test(name) && !name.startsWith('.') && !name.endsWith('.') && !name.includes('..');
|
||||
}
|
||||
|
||||
/** A text Febe would type on the site (SearchText: letters, digits, «.», «_» and spaces, 2 to 40). */
|
||||
function likelyTypable(term) {
|
||||
return term.length >= 2 && term.length <= 40 && /^[a-z0-9._]+( [a-z0-9._]+)*$/.test(term);
|
||||
}
|
||||
|
||||
function randomClient() {
|
||||
const bytes = new Uint8Array(8);
|
||||
crypto.getRandomValues(bytes);
|
||||
return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
function photoOf(avatarKey, searchKey) {
|
||||
if (avatarKey) return `/api/thumbnails/${avatarKey}`;
|
||||
if (searchKey) return `/api/ricerca/foto/${searchKey}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
function build(close) {
|
||||
let tab = 'seguiti';
|
||||
const client = randomClient();
|
||||
const listId = uid('suggerimenti');
|
||||
const aborter = new AbortController();
|
||||
let closed = false;
|
||||
let following = null;
|
||||
let parsed = { names: [], problems: [] };
|
||||
const chosen = new Set();
|
||||
let byName = new Map();
|
||||
let byId = new Map();
|
||||
let view = 'scelti';
|
||||
let open = false;
|
||||
let options = [];
|
||||
let active = -1;
|
||||
let remote = null;
|
||||
let lastVersion = -1;
|
||||
let awaiting = false;
|
||||
let pollTimer = 0;
|
||||
let pollFrom = 0;
|
||||
let photosFrom = 0;
|
||||
let start = 'everything';
|
||||
let depth = 'all';
|
||||
let parsedNote = null;
|
||||
/** username → { username, displayName, photo, followed, isPrivate } */
|
||||
const chosen = new Map();
|
||||
/** One avatar node per place, name and photo, moved from one drawing to the next so a photo never flickers. */
|
||||
const faces = new Map();
|
||||
|
||||
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: the box and its list
|
||||
const box = h('input', {
|
||||
type: 'search', autocomplete: 'off', spellcheck: 'false', autocapitalize: 'off', maxlength: String(MAX_TEXT),
|
||||
placeholder: t('aggiungi.cerca'), 'aria-label': t('aggiungi.cercaEtichetta'),
|
||||
role: 'combobox', 'aria-expanded': 'false', 'aria-controls': listId, 'aria-autocomplete': 'list',
|
||||
});
|
||||
const suggestions = h('div.suggerimenti', { id: listId, role: 'listbox', 'aria-label': t('aggiungi.suggerimenti'), hidden: true });
|
||||
const announce = h('div.vh', { role: 'status', 'aria-live': 'polite' });
|
||||
const searchZone = h('div.cerca-zona', h('label.campo', icon('search'), box), suggestions, announce);
|
||||
|
||||
// ---------------------------------------------------------------------------- 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 chosenTitle = h('h3');
|
||||
const toFollowed = h('button.btn.collegamento', { type: 'button', onclick: () => setView(view === 'scelti' ? 'seguiti' : 'scelti') });
|
||||
const chosenList = h('div.elenco.scelti', { role: 'list', 'aria-label': t('aggiungi.daAggiungere') });
|
||||
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);
|
||||
|
||||
const allButton = h('button.btn.piccolo', { type: 'button' }, t('aggiungi.selezionaTutti'));
|
||||
const followedList = h('div.elenco', { role: 'group', 'aria-label': t('aggiungi.seguiti') });
|
||||
const progress = h('div.avanzamento', { role: 'status' });
|
||||
|
||||
const left = h('div.sinistra');
|
||||
|
||||
// ---------------------------------------------------------------------------- what Febe knows locally
|
||||
function present(p) {
|
||||
return p.accountId != null;
|
||||
}
|
||||
|
||||
function drawList() {
|
||||
if (!following) {
|
||||
fill(list, h('div.caricamento', t('comune.caricamento')));
|
||||
return;
|
||||
function known(username, instagramId) {
|
||||
return (instagramId && byId.get(instagramId)) || byName.get(username) || null;
|
||||
}
|
||||
|
||||
/** Followed profiles and accounts in Febe whose name or full name holds the text: prefix first, then alphabetical. */
|
||||
function localMatches(term) {
|
||||
if (!following || !term) return [];
|
||||
const dotted = term.replace(/ /g, '.');
|
||||
const joined = term.replace(/ /g, '');
|
||||
const found = [];
|
||||
for (const p of following.profiles) {
|
||||
const name = p.username;
|
||||
const full = fold(p.displayName);
|
||||
let rank = -1;
|
||||
if (name.startsWith(term) || name.startsWith(dotted) || name.startsWith(joined)) rank = 0;
|
||||
else if (full.startsWith(term) || full.split(/\s+/).some((w) => w.startsWith(term))) rank = 1;
|
||||
else if (name.includes(term) || name.includes(dotted) || name.includes(joined) || full.includes(term)) rank = 2;
|
||||
if (rank >= 0) found.push([rank, p]);
|
||||
}
|
||||
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;
|
||||
found.sort((a, b) => a[0] - b[0] || a[1].username.localeCompare(b[1].username));
|
||||
return found.slice(0, MAX_LOCAL).map(([, p]) => ({
|
||||
username: p.username,
|
||||
displayName: p.displayName,
|
||||
followed: p.followed !== false,
|
||||
isPrivate: p.isPrivate,
|
||||
accountId: p.accountId,
|
||||
instagramId: p.instagramId,
|
||||
isVerified: null,
|
||||
photo: photoOf(p.avatar, p.photo),
|
||||
}));
|
||||
}
|
||||
|
||||
/** The profiles of Instagram's answer that are not already among the local ones; the local ones take their photo. */
|
||||
function mergeRemote(local, term) {
|
||||
if (!remote || !remote.mine) return [];
|
||||
const current = !awaiting || remote.text === term;
|
||||
const extra = [];
|
||||
for (const hit of remote.hits) {
|
||||
// While a newer text is on its way, the older answer stays only where it still fits what is written.
|
||||
if (!current && !(hit.username.includes(term.replace(/ /g, '.')) || hit.username.includes(term.replace(/ /g, '')) || fold(hit.displayName).includes(term))) continue;
|
||||
const photo = photoOf(hit.avatar, hit.photoReady ? hit.photo : null);
|
||||
const same = local.find((r) => (r.instagramId && r.instagramId === hit.instagramId) || r.username === hit.username);
|
||||
if (same) {
|
||||
same.photo = same.photo || photo;
|
||||
same.displayName = same.displayName || hit.displayName;
|
||||
same.isVerified = hit.isVerified;
|
||||
continue;
|
||||
}
|
||||
const f = known(hit.username, hit.instagramId);
|
||||
extra.push({
|
||||
username: hit.username,
|
||||
displayName: hit.displayName || (f && f.displayName),
|
||||
followed: hit.followed || Boolean(f && f.followed !== false),
|
||||
isPrivate: hit.isPrivate != null ? hit.isPrivate : f ? f.isPrivate : null,
|
||||
accountId: hit.accountId != null ? hit.accountId : f ? f.accountId : null,
|
||||
instagramId: hit.instagramId,
|
||||
isVerified: hit.isVerified,
|
||||
photo: photo || (f ? photoOf(f.avatar, f.photo) : null),
|
||||
});
|
||||
}
|
||||
return extra;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- the list under the box
|
||||
function face(where, username, photo) {
|
||||
const key = `${where}|${username}|${photo || ''}`;
|
||||
let node = faces.get(key);
|
||||
if (node) return node;
|
||||
node = avatar(username, 'm');
|
||||
if (photo) {
|
||||
// The initials stay until the photo has arrived from Febe.
|
||||
const img = h('img', { src: photo, alt: '', decoding: 'async' });
|
||||
img.addEventListener('load', () => {
|
||||
node.textContent = '';
|
||||
node.append(img);
|
||||
node.classList.add('con-foto');
|
||||
}, { once: true });
|
||||
}
|
||||
faces.set(key, node);
|
||||
return node;
|
||||
}
|
||||
|
||||
function labelsOf(r) {
|
||||
return h('span.etichette',
|
||||
r.followed ? label(t('aggiungi.seguito'), '', 'user-check') : null,
|
||||
r.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null,
|
||||
present(r) ? label(t('aggiungi.giaPresente')) : null);
|
||||
}
|
||||
|
||||
function optionRow(r, index) {
|
||||
const isPresent = present(r);
|
||||
const isChosen = chosen.has(r.username);
|
||||
// The option itself says whether the profile is in «Da aggiungere» (aria-checked; aria-selected is the keyboard
|
||||
// cursor): the children of an option are presentational, so the button below is only for the mouse.
|
||||
const row = h(`div.opzione${isPresent ? '.presente' : ''}`, {
|
||||
id: `${listId}-${index}`, role: 'option', 'aria-selected': String(index === active),
|
||||
'aria-checked': isPresent ? null : String(isChosen),
|
||||
'aria-disabled': isPresent ? 'true' : null,
|
||||
onmousedown: (e) => e.preventDefault(),
|
||||
onclick: () => activate(index),
|
||||
},
|
||||
face('lista', r.username, r.photo),
|
||||
h('span.chi-nome',
|
||||
h('b', `@${r.username}`, r.isVerified ? h('span.verificato', { title: t('aggiungi.verificato'), 'aria-label': t('aggiungi.verificato') }, icon('circle-check', 's')) : null),
|
||||
r.displayName ? h('small', r.displayName) : null),
|
||||
labelsOf(r),
|
||||
isPresent ? null : h(`button.btn.piccolo${isChosen ? '.scelto' : ''}`, {
|
||||
type: 'button', tabindex: '-1', 'aria-hidden': 'true',
|
||||
onmousedown: (e) => e.preventDefault(),
|
||||
onclick: (e) => {
|
||||
e.stopPropagation();
|
||||
activate(index);
|
||||
},
|
||||
}, isChosen ? [icon('check', 's'), t('aggiungi.aggiunto')] : [icon('plus', 's'), t('aggiungi.aggiungiUno')]));
|
||||
return row;
|
||||
}
|
||||
|
||||
function actionRow(o, index) {
|
||||
return h('div.opzione.azione', {
|
||||
id: `${listId}-${index}`, role: 'option', 'aria-selected': String(index === active),
|
||||
onmousedown: (e) => e.preventDefault(),
|
||||
onclick: () => activate(index),
|
||||
},
|
||||
h('span.av.m.segnaposto', { 'aria-hidden': 'true' }, icon(o.action === 'nomi' ? 'users' : 'at-sign')),
|
||||
h('span.chi-nome', h('b', o.title), h('small', o.note)));
|
||||
}
|
||||
|
||||
/** The status line of the Instagram part: searching, waiting for the page, or why Instagram is not searched. */
|
||||
function remoteStatus(term, extraCount) {
|
||||
const driving = (engineState() && engineState().snapshot && engineState().snapshot.mode) === 'UserDriving';
|
||||
if (awaiting) {
|
||||
if (!likelyTypable(term)) return null;
|
||||
return driving ? { text: t('aggiungi.alVolante'), kind: 'info' } : { text: t('aggiungi.cercoSuInstagram'), kind: 'lavoro' };
|
||||
}
|
||||
if (!remote) return null;
|
||||
if (!remote.mine) return { text: t('aggiungi.altraFinestra'), kind: 'info' };
|
||||
switch (remote.state) {
|
||||
case 'idle':
|
||||
return null;
|
||||
case 'cerca':
|
||||
return { text: t('aggiungi.cercoSuInstagram'), kind: 'lavoro' };
|
||||
case 'attesa':
|
||||
return { text: remote.message || t('aggiungi.attesa'), kind: 'lavoro' };
|
||||
case 'pronta':
|
||||
return extraCount ? null : { text: t('aggiungi.nessunAltro'), kind: 'info' };
|
||||
case 'non-possibile':
|
||||
return { text: remote.message || t('aggiungi.alVolante'), kind: 'info' };
|
||||
case 'ferma':
|
||||
case 'errore':
|
||||
case 'rifiutata':
|
||||
return { text: remote.message || t('comune.errore'), kind: 'allarme' };
|
||||
default:
|
||||
return remote.message ? { text: remote.message, kind: 'info' } : null;
|
||||
}
|
||||
}
|
||||
|
||||
function drawSuggestions() {
|
||||
const term = searchTerm(box.value);
|
||||
const several = isSeveralNames(box.value);
|
||||
const pageAddress = !several && isPageAddress(box.value);
|
||||
const keep = active >= 0 && options[active] ? options[active].username || options[active].action : null;
|
||||
options = [];
|
||||
const parts = [];
|
||||
if (!several && term) {
|
||||
const local = localMatches(term);
|
||||
const extra = mergeRemote(local, term);
|
||||
if (local.length) {
|
||||
const titleId = `${listId}-locali`;
|
||||
parts.push(h('div', { role: 'group', 'aria-labelledby': titleId },
|
||||
h('div.sezione-titolo', { id: titleId, 'aria-hidden': 'true' }, t('aggiungi.traSeguiti')),
|
||||
local.map((r) => {
|
||||
options.push(r);
|
||||
return optionRow(r, options.length - 1);
|
||||
})));
|
||||
}
|
||||
const status = remoteStatus(term, extra.length);
|
||||
if (extra.length || status) {
|
||||
const titleId = `${listId}-instagram`;
|
||||
const shown = remote && remote.mine && remote.text ? remote.text : term;
|
||||
parts.push(h('div', { role: 'group', 'aria-labelledby': titleId },
|
||||
h('div.sezione-titolo', { id: titleId, 'aria-hidden': 'true' }, t('aggiungi.daInstagram'), h('span.per', t('aggiungi.perTesto', { testo: shown }))),
|
||||
// The status is read out by the live region (announce): inside the list it is only seen.
|
||||
status ? h(`div.stato-remoto.${status.kind}`, { 'aria-hidden': 'true' }, icon(status.kind === 'lavoro' ? 'hourglass' : status.kind === 'allarme' ? 'triangle-alert' : 'info', 's'), h('span', status.text)) : null,
|
||||
extra.map((r) => {
|
||||
options.push(r);
|
||||
return optionRow(r, options.length - 1);
|
||||
})));
|
||||
}
|
||||
if (validName(term) && !options.some((r) => r.username === term)) {
|
||||
options.push({ action: 'nome', name: term, title: t('aggiungi.perNomeUtente', { nome: term }), note: t('aggiungi.perNomeSpiega') });
|
||||
parts.push(actionRow(options[options.length - 1], options.length - 1));
|
||||
}
|
||||
if (!local.length && following && following.profiles.length && !extra.length) {
|
||||
// Seen, not an option: hidden from the list's structure (the live region says how many were found).
|
||||
parts.unshift(h('div', { 'aria-hidden': 'true' },
|
||||
h('div.sezione-titolo', t('aggiungi.traSeguiti')),
|
||||
h('div.stato-remoto.info', icon('info', 's'), h('span', t('aggiungi.nessunLocale')))));
|
||||
}
|
||||
announce.textContent = status ? status.text : t('aggiungi.trovati', { n: options.filter((o) => !o.action).length });
|
||||
} else if (pageAddress) {
|
||||
parts.push(h('div', { 'aria-hidden': 'true' }, h('div.stato-remoto.info', icon('info', 's'), h('span', t('aggiungi.nonProfilo')))));
|
||||
announce.textContent = t('aggiungi.nonProfilo');
|
||||
} else if (several) {
|
||||
options.push({ action: 'nomi', title: t('aggiungi.piuNomi'), note: t('aggiungi.piuNomiSpiega') });
|
||||
parts.push(actionRow(options[0], 0));
|
||||
announce.textContent = t('aggiungi.piuNomi');
|
||||
}
|
||||
active = keep ? options.findIndex((o) => (o.username || o.action) === keep) : -1;
|
||||
fill(suggestions, parts);
|
||||
setOpen(view === 'scelti' && document.activeElement === box && options.length + parts.length > 0);
|
||||
markActive();
|
||||
}
|
||||
|
||||
function setOpen(value) {
|
||||
open = value;
|
||||
suggestions.hidden = !value;
|
||||
box.setAttribute('aria-expanded', String(value));
|
||||
if (!value) {
|
||||
active = -1;
|
||||
box.removeAttribute('aria-activedescendant');
|
||||
}
|
||||
}
|
||||
|
||||
function markActive() {
|
||||
const rows = [...suggestions.querySelectorAll('[role=option]')];
|
||||
rows.forEach((row, i) => row.setAttribute('aria-selected', String(i === active)));
|
||||
if (active >= 0 && rows[active]) {
|
||||
box.setAttribute('aria-activedescendant', rows[active].id);
|
||||
rows[active].scrollIntoView({ block: 'nearest' });
|
||||
} else {
|
||||
box.removeAttribute('aria-activedescendant');
|
||||
}
|
||||
}
|
||||
|
||||
function move(step) {
|
||||
if (!open) {
|
||||
drawSuggestions();
|
||||
if (!open) return;
|
||||
}
|
||||
if (!options.length) return;
|
||||
active = active < 0 ? (step > 0 ? 0 : options.length - 1) : active + step;
|
||||
if (active >= options.length || active < 0) active = -1;
|
||||
markActive();
|
||||
}
|
||||
|
||||
function activate(index) {
|
||||
const o = options[index];
|
||||
if (!o) return;
|
||||
active = index;
|
||||
if (o.action === 'nomi') {
|
||||
addNames(box.value, true);
|
||||
return;
|
||||
}
|
||||
if (o.action === 'nome') {
|
||||
addNames(o.name, true);
|
||||
return;
|
||||
}
|
||||
if (present(o)) return;
|
||||
if (chosen.has(o.username)) chosen.delete(o.username);
|
||||
else chosen.set(o.username, { username: o.username, displayName: o.displayName, photo: o.photo, followed: o.followed, isPrivate: o.isPrivate });
|
||||
drawChosen();
|
||||
drawSuggestions();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- talking to Febe
|
||||
const send = later(async () => {
|
||||
if (closed) return;
|
||||
pollFrom = Date.now();
|
||||
photosFrom = 0;
|
||||
let answer;
|
||||
try {
|
||||
answer = await api('/api/ricerca', { method: 'POST', body: { client, text: box.value.slice(0, MAX_TEXT) }, signal: aborter.signal });
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') return;
|
||||
awaiting = false;
|
||||
remote = { version: lastVersion, mine: true, text: '', state: 'errore', message: error.message, hits: [] };
|
||||
drawSuggestions();
|
||||
return;
|
||||
}
|
||||
accept(answer, true);
|
||||
}, DEBOUNCE_MS);
|
||||
|
||||
function accept(answer, fromSend) {
|
||||
if (closed || !answer || answer.version < lastVersion) {
|
||||
schedule();
|
||||
return;
|
||||
}
|
||||
lastVersion = answer.version;
|
||||
remote = answer;
|
||||
if (fromSend) awaiting = false;
|
||||
drawSuggestions();
|
||||
schedule();
|
||||
}
|
||||
|
||||
function needsPoll() {
|
||||
if (!remote || !remote.mine || closed) return false;
|
||||
if (WORKING.includes(remote.state) || RESUMING.includes(remote.state)) {
|
||||
photosFrom = 0;
|
||||
return true;
|
||||
}
|
||||
if (!remote.hits.some((hit) => !hit.photoReady && !hit.avatar)) return false;
|
||||
photosFrom = photosFrom || Date.now();
|
||||
return Date.now() - photosFrom < PHOTOS_FOR_MS;
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = 0;
|
||||
if (awaiting || !needsPoll()) return;
|
||||
let wait = Date.now() - pollFrom < FAST_FOR_MS ? FAST_POLL_MS : SLOW_POLL_MS;
|
||||
if (RESUMING.includes(remote.state)) {
|
||||
// Febe resumes the search by itself: slowly, and right when the stop says it ends (retryAfter).
|
||||
wait = SLOW_POLL_MS;
|
||||
if (remote.retryAfter) wait = Math.max(FAST_POLL_MS, Math.min(wait, remote.retryAfter - Date.now() + 250));
|
||||
}
|
||||
pollTimer = setTimeout(poll, wait);
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
pollTimer = 0;
|
||||
try {
|
||||
accept(await api(`/api/ricerca?client=${client}`, { signal: aborter.signal }), false);
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') return;
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
|
||||
function onInput() {
|
||||
if (view === 'seguiti') {
|
||||
drawFollowed();
|
||||
return;
|
||||
}
|
||||
awaiting = !isSeveralNames(box.value);
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = 0;
|
||||
drawSuggestions();
|
||||
if (isSeveralNames(box.value)) {
|
||||
send.cancel();
|
||||
return;
|
||||
}
|
||||
send();
|
||||
}
|
||||
|
||||
async function addNames(raw, clearBox) {
|
||||
const text = namesPerLine(raw);
|
||||
if (!text) return;
|
||||
let parsed;
|
||||
try {
|
||||
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text }, signal: aborter.signal });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
}
|
||||
let ready = 0;
|
||||
let already = 0;
|
||||
for (const n of parsed.names) {
|
||||
if (n.present) {
|
||||
already += 1;
|
||||
continue;
|
||||
}
|
||||
ready += 1;
|
||||
const f = byName.get(n.username);
|
||||
chosen.set(n.username, {
|
||||
username: n.username,
|
||||
displayName: n.displayName || (f && f.displayName),
|
||||
photo: f ? photoOf(f.avatar, f.photo) : null,
|
||||
followed: n.followed,
|
||||
isPrivate: n.isPrivate,
|
||||
});
|
||||
}
|
||||
parsedNote = parsed.names.length > 1 || parsed.problems.length || already ? { ready, already, problems: parsed.problems } : null;
|
||||
if (clearBox) {
|
||||
box.value = '';
|
||||
awaiting = false;
|
||||
send();
|
||||
}
|
||||
drawChosen();
|
||||
drawSuggestions();
|
||||
// Pasted names went to «Da aggiungere»: the list under the box gives way, so the result shows.
|
||||
if (!clearBox) setOpen(false);
|
||||
if (view === 'seguiti') {
|
||||
// «Da aggiungere» is not on screen in this view: the check boxes show the names, and a note says where they went.
|
||||
drawFollowed();
|
||||
if (ready) toast(t('aggiungi.incollatiSeguiti', { n: ready }));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- left: «Da aggiungere»
|
||||
function drawChosen() {
|
||||
fill(chosenTitle, t('aggiungi.daAggiungere'), chosen.size ? h('i', number(chosen.size)) : null);
|
||||
if (!chosen.size) {
|
||||
fill(chosenList, h('div.vuoto-scelti', { role: 'listitem' }, icon('search', 's'), h('span', t('aggiungi.sceltiNessuno'))));
|
||||
} else {
|
||||
fill(chosenList, [...chosen.values()].map((c) => h('div.voce.scelto', { role: 'listitem' },
|
||||
face('scelti', c.username, c.photo),
|
||||
h('span.chi-nome', h('b', `@${c.username}`), c.displayName ? h('small', c.displayName) : null),
|
||||
h('span.etichette', c.followed ? label(t('aggiungi.seguito'), '', 'user-check') : null, c.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
|
||||
h('button.btn.nudo.solo', {
|
||||
type: 'button', 'aria-label': t('aggiungi.togli', { nome: c.username }), title: t('aggiungi.togli', { nome: c.username }),
|
||||
onclick: () => {
|
||||
chosen.delete(c.username);
|
||||
drawChosen();
|
||||
box.focus();
|
||||
},
|
||||
}, icon('x', 's')))));
|
||||
}
|
||||
if (parsedNote) {
|
||||
fill(parsedInfo, t('aggiungi.riconosciuti', { n: parsedNote.ready }), parsedNote.already ? ` · ${t('aggiungi.presenti', { n: parsedNote.already })}` : '');
|
||||
fill(problems, parsedNote.problems.map((p) => h('div', t('aggiungi.riga', { n: p.line, motivo: `«${p.text}»: ${p.reason}` }))));
|
||||
} else {
|
||||
fill(parsedInfo);
|
||||
fill(problems);
|
||||
}
|
||||
drawRight();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- left: all followed profiles
|
||||
function followedShown() {
|
||||
const term = searchTerm(box.value);
|
||||
return following.profiles.filter((p) => p.followed !== false && (!term || p.username.includes(term) || fold(p.displayName).includes(term)));
|
||||
}
|
||||
|
||||
function drawFollowed() {
|
||||
if (!following) {
|
||||
fill(followedList, h('div.caricamento', t('comune.caricamento')));
|
||||
return;
|
||||
}
|
||||
const shown = followedShown();
|
||||
if (!shown.length) {
|
||||
fill(followedList, h('div.caricamento', following.total ? t('aggiungi.nessunSeguito') : t('aggiungi.maiLetto')));
|
||||
return;
|
||||
}
|
||||
fill(followedList, shown.map((p) => {
|
||||
const isPresent = present(p);
|
||||
const item = checkbox({
|
||||
checked: isPresent || chosen.has(p.username),
|
||||
disabled: isPresent,
|
||||
labelNode: h('span', { style: { display: 'contents' } },
|
||||
face('seguiti', p.username, photoOf(p.avatar, p.photo)),
|
||||
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.set(p.username, { username: p.username, displayName: p.displayName, photo: photoOf(p.avatar, p.photo), followed: true, isPrivate: p.isPrivate });
|
||||
else chosen.delete(p.username);
|
||||
drawChosen();
|
||||
},
|
||||
});
|
||||
item.classList.toggle('presente', isPresent);
|
||||
return item;
|
||||
}));
|
||||
}
|
||||
|
||||
allButton.addEventListener('click', () => {
|
||||
if (!following) return;
|
||||
const shown = followedShown().filter((p) => !present(p));
|
||||
const all = shown.every((p) => chosen.has(p.username));
|
||||
for (const p of shown) {
|
||||
if (all) chosen.delete(p.username);
|
||||
else chosen.set(p.username, { username: p.username, displayName: p.displayName, photo: photoOf(p.avatar, p.photo), followed: true, isPrivate: p.isPrivate });
|
||||
}
|
||||
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
|
||||
drawFollowed();
|
||||
drawChosen();
|
||||
});
|
||||
|
||||
function drawProgress() {
|
||||
fill(toFollowed, view === 'seguiti' ? t('aggiungi.chiudiSeguiti') : t('aggiungi.scegliTraSeguiti', { n: following ? following.total : 0 }));
|
||||
if (!following) return;
|
||||
progress.hidden = !following.inProgress;
|
||||
fill(progress, following.inProgress
|
||||
@@ -104,65 +653,111 @@ function build(close) {
|
||||
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);
|
||||
}
|
||||
|
||||
function setFollowing(value) {
|
||||
following = value;
|
||||
byName = new Map(following.profiles.map((p) => [p.username, p]));
|
||||
byId = new Map(following.profiles.filter((p) => p.instagramId).map((p) => [p.instagramId, p]));
|
||||
}
|
||||
|
||||
async function loadFollowing() {
|
||||
try {
|
||||
following = await api('/api/following');
|
||||
setFollowing(await api('/api/following', { signal: aborter.signal }));
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') return;
|
||||
showError(error);
|
||||
following = { profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 };
|
||||
setFollowing({ profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 });
|
||||
}
|
||||
drawList();
|
||||
drawProgress();
|
||||
drawFollowed();
|
||||
drawRight();
|
||||
if (box.value) drawSuggestions();
|
||||
}
|
||||
|
||||
async function reread() {
|
||||
try {
|
||||
following = await api('/api/following/read', { method: 'POST' });
|
||||
setFollowing(await api('/api/following/read', { method: 'POST' }));
|
||||
drawProgress();
|
||||
drawList();
|
||||
drawFollowed();
|
||||
} 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);
|
||||
function setView(value) {
|
||||
view = value;
|
||||
if (value === 'seguiti') {
|
||||
setOpen(false);
|
||||
send.cancel();
|
||||
awaiting = false;
|
||||
fill(left, searchZone,
|
||||
h('div.scelti-testa', h('h3', t('aggiungi.seguiti')), allButton, toFollowed),
|
||||
followedList, progress);
|
||||
drawFollowed();
|
||||
endRemote();
|
||||
} else {
|
||||
fill(left, searchZone,
|
||||
h('div.scelti-testa', chosenTitle, toFollowed),
|
||||
chosenList, parsedInfo, problems);
|
||||
drawChosen();
|
||||
}
|
||||
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
|
||||
drawList();
|
||||
drawRight();
|
||||
});
|
||||
search.addEventListener('input', later(drawList, 120));
|
||||
drawProgress();
|
||||
box.placeholder = value === 'seguiti' ? t('aggiungi.filtraSeguiti') : t('aggiungi.cerca');
|
||||
box.focus();
|
||||
if (value === 'scelti' && box.value) onInput();
|
||||
}
|
||||
|
||||
const parse = later(async () => {
|
||||
try {
|
||||
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text: area.value } });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
/** The window no longer searches on Instagram (closed, or the whole list is open). */
|
||||
function endRemote() {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = 0;
|
||||
remote = null;
|
||||
lastVersion = -1;
|
||||
api('/api/ricerca/fine', { method: 'POST', body: { client }, keepalive: true }).catch(() => {});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- the box
|
||||
box.addEventListener('input', onInput);
|
||||
box.addEventListener('focus', () => {
|
||||
if (view === 'scelti' && box.value) drawSuggestions();
|
||||
});
|
||||
box.addEventListener('blur', () => setOpen(false));
|
||||
// A press on the list (its scroll bar, a title) keeps the focus in the box, so the list stays open.
|
||||
suggestions.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
box.addEventListener('paste', (e) => {
|
||||
const text = e.clipboardData ? e.clipboardData.getData('text') : '';
|
||||
if (!isSeveralNames(text)) return; // one name or address: it goes in the box and is searched
|
||||
e.preventDefault();
|
||||
addNames(text, false);
|
||||
});
|
||||
box.addEventListener('keydown', (e) => {
|
||||
if (view !== 'scelti') return;
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
move(e.key === 'ArrowDown' ? 1 : -1);
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (open && active >= 0) {
|
||||
activate(active);
|
||||
return;
|
||||
}
|
||||
if (isSeveralNames(box.value)) {
|
||||
addNames(box.value, true);
|
||||
return;
|
||||
}
|
||||
const name = searchTerm(box.value);
|
||||
const exact = options.findIndex((o) => o.username === name);
|
||||
if (exact >= 0) activate(exact);
|
||||
else if (validName(name)) addNames(name, true);
|
||||
} else if (e.key === 'Tab') {
|
||||
setOpen(false);
|
||||
}
|
||||
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);
|
||||
return [...chosen.keys()];
|
||||
}
|
||||
|
||||
function drawRight() {
|
||||
@@ -208,26 +803,37 @@ function build(close) {
|
||||
}
|
||||
}
|
||||
|
||||
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'));
|
||||
let engineMode = null;
|
||||
const stopEngine = onEngine((state) => {
|
||||
if (open) drawSuggestions();
|
||||
const mode = state && state.snapshot ? state.snapshot.mode : null;
|
||||
const changed = mode !== engineMode;
|
||||
engineMode = mode;
|
||||
// Alberto let go of the browser, «Riprendi»: the search resumes by itself, the window asks at once.
|
||||
if (changed && remote && remote.mine && RESUMING.includes(remote.state) && !awaiting && !closed) {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = setTimeout(poll, FAST_POLL_MS);
|
||||
}
|
||||
});
|
||||
|
||||
fill(left, followedPanel);
|
||||
drawList();
|
||||
box.setAttribute('autofocus', '');
|
||||
setView('scelti');
|
||||
drawRight();
|
||||
loadFollowing();
|
||||
return {
|
||||
body: h('div', { style: { display: 'contents' } }, tabs, h('div.corpo-dialogo', left, right)),
|
||||
body: 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)),
|
||||
onEscape: () => {
|
||||
if (!open) return false;
|
||||
setOpen(false);
|
||||
return true;
|
||||
},
|
||||
onClose: () => {
|
||||
closed = true;
|
||||
send.cancel();
|
||||
stopEngine();
|
||||
endRemote();
|
||||
aborter.abort();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -313,9 +313,36 @@
|
||||
},
|
||||
"aggiungi": {
|
||||
"titolo": "Aggiungi account",
|
||||
"seguiti": "Dai profili che segui",
|
||||
"perNome": "Per nome utente",
|
||||
"cerca": "Cerca tra i profili che segui",
|
||||
"seguiti": "Profili che segui",
|
||||
"cerca": "Cerca un profilo per nome o nome utente, o incolla più nomi",
|
||||
"cercaEtichetta": "Cerca un profilo da aggiungere",
|
||||
"filtraSeguiti": "Filtra i profili che segui",
|
||||
"suggerimenti": "Profili trovati",
|
||||
"traSeguiti": "Profili che segui e account in Febe",
|
||||
"nessunLocale": "Nessun profilo che segui ha questo nome.",
|
||||
"nonProfilo": "È l'indirizzo di un post, di un reel o di un'altra pagina, non di un profilo: incolla l'indirizzo del profilo (instagram.com/nome.utente).",
|
||||
"incollatiSeguiti": "1 nome aggiunto a «Da aggiungere»|{n} nomi aggiunti a «Da aggiungere»",
|
||||
"daInstagram": "Da Instagram",
|
||||
"perTesto": "per «{testo}»",
|
||||
"cercoSuInstagram": "Cerco su Instagram…",
|
||||
"attesa": "In attesa del turno: i risultati di Instagram arrivano appena il browser di Febe è libero.",
|
||||
"nessunAltro": "Su Instagram nessun altro profilo oltre a questi.",
|
||||
"alVolante": "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito. Intanto vedi i profili che segui.",
|
||||
"altraFinestra": "La ricerca su Instagram è in uso da un'altra finestra di Febe: qui vedi solo i profili che segui.",
|
||||
"trovati": "1 profilo trovato|{n} profili trovati",
|
||||
"seguito": "Seguito",
|
||||
"verificato": "Profilo verificato",
|
||||
"aggiungiUno": "Aggiungi",
|
||||
"aggiunto": "Aggiunto",
|
||||
"perNomeUtente": "Aggiungi @{nome} per nome utente",
|
||||
"perNomeSpiega": "Anche se non compare fra i risultati: Febe lo controlla alla prossima sessione",
|
||||
"piuNomi": "Aggiungi all'elenco i nomi scritti",
|
||||
"piuNomiSpiega": "Più nomi utente o indirizzi di profilo, separati da virgole",
|
||||
"daAggiungere": "Da aggiungere",
|
||||
"sceltiNessuno": "Cerca un profilo qui sopra e premi «Aggiungi», oppure incolla più nomi utente o indirizzi di profilo: uno per riga o separati da virgole.",
|
||||
"togli": "Togli @{nome} dall'elenco",
|
||||
"scegliTraSeguiti": "Scegli fra tutti i profili che segui ({n})",
|
||||
"chiudiSeguiti": "Torna a «Da aggiungere»",
|
||||
"selezionaTutti": "Seleziona tutti",
|
||||
"togliTutti": "Togli tutti",
|
||||
"giaPresente": "Già in Febe",
|
||||
@@ -328,11 +355,9 @@
|
||||
"inAttesa": "Lettura chiesta: comincia alla prossima sessione",
|
||||
"rilettura": "Febe rilegge l'elenco a ritmo umano, dentro i tetti: può servire più di una sessione.",
|
||||
"nessunSeguito": "Nessun profilo con questo nome nell'elenco.",
|
||||
"area": "Nomi utente o indirizzi dei profili",
|
||||
"areaAiuto": "Uno per riga: nome.utente, @nome.utente oppure instagram.com/nome.utente",
|
||||
"riconosciuti": "1 nome pronto|{n} nomi pronti",
|
||||
"presenti": "1 già in Febe|{n} già in Febe",
|
||||
"riga": "Riga {n}: {motivo}",
|
||||
"riga": "{n}° nome: {motivo}",
|
||||
"perScelti": "Per l'account scelto|Per i {n} account scelti",
|
||||
"perNessuno": "Scegli gli account a sinistra",
|
||||
"potraiCambiare": "Potrai cambiare tutto dopo, account per account.",
|
||||
|
||||
Reference in new issue
Block a user