diff --git a/e2e/comment-detail.spec.ts b/e2e/comment-detail.spec.ts index 54ce9eb..bcaa629 100644 --- a/e2e/comment-detail.spec.ts +++ b/e2e/comment-detail.spec.ts @@ -34,6 +34,22 @@ test.describe('Comment Detail', () => { await expect(page.getByText(/DX improvements/i).first()).toBeVisible(); }); + test('spaces out every paragraph, including the bare first one', async ({ page }) => { + await page.goto('/#/item/1001'); + + // HN leaves the first paragraph as a bare text node: "Agreed.

The DX…". + const second = page.locator('.comment-content p', { hasText: /DX improvements/i }).first(); + await expect(second).toBeVisible(); + const gap = await second.evaluate((p) => { + const range = document.createRange(); + range.selectNodeContents(p.parentElement!.firstChild!); + return p.getBoundingClientRect().top - range.getBoundingClientRect().bottom; + }); + + // Without a margin the gap is only line-height leading (~3.5px). + expect(gap).toBeGreaterThan(8); + }); + test('parent link navigates to parent item', async ({ page }) => { await page.goto('/#/item/1001'); diff --git a/e2e/domain-filter.spec.ts b/e2e/domain-filter.spec.ts index d601444..561acfd 100644 --- a/e2e/domain-filter.spec.ts +++ b/e2e/domain-filter.spec.ts @@ -268,6 +268,13 @@ test.describe('Domain Filter - Mobile Swipe', () => { }); }); + test('treats a domain of only dots as no domain', async ({ page }) => { + await page.goto('/#/from/.'); + + await expect(page.getByRole('heading', { name: 'No domain specified' })).toBeVisible(); + await expect(page.getByTestId('swipe-container')).toHaveCount(0); + }); + test('updates URL to /item/:id and carries fromDomain state on swipe', async ({ page }) => { await page.goto('/#/from/example.com'); diff --git a/e2e/fixtures/api-mocks.ts b/e2e/fixtures/api-mocks.ts index 65061d5..e9f9f2b 100644 --- a/e2e/fixtures/api-mocks.ts +++ b/e2e/fixtures/api-mocks.ts @@ -372,7 +372,7 @@ export async function setupApiMocks(page: Page) { { objectID: '2001', author: 'tptacek', - comment_text: 'Agreed. The DX improvements in the latest release are substantial.', + comment_text: 'Agreed.

The DX improvements in the latest release are substantial.', created_at_i: Math.floor(Date.now() / 1000) - 900, parent_id: 1001, story_id: 12345, diff --git a/e2e/fixtures/mock-data.ts b/e2e/fixtures/mock-data.ts index 57cde00..29d0c87 100644 --- a/e2e/fixtures/mock-data.ts +++ b/e2e/fixtures/mock-data.ts @@ -271,7 +271,7 @@ export const mockAlgoliaCommentItem = { { id: 2001, author: 'tptacek', - text: 'Agreed. The DX improvements in the latest release are substantial.', + text: 'Agreed.

The DX improvements in the latest release are substantial.', created_at_i: now() - 900, parent_id: 1001, children: [], diff --git a/e2e/pwa-update.spec.ts b/e2e/pwa-update.spec.ts new file mode 100644 index 0000000..87eb5a8 --- /dev/null +++ b/e2e/pwa-update.spec.ts @@ -0,0 +1,181 @@ +import { test, expect, type Page } from '@playwright/test'; +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import type { AddressInfo } from 'node:net'; + +/** + * PWA updates: a release that changes sw.js installs the new worker into the + * same caches the running one boots from, and an app-only release replaces the + * offline shell only once its bundles are cached. + * + * The browser fetches the new sw.js itself, which context.route() can't + * intercept, so these tests serve dist/ (built by the webServer) from a local + * server that can switch to a "next release" mid-test. + * + * Chromium only, like the PWA spec. The HN APIs aren't mocked: Playwright's + * route interception (setupApiMocks) intermittently keeps the old worker from + * handing over to the new one. External hosts fail to resolve instead, which is + * enough here, since only the app shell has to boot. + */ +test.use({ + serviceWorkers: 'allow', + launchOptions: { args: ['--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'] }, +}); + +interface NextRelease { + bundles: 'ok' | 'fail'; + bumpVersion?: boolean; + // An app-only release: sw.js is unchanged and the page is cacheable for 10 + // minutes, as on GitHub Pages. + appOnly?: boolean; +} + +const DIST = path.resolve('dist'); +const TYPES: Record = { + '.html': 'text/html', + '.js': 'text/javascript', + '.css': 'text/css', + '.svg': 'image/svg+xml', + '.webmanifest': 'application/manifest+json', +}; + +let server: http.Server | undefined; + +// Serves dist/. Once `ship()` is called, it serves the next release: a changed +// sw.js and a page whose bundles are renamed /assets/next-*, which either load +// (the same files) or never arrive. +async function serveDist() { + const sw = fs.readFileSync(path.join(DIST, 'sw.js'), 'utf8'); + const html = fs.readFileSync(path.join(DIST, 'index.html'), 'utf8'); + let next: NextRelease | null = null; + + server = http.createServer((req, res) => { + let pathname = new URL(req.url ?? '/', 'http://localhost').pathname; + const send = (body: string | Buffer, type: string, cacheControl = 'no-cache') => { + res.writeHead(200, { 'Content-Type': type, 'Cache-Control': cacheControl }); + res.end(body); + }; + if (pathname === '/sw.js') { + if (!next || next.appOnly) return send(sw, TYPES['.js']); + const nextSw = next.bumpVersion + ? sw.replace(/const VERSION = '([^']+)'/, "const VERSION = '$1-next'") + : `${sw}\n// next release\n`; + return send(nextSw, TYPES['.js']); + } + if (next && !next.bumpVersion && (pathname === '/' || pathname === '/index.html')) { + return send(html.replaceAll('/assets/', '/assets/next-'), TYPES['.html'], next.appOnly ? 'max-age=600' : undefined); + } + if (pathname.startsWith('/assets/next-')) { + if (next?.bundles !== 'ok') return res.destroy(); + pathname = pathname.replace('/assets/next-', '/assets/'); + } + const file = path.join(DIST, pathname === '/' ? 'index.html' : pathname); + if (!file.startsWith(DIST) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) { + res.writeHead(404); + return res.end(); + } + send(fs.readFileSync(file), TYPES[path.extname(file)] ?? 'application/octet-stream'); + }); + await new Promise((resolve) => server!.listen(0, '127.0.0.1', resolve)); + + return { + url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/`, + ship: (release: NextRelease) => { + next = release; + }, + }; +} + +async function installOnFirstVisit(page: Page, url: string) { + await page.goto(url); + await page.waitForFunction(() => navigator.serviceWorker.controller !== null); + await page.waitForFunction(async () => { + const runtime = (await caches.keys()).find((key) => key.includes('runtime')); + return !!runtime && (await (await caches.open(runtime)).keys()).length > 0; + }); +} + +// Resolves once the next release's worker has taken over this page. +async function updateServiceWorker(page: Page) { + const tookOver = await page.evaluate( + () => + new Promise((resolve) => { + navigator.serviceWorker.addEventListener('controllerchange', () => resolve(true), { once: true }); + setTimeout(() => resolve(false), 15_000); + void navigator.serviceWorker.getRegistration().then((registration) => registration?.update()); + }), + ); + expect(tookOver).toBe(true); +} + +const cachedShell = (page: Page) => + page.evaluate(async () => (await (await caches.match('/index.html', { ignoreVary: true }))?.text()) ?? ''); + +test.describe('PWA updates', () => { + test.skip(({ browserName }) => browserName !== 'chromium', 'SW offline behavior validated in Chromium'); + + test.afterEach(async () => { + await new Promise((resolve) => (server ? server.close(resolve) : resolve(undefined))); + server = undefined; + }); + + test("keeps the working offline shell when an update's bundles fail to download", async ({ page, context }) => { + const site = await serveDist(); + await installOnFirstVisit(page, site.url); + + site.ship({ bundles: 'fail' }); + await updateServiceWorker(page); + + await context.setOffline(true); + await page.reload(); + await expect(page.locator('header').first()).toBeVisible(); + }); + + test("boots offline after visiting a release whose bundles didn't download", async ({ page, context }) => { + const site = await serveDist(); + await installOnFirstVisit(page, site.url); + + // Visiting it online puts the new page in the browser's HTTP cache, but its + // bundles never arrive, so the offline shell stays on the working build. + site.ship({ bundles: 'fail', appOnly: true }); + await page.reload(); + + // A launch, not a reload: a reload would revalidate the page anyway. + await context.setOffline(true); + await page.close(); + const launch = await context.newPage(); + await launch.goto(site.url); + await expect(launch.locator('header').first()).toBeVisible(); + }); + + test("adopts an update's shell once its bundles are cached", async ({ page, context }) => { + const site = await serveDist(); + await installOnFirstVisit(page, site.url); + + site.ship({ bundles: 'ok' }); + await updateServiceWorker(page); + expect(await cachedShell(page)).toContain('/assets/next-'); + + await context.setOffline(true); + await page.reload(); + await expect(page.locator('header').first()).toBeVisible(); + }); + + test('boots offline after a VERSION bump replaces the caches', async ({ page, context }) => { + const site = await serveDist(); + await installOnFirstVisit(page, site.url); + const before = await page.evaluate(() => caches.keys()); + + site.ship({ bundles: 'ok', bumpVersion: true }); + await updateServiceWorker(page); + // `activate` deletes the old version's caches, bundles included. + await expect + .poll(() => page.evaluate(async (old) => (await caches.keys()).filter((key) => old.includes(key)), before)) + .toEqual([]); + + await context.setOffline(true); + await page.reload(); + await expect(page.locator('header').first()).toBeVisible(); + }); +}); diff --git a/e2e/pwa.spec.ts b/e2e/pwa.spec.ts index 1bbe1a9..ede24a6 100644 --- a/e2e/pwa.spec.ts +++ b/e2e/pwa.spec.ts @@ -76,6 +76,92 @@ test.describe('PWA offline app shell', () => { expect(controlled).toBe(true); }); + test('boots from the cached shell when the server answers with a 5xx', async ({ page, context, baseURL }) => { + await setupApiMocks(page); + await page.goto('/'); + await waitForSwControl(page); + await waitForCachedBundle(page); + + // A GitHub Pages / CDN outage. Everything the app needs is cached. + await context.route(`${baseURL}/`, (route) => route.fulfill({ status: 503, body: 'Service Unavailable' })); + await page.reload(); + + await expect(page.locator('header').first()).toBeVisible(); + }); + + test("keeps the cached shell when a new build's bundles fail to download", async ({ page, context, baseURL }) => { + await setupApiMocks(page); + await page.goto('/'); + await waitForSwControl(page); + await waitForCachedBundle(page); + + // A deploy ships a new page whose bundles never arrive (the connection + // drops mid-download). + const html = await (await page.request.get('/')).text(); + const nextBuild = html.replaceAll('/assets/', '/assets/next-'); + await context.route(`${baseURL}/`, (route) => route.fulfill({ contentType: 'text/html', body: nextBuild })); + await context.route('**/assets/next-*', (route) => route.abort()); + await page.reload(); + // Give the SW time to finish with the new page. + await page.waitForTimeout(1000); + await context.unrouteAll(); + + // The next launch is offline: the shell it gets has to be one whose bundles + // are cached, or the screen stays blank. + await context.setOffline(true); + await page.reload(); + + await expect(page.locator('header').first()).toBeVisible(); + }); + + test('boots offline after a deploy that overflows the runtime cache', async ({ page, context, baseURL }) => { + await setupApiMocks(page); + await page.goto('/'); + await waitForSwControl(page); + await waitForCachedBundle(page); + + // Bundles from the deploys since install, all written after this shell's + // own: fill the runtime cache to its cap. + const cap = Number(/MAX_RUNTIME_ENTRIES = (\d+)/.exec(await (await page.request.get('/sw.js')).text())?.[1]); + expect(cap).toBeGreaterThan(0); + const runtimeEntries = () => + page.evaluate(async () => { + const name = (await caches.keys()).find((key) => key.includes('runtime')); + return name ? (await (await caches.open(name)).keys()).length : 0; + }); + await page.evaluate(async (cap) => { + const name = (await caches.keys()).find((key) => key.includes('runtime'))!; + const cache = await caches.open(name); + for (let i = (await cache.keys()).length; i < cap; i++) { + await cache.put(`/assets/old-${i}.js`, new Response('')); + } + }, cap); + + // The next deploy changes only the app code: new index bundles, the same + // vendor and runtime chunks. + const html = await (await page.request.get('/')).text(); + const appBundles = [...new Set(html.match(/\/assets\/index-[^"']+/g))]; + const nextBuild = appBundles.reduce((built, bundle) => built.replaceAll(bundle, bundle.replace('index-', 'index-next-')), html); + await context.route(`${baseURL}/`, (route) => route.fulfill({ contentType: 'text/html', body: nextBuild })); + await context.route('**/assets/index-next-*', async (route) => + route.fulfill({ response: await page.request.get(new URL(route.request().url()).pathname.replace('index-next-', 'index-')) }), + ); + await page.reload(); + await expect(page.locator('header').first()).toBeVisible(); + await expect + .poll(() => page.evaluate(async () => (await (await caches.match('/index.html', { ignoreVary: true }))?.text()) ?? '')) + .toContain('index-next-'); + await expect.poll(runtimeEntries).toBeLessThanOrEqual(cap); + await context.unrouteAll(); + + // Trimming the cache back to its cap must not drop a chunk the new shell + // still loads, or the next offline launch is a blank screen. + await context.setOffline(true); + await page.reload(); + + await expect(page.locator('header').first()).toBeVisible(); + }); + test('shows the offline bar on a cold reload when navigator.onLine wrongly reports online, then clears it on reconnect', async ({ page, context }) => { await setupApiMocks(page); diff --git a/public/sw.js b/public/sw.js index 4e48f64..d1e49b3 100644 --- a/public/sw.js +++ b/public/sw.js @@ -14,8 +14,9 @@ * hash-based CSP stays clean; `worker-src 'self'` (vite.config.js) authorizes it. * * Two caches: an install-time SHELL precache and a bounded RUNTIME cache for - * hashed assets, FIFO-trimmed to MAX_RUNTIME_ENTRIES so stale chunks from prior - * deploys can't accumulate between VERSION bumps. + * hashed assets, FIFO-trimmed to MAX_RUNTIME_ENTRIES (never the offline shell's + * own bundles) so stale chunks from prior deploys can't accumulate between + * VERSION bumps. */ // Cache-schema version, NOT the app/GitHub release. Bump only when the caching @@ -34,37 +35,49 @@ const MAX_RUNTIME_ENTRIES = 64; // How long a navigation waits on the network before falling back to the cached // shell. Bounds "lie-fi" launches (connected but stalled) that would otherwise -// hang on the browser's own ~30–60s timeout. The request is NOT abandoned at the -// cutoff — it keeps running to refresh the shell for the next launch. +// hang on the browser's own ~30–60s timeout. The request is not abandoned at the +// cutoff, so a late response can still refresh the shell for the next launch, +// but that's best-effort: Chromium cancels it once the cached shell is served. const NETWORK_TIMEOUT_MS = 3000; // Static shell precached up-front. The build's hashed JS/CSS can't be listed here -// (names are unknown at author time) — `install` parses them from the cached shell -// HTML instead, so the first visit alone is enough to boot offline. +// (names are unknown at author time) — `install` parses them from the shell HTML +// instead, so the first visit alone is enough to boot offline. const PRECACHE_URLS = ['/', OFFLINE_SHELL, '/manifest.webmanifest', '/icons/icon.svg']; self.addEventListener('install', (event) => { event.waitUntil( (async () => { + // All-or-nothing, like Cache.addAll, but held in memory so the shell HTML + // can wait for its bundles. + const responses = await Promise.all( + PRECACHE_URLS.map(async (url) => { + const response = await fetch(url); + if (!response.ok) throw new TypeError(`precache ${url}: ${response.status}`); + return response; + }), + ); const shell = await caches.open(SHELL_CACHE); - await shell.addAll(PRECACHE_URLS); // Precache this build's hashed bundles by parsing their /assets/* refs out of - // the shell HTML cached above. The SW doesn't control the first navigation, so - // those requests never reach the fetch handler — without this they'd be cached - // only on a later controlled load, defeating first-visit offline boot. - // Best-effort: any failure just defers to runtime caching. + // the shell HTML. The SW doesn't control the first navigation, so those + // requests never reach the fetch handler — without this they'd be cached only + // on a later controlled load, defeating first-visit offline boot. + // An update (a release that changes this file) installs into the same caches, + // so it keeps a working offline shell over one whose bundles failed to + // download. A first install has no shell to keep: it caches this one anyway + // and leaves missing bundles to runtime caching. + let adoptShell = true; try { - const shellResponse = await shell.match(OFFLINE_SHELL); - const html = shellResponse ? await shellResponse.text() : ''; - const assets = [...new Set(Array.from(html.matchAll(/["'](\/assets\/[^"']+)["']/g), (m) => m[1]))]; - if (assets.length) { - const runtime = await caches.open(RUNTIME_CACHE); - await runtime.addAll(assets); - } + await cacheShellAssets(await responses[PRECACHE_URLS.indexOf(OFFLINE_SHELL)].clone().text()); } catch { - /* defer to runtime caching on the next controlled load */ + adoptShell = !(await shell.match(OFFLINE_SHELL, { ignoreVary: true })); } + await Promise.all( + PRECACHE_URLS.map((url, i) => + adoptShell || (url !== '/' && url !== OFFLINE_SHELL) ? shell.put(url, responses[i]) : undefined, + ), + ); await self.skipWaiting(); })(), @@ -81,25 +94,68 @@ self.addEventListener('activate', (event) => { ); }); -// FIFO-trim the runtime cache. Cache.keys() returns entries in insertion order, -// so deleting from the front evicts the oldest (least-recently-written) assets. -async function trimCache(cache, maxEntries) { +const assetsIn = (html) => new Set(Array.from(html.matchAll(/["'](\/assets\/[^"']+)["']/g), (m) => m[1])); + +// The bundles the cached offline shell boots with. +async function offlineShellAssets() { + const shell = await caches.match(OFFLINE_SHELL, { ignoreVary: true }); + return shell ? assetsIn(await shell.text()) : new Set(); +} + +// FIFO-trim the runtime cache, skipping the bundles in `keep`. Cache.keys() +// returns entries in insertion order, so deleting from the front evicts the +// oldest (least-recently-written) assets. A cache hit doesn't rewrite an entry, +// so a chunk that rarely changes (the rolldown runtime) stays the oldest entry +// while every shell still needs it. +async function trimCache(cache, maxEntries, keep) { const keys = await cache.keys(); - for (let i = 0; i < keys.length - maxEntries; i++) { - await cache.delete(keys[i]); + let excess = keys.length - maxEntries; + for (const key of keys) { + if (excess <= 0) break; + if (keep.has(new URL(key.url).pathname)) continue; + await cache.delete(key); + excess -= 1; } } +// Cache every /assets/* bundle a shell references that isn't cached yet. Rejects if +// any can't be fetched (addAll is all-or-nothing), so a shell is never adopted +// unless it can boot offline. Checks this version's runtime cache only: during a +// VERSION bump's install, the old caches still hold the bundles, but `activate` +// is about to delete them. +async function cacheShellAssets(html) { + const assets = assetsIn(html); + const runtime = await caches.open(RUNTIME_CACHE); + const missing = []; + for (const url of assets) { + if (!(await runtime.match(url, { ignoreVary: true }))) missing.push(url); + } + if (!missing.length) return; + await runtime.addAll(missing); + // The current offline shell stays the fallback until this one replaces it. + await trimCache(runtime, MAX_RUNTIME_ENTRIES, new Set([...assets, ...(await offlineShellAssets())])); +} + // Network-first navigation, bounded by NETWORK_TIMEOUT_MS, falling back to the // cached shell. Online users get the freshest index.html (and its newest hashed // bundles); offline / lie-fi users get the cached shell promptly. async function navigate(event) { const { request } = event; - const network = fetch(request); + // Revalidate rather than trust the HTTP cache: GitHub Pages' max-age=600 would + // otherwise hand an offline launch a just-deployed index.html whose bundles + // never downloaded (a blank screen) instead of the cached shell. + const network = fetch(request, { cache: 'no-cache' }); + // A 5xx (a Pages/CDN outage) counts as a network failure, so a working cached + // shell wins over an error page. 4xx passes through: unknown paths get Pages' + // 404.html, which redirects to the hash route. + const usable = network.then((response) => { + if (response.status >= 500) throw new Error(`nav-${response.status}`); + return response; + }); // Refresh the offline shell only from a genuine root navigation. GitHub Pages - // serves unknown paths (e.g. a shared /item/123 deep link) as 404.html with a - // 200, so caching a non-root document here would poison the shell. Only `/` is + // answers unknown paths (e.g. a shared /item/123 deep link) with 404.html, so + // caching a non-root document here would poison the shell. Only `/` is // guaranteed to be the real index.html. const refreshShell = (response) => { if (new URL(request.url).pathname !== '/' || !response.ok) return undefined; @@ -110,25 +166,34 @@ async function navigate(event) { // the shell silently never refreshes (it would then stay pinned to an old build // across app-only deploys until its hashed bundles get evicted). const copy = response.clone(); - return caches.open(SHELL_CACHE).then((cache) => cache.put(OFFLINE_SHELL, copy)); + const html = response.clone(); + // Swap the shell only after every bundle it references is cached: the new HTML + // can land before (or, on the timeout path, without) the page fetching its new + // hashed bundles, and an offline launch of a shell whose bundles aren't cached + // is a blank screen. + return html + .text() + .then(cacheShellAssets) + .then(() => caches.open(SHELL_CACHE)) + .then((cache) => cache.put(OFFLINE_SHELL, copy)); }; try { const response = await Promise.race([ - network, + usable, new Promise((_, reject) => setTimeout(() => reject(new Error('nav-timeout')), NETWORK_TIMEOUT_MS)), ]); event.waitUntil(Promise.resolve(refreshShell(response)).catch(() => {})); return response; } catch { - // Timed out or the network failed. Serve the cached shell if we have one; on a - // brand-new install whose precache hasn't landed yet, fall through to the - // still-running network request. + // Timed out, the network failed, or the server returned a 5xx. Serve the cached + // shell if we have one; on a brand-new install whose precache hasn't landed yet, + // fall through to the still-running network request (a 5xx page included). const cached = (await caches.match(OFFLINE_SHELL, { ignoreVary: true })) || (await caches.match('/', { ignoreVary: true })); if (!cached) return network; - // Keep the slow request alive: a late success still refreshes the shell for the - // next launch. Swallow its rejection (offline) to avoid an unhandled rejection. + // Keep the slow request alive: a late success can still refresh the shell for + // the next launch. Swallow its rejection (offline) to avoid an unhandled rejection. event.waitUntil( network .then((response) => refreshShell(response)) @@ -174,7 +239,12 @@ self.addEventListener('fetch', (event) => { event.waitUntil( caches .open(RUNTIME_CACHE) - .then((cache) => cache.put(request, copy).then(() => trimCache(cache, MAX_RUNTIME_ENTRIES))) + .then((cache) => + cache + .put(request, copy) + .then(offlineShellAssets) + .then((keep) => trimCache(cache, MAX_RUNTIME_ENTRIES, keep)), + ) .catch(() => {}), ); } diff --git a/src/App.tsx b/src/App.tsx index c6048c1..08299e9 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -21,15 +21,16 @@ import { fetchItemOnly } from './api/hn'; import { readSwipePosition } from './utils/swipePosition'; import type { FeedType, LocationState, SwipePosition } from './types'; -// Falls through to the desktop list when the URL has no domain (empty `/from/`) -// so the "No domain specified" fallback in DomainStories handles it consistently -// on both platforms. +// Falls through to the desktop list when the URL has no domain (empty `/from/`, +// or one that canonicalizes to nothing, like `/from/.`) so the "No domain +// specified" fallback in DomainStories handles it consistently on both +// platforms. function MobileDomainStoriesWrapper() { const params = useParams(); const domain = params['*'] ?? ''; const canSwipe = useCanSwipe(); - if (canSwipe && domain) { + if (canSwipe && canonicalizeDomain(domain)) { // key={domain} forces a clean remount on domain change so the hook's lazy // useState init re-reads the module-level cache for the new domain. return ; diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index d8d1954..5313d10 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -748,6 +748,15 @@ describe('hn API utilities', () => { expect(result.createdAt).toBeGreaterThan(1000000000000); }); + it('never reports a negative comment count', async () => { + vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ + id: 28, title: 'google!', by: 'spez', score: 1, time: 1160490910, descendants: -1, dead: true, type: 'story', + }); + const result = await fetchItemOnly(28); + + expect(result.type === 'story' && result.commentCount).toBe(0); + }); + it('handles string ID parameter', async () => { const result = await fetchItemOnly('12345'); diff --git a/src/api/hn.ts b/src/api/hn.ts index 04d72e4..11dfbcd 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -187,7 +187,8 @@ function normalizeFirebaseToStoryItem(fb: FirebaseItem): StoryItem { points: fb.score ?? 0, author: fb.by ?? '', createdAt: (fb.time ?? 0) * 1000, - commentCount: fb.descendants ?? 0, + // A few dead stories (e.g. item 28) report `descendants: -1`. + commentCount: Math.max(0, fb.descendants ?? 0), }; } diff --git a/src/components/Comment.test.tsx b/src/components/Comment.test.tsx index f1b3906..08f21ca 100644 --- a/src/components/Comment.test.tsx +++ b/src/components/Comment.test.tsx @@ -228,6 +228,19 @@ describe('Comment', () => { expect(screen.getByText(/1 reply/i)).toBeInTheDocument(); }); + it('keeps keyboard focus on the replies toggle through expand and collapse', () => { + render(); + const expander = screen.getByRole('button', { name: /1 reply/i }); + expander.focus(); + + fireEvent.click(expander); + const collapse = screen.getByRole('button', { name: /collapse replies/i }); + expect(collapse).toHaveFocus(); + + fireEvent.click(collapse); + expect(screen.getByRole('button', { name: /1 reply/i })).toHaveFocus(); + }); + it('shows direct children count, not total descendants', () => { const deepComment = createComment({ id: 10, diff --git a/src/components/Comment.tsx b/src/components/Comment.tsx index 1c2db70..495b23e 100644 --- a/src/components/Comment.tsx +++ b/src/components/Comment.tsx @@ -1,4 +1,4 @@ -import { memo, useMemo, useState, type CSSProperties } from 'react'; +import { memo, useEffect, useMemo, useRef, useState, type CSSProperties, type MouseEvent } from 'react'; import { Link } from 'react-router'; import { isKnownAuthor } from '../api/hn'; import { sanitizeHtml } from '../utils/sanitize'; @@ -20,14 +20,22 @@ interface CommentProps { // Memoized: the swipe viewer re-renders every mounted panel on each swipe. export const Comment = memo(function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { const [repliesExpanded, setRepliesExpanded] = useState(false); - - const expandReplies = () => { - setRepliesExpanded(true); + const expandButtonRef = useRef(null); + const collapseButtonRef = useRef(null); + const moveFocusRef = useRef(false); + + // Each toggle unmounts the button that was pressed, which would drop focus + // to . If it had focus, hand it to the button that replaces it. + const toggleReplies = (e: MouseEvent, expanded: boolean) => { + moveFocusRef.current = e.currentTarget === document.activeElement; + setRepliesExpanded(expanded); }; - const collapseReplies = () => { - setRepliesExpanded(false); - }; + useEffect(() => { + if (!moveFocusRef.current) return; + moveFocusRef.current = false; + (repliesExpanded ? collapseButtonRef : expandButtonRef).current?.focus({ preventScroll: true }); + }, [repliesExpanded]); const sanitizedText = useMemo( () => comment.text ? sanitizeHtml(comment.text) : '', @@ -102,8 +110,9 @@ export const Comment = memo(function Comment({ comment, storyAuthor = '', stageI

{repliesExpanded && (