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:
1 parent
34fe5e9073
commit
30e159cbd4
23 files changed
+1126
-130
No files matched your search
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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){
|
||||
|
||||
@@ -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')))),
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user