aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/photos-app.js
blob: 73b8c158157000f72b5c6e462501fe76cdf560c1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import {
  html, useState, useEffect, useMemo, useCallback, useRef,
} from './vendor/htm-preact.js';
import { t } from './i18n.js';
import { Icon } from './icon.js';
import {
  formatSize, CHUNK_SIZE, pipelinedDownload, downloadDirectory,
} from './file-utils.js';
import { transfers } from './transfers.js';
import { MediaThumb, LazyTile } from './media-tiles.js';
import { SourceTag } from './group-name.js';

// ── Photos ───────────────────────────────────────────────────────────────────
//
// docs/MESHBAY_DESIGN.md §9.9. Unlike Videos/Music: several root folders per group
// (photoRoots is a list, §2.1), one album-grid view with no mode toggle and
// no third-party matching step (§2.3), and per-photo info read from the
// file's own EXIF at index time rather than fetched live. Every directory
// containing at least one image under a configured root is one album card;
// opening one shows its photos in a grid with a lightbox (next/previous,
// keyboard arrows, EXIF info when present) and a "zip this album" button
// that reuses Files' own zip mechanism unchanged (file-utils.js's
// downloadDirectory, lifted out of files-app.js for exactly this reuse).

function underAnyPhotoRoot(entry, photoRoots) {
  const p = entry.path || '';
  return (photoRoots || []).some((r) => p === r || p.startsWith(r + '/'));
}

function groupPhotoAlbums(entries, photoRoots) {
  const byDir = new Map();
  for (const e of entries) {
    if (e.type !== 'image' || !underAnyPhotoRoot(e, photoRoots)) continue;
    // e.path is already the file's containing directory, not the full
    // path+filename (files-app.js's own convention, also relied on by
    // zipstream.js's entriesUnder) — it must not be stripped a second time,
    // or every album collapses one level up into its parent (found live:
    // a "backup" root with several subfolders showed as a single "backup"
    // album holding everything, because this line was extracting the
    // dirname of a value that was already a dirname).
    const dir = e.path || '';
    if (!byDir.has(dir)) byDir.set(dir, []);
    byDir.get(dir).push(e);
  }
  return [...byDir.entries()]
    .map(([dir, photos]) => ({
      dir, photos: photos.sort((a, b) => a.name.localeCompare(b.name)),
    }))
    .sort((a, b) => a.dir.localeCompare(b.dir));
}

// Underscores replaced with spaces for display only — this never touches
// the folder on disk or anything sent to the node, purely how the name
// reads in the grid/heading (a raw "mariage_joce" reads worse than
// "mariage joce" for something meant to look like an album, not a filename).
function albumTitle(dir) {
  return dir ? dir.split('/').pop().replace(/_/g, ' ') : t('photo.root_album');
}

function formatTakenAt(ts) {
  if (!ts) return '';
  return new Date(ts * 1000).toLocaleString(undefined, {
    year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
  });
}

// A single year when every dated photo in the album agrees, a range when
// they don't (an album spanning New Year's Eve, or just a loosely-sorted
// folder) — never guessed for photos with no EXIF date at all, which just
// don't count toward it.
function albumYearLabel(photos) {
  const years = [...new Set(
    photos.filter((p) => p.taken_at).map((p) => new Date(p.taken_at * 1000).getFullYear()),
  )].sort((a, b) => a - b);
  if (years.length === 0) return '';
  if (years.length === 1) return String(years[0]);
  return `${years[0]}–${years[years.length - 1]}`;
}

// ── landing grid: one card per album (directory containing images) ─────────

function AlbumCard({ album, transportRef, gekRef, onOpen }) {
  const cover = album.photos.find((p) => p.thumb_hash) || album.photos[0];
  const tRef = cover._tRef || transportRef;
  const gRef = cover._gRef || gekRef;
  const year = albumYearLabel(album.photos);
  return html`
    <div class="photo-album-card" onClick=${onOpen}>
      <${MediaThumb} thumbHash=${cover.thumb_hash} alt=${albumTitle(album.dir)}
        cls="photo-album-cover" transportRef=${tRef} gekRef=${gRef}
        emptyIcon="image" />
      <div class="photo-album-info">
        <div class="photo-album-title">${albumTitle(album.dir)}</div>
        <div class="photo-album-sub">
          ${year}${year ? ' · ' : ''}${t('photo.n_photos', { n: album.photos.length })}
        </div>
        <${SourceTag} entries=${album.photos} cls="photo-card-group" />
      </div>
    </div>
  `;
}

function AlbumLanding({ albums, transportRef, gekRef, onOpen }) {
  return html`
    <div class="photo-album-grid">
      ${albums.map((a) => html`
        <${LazyTile} key=${a.dir} cls="photo-album-tile-slot">
          <${AlbumCard} album=${a} transportRef=${transportRef} gekRef=${gekRef}
            onOpen=${() => onOpen(a.dir)} />
        </${LazyTile}>
      `)}
    </div>
  `;
}

// ── open album: grid of its own photos ──────────────────────────────────────

function PhotoTile({ entry, transportRef, gekRef, onOpen }) {
  const tRef = entry._tRef || transportRef;
  const gRef = entry._gRef || gekRef;
  return html`
    <div class="photo-tile" onClick=${onOpen}>
      <${MediaThumb} thumbHash=${entry.thumb_hash} alt=${entry.name}
        cls="photo-tile-thumb" transportRef=${tRef} gekRef=${gRef}
        emptyIcon="image" />
    </div>
  `;
}

// ── lightbox: full image, next/previous, per-photo info, zoom ──────────────
//
// Cached per session by file id, same shape as media-tiles.js's
// _thumbBlobCache — clicking back and forth between two photos decrypts
// each once, not once per visit.
const _fullBlobCache = new Map();

// Zoom is only ever meaningful for the lightbox's own full-resolution
// image — nowhere else in the app shows one, so there is nothing to gate
// this behind beyond the component itself only ever being mounted for a
// photo.
const ZOOM_STEP = 25;
const ZOOM_MIN = 25;
const ZOOM_MAX = 400;

function Lightbox({ photos, index, transportRef, gekRef, onClose, onNav }) {
  const entry = photos[index];
  const tRef = entry._tRef || transportRef;
  const gRef = entry._gRef || gekRef;
  const [blobUrl, setBlobUrl] = useState(() => _fullBlobCache.get(entry.id) || null);
  const [loading, setLoading] = useState(!_fullBlobCache.has(entry.id));
  // null = "fit to window" (the default, object-fit: contain); a number is
  // an explicit percentage of the image's own natural size, read off the
  // loaded <img> itself rather than trusted from EXIF — accurate whether or
  // not enrichment ever ran, and already EXIF-orientation-corrected the
  // same way the browser renders the <img> itself.
  const [zoomPercent, setZoomPercent] = useState(null);
  const [naturalSize, setNaturalSize] = useState(null);
  const slotRef = useRef(null);

  useEffect(() => {
    const cached = _fullBlobCache.get(entry.id);
    if (cached) { setBlobUrl(cached); setLoading(false); return; }
    setBlobUrl(null);
    setLoading(true);
    let cancelled = false;
    (async () => {
      const transport = tRef.current;
      if (!transport || !transport.connected) { setLoading(false); return; }
      try {
        const totalChunks = Math.ceil(entry.size / CHUNK_SIZE);
        const chunks = await pipelinedDownload(
          transport, gRef.current, entry.id, totalChunks);
        if (cancelled) return;
        const url = URL.createObjectURL(new Blob(chunks));
        _fullBlobCache.set(entry.id, url);
        setBlobUrl(url);
      } catch {
        /* leave the placeholder — a transient fetch failure isn't fatal, next/close still work */
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [entry.id]);

  // Every photo opens fit-to-window, same as any other viewer — a zoom
  // level chosen for one picture saying nothing about the next.
  useEffect(() => { setZoomPercent(null); setNaturalSize(null); }, [entry.id]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowLeft' && index > 0) onNav(-1);
      else if (e.key === 'ArrowRight' && index < photos.length - 1) onNav(1);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose, onNav, index, photos.length]);

  const handleImgLoad = (e) => {
    setNaturalSize({ w: e.target.naturalWidth, h: e.target.naturalHeight });
  };

  // The percentage "fit to window" actually renders at, so the first zoom
  // step moves from *there* rather than silently snapping to 100% first —
  // object-fit: contain never upscales past the image's own natural size
  // (nothing here sets width/height:100% to force it to), so fit is never
  // above 100% either.
  const fitPercent = () => {
    if (!naturalSize || !slotRef.current) return 100;
    const rect = slotRef.current.getBoundingClientRect();
    return Math.min(1, rect.width / naturalSize.w, rect.height / naturalSize.h) * 100;
  };
  const zoomIn = () => setZoomPercent(
    (z) => Math.min(ZOOM_MAX, Math.round(z ?? fitPercent()) + ZOOM_STEP));
  const zoomOut = () => setZoomPercent(
    (z) => Math.max(ZOOM_MIN, Math.round(z ?? fitPercent()) - ZOOM_STEP));
  const zoomFit = () => setZoomPercent(null);
  const zoomActual = () => setZoomPercent(100);

  const zoomed = zoomPercent != null;
  const imgStyle = zoomed && naturalSize
    ? `width:${Math.round(naturalSize.w * zoomPercent / 100)}px; `
    + `height:${Math.round(naturalSize.h * zoomPercent / 100)}px;`
    : '';

  return html`
    <div class="video-overlay photo-lightbox" onClick=${(e) => {
      if (e.target.classList.contains('photo-lightbox')) onClose();
    }}>
      <div class="video-top-bar">
        <span class="video-title">${entry.name}</span>
        <div class="photo-zoom-controls">
          <button class="photo-icon-btn" disabled=${!blobUrl || zoomPercent === ZOOM_MIN}
            onClick=${zoomOut} title=${t('photo.zoom_out')}>
            <${Icon} name="zoom-out" cls="photo-icon-btn-icon" /></button>
          <span class="photo-zoom-percent">
            ${zoomed ? `${zoomPercent}%` : t('photo.zoom_fit_label')}</span>
          <button class="photo-icon-btn" disabled=${!blobUrl || zoomPercent === ZOOM_MAX}
            onClick=${zoomIn} title=${t('photo.zoom_in')}>
            <${Icon} name="zoom-in" cls="photo-icon-btn-icon" /></button>
          <button class="photo-icon-btn ${!zoomed ? 'active' : ''}" disabled=${!blobUrl}
            onClick=${zoomFit} title=${t('photo.zoom_fit_title')}>
            <${Icon} name="frame" cls="photo-icon-btn-icon" /></button>
          <button class="photo-icon-btn photo-icon-btn-text ${zoomPercent === 100 ? 'active' : ''}"
            disabled=${!blobUrl} onClick=${zoomActual} title=${t('photo.zoom_100')}>100%</button>
        </div>
        <button class="video-close" onClick=${onClose} title=${t('video.close')}>
          <${Icon} name="close" /></button>
      </div>
      <div class="photo-lightbox-body">
        <button class="photo-nav photo-nav-prev" disabled=${index === 0}
          onClick=${() => onNav(-1)} title=${t('photo.prev')}>
          <${Icon} name="chevron" cls="photo-nav-icon photo-nav-prev-icon" /></button>
        <div ref=${slotRef} class="photo-lightbox-image-slot ${zoomed ? 'zoomed' : ''}">
          ${loading && html`<span class="spinner"></span>`}
          ${blobUrl && html`<img class="photo-lightbox-image ${zoomed ? 'zoomed' : ''}"
            style=${imgStyle} src=${blobUrl} alt=${entry.name} onLoad=${handleImgLoad} />`}
        </div>
        <button class="photo-nav photo-nav-next" disabled=${index === photos.length - 1}
          onClick=${() => onNav(1)} title=${t('photo.next')}>
          <${Icon} name="chevron" cls="photo-nav-icon photo-nav-next-icon" /></button>
      </div>
      <div class="photo-lightbox-info">
        ${entry.width && entry.height && html`<span>${entry.width}×${entry.height}</span>`}
        <span>${formatSize(entry.size)}</span>
        ${entry.taken_at && html`<span>${formatTakenAt(entry.taken_at)}</span>`}
        ${entry.camera && html`<span>${entry.camera}</span>`}
        <span class="photo-lightbox-count">${index + 1} / ${photos.length}</span>
      </div>
    </div>
  `;
}

function AlbumView({ album, entries, transportRef, gekRef, setError, onBack, readOnly }) {
  const [lightboxIndex, setLightboxIndex] = useState(null);

  const zip = useCallback(async () => {
    const transport = transportRef.current;
    await downloadDirectory(
      transfers, transport, gekRef.current, entries, album.dir, { setError });
  }, [entries, album.dir]);

  const navigate = useCallback((delta) => {
    setLightboxIndex((i) => {
      const next = i + delta;
      return next >= 0 && next < album.photos.length ? next : i;
    });
  }, [album.photos.length]);

  const year = albumYearLabel(album.photos);

  return html`
    <div class="photo-album-bar">
      <div class="photo-album-heading">
        <button class="photo-icon-btn" onClick=${onBack} title=${t('photo.back')}>
          <${Icon} name="chevron" cls="photo-icon-btn-icon photo-back-icon" /></button>
        <div class="photo-album-heading-text">
          <span class="photo-album-heading-title">${albumTitle(album.dir)}</span>
          ${year && html`<span class="photo-album-heading-year">${year}</span>`}
        </div>
      </div>
      ${!readOnly && html`<button class="photo-icon-btn" onClick=${zip} title=${t('photo.zip_album')}>
        <${Icon} name="archive" cls="photo-icon-btn-icon" /></button>`}
    </div>
    <div class="photo-grid">
      ${album.photos.map((e, i) => html`
        <${LazyTile} key=${e.id} cls="photo-tile-slot">
          <${PhotoTile} entry=${e} transportRef=${transportRef} gekRef=${gekRef}
            onOpen=${() => setLightboxIndex(i)} />
        </${LazyTile}>
      `)}
    </div>
    ${lightboxIndex !== null && html`
      <${Lightbox} photos=${album.photos} index=${lightboxIndex}
        transportRef=${transportRef} gekRef=${gekRef}
        onClose=${() => setLightboxIndex(null)} onNav=${navigate} />
    `}
  `;
}

// ── shell ────────────────────────────────────────────────────────────────────

function PhotosApp({
  groupId, transportRef, gekRef, status, entries, availableEntries,
  photoDirectories, setError,
  hideFilter, readOnly,
}) {
  const [openDir, setOpenDir] = useState(null);
  const [filter, setFilter] = useState('');

  useEffect(() => { setOpenDir(null); setFilter(''); }, [groupId]);

  const photoEntries = availableEntries || entries;
  const albums = useMemo(
    () => groupPhotoAlbums(photoEntries, photoDirectories),
    [photoEntries, photoDirectories]);

  const needle = filter.trim().toLowerCase();
  const filteredAlbums = useMemo(() => (!needle ? albums : albums.filter(
    (a) => albumTitle(a.dir).toLowerCase().includes(needle))), [albums, needle]);

  const openAlbum = openDir != null ? albums.find((a) => a.dir === openDir) : null;

  return html`
    ${(status === 'discovering' || status === 'connecting' || status === 'fetching') && html`
      <p class="page-message"><span class="spinner"></span>${' '}${t('status.connecting_short')}</p>
    `}
    ${status === 'offline' && html`
      <p class="page-message">${t('group.offline_title')} ${t('group.offline_hint')}</p>
    `}
    ${status === 'connected' && (photoDirectories || []).length === 0 && html`
      <p class="page-message">${t('photo.no_roots_configured')}</p>
    `}
    ${status === 'connected' && (photoDirectories || []).length > 0 && !openAlbum && html`
      ${/* The filter is the only thing in it, so under `hideFilter` there is
            no toolbar rather than an empty one — an empty band still pins,
            and would hold a strip of the page open under the search field
            for nothing. */
        !hideFilter && html`
        <div class="photo-toolbar">
          <div class="tb-search">
            <${Icon} name="search" />
            <input type="text" placeholder="${t('group.filter')}"
              value=${filter} onInput=${(e) => setFilter(e.target.value)} />
          </div>
        </div>
      `}
      ${filteredAlbums.length === 0 && html`
        <p class="page-message">${needle ? t('group.empty_filter') : t('photo.empty')}</p>
      `}
      <${AlbumLanding} albums=${filteredAlbums}
        transportRef=${transportRef} gekRef=${gekRef}
        onOpen=${(dir) => setOpenDir(dir)} />
    `}
    ${status === 'connected' && openAlbum && html`
      <${AlbumView} album=${openAlbum} entries=${entries}
        transportRef=${transportRef} gekRef=${gekRef} setError=${setError}
        onBack=${() => setOpenDir(null)} readOnly=${readOnly} />
    `}
  `;
}

// groupPhotoAlbums is exported for the Search page, which needs the album a
// photo belongs to in order to merge duplicate sources per album rather than
// per file (docs/MESHBAY_DESIGN.md §9.11). It calls this one, never a copy:
// a second implementation of the album key would keep agreeing with this one
// right up until one of them changed.
export { PhotosApp, groupPhotoAlbums };