aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/features/messages.js17
-rw-r--r--src/style.css2
-rw-r--r--tools/slow-image-test.js73
3 files changed, 89 insertions, 3 deletions
diff --git a/src/features/messages.js b/src/features/messages.js
index 4512818..358bd2e 100644
--- a/src/features/messages.js
+++ b/src/features/messages.js
@@ -6073,6 +6073,7 @@ export function messagesFeature(ctx) {
// a late response is useful on the next visit, not a mid-read replacement.
const READY_MS = 8000;
const mediaReady = new Map(); // URL -> decoded dimensions
+ const mediaFailed = new Set(); // URLs whose picture refused to load (not merely slow)
const mediaWarming = new Map();
// A post's photo is often the camera's original — 3024px wide, twelve
// megapixels — painted into a column a sixth of that. Chrome decodes it
@@ -6160,11 +6161,11 @@ export function messagesFeature(ctx) {
const done = (ok) => {
clearTimeout(timer);
img.onload = img.onerror = null;
- if (ok) mediaReady.set(url, { width: img.naturalWidth, height: img.naturalHeight });
+ if (ok) { mediaReady.set(url, { width: img.naturalWidth, height: img.naturalHeight }); mediaFailed.delete(url); }
resolve();
};
img.onload = () => { (img.decode ? img.decode() : Promise.resolve()).then(() => done(true), () => done(false)); };
- img.onerror = () => done(false);
+ img.onerror = () => { mediaFailed.add(url); done(false); };
img.src = url;
}).finally(() => { if (mediaWarming.get(url) === task) mediaWarming.delete(url); });
task.plain = true;
@@ -7726,7 +7727,17 @@ export function messagesFeature(ctx) {
if (AUDIO_RE.test(url)) return audioNode(url, label);
if (isImage || /\.(png|jpe?g|gif|webp|avif)(\?[^\s]*)?$/i.test(url)) {
const size = feedPaint ? feedMedia(url) : null;
- if (feedPaint && !size) return h('a', { href: url, target: '_blank', rel: 'noopener noreferrer' }, label || url);
+ if (feedPaint && !size) {
+ // a picture that refused to load is a link; one that was merely
+ // slow (a 3.5 MB PNG on a phone outran the row's deadline) keeps
+ // loading inside a box of fixed shape, so nothing moves when it lands
+ if (mediaFailed.has(url)) return h('a', { href: url, target: '_blank', rel: 'noopener noreferrer' }, label || url);
+ return h('img', {
+ src: url, class: 'note-img note-img-late clickable', loading: 'lazy', decoding: 'async', alt: label || '',
+ onClick: (e) => { if (!onPicture(e)) return; e.stopPropagation(); ctx.openImage && ctx.openImage(url); },
+ onError: (e) => { e.target.style.display = 'none'; },
+ });
+ }
// tap it to see it full size (the feed shows it uncropped, but
// height-capped: see .note-img)
const known = size || mediaReady.get(url);
diff --git a/src/style.css b/src/style.css
index 8d41124..dad0520 100644
--- a/src/style.css
+++ b/src/style.css
@@ -691,6 +691,8 @@ html:has(#app .chat-card), body:has(#app .chat-card) { overflow: hidden; }
its width/height, keeps the frame to the picture) */
.note-img { display: block; max-width: min(100%, calc(min(560px, 70vh) * var(--ar, 100))); max-height: min(560px, 70vh); border-radius: 10px; margin-top: 6px; object-fit: contain; }
.note-img.clickable { cursor: zoom-in; }
+/* a picture still loading when its row was frozen: a fixed box, fitted inside */
+.note-img.note-img-late { width: 100%; max-width: 100%; aspect-ratio: 4 / 3; height: auto; background: rgba(127,127,127,.08); }
/* The row under a post: reply, boost, quote, react, zap — spread across the
post's full width so each is a comfortable target, quiet until one carries
a count or you've used it. */
diff --git a/tools/slow-image-test.js b/tools/slow-image-test.js
new file mode 100644
index 0000000..463a855
--- /dev/null
+++ b/tools/slow-image-test.js
@@ -0,0 +1,73 @@
+// A feed row waits up to 8 s for its pictures, then freezes as it is. A
+// picture still downloading then (a 3.5 MB PNG on a phone) used to be frozen
+// as a bare link — the post looked broken until opened. Now it keeps loading
+// inside a fixed box (nothing moves when it lands); a picture that refused to
+// load is still a link.
+// Run: bun tools/slow-image-test.js
+import puppeteer from './puppeteer.js';
+import { cacheKeyFor } from '../src/wallet.js';
+import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
+import { buildHtml } from '../build.js';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+let ok = true;
+const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
+const AUTHOR = (() => { const sk = generateSecretKey(); return { sk, pk: getPublicKey(sk) }; })();
+const now = Math.floor(Date.now() / 1000);
+const html = await buildHtml({ minify: true, pwa: false });
+const server = Bun.serve({ port: 5313, idleTimeout: 60, async fetch(req) {
+ const p = new URL(req.url).pathname;
+ if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p));
+ if (p === '/slow.png') { await sleep(11000); return new Response(PNG, { headers: { 'content-type': 'image/png', 'access-control-allow-origin': '*' } }); }
+ if (p === '/gone.png') return new Response('no', { status: 404 });
+ return new Response(html, { headers: { 'content-type': 'text/html' } });
+} });
+const POSTS = [
+ finalizeEvent({ kind: 1, created_at: now - 100, tags: [], content: 'slow picture http://localhost:5313/slow.png' }, AUTHOR.sk),
+ finalizeEvent({ kind: 1, created_at: now - 200, tags: [], content: 'dead picture http://localhost:5313/gone.png' }, AUTHOR.sk),
+];
+const browser = await puppeteer.launch({ relays: 'read', executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] });
+const page = await browser.newPage();
+// the posts arrive from a relay, as live ones do (cached rows skip the gate)
+await page.evaluateOnNewDocument((fx) => {
+ const Real = window.WebSocket;
+ const fits = (ev, f) => (!f.kinds || f.kinds.includes(ev.kind)) && (!f.authors || f.authors.includes(ev.pubkey)) && (!f.ids || f.ids.includes(ev.id));
+ window.WebSocket = function (...a) { const ws = new Real(...a); const send = ws.send.bind(ws); ws.send = (d) => { try { const m = JSON.parse(d); if (m[0] === 'REQ') { const fs = m.slice(2); setTimeout(() => { if (window.__live) for (const ev of fx.filter((e) => fs.some((f) => fits(e, f)))) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], ev]) })); ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })); }, 0); return; } if (m[0] === 'EVENT') return; } catch {} return send(d); }; return ws; };
+ window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real);
+}, POSTS);
+const errs = [];
+page.on('pageerror', (e) => errs.push(String(e)));
+const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t);
+const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
+const row = (m) => `[...document.querySelectorAll('[data-zap-post]')].find((n) => n.textContent.includes(${JSON.stringify(m)}))`;
+try {
+ await page.setViewport({ width: 390, height: 844 });
+ await page.goto('http://localhost:5313/', { waitUntil: 'domcontentloaded' });
+ await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
+ await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400);
+ await click('create a new wallet'); await sleep(600);
+ await page.waitForSelector('.words .w .t');
+ const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' ');
+ await click('skip verification');
+ await waitText('receive', 20000);
+ const base = cacheKeyFor(mn + '\n');
+ await page.evaluate(([k, pk, ns]) => {
+ localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) }));
+ localStorage.setItem(k + ':profiles', JSON.stringify({ [pk]: { name: 'Slowpoke', t: Date.now() } }));
+ localStorage.setItem('btc-wallet-feed:' + k, 'following');
+ }, [base, AUTHOR.pk, POSTS]);
+ await page.evaluateOnNewDocument(() => { window.__live = true; });
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await waitText('receive', 20000);
+ await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click());
+ check('both posts show', await waitText('slow picture', 30000) && await waitText('dead picture', 5000), JSON.stringify(await page.evaluate(() => [window.__live, (window.__reqlog || []).filter((r) => r.includes('[1')).slice(0, 4)])));
+ check('the slow picture is a picture box, not a link', await page.evaluate((r) => { const n = eval(r); return !!n && !!n.querySelector('img.note-img') && ![...n.querySelectorAll('a')].some((a) => a.href.endsWith('/slow.png')); }, row('slow picture')),
+ await page.evaluate((r) => eval(r)?.innerHTML.slice(0, 300), row('slow picture')));
+ let loaded = false;
+ for (let i = 0; i < 60 && !loaded; i++) { loaded = await page.evaluate((r) => { const i = eval(r)?.querySelector('img.note-img'); return !!i && i.complete && i.naturalWidth > 0; }, row('slow picture')); if (!loaded) await sleep(250); }
+ check('...and it lands once downloaded', loaded);
+ check('a picture that refused to load is a link', await page.evaluate((r) => { const n = eval(r); return !!n && [...n.querySelectorAll('a')].some((a) => a.href.endsWith('/gone.png')) && !n.querySelector('img.note-img'); }, row('dead picture')));
+ check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
+} finally { await browser.close(); server.stop(true); }
+console.log(ok ? '\n✅ slow pictures keep loading in place' : '\n❌ failed');
+process.exit(ok ? 0 : 1);