From 6fc4554438ae584dd6140d28f86f08775c6b7e7a Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:24:10 +0200 Subject: [PATCH 01/16] fix(feed): refresh a cached feed left before its refresh landed A list restored from the cache was saved to the session on the way out even when it was never refreshed. Coming back restored it as current, so it skipped the refresh and its next page repeated the front page. Clear the session state instead, so returning refreshes it like a fresh visit. --- src/hooks/useInfiniteStories.test.ts | 23 ++++++++++++++++++++++- src/hooks/useInfiniteStories.ts | 8 ++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts index ed044cd..e847cad 100644 --- a/src/hooks/useInfiniteStories.test.ts +++ b/src/hooks/useInfiniteStories.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { renderHook, act } from '@testing-library/react'; import { useInfiniteStories } from './useInfiniteStories'; import { setCachedFeed, getCachedFeed, clearFeedCache } from '../utils/feedCache'; -import { clearListSessionState } from '../utils/itemCache'; +import { clearListSessionState, saveListSessionState } from '../utils/itemCache'; import { createStoryItem } from '../test/factories'; import { server } from '../mocks/server'; import { hnSdk } from '../api/hnSdk'; @@ -104,13 +104,34 @@ describe('useInfiniteStories', () => { it('keeps a stale cache stale when saving the session', () => { const hourAgo = Date.now() - 60 * 60 * 1000; setCachedFeed('top', [1, 2, 3].map(id => createStoryItem({ id })), hourAgo); + saveListSessionState('top', { + scrollY: 0, storyIds: [1, 2, 3], position: 1, seenIds: new Set([1, 2, 3]), hasMore: true, phase: 'firebase', + }); const { result } = renderHook(() => useInfiniteStories('top')); + expect(result.current.isFromSession).toBe(true); act(() => result.current.saveSessionState(0)); expect(getCachedFeed('top')).toMatchObject({ timestamp: hourAgo, isStale: true }); }); + it('refreshes, rather than repeats, a cached feed left before its refresh landed', async () => { + // The live front page (1–20) is the one cached. + setCachedFeed('top', Array.from({ length: 20 }, (_, i) => createStoryItem({ id: i + 1 }))); + const first = renderHook(() => useInfiniteStories('top')); + // Opening a story while offline, or before the refresh comes back. + act(() => first.result.current.saveSessionState(0)); + first.unmount(); + + const { result } = renderHook(() => useInfiniteStories('top')); + expect(result.current.isFromCache).toBe(true); + await act(() => result.current.loadMore()); + + const ids = result.current.stories.map(s => s.id); + expect(ids).toHaveLength(20); + expect(new Set(ids).size).toBe(ids.length); + }); + it.each(['best', 'newest'])('stops at the end of the %s list', async (type) => { vi.mocked(hnSdk.readRankedIds).mockResolvedValue(rankedIds.slice(0, 40)); const { result } = renderHook(() => useInfiniteStories(type)); diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts index c902247..ff1ac31 100644 --- a/src/hooks/useInfiniteStories.ts +++ b/src/hooks/useInfiniteStories.ts @@ -260,6 +260,14 @@ export function useInfiniteStories(type: FeedType = 'top') { // Save session state for instant back navigation const saveSessionState = useCallback((scrollY = window.scrollY) => { if (stories.length === 0) return; + + // A cached list that was never refreshed has no cursor or seenIds to go + // with it: restored, it would skip the refresh and its next page would + // repeat the front page. Coming back refreshes it like a fresh visit. + if (hasStaleCacheRef.current) { + clearListSessionState(type); + return; + } saveListSessionState(type, { scrollY, From eaa2db19b2d5298c42051ee571696cdfe3bcad8b Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:24:11 +0200 Subject: [PATCH 02/16] fix(swipe): show a linked out-of-feed story once The injected story was compared to the first story by reference. Once the feed loaded its own copy of the anchored story, the check missed and the linked story was spliced in twice, with duplicate React keys. Compare by id. --- src/components/SwipeStoryViewer.test.tsx | 26 ++++++++++++++++++++++++ src/components/SwipeStoryViewer.tsx | 5 +++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index 395b3f1..e6bfc6f 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -313,6 +313,32 @@ describe('SwipeStoryViewerCore — swipe-position restore', () => { expect(renderedPanelIds()[0]).toBe('3'); }); + it('shows a linked out-of-feed story once after the feed loads its own copy', async () => { + vi.mocked(fetchItemOnly).mockResolvedValueOnce(createStoryItem({ id: 50 })); + const feed = [createStoryItem({ id: 1 }), createStoryItem({ id: 2 })]; + const { rerender } = render( + , + ); + await waitFor(() => expect(renderedPanelIds()).toEqual(['50', '1', '2'])); + // Touches are ignored while the landing jump settles. + await act(() => new Promise(resolve => setTimeout(resolve, 60))); + swipeToNext(); + expect(activePanel()?.getAttribute('data-item-id')).toBe('1'); + + // The swipe moved the URL to story 1, and a later page brought story 50 + // into the feed. + rerender( + , + ); + + expect(renderedPanelIds()).toEqual(['50', '1', '2']); + }); + it('persists a snapshot of the current story when the page hides', () => { const stories = [ createStoryItem({ id: 1, title: 'A' }), diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 430f5ee..3389568 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -172,8 +172,9 @@ export function SwipeStoryViewerCore({ : baseStories; // Also include injectedStory in the list (for swiping back to it) - // but only if it's not already the firstStory - if (injectedStory && firstStory !== injectedStory) { + // but only if it's not already the firstStory. By id: once the feed loads + // its own copy of the anchored story, that copy is firstStory. + if (injectedStory && firstStory?.id !== injectedStory.id) { result = [result[0], injectedStory, ...result.slice(1).filter(s => s.id !== injectedStory.id)]; } From 537279d7bdfc5efabc4cd7eb225a6280ae4aef1b Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:24:11 +0200 Subject: [PATCH 03/16] fix(swipe): keep the page when a touch interrupts a snap-back A new touch during any running animation restored the panel and its saved scroll, but only an interrupted commit needs that. A snap-back leaves the panel in place, and its scroll was never saved, so the page jumped to the top. Track whether the running animation is a commit. --- src/hooks/useSwipeScroll.test.ts | 30 ++++++++++++++++++++++++++++++ src/hooks/useSwipeScroll.ts | 15 +++++++++++---- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts index 5e4e602..c1f5a2a 100644 --- a/src/hooks/useSwipeScroll.test.ts +++ b/src/hooks/useSwipeScroll.test.ts @@ -615,6 +615,36 @@ describe('useSwipeScroll', () => { expect(Element.prototype.animate).toHaveBeenCalled(); }); + it('keeps the page where it is when a touch interrupts the snap-back', () => { + render(createElement(TestHarness), { wrapper: Wrapper }); + const container = getContainer(); + mockScrollY = 2500; + + dispatchTouch(container, 'touchstart', CENTER_X, CENTER_Y); + vi.advanceTimersByTime(1000); + dispatchTouch(container, 'touchmove', CENTER_X - 20, CENTER_Y); + dispatchTouch(container, 'touchend', CENTER_X - 20, CENTER_Y); + expect(createdAnimations.length).toBeGreaterThan(0); + + // The next touch lands while the snap-back is still running. + dispatchTouch(container, 'touchstart', CENTER_X, CENTER_Y); + + expect(window.scrollY).toBe(2500); + expect(hasActive(0)).toBe(true); + }); + + it('lands on the next panel when a touch interrupts the settle animation', () => { + render(createElement(TestHarness), { wrapper: Wrapper }); + const container = getContainer(); + + swipeGesture(container, 'left', 150); + dispatchTouch(container, 'touchstart', CENTER_X, CENTER_Y); + + expect(hasActive(1)).toBe(true); + expect(activePanelCount()).toBe(1); + expect(hookResult.currentIndex).toBe(1); + }); + it('short slow drag snaps back instantly without animating (reduced motion)', () => { reducedMotionValue = true; render(createElement(TestHarness), { wrapper: Wrapper }); diff --git a/src/hooks/useSwipeScroll.ts b/src/hooks/useSwipeScroll.ts index a754ed9..7497251 100644 --- a/src/hooks/useSwipeScroll.ts +++ b/src/hooks/useSwipeScroll.ts @@ -246,6 +246,9 @@ export function useSwipeScroll({ // --- Animation lifecycle --- let runningAnimations: Animation[] = []; + // Whether runningAnimations is a commit: only a commit moves .active and + // the scroll when it finishes, so only an interrupted one needs restoring. + let animatingCommit = false; let pendingTimeouts: ReturnType[] = []; let gestureId = 0; let dragFrameId = 0; @@ -467,11 +470,13 @@ export function useSwipeScroll({ document.body.classList.remove('is-swiping'); // Clean slate: cancel stale animations and residual classes - const hadActiveAnimations = runningAnimations.length > 0; + const interruptedCommit = animatingCommit && runningAnimations.length > 0; cleanSlate(); - // Only restore panel/scroll if an animation was actually interrupted - // (finishCommit was killed before it could swap .active and scrollTo) - if (hadActiveAnimations) { + // Only restore panel/scroll if a commit was actually interrupted + // (finishCommit was killed before it could swap .active and scrollTo). + // A snap-back leaves both where they are, and this panel's scroll was + // never saved: restoring it would jump to the top. + if (interruptedCommit) { activatePanelAndRestoreScroll(currentIndexRef.current); setCurrentIndex(prev => (prev === currentIndexRef.current ? prev : currentIndexRef.current)); } @@ -686,6 +691,7 @@ export function useSwipeScroll({ } runningAnimations = anims; + animatingCommit = true; // Robust cleanup: fires once via onfinish or safety timeout, deferred by one frame const myGesture = gestureId; @@ -778,6 +784,7 @@ export function useSwipeScroll({ } runningAnimations = anims; + animatingCommit = false; if (anims.length > 0) { const myGesture = gestureId; From 26e2a6b211bec7a181d1f872112895f7d49655ca Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:24:11 +0200 Subject: [PATCH 04/16] fix(sw): serve the cached shell on a 5xx and adopt a shell only with its bundles A 5xx from Pages won the navigation race and replaced a working app with an error page; it now counts as a network failure. The offline shell was also replaced as soon as new HTML arrived, before its hashed bundles were cached, so a failed bundle download left a shell that opened to a blank screen offline. Cache the bundles first, then swap the shell. Also correct two comments about Pages and the timeout path. --- e2e/pwa.spec.ts | 38 ++++++++++++++++++++++++++++++++++ public/sw.js | 54 +++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 81 insertions(+), 11 deletions(-) diff --git a/e2e/pwa.spec.ts b/e2e/pwa.spec.ts index 1bbe1a9..8157145 100644 --- a/e2e/pwa.spec.ts +++ b/e2e/pwa.spec.ts @@ -76,6 +76,44 @@ 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('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..8a2cac6 100644 --- a/public/sw.js +++ b/public/sw.js @@ -34,8 +34,9 @@ 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 @@ -90,16 +91,38 @@ async function trimCache(cache, maxEntries) { } } +// 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. +async function cacheShellAssets(html) { + const assets = new Set(Array.from(html.matchAll(/["'](\/assets\/[^"']+)["']/g), (m) => m[1])); + const missing = []; + for (const url of assets) { + if (!(await caches.match(url, { ignoreVary: true }))) missing.push(url); + } + if (!missing.length) return; + const runtime = await caches.open(RUNTIME_CACHE); + await runtime.addAll(missing); + await trimCache(runtime, MAX_RUNTIME_ENTRIES); +} + // 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); + // 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 +133,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)) From 18f0a1c70ef5a8ecd18b3896cfa992281318d94b Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:24:12 +0200 Subject: [PATCH 05/16] fix(comments): space out a comment's first paragraph HN leaves the first paragraph as a bare text node (first

second), so the p + p rule never spaced the first break. Give every p a top margin instead. The e2e mock comment now uses HN's real markup. --- e2e/comment-detail.spec.ts | 16 ++++++++++++++++ e2e/fixtures/api-mocks.ts | 2 +- e2e/fixtures/mock-data.ts | 2 +- src/index.css | 15 ++++++--------- 4 files changed, 24 insertions(+), 11 deletions(-) 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/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/src/index.css b/src/index.css index 63221ad..53dbe81 100644 --- a/src/index.css +++ b/src/index.css @@ -132,10 +132,11 @@ html.dark { color-scheme: dark; } /* Custom styles for comment HTML content. The base typography mirrors the user-approved comments-tier1.html mock — slightly larger comfort font (14.5px / 1.62 line-height) than HN's defaults so dense threads stay - readable. `p { margin: 0 }` + `p + p` adjacency replaces the old - bottom-margin approach so the last paragraph never adds an unbalanced - gap. Links use a subtle accent-tinted pill with a bottom border - for high contrast in both themes. */ + readable. Every `p` gets a top margin only, as on HN: HN's markup leaves + the first paragraph as a bare text node (`first

second

third`), which + a `p + p` rule can't see, and a top-only margin means the last paragraph + never adds an unbalanced gap. Links use a subtle accent-tinted pill with a + bottom border for high contrast in both themes. */ .comment-content { font-size: 14.5px; line-height: 1.62; @@ -144,11 +145,7 @@ html.dark { color-scheme: dark; } } .comment-content p { - margin: 0; -} - -.comment-content p + p { - margin-top: 0.75em; + margin: 0.75em 0 0; } .comment-content a { From a1f6bce61118226b9c92925b38ef26471af28a1f Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:24:12 +0200 Subject: [PATCH 06/16] fix(comments): keep keyboard focus on the replies toggle Expanding or collapsing replies unmounted the pressed button and dropped focus to . When the button had focus, move it to the button that replaces it. --- src/components/Comment.test.tsx | 13 +++++++++++++ src/components/Comment.tsx | 28 +++++++++++++++++++--------- 2 files changed, 32 insertions(+), 9 deletions(-) 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 && (