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
39 changes: 39 additions & 0 deletions e2e/comment-swipe.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { test, expect } from '@playwright/test';
import { setupApiMocks, FIREBASE_WS_PATTERN, createFirebaseWsHandler } from './fixtures/api-mocks';
import {
dispatchSwipeGesture,
expectActiveSwipePanelText,
waitForSwipeReady,
smoothScrollAndAwaitSettled,
Expand Down Expand Up @@ -273,6 +274,44 @@ test.describe('Mobile Comment Swipe Viewer', () => {
await expect(page.getByText('Comment deleted').first()).toBeVisible({ timeout: 10000 });
});

test('swipes past a deleted sibling with no replies', async ({ page }) => {
await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({
itemOverrides: {
5555: {
id: 5555,
time: Math.floor(Date.now() / 1000) - 600,
parent: 12345,
type: 'comment',
deleted: true,
},
12345: {
id: 12345,
title: 'Rust Is the Future of JavaScript Infrastructure',
url: 'https://leerob.io/blog/rust',
by: 'leerob',
score: 284,
time: Math.floor(Date.now() / 1000) - 3600,
descendants: 5,
kids: [1001, 5555, 1002, 1003, 1004],
type: 'story',
},
},
}));

await page.goto('/#/item/1001');
await waitForSwipeReady(page, 5);
// 1003 is the swipe's second stop once 5555 is known to be skipped.
await expect(page.locator('[data-item-id="1003"] .comment-content').first()).toBeAttached({ timeout: 10000 });

const container = page.getByTestId('swipe-container');
const width = await container.evaluate((el) => el.getBoundingClientRect().width);
await dispatchSwipeGesture(container, { forward: true, width });

await waitForScrollAtIndex(page, 2);
await expect(page).toHaveURL(/\/item\/1002/, { timeout: 5000 });
await expectActiveSwipePanelText(page, 'jgrahamc', { minPanels: 5 });
});

test('shows error state when comment fetch fails', async ({ page }) => {
// Auto-retry exhausts 3 backoff attempts (2+4+8s) before showing error.
test.setTimeout(60000);
Expand Down
86 changes: 46 additions & 40 deletions e2e/fixtures/swipe-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,51 @@ export async function expectActiveSwipePanelText(
await expect(activePanel.getByText(text)).toBeVisible({ timeout });
}

/**
* Dispatch one swipe gesture on the swipe container, forward or back.
* Uses Event + Object.defineProperty to avoid `new Touch()` / `new TouchEvent()`
* which throw "Illegal constructor" in WebKit (Safari) and may be unavailable
* in Firefox desktop even with hasTouch:true.
*/
export async function dispatchSwipeGesture(container: Locator, { forward, width }: { forward: boolean; width: number }) {
await container.evaluate((el, { forward, width }) => {
const rect = el.getBoundingClientRect();
const centerX = rect.left + width / 2;
const centerY = rect.top + rect.height / 2;

// Swipe distance: 40% of panel width (exceeds the 25% commit threshold)
const swipeDistance = width * 0.4;
const endX = forward ? centerX - swipeDistance : centerX + swipeDistance;

const makeTouch = (clientX: number) => ({
identifier: 1,
target: el,
clientX,
clientY: centerY,
pageX: clientX,
pageY: centerY,
screenX: clientX,
screenY: centerY,
radiusX: 1,
radiusY: 1,
rotationAngle: 0,
force: 1,
});

const dispatchTouch = (type: string, touches: object[], changed?: object[]) => {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperty(event, 'touches', { value: touches });
Object.defineProperty(event, 'changedTouches', { value: changed ?? touches });
Object.defineProperty(event, 'targetTouches', { value: touches });
el.dispatchEvent(event);
};

dispatchTouch('touchstart', [makeTouch(centerX)]);
dispatchTouch('touchmove', [makeTouch(endX)]);
dispatchTouch('touchend', [], [makeTouch(endX)]);
}, { forward, width });
}

/**
* Navigate the swipe viewer to a specific panel index by simulating touch
* gesture events that trigger the hook's native gesture system.
Expand Down Expand Up @@ -138,46 +183,7 @@ export async function smoothScrollAndAwaitSettled(container: Locator, targetLeft
// initial scrollToIndex — the handler silently ignores the touch.
let success = false;
for (let attempt = 0; attempt < 3 && !success; attempt++) {
// Dispatch touch gesture for one step.
// Uses Event + Object.defineProperty to avoid `new Touch()` / `new TouchEvent()`
// which throw "Illegal constructor" in WebKit (Safari) and may be unavailable
// in Firefox desktop even with hasTouch:true.
await container.evaluate((el, { forward, width }) => {
const rect = el.getBoundingClientRect();
const centerX = rect.left + width / 2;
const centerY = rect.top + rect.height / 2;

// Swipe distance: 40% of panel width (exceeds the 25% commit threshold)
const swipeDistance = width * 0.4;
const endX = forward ? centerX - swipeDistance : centerX + swipeDistance;

const makeTouch = (clientX: number) => ({
identifier: 1,
target: el,
clientX,
clientY: centerY,
pageX: clientX,
pageY: centerY,
screenX: clientX,
screenY: centerY,
radiusX: 1,
radiusY: 1,
rotationAngle: 0,
force: 1,
});

const dispatchTouch = (type: string, touches: object[], changed?: object[]) => {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperty(event, 'touches', { value: touches });
Object.defineProperty(event, 'changedTouches', { value: changed ?? touches });
Object.defineProperty(event, 'targetTouches', { value: touches });
el.dispatchEvent(event);
};

dispatchTouch('touchstart', [makeTouch(centerX)]);
dispatchTouch('touchmove', [makeTouch(endX)]);
dispatchTouch('touchend', [], [makeTouch(endX)]);
}, { forward: isForward, width: panelWidth });
await dispatchSwipeGesture(container, { forward: isForward, width: panelWidth });

// Wait for the animation to complete (panel gets .active). Long enough
// for WebKit under load: a gesture that lands late after a retry has
Expand Down
16 changes: 16 additions & 0 deletions src/api/hn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,22 @@ export async function fetchFirebaseItem(id: number | string, signal?: AbortSigna
return item;
}

/**
* The comments among `ids` that a thread leaves out: flagged and deleted ones
* with no replies. Never `keepId`, so a link to it still opens, nor one whose
* read fails.
*/
export async function fetchHiddenCommentIds(ids: number[], keepId: number, signal?: AbortSignal): Promise<Set<number>> {
const items = await Promise.all(ids.map(id => hnSdk.readItem(id).catch(() => null)));
if (signal?.aborted) {
throw new DOMException('Aborted', 'AbortError');
}
return new Set(ids.filter((id, i) => {
const item = items[i];
return id !== keepId && !!item && !item.kids?.length && (!!item.dead || !!item.deleted);
}));
}

// Algolia is much faster than Firebase here — 1-2 requests instead of hundreds
// of recursive item fetches. `stopIfCapped` skips the remaining pages of a
// thread bigger than search returns.
Expand Down
86 changes: 86 additions & 0 deletions src/components/SwipeCommentViewer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { http, HttpResponse } from 'msw';
import { server } from '../mocks/server';
import { hnSdk } from '../api/hnSdk';
import { __resetFetchCachesForTests } from '../api/hn';
import { mockAlgoliaCommentItem1003 } from '../mocks/handlers';
import { ALGOLIA_API } from '../config/api';
import type { FirebaseItem } from '../types';

Expand Down Expand Up @@ -331,6 +332,91 @@ describe('SwipeCommentViewer', () => {
expect(paths).toEqual(['/item/1003', '/item/3101']);
});

it('shows the comment it was opened on while its siblings load, and keeps it when they land', async () => {
let releaseParent!: () => void;
const parentRead = new Promise<void>(resolve => { releaseParent = resolve; });
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => {
if (Number(id) === 12345) await parentRead;
return defaultItems[Number(id)] ?? null;
});
let commentFetches = 0;
server.use(
http.get(`${ALGOLIA_API}/items/1003`, () => {
commentFetches++;
return HttpResponse.json(mockAlgoliaCommentItem1003);
}),
);

render(<SwipeCommentViewer initialCommentId="1003" />, {
initialEntries: [{ pathname: '/item/1003', state: { isComment: true } }],
});

expect(await screen.findByText(mockAlgoliaCommentItem1003.text)).toBeInTheDocument();
expect(screen.getAllByTestId('swipe-panel')).toHaveLength(1);
expect(activePanelId()).toBe('1003');

window.scrollTo = vi.fn();
releaseParent();

// Third of [1001, 1002, 1003, 1004].
await waitFor(() => {
expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4);
});
expect(activePanelId()).toBe('1003');
expect(screen.getByText(mockAlgoliaCommentItem1003.text)).toBeInTheDocument();
expect(commentFetches).toBe(1);
expect(window.scrollTo).not.toHaveBeenCalled();
});

it('loads the swipe\'s next stops past a deleted sibling, and not the deleted one', async () => {
const items: Record<number, FirebaseItem> = {
...defaultItems,
3001: { id: 3001, type: 'comment', deleted: true, parent: 12345, time: Math.floor(Date.now() / 1000) - 500 },
12345: { ...defaultItems[12345], kids: [1001, 3001, 1002, 1003, 1004] },
};
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => items[Number(id)] ?? null);

render(<SwipeCommentViewer initialCommentId="1001" />, {
initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }],
});

// 1003 is three panels on, but the second stop.
const panel1003 = () => document.querySelector('[data-item-id="1003"]')!;
await waitFor(() => {
expect(panel1003().textContent).toContain(mockAlgoliaCommentItem1003.text);
});
expect(document.querySelector('[data-item-id="3001"] .animate-pulse')).not.toBeNull();
});

it('stays on the comment it was opened on, without mounting it again, when its siblings load on a retry', async () => {
let parentReads = 0;
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => {
if (Number(id) === 12345 && parentReads++ === 0) throw new Error('Network error');
return defaultItems[Number(id)] ?? null;
});
let commentFetches = 0;
server.use(
http.get(`${ALGOLIA_API}/items/1003`, () => {
commentFetches++;
return HttpResponse.json(mockAlgoliaCommentItem1003);
}),
);

render(<SwipeCommentViewer initialCommentId="1003" />, {
initialEntries: [{ pathname: '/item/1003', state: { isComment: true } }],
});
expect(await screen.findByText(mockAlgoliaCommentItem1003.text)).toBeInTheDocument();
const panel = document.querySelector('[data-item-id="1003"]');

// The retry waits out a 2s backoff.
await waitFor(() => {
expect(screen.getAllByTestId('swipe-panel')).toHaveLength(4);
expect(activePanelId()).toBe('1003');
}, { timeout: 5000 });
expect(document.querySelector('[data-item-id="1003"]')).toBe(panel);
expect(commentFetches).toBe(1);
}, 10000);

it('sets data-item-id on each panel', async () => {
render(<SwipeCommentViewer initialCommentId="1001" />, {
initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }],
Expand Down
Loading
Loading