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
23 changes: 19 additions & 4 deletions e2e/fixtures/swipe-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ export async function waitForSwipeReady(page: Page, minPanels = 2) {
await page.waitForFunction(() => {
const el = document.querySelector('[data-testid="swipe-container"]');
return el && el.getBoundingClientRect().width > 0;
}, { timeout: 5000 });
}, undefined, { timeout: 5000 });

// Wait for the gesture system to signal readiness (listeners attached).
// This eliminates the race between panels rendering and useEffect attaching handlers.
await page.waitForFunction(() => {
const el = document.querySelector('[data-testid="swipe-container"]');
return el && (el as HTMLElement).dataset.swipeEnabled === 'true';
}, { timeout: 5000 });
}, undefined, { timeout: 5000 });

// Some Mobile Safari route transitions attach listeners one frame before the
// viewer finishes applying its `.active` marker. Tests that scope to the
Expand All @@ -45,7 +45,7 @@ export async function waitForSwipeReady(page: Page, minPanels = 2) {

const activePanel = activePanels[0] as HTMLElement;
return activePanel.getBoundingClientRect().width > 0;
}, { timeout: 5000 });
}, undefined, { timeout: 5000 });
}

/** Returns the currently active swipe panel. */
Expand Down Expand Up @@ -81,10 +81,25 @@ export async function expectActiveSwipePanelText(
export async function smoothScrollAndAwaitSettled(container: Locator, targetLeft: number) {
const page = container.page();

// The container width can momentarily read 0 while React is mid-commit
// (notably Firefox re-rendering the offline feed as its load/error state
// churns during a deep swipe). Measuring then makes `target` below Infinity,
// which crashes the `Array.from({ length })` step builder with
// "Invalid array length". Wait for a laid-out container before measuring.
await page.waitForFunction(() => {
const el = document.querySelector('[data-testid="swipe-container"]');
return !!el && el.getBoundingClientRect().width > 0;
}, undefined, { timeout: 5000 });

// Determine target index and current index
const { targetIndex, currentIndex, panelWidth } = await container.evaluate((el, left) => {
const width = el.getBoundingClientRect().width;
const target = Math.round(left / width);
const childCount = el.children.length;
// Defense in depth against a transient 0/elem-detached read slipping past
// the wait above: clamp the derived index to a real child so a mismeasure
// can never yield a non-finite or out-of-range step count.
const rawTarget = width > 0 ? Math.round(left / width) : 0;
const target = Math.max(0, Math.min(Math.max(childCount - 1, 0), rawTarget));
let current = 0;
for (let i = 0; i < el.children.length; i++) {
if (el.children[i].classList.contains('active')) {
Expand Down
50 changes: 35 additions & 15 deletions e2e/viewed-items.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { test, expect } from '@playwright/test';
import { setupApiMocks } from './fixtures/api-mocks';
import { expectActiveSwipePanelText } from './fixtures/swipe-helpers';
import { expectActiveSwipePanelText, getActiveSwipePanel } from './fixtures/swipe-helpers';

test.describe('Viewed Items', () => {
test.use({ viewport: { width: 1280, height: 720 } });
Expand All @@ -14,9 +14,10 @@ test.describe('Viewed Items', () => {
});

test('viewed items persist across page reload', async ({ page }) => {
// 'viewed:times:detail' is the detail time-based store: { itemId: timestamp }.
// 'viewed:times:detail' is the detail time-based store: { itemId: expiresAt }.
// Seed a live (future) expiry so the entry survives the startup prune.
await page.addInitScript(() => {
const viewed = { '12345': Date.now() };
const viewed = { '12345': Date.now() + 12 * 60 * 60 * 1000 };
localStorage.setItem('viewed:times:detail', JSON.stringify(viewed));
});

Expand Down Expand Up @@ -57,7 +58,7 @@ test.describe('Viewed Items', () => {
await expect(unviewedCard).not.toHaveAttribute('data-viewed', 'true');
});

test('old viewed items are cleaned up after 5 days (title)', async ({ browser, baseURL }) => {
test('expired viewed entries are pruned on load; live ones are kept (title)', async ({ browser, baseURL }) => {
// Multiple page loads + storage manipulation push past default timeout.
test.setTimeout(60000);

Expand All @@ -66,12 +67,17 @@ test.describe('Viewed Items', () => {
const page = await context.newPage();
await setupApiMocks(page);

const oldTimestamp = Date.now() - (121 * 60 * 60 * 1000); // 121h ago: past 120h (5-day) window

await page.addInitScript((oldTime) => {
const viewed = { '12345': oldTime };
// 'viewed:times:title' stores { itemId: expiresAt }. The 5-day window is
// applied at write time, so prune just drops anything already expired: seed
// one expired (past) entry and one live (future) entry.
await page.addInitScript(() => {
const hour = 60 * 60 * 1000;
const viewed = {
'12345': Date.now() - hour, // expired -> pruned on load
'12346': Date.now() + hour, // live -> retained
};
localStorage.setItem('viewed:times:title', JSON.stringify(viewed));
}, oldTimestamp);
});

await page.goto('/#/');

Expand All @@ -83,6 +89,13 @@ test.describe('Viewed Items', () => {
const viewedTimes = stored ? JSON.parse(stored) : {};
return viewedTimes['12345'];
}, { timeout: 10000 }).toBeUndefined();

const liveEntry = await page.evaluate(() => {
const stored = localStorage.getItem('viewed:times:title');
const viewedTimes = stored ? JSON.parse(stored) : {};
return viewedTimes['12346'];
});
expect(liveEntry).toBeGreaterThan(0);
});
});

Expand Down Expand Up @@ -127,20 +140,27 @@ test.describe('Viewed Items - Mobile', () => {

test('viewed items are filtered in mobile swipe mode', async ({ page }) => {
// Seed 'viewed:times:detail' WITHOUT touching 'viewed:session' — the swipe
// filter should hide items that are time-viewed but not session-viewed.
// filter should hide items whose hide window is still live but not
// session-viewed. Values are expiresAt, so use a future time (not expired).
// The top feed is [12345, 12346, 12347, ...]; hiding 12345 + 12346 must
// promote 12347 ("Why We Moved from React to htmx") to the active panel.
await page.addInitScript(() => {
const viewed = {
'12345': Date.now() - 1000,
'12346': Date.now() - 1000,
'12345': Date.now() + 12 * 60 * 60 * 1000,
'12346': Date.now() + 12 * 60 * 60 * 1000,
};
localStorage.setItem('viewed:times:detail', JSON.stringify(viewed));
});

await page.goto('/#/');

const container = page.getByTestId('swipe-container');
await expect(container).toBeVisible();
// The first two stories are hidden, so the third is the active panel...
await expectActiveSwipePanelText(page, 'Why We Moved from React to htmx');

await expect(page.getByTestId('swipe-panel').first()).toBeVisible();
// ...and the filtered story must not be the one on screen (a filtering
// regression would leave 12345's title here, which the old "a panel is
// visible" assertion could not catch).
const activePanel = getActiveSwipePanel(page);
await expect(activePanel.getByText('Rust Is the Future of JavaScript Infrastructure')).toHaveCount(0);
});
});
75 changes: 75 additions & 0 deletions src/components/SwipeStoryViewer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { screen } from '@testing-library/react';
import { render } from '../test/test-utils';
import { SwipeStoryViewerCore } from './SwipeStoryViewer';
import { createStoryItem } from '../test/factories';
import {
clearViewed,
clearViewedTimes,
clearSessionViewed,
addToSessionViewed,
VIEWED_DETAIL_TIMES_KEY,
} from '../utils/viewedItems';

// The panel wrapper (with data-item-id) is rendered by SwipeStoryViewerCore
// itself, so stub the heavy detail child to keep these tests focused on the
// mount-snapshot filtering and free of its data-fetching / async state.
vi.mock('./FullScreenItem', () => ({
FullScreenItem: ({ itemId }: { itemId: number }) => <div data-testid="fsi">{itemId}</div>,
FullScreenItemSkeletonPanel: () => <div data-testid="fsi-skeleton" />,
}));

Object.defineProperty(window, 'innerWidth', { value: 375, writable: true });

Expand Down Expand Up @@ -31,4 +47,63 @@ describe('SwipeStoryViewerCore', () => {

expect(title.closest('div')).toHaveClass('swipe-state-center');
});
});

describe('SwipeStoryViewerCore — mount-snapshot filtering', () => {
const baseProps = {
loading: false,
error: null,
hasMore: false,
loadMore: vi.fn().mockResolvedValue(undefined),
backState: { fromUser: 'test' },
};

beforeEach(() => {
clearViewed();
clearViewedTimes();
clearSessionViewed();
});

// Seed the detail-times map directly: markViewedWithTime would also add the
// id to the session set, which is the exact dimension under test here.
function seedRecentlyViewed(ids: number[]) {
const future = Date.now() + 10 * 60 * 60 * 1000; // inside the 12h window
const map = Object.fromEntries(ids.map((id) => [String(id), future]));
localStorage.setItem(VIEWED_DETAIL_TIMES_KEY, JSON.stringify(map));
}

function renderedPanelIds(): string[] {
return screen
.getAllByTestId('swipe-panel')
.map((el) => el.getAttribute('data-item-id') ?? '');
}

it('keeps a recently-viewed story that was also viewed THIS session', () => {
const stories = [
createStoryItem({ id: 1, title: 'A' }),
createStoryItem({ id: 2, title: 'B' }),
createStoryItem({ id: 3, title: 'C' }),
];
seedRecentlyViewed([1, 2]); // both still inside their hide window
addToSessionViewed(1); // ...but #1 was seen this session

render(<SwipeStoryViewerCore {...baseProps} stories={stories} />);

// #1 stays (session-exempt), #2 is filtered out, #3 was never viewed.
expect(renderedPanelIds()).toEqual(['1', '3']);
});

it('falls back to the full list when every story is filtered out', () => {
const stories = [
createStoryItem({ id: 1, title: 'A' }),
createStoryItem({ id: 2, title: 'B' }),
createStoryItem({ id: 3, title: 'C' }),
];
seedRecentlyViewed([1, 2, 3]); // all hidden, none seen this session

render(<SwipeStoryViewerCore {...baseProps} stories={stories} />);

// An empty feed is never shown — the fallback restores the full list.
expect(renderedPanelIds()).toEqual(['1', '2', '3']);
});
});
16 changes: 7 additions & 9 deletions src/components/SwipeStoryViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
import { fetchItemOnly, NotFoundError } from '../api/hn';
import { getFilteredViewedIds, getSessionViewedIds, markViewedWithTime } from '../utils/viewedItems';
import { getFilteredViewedIds, getSessionViewedIds } from '../utils/viewedItems';
import { useViewDwell } from '../hooks/useViewDwell';
import { FEED_TYPE_TITLES } from '../config/feedTypes';
import { FullScreenItem, FullScreenItemSkeletonPanel } from './FullScreenItem';
import { StateView } from './StateView';
Expand Down Expand Up @@ -81,7 +82,8 @@ export function SwipeStoryViewerCore({
const isOurNavigationRef = useRef(false);

// Snapshots at mount for filtering logic:
// - recentlyViewedOnMount: stories that should be filtered (title=5d, detail=12h TTLs)
// - recentlyViewedOnMount: stories still within their hide window and thus
// filtered out (title click = 5d; detail view = dwell-based 12h/24h/48h)
// - sessionViewedOnMount: stories viewed THIS session (from sessionStorage)
// Stories in sessionStorage are NOT filtered (can always go back to them)
// Stories in localStorage but NOT sessionStorage are filtered
Expand Down Expand Up @@ -395,13 +397,9 @@ export function SwipeStoryViewerCore({

usePrefetchItems(currentIndex, mergedStories, 6);

// Mark all stories as viewed (detail) on swipe — each panel IS the story detail on mobile
useEffect(() => {
const currentStory = mergedStories[currentIndex];
if (currentStory) {
markViewedWithTime(currentStory.id, 'detail');
}
}, [currentIndex, mergedStories]);
// Each panel IS the story detail on mobile — track how long the active story
// is looked at and hide it for a window scaled to that dwell time.
useViewDwell(currentStory?.id);

// Load more stories when approaching the end (don't auto-retry on error — user taps Retry)
useEffect(() => {
Expand Down
7 changes: 6 additions & 1 deletion src/hooks/useSwipeScroll.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,12 @@ function dispatchTouch(el: EventTarget, type: string, clientX: number, clientY:
Object.defineProperty(event, 'touches', { value: isEnd ? [] : [touch] });
Object.defineProperty(event, 'changedTouches', { value: [touch] });
Object.defineProperty(event, 'targetTouches', { value: isEnd ? [] : [touch] });
el.dispatchEvent(event);
// Touch handlers can synchronously commit a panel swap (reduced-motion path
// calls setCurrentIndex), so wrap the native dispatch in act() to flush any
// resulting React state update inside the test's act scope.
act(() => {
el.dispatchEvent(event);
});
}

const CENTER_X = 187.5;
Expand Down
Loading