Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 0 additions & 33 deletions e2e/accessibility.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
37 changes: 8 additions & 29 deletions e2e/mobile-swipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -304,45 +304,24 @@ 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);

await smoothScrollAndAwaitSettled(container, panelWidth);
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 }) => {
Expand Down
14 changes: 13 additions & 1 deletion e2e/navigation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
5 changes: 3 additions & 2 deletions e2e/network-status-bar.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <body> 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));
Expand Down
6 changes: 3 additions & 3 deletions e2e/user-profile.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ test.describe('User Profile - Mobile', () => {
// and <body> 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
Expand All @@ -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/);
});
Expand Down
51 changes: 1 addition & 50 deletions src/components/Comment.test.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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(<Comment comment={mockCommentWithChildren} />);

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(<Comment comment={mockCommentWithChildren} />);

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(<Comment comment={mockCommentWithChildren} />);

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(<Comment comment={mockCommentWithChildren} />);

Expand Down
54 changes: 5 additions & 49 deletions src/components/Comment.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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<ReturnType<typeof setTimeout> | 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);
};

Expand All @@ -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
Expand Down Expand Up @@ -157,16 +118,11 @@ export function Comment({ comment, storyAuthor = '', stageIdx }: CommentProps) {
</div>
)}

{/* 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) => (
<div
key={child.id}
className={`tree-branch${i === comment.children.length - 1 ? ' tree-branch--last' : ''}${shouldAnimateReplies ? ' reply-fade' : ''}`}
className={`tree-branch${i === comment.children.length - 1 ? ' tree-branch--last' : ''}`}
>
<Comment comment={child} storyAuthor={storyAuthor} />
</div>
Expand Down
16 changes: 11 additions & 5 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)`.
<header
className={`
${isSwipeMode ? 'bg-card/98' : 'bg-card/95 backdrop-blur-sm'}
${isSwipeMode ? 'bg-card' : 'bg-card/95 backdrop-blur-sm'}
border-b border-border
md:relative md:transform-none
fixed top-0 left-0 right-0 z-50
transition-transform duration-300 ease-out
${!isSwipeMode && mobileHidden ? '-translate-y-full' : 'translate-y-0'}
md:relative md:transform-none md:mb-0
${isSwipeMode
? 'sticky top-0 z-50 mb-[calc(-1*var(--header-height))]'
: 'fixed top-0 left-0 right-0 z-50'}
${isSwipeMode ? '' : 'transition-transform duration-300 ease-out'}
${isSwipeMode ? '' : !mobileHidden ? 'translate-y-0' : '-translate-y-full'}
md:translate-y-0
`}
>
Expand Down
Loading