From 86e7f98e745990ede2d6397a087b298c6edccebf Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sat, 6 Jun 2026 20:24:56 +0200 Subject: [PATCH] fix: stop Firefox mobile header blink on swipe and remove reply fade --- e2e/accessibility.spec.ts | 33 -------- e2e/mobile-swipe.spec.ts | 37 ++------- e2e/navigation.spec.ts | 14 +++- e2e/network-status-bar.spec.ts | 5 +- e2e/user-profile.spec.ts | 6 +- src/components/Comment.test.tsx | 51 +------------ src/components/Comment.tsx | 54 ++------------ src/components/Header.tsx | 16 ++-- src/hooks/useSwipeScroll.test.ts | 69 ++++++++++++++++- src/hooks/useSwipeScroll.ts | 124 +++++++++++++++++++++++-------- src/index.css | 52 ++++--------- src/pages/UserProfile.test.tsx | 2 +- src/pages/UserProfile.tsx | 2 +- 13 files changed, 224 insertions(+), 241 deletions(-) diff --git a/e2e/accessibility.spec.ts b/e2e/accessibility.spec.ts index 8d57b4a..f3028b9 100644 --- a/e2e/accessibility.spec.ts +++ b/e2e/accessibility.spec.ts @@ -449,37 +449,4 @@ test.describe('Accessibility - prefers-reduced-motion', () => { expect(['none', 'unmounted']).toContain(overlayDisplay); }); - test('disables .reply-fade animation when reduced motion is preferred', async ({ page }) => { - await page.emulateMedia({ reducedMotion: 'reduce' }); - - // Emulate BEFORE navigation so the @media query resolves at first - // paint and reduced-motion behavior applies the moment replies - // mount on expand. - await page.goto('/#/item/12345'); - - // Wait for the top-level comment to mount, then expand its reply - // tree. Mock data: comment 1001 (patio11) has child 2001 (tptacek). - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); - await page.getByText(/1 reply/i).first().click(); - const replyAuthor = page.getByRole('link', { name: 'tptacek' }).first(); - await expect(replyAuthor).toBeVisible(); - - // Reduced-motion users should never pass through the transient - // `.reply-fade` state. The branch stays mounted, so asserting on - // the branch that owns the visible reply is stable even if the DOM - // is slow. - const replyBranch = replyAuthor.locator('xpath=ancestor::div[contains(@class, "tree-branch")][1]'); - await expect(replyBranch).not.toHaveClass(/reply-fade/); - - // The inner Comment row remains the element that would animate in - // motion-enabled mode, so we still verify it rests at the reduced- - // motion contract: `animation-name:none` and `opacity:1`. - const replyChild = replyBranch.locator(':scope > .comment-row').first(); - const replyStyles = await replyChild.evaluate((el) => { - const style = getComputedStyle(el); - return { animationName: style.animationName, opacity: style.opacity }; - }); - expect(replyStyles.animationName).toBe('none'); - expect(replyStyles.opacity).toBe('1'); - }); }); diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index 0b79f0c..2eb47c5 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -295,7 +295,7 @@ test.describe('Mobile Swipe Viewer', () => { ).toBeLessThan(beforeHeightGrowth.translateY - 5); }); - test('does not replay expanded reply fade after swiping away and back', async ({ page }) => { + test('preserves expanded replies when swiping away and back', async ({ page }) => { await page.goto('/#/'); await waitForSwipeReady(page, 6); @@ -304,30 +304,11 @@ test.describe('Mobile Swipe Viewer', () => { const activePanel = getActiveSwipePanel(page); await activePanel.getByRole('button', { name: /1 reply|\d+ replies/i }).first().click(); - // Wait for reply content to appear (stable selector — .reply-fade is transient and removed after 180ms) - await expect(activePanel.locator('.tree-trunk > .tree-branch .comment-content').first()).toBeVisible({ timeout: 5000 }); - - const getReplyState = () => activePanel.evaluate((panel) => { - const replyBranch = panel.querySelector('.tree-trunk > .tree-branch'); - if (!(replyBranch instanceof HTMLElement)) { - return null; - } - - const inner = replyBranch.firstElementChild; - const style = inner ? getComputedStyle(inner) : null; - return { - hasReplyFade: replyBranch.classList.contains('reply-fade'), - animationName: style?.animationName ?? null, - opacity: style?.opacity ?? null, - }; - }); - - await expect.poll(getReplyState, { timeout: 5000 }).toMatchObject({ - hasReplyFade: false, - animationName: 'none', - opacity: '1', - }); + // Wait for reply content to appear + const replyContent = activePanel.locator('.tree-trunk > .tree-branch .comment-content').first(); + await expect(replyContent).toBeVisible({ timeout: 5000 }); + // Swipe forward to next panel const container = page.getByTestId('swipe-container'); const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width); @@ -335,14 +316,12 @@ test.describe('Mobile Swipe Viewer', () => { await waitForScrollAtIndex(page, 1); await expect(page).toHaveURL(/\/item\//, { timeout: 5000 }); + // Swipe back to original panel await smoothScrollAndAwaitSettled(container, 0); await waitForScrollAtIndex(page, 0); - await expect.poll(getReplyState, { timeout: 5000 }).toMatchObject({ - hasReplyFade: false, - animationName: 'none', - opacity: '1', - }); + // Replies should still be expanded and visible + await expect(replyContent).toBeVisible({ timeout: 5000 }); }); test('preserves scroll position when swiping away and back', async ({ page }) => { diff --git a/e2e/navigation.spec.ts b/e2e/navigation.spec.ts index 781eb55..fb7fc6d 100644 --- a/e2e/navigation.spec.ts +++ b/e2e/navigation.spec.ts @@ -135,11 +135,23 @@ test.describe('Navigation', () => { await page.goto('/#/'); await expectTopStoryVisible(page); + const isMobile = (page.viewportSize()?.width ?? 1280) < 768; + const bestLink = page.getByRole('link', { name: /best/i }); await bestLink.scrollIntoViewIfNeeded(); await bestLink.click({ force: true }); - await expect(page).toHaveURL(/\/#\/(best|item\/)/); + // Wait for the route to actually resolve before going back. A URL check is + // unreliable on mobile (pre-click URL is already /#/item/:id), so assert the + // active (bg-accent) "best" tab instead. + await expect(page.getByRole('link', { name: 'best', exact: true })) + .toHaveClass(/bg-accent/, { timeout: 10_000 }); + + if (isMobile) { + // Wait for the swipe viewer's /#/best → /#/item/:id replaceState, so goBack() + // doesn't race a pending replace that overwrites the restored history entry. + await expect(page).toHaveURL(/\/#\/item\//, { timeout: 10_000 }); + } await page.goBack(); diff --git a/e2e/network-status-bar.spec.ts b/e2e/network-status-bar.spec.ts index 999e318..1eb8c26 100644 --- a/e2e/network-status-bar.spec.ts +++ b/e2e/network-status-bar.spec.ts @@ -70,13 +70,14 @@ test.describe('Network Status Bar - Viewport Switch', () => { return panels.length >= 2; }, { timeout: 5000 }); - // Swipe mode must clip overflow on html/body to prevent horizontal scroll. + // html/body use `clip` not `hidden`: `hidden` would make a scroll + // container that traps the sticky header. `clip` avoids that side effect. const overflowState = await page.evaluate(() => ({ htmlOx: getComputedStyle(document.documentElement).overflowX, bodyOx: getComputedStyle(document.body).overflowX, })); expect(overflowState.htmlOx).toBe('clip'); - expect(overflowState.bodyOx).toBe('hidden'); + expect(overflowState.bodyOx).toBe('clip'); // Active assertion: scrolling to 9999 must be clamped to 0. await page.evaluate(() => window.scrollTo(9999, 0)); diff --git a/e2e/user-profile.spec.ts b/e2e/user-profile.spec.ts index 6630172..41c6589 100644 --- a/e2e/user-profile.spec.ts +++ b/e2e/user-profile.spec.ts @@ -115,7 +115,7 @@ test.describe('User Profile - Mobile', () => { // and for ANY `#/...` route on mobile (the regex // `^#\/(show|ask|best|item\/)?` is not end-anchored and the group is // optional, so `#/user/pg` matches via the empty-group fallback). That - // class sets `overflow: hidden` on the body, which would wedge the + // class sets `overflow: clip` on the body, which would wedge the // vertically scrollable profile if nothing cleared it. UserProfile's // mount effect imperatively calls `disableSwipeMode()` to unwedge it — // this assertion runs AFTER the heading is visible (i.e. after React has @@ -125,8 +125,8 @@ test.describe('User Profile - Mobile', () => { await expect(page.getByRole('heading', { level: 1, name: 'pg' })).toBeVisible(); - // Both class targets must clear — html has `overflow: clip`, body has - // `overflow: hidden`. Either one being stuck blocks vertical scroll. + // Both class targets must clear — html and body both have `overflow: clip`. + // Either one being stuck blocks vertical scroll. await expect(page.locator('html')).not.toHaveClass(/swipe-mode/); await expect(page.locator('body')).not.toHaveClass(/swipe-mode/); }); diff --git a/src/components/Comment.test.tsx b/src/components/Comment.test.tsx index bdaf78c..cfe28b3 100644 --- a/src/components/Comment.test.tsx +++ b/src/components/Comment.test.tsx @@ -1,4 +1,4 @@ -import { act, screen, fireEvent } from '@testing-library/react'; +import { screen, fireEvent } from '@testing-library/react'; import { afterEach, describe, it, expect, vi } from 'vitest'; import { render } from '../test/test-utils'; import { Comment, CommentTree } from './Comment'; @@ -232,55 +232,6 @@ describe('Comment', () => { expect(screen.getByText(/1 reply/i)).toBeInTheDocument(); }); - it('drops reply-fade after the initial expand so it cannot replay on re-show', () => { - vi.useFakeTimers(); - try { - render(); - - fireEvent.click(screen.getByText(/1 reply/i)); - - const childBranch = screen.getByText('childuser').closest('.tree-branch'); - expect(childBranch).toHaveClass('reply-fade'); - - act(() => { - vi.advanceTimersByTime(180); - }); - - expect(screen.getByText('childuser').closest('.tree-branch')).not.toHaveClass('reply-fade'); - } finally { - vi.useRealTimers(); - } - }); - - it('reapplies reply-fade when replies are collapsed and expanded again', () => { - vi.useFakeTimers(); - try { - render(); - - fireEvent.click(screen.getByText(/1 reply/i)); - act(() => { - vi.advanceTimersByTime(180); - }); - - fireEvent.click(screen.getByRole('button', { name: /collapse replies/i })); - fireEvent.click(screen.getByText(/1 reply/i)); - - expect(screen.getByText('childuser').closest('.tree-branch')).toHaveClass('reply-fade'); - } finally { - vi.useRealTimers(); - } - }); - - it('skips reply-fade entirely when reduced motion is preferred', () => { - reducedMotionValue = true; - - render(); - - fireEvent.click(screen.getByText(/1 reply/i)); - - expect(screen.getByText('childuser').closest('.tree-branch')).not.toHaveClass('reply-fade'); - }); - it('gates replies behind expand button at all depths', () => { render(); diff --git a/src/components/Comment.tsx b/src/components/Comment.tsx index ed2234d..e495739 100644 --- a/src/components/Comment.tsx +++ b/src/components/Comment.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; +import { useMemo, useState, type CSSProperties } from 'react'; import { Link } from 'react-router-dom'; import { isKnownAuthor } from '../api/hn'; import { sanitizeHtml } from '../utils/sanitize'; @@ -17,51 +17,14 @@ interface CommentProps { stageIdx?: number; } -const REPLY_FADE_DURATION_MS = 180; - -function prefersReducedMotion() { - return typeof window !== 'undefined' - && typeof window.matchMedia === 'function' - && window.matchMedia('(prefers-reduced-motion: reduce)').matches; -} - export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { const [repliesExpanded, setRepliesExpanded] = useState(false); - const [shouldAnimateReplies, setShouldAnimateReplies] = useState(false); - const replyFadeTimerRef = useRef | null>(null); - - useEffect(() => { - return () => { - if (replyFadeTimerRef.current) { - clearTimeout(replyFadeTimerRef.current); - } - }; - }, []); - - const clearReplyFadeTimer = () => { - if (replyFadeTimerRef.current) { - clearTimeout(replyFadeTimerRef.current); - replyFadeTimerRef.current = null; - } - }; const expandReplies = () => { - clearReplyFadeTimer(); - const reducedMotion = prefersReducedMotion(); - setShouldAnimateReplies(!reducedMotion); setRepliesExpanded(true); - if (reducedMotion) { - return; - } - replyFadeTimerRef.current = setTimeout(() => { - setShouldAnimateReplies(false); - replyFadeTimerRef.current = null; - }, REPLY_FADE_DURATION_MS); }; const collapseReplies = () => { - clearReplyFadeTimer(); - setShouldAnimateReplies(false); setRepliesExpanded(false); }; @@ -81,10 +44,8 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { const isOp = isKnownAuthor(storyAuthor) && comment.author === storyAuthor; - // Top-level comments inside a tree get a cascade slot; nested - // children fade in together via `.reply-fade` on their - // `.tree-branch` wrappers when the user expands a thread (no - // stagger — reply expansion is a deliberate user-initiated reveal). + // Top-level comments get a cascade slot (stagger-fade); nested + // children appear instantly when the user expands a thread. const wrapperClass = stageIdx !== undefined ? 'py-2 comment-row stagger-fade' : 'py-2 comment-row'; const wrapperStyle: CSSProperties | undefined = stageIdx !== undefined @@ -157,16 +118,11 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { )} - {/* Children re-mount on every expand (React's conditional - render); the `.reply-fade` fade animation re-fires each - time. The .tree-branch wrapper itself stays opaque so - its `::before` connector and `--last::after` trunk-end - mask render at full opacity from frame 0 — see the - comment on `.reply-fade > *` in src/index.css. */} + {/* Children re-mount on every expand (React's conditional render). */} {repliesExpanded && comment.children.map((child, i) => (
diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 42fa7b2..847a984 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -220,14 +220,20 @@ export function Header() { }; return ( + // Swipe mode pins the header with `sticky` (not `fixed`) so Firefox Android's + // URL bar can't re-anchor it mid-swipe (the blink fix). The negative margin + // cancels the flow height `sticky` adds, which would otherwise double up with + // the panel's `padding-top: var(--header-height)`.
diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts index 759d546..ecff766 100644 --- a/src/hooks/useSwipeScroll.test.ts +++ b/src/hooks/useSwipeScroll.test.ts @@ -38,9 +38,11 @@ Object.defineProperty(mockVisualViewport, 'height', { configurable: true, }); -window.scrollTo = vi.fn((...args: unknown[]) => { +const updateMockScrollY = (...args: unknown[]) => { if (typeof args[0] === 'number') mockScrollY = args[1] as number; -}); +}; + +window.scrollTo = vi.fn(updateMockScrollY); // Web Animations API stub (jsdom doesn't implement it) Element.prototype.animate = vi.fn(() => { @@ -152,6 +154,10 @@ function hasActive(index: number) { return getPanel(index).classList.contains('active'); } +function activePanelCount() { + return document.querySelectorAll('[data-testid^="panel-"].active').length; +} + // ---- Tests ---- describe('useSwipeScroll', () => { @@ -165,6 +171,7 @@ describe('useSwipeScroll', () => { createdAnimations.length = 0; resizeObserverCallback = null; observedResizeTarget = null; + vi.mocked(window.scrollTo).mockImplementation(updateMockScrollY); vi.mocked(window.scrollTo).mockClear(); vi.mocked(Element.prototype.animate).mockClear(); document.documentElement.className = ''; @@ -443,6 +450,64 @@ describe('useSwipeScroll', () => { expect(window.scrollTo).toHaveBeenCalledWith(0, 200); }); + it('suppresses the scroll indicator during a deep forward panel swap', async () => { + reducedMotionValue = true; + mockInnerHeight = 400; + mockScrollHeight = 5000; + mockScrollY = 4600; + render(createElement(TestHarness), { wrapper: Wrapper }); + + const activeCountsAtScroll: number[] = []; + vi.mocked(window.scrollTo).mockImplementation((...args: unknown[]) => { + activeCountsAtScroll.push(activePanelCount()); + updateMockScrollY(...args); + }); + vi.mocked(window.scrollTo).mockClear(); + swipeGesture(getContainer(), 'left', 150); + + expect(hasActive(0)).toBe(false); + expect(hasActive(1)).toBe(true); + expect(window.scrollTo).toHaveBeenCalledWith(0, 0); + expect(activeCountsAtScroll).toEqual([1, 1]); + expect(Number(document.body.style.getPropertyValue('--swipe-scroll-progress'))).toBeCloseTo(0); + + act(() => { + window.dispatchEvent(new Event('scroll')); + }); + + expect(document.body.classList.contains('is-scrolling')).toBe(false); + + act(() => { + vi.runAllTimers(); + }); + await act(async () => { /* flush */ }); + }); + + it('keeps outgoing panel in flow for non-zero scroll restores', async () => { + reducedMotionValue = true; + render(createElement(TestHarness), { wrapper: Wrapper }); + + mockScrollY = 200; + swipeGesture(getContainer(), 'left', 150); + act(() => { vi.runAllTimers(); }); + await act(async () => { /* flush */ }); + + const activeCountsAtScroll: number[] = []; + vi.mocked(window.scrollTo).mockImplementation((...args: unknown[]) => { + activeCountsAtScroll.push(activePanelCount()); + updateMockScrollY(...args); + }); + vi.mocked(window.scrollTo).mockClear(); + + swipeGesture(getContainer(), 'right', 150); + + expect(window.scrollTo).toHaveBeenCalledWith(0, 200); + expect(activeCountsAtScroll[0]).toBe(2); + + act(() => { vi.runAllTimers(); }); + await act(async () => { /* flush */ }); + }); + it('ignores vertical gestures', () => { render(createElement(TestHarness), { wrapper: Wrapper }); diff --git a/src/hooks/useSwipeScroll.ts b/src/hooks/useSwipeScroll.ts index 4d96d7c..97cde68 100644 --- a/src/hooks/useSwipeScroll.ts +++ b/src/hooks/useSwipeScroll.ts @@ -29,6 +29,7 @@ export function useSwipeScroll({ const currentIndexRef = useRef(currentIndex); const itemCountRef = useRef(itemCount); const isScrollingProgrammaticallyRef = useRef(false); + const isSuppressingScrollIndicatorRef = useRef(false); const isDraggingRef = useRef(false); const updateScrollIndicatorRef = useRef<() => void>(noop); const syncObservedPanelRef = useRef<() => void>(noop); @@ -106,7 +107,14 @@ export function useSwipeScroll({ const showIndicator = () => { updateScrollIndicator(); // Don't show indicator during programmatic scrolls (panel switch) or active gestures - if (isScrollingProgrammaticallyRef.current || isDraggingRef.current) return; + if ( + isScrollingProgrammaticallyRef.current || + isSuppressingScrollIndicatorRef.current || + isDraggingRef.current + ) { + document.body.classList.remove('is-scrolling'); + return; + } document.body.classList.add('is-scrolling'); if (scrollTimer) clearTimeout(scrollTimer); scrollTimer = setTimeout(() => { @@ -129,6 +137,8 @@ export function useSwipeScroll({ if (scrollTimer) clearTimeout(scrollTimer); document.body.classList.remove('is-scrolling'); document.body.style.removeProperty('--swipe-scroll-progress'); + document.body.style.removeProperty('--swipe-viewport-height'); + isSuppressingScrollIndicatorRef.current = false; updateScrollIndicatorRef.current = noop; syncObservedPanelRef.current = noop; if (observedPanel && panelResizeObserver) { @@ -203,6 +213,83 @@ export function useSwipeScroll({ let dragFrameId = 0; let pendingDragDelta = 0; + // Pin --swipe-viewport-height to a px value so panel min-height doesn't shift + // when the URL bar toggles 100dvh. Released ~350ms later (after chrome settles). + const lockViewportHeight = () => { + const height = window.visualViewport?.height ?? window.innerHeight; + document.body.style.setProperty('--swipe-viewport-height', `${height}px`); + }; + const unlockViewportHeight = () => { + document.body.style.removeProperty('--swipe-viewport-height'); + }; + const suppressScrollIndicatorDuringSwap = () => { + isSuppressingScrollIndicatorRef.current = true; + document.body.classList.remove('is-scrolling'); + + // Re-enable only after the swap + scrollTo settle, so it can't flash + // mid-swap. 180ms is empirical (swaps run ~50–250ms). + const releaseTimeout = setTimeout(() => { + pendingTimeouts = pendingTimeouts.filter(id => id !== releaseTimeout); + isSuppressingScrollIndicatorRef.current = false; + updateScrollIndicatorRef.current(); + }, 180); + pendingTimeouts.push(releaseTimeout); + }; + + const clearPanelTransitionState = (panel: HTMLElement) => { + panel.classList.remove('peeking', 'incoming', 'dragging'); + panel.style.transform = ''; + panel.style.opacity = ''; + panel.style.transformOrigin = ''; + }; + + // Shared panel-swap. Non-zero restores keep the outgoing panel in flow through + // scrollTo so Firefox/APZ won't clamp the offset; top restores drop it first to + // avoid a tall dual-flow layout that flickers fixed chrome. + const commitPanelSwap = ( + targetPanel: HTMLElement | undefined, + activePanel: HTMLElement | undefined, + targetIndex: number, + ) => { + suppressScrollIndicatorDuringSwap(); + lockViewportHeight(); + + const savedY = scrollMapRef.current.get(targetIndex) ?? 0; + const restoreAtTop = savedY <= 0; + + if (restoreAtTop && activePanel && activePanel !== targetPanel) { + activePanel.classList.remove('active'); + clearPanelTransitionState(activePanel); + } + + // 1. Target into flow. + if (targetPanel) { + targetPanel.classList.add('active'); + clearPanelTransitionState(targetPanel); + targetPanel.scrollTop = 0; + } + // 2. Scroll while both panels are in flow (non-zero restores) so FF won't clamp. + window.scrollTo(0, savedY); + // 3. Drop the outgoing panel after non-zero restores. + if (!restoreAtTop && activePanel && activePanel !== targetPanel) { + activePanel.classList.remove('active'); + clearPanelTransitionState(activePanel); + } + // Reflow + re-scroll — backward swipes may have changed content height since savedY. + void document.documentElement.scrollHeight; + window.scrollTo(0, savedY); + updateScrollIndicatorRef.current(); + syncObservedPanelRef.current(); + setCurrentIndex(targetIndex); + isDraggingRef.current = false; + // Release viewport height lock after browser chrome animation settles + const unlockTimeout = setTimeout(() => { + pendingTimeouts = pendingTimeouts.filter(id => id !== unlockTimeout); + unlockViewportHeight(); + }, 350); + pendingTimeouts.push(unlockTimeout); + }; + const cleanSlate = () => { // Cancel any in-progress animations runningAnimations.forEach(a => a.cancel()); @@ -214,8 +301,12 @@ export function useSwipeScroll({ // Kill stale safety timeouts from previous gestures pendingTimeouts.forEach(id => clearTimeout(id)); pendingTimeouts = []; + isSuppressingScrollIndicatorRef.current = false; // Increment generation so any lingering callbacks become no-ops gestureId++; + // Release any viewport height lock from a previous gesture + unlockViewportHeight(); + document.body.classList.remove('is-scrolling'); // Remove residual card-stack classes and inline styles from all panels for (const panel of Array.from(container.children) as HTMLElement[]) { panel.classList.remove('peeking', 'dragging', 'incoming'); @@ -455,16 +546,7 @@ export function useSwipeScroll({ if (reducedMotion) { // Instant swap — no animation cleanSlate(); - activatePanelAndRestoreScroll(targetIndex); - isDraggingRef.current = false; - // Schedule React state update AFTER cleanSlate (which clears pendingTimeouts). - // Without this, setCurrentIndex is never called and currentIndex stays stale — - // breaking URL updates and causing the useLayoutEffect to revert the swap. - const deferredCommitTimeout = setTimeout(() => { - pendingTimeouts = pendingTimeouts.filter((timeoutId) => timeoutId !== deferredCommitTimeout); - setCurrentIndex(targetIndex); - }, 0); - pendingTimeouts.push(deferredCommitTimeout); + commitPanelSwap(targetPanel, activePanel, targetIndex); } else { // Velocity-matched duration: animation continues at finger speed. // Slight 1.2× boost gives a "pop" feel on release (iOS-like). @@ -543,24 +625,7 @@ export function useSwipeScroll({ if (gestureId !== myGesture) return; runningAnimations = []; anims.forEach(a => a.cancel()); - // Hide old panel - if (activePanel) { - activePanel.classList.remove('active', 'dragging'); - activePanel.style.transform = ''; - activePanel.style.opacity = ''; - activePanel.style.transformOrigin = ''; - } - // Switch target into document flow first (gives document height), - // then scroll — order matters because scrollTo is clamped by document height - if (targetPanel) { - targetPanel.classList.remove('peeking', 'incoming'); - targetPanel.style.transform = ''; - targetPanel.style.opacity = ''; - targetPanel.scrollTop = 0; - } - activatePanelAndRestoreScroll(targetIndex); - setCurrentIndex(targetIndex); - isDraggingRef.current = false; + commitPanelSwap(targetPanel, activePanel, targetIndex); }); }; @@ -687,6 +752,7 @@ export function useSwipeScroll({ cancelAnimationFrame(dragFrameId); } pendingTimeouts.forEach(id => clearTimeout(id)); + isSuppressingScrollIndicatorRef.current = false; gestureId++; delete container.dataset.swipeEnabled; }; diff --git a/src/index.css b/src/index.css index 05ab451..05b49e3 100644 --- a/src/index.css +++ b/src/index.css @@ -27,6 +27,8 @@ button { --viewed: oklch(0.55 0.01 60); /* dimmed for read stories */ --tok-color: oklch(0.623 0 0); /* gray (#878787) */ --pill-glow: 0 2px 8px oklch(0.673 0.195 44 / 0.3); + /* MUST match the real rendered header height — fixed swipe panels and the + scroll indicator position off this literal and don't self-correct if it drifts. */ --header-height: 53px; --network-bar-height: 0px; @@ -348,13 +350,21 @@ button { Native scrollbar is hidden — replaced by custom indicator below the header. */ html.swipe-mode { overflow-x: clip; + overflow-anchor: none; scrollbar-width: none; } html.swipe-mode::-webkit-scrollbar { display: none; } body.swipe-mode { - overflow-x: hidden; + /* `clip`, not `hidden`: `hidden` forces the cross-axis to `auto`, making + a scroll container that traps `position: sticky` (the header would scroll away + instead of pinning). `clip` suppresses horizontal overflow without that. */ + overflow-x: clip; + /* Stop Firefox re-anchoring scrollY after the panel DOM swap (~20px shift on + mobile). The html.swipe-mode rule disables the document scroller; this body + rule is defensive (overflow-anchor doesn't propagate to the viewport). */ + overflow-anchor: none; --swipe-viewport-height: 100vh; --swipe-scroll-progress: 0; } @@ -377,7 +387,8 @@ body.swipe-mode::after { border-radius: 2px; background: color-mix(in srgb, currentColor 20%, transparent); opacity: 0; - z-index: 9999; + /* Keep the indicator above swipe panels but below the sticky header (z-50). */ + z-index: 40; pointer-events: none; transform: translateY(calc(var(--swipe-scroll-progress, 0) * ((var(--swipe-viewport-height, 100vh) - var(--header-height) - var(--network-bar-height)) * 0.8))); transition: opacity 0.3s ease; @@ -390,8 +401,8 @@ body.swipe-mode::after { } } -/* Show indicator while scrolling */ -body.swipe-mode:has(:active)::after, +/* Show only during real vertical scrolling (.is-scrolling), never on touch-active: + Firefox Android repaints fixed chrome when :has(:active) and APZ scroll overlap. */ body.swipe-mode.is-scrolling::after { opacity: 1; } @@ -570,7 +581,7 @@ body.swipe-mode.is-scrolling::after { /* ── Page stage choreography ──────────────────────────────────────── */ /* Shared keyframe — used by story cards, top-level comments, AND the - story-header leader. (Nested replies use `reply-fade-in` below.) + story-header leader. Lifts 4px while fading; only opacity + transform animate so the work stays on the compositor (no layout thrash even on long threads). */ @@ -579,15 +590,6 @@ body.swipe-mode.is-scrolling::after { to { opacity: 1; transform: translateY(0); } } -/* Opacity-only fade for reply expansion. No translateY — the - .tree-branch wrapper holds the connector + trunk-end mask at - rest, and any vertical lift on the inner Comment would briefly - misalign them with the byline. See `.reply-fade` below. */ -@keyframes reply-fade-in { - from { opacity: 0; } - to { opacity: 1; } -} - /* Grid stack so children + overlay share a cell that auto-sizes to `max(skeleton, children)`. Avoids the absolute-overlay-over-empty- flex pitfall where a cold load with empty children would render @@ -638,27 +640,6 @@ body.swipe-mode.is-scrolling::after { animation-delay: var(--stagger-delay, 0ms); } -/* Children-on-expand — a soft, unified opacity fade. Reply expansion - is a deliberate user action ("show me these N replies"); a per- - child stagger would just add latency to a reveal the user already - asked for. The cascade earns its keep on UNSOLICITED reveals - (initial page load, infinite-scroll appends), not here. 180ms is - enough to feel intentional without making the reader wait. - - Animation targets the inner Comment (`> *`), NOT the .tree-branch - wrapper itself. The wrapper owns two pseudo-elements that must - stay visible from frame 0: `.tree-branch::before` (horizontal - connector into the trunk) and `.tree-branch--last::after` - (var(--background) mask that paints over the trunk line below the - L-curve, making the trunk visually "end" at the last child). If - those fade with the wrapper, the trunk line — which spans - `top:0;bottom:0` of its container — would be unmasked during the - fade and visibly extend past where the L-curve should clip it. */ -.reply-fade > * { - animation: reply-fade-in 180ms cubic-bezier(0.16, 1, 0.3, 1) both; - opacity: 0; -} - /* Infinite-scroll appends — UNSCOPED so the cascade fires whenever a card mounts past the cold-load batch (the `.play-real` scope on `.stagger-fade` no longer matches in `'done'`). Same animation + @@ -694,7 +675,6 @@ body.swipe-mode.is-scrolling::after { the choreography and land straight on the resting content. */ .page-stage .story-stage-leader, .page-stage .stagger-fade, - .reply-fade > *, .append-fade { animation: none !important; opacity: 1 !important; diff --git a/src/pages/UserProfile.test.tsx b/src/pages/UserProfile.test.tsx index 95cc551..bbb9fa6 100644 --- a/src/pages/UserProfile.test.tsx +++ b/src/pages/UserProfile.test.tsx @@ -176,7 +176,7 @@ describe('UserProfile', () => { // for all `#/...` routes on mobile so the swipe viewers don't double-paint // a scrollable page first. UserProfile is vertically scrollable, so it // must imperatively turn that class off on mount or direct loads end up - // with `body { overflow: hidden }` and the page can't scroll. + // with `body { overflow: clip }` and the page can't scroll. it('removes the swipe-mode class from and on mount', async () => { document.documentElement.classList.add('swipe-mode'); document.body.classList.add('swipe-mode'); diff --git a/src/pages/UserProfile.tsx b/src/pages/UserProfile.tsx index 4d1155a..5b84096 100644 --- a/src/pages/UserProfile.tsx +++ b/src/pages/UserProfile.tsx @@ -38,7 +38,7 @@ export function UserProfile() { // index.html optimistically applies `swipe-mode` to / // for any `#/...` route on mobile so swipe viewers don't double- // paint a scrollable page first. This page IS vertically scrollable, - // so we undo that on mount or `overflow: hidden` sticks on direct + // so we undo that on mount or `overflow: clip` sticks on direct // load (`https://.../#/user/pg`). Desktop is a no-op via the // provider's noop fallback. //