diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/features/messages.js | 160 | ||||
| -rw-r--r-- | src/features/nwc.js | 24 | ||||
| -rw-r--r-- | src/image-thumbnails.js | 19 | ||||
| -rw-r--r-- | src/style.css | 14 |
4 files changed, 178 insertions, 39 deletions
diff --git a/src/features/messages.js b/src/features/messages.js index 4900c40..030d9fa 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -6716,7 +6716,8 @@ export function messagesFeature(ctx) { const d = {}; if (!have.size && +f.size > 0) d.size = +f.size; // no size, but a bitrate (bits/s) and a duration (Primal posts these): near enough - else if (!have.size && +f.bitrate > 0 && +f.duration > 0) d.size = Math.round(+f.bitrate * +f.duration / 8); + // (a guess: never taken for the file's identity, see mediaItems) + else if (!have.size && +f.bitrate > 0 && +f.duration > 0) { d.size = Math.round(+f.bitrate * +f.duration / 8); d.sizeGuess = true; } if (!have.dur && +f.duration > 0) d.dur = +f.duration; const m = /^(\d+)(?:\.0+)?x(\d+)(?:\.0+)?$/.exec(f.dim || ''); if (!have.w && m) { d.w = +m[1]; d.h = +m[2]; } @@ -6768,6 +6769,7 @@ export function messagesFeature(ctx) { const videoProbes = new Map(); let videoProbing = 0; const videoProbeQueue = []; + const clipGone = (url) => { const d = videoInfo.get(url); return !!d && typeof d.goneAt === 'number' && Date.now() - d.goneAt < 86_400_000; }; const probeFailedLately = (d) => !!d && typeof d.failedAt === 'number' && Date.now() - d.failedAt < 3_600_000; function probeVideo(url, layout = false) { const have = videoInfo.get(url); @@ -6801,7 +6803,7 @@ export function messagesFeature(ctx) { // player's plain load answers this request without them, and it fails. // Any clip that had played in the feed was "unmeasurable" that way. const r = await fetch(url, { headers: { Range: 'bytes=0-' + (VIDEO_PROBE_BYTES - 1) }, cache: 'no-store', signal: ctrl.signal }); - if (!r.ok) throw new Error('HTTP ' + r.status); + if (!r.ok) throw Object.assign(new Error('HTTP ' + r.status), { status: r.status }); const ranges = r.status === 206; const total = ranges ? +(/\/(\d+)\s*$/.exec(r.headers.get('content-range') || '') || [])[1] : +r.headers.get('content-length'); // never more than the first bytes, even from a server that ignored the range @@ -6818,22 +6820,27 @@ export function messagesFeature(ctx) { let o = 0; for (const p of parts) { if (o >= buf.length) break; buf.set(p.subarray(0, buf.length - o), o); o += p.length; } const head = readMp4Head(buf); - const d = { probed: true, ranges, faststart: head.faststart === true, failedAt: undefined, ...(head.moovEnd ? { moovEnd: head.moovEnd } : {}), ...(head.hevc ? { hevc: true } : {}), ...(head.dur && !(videoInfo.get(url) || {}).dur ? { dur: head.dur } : {}) }; - if (total > 0) d.size = total; + const d = { probed: true, ranges, faststart: head.faststart === true, failedAt: undefined, goneAt: undefined, ...(head.moovEnd ? { moovEnd: head.moovEnd } : {}), ...(head.hevc ? { hevc: true } : {}), ...(head.dur && !(videoInfo.get(url) || {}).dur ? { dur: head.dur } : {}) }; + if (total > 0) { d.size = total; d.sizeGuess = undefined; } else { // a server that hides Content-Range from scripts (Primal's) still // says Content-Length to a HEAD, which any page may read try { const hr = await fetch(url, { method: 'HEAD', cache: 'no-store', signal: AbortSignal.timeout(5000) }); const n = +hr.headers.get('content-length'); - if (hr.ok && n > 0) d.size = n; + if (hr.ok && n > 0) { d.size = n; d.sizeGuess = undefined; } } catch {} } if (head.w && !(videoInfo.get(url) || {}).w) { d.w = head.w; d.h = head.h; } if (head.w) rememberVideo(url, head.w, head.h); noteVideoInfo(url, d); - } catch { - noteVideoInfo(url, { failedAt: Date.now() }); // a host that won't say (no CORS, down, slow): asked again in an hour + } catch (e) { + // a host that won't say (no CORS, down, slow): asked again in an hour. + // One that says the file is gone (deleted: a 404 or 410) is believed + // for a day, and the grid leaves the clip out (clipGone). + const gone = e && (e.status === 404 || e.status === 410); + noteVideoInfo(url, { failedAt: Date.now(), ...(gone ? { goneAt: Date.now() } : {}) }); + if (gone && mediaMode === 'videos') scheduleRepaint(); } finally { clearTimeout(timer); } return videoInfo.get(url); } @@ -7980,6 +7987,7 @@ export function messagesFeature(ctx) { const h264Of = (url) => VMEDIA + 'h264.mp4?u=' + encodeURIComponent(url); const noPicture = new Set(), h264Failed = new Set(); const serverThumbFailed = new Set(); // clips vmedia had no picture for (this session) + const deadTiles = new Set(); // grid pictures that wouldn't load (this session): left out // A picture from a host that won't hand over its bytes (no CORS: primal's // blossom, nostrcheck, most personal sites) can't have its column copy made // here, so the server makes it (pic.webp: 1100px wide, or a 360px square @@ -13717,12 +13725,17 @@ export function messagesFeature(ctx) { // <img> of the original (or the 1100px column copy) to fetch and decode, // and the browser's lazy margin is a screen or two. These are local and a // few KB, so every tile loads at once and decodes in no time. - const TILE_CACHE = 'coinos-tile-thumbs-v1', TILE_PX = 360, TILE_MAX = 1200; + const TILE_CACHE = 'coinos-tile-thumbs-v2', TILE_PX = 360, TILE_MAX = 1200; const tileThumbs = new Map(); // url -> object URL const tileKey = (url) => 'https://tile-thumb.invalid/?u=' + encodeURIComponent(url); const tileQueue = [], tileTried = new Set(), tileLooked = new Set(); let tileBusy = 0, tileRepaint = null; - const tileStore = () => caches.open(TILE_CACHE); + let tileOldGone = false; + const tileStore = () => { + // the square tiles of before (v1) go: the grid's rows want each shape + if (!tileOldGone) { tileOldGone = true; caches.delete('coinos-tile-thumbs-v1').catch(() => {}); } + return caches.open(TILE_CACHE); + }; async function warmTileThumbs(urls) { if (typeof caches === 'undefined') return; let found = 0; @@ -13742,7 +13755,7 @@ export function messagesFeature(ctx) { const kept = mediaReady.get(url)?.thumb; if (!kept && (noCorsHost(url) || corsRefused.has(url))) { // the host keeps its bytes: the server cuts the tile - const tile = await serverPicBlob(url, 'tile'); + const tile = await serverPicBlob(url, 'row'); if (tile) await saveTileThumb(url, tile); return; } @@ -13752,7 +13765,7 @@ export function messagesFeature(ctx) { if (!res.ok) return; blob = await res.blob(); } catch (e) { - if (e && e.corsRefused) { corsRefused.add(url); const tile = await serverPicBlob(url, 'tile'); if (tile) await saveTileThumb(url, tile); } + if (e && e.corsRefused) { corsRefused.add(url); const tile = await serverPicBlob(url, 'row'); if (tile) await saveTileThumb(url, tile); } return; } if (/gif/i.test(blob.type)) return; // animated: the tile shows the original @@ -13907,16 +13920,51 @@ export function messagesFeature(ctx) { // videos by default on a phone that's in vertical orientation and only // horizontal videos if the phone is in landscape but have some kind of // control to toggle the ability to see all videos".) - const CLIPS_FIT_KEY = 'coinos-clips-fit'; // 'all', or unset: the screen's way round - const clipsAll = () => { try { return localStorage.getItem(CLIPS_FIT_KEY) === 'all'; } catch { return false; } }; - const setClipsAll = (all) => { try { if (all) localStorage.setItem(CLIPS_FIT_KEY, 'all'); else localStorage.removeItem(CLIPS_FIT_KEY); } catch {} }; + // On a desktop-sized window every shape is the default (Adam, 2026-10-22: + // the justified rows hold both); a phone keeps to its way round. + const CLIPS_FIT_KEY = 'coinos-clips-fit'; // 'all', 'fit' (the screen's way round), or unset: the device's default + const bigWindow = () => { try { return matchMedia('(min-width: 1000px) and (min-height: 600px)').matches; } catch { return false; } }; + const clipsAll = () => { try { const v = localStorage.getItem(CLIPS_FIT_KEY); return v === 'all' || (v !== 'fit' && bigWindow()); } catch { return bigWindow(); } }; + const setClipsAll = (all) => { try { if (all === bigWindow()) localStorage.removeItem(CLIPS_FIT_KEY); else localStorage.setItem(CLIPS_FIT_KEY, all ? 'all' : 'fit'); } catch {} }; const screenTall = () => window.innerHeight >= window.innerWidth; - const clipShape = (url) => { + const clipSize = (url) => { const d = videoInfo.get(url) || {}; const k = d.w && d.h ? d : videoDims.get(url) || mediaReady.get(url); const w = k && (k.w || k.width), hh = k && (k.h || k.height); - return w && hh ? (hh > w ? 'tall' : hh < w ? 'wide' : 'square') : null; + return w && hh ? { w, h: hh } : null; }; + // (no size yet: the still's proportions, which a grid of every shape has + // loaded without measuring anything — so going back to one shape finds + // the clips' shapes known) + const clipShape = (url) => { + const z = clipSize(url), r = z ? z.w / z.h : posterAr.get(url); + return r ? (r < 0.99 ? 'tall' : r > 1.01 ? 'wide' : 'square') : null; + }; + // width over height, kept between a phone's upright 9:16 and a cinema 2:1 + // (a stray 32:9 or 1:4 would make a tile a sliver); unknown: a square + // (until the clip's size is known, the still's own proportions: the + // server's and a frame grab keep the clip's shape) + const posterAr = new Map(); + const clampAr = (r) => Math.min(2, Math.max(0.5, r)); + const clipRatio = (url) => { const z = clipSize(url); return z ? clampAr(z.w / z.h) : posterAr.get(url) || 1; }; + // a grid item's: the file's measured size, the post's word for it (NIP-92 + // dim), or its still once that has loaded + function itemRatio(it) { + if (clipSize(it.url)) return clipRatio(it.url); + for (const tag of it.ev.tags || []) { + if (tag[0] !== 'imeta' || !tag.includes('url ' + it.url)) continue; + const m = /^(\d+)(?:\.0+)?x(\d+)(?:\.0+)?$/.exec(imetaFields(tag).dim || ''); + if (m && +m[1] && +m[2]) return clampAr(+m[1] / +m[2]); + } + return posterAr.get(it.url) || 1; + } + function arFromStill(img, url) { + if (clipSize(url) || !img.naturalWidth || !img.naturalHeight) return; + const r = clampAr(img.naturalWidth / img.naturalHeight); + posterAr.set(url, r); + const tile = img.closest('.media-grid.justified .media-tile'); + if (tile) tile.style.setProperty('--ar', r.toFixed(3)); + } // true/false, or null while the clip's shape isn't known const clipFits = (url) => { if (clipsAll()) return true; const sh = clipShape(url); return sh === null ? null : sh === 'square' || sh === (screenTall() ? 'tall' : 'wide'); }; const clipsLabel = () => t(clipsAll() ? 'clipsAll' : screenTall() ? 'clipsTall' : 'clipsWide'); @@ -13952,7 +14000,10 @@ export function messagesFeature(ctx) { // or the same words from the same person posted again with another upload. const sameFile = (url) => { const m = /\/([0-9a-f]{64})(?:\.\w+)?(?:[?#]|$)/i.exec(url); return m ? m[1].toLowerCase() : url.replace(/[?#].*$/, ''); }; const saidAgain = (ev) => { const w = String(ev.content || '').replace(/https?:\/\/\S+/g, '').replace(/\s+/g, ' ').trim(); return w.length >= 8 ? ev.pubkey + '|' + w : null; }; - function mediaItems(c, kind) { + // (anyShape: the pager's list — every clip, the ones the wrong way round + // for the screen held out of sight by pagerFit, so "All shapes" there has + // them to show) + function mediaItems(c, kind, anyShape = false) { const out = [], seen = new Set(), said = new Map(); const r = mediaIndex(c.id); indexMedia(r, c.notes); @@ -13965,15 +14016,24 @@ export function messagesFeature(ctx) { const again = saidAgain(ev); if (again && said.has(again) && said.get(again) !== ev.id) continue; if (kind === 'videos') learnVideoMeta(ev); - const urls = kind === 'videos' ? clipUrlsOf(ev).filter(fitClip) + // (a clip whose host says it's deleted has nothing to show: a blank tile) + const urls = kind === 'videos' ? clipUrlsOf(ev).filter((u) => !clipGone(u) && (anyShape || fitClip(u))) : noteMediaUrls(ev.content).filter((u) => !u.startsWith('https://i.ytimg.com/')); // (the words are taken by a post that shows: one whose clip doesn't fit // the screen leaves them to the next) if (again && urls.length) said.set(again, ev.id); for (const url of urls) { + if (deadTiles.has(url)) continue; const f = sameFile(url); if (seen.has(f)) continue; seen.add(f); + // the same clip uploaded twice by one person (a note and a video + // event a few minutes apart) gets two hashes but keeps its size to + // the byte + const d = kind === 'videos' ? videoInfo.get(url) || {} : {}; + const twin = d.size && !d.sizeGuess ? ev.pubkey + '|' + d.size : null; + if (twin && seen.has(twin)) continue; + if (twin) seen.add(twin); out.push({ ev, url }); } } @@ -14195,7 +14255,15 @@ export function messagesFeature(ctx) { if (missing.length) warmTileThumbs(missing).then(() => queueTileThumbs(missing.filter((u) => !tileThumbs.has(u)))); } if (mediaMode === 'videos') for (const it of items.slice(0, 24)) preconnect(playSrc(it.url)); - return h('div', { class: 'media-grid', 'data-key': 'media-grid:' + mediaMode }, + // The tiles take the clips' shape (Adam, 2026-10-22): wide clips only (a + // wide screen) go one to a row, their posters whole, not slivers cut to + // portrait tiles; every shape ("All shapes") is laid out in justified + // rows, each tile its clip's own proportions and each row as tall as it + // takes to fill the width; tall ones only (a phone held upright) keep + // the tall tiles three across. + // Pictures go in justified rows too, in their own shapes. + const shape = mediaMode === 'images' ? ' justified' : mediaMode !== 'videos' ? '' : clipsAll() ? ' justified' : screenTall() ? '' : ' wide'; + return h('div', { class: 'media-grid' + shape, 'data-key': 'media-grid:' + mediaMode }, ...items.map((it) => { const k = mediaKey(it); // a video tile shows a still at once: kept, given, or the server's @@ -14208,19 +14276,28 @@ export function messagesFeature(ctx) { const fromServer = mediaMode === 'videos' && poster && poster === serverThumb(it.url); return h('button', { class: 'media-tile' + (mediaMode === 'videos' ? ' video' : ''), type: 'button', 'data-key': 'tile:' + k, + style: shape === ' justified' ? '--ar:' + itemRatio(it).toFixed(3) : undefined, 'aria-label': displayName(it.ev.pubkey), onClick: () => openMediaPager(mediaMode, k), onPointerDown: mediaMode === 'videos' ? () => earlyPlayer(it.url) : undefined, }, mediaMode === 'images' || poster ? h('img', { src: poster || tileThumbs.get(it.url) || mediaSrc(it.url), alt: '', draggable: 'false', loading: poster || tileThumbs.has(it.url) ? 'eager' : 'lazy', decoding: 'async', + onLoad: (e) => arFromStill(e.currentTarget, it.url), onError: (e) => { if (fromServer) { serverThumbFailed.add(it.url); render(); return; } // the frame grab's turn + // remembered, not only a class on the tile: the next + // repaint rewrites the class list, and the broken-picture + // glyph came back (a deleted nostr.media file in #artstr) + deadTiles.add(it.url); const b = e.target.closest('.media-tile'); if (b) b.classList.add('broken'); + scheduleRepaint(); } }) // no still to show: the clip's first frame, fetched once the tile is near : h('video', { 'data-src': it.url + '#t=0.1', muted: true, playsinline: true, preload: 'metadata' }), - mediaMode === 'videos' && poster && videoInfo.get(it.url)?.size && videoHeavy(it.url) ? h('span', { class: 'media-tile-badge' }, heavyLabel(it.url)) : null, + // (drawn here whatever the tile shows, so a repaint keeps the one + // the frame-grab added) + mediaMode === 'videos' && videoInfo.get(it.url)?.size && videoHeavy(it.url) ? h('span', { class: 'media-tile-badge' }, heavyLabel(it.url)) : null, mediaMode === 'videos' ? h('span', { class: 'media-tile-play', 'aria-hidden': 'true' }, '▶') : null); })); } @@ -14234,8 +14311,14 @@ export function messagesFeature(ctx) { if (!e.isIntersecting) continue; const v = e.target; tileObs.unobserve(v); - const tile = v.closest('.media-tile'); - if (tile) tile._skipMorph = true; + // the player (and whatever stands in for it) is left alone by + // repaints, which would strip its src; the tile around it keeps up + // with them (its shape when the grid's layout changes, its class). + // Freezing the whole tile kept a tile built for one-to-a-row out of + // the justified rows: no --ar, no width. + v._skipMorph = true; + const standIn = (el) => { el._skipMorph = true; return el; }; + const badge = (el) => { if (!el.parentNode.querySelector('.media-tile-badge')) el.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); }; // A first frame costs the start of the file when the index leads or // the server serves ranges — whatever the clip's size. Only an // index-last file without ranges would have to come down whole for @@ -14249,9 +14332,11 @@ export function messagesFeature(ctx) { if (await grabFrame(url)) { if (!v.isConnected) return; const img = document.createElement('img'); - img.alt = ''; img.draggable = false; img.src = videoThumbs.get(url); + img.alt = ''; img.draggable = false; + img.addEventListener('load', () => arFromStill(img, url), { once: true }); + img.src = videoThumbs.get(url); v.replaceWith(img); - if (heavy && d.size) img.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); + if (heavy && d.size) badge(img); return; } if (!v.isConnected) return; @@ -14263,7 +14348,7 @@ export function messagesFeature(ctx) { const cap = setTimeout(() => { if (v.readyState >= 2 || !v.isConnected) return; try { v.removeAttribute('src'); v.load(); } catch {} - v.replaceWith(h('span', { class: 'media-tile-cost' }, '')); + v.replaceWith(standIn(h('span', { class: 'media-tile-cost' }, ''))); }, 8000); v.addEventListener('loadeddata', () => clearTimeout(cap), { once: true }); } @@ -14271,11 +14356,23 @@ export function messagesFeature(ctx) { // (a plain load: shown, not kept — a player's pixels can only be // read from a CORS load, and those fail on a cached plain copy) v.muted = true; + // a clip the player can't load either is gone as far as the grid + // goes: a deleted file whose 404 came without CORS headers + // (Primal's blossom) only looked like a quiet host to the probe, + // and its tile sat blank. Left out for a day, like a 404 the + // probe could read. + v.addEventListener('error', () => { + if (!v.isConnected || !v.getAttribute('src')) return; // let go of by the eight-second cap + noteVideoInfo(url, { goneAt: Date.now() }); + const b = v.closest('.media-tile'); + if (b) b.classList.add('broken'); + scheduleRepaint(); + }, { once: true }); v.src = v.getAttribute('data-src'); - if (heavy && d.size) v.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); + if (heavy && d.size) badge(v); return; } - v.replaceWith(h('span', { class: 'media-tile-cost' }, d && d.size ? heavyLabel(url) : '')); + v.replaceWith(standIn(h('span', { class: 'media-tile-cost' }, d && d.size ? heavyLabel(url) : ''))); }); } }, { rootMargin: '400px 0px' }); @@ -15587,7 +15684,7 @@ export function messagesFeature(ctx) { const c = feedNow(); pager.groups ||= new Map(); const src = pagerSource(); - for (const it of (src ? src.items(pager.kind) : mediaItems(c, pager.kind))) { + for (const it of (src ? src.items(pager.kind) : mediaItems(c, pager.kind, true))) { const k = mediaKey(it); if (pager.keys.has(k)) continue; pager.keys.add(k); @@ -15683,8 +15780,13 @@ export function messagesFeature(ctx) { function pagerFit() { if (!pager) return; const cur = pager.cur || pager.anchor, cg = cur && cur.closest('.mp-group'); + // the grid's pager goes by the grid's rule: a clip of a shape not yet + // known stays out until it's measured (fitClip measures it); a page's + // pager shows one until it's known not to fit + const strict = pager.kind === 'videos' && !pagerSource(); + const ok = (u) => (strict ? fitClip(u) : clipFits(u) !== false); for (const g of pagerGroups(true)) { - const fits = g._opened || g === cg || [...g._row.children].some((s) => { const m = s.querySelector('.mp-media'); return !m || clipFits(m.getAttribute('data-full') || m.getAttribute('data-src')) !== false; }); + const fits = g._opened || g === cg || [...g._row.children].some((s) => { const m = s.querySelector('.mp-media'); return !m || ok(m.getAttribute('data-full') || m.getAttribute('data-src')); }); pagerToggleGroup(g, 'mp-off', !fits); } } diff --git a/src/features/nwc.js b/src/features/nwc.js index ec79081..9c71a7f 100644 --- a/src/features/nwc.js +++ b/src/features/nwc.js @@ -822,6 +822,25 @@ export function nwcFeature(ctx) { // wrong keys — background wake-ups silently die the first time a // connection is recreated. Debounced; the server replaces by endpoint. let regTimer = null; + // The browser's subscription, made again when it's gone: iOS drops it after + // three pushes that showed no notification (and a key rotation strands an + // old one), and nothing else re-arms a wallet whose `background` is still on. + async function currentSub() { + const reg = await navigator.serviceWorker.ready; + const { publicKey } = await (await fetch(`${NOTIFIER}/vapid`)).json(); + const want = b64ToBytes(publicKey); + let sub = await reg.pushManager.getSubscription(); + if (sub) { + let have = []; + try { have = new Uint8Array(sub.options.applicationServerKey || []); } catch {} + if (have.length === want.length && have.every((b, i) => b === want[i])) return sub.toJSON(); + try { await sub.unsubscribe(); } catch {} + } + if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return null; + sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: want }); + dlog('nwc: push subscription was gone, made a new one'); + return sub.toJSON(); + } function refreshRegistration() { if (!load().background) return; if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) return; @@ -831,8 +850,7 @@ export function nwcFeature(ctx) { const pks = watchPks(); if (!pks.length) return; const up2 = upEndpoint(); - const sub = up2 ? { endpoint: up2, unifiedpush: true } - : await (await navigator.serviceWorker.ready).pushManager.getSubscription().then((x) => x && x.toJSON()); + const sub = up2 ? { endpoint: up2, unifiedpush: true } : await currentSub(); if (!sub) return; await fetch(`${NOTIFIER}/register`, { method: 'POST', headers: { 'content-type': 'application/json' }, @@ -949,7 +967,7 @@ export function nwcFeature(ctx) { if (typeof window !== 'undefined') { window.addEventListener('online', () => listen()); document.addEventListener('visibilitychange', () => { - if (document.visibilityState === 'visible' && conns().length) listen(); + if (document.visibilityState === 'visible' && conns().length) { listen(); refreshRegistration(); } }); } } diff --git a/src/image-thumbnails.js b/src/image-thumbnails.js index ffac4b9..2686dac 100644 --- a/src/image-thumbnails.js +++ b/src/image-thumbnails.js @@ -14,16 +14,21 @@ function thumbnailWorker() { const result = { width: bitmap.width, height: bitmap.height, media: null, tile: null }; // GIFs must keep animating; a canvas copy would freeze their first frame. if (!/gif/i.test(blob.type)) { + // The grid's tile: the picture in its own shape (justified rows), + // tileSize tall, its middle cut to between 1:2 and 2:1 — the most a + // tile stretches either way. if (tileSize) { - const side = Math.min(bitmap.width, bitmap.height), px = Math.min(tileSize, side); - let square; + const W = bitmap.width, H = bitmap.height; + const cw = Math.min(W, H * 2), ch = Math.min(H, W * 2); + const th = Math.min(tileSize, ch), tw = Math.max(1, Math.round(th * cw / ch)); + let cut; try { - square = await createImageBitmap(bitmap, (bitmap.width - side) / 2, (bitmap.height - side) / 2, side, side, - { resizeWidth: px, resizeHeight: px, resizeQuality: 'high' }); - const canvas = new OffscreenCanvas(px, px); - canvas.getContext('2d').drawImage(square, 0, 0); + cut = await createImageBitmap(bitmap, (W - cw) / 2, (H - ch) / 2, cw, ch, + { resizeWidth: tw, resizeHeight: th, resizeQuality: 'high' }); + const canvas = new OffscreenCanvas(tw, th); + canvas.getContext('2d').drawImage(cut, 0, 0); result.tile = await encode(canvas, 0.8); - } catch {} finally { square?.close(); } + } catch {} finally { cut?.close(); } } if (width && bitmap.width > width * 1.25) { try { diff --git a/src/style.css b/src/style.css index 4fbe96b..275bb59 100644 --- a/src/style.css +++ b/src/style.css @@ -1538,6 +1538,20 @@ body::after { background: var(--surface2); overflow: hidden; cursor: pointer; } .media-tile.video { aspect-ratio: 9 / 16; } +/* only wide clips in it: one to a row, the poster whole */ +.media-grid.wide { grid-template-columns: 1fr; gap: 6px; } +.media-grid.wide .media-tile.video { aspect-ratio: 16 / 9; } +/* every shape in it: justified rows. A tile starts at its proportions at + the row height and grows in proportion to them, so a row's tiles share one + height and fill the width; the filler takes the last row's slack instead + of stretching its few tiles. */ +.media-grid.justified { display: flex; flex-wrap: wrap; --row-h: 140px; } +.media-grid.justified .media-tile { aspect-ratio: var(--ar); flex: var(--ar) 1 calc(var(--ar) * var(--row-h)); min-width: 0; } +.media-grid.justified::after { content: ''; flex: 1000 1 0; } +/* the picture fills the tile without sizing it: a frame-grab <video>'s own + 320px would widen its tile, and the row's height with it */ +.media-grid.justified .media-tile > img, .media-grid.justified .media-tile > video { position: absolute; inset: 0; } +@media (max-width: 600px) { .media-grid.justified { --row-h: 100px; } } .media-tile img, .media-tile video { width: 100%; height: 100%; object-fit: cover; display: block; pointer-events: none; } .media-tile.broken { display: none; } .media-tile-play { |
