diff --git a/e2e/accessibility.spec.ts b/e2e/accessibility.spec.ts index 3c91514..8d57b4a 100644 --- a/e2e/accessibility.spec.ts +++ b/e2e/accessibility.spec.ts @@ -453,7 +453,7 @@ test.describe('Accessibility - prefers-reduced-motion', () => { await page.emulateMedia({ reducedMotion: 'reduce' }); // Emulate BEFORE navigation so the @media query resolves at first - // paint and the override applies the moment .reply-fade children + // paint and reduced-motion behavior applies the moment replies // mount on expand. await page.goto('/#/item/12345'); @@ -461,19 +461,20 @@ test.describe('Accessibility - prefers-reduced-motion', () => { // 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(); - await expect(page.getByText('tptacek').first()).toBeVisible(); - - // Override target is `.reply-fade > *` (the inner Comment), NOT - // the .reply-fade wrapper itself. The wrapper has to stay opaque - // because it carries `.tree-branch::before` + `.tree-branch--last - // ::after` — the trunk connector and trunk-end mask. If the - // selector ever drifts (the rule and the override are paired in - // src/index.css and easy to evolve out of sync), AT users get - // opacity:0 replies and the cascade animation they opted out of, - // on every expand. - const replyChild = page.locator('.reply-fade > *').first(); - await expect(replyChild).toBeAttached(); - + 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 }; diff --git a/e2e/comment-swipe.spec.ts b/e2e/comment-swipe.spec.ts index 585b013..3cecc4f 100644 --- a/e2e/comment-swipe.spec.ts +++ b/e2e/comment-swipe.spec.ts @@ -1,6 +1,34 @@ import { test, expect } from '@playwright/test'; import { setupApiMocks } from './fixtures/api-mocks'; -import { waitForSwipeReady, smoothScrollAndAwaitSettled, waitForScrollAtIndex } from './fixtures/swipe-helpers'; +import { + expectActiveSwipePanelText, + waitForSwipeReady, + smoothScrollAndAwaitSettled, + waitForScrollAtIndex, +} from './fixtures/swipe-helpers'; + +async function getSwipeScrollbarTranslateY(page: Parameters[0]['page']) { + return page.evaluate(() => { + const transform = getComputedStyle(document.body, '::after').transform; + + if (!transform || transform === 'none') { + return 0; + } + + const match = transform.match(/^matrix(3d)?\((.+)\)$/); + if (!match) { + return 0; + } + + const values = match[2] + .split(',') + .map((value) => Number.parseFloat(value.trim())); + + return match[1] === '3d' + ? (values[13] ?? 0) + : (values[5] ?? 0); + }); +} test.describe('Mobile Comment Swipe Viewer', () => { test.use({ @@ -23,7 +51,7 @@ test.describe('Mobile Comment Swipe Viewer', () => { // that fallback path. await page.goto('/#/item/1001'); - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 }); await expect(page).toHaveURL(/\/item\/1001/, { timeout: 5000 }); }); @@ -34,9 +62,9 @@ test.describe('Mobile Comment Swipe Viewer', () => { const swipeContainer = page.getByTestId('swipe-container'); await expect(swipeContainer).toBeVisible(); - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 }); - await expect(page.getByText(/wasm-bindgen/i).first()).toBeVisible(); + await expectActiveSwipePanelText(page, /wasm-bindgen/i); }); test('loads sibling comments as swipeable panels', async ({ page }) => { @@ -61,7 +89,45 @@ test.describe('Mobile Comment Swipe Viewer', () => { await waitForScrollAtIndex(page, 1); await expect(page).toHaveURL(/\/item\/1002/, { timeout: 5000 }); - await expect(page.getByText('jgrahamc').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'jgrahamc', { minPanels: 4, timeout: 10000 }); + }); + + test('custom swipe scrollbar moves when document scrolls in comment viewer', async ({ page }) => { + await page.goto('/#/item/1002'); + + await waitForSwipeReady(page, 4); + await waitForScrollAtIndex(page, 1); + await expect(page).toHaveURL(/\/item\/1002/, { timeout: 5000 }); + + await page.evaluate(() => { + const activePanel = document.querySelector('[data-testid="swipe-panel"].active'); + if (activePanel) { + (activePanel as HTMLElement).style.minHeight = `${window.innerHeight + 1200}px`; + } + }); + + await expect(async () => { + const isScrollable = await page.evaluate(() => { + return document.documentElement.scrollHeight > window.innerHeight; + }); + expect(isScrollable).toBe(true); + }).toPass(); + + const initialTranslateY = await getSwipeScrollbarTranslateY(page); + + await page.evaluate(() => { + window.scrollTo(0, 300); + }); + + await expect.poll( + () => page.evaluate(() => window.scrollY), + { timeout: 5000 }, + ).toBeGreaterThanOrEqual(250); + + await expect.poll( + () => getSwipeScrollbarTranslateY(page), + { timeout: 5000 }, + ).toBeGreaterThan(initialTranslateY + 5); }); test('can swipe through multiple siblings and back', async ({ page }) => { @@ -92,18 +158,18 @@ test.describe('Mobile Comment Swipe Viewer', () => { test('shows parent and story links in comment', async ({ page }) => { await page.goto('/#/item/1001'); - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 }); const parentLink = page.getByRole('link', { name: 'parent' }).first(); await expect(parentLink).toBeVisible(); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); }); test('header shows "comments" indicator on mobile comment view', async ({ page }) => { await page.goto('/#/item/1001'); - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 }); await expect(page.getByText('comments').first()).toBeVisible(); }); @@ -133,7 +199,7 @@ test.describe('Mobile Comment Swipe Viewer', () => { test('in-panel links have correct hrefs and comments indicator clears when leaving comment view', async ({ page }) => { await page.goto('/#/item/1001'); - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 }); await expect(page.getByText('comments').first()).toBeVisible(); const firstPanel = page.locator('[data-item-id="1001"]'); @@ -248,7 +314,7 @@ test.describe('Mobile Comment Swipe Viewer', () => { test('sets document title to "Comment by {author}" for the current comment', async ({ page }) => { await page.goto('/#/item/1001'); - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 }); await expect(page).toHaveTitle(/Comment by patio11/); }); @@ -283,7 +349,7 @@ test.describe('Mobile Comment Swipe Viewer', () => { await smoothScrollAndAwaitSettled(container, panelWidth); await waitForScrollAtIndex(page, 1); await expect(page).toHaveURL(/\/item\/1002/, { timeout: 5000 }); - await expect(page.getByText('jgrahamc').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'jgrahamc', { minPanels: 4, timeout: 10000 }); const panel1002 = page.locator('[data-item-id="1002"]'); await panel1002.getByRole('link', { name: 'parent' }).click(); @@ -297,14 +363,14 @@ test.describe('Mobile Comment Swipe Viewer', () => { // link must carry isComment: true and land in SwipeCommentViewer for 1001. await page.goto('/#/item/2001'); - await expect(page.getByText('tptacek').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'tptacek', { timeout: 10000 }); await page.getByRole('link', { name: 'parent' }).click(); await expect(page).toHaveURL(/\/item\/1001/, { timeout: 10000 }); // 1001's siblings are [1001, 1002, 1003, 1004] → confirms we're in the // comment viewer with the correct sibling set. - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'patio11', { minPanels: 4, timeout: 10000 }); await expect(page).toHaveTitle(/Comment by patio11/); await waitForSwipeReady(page, 4); diff --git a/e2e/domain-filter.spec.ts b/e2e/domain-filter.spec.ts index e2722b9..f9d675d 100644 --- a/e2e/domain-filter.spec.ts +++ b/e2e/domain-filter.spec.ts @@ -1,7 +1,12 @@ import { test, expect } from '@playwright/test'; import { setupApiMocks, stubEmptyDomainSearch } from './fixtures/api-mocks'; import { ALGOLIA_API } from './fixtures/mock-data'; -import { waitForSwipeReady, smoothScrollAndAwaitSettled, waitForScrollAtIndex } from './fixtures/swipe-helpers'; +import { + expectActiveSwipePanelText, + waitForSwipeReady, + smoothScrollAndAwaitSettled, + waitForScrollAtIndex, +} from './fixtures/swipe-helpers'; test.describe('Domain Filter', () => { test.beforeEach(async ({ page }) => { @@ -270,7 +275,10 @@ test.describe('Domain Filter - Mobile Swipe', () => { // mockDomainItem + 4 clones = 5 panels total; we just need ≥2 for snap. await waitForSwipeReady(page, 2); - await expect(page.getByText('Google Announces Gemini 3.0 with Extended Context').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'Google Announces Gemini 3.0 with Extended Context', { + minPanels: 2, + timeout: 10000, + }); }); test('updates URL to /item/:id and carries fromDomain state on swipe', async ({ page }) => { @@ -406,9 +414,10 @@ test.describe('Domain Filter - Mobile Swipe', () => { // Story renders inside the swipe viewer after recovery. `.first()` // because the title may also render in the document title bar. - await expect( - page.getByText('Google Announces Gemini 3.0 with Extended Context').first(), - ).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'Google Announces Gemini 3.0 with Extended Context', { + minPanels: 1, + timeout: 10000, + }); }); }); diff --git a/e2e/fixtures/swipe-helpers.ts b/e2e/fixtures/swipe-helpers.ts index 5907db6..dc4f681 100644 --- a/e2e/fixtures/swipe-helpers.ts +++ b/e2e/fixtures/swipe-helpers.ts @@ -1,6 +1,11 @@ import type { Page, Locator } from '@playwright/test'; import { expect } from '@playwright/test'; +interface ActiveSwipeTextOptions { + minPanels?: number; + timeout?: number; +} + /** * Wait for swipe container to be ready with multiple panels. * Verifies container visibility, minimum panel count, rendered dimensions, @@ -27,6 +32,42 @@ export async function waitForSwipeReady(page: Page, minPanels = 2) { const el = document.querySelector('[data-testid="swipe-container"]'); return el && (el as HTMLElement).dataset.swipeEnabled === 'true'; }, { timeout: 5000 }); + + // Some Mobile Safari route transitions attach listeners one frame before the + // viewer finishes applying its `.active` marker. Tests that scope to the + // active panel should not proceed until exactly one panel owns that state. + await page.waitForFunction(() => { + const containerEl = document.querySelector('[data-testid="swipe-container"]'); + if (!containerEl) return false; + + const activePanels = containerEl.querySelectorAll('[data-testid="swipe-panel"].active'); + if (activePanels.length !== 1) return false; + + const activePanel = activePanels[0] as HTMLElement; + return activePanel.getBoundingClientRect().width > 0; + }, { timeout: 5000 }); +} + +/** Returns the currently active swipe panel. */ +export function getActiveSwipePanel(page: Page) { + return page.locator('[data-testid="swipe-panel"].active'); +} + +/** + * Assert that visible content is inside the active swipe panel, not just + * somewhere in the mounted panel stack. + */ +export async function expectActiveSwipePanelText( + page: Page, + text: string | RegExp, + { minPanels = 1, timeout = 5000 }: ActiveSwipeTextOptions = {}, +) { + await waitForSwipeReady(page, minPanels); + + const activePanel = getActiveSwipePanel(page); + + await expect(activePanel).toBeVisible({ timeout }); + await expect(activePanel.getByText(text)).toBeVisible({ timeout }); } /** diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index a384a29..bd00248 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -1,6 +1,35 @@ import { test, expect } from '@playwright/test'; import { setupApiMocks } from './fixtures/api-mocks'; -import { waitForSwipeReady, smoothScrollAndAwaitSettled, waitForScrollAtIndex } from './fixtures/swipe-helpers'; +import { + expectActiveSwipePanelText, + getActiveSwipePanel, + waitForSwipeReady, + smoothScrollAndAwaitSettled, + waitForScrollAtIndex, +} from './fixtures/swipe-helpers'; + +async function getSwipeScrollbarTranslateY(page: Parameters[0]['page']) { + return page.evaluate(() => { + const transform = getComputedStyle(document.body, '::after').transform; + + if (!transform || transform === 'none') { + return 0; + } + + const match = transform.match(/^matrix(3d)?\((.+)\)$/); + if (!match) { + return 0; + } + + const values = match[2] + .split(',') + .map((value) => Number.parseFloat(value.trim())); + + return match[1] === '3d' + ? (values[13] ?? 0) + : (values[5] ?? 0); + }); +} test.describe('Mobile Swipe Viewer', () => { test.use({ @@ -22,13 +51,13 @@ test.describe('Mobile Swipe Viewer', () => { const swipeContainer = page.getByTestId('swipe-container'); await expect(swipeContainer).toBeVisible(); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); }); test('can swipe to next item', async ({ page }) => { await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); await expect(page).toHaveTitle(/Rust Is the Future.*HackerTok/); @@ -91,6 +120,230 @@ test.describe('Mobile Swipe Viewer', () => { }).toPass(); }); + test('custom swipe scrollbar moves when document scrolls', async ({ page }) => { + await page.goto('/#/'); + + await waitForSwipeReady(page, 6); + await expect(page).toHaveURL(/\/item\/12345/, { timeout: 5000 }); + + // Guarantee a tall active panel so the document can scroll on every browser. + await page.evaluate(() => { + const activePanel = document.querySelector('[data-testid="swipe-panel"].active'); + if (activePanel) { + (activePanel as HTMLElement).style.minHeight = `${window.innerHeight + 1200}px`; + } + }); + + await expect(async () => { + const isScrollable = await page.evaluate(() => { + return document.documentElement.scrollHeight > window.innerHeight; + }); + expect(isScrollable).toBe(true); + }).toPass(); + + const initialTranslateY = await getSwipeScrollbarTranslateY(page); + + await page.evaluate(() => { + window.scrollTo(0, 300); + }); + + await expect.poll( + () => page.evaluate(() => window.scrollY), + { timeout: 5000 }, + ).toBeGreaterThanOrEqual(250); + + await expect.poll( + () => getSwipeScrollbarTranslateY(page), + { timeout: 5000 }, + ).toBeGreaterThan(initialTranslateY + 5); + + const scrolledTranslateY = await getSwipeScrollbarTranslateY(page); + + await page.evaluate(() => { + window.scrollTo(0, 0); + }); + + await expect.poll( + () => page.evaluate(() => window.scrollY), + { timeout: 5000 }, + ).toBe(0); + + await expect.poll( + () => getSwipeScrollbarTranslateY(page), + { timeout: 5000 }, + ).toBeLessThan(scrolledTranslateY - 5); + }); + + test('custom swipe scrollbar updates when active panel height grows without scrolling', async ({ page }) => { + await page.goto('/#/'); + + await waitForSwipeReady(page, 6); + await expect(page).toHaveURL(/\/item\/12345/, { timeout: 5000 }); + + await page.evaluate(() => { + const activePanel = document.querySelector('[data-testid="swipe-panel"].active'); + if (activePanel) { + (activePanel as HTMLElement).style.minHeight = `${window.innerHeight + 1200}px`; + } + }); + + await expect(async () => { + const isScrollable = await page.evaluate(() => { + return document.documentElement.scrollHeight > window.innerHeight; + }); + expect(isScrollable).toBe(true); + }).toPass(); + + await page.evaluate(() => { + window.scrollTo(0, 300); + }); + + await expect.poll( + () => page.evaluate(() => window.scrollY), + { timeout: 5000 }, + ).toBeGreaterThanOrEqual(250); + + await expect.poll( + () => getSwipeScrollbarTranslateY(page), + { timeout: 5000 }, + ).toBeGreaterThan(5); + + const beforeHeightGrowth = { + scrollHeight: await page.evaluate(() => document.documentElement.scrollHeight), + translateY: await getSwipeScrollbarTranslateY(page), + }; + + await page.evaluate(() => { + const activePanel = document.querySelector('[data-testid="swipe-panel"].active'); + if (activePanel) { + (activePanel as HTMLElement).style.minHeight = `${window.innerHeight + 2400}px`; + } + }); + + await expect.poll( + () => page.evaluate(() => document.documentElement.scrollHeight), + { timeout: 5000 }, + ).toBeGreaterThan(beforeHeightGrowth.scrollHeight + 500); + + await expect.poll( + () => getSwipeScrollbarTranslateY(page), + { timeout: 5000 }, + ).toBeLessThan(beforeHeightGrowth.translateY - 5); + }); + + test('custom swipe scrollbar updates after swiping to a new active panel', async ({ page }) => { + await page.goto('/#/'); + + await waitForSwipeReady(page, 6); + await expect(page).toHaveURL(/\/item\/12345/, { timeout: 5000 }); + + const container = page.getByTestId('swipe-container'); + const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width); + + await smoothScrollAndAwaitSettled(container, panelWidth); + await waitForScrollAtIndex(page, 1); + await expect(page).toHaveURL(/\/item\/12346/, { timeout: 5000 }); + + await page.evaluate(() => { + const activePanel = document.querySelector('[data-testid="swipe-panel"].active'); + if (activePanel) { + (activePanel as HTMLElement).style.minHeight = `${window.innerHeight + 1200}px`; + } + }); + + await expect(async () => { + const isScrollable = await page.evaluate(() => { + return document.documentElement.scrollHeight > window.innerHeight; + }); + expect(isScrollable).toBe(true); + }).toPass(); + + await page.evaluate(() => { + window.scrollTo(0, 300); + }); + + await expect.poll( + () => page.evaluate(() => window.scrollY), + { timeout: 5000 }, + ).toBeGreaterThanOrEqual(250); + + await expect.poll( + () => getSwipeScrollbarTranslateY(page), + { timeout: 5000 }, + ).toBeGreaterThan(5); + + const beforeHeightGrowth = { + scrollHeight: await page.evaluate(() => document.documentElement.scrollHeight), + translateY: await getSwipeScrollbarTranslateY(page), + }; + + await page.evaluate(() => { + const activePanel = document.querySelector('[data-testid="swipe-panel"].active'); + if (activePanel) { + (activePanel as HTMLElement).style.minHeight = `${window.innerHeight + 2400}px`; + } + }); + + await expect.poll( + () => page.evaluate(() => document.documentElement.scrollHeight), + { timeout: 5000 }, + ).toBeGreaterThan(beforeHeightGrowth.scrollHeight + 500); + + await expect.poll( + () => getSwipeScrollbarTranslateY(page), + { timeout: 5000 }, + ).toBeLessThan(beforeHeightGrowth.translateY - 5); + }); + + test('does not replay expanded reply fade after swiping away and back', async ({ page }) => { + await page.goto('/#/'); + + await waitForSwipeReady(page, 6); + await expect(page).toHaveURL(/\/item\//, { timeout: 5000 }); + + const activePanel = getActiveSwipePanel(page); + await activePanel.getByRole('button', { name: /1 reply|\d+ replies/i }).first().click(); + + await expect(activePanel.locator('.reply-fade > *').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', + }); + + const container = page.getByTestId('swipe-container'); + const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width); + + await smoothScrollAndAwaitSettled(container, panelWidth); + await waitForScrollAtIndex(page, 1); + await expect(page).toHaveURL(/\/item\//, { timeout: 5000 }); + + await smoothScrollAndAwaitSettled(container, 0); + await waitForScrollAtIndex(page, 0); + + await expect.poll(getReplyState, { timeout: 5000 }).toMatchObject({ + hasReplyFade: false, + animationName: 'none', + opacity: '1', + }); + }); + test('preserves scroll position when swiping away and back', async ({ page }) => { await page.goto('/#/'); @@ -135,7 +388,7 @@ test.describe('Mobile Swipe Viewer', () => { const container = page.getByTestId('swipe-container'); await expect(container).toBeVisible(); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); // Initial / → /item/12345 redirect must settle before scripted swipes. await expect(page).toHaveURL(/\/item\/12345/, { timeout: 5000 }); @@ -160,7 +413,7 @@ test.describe('Mobile Swipe Viewer', () => { // exits the swipe viewer rather than stepping through items. await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); // Wait for / → /item/12345 to settle so React's scroll-init cycle // and the programmatic-scroll flag have cleared before we swipe. await expect(page).toHaveURL(/\/item\/12345/, { timeout: 5000 }); @@ -198,7 +451,7 @@ test.describe('Mobile Direct Item Access', () => { test('can access item directly via URL on mobile', async ({ page }) => { await page.goto('/#/item/12345'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); }); test('displays Ask HN body text in mobile swipe view', async ({ page }) => { @@ -207,7 +460,7 @@ test.describe('Mobile Direct Item Access', () => { await page.goto('/#/item/88888'); // Should display the Ask HN title - await expect(page.getByText('Ask HN: What are you working on?').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Ask HN: What are you working on?'); // Should display the item body text (sanitized HTML rendered in FullScreenItem) await expect(page.getByText(/curious what side projects everyone is working on/i)).toBeVisible(); @@ -220,7 +473,7 @@ test.describe('Mobile Direct Item Access', () => { // Start at a valid item (creates browser history entry) await page.goto('/#/item/12345'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); // Navigate to a non-existent item via client-side hash change await page.evaluate(() => window.location.hash = '#/item/99999999'); @@ -230,7 +483,7 @@ test.describe('Mobile Direct Item Access', () => { // Press browser back — valid item should render await page.goBack(); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); await expect(page.getByText(/not found/i)).not.toBeVisible(); await expect(page).toHaveTitle(/Rust Is the Future of JavaScript Infrastructure.*HackerTok/); @@ -244,7 +497,7 @@ test.describe('Mobile Direct Item Access', () => { // then pressing back should restore the scroll position (not reset to index 0). await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); const container = page.getByTestId('swipe-container'); // Wait for pagination panels (stories.length < 10 auto-load) so @@ -266,7 +519,7 @@ test.describe('Mobile Direct Item Access', () => { await expect(page.getByText(/not found/i)).not.toBeVisible(); await expect(page).toHaveURL(/\/item\/12346/, { timeout: 5000 }); await waitForScrollAtIndex(page, 1); - await expect(page.getByText('SQLite Does Not Do Full FSYNC by Default').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'SQLite Does Not Do Full FSYNC by Default', { minPanels: 6 }); // Verify scroll position is actually at index 1 (not just that element exists in DOM). // Use expect.poll to tolerate brief state transitions after goBack. @@ -286,7 +539,7 @@ test.describe('Mobile Direct Item Access', () => { // non-existent item, then pressing back should restore scroll to index 2. await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); const container = page.getByTestId('swipe-container'); // Wait for pagination panels (stories.length < 10 auto-load) so @@ -310,7 +563,7 @@ test.describe('Mobile Direct Item Access', () => { await expect(page.getByText(/not found/i)).not.toBeVisible(); await expect(page).toHaveURL(/\/item\/12347/, { timeout: 5000 }); await waitForScrollAtIndex(page, 2); - await expect(page.getByText('Why We Moved from React to htmx').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Why We Moved from React to htmx', { minPanels: 6 }); // Verify scroll position is actually at index 2 (not just that element exists in DOM). // Use expect.poll to tolerate brief state transitions after goBack. @@ -328,7 +581,7 @@ test.describe('Mobile Direct Item Access', () => { test('back from best section shows top items, not best items', async ({ page }) => { // Start on home (top items) await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); const container = page.getByTestId('swipe-container'); // Wait for pagination panels (stories.length < 10 auto-load) so @@ -346,15 +599,18 @@ test.describe('Mobile Direct Item Access', () => { await bestLink.click({ force: true }); // Should show best items (distinct from top items) + await expect(page).toHaveURL(/\/item\/33001/, { timeout: 5000 }); await expect(page.getByText('The Art of Finishing Projects').first()).toBeVisible({ timeout: 5000 }); // Press browser back — should return to top items await page.goBack(); - await expect(page.getByText('The Art of Finishing Projects')).not.toBeVisible({ timeout: 5000 }); + await expect(page).toHaveURL(/\/item\/12346/, { timeout: 5000 }); // Should show a top item in the active panel. After back-nav, the swipe viewer // restores to the previous index (1 = SQLite story). await waitForScrollAtIndex(page, 1); - await expect(page.getByText('SQLite Does Not Do Full FSYNC by Default').first()).toBeVisible({ timeout: 5000 }); + const activePanel = getActiveSwipePanel(page); + await expect(activePanel.getByText('SQLite Does Not Do Full FSYNC by Default')).toBeVisible({ timeout: 5000 }); + await expect(activePanel.getByText('The Art of Finishing Projects')).toHaveCount(0); }); test('loads more items when swiping near the end', async ({ page }) => { @@ -363,7 +619,7 @@ test.describe('Mobile Direct Item Access', () => { // the initial batch, it should auto-load pagination items. await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); const container = page.getByTestId('swipe-container'); @@ -426,7 +682,7 @@ test.describe('Mobile Direct Item Access', () => { await page.goto('/#/item/1001'); // Comment author renders inside the swipe viewer — not the "not a story" guard. - await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 }); + await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 }); await expect(page).toHaveURL(/\/item\/1001/); }); diff --git a/e2e/navigation.spec.ts b/e2e/navigation.spec.ts index 4e931e9..a7cf5b2 100644 --- a/e2e/navigation.spec.ts +++ b/e2e/navigation.spec.ts @@ -1,5 +1,25 @@ -import { test, expect } from '@playwright/test'; +import { test, expect, type Page } from '@playwright/test'; import { setupApiMocks } from './fixtures/api-mocks'; +import { getActiveSwipePanel, waitForScrollAtIndex, waitForSwipeReady } from './fixtures/swipe-helpers'; + +const TOP_STORY_TITLE = 'Rust Is the Future of JavaScript Infrastructure'; + +async function expectTopStoryVisible(page: Page) { + const isMobileViewport = (page.viewportSize()?.width ?? 1280) < 768; + + if (isMobileViewport) { + await waitForSwipeReady(page, 1); + await waitForScrollAtIndex(page, 0); + await expect( + getActiveSwipePanel(page).getByRole('link', { name: TOP_STORY_TITLE }), + ).toBeVisible({ timeout: 10_000 }); + return; + } + + await expect( + page.getByRole('link', { name: TOP_STORY_TITLE }).first(), + ).toBeVisible({ timeout: 10_000 }); +} test.describe('Navigation', () => { test.beforeEach(async ({ page }) => { @@ -74,7 +94,7 @@ test.describe('Navigation', () => { // On mobile, wait for the swipe-viewer panel to become active before // asserting visibility (Safari may need an extra frame after route change). - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible({ timeout: 10000 }); + await expectTopStoryVisible(page); }); test('logo click returns to homepage', async ({ page }) => { @@ -91,7 +111,7 @@ test.describe('Navigation', () => { test('browser back button works', async ({ page }) => { await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectTopStoryVisible(page); const bestLink = page.getByRole('link', { name: /best/i }); await bestLink.scrollIntoViewIfNeeded(); @@ -102,6 +122,7 @@ test.describe('Navigation', () => { await page.goBack(); await expect(page).toHaveURL(/\/#\/(item\/\d+)?$/); + await expectTopStoryVisible(page); }); test('direct URL navigation works', async ({ page }) => { @@ -135,7 +156,7 @@ test.describe('Navigation - Viewport Resize Transition', () => { await page.setViewportSize({ width: 1280, height: 720 }); await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectTopStoryVisible(page); await expect(page.getByTestId('swipe-container')).not.toBeVisible(); await page.setViewportSize({ width: 375, height: 667 }); @@ -152,13 +173,13 @@ test.describe('Navigation - Viewport Resize Transition', () => { await page.setViewportSize({ width: 1280, height: 720 }); await expect(page.getByTestId('swipe-container')).not.toBeVisible({ timeout: 5000 }); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectTopStoryVisible(page); }); test('no layout overflow during desktop-to-mobile transition', async ({ page }) => { await page.setViewportSize({ width: 1280, height: 720 }); await page.goto('/#/'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectTopStoryVisible(page); await page.setViewportSize({ width: 375, height: 667 }); await expect(page.getByTestId('swipe-container')).toBeVisible({ timeout: 5000 }); diff --git a/e2e/user-submissions.spec.ts b/e2e/user-submissions.spec.ts index 701a73b..e34aad1 100644 --- a/e2e/user-submissions.spec.ts +++ b/e2e/user-submissions.spec.ts @@ -1,7 +1,12 @@ import { test, expect } from '@playwright/test'; import { setupApiMocks, stubEmptyUserSubmissions } from './fixtures/api-mocks'; import { ALGOLIA_API } from './fixtures/mock-data'; -import { waitForSwipeReady, smoothScrollAndAwaitSettled, waitForScrollAtIndex } from './fixtures/swipe-helpers'; +import { + expectActiveSwipePanelText, + waitForSwipeReady, + smoothScrollAndAwaitSettled, + waitForScrollAtIndex, +} from './fixtures/swipe-helpers'; test.describe('User Submissions - Desktop', () => { // Desktop viewport — `MobileUserSubmissionsWrapper` falls through to the @@ -150,7 +155,7 @@ test.describe('User Submissions - Mobile Swipe', () => { await waitForSwipeReady(page, 2); - await expect(page.getByText('Beating the Averages').first()).toBeVisible({ timeout: 10_000 }); + await expectActiveSwipePanelText(page, 'Beating the Averages', { minPanels: 2, timeout: 10_000 }); }); test('updates URL to /item/:id and carries fromUser state on swipe', async ({ page }) => { diff --git a/e2e/viewed-items.spec.ts b/e2e/viewed-items.spec.ts index cac0b01..d0e7031 100644 --- a/e2e/viewed-items.spec.ts +++ b/e2e/viewed-items.spec.ts @@ -1,5 +1,6 @@ import { test, expect } from '@playwright/test'; import { setupApiMocks } from './fixtures/api-mocks'; +import { expectActiveSwipePanelText } from './fixtures/swipe-helpers'; test.describe('Viewed Items', () => { test.use({ viewport: { width: 1280, height: 720 } }); @@ -104,7 +105,7 @@ test.describe('Viewed Items - Mobile', () => { // (not just text posts) are marked as detail-viewed on swipe. await page.goto('/#/item/12345'); - await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible(); + await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure'); // 'viewed:session' is the session-only store (cleared per browser session). const sessionViewed = await page.evaluate(() => { diff --git a/src/components/Comment.test.tsx b/src/components/Comment.test.tsx index 0ce3f77..bdaf78c 100644 --- a/src/components/Comment.test.tsx +++ b/src/components/Comment.test.tsx @@ -1,10 +1,26 @@ -import { describe, it, expect } from 'vitest'; -import { screen, fireEvent } from '@testing-library/react'; +import { act, 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'; import type { Comment as CommentType } from '../types'; import { createComment } from '../test/factories'; +let reducedMotionValue = false; + +Object.defineProperty(window, 'matchMedia', { + writable: true, + value: vi.fn((query: string) => ({ + matches: query.includes('reduced-motion') ? reducedMotionValue : false, + media: query, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + onchange: null, + dispatchEvent: vi.fn(), + })), +}); + describe('Comment', () => { const mockComment = createComment({ id: 1, @@ -28,6 +44,10 @@ describe('Comment', () => { ], }); + afterEach(() => { + reducedMotionValue = false; + }); + describe('rendering', () => { it('renders comment author', () => { render(); @@ -212,6 +232,55 @@ 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 a50b036..ed2234d 100644 --- a/src/components/Comment.tsx +++ b/src/components/Comment.tsx @@ -1,4 +1,4 @@ -import { useState, useMemo, type CSSProperties } from 'react'; +import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; import { Link } from 'react-router-dom'; import { isKnownAuthor } from '../api/hn'; import { sanitizeHtml } from '../utils/sanitize'; @@ -17,8 +17,53 @@ 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); + }; const sanitizedText = useMemo( () => comment.text ? sanitizeHtml(comment.text) : '', @@ -90,7 +135,7 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) { {repliesExpanded && (