D1, quarta parte: «Raggruppa i post» o «Tutte le foto» in Libreria e scheda account

Un post con più foto era una tessera sola: per vederle tutte bisognava aprirlo.
Ora un interruttore nella riga degli strumenti (Libreria e Contenuti
dell'account, non «In evidenza») passa a una tessera per file, video dei
caroselli compresi, con la posizione «2/4» sulla tessera; la scelta resta nel
browser, una per pagina, e il predefinito è raggruppato (§4.6).

- API: /api/library e /api/library/days accettano mode=files; il cursore
  diventa «ms.elemento.posizione», i giorni contano file e il totale dice anche
  quanti file. Le finestre restano a chiavi sull'indice di pubblicazione; per i
  conteggi un indice ix_media_entry_files (entry_id, state, kind) nella
  migrazione 0002 non ancora unita. Prova di scala a 200.000 elementi: finestre
  6-11 ms, conteggi 0,2-0,3 s.
- Visualizzatore: si apre sul file della tessera e va di file in file, anche da
  un elemento al successivo («Libreria, file 12 di 30.340»).
- Selezione di file; elenco CSV ed «Elimina» lavorano sugli elementi interi e
  lo dicono («3 file scelti appartengono a 2 elementi: elimino gli elementi
  interi, 9 file»). «Copia in…» non è in questo ramo.
- Dimostrazione: alcune serie hanno un video in seconda posizione, scelto
  dall'identificativo senza toccare la sequenza casuale.
- Prove di archivio, API, dimostrazione e interfaccia (queste ultime con
  Chromium, solo nella CI); guida e decisioni aggiornate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 16:40:07 +01:00
1 parent 34fe5e9073
commit 30e159cbd4
23 files changed
+1126 -130

No files matched your search

+5
View File
@@ -553,3 +553,8 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-25 | La voce Dashboard della barra laterale ha un'icona sua, `layout-dashboard` (quattro riquadri, disegnata in casa sulla griglia di 24); `activity` resta fra le icone | §10.3 «Schermate della tappa D1»: «prima voce, con la sua icona»; l'impulso di `activity` diceva Attività |
| 2026-11-25 | Miniature della cronologia: `/api/activity/arrived` senza `account` dà ciò che è arrivato di tutti gli account nel tempo della riga (le righe del Giro dei seguiti, che salva post di più account), sempre e solo elementi scaricati da Febe (mai gli importati); indice `ix_entry_discovered` (`discovered_at`) aggiunto alla migrazione 0002, non ancora unita, così la domanda legge solo le righe di quei minuti | §7.9: «le righe che hanno salvato qualcosa» mostrano le miniature, anche il Giro; un'importazione nello stesso momento non è uno scaricamento; libreria da 200.000 elementi |
| 2026-11-25 | Guida: la pagina «Attività e arresti» diventa «Dashboard e arresti» (`docs/guida/Dashboard-e-arresti.md`), con i collegamenti delle altre pagine | §7.9: la pagina si chiama Dashboard; il wiki si pubblica a mano: lì la pagina vecchia va tolta o lasciata con un rimando |
| 2026-11-25 | «Tutte le foto»: una tessera per ogni file **presente in libreria** (scaricato o importato), video compresi; un file ancora da scaricare, fallito o saltato non ha tessera, e la posizione «2/4» resta quella nella serie dell'elemento (il 4 è il numero dei suoi file, come sulla tessera raggruppata). Con «Foto» e «Video» si vedono solo i file di quel tipo dei post. L'API è la stessa con `mode=files`: le finestre vanno avanti con il cursore `ms.elemento.posizione`, `/api/library/days` conta i file per giorno e dice anche `files`, i totali restano elementi | §4.6: «una tessera per file»; una tessera di un file che non c'è non avrebbe nulla da mostrare; un video dentro «Foto» confonderebbe il filtro. Il titolo dice entrambi («61.034 file in 48.212 elementi di 38 account»), §4.3: i contatori contano elementi |
| 2026-11-25 | Finestre di «Tutte le foto»: le chiavi degli elementi vengono dalla stessa scansione a chiavi dell'indice di pubblicazione del mosaico raggruppato, poi i loro file si leggono per chiave; i conteggi per giorno e il totale dei file leggono i file di tutta la libreria in un passaggio sul nuovo indice `ix_media_entry_files (entry_id, state, kind)`, aggiunto alla migrazione 0002 (non ancora unita), e con un filtro sugli account li contano elemento per elemento. Per i conteggi «Foto» e «Video» valgono come «Post» (il tipo del file decide già). Il filtro «Post» usa `+e.kind` come «Tutto» | Prova di scala con 200.000 elementi: finestre 6-11 ms come quelle raggruppate; un conteggio per elemento costava 1,3-2,3 s, un passaggio sull'indice 0,2-0,3 s; senza `+` il filtro «Post» passava dall'indice del tipo e leggeva la riga di ogni post per lo stato. Una base già portata a v2 da una build precedente di D1 non riceve l'indice: le domande funzionano, solo più lente |
| 2026-11-25 | Selezione con «Tutte le foto»: si scelgono file (la chiave della tessera è il file); l'elenco CSV ed «Elimina» lavorano sugli elementi a cui appartengono, e barra e conferma lo dicono («3 file scelti, di 2 elementi», «3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»); anche «Elimina» del visualizzatore elimina l'elemento intero. «Copia in…» e «Fotogrammi…» non sono in questo ramo: quando arrivano (E2, E3) lavorano sui file scelti | §4.6: eliminare resta per elemento, per non lasciare post a metà; «Copia in…» di §4.10 lavora sui file |
| 2026-11-25 | La scelta «Raggruppa i post» / «Tutte le foto» sta nella memoria locale del browser (`febe.mosaico.libreria`, `febe.mosaico.account`, lette e scritte in un `try` da `local`); qualunque altro valore, o nessuna memoria, vale «Raggruppa i post». Nella scheda account l'interruttore manca in «In evidenza» (disegnata per raccolta) e le linguette contano elementi. Nella Libreria l'interruttore mostra solo le icone sotto i 1680 px di finestra, nella scheda account sotto i 1000 px | §4.6; la riga degli strumenti della Libreria a 1440 px non ha posto per due voci con il testo; nome e suggerimento restano sui pulsanti |
| 2026-11-25 | Dimostrazione: circa una serie di tre file o più su cinque ha un video in seconda posizione, deciso dall'identificativo dell'elemento (durata e peso compresi) e non dalla sequenza casuale, così il resto del mondo della dimostrazione resta com'era | «Tutte le foto» va provata anche con i video dentro un carosello; le prove della dimostrazione contano sugli stessi dati |
+6
View File
@@ -114,6 +114,12 @@ risulta «Non raggiungibile»: puoi indicare il nuovo nome.
Tre linguette: **Contenuti** (Post, Storie, In evidenza raggruppati per raccolta, Taggati, e Profilo se ci sono più
foto del profilo), **Impostazioni** e **Cronologia** (i controlli con il loro esito).
Nei Contenuti c'è lo stesso interruttore della Libreria, **«Raggruppa i post» / «Tutte le foto»** (vedi
[Libreria](Libreria)): una tessera per elemento oppure una per file, con la posizione nella serie («2/4») e la riga del
giorno che conta i file. La scelta vale per le schede di tutti gli account ed è separata da quella della Libreria. In
«In evidenza», ordinata per raccolta, l'interruttore non c'è: ogni contenuto di una raccolta è già un file solo, o quasi.
I numeri dell'intestazione e delle linguette restano elementi.
### Impostazioni dell'account
- **Tieni aggiornato:** con «no» Febe fa un solo scaricamento, poi mette l'account in pausa.
+24 -1
View File
@@ -16,10 +16,28 @@ anche con centinaia di migliaia di elementi: carica a finestre e le miniature si
I nuovi elementi compaiono in cima senza spostare ciò che stai guardando.
## «Raggruppa i post» o «Tutte le foto»
Accanto al cursore della grandezza c'è un interruttore a due voci (nelle finestre meno larghe solo le due icone, con il
nome nel suggerimento):
- **Raggruppa i post** (il predefinito): una tessera per elemento. Un post con quattro foto è una tessera sola, con
il numero dei file in alto a destra.
- **Tutte le foto**: una tessera per ogni file della libreria, video compresi, nello stesso ordine (la data
dell'elemento, poi la posizione nella serie). È utile quando un post ha più foto. La tessera di un file di una serie
dice la sua posizione («2/4»); la riga del giorno conta i file («23 file nuovi») e il titolo dice file ed elementi
(«61.034 file in 48.212 elementi di 38 account»). Con «Foto» e «Video» si vedono solo le foto, o solo i video, dei
post. Un file non ancora scaricato non ha tessera.
Filtri, ricerca e caricamento a finestre funzionano allo stesso modo nei due modi. Febe ricorda la scelta in questo
browser, una per la Libreria e una per le schede degli account (come il tema); in una finestra privata, o se il
browser non conserva nulla, si riparte da «Raggruppa i post».
## Il visualizzatore
Un clic su una tessera apre l'elemento a tutta finestra: frecce (anche da tastiera) per scorrere, Esc per chiudere, i
video partono senza audio. A lato: la serie dei file, didascalia, dati (data, codice, autore, raccolte), file
video partono senza audio. Con «Tutte le foto» si apre sul file della tessera, le frecce vanno di file in file e in alto
si legge «Libreria, file 12 di 61.034». A lato: la serie dei file, didascalia, dati (data, codice, autore, raccolte), file
(nome, dimensioni, peso, cartella) e provenienza. Azioni:
- **Mostra nella cartella** (Windows) oppure **Scarica** il file (dal browser, in Docker);
@@ -46,6 +64,11 @@ resta. Un file si elimina o si sostituisce solo per una scelta tua.
«Seleziona» attiva la scelta delle tessere; nella barra in basso: **Esporta l'elenco** degli elementi scelti oppure
**Elimina** (con la stessa conferma di sopra). «Fine» chiude la selezione.
Con «Tutte le foto» si scelgono i file, ma l'elenco CSV ed «Elimina» lavorano sugli **elementi interi** a cui
appartengono: la barra lo dice («3 file scelti, di 2 elementi», «Elimina 2 elementi») e anche la conferma («3 file
scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»). Un solo file di un post non si elimina: si
elimina il post. Lo stesso vale per «Elimina dalla libreria» nel visualizzatore.
## Esportare l'elenco in CSV
Il pulsante con l'icona del documento nella riga degli strumenti, **«Esporta l'elenco»**, scarica in un file CSV
+21
View File
@@ -168,6 +168,27 @@ con il programma delle schermate. Differenze dai mockup 06, 11 e 14 da cui la pa
numeri vengono dal mondo dimostrativo (alcune righe «Scaricato» della dimostrazione non hanno miniature perché nel
mondo finto i loro elementi non sono stati scoperti nel tempo di quella riga).
### «Raggruppa i post» / «Tutte le foto» (tappa D1, issue #59, dal 25 novembre 2026)
L'interruttore di §4.6 (§10.3 «Schermate della tappa D1») è composto dai mockup 01 e 12, che non lo hanno. Le
schermate `01-*` e `12-*` della tabella mostrano «Raggruppa i post», il predefinito, e non sono state rifatte; una
schermata con «Tutte le foto» non c'è ancora. **Non confrontato** con il programma delle schermate né nel browser di
prova: le prove dell'interfaccia (`LibraryModeInterfaceTests`) girano solo nella CI. Differenze:
- **Controllo a due voci** (`.gruppo` dell'appendice B, come i controlli segmentati delle impostazioni) nella riga degli
strumenti, fra l'icona dell'elenco CSV e il cursore della grandezza nella Libreria, prima di «Seleziona» nella scheda
account. Icone `layers` (raggruppa) e `layout-grid` (tutte le foto). Nella Libreria, sotto i 1680 px di finestra,
restano solo le icone (la riga del mockup 01 a 1440 px non ha posto per i due testi); nella scheda account sotto i
1000 px. Nome e suggerimento restano sui pulsanti. In «In evidenza» della scheda account non c'è.
- **Tessere di un file.** Stesse misure e righe giustificate del mosaico; il segno in alto a destra di un file di una
serie è «2/4» con l'icona `layers` al posto del numero dei file. Un file non ancora scaricato non ha tessera.
- **Intestazioni.** La riga del giorno conta i file («Oggi martedì 13 ottobre, 23 file nuovi», «9 file»), il titolo
della Libreria dice «61.034 file in 48.212 elementi di 38 account»; nella scheda account numeri e linguette restano
elementi.
- **Selezione.** La barra dice «3 file scelti, di 2 elementi» ed «Elimina 2 elementi»; la conferma aggiunge «3 file
scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file».
- **Visualizzatore** (mockup 02): si apre sul file della tessera; in alto «Libreria, file 12 di 61.034».
### Carattere e icone (dal 18 novembre 2026)
Mockup e schermate di questa cartella sono stati presi con il carattere Archivo e le icone Lucide, che dal 18 novembre
+11 -2
View File
@@ -81,8 +81,17 @@ public interface IEntryStore
Task<LibraryTotals> GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default);
/// <summary>Entries per local calendar day in Alberto's zone, newest day first.</summary>
Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default);
/// <summary>
/// Files of the entries of the filter that are in the library (downloaded or imported): the tiles of
/// «Tutte le foto». With «Foto» and «Video» only the files of that kind.
/// </summary>
Task<int> CountLibraryFilesAsync(LibraryFilter filter, CancellationToken ct = default);
/// <summary>
/// Entries (or, with <see cref="MosaicMode.Files"/>, files) per local calendar day in Alberto's zone, newest day
/// first. A day without files is left out in that mode.
/// </summary>
Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, MosaicMode mode = MosaicMode.Grouped, CancellationToken ct = default);
/// <summary>Tiles for given entries, in the given order (e.g. the items of a highlight collection).</summary>
Task<IReadOnlyList<LibraryTile>> GetTilesAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
+28 -5
View File
@@ -56,8 +56,25 @@ public sealed record LibraryFilter
public IReadOnlyList<EntryState>? States { get; init; }
}
/// <summary>Keyset position in the library order (publication time descending, then id descending).</summary>
public readonly record struct LibraryCursor(DateTimeOffset PublishedAt, long EntryId)
/// <summary>
/// «Raggruppa i post» or «Tutte le foto» (spec §4.6): one tile per entry, the default, or one tile per file of the
/// library (videos included), in the same order: publication of the entry, then position in the series.
/// </summary>
public enum MosaicMode
{
/// <summary>«Raggruppa i post»: one tile per entry, with its cover.</summary>
Grouped,
/// <summary>«Tutte le foto»: one tile per file present in the library (downloaded or imported).</summary>
Files,
}
/// <summary>
/// Keyset position in the library order (publication time descending, then id descending). With
/// <see cref="MosaicMode.Files"/> <see cref="Position"/> continues inside the entry: the window goes on after the file at
/// that position (0: before every file of the entry). <see cref="MosaicMode.Grouped"/> ignores it.
/// </summary>
public readonly record struct LibraryCursor(DateTimeOffset PublishedAt, long EntryId, int Position = 0)
{
/// <summary>A cursor that starts the older direction at a given instant (to jump to a date).</summary>
public static LibraryCursor At(DateTimeOffset instant) => new(instant, long.MaxValue);
@@ -81,13 +98,18 @@ public sealed record LibraryQuery
public LibraryDirection Direction { get; init; } = LibraryDirection.Older;
/// <summary>One tile per entry (default) or per file.</summary>
public MosaicMode Mode { get; init; } = MosaicMode.Grouped;
/// <summary>Maximum tiles (1–1000).</summary>
public int Limit { get; init; } = 200;
}
/// <summary>
/// One tile of the mosaic: an entry with its cover file (the file at the lowest position).
/// <see cref="CoverSha256"/> is the thumbnail key.
/// One tile of the mosaic: an entry with its cover file (the file at the lowest position). With
/// <see cref="MosaicMode.Files"/> the tile is one file of the entry: the cover columns describe that file and
/// <see cref="FilePosition"/> is its position in the series (null for an entry tile). <see cref="CoverSha256"/> is the
/// thumbnail key.
/// </summary>
public sealed record LibraryTile(
long EntryId,
@@ -104,7 +126,8 @@ public sealed record LibraryTile(
int? CoverHeight,
TimeSpan? CoverDuration,
string? CoverSha256,
bool CoverHasThumbnail);
bool CoverHasThumbnail,
int? FilePosition = null);
/// <summary>
/// A window of tiles, always in display order (newest first). <see cref="Older"/> and <see cref="Newer"/> continue
@@ -1,6 +1,6 @@
-- Febe, schema version 2: «Cosa scaricare prima» (tappa D1, issue #59; spec §7.2, §4.4, §8.3).
-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner.
-- Only columns and an index are added: no behaviour changes for the data already stored.
-- Only columns and indexes are added: no behaviour changes for the data already stored.
-- The order of «Cosa scaricare prima» of the account: the Italian names of the five kinds, comma separated
-- («storie,evidenza,post,reel,taggati»). NULL: «Come le impostazioni generali» (setting scaricamento.ordine).
@@ -13,3 +13,7 @@ ALTER TABLE entry ADD COLUMN is_reel INTEGER NOT NULL DEFAULT 0 CHECK (is_reel I
-- What a recipe saved, for the thumbnails of the history of the Dashboard (spec §7.9): the entries discovered in the
-- few minutes of the recipe, of one account or of all (the Giro dei seguiti), read by range whatever the library's size.
CREATE INDEX ix_entry_discovered ON entry (discovered_at);
-- «Tutte le foto» (spec §4.6): the files of an entry that are in the library, and of which kind, read from the index
-- alone, so the counts of the days and the total of the files stay within the times of the scale test (200,000 entries).
CREATE INDEX ix_media_entry_files ON media (entry_id, state, kind);
+284 -5
View File
@@ -242,6 +242,11 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{
ArgumentNullException.ThrowIfNull(query);
var limit = Math.Clamp(query.Limit, 1, 1000);
if (query.Mode == MosaicMode.Files)
{
return db.ReadAsync(c => QueryFiles(c, query, limit), ct);
}
return db.ReadAsync(
c =>
{
@@ -327,7 +332,35 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
ct);
}
public Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default)
public Task<int> CountLibraryFilesAsync(LibraryFilter filter, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
return db.ReadAsync(
c =>
{
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, EntriesOfFiles(filter));
var counts = FileCounts(c, filter);
if (counts is null)
{
command.CommandText = $"SELECT COALESCE(SUM({FilesOfEntry(filter)}), 0) FROM entry e WHERE {where}";
return (int)command.ScalarInt64();
}
command.CommandText = $"SELECT e.id FROM entry e WHERE {where}";
var total = 0;
using var r = command.ExecuteReader();
while (r.Read())
{
total += counts.GetValueOrDefault(r.GetInt64(0));
}
return total;
},
ct);
}
public Task<IReadOnlyList<DayCount>> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, MosaicMode mode = MosaicMode.Grouped, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(filter);
ArgumentNullException.ThrowIfNull(zone);
@@ -337,8 +370,15 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// Stream the publication times in index order and fold them into local days here: no time zone logic
// in SQL, no sort, and the day bounds are computed once per day rather than once per entry.
var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
command.CommandText = $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at";
var files = mode == MosaicMode.Files;
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter);
var counts = files ? FileCounts(c, filter) : null;
var perEntry = files && counts is null;
command.CommandText = !files
? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at"
: perEntry
? $"SELECT e.published_at, {FilesOfEntry(filter)} FROM entry e WHERE {where} ORDER BY e.published_at"
: $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at";
var days = new List<DayCount>();
long dayStart = long.MaxValue, dayEnd = long.MinValue;
DateOnly day = default;
@@ -360,7 +400,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
(dayStart, dayEnd, count) = (Sql.Time(start), Sql.Time(end), 0);
}
count++;
count += !files ? 1 : perEntry ? r.GetInt32(1) : counts!.GetValueOrDefault(r.GetInt64(1));
}
}
@@ -403,6 +443,243 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
return entryIds.Where(byId.ContainsKey).Select(id => byId[id]).ToList();
}
// --------------------------------------------------------------------------------------------- «Tutte le foto»
/// <summary>The files of «Tutte le foto» on <c>media m</c>: those in the library, of the kind of «Foto» or «Video».</summary>
private static string FileTerms(LibraryFilter filter) =>
// The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index.
"+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch
{
LibraryKindFilter.Photos => " AND m.kind = 'Photo'",
LibraryKindFilter.Videos => " AND m.kind = 'Video'",
_ => string.Empty,
};
/// <summary>
/// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a
/// count per entry would cost a subquery for each of 200,000 rows (over a second), this a tenth of that. With a
/// filter on accounts the entries are few and are counted one by one instead (null).
/// </summary>
private static Dictionary<long, int>? FileCounts(SqliteConnection c, LibraryFilter filter)
{
if (filter.AccountIds is { Count: > 0 })
{
return null;
}
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM media m WHERE {FileTerms(filter)} GROUP BY m.entry_id");
var counts = new Dictionary<long, int>();
using var r = command.ExecuteReader();
while (r.Read())
{
counts[r.GetInt64(0)] = r.GetInt32(1);
}
return counts;
}
/// <summary>
/// The entries whose files a count of «Tutte le foto» adds up: for «Foto» and «Video» every post, since the kind of
/// the files already decides (a post without videos adds 0) and the EXISTS per post of the grouped filter would cost
/// a second over 200,000 entries.
/// </summary>
private static LibraryFilter EntriesOfFiles(LibraryFilter filter) =>
filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter;
/// <summary>A correlated count of the files of «Tutte le foto» of the entry <c>e</c>.</summary>
private static string FilesOfEntry(LibraryFilter filter) =>
$"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})";
/// <summary>
/// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as
/// the grouped mosaic (so it stays as fast over 200,000 entries), then their files are read by key and laid out in
/// order, entry by entry and each by position. More entries are read only when those had too few files.
/// </summary>
private static LibraryPage QueryFiles(SqliteConnection c, LibraryQuery query, int limit)
{
var newer = query.Direction == LibraryDirection.Newer;
var wanted = limit + 1;
var files = new List<FileRow>(wanted);
var cursor = query.Cursor;
var from = cursor;
// The first read includes the entry of the cursor, for its files after (or before) the cursor's position.
var inclusive = true;
while (files.Count < wanted)
{
var keys = EntryKeys(c, query.Filter, from, newer, inclusive, wanted);
if (keys.Count == 0)
{
break;
}
var byEntry = FilesOf(c, keys.Select(k => k.Id).ToList(), query.Filter);
foreach (var (id, _) in keys)
{
if (!byEntry.TryGetValue(id, out var list))
{
continue;
}
for (var i = 0; i < list.Count && files.Count < wanted; i++)
{
var file = list[newer ? list.Count - 1 - i : i];
if (cursor is { } at && at.EntryId == id && (newer ? file.Position >= at.Position : file.Position <= at.Position))
{
continue;
}
files.Add(file);
}
if (files.Count == wanted)
{
break;
}
}
if (keys.Count < wanted)
{
break;
}
from = new LibraryCursor(Sql.ToTime(keys[^1].PublishedAt), keys[^1].Id);
inclusive = false;
}
var moreInDirection = files.Count > limit;
if (moreInDirection)
{
files.RemoveAt(files.Count - 1);
}
if (newer)
{
files.Reverse();
}
var entries = TilesOf(c, files.Select(f => f.EntryId).Distinct().ToList()).ToDictionary(t => t.EntryId);
var tiles = new List<LibraryTile>(files.Count);
foreach (var f in files)
{
if (entries.TryGetValue(f.EntryId, out var entry))
{
tiles.Add(entry with
{
CoverMediaId = f.MediaId,
CoverKind = f.Kind,
CoverWidth = f.Width,
CoverHeight = f.Height,
CoverDuration = f.Duration,
CoverSha256 = f.Sha256,
CoverHasThumbnail = f.HasThumbnail,
FilePosition = f.Position,
});
}
}
if (tiles.Count == 0)
{
return new LibraryPage(tiles, null, null);
}
var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId, tiles[0].FilePosition ?? 0);
var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId, tiles[^1].FilePosition ?? 0);
bool hasOlder, hasNewer;
if (newer)
{
hasNewer = moreInDirection;
hasOlder = FileExists(c, query.Filter, last, older: true);
}
else
{
hasOlder = moreInDirection;
hasNewer = cursor is not null && FileExists(c, query.Filter, first, older: false);
}
return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null);
}
/// <summary>Keys of the entries of a filter from a cursor, in the order of the direction (the grouped keyset scan).</summary>
private static List<(long Id, long PublishedAt)> EntryKeys(SqliteConnection c, LibraryFilter filter, LibraryCursor? cursor, bool newer, bool inclusive, int limit)
{
using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}");
if (cursor is { } at)
{
var op = (newer, inclusive) switch { (true, true) => ">=", (true, false) => ">", (false, true) => "<=", _ => "<" };
sql.Append(" AND (e.published_at, e.id) ").Append(op).Append(" (@cp, @ci)");
command.With("@cp", Sql.Time(at.PublishedAt)).With("@ci", at.EntryId);
}
var order = string.IsNullOrWhiteSpace(filter.Search) ? "e.published_at" : "+e.published_at";
sql.Append(newer ? $" ORDER BY {order} ASC, e.id ASC" : $" ORDER BY {order} DESC, e.id DESC");
sql.Append(" LIMIT @limit");
command.With("@limit", (long)limit);
command.CommandText = sql.ToString();
var keys = new List<(long, long)>(limit);
using var r = command.ExecuteReader();
while (r.Read())
{
keys.Add((r.GetInt64(0), r.GetInt64(1)));
}
return keys;
}
/// <summary>The files of «Tutte le foto» of the given entries, each list by position.</summary>
private static Dictionary<long, List<FileRow>> FilesOf(SqliteConnection c, IReadOnlyList<long> entryIds, LibraryFilter filter)
{
var byEntry = new Dictionary<long, List<FileRow>>(entryIds.Count);
foreach (var chunk in entryIds.Chunk(500))
{
using var command = c.Command(string.Empty);
var list = command.AddList("f", chunk);
command.CommandText = "SELECT m.entry_id, m.id, m.position, m.kind, m.width, m.height, m.duration_ms, m.sha256, m.has_thumbnail "
+ $"FROM media m WHERE m.entry_id IN ({list}) AND {FileTerms(filter)} ORDER BY m.entry_id, m.position";
using var r = command.ExecuteReader();
while (r.Read())
{
var row = new FileRow(
r.GetInt64(0),
r.GetInt64(1),
r.GetInt32(2),
r.GetEnum<MediaKind>(3),
r.GetInt32OrNull(4),
r.GetInt32OrNull(5),
r.GetDurationOrNull(6),
r.GetTextOrNull(7),
r.GetBool(8));
if (!byEntry.TryGetValue(row.EntryId, out var files))
{
byEntry[row.EntryId] = files = [];
}
files.Add(row);
}
}
return byEntry;
}
/// <summary>Whether «Tutte le foto» has a file after (older) or before (newer) a cursor.</summary>
private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older)
{
using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var terms = FileTerms(filter);
command.CommandText =
$"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} "
+ $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) "
+ $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) "
+ $"AND EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {terms}))";
command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId).With("@xn", (long)cursor.Position);
return command.ScalarInt64() != 0;
}
/// <summary>A file of «Tutte le foto»: what its tile needs.</summary>
private readonly record struct FileRow(long EntryId, long MediaId, int Position, MediaKind Kind, int? Width, int? Height, TimeSpan? Duration, string? Sha256, bool HasThumbnail);
private static void Validate(Entry entry, IReadOnlyList<Media> media)
{
ArgumentNullException.ThrowIfNull(entry);
@@ -492,7 +769,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
parts.Add(filter.Kind switch
{
LibraryKindFilter.All => "+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged')",
LibraryKindFilter.Posts => "e.kind = 'Post'",
// Like «Tutto», a broad term: on the kind index every post would need its table row for the state (most of
// the library); the publication index already holds kind and state.
LibraryKindFilter.Posts => "+e.kind = 'Post'",
LibraryKindFilter.Photos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Photo')",
LibraryKindFilter.Videos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Video')",
LibraryKindFilter.Stories => "e.kind = 'Story'",
+20 -7
View File
@@ -136,8 +136,18 @@ public static class ApiMapping
return local.Hour.ToString(CultureInfo.InvariantCulture) + ":" + local.Minute.ToString("00", CultureInfo.InvariantCulture);
}
public static string Cursor(LibraryCursor cursor) =>
cursor.PublishedAt.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + "." + cursor.EntryId.ToString(CultureInfo.InvariantCulture);
/// <summary>«ms.entry», with «Tutte le foto» «ms.entry.position» (the window goes on after that file).</summary>
public static string Cursor(LibraryCursor cursor, MosaicMode mode = MosaicMode.Grouped) =>
cursor.PublishedAt.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + "." + cursor.EntryId.ToString(CultureInfo.InvariantCulture)
+ (mode == MosaicMode.Files ? "." + cursor.Position.ToString(CultureInfo.InvariantCulture) : string.Empty);
/// <summary>«mode»: <c>grouped</c> (default, «Raggruppa i post») or <c>files</c> («Tutte le foto»).</summary>
public static MosaicMode Mode(string? text) => (text ?? string.Empty).ToLowerInvariant() switch
{
"" or "grouped" => MosaicMode.Grouped,
"files" => MosaicMode.Files,
_ => throw new BadRequestException("Modo del mosaico sconosciuto."),
};
public static LibraryCursor? ParseCursor(string? text)
{
@@ -146,15 +156,18 @@ public static class ApiMapping
return null;
}
var dot = text.IndexOf('.', StringComparison.Ordinal);
if (dot <= 0
|| !long.TryParse(text.AsSpan(0, dot), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms)
|| !long.TryParse(text.AsSpan(dot + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var id))
var parts = text.Split('.');
var position = 0;
if (parts.Length is < 2 or > 3
|| !long.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms)
|| !long.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var id)
|| (parts.Length == 3 && (!int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out position) || position < 0))
|| ms < -62135596800000 || ms > 253402300799999)
{
throw new BadRequestException("Posizione nella libreria non valida.");
}
return new LibraryCursor(DateTimeOffset.FromUnixTimeMilliseconds(ms), id);
return new LibraryCursor(DateTimeOffset.FromUnixTimeMilliseconds(ms), id, position);
}
/// <summary>
+8 -3
View File
@@ -41,7 +41,10 @@ public sealed record PreferencesDto(string Theme);
/// <summary>The cover of a tile. <see cref="Thumb"/> is the thumbnail key (null: neutral tile).</summary>
public sealed record CoverDto(long MediaId, string Kind, int? Width, int? Height, double? Duration, string? Thumb);
/// <summary>A tile of the mosaic: one entry.</summary>
/// <summary>
/// A tile of the mosaic: one entry, or with «Tutte le foto» one file of it (the cover is that file and
/// <see cref="Position"/> its place in the series; null for an entry tile).
/// </summary>
public sealed record TileDto(
long Id,
long AccountId,
@@ -53,7 +56,8 @@ public sealed record TileDto(
string Provenance,
string State,
int Files,
CoverDto? Cover);
CoverDto? Cover,
int? Position = null);
/// <summary>A window of tiles; cursors continue it (null: nothing more that way).</summary>
public sealed record LibraryPageDto(IReadOnlyList<TileDto> Tiles, string? Older, string? Newer);
@@ -64,7 +68,8 @@ public sealed record ArrivedDto(IReadOnlyList<TileDto> Tiles, int Total);
/// <summary>A day of the mosaic: its count and the cursor that starts at its end.</summary>
public sealed record DayDto(string Day, int Count, string Cursor);
public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList<DayDto> Days);
/// <summary>Days of the mosaic with the totals; <see cref="Files"/> only with «Tutte le foto» (the files of the entries).</summary>
public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList<DayDto> Days, int? Files = null);
public sealed record AccountBriefDto(long Id, string Username, string? DisplayName, bool IsPrivate, bool IsFollowed, bool IsMine, string State, string? Avatar);
+11 -6
View File
@@ -31,15 +31,17 @@ public static class LibraryApi
var zone = clock.LocalZone;
var now = clock.Now;
var filter = ApiMapping.Filter(context.Request.Query, zone);
var mode = ApiMapping.Mode(context.Request.Query["mode"]);
var totals = await storage.Entries.GetLibraryTotalsAsync(filter, ct).ConfigureAwait(false);
var days = await storage.Entries.CountLibraryByDayAsync(filter, zone, ct).ConfigureAwait(false);
int? files = mode == MosaicMode.Files ? await storage.Entries.CountLibraryFilesAsync(filter, ct).ConfigureAwait(false) : null;
var days = await storage.Entries.CountLibraryByDayAsync(filter, zone, mode, ct).ConfigureAwait(false);
var list = days.Select(d =>
{
var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone);
return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0)));
return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0), mode));
}).ToList();
return ApiHttp.Json(
new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list),
new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files),
FebeJsonContext.Default.LibraryDaysDto);
});
@@ -49,20 +51,22 @@ public static class LibraryApi
var zone = clock.LocalZone;
var limit = int.TryParse(query["limit"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var l) ? Math.Clamp(l, 1, MaxWindow) : 200;
var direction = string.Equals(query["direction"], "newer", StringComparison.OrdinalIgnoreCase) ? LibraryDirection.Newer : LibraryDirection.Older;
var mode = ApiMapping.Mode(query["mode"]);
var page = await storage.Entries.QueryLibraryAsync(
new LibraryQuery
{
Filter = ApiMapping.Filter(query, zone),
Cursor = ApiMapping.ParseCursor(query["cursor"]),
Direction = direction,
Mode = mode,
Limit = limit,
},
ct).ConfigureAwait(false);
return ApiHttp.Json(
new LibraryPageDto(
page.Tiles.Select(t => Tile(t, zone)).ToList(),
page.Older is { } older ? ApiMapping.Cursor(older) : null,
page.Newer is { } newer ? ApiMapping.Cursor(newer) : null),
page.Older is { } older ? ApiMapping.Cursor(older, mode) : null,
page.Newer is { } newer ? ApiMapping.Cursor(newer, mode) : null),
FebeJsonContext.Default.LibraryPageDto);
});
@@ -209,7 +213,8 @@ public static class LibraryApi
tile.CoverHeight,
tile.CoverDuration?.TotalSeconds,
tile.CoverHasThumbnail && tile.CoverSha256 is not null ? tile.CoverSha256 : tile.CoverKind == MediaKind.Video ? "video" : null)
: null);
: null,
tile.FilePosition);
}
public static async Task<EntryDto> EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct)
+8 -3
View File
@@ -860,9 +860,14 @@ public static class DemoSeeder
_ => video ? (random.NextDouble() < 0.7 ? PictureShape.Story : PictureShape.Portrait) : PickShape(random),
};
// «Tutte le foto» (spec §4.6): about one series of three files or more in five has a video in second place, as on
// Instagram. Decided from the entry's own identifier, so the rest of the demo world (drawn from the same random
// sequence) stays as it was; its length and weight too.
var seriesVideo = !video && count >= 3 && entry.InstagramId is { Length: > 0 } id && id[^1] is '3' or '7';
for (var n = 1; n <= count; n++)
{
var isVideo = video && n == 1;
var inSeries = seriesVideo && n == 2;
var isVideo = (video && n == 1) || inSeries;
var picture = pool.Pick(n == 1 ? subject : spec.Themes[random.Next(spec.Themes.Length)], n == 1 || !video ? shape : PickShape(random), random);
var extension = isVideo ? ".mp4" : ".jpg";
var relative = layout.RelativePathFor(folder, LibraryNaming.Default.For(entry.Kind), NamingValues.For(account.Username, entry, n, extension, collection, picture.Sha256), zone);
@@ -872,10 +877,10 @@ public static class DemoSeeder
Kind = isVideo ? MediaKind.Video : MediaKind.Photo,
Width = picture.Width,
Height = picture.Height,
Duration = isVideo ? TimeSpan.FromSeconds(item.Kind is EntryKind.Story or EntryKind.Highlight ? random.Next(5, 16) : random.Next(8, 95)) : null,
Duration = inSeries ? TimeSpan.FromSeconds(9 + (count * 4)) : isVideo ? TimeSpan.FromSeconds(item.Kind is EntryKind.Story or EntryKind.Highlight ? random.Next(5, 16) : random.Next(8, 95)) : null,
State = item.Imported ? MediaState.Imported : MediaState.Downloaded,
RelativePath = relative,
Bytes = isVideo ? random.Next(2_000_000, 38_000_000) : picture.Bytes,
Bytes = inSeries ? 6_000_000 + (count * 900_000) : isVideo ? random.Next(2_000_000, 38_000_000) : picture.Bytes,
Sha256 = picture.Sha256,
PerceptualHash = isVideo ? null : picture.PerceptualHash,
HasThumbnail = true,
+6
View File
@@ -331,6 +331,12 @@ input[type=range].cursore::-moz-range-thumb{width:14px;height:14px;border-radius
input[type=range].cursore:focus-visible{outline:2px solid var(--accento);outline-offset:3px}
.grandezza{display:flex;align-items:center;gap:8px;color:var(--testo-2)}
.btn.solo-icona{padding:0 8px}
/* «Raggruppa i post» / «Tutte le foto» (spec §4.6): the two voices of .gruppo; in the crowded row of the Libreria only
the icons until the window is wide, in every row below 1000 px (name and tooltip stay on the buttons). */
.modo-mosaico{flex:none}
.modo-mosaico > button{padding:0 10px}
@media (max-width:1679px){ .modo-mosaico.compatto .voce{display:none} .modo-mosaico.compatto > button{padding:0 8px} }
@media (max-width:1000px){ .modo-mosaico .voce{display:none} .modo-mosaico > button{padding:0 8px} }
/* Libreria: when the tools do not fit in one row (a duplicates link, a narrow screen above 1000 px) the group on
the right goes to a second row instead of squeezing the kind chips into a column. */
@media (min-width:1001px){
+32 -24
View File
@@ -11,8 +11,8 @@ 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 { confirmDelete, selectionBar } from './library.js';
import { Mosaic, justify, tileElement, defaultDayLabel, filesDayLabel, modeSwitch, storedMode } from './mosaic.js';
import { kindName, orderEditor, orderOrDefault } from './download-order.js';
import { openViewer } from './viewer.js';
@@ -109,6 +109,12 @@ async function contentsTab(page, route, detail) {
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;
// «Raggruppa i post» / «Tutte le foto» (spec §4.6): one choice for the views of every account, apart from the Libreria.
let mode = storedMode('account');
const modes = modeSwitch('account', (value) => {
mode = value;
show();
});
// «In evidenza» is drawn by its own code: its listeners go when another chip is chosen. The token tells a view
// still loading that another one took its place.
let highlightCleanup = null;
@@ -116,7 +122,7 @@ async function contentsTab(page, route, detail) {
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)));
page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, h('div.destra', modes, selectButton)));
const host = h('div');
fill(page.body, host);
@@ -131,6 +137,8 @@ async function contentsTab(page, route, detail) {
}, 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';
// «In evidenza» is drawn by collection, one tile per item (almost always a single story): no switch there.
modes.hidden = kind.key === 'evidenza';
}
periodButton.addEventListener('click', () => menu(periodButton,
@@ -159,26 +167,25 @@ async function contentsTab(page, route, detail) {
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 })))));
page.saveBar(selectionBar(mosaic, selected, {
cancel: () => setSelecting(false),
exportSelected: async () => {
try {
await download('/api/entries/export', { ids: mosaic.selectedEntries().ids }, 'febe-elementi.csv');
toast(t('selezione.esportato'));
} catch (error) {
showError(error);
}
},
deleteSelected: async () => {
const { ids, files } = mosaic.selectedEntries();
const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null);
if (removed) {
mosaic.removeTiles(removed);
setSelecting(false);
}
},
}));
}
function setSelecting(on) {
@@ -211,9 +218,10 @@ async function contentsTab(page, route, detail) {
host,
query: query(),
mode: kind.grid ? 'grid' : 'justified',
files: mode === 'files',
rowHeight,
signal: page.signal,
dayLabel: kind.grid ? storiesDayLabel : defaultDayLabel,
dayLabel: mode === 'files' ? filesDayLabel : kind.grid ? storiesDayLabel : defaultDayLabel,
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: `@${detail.account.username}`, onDeleted: (ids) => mosaic.removeTiles(ids) }),
onSelection: drawSelection,
onEmpty: () => fill(host, h('div.vuoto-pagina', icon(kind.grid ? 'circle-dashed' : 'image'), h('p', t('scheda.nessunContenuto')))),
+42 -14
View File
@@ -1,6 +1,8 @@
// 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).
// «Raggruppa i post» / «Tutte le foto» (spec §4.6): one tile per entry or per file, remembered in this browser. With
// «Tutte le foto» the selection is of files; the CSV list and «Elimina» work on the entries they belong to.
import { api, download, withCarried } from '../core/api.js';
import { caps } from '../core/context.js';
@@ -9,7 +11,7 @@ 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 { Mosaic, modeSwitch, storedMode } from './mosaic.js';
import { welcome } from './welcome.js';
import { openViewer } from './viewer.js';
@@ -73,6 +75,7 @@ export default {
const today = () => caps().today || new Date().toISOString().slice(0, 10);
let accounts = null;
let mosaic = null;
let mode = storedMode('libreria');
page.title(t('libreria.titolo'), '');
const search = h('input', { type: 'search', placeholder: t('libreria.cerca'), 'aria-label': t('libreria.cerca'), value: state.q });
@@ -93,6 +96,10 @@ export default {
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 modes = modeSwitch('libreria', (value) => {
mode = value;
apply();
}, { compact: true });
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 });
@@ -108,6 +115,7 @@ export default {
h('div.destra',
duplicates,
exportButton,
modes,
h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')),
selectButton)));
@@ -273,13 +281,7 @@ export default {
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 })))));
page.saveBar(selectionBar(mosaic, selected, { cancel: () => setSelecting(false), exportSelected, deleteSelected }));
}
function setSelecting(on) {
@@ -295,7 +297,7 @@ export default {
async function exportSelected() {
try {
await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv');
await download('/api/entries/export', { ids: mosaic.selectedEntries().ids }, 'febe-elementi.csv');
toast(t('selezione.esportato'));
} catch (error) {
showError(error);
@@ -315,8 +317,8 @@ export default {
}
async function deleteSelected() {
const ids = [...mosaic.selected];
const removed = await confirmDelete(ids);
const { ids, files } = mosaic.selectedEntries();
const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null);
if (removed) {
mosaic.removeTiles(removed);
setSelecting(false);
@@ -368,11 +370,14 @@ export default {
scroller: page.body,
host,
query: apiQuery(state, today()),
files: mode === 'files',
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 }) })),
onTotals: ({ entries, accounts: n, files }) => page.count(files == null
? t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })
: t('libreria.quantiFile', { file: t('comune.file', { n: files }), elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })),
onEmpty: drawEmpty,
});
try {
@@ -395,16 +400,39 @@ export default {
},
};
/**
* The bar of the selection (Libreria and account view): how many are chosen, «Esporta l'elenco» and «Elimina». With
* «Tutte le foto» it counts the files and says how many entries they belong to: those are what the actions work on.
*/
export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteSelected }) {
const n = selected.size;
const entries = mosaic.selectedEntries().ids.length;
let note = t('selezione.nessuno');
if (n && mosaic.files) note = t('selezione.sceltiFile', { n, elementi: t('comune.elementi', { n: entries }) });
else if (n) note = t('selezione.scelti', { n });
return h('div', { style: { display: 'contents' } },
h('span.nota', note),
h('div.destra',
h('button.btn.nudo', { type: 'button', onclick: cancel }, 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: entries }))));
}
/**
* «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.
* files: with «Tutte le foto», { files: chosen files, total: files of their entries }: the confirmation says that the
* whole entries go («3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»).
*/
export async function confirmDelete(ids) {
export async function confirmDelete(ids, files = null) {
const n = ids.length;
const whole = files
? h('p', `${t('elimina.fileDi', { n: files.files, elementi: t('comune.elementi', { n }) })}: ${t('elimina.interi', { n, file: t('comune.file', { n: files.total }) })}`)
: null;
const mode = await confirmDialog({
title: t('elimina.titolo', { n }),
text: t('elimina.testo', { n }),
extra: h('p.aiuto', t('elimina.tornaSpiega')),
extra: h('div', whole, h('p.aiuto', t('elimina.tornaSpiega'))),
buttons: [
{ label: t('comune.annulla'), value: undefined, kind: 'nudo' },
{ label: t('elimina.torna', { n }), value: 'allowReturn' },
+128 -38
View File
@@ -3,11 +3,47 @@
// 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.
// «Raggruppa i post» (one tile per entry, the default) or «Tutte le foto» (spec §4.6: one tile per file, in the order of
// the entries and then of the series; the day rows count files). A tile is known by its key: the entry in the first
// mode, the file in the second; the entry stays tile.id in both.
import { api } from '../core/api.js';
import { h, icon, fill, perFrame } from '../core/dom.js';
import { h, icon, fill, perFrame, local } from '../core/dom.js';
import { t, dayName, duration, capitalize } from '../core/text.js';
import { avatar } from '../core/ui.js';
import { avatar, segmented } from '../core/ui.js';
/**
* «Raggruppa i post» or «Tutte le foto» of a page ('libreria', or 'account' for every account), remembered in this
* browser like the theme (spec §4.6). Storage that is missing, blocked or holds anything else means grouped.
*/
export function storedMode(page) {
return local.get(`mosaico.${page}`, 'grouped') === 'files' ? 'files' : 'grouped';
}
/** The two-voice switch of the tools row; onchange(mode) after the choice is remembered. compact: icons only sooner. */
export function modeSwitch(page, onchange, { compact = false } = {}) {
const labels = { grouped: t('libreria.modi.grouped'), files: t('libreria.modi.files') };
const group = segmented({
label: t('libreria.modi.etichetta'),
value: storedMode(page),
options: [
{ value: 'grouped', icon: 'layers', label: h('span.voce', labels.grouped) },
{ value: 'files', icon: 'layout-grid', label: h('span.voce', labels.files) },
],
onchange: (value) => {
local.set(`mosaico.${page}`, value);
onchange(value);
},
});
group.classList.add('modo-mosaico');
if (compact) group.classList.add('compatto');
// The label may be hidden in a narrow row: the name and the tooltip stay.
for (const button of group.querySelectorAll('button')) {
button.setAttribute('aria-label', labels[button.dataset.value]);
button.title = t(`libreria.modi.${button.dataset.value}Aiuto`);
}
return group;
}
const GAP = 4;
const NEAR = '1400px 0px';
@@ -20,12 +56,20 @@ function aspectOf(tile) {
}
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);
// true when tile a comes after tile b in display order (published earlier, or same time and smaller id, or a later
// file of the same entry)
if (a.publishedAt !== b.publishedAt) return a.publishedAt < b.publishedAt;
if (a.id !== b.id) return a.id < b.id;
return (a.position || 0) > (b.position || 0);
}
export function cursorOf(tile) {
return `${tile.publishedAt}.${tile.id}`;
return tile.position != null ? `${tile.publishedAt}.${tile.id}.${tile.position}` : `${tile.publishedAt}.${tile.id}`;
}
/** The key of a tile: the file with «Tutte le foto», otherwise the entry. */
export function keyOf(tile) {
return tile.key != null ? tile.key : tile.id;
}
/** Justified rows: every full row exactly fills the width; the last row keeps the target height. */
@@ -72,15 +116,19 @@ export function tileElement(tile, width, height, { selected = false, today = '',
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)));
// A file of a series says its place («2/4»), an entry how many files it has.
const file = tile.position != null;
if (file && tile.files > 1) marks.push(h('span', icon('layers'), t('libreria.posizioneFile', { n: tile.position, totale: tile.files })));
else if (!file && 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 (file && tile.files > 1) description.push(t('libreria.tesseraPosizione', { n: tile.position, totale: tile.files }));
else if (!file && 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) },
dataset: { id: String(keyOf(tile)), entry: String(tile.id) },
'aria-label': description.join(', '),
'aria-pressed': selected ? 'true' : null,
},
@@ -88,11 +136,20 @@ export function tileElement(tile, width, height, { selected = false, today = '',
? 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.sel', { role: 'checkbox', 'aria-checked': String(selected), 'aria-label': t(file ? 'libreria.scegliFile' : 'libreria.scegliTessera'), title: t(file ? 'libreria.scegliFile' : '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 day header of «Tutte le foto»: «Oggi martedì 13 ottobre, 23 file nuovi», «Sabato 10 ottobre 9 file». */
export function filesDayLabel(day, count, today) {
const name = dayName(day, today);
if (day === today) return [t('tempo.Oggi'), t('libreria.giornoNuovi', { giorno: name, n: t('libreria.fileNuoviOggi', { 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('comune.file', { n: count }) })];
return [capitalize(name), t('comune.file', { n: count })];
}
/** The default day header: «Oggi martedì 13 ottobre, 14 nuovi elementi». */
export function defaultDayLabel(day, count, today) {
const name = dayName(day, today);
@@ -105,20 +162,23 @@ export function defaultDayLabel(day, count, today) {
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).
* mode: 'justified' or 'grid' (9:16 stories); files: «Tutte le foto» (one tile per file); rowHeight: target height;
* onOpen(tile), onSelection(set), onTotals({ entries, accounts, files, today }) (files only with «Tutte le foto»),
* onEmpty(), dayLabel(day, count, today).
*/
constructor(options) {
this.scroller = options.scroller;
this.host = options.host;
this.query = options.query || '';
this.files = Boolean(options.files);
const filter = options.query || '';
this.query = this.files ? `${filter}${filter ? '&' : ''}mode=files` : filter;
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.dayLabel = options.dayLabel || (this.files ? filesDayLabel : defaultDayLabel);
// Its own requests stop with the page and with destroy(): a mosaic replaced by a new filter never answers late
// over the new one (totals, empty state, sections).
this.controller = new AbortController();
@@ -131,6 +191,8 @@ export class Mosaic {
this.sections = [];
this.byDay = new Map();
this.selected = new Set();
// What each chosen key belongs to ({ entry, files }), also after its day was emptied or reloaded.
this.chosen = new Map();
this.selecting = false;
this.today = '';
this.avgAspect = this.mode === 'grid' ? 0.5625 : 0.95;
@@ -159,7 +221,7 @@ export class Mosaic {
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
if (this.destroyed) return;
this.today = data.today;
this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today });
this.onTotals({ entries: data.entries, accounts: data.accounts, files: data.files, today: data.today });
this.width = this.root.clientWidth || this.host.clientWidth || 800;
for (const section of this.sections) this.unobserve(section);
this.sections = [];
@@ -235,6 +297,7 @@ export class Mosaic {
if (this.destroyed) return;
const touched = new Set();
for (const tile of page.tiles) {
tile.key = this.files && tile.cover ? tile.cover.mediaId : tile.id;
const target = this.byDay.get(tile.day);
if (!target || target.complete) continue;
const last = target.tiles[target.tiles.length - 1];
@@ -282,7 +345,7 @@ export class Mosaic {
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' }))));
row.items.map((item) => tileElement(item.tile, item.width, row.height, { selected: this.selected.has(keyOf(item.tile)), today: this.today, ring: this.mode !== 'grid' }))));
this.keepView(section, () => {
section.rows.style.height = '';
fill(section.rows, nodes);
@@ -347,6 +410,7 @@ export class Mosaic {
clearSelection() {
this.selected.clear();
this.chosen.clear();
for (const el of this.root.querySelectorAll('.tess.scelta')) this.markTile(el, false);
this.onSelection(this.selected);
}
@@ -358,10 +422,16 @@ export class Mosaic {
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);
toggle(key, el) {
const on = !this.selected.has(key);
if (on) {
const tile = this.findTile(key);
this.selected.add(key);
if (tile) this.chosen.set(key, { entry: tile.id, files: tile.files });
} else {
this.selected.delete(key);
this.chosen.delete(key);
}
if (el) this.markTile(el, on);
if (!this.selecting && on) this.setSelecting(true);
this.onSelection(this.selected);
@@ -370,42 +440,57 @@ export class Mosaic {
onClick(e) {
const el = e.target.closest('.tess[data-id]');
if (!el) return;
const id = Number(el.dataset.id);
const key = Number(el.dataset.id);
if (e.target.closest('.sel') || this.selecting) {
e.preventDefault();
this.toggle(id, el);
this.toggle(key, el);
return;
}
const tile = this.findTile(id);
const tile = this.findTile(key);
if (tile) this.onOpen(tile);
}
findTile(id) {
findTile(key) {
for (const s of this.sections) {
const tile = s.tiles.find((x) => x.id === id);
const tile = s.tiles.find((x) => keyOf(x) === key);
if (tile) return tile;
}
return null;
}
/** Whether a key is a tile of the mosaic (the viewer asks it about the files of an entry). */
has(key) {
return Boolean(this.findTile(key));
}
/**
* The entries of the selection: with «Tutte le foto» the posts the chosen files belong to (spec §4.6: the CSV list
* and «Elimina» work on them), with how many files those entries have in all.
*/
selectedEntries() {
const entries = new Map();
for (const [key, info] of this.chosen) if (this.selected.has(key)) entries.set(info.entry, info.files || 0);
return { ids: [...entries.keys()], files: [...entries.values()].reduce((a, n) => a + n, 0) };
}
// ------------------------------------------------------------------------------------------- viewer navigation
/** Position of an entry among all the entries of the filter (1-based) and the total. */
position(id) {
/** Position of a tile (an entry, or a file) among all those of the filter (1-based) and the total. */
position(key) {
let before = 0;
for (const s of this.sections) {
const i = s.tiles.findIndex((x) => x.id === id);
const i = s.tiles.findIndex((x) => keyOf(x) === key);
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));
/** The tile before (delta −1) or after (+1) a tile, loading the next group when needed. */
async neighbor(key, delta) {
let si = this.sections.findIndex((s) => s.tiles.some((x) => keyOf(x) === key));
if (si < 0) return null;
let i = this.sections[si].tiles.findIndex((x) => x.id === id) + delta;
let i = this.sections[si].tiles.findIndex((x) => keyOf(x) === key) + delta;
for (;;) {
const s = this.sections[si];
if (i >= 0 && i < s.tiles.length) return s.tiles[i];
@@ -421,24 +506,29 @@ export class Mosaic {
}
}
/** Scrolls so that an entry is visible (after the viewer moved far). */
reveal(id) {
const el = this.root.querySelector(`.tess[data-id="${id}"]`);
/** Scrolls so that a tile is visible (after the viewer moved far). */
reveal(key) {
const el = this.root.querySelector(`.tess[data-id="${Number(key)}"]`);
if (el) el.scrollIntoView({ block: 'nearest' });
}
// ------------------------------------------------------------------------------------------- changes
/** Removes entries (after a deletion) and updates the counts of their days. */
/** Removes entries (after a deletion), with every file tile of theirs, and updates the counts of their days. */
removeTiles(ids) {
const set = new Set(ids);
for (const [key, info] of [...this.chosen]) {
if (set.has(info.entry)) {
this.selected.delete(key);
this.chosen.delete(key);
}
}
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());
@@ -460,7 +550,7 @@ export class Mosaic {
async refresh() {
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
if (this.destroyed) return;
this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today });
this.onTotals({ entries: data.entries, accounts: data.accounts, files: data.files, today: data.today });
// The empty state of the page took the place of the mosaic: the first new entries bring it back.
if (data.days.length && !this.root.isConnected) {
this.pendingNew = 0;
@@ -538,7 +628,7 @@ export class Mosaic {
this.pill.hidden = true;
this.scroller.scrollTo({ top: 0 });
},
}, icon('arrow-left', 's'), t('libreria.nuoviInCima', { n: this.pendingNew })));
}, icon('arrow-left', 's'), t(this.files ? 'libreria.fileNuoviInCima' : 'libreria.nuoviInCima', { n: this.pendingNew })));
this.pill.querySelector('svg').style.transform = 'rotate(90deg)';
this.pill.hidden = false;
}
+48 -20
View File
@@ -13,11 +13,14 @@ 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.
* Opens the viewer on a tile. source: { position(key), neighbor(key, delta), reveal(key) } (the mosaic, or a plain
* list), where a key is the entry. With «Tutte le foto» the source says files: true and has(key), and a key is a file:
* the viewer opens on the file of the tile and its position counts files (spec §4.6). origin: «Libreria» or the
* account name. onDeleted(ids): called with the deleted entries.
*/
export function openViewer({ tile, source, origin, onDeleted }) {
const opener = document.activeElement;
const files = Boolean(source && source.files && source.has);
let entry = null;
let fileIndex = 0;
let zoomed = false;
@@ -77,7 +80,10 @@ export function openViewer({ tile, source, origin, onDeleted }) {
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
box.remove();
document.body.style.overflow = '';
if (entry && source && source.reveal) source.reveal(entry.id);
if (entry && source && source.reveal) {
const key = keyAt(0);
if (key != null) source.reveal(key);
}
if (opener && document.contains(opener)) opener.focus();
}
@@ -87,13 +93,25 @@ export function openViewer({ tile, source, origin, onDeleted }) {
zoomButton.setAttribute('aria-pressed', String(on));
}
async function load(id, index = 0) {
/** The key of the source at the edge of the entry it is left by (delta), or of the file shown when it is a tile. */
function keyAt(delta = 0) {
if (!files) return entry.id;
const current = entry.media[fileIndex];
if (delta === 0 && current && source.has(current.id)) return current.id;
const known = entry.media.filter((m) => source.has(m.id));
if (!known.length) return null;
return (delta > 0 ? known[known.length - 1] : known[0]).id;
}
async function load(id, index = 0, mediaId = null) {
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);
const at = mediaId == null ? -1 : entry.media.findIndex((m) => m.id === mediaId);
if (at >= 0) fileIndex = at;
else fileIndex = index < 0 ? entry.media.length - 1 : Math.min(index, entry.media.length - 1);
draw();
} catch (error) {
showError(error);
@@ -105,14 +123,22 @@ export function openViewer({ tile, source, origin, onDeleted }) {
const target = fileIndex + delta;
if (target >= 0 && target < entry.media.length) {
fileIndex = target;
drawMedia();
drawStrip();
drawPanel();
drawFile();
return;
}
if (!source || !source.neighbor) return;
const other = await source.neighbor(entry.id, delta);
if (other) await load(other.id, delta > 0 ? 0 : -1);
const key = keyAt(delta);
if (key == null) return;
const other = await source.neighbor(key, delta);
if (other) await load(other.id, delta > 0 ? 0 : -1, files && other.cover ? other.cover.mediaId : null);
}
/** Another file of the same entry: with «Tutte le foto» the place in the source moves too. */
function drawFile() {
if (files) drawWhere();
drawMedia();
drawStrip();
drawPanel();
}
function draw() {
@@ -123,9 +149,10 @@ export function openViewer({ tile, source, origin, onDeleted }) {
}
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;
const key = source && source.position ? keyAt(0) : null;
if (key != null) {
const p = source.position(key);
where.textContent = p.index ? t(files ? 'vis.doveFile' : 'vis.dove', { origine: origin, n: number(p.index), totale: number(p.total) }) : origin;
} else where.textContent = origin;
}
@@ -175,9 +202,7 @@ export function openViewer({ tile, source, origin, onDeleted }) {
'aria-current': i === fileIndex ? 'true' : null,
onclick: () => {
fileIndex = i;
drawMedia();
drawStrip();
drawPanel();
drawFile();
},
}, m.thumb ? h('img', { src: `/api/thumbnails/${m.thumb}`, alt: '', loading: 'lazy' }) : null, m.kind === 'video' ? icon('play') : null)));
}
@@ -254,17 +279,20 @@ export function openViewer({ tile, source, origin, onDeleted }) {
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]);
const after = keyAt(1);
const before = keyAt(-1);
const following = source && source.neighbor && after != null ? (await source.neighbor(after, 1)) || (await source.neighbor(before, -1)) : null;
// With «Tutte le foto» too the viewer deletes the whole entry (spec §4.6), and the confirmation says so.
const removed = await confirmDelete([id], files && entry.media.length > 1 ? { files: 1, total: entry.media.length } : null);
if (!removed) return;
if (onDeleted) onDeleted(removed);
if (following) await load(following.id, 0);
if (following) await load(following.id, 0, files && following.cover ? following.cover.mediaId : null);
else close();
}
document.addEventListener('keydown', onKey, true);
document.body.append(box);
closeButton.focus();
load(tile.id, 0);
load(tile.id, 0, files && tile.cover ? tile.cover.mediaId : null);
void withCarried;
}
+18 -1
View File
@@ -82,6 +82,7 @@
"libreria": {
"titolo": "Libreria",
"quanti": "{elementi} di {account}",
"quantiFile": "{file} in {elementi} di {account}",
"cerca": "Cerca per account o didascalia",
"cercaBreve": "Cerca",
"filtriTipo": "Tipo di contenuto",
@@ -127,6 +128,8 @@
"elementiGiorno": "1 elemento|{n} elementi",
"storieGiorno": "1 storia|{n} storie",
"nuoviInCima": "1 nuovo elemento in cima|{n} nuovi elementi in cima",
"fileNuoviOggi": "1 file nuovo|{n} file nuovi",
"fileNuoviInCima": "1 file nuovo in cima|{n} file nuovi in cima",
"vuota": "La libreria è ancora vuota",
"vuotaTesto": "Aggiungi gli account da seguire: i loro contenuti arrivano qui poco per volta.",
"nessuno": "Nessun elemento con questi filtri",
@@ -139,8 +142,18 @@
"esportatoFiltro": "Elenco degli elementi filtrati esportato: il file CSV è nei download del browser.",
"tessera": "{tipo} di @{account}, {quando}",
"tesseraFile": "{n} file",
"tesseraPosizione": "file {n} di {totale}",
"posizioneFile": "{n}/{totale}",
"tesseraDurata": "video di {durata}",
"scegliTessera": "Scegli questo elemento",
"scegliFile": "Scegli questo file",
"modi": {
"etichetta": "Come mostrare i post",
"grouped": "Raggruppa i post",
"files": "Tutte le foto",
"groupedAiuto": "Raggruppa i post: una tessera per elemento, con il numero dei suoi file",
"filesAiuto": "Tutte le foto: una tessera per ogni foto e video, anche di un post con più file"
},
"tipiTessera": {
"post": "Post",
"story": "Storia",
@@ -151,6 +164,7 @@
},
"selezione": {
"scelti": "1 elemento scelto|{n} elementi scelti",
"sceltiFile": "1 file scelto, di {elementi}|{n} file scelti, di {elementi}",
"nessuno": "Tocca le tessere per sceglierle",
"esporta": "Esporta l'elenco",
"elimina": "Elimina 1 elemento|Elimina {n} elementi",
@@ -162,12 +176,15 @@
"testo": "I file vengono cancellati dal disco e non si recuperano. Febe ricorda la scelta: l'elemento resta nell'elenco come «eliminato» e non viene scaricato di nuovo.|I file vengono cancellati dal disco e non si recuperano. Febe ricorda la scelta: gli elementi restano nell'elenco come «eliminati» e non vengono scaricati di nuovo.",
"conferma": "Elimina dalla libreria",
"torna": "Eliminalo e lascia che torni|Eliminali e lascia che tornino",
"tornaSpiega": "Con «lascia che torni» Febe dimentica l'elemento: se è ancora su Instagram, al prossimo controllo lo scarica di nuovo."
"tornaSpiega": "Con «lascia che torni» Febe dimentica l'elemento: se è ancora su Instagram, al prossimo controllo lo scarica di nuovo.",
"fileDi": "1 file scelto appartiene a {elementi}|{n} file scelti appartengono a {elementi}",
"interi": "elimino l'elemento intero, {file}.|elimino gli elementi interi, {file}."
},
"vis": {
"etichetta": "Visualizzatore",
"chiudi": "Chiudi (Esc)",
"dove": "{origine}, elemento {n} di {totale}",
"doveFile": "{origine}, file {n} di {totale}",
"precedente": "Precedente",
"successivo": "Successivo",
"ingrandisci": "Ingrandisci",
+157
View File
@@ -0,0 +1,157 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Data;
/// <summary>
/// «Tutte le foto» (spec §4.6): one tile per file of the library, in the order of the entries and then of the series,
/// with keyset paging that may stop and start again inside a post.
/// </summary>
[TestClass]
public sealed class LibraryFilesTests
{
[TestMethod]
public async Task EveryFileOfTheLibraryIsATileInTheOrderOfTheEntriesAndOfTheSeries()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var (carousel, single, partial, story) = await FillAsync(db);
var page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files });
var keys = page.Tiles.Select(t => (t.EntryId, t.FilePosition)).ToList();
CollectionAssert.AreEqual(
new (long, int?)[] { (story, 1), (carousel, 1), (carousel, 2), (carousel, 3), (partial, 1), (partial, 3), (single, 1) },
keys,
"Newest entry first, each by position; the file still to download of the partial post is not a tile.");
Assert.IsNull(page.Older);
Assert.IsNull(page.Newer);
// A file tile describes that file, and keeps the count of the files of its post («2/3»).
var second = page.Tiles[2];
Assert.AreEqual(3, second.MediaCount);
Assert.AreEqual(MediaKind.Video, second.CoverKind);
Assert.AreEqual(Make.Sha(12), second.CoverSha256);
Assert.AreEqual(TimeSpan.FromSeconds(15), second.CoverDuration);
Assert.AreEqual(3, page.Tiles[5].FilePosition);
Assert.AreEqual(3, page.Tiles[5].MediaCount);
// The grouped mosaic is what it was: one tile per entry.
var grouped = await db.Entries.QueryLibraryAsync(new LibraryQuery());
CollectionAssert.AreEqual(new[] { story, carousel, partial, single }, grouped.Tiles.Select(t => t.EntryId).ToArray());
Assert.IsTrue(grouped.Tiles.All(t => t.FilePosition is null));
}
[TestMethod]
public async Task WindowsOfTwoWalkEveryFileOnceInBothDirectionsAlsoFromInsideAPost()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
await FillAsync(db);
var all = (await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files })).Tiles.Select(Key).ToList();
// Older, two at a time from the top: the second window starts in the middle of the carousel.
var walked = new List<string>();
LibraryCursor? cursor = null;
var windows = 0;
do
{
var page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Limit = 2, Cursor = cursor });
walked.AddRange(page.Tiles.Select(Key));
Assert.AreEqual(windows > 0, page.Newer is not null, "a window after the first has something newer");
cursor = page.Older;
windows++;
}
while (cursor is not null);
CollectionAssert.AreEqual(all, walked);
Assert.AreEqual(4, windows);
// Newer, two at a time from the last file, back to the top.
var last = (await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Limit = 1000 })).Tiles[^1];
cursor = new LibraryCursor(last.PublishedAt, last.EntryId, last.FilePosition!.Value);
var back = new List<string>();
while (cursor is not null)
{
var page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Limit = 2, Cursor = cursor, Direction = LibraryDirection.Newer });
Assert.IsNotNull(page.Older, "a window newer than a file has that file after it");
back.InsertRange(0, page.Tiles.Select(Key));
cursor = page.Newer;
}
CollectionAssert.AreEqual(all.Take(all.Count - 1).ToList(), back);
}
[TestMethod]
public async Task FiltersCountsAndDaysCountTheFiles()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var (carousel, _, _, _) = await FillAsync(db);
// «Video» shows only the videos, «Foto» only the photos (of posts, as in the grouped mosaic).
var videos = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Filter = new LibraryFilter { Kind = LibraryKindFilter.Videos } });
CollectionAssert.AreEqual(new[] { $"{carousel}.2" }, videos.Tiles.Select(Key).ToArray());
var photos = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Filter = new LibraryFilter { Kind = LibraryKindFilter.Photos } });
Assert.HasCount(5, photos.Tiles);
Assert.IsTrue(photos.Tiles.All(t => t.CoverKind == MediaKind.Photo));
Assert.AreEqual(7, await db.Entries.CountLibraryFilesAsync(new LibraryFilter()));
Assert.AreEqual(1, await db.Entries.CountLibraryFilesAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }));
Assert.AreEqual(5, await db.Entries.CountLibraryFilesAsync(new LibraryFilter { Kind = LibraryKindFilter.Photos }));
Assert.AreEqual(1, await db.Entries.CountLibraryFilesAsync(new LibraryFilter { Kind = LibraryKindFilter.Stories }));
Assert.AreEqual(new LibraryTotals(4, 1), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter()), "the totals stay entries");
var days = await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files);
CollectionAssert.AreEqual(new[] { new DayCount(new DateOnly(2026, 10, 13), 6), new DayCount(new DateOnly(2026, 10, 12), 1) }, days.ToArray());
var entryDays = await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome);
CollectionAssert.AreEqual(new[] { new DayCount(new DateOnly(2026, 10, 13), 3), new DayCount(new DateOnly(2026, 10, 12), 1) }, entryDays.ToArray());
// With a filter on accounts the files are counted entry by entry: the same numbers.
var accountId = (await db.Entries.GetAsync(carousel))!.AccountId;
var other = await db.Accounts.AddAsync(Make.Account("luca.demo"));
await db.Entries.AddAsync(Make.Entry(other.Id, "o", new DateTimeOffset(2026, 10, 13, 8, 0, 0, TimeSpan.Zero)), [Make.Stored(Make.Photo(), Make.Sha(41), "o/o.jpg")]);
var mine = new LibraryFilter { AccountIds = [accountId] };
Assert.AreEqual(7, await db.Entries.CountLibraryFilesAsync(mine));
Assert.AreEqual(8, await db.Entries.CountLibraryFilesAsync(new LibraryFilter()));
CollectionAssert.AreEqual(days.ToArray(), (await db.Entries.CountLibraryByDayAsync(mine, TestZones.Rome, MosaicMode.Files)).ToArray());
Assert.AreEqual(8, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files)).Sum(d => d.Count));
Assert.AreEqual(1, await db.Entries.CountLibraryFilesAsync(mine with { Kind = LibraryKindFilter.Videos }));
// A day whose files are all of another kind has no row in «Video».
var videoDays = await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome, MosaicMode.Files);
CollectionAssert.AreEqual(new[] { new DayCount(new DateOnly(2026, 10, 13), 1) }, videoDays.ToArray());
// The cursor at the end of a day (what the mosaic asks first for a day) starts with that day's newest file.
var dayStart = LocalCalendar.StartOfDay(new DateOnly(2026, 10, 13), TestZones.Rome);
var fromDay = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Limit = 1, Cursor = new LibraryCursor(dayStart, 0) });
Assert.AreEqual(new DateOnly(2026, 10, 12), LocalCalendar.Today(fromDay.Tiles.Single().PublishedAt, TestZones.Rome));
}
private static string Key(LibraryTile tile) => $"{tile.EntryId}.{tile.FilePosition}";
/// <summary>
/// A story (13 Oct, 12:00), a carousel of photo, video, photo (13 Oct, 10:00), a post with its second file still to
/// download (13 Oct, 9:00) and a single photo (12 Oct, 9:00), all of one account.
/// </summary>
private static async Task<(long Carousel, long Single, long Partial, long Story)> FillAsync(FebeDatabase db)
{
var account = await db.Accounts.AddAsync(Make.Account("marta.demo"));
var day = new DateTimeOffset(2026, 10, 13, 0, 0, 0, TimeSpan.FromHours(2));
var single = await db.Entries.AddAsync(Make.Entry(account.Id, "s", day.AddHours(-15)), [Make.Stored(Make.Photo(), Make.Sha(1), "p/s.jpg")]);
var partial = await db.Entries.AddAsync(Make.Entry(account.Id, "p", day.AddHours(9)), [
Make.Stored(Make.Photo(1), Make.Sha(21), "p/p1.jpg"),
Make.Photo(2),
Make.Stored(Make.Photo(3), Make.Sha(23), "p/p3.jpg"),
]);
var carousel = await db.Entries.AddAsync(Make.Entry(account.Id, "c", day.AddHours(10)), [
Make.Stored(Make.Photo(1), Make.Sha(11), "p/c1.jpg"),
Make.Stored(Make.Video(2), Make.Sha(12), "p/c2.mp4"),
Make.Stored(Make.Photo(3), Make.Sha(13), "p/c3.jpg"),
]);
var story = await db.Entries.AddAsync(Make.Entry(account.Id, "st", day.AddHours(12), EntryKind.Story), [Make.Stored(Make.Photo(), Make.Sha(31), "s/st.jpg")]);
Assert.AreEqual(EntryState.Partial, partial.Stored.Entry.State);
return (carousel.Stored.Entry.Id, single.Stored.Entry.Id, partial.Stored.Entry.Id, story.Stored.Entry.Id);
}
}
@@ -109,6 +109,34 @@ public sealed class LibraryScaleTests
Assert.AreEqual(new LibraryTotals(Entries, Accounts), totals);
var days = await Measure("conteggi per giorno", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome));
Assert.AreEqual(Entries, days.Sum(d => d.Count));
// «Tutte le foto» (spec §4.6): one tile per file, in the same times as the grouped mosaic.
var files = await Measure("tutte le foto: prima finestra", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files }));
Assert.HasCount(200, files.Tiles);
Assert.IsTrue(files.Tiles.All(t => t.FilePosition is not null));
var insidePost = files.Tiles.First(t => t.MediaCount == 2 && t.FilePosition == 1);
var resumed = await Measure("tutte le foto: finestra dentro un post", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery
{
Limit = 200,
Mode = MosaicMode.Files,
Cursor = new LibraryCursor(insidePost.PublishedAt, insidePost.EntryId, 1),
}));
Assert.AreEqual((insidePost.EntryId, (int?)2), (resumed.Tiles[0].EntryId, resumed.Tiles[0].FilePosition));
var filesMiddle = await Measure("tutte le foto: finestra a metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Cursor = middleCursor }));
Assert.HasCount(200, filesMiddle.Tiles);
await Measure("tutte le foto: più recente da metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Cursor = middleCursor, Direction = LibraryDirection.Newer }));
await Measure("tutte le foto: filtro Video", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { Kind = LibraryKindFilter.Videos } }));
await Measure("tutte le foto: un account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]] } }));
await Measure("tutte le foto: ricerca comune", AggregateBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { Search = "caffe" } }));
var fileCount = await Measure("tutte le foto: totale dei file", AggregateBoundMs, () => db.Entries.CountLibraryFilesAsync(new LibraryFilter()));
Assert.AreEqual(Entries + (Entries / 5), fileCount);
var fileDays = await Measure("tutte le foto: conteggi per giorno", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files));
Assert.AreEqual(fileCount, fileDays.Sum(d => d.Count));
var accountFiles = await Measure("tutte le foto: conteggi di un account", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]] }, TestZones.Rome, MosaicMode.Files));
Assert.AreEqual(await db.Entries.CountLibraryFilesAsync(new LibraryFilter { AccountIds = [accountIds[3]] }, ct), accountFiles.Sum(d => d.Count));
await Measure("scheda account: Post", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } }));
await Measure("scheda account: Post, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } }));
await Measure("scheda account: conteggi dei Post", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts }, TestZones.Rome));
await Measure("tutte le foto: conteggi del filtro Video", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome, MosaicMode.Files));
await Measure("è già noto? (pagina di 12)", IndexBoundMs, async () => await db.Entries.GetKnownInstagramIdsAsync(accountIds[5], EntryKind.Post, Enumerable.Range(0, 12).Select(i => $"id{5 + (i * 40)}").ToList()));
await Measure("SHA-256 in tutta la libreria", IndexBoundMs, () => db.Media.FindBySha256Async(Make.Sha(150_001)));
var summaries = await Measure("elenco account con conteggi", AggregateBoundMs, () => db.Accounts.ListSummariesAsync(new DateTimeOffset(2026, 10, 1, 0, 0, 0, TimeSpan.Zero)));
+28
View File
@@ -163,6 +163,34 @@ public sealed class DemoTests
Assert.IsGreaterThan(0, videos, "some entries are videos");
}
[TestMethod]
public async Task TutteLeFotoShowsEveryFileOfTheDemoSeriesAlsoTheirVideos()
{
// «Tutte le foto» (spec §4.6) has something to show in the demo: posts of many photos, and series with a video.
var grouped = await GetAsync("/api/library/days");
var files = await GetAsync("/api/library/days?mode=files");
Assert.AreEqual(grouped.Int("entries"), files.Int("entries"));
Assert.IsGreaterThan(grouped.Int("entries"), files.Int("files"), "more files than entries");
Assert.AreEqual(files.Int("files"), files.Items("days").Sum(d => d.Int("count")));
var seriesVideos = 0;
string? cursor = null;
var pages = 0;
do
{
var page = await GetAsync("/api/library?mode=files&kind=videos&limit=600" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor)));
seriesVideos += page.Items("tiles").Count(t => t.Int("files") >= 3 && t.Int("position") == 2);
cursor = page.GetProperty("older").ValueKind == JsonValueKind.String ? page.Str("older") : null;
pages++;
}
while (cursor is not null && pages < 100);
var first = await GetAsync("/api/library?mode=files&limit=600");
var series = first.Items("tiles").Count(t => t.Int("files") > 1 && t.Int("position") == 1);
Assert.IsGreaterThan(0, series, "posts of several photos near the top");
Assert.IsGreaterThan(0, seriesVideos, "some series have a video in second place");
}
[TestMethod]
public async Task EntriesAreDiscoveredAfterPublicationAndTheirFilesLiveInTheTemporaryFolder()
{
@@ -0,0 +1,120 @@
using System.Net;
using System.Text.Json;
using Febe.Core.Domain;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
namespace Febe.Tests.Web;
/// <summary>
/// «Tutte le foto» through the API (spec §4.6): <c>mode=files</c> on the days and on the windows, one tile per file
/// with its position, cursors that go on inside a post, day rows that count files and totals that say both.
/// </summary>
[TestClass]
public sealed class LibraryFilesApiTests
{
[TestMethod]
public async Task WindowsOfFilesWalkEveryFileOnceAndTheDaysCountThem()
{
await using var server = await WebTestServer.StartAsync();
var (entries, files) = await FillAsync(server);
var days = await server.GetJsonAsync("/api/library/days?mode=files");
Assert.AreEqual(entries, days.Int("entries"), "the totals still count the entries");
Assert.AreEqual(files, days.Int("files"));
Assert.AreEqual(files, days.Items("days").Sum(d => d.Int("count")), "the day rows count the files");
Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/library/days")).GetProperty("files").ValueKind, "grouped: no file total");
var seen = new List<(long Ms, long Id, int Position, long Media)>();
string? cursor = null;
var pages = 0;
do
{
var page = await server.GetJsonAsync("/api/library?mode=files&limit=4" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor)));
foreach (var tile in page.Items("tiles"))
{
seen.Add((tile.Long("publishedAt"), tile.Long("id"), tile.Int("position"), tile.GetProperty("cover").Long("mediaId")));
}
cursor = page.GetProperty("older").ValueKind == JsonValueKind.Null ? null : page.Str("older");
pages++;
}
while (cursor is not null && pages < 50);
Assert.HasCount(files, seen);
Assert.HasCount(files, seen.Select(s => s.Media).Distinct(), "every file once");
Assert.HasCount(entries, seen.Select(s => s.Id).Distinct());
for (var i = 1; i < seen.Count; i++)
{
var (a, b) = (seen[i - 1], seen[i]);
Assert.IsTrue(b.Ms < a.Ms || (b.Ms == a.Ms && (b.Id < a.Id || (b.Id == a.Id && b.Position > a.Position))), "entries newest first, each by position");
}
// The cursor of a day starts at that day, in files.
foreach (var day in days.Items("days").Take(3))
{
var page = await server.GetJsonAsync($"/api/library?mode=files&limit={day.Int("count")}&cursor={Uri.EscapeDataString(day.Str("cursor"))}");
Assert.IsTrue(page.Items("tiles").All(t => t.Str("day") == day.Str("day")), day.Str("day"));
Assert.AreEqual(day.Int("count"), page.Items("tiles").Count());
}
// From inside a carousel: the next file of the same post, and back up.
var inside = seen.FindIndex(s => s.Position == 2);
var at = seen[inside];
var next = await server.GetJsonAsync($"/api/library?mode=files&limit=1&cursor={at.Ms}.{at.Id}.{at.Position}");
Assert.AreEqual(seen[inside + 1].Media, next.Items("tiles").Single().GetProperty("cover").Long("mediaId"));
var back = await server.GetJsonAsync($"/api/library?mode=files&limit=2&direction=newer&cursor={at.Ms}.{at.Id}.{at.Position}");
CollectionAssert.AreEqual(seen.Skip(inside - 2).Take(2).Select(s => s.Media).ToList(), back.Items("tiles").Select(t => t.GetProperty("cover").Long("mediaId")).ToList());
// A file tile says the files of its post; the grouped tiles have no position.
var carousel = seen.First(s => s.Position == 3);
var tiles = (await server.GetJsonAsync("/api/library?mode=files&limit=200")).Items("tiles").Where(t => t.Long("id") == carousel.Id).ToList();
Assert.IsTrue(tiles.All(t => t.Int("files") == tiles.Count));
Assert.IsTrue((await server.GetJsonAsync("/api/library?limit=200")).Items("tiles").All(t => t.GetProperty("position").ValueKind == JsonValueKind.Null));
}
[TestMethod]
public async Task FiltersWorkTheSameAndBadValuesAreRefused()
{
await using var server = await WebTestServer.StartAsync();
await FillAsync(server);
// «Video» shows only the video files, «Foto» only the photos.
var videos = await server.GetJsonAsync("/api/library?mode=files&kind=videos&limit=200");
Assert.IsTrue(videos.Items("tiles").All(t => t.GetProperty("cover").Str("kind") == "video"));
Assert.AreEqual(videos.Items("tiles").Count(), (await server.GetJsonAsync("/api/library/days?mode=files&kind=videos")).Int("files"));
var photos = await server.GetJsonAsync("/api/library?mode=files&kind=photos&limit=200");
Assert.IsTrue(photos.Items("tiles").All(t => t.GetProperty("cover").Str("kind") == "photo"));
Assert.AreEqual(4, (await server.GetJsonAsync("/api/library/days?mode=files&kind=stories")).Int("files"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?mode=gatti")).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library/days?mode=tutte")).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?mode=files&cursor=1.2.x")).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?mode=files&cursor=1.2.-1")).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?cursor=99999999999999999.2")).Status, "a time outside the calendar");
}
/// <summary>Ten posts of one to four files (the third of a series is a video) and four stories: entries and files.</summary>
private static async Task<(int Entries, int Files)> FillAsync(WebTestServer server)
{
var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var files = 0;
for (var i = 0; i < 10; i++)
{
var count = (i % 4) + 1;
var media = Enumerable.Range(1, count)
.Select(p => Make.Stored(p == 3 ? Make.Video(p) : Make.Photo(p), Make.Sha((i * 10) + p), $"p/{i}_{p}.jpg"))
.ToList();
await server.Db.Entries.AddAsync(Make.Entry(account.Id, $"p{i}", Make.T0 - TimeSpan.FromHours(9 * i)), media);
files += count;
}
for (var i = 0; i < 4; i++)
{
await server.Db.Entries.AddAsync(Make.Entry(account.Id, $"s{i}", Make.T0 - TimeSpan.FromHours((13 * i) + 2), EntryKind.Story), [Make.Stored(Make.Photo(), Make.Sha(500 + i), $"s/{i}.jpg")]);
files++;
}
return (14, files);
}
}
@@ -0,0 +1,88 @@
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
/// <summary>
/// «Raggruppa i post» / «Tutte le foto» in a real browser, on the demo (spec §4.6, tappa D1): the switch of the tools
/// row, the file tiles with their place («2/4»), the day rows in files, the viewer that opens on the file and counts
/// files, the selection of files that acts on their entries, the choice remembered per page (Libreria apart from the
/// account views) and grouped when the browser keeps nothing. Chromium only (CI).
/// </summary>
[TestClass]
public sealed class LibraryModeInterfaceTests
{
private const string Switch = "document.querySelector('.strumenti .modo-mosaico')";
private const string Mode = Switch + ".querySelector('[aria-checked=true]').dataset.value";
[TestMethod]
public async Task TutteLeFotoShowsTheFilesOpensTheViewerOnTheFileAndIsRememberedPerPage()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("modo-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
await ui.OpenAsync(new Uri(demo.Address, "/libreria"));
await ui.WaitAsync($"{Switch} !== null && document.querySelector('.mosaico .tess') !== null", "Libreria con l'interruttore");
Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), "predefinito «Raggruppa i post» " + ui.Report());
Assert.AreEqual(2, (await ui.EvalAsync($"{Switch}.querySelectorAll('[role=radio]').length")).GetInt32());
var entries = (await ui.EvalAsync("document.querySelector('.quanti')?.textContent || ''")).GetString();
StringAssert.Contains(entries, "elementi");
// «Tutte le foto»: tiles of single files, those of a series with their place.
await ui.EvalAsync($"{Switch}.querySelector('[data-value=files]').click()");
await ui.WaitAsync("[...document.querySelectorAll('.mosaico .tess .segno span')].some((s) => /^\\d+\\/\\d+$/.test(s.textContent))", "tessere con «2/4»");
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.mosaico .giorno span')?.textContent || ''")).GetString(), "file", "la riga del giorno conta i file");
await ui.WaitAsync("/ file in .* elementi di /.test(document.querySelector('.quanti')?.textContent || '')", "«61.034 file in 48.212 elementi di 38 account»");
// The viewer opens on the second file of a series and counts files.
const string Second = "[...document.querySelectorAll('.mosaico .tess')].find((t) => /^2\\/\\d+$/.test(t.querySelector('.segno span')?.textContent || ''))";
await ui.WaitAsync($"({Second}) !== undefined", "un secondo file di una serie");
await ui.EvalAsync($"({Second}).click()");
await ui.WaitAsync("document.querySelector('.vis .serie button[aria-current=true]') !== null", "visualizzatore con la serie");
Assert.AreEqual(1, (await ui.EvalAsync("[...document.querySelectorAll('.vis .serie button')].findIndex((b) => b.getAttribute('aria-current') === 'true')")).GetInt32(), "aperto sul file della tessera");
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.vis .dove').textContent")).GetString(), "file", "«Libreria, file 12 di …»");
var where = (await ui.EvalAsync("document.querySelector('.vis .dove').textContent")).GetString();
await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))");
await ui.WaitAsync($"document.querySelector('.vis .dove').textContent !== {System.Text.Json.JsonSerializer.Serialize(where)}", "la freccia va al file seguente");
await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))");
await ui.WaitAsync("document.querySelector('.vis') === null", "Esc chiude");
// Selection of files: two files of one post are one entry for «Elimina».
await ui.EvalAsync("[...document.querySelectorAll('.strumenti .btn')].find((b) => b.textContent.includes('Seleziona')).click()");
await ui.EvalAsync($"(() => {{ const t = {Second}; const entry = t.dataset.entry; const all = [...document.querySelectorAll(`.mosaico .tess[data-entry='${{entry}}']`)]; all.slice(0, 2).forEach((x) => x.click()); return all.length; }})()");
await ui.WaitAsync("/2 file scelti, di 1 elemento/.test(document.querySelector('.salva .nota')?.textContent || '')", "«2 file scelti, di 1 elemento»");
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.salva .btn.pericolo').textContent")).GetString(), "Elimina 1 elemento");
// Remembered for the Libreria, not for the account views.
await ui.OpenAsync(new Uri(demo.Address, "/libreria"));
await ui.WaitAsync($"{Switch} !== null", "Libreria di nuovo");
Assert.AreEqual("files", (await ui.EvalAsync(Mode)).GetString(), "la Libreria ricorda «Tutte le foto»");
await ui.OpenAsync(new Uri(demo.Address, "/account"));
await ui.WaitAsync("document.querySelector('a[href^=\"/account/\"]') !== null", "elenco degli account");
await ui.EvalAsync("document.querySelector('a[href^=\"/account/\"]').click()");
await ui.WaitAsync($"location.pathname.startsWith('/account/') && {Switch} !== null", "scheda account con l'interruttore");
Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), "le viste degli account hanno la loro scelta");
}
[TestMethod]
public async Task WithoutTheBrowserStorageTheMosaicIsGrouped()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("modo-senza-memoria");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
await ui.AddInitScriptAsync("Object.defineProperty(window, 'localStorage', { configurable: true, get() { throw new DOMException('bloccato', 'SecurityError'); } });");
await ui.OpenAsync(new Uri(demo.Address, "/libreria"));
await ui.WaitAsync($"{Switch} !== null && document.querySelector('.mosaico .tess') !== null", "Libreria senza memoria del browser");
Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), ui.Report());
// The choice still works for the page that is open.
await ui.EvalAsync($"{Switch}.querySelector('[data-value=files]').click()");
await ui.WaitAsync("[...document.querySelectorAll('.mosaico .tess .segno span')].some((s) => /^\\d+\\/\\d+$/.test(s.textContent))", "«Tutte le foto» anche senza memoria");
await ui.OpenAsync(new Uri(demo.Address, "/libreria"));
await ui.WaitAsync($"{Switch} !== null", "Libreria riaperta");
Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), "nulla da ricordare: di nuovo «Raggruppa i post»");
}
}