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

+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",