From 69fe59ad8394cf22e12e9beee0acaf1df10009cf Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Sun, 7 Jun 2026 18:55:16 +0200
Subject: [PATCH] feat: hide viewed stories by dwell time
Track viewed items with an absolute expiresAt model and dwell-based TTL
tiers (12h for <3s, 24h for 3-60s, 48h for >60s; 5 days on title click).
Add a useViewDwell hook that measures visible dwell and extends (never
shortens) the hide window; re-views skip the write when they wouldn't
extend it. Also wrap touch event dispatches in act() to clear
useSwipeScroll test warnings.
Consolidate the parallel title/detail time stores behind a single
createTimeMap factory, and make its load() tolerant of a corrupt/foreign
value at the key: only a plain object with finite-number values is a valid
id->expiresAt map (a non-number would poison the Math.max merge with NaN
and wedge the entry). Strengthen the mobile swipe filter e2e to assert the
hidden story is actually gone rather than merely that a panel renders.
Guard the e2e swipe helper against a transient 0-width container read
that made the offline end-of-feed test crash with "Invalid array length"
on Firefox, and pass waitForSwipeReady's timeout in the options arg so
its intended 5s limit is actually applied.
Backfill the highest-value test gaps: the useViewDwell re-key path (swipe
A->B finalizes A's tier and floors B) and its pagehide finalize;
SwipeStoryViewerCore mount-snapshot filtering (session-exempt keep +
all-filtered fallback); and the load() guard's array-discard and
non-number-value branches.
---
e2e/fixtures/swipe-helpers.ts | 23 ++-
e2e/viewed-items.spec.ts | 50 +++++--
src/components/SwipeStoryViewer.test.tsx | 75 ++++++++++
src/components/SwipeStoryViewer.tsx | 16 +-
src/hooks/useSwipeScroll.test.ts | 7 +-
src/hooks/useViewDwell.test.tsx | 157 +++++++++++++++++++
src/hooks/useViewDwell.ts | 68 +++++++++
src/utils/viewedItems.test.ts | 125 ++++++++++++++++
src/utils/viewedItems.ts | 182 +++++++++++++----------
9 files changed, 592 insertions(+), 111 deletions(-)
create mode 100644 src/hooks/useViewDwell.test.tsx
create mode 100644 src/hooks/useViewDwell.ts
diff --git a/e2e/fixtures/swipe-helpers.ts b/e2e/fixtures/swipe-helpers.ts
index dc4f681..cedaf3f 100644
--- a/e2e/fixtures/swipe-helpers.ts
+++ b/e2e/fixtures/swipe-helpers.ts
@@ -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
@@ -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. */
@@ -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')) {
diff --git a/e2e/viewed-items.spec.ts b/e2e/viewed-items.spec.ts
index d0e7031..74ec920 100644
--- a/e2e/viewed-items.spec.ts
+++ b/e2e/viewed-items.spec.ts
@@ -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 } });
@@ -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));
});
@@ -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);
@@ -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('/#/');
@@ -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);
});
});
@@ -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);
});
});
diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx
index 38247f3..8ba5785 100644
--- a/src/components/SwipeStoryViewer.test.tsx
+++ b/src/components/SwipeStoryViewer.test.tsx
@@ -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 }) =>
{itemId}
,
+ FullScreenItemSkeletonPanel: () => ,
+}));
Object.defineProperty(window, 'innerWidth', { value: 375, writable: true });
@@ -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();
+
+ // #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();
+
+ // An empty feed is never shown — the fallback restores the full list.
+ expect(renderedPanelIds()).toEqual(['1', '2', '3']);
+ });
});
\ No newline at end of file
diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx
index 0299029..99adc32 100644
--- a/src/components/SwipeStoryViewer.tsx
+++ b/src/components/SwipeStoryViewer.tsx
@@ -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';
@@ -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
@@ -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(() => {
diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts
index ecff766..cab03b0 100644
--- a/src/hooks/useSwipeScroll.test.ts
+++ b/src/hooks/useSwipeScroll.test.ts
@@ -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;
diff --git a/src/hooks/useViewDwell.test.tsx b/src/hooks/useViewDwell.test.tsx
new file mode 100644
index 0000000..2f1308d
--- /dev/null
+++ b/src/hooks/useViewDwell.test.tsx
@@ -0,0 +1,157 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import { useViewDwell } from './useViewDwell';
+import {
+ clearViewed,
+ clearViewedTimes,
+ clearSessionViewed,
+ getSessionViewedIds,
+ VIEWED_DETAIL_TIMES_KEY,
+ DETAIL_VIEW_TTL_HOURS,
+ DETAIL_VIEW_TTL_MEDIUM_HOURS,
+ DETAIL_VIEW_TTL_LONG_HOURS,
+ DETAIL_DWELL_MEDIUM_MS,
+ DETAIL_DWELL_LONG_MS,
+} from '../utils/viewedItems';
+
+const HOUR_MS = 3_600_000;
+const FIXED_NOW = 1_700_000_000_000;
+const ID = 12345;
+
+// `document.visibilityState` is read-only; back it with a mutable variable so
+// tests can toggle it and dispatch the matching `visibilitychange` event.
+let visibility: DocumentVisibilityState = 'visible';
+Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => visibility,
+});
+
+// Mutable monotonic clock for performance.now() (drives dwell measurement).
+let perf = 0;
+
+function setVisibility(state: DocumentVisibilityState) {
+ visibility = state;
+ act(() => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+}
+
+function detailExpiry(id: number): number | undefined {
+ const raw = localStorage.getItem(VIEWED_DETAIL_TIMES_KEY);
+ return raw ? (JSON.parse(raw) as Record)[String(id)] : undefined;
+}
+
+describe('useViewDwell', () => {
+ beforeEach(() => {
+ clearViewed();
+ clearViewedTimes();
+ clearSessionViewed();
+ visibility = 'visible';
+ perf = 0;
+ vi.spyOn(performance, 'now').mockImplementation(() => perf);
+ vi.spyOn(Date, 'now').mockReturnValue(FIXED_NOW);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('writes the 12h floor and session entry on land', () => {
+ renderHook(() => useViewDwell(ID));
+
+ expect(detailExpiry(ID)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_HOURS * HOUR_MS);
+ expect(getSessionViewedIds().has(ID)).toBe(true);
+ });
+
+ it('does nothing when there is no active id', () => {
+ renderHook(() => useViewDwell(undefined));
+
+ expect(detailExpiry(ID)).toBeUndefined();
+ expect(localStorage.getItem(VIEWED_DETAIL_TIMES_KEY)).toBeNull();
+ });
+
+ it('keeps the 12h tier for a dwell under 3s', () => {
+ const { unmount } = renderHook(() => useViewDwell(ID));
+
+ perf = DETAIL_DWELL_MEDIUM_MS - 500; // 2.5s visible
+ unmount();
+
+ expect(detailExpiry(ID)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_HOURS * HOUR_MS);
+ });
+
+ it('upgrades to the 24h tier for a 3-60s dwell', () => {
+ const { unmount } = renderHook(() => useViewDwell(ID));
+
+ perf = DETAIL_DWELL_MEDIUM_MS; // exactly 3s visible
+ unmount();
+
+ expect(detailExpiry(ID)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_MEDIUM_HOURS * HOUR_MS);
+ });
+
+ it('upgrades to the 48h tier for a dwell of 60s or more', () => {
+ const { unmount } = renderHook(() => useViewDwell(ID));
+
+ perf = DETAIL_DWELL_LONG_MS; // 60s visible
+ unmount();
+
+ expect(detailExpiry(ID)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_LONG_HOURS * HOUR_MS);
+ });
+
+ it('excludes time while the tab is hidden from the dwell total', () => {
+ const { unmount } = renderHook(() => useViewDwell(ID));
+
+ // 2s visible, then hidden for a long stretch of wall-clock time.
+ perf = 2_000;
+ setVisibility('hidden');
+
+ perf = 2_000 + 5 * 60_000; // 5 minutes pass while hidden
+ setVisibility('visible');
+
+ // Only 1 more second of visible time before leaving.
+ perf += 1_000;
+ setVisibility('hidden');
+ unmount();
+
+ // 2s + 1s = 3s of *visible* dwell -> 24h tier, NOT the 48h that raw
+ // wall-clock (>5min) would have produced.
+ expect(detailExpiry(ID)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_MEDIUM_HOURS * HOUR_MS);
+ });
+
+ it('finalizes on visibilitychange:hidden even without unmount', () => {
+ renderHook(() => useViewDwell(ID));
+
+ perf = DETAIL_DWELL_LONG_MS;
+ setVisibility('hidden');
+
+ expect(detailExpiry(ID)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_LONG_HOURS * HOUR_MS);
+ });
+
+ it('finalizes the previous story and floors the next when the active id changes', () => {
+ // The common production path: the user swipes from one story to the next,
+ // which re-keys the effect (cleanup-finalizes the old id, re-runs for the new).
+ const NEXT = 67890;
+ const { rerender } = renderHook(({ id }) => useViewDwell(id), {
+ initialProps: { id: ID },
+ });
+
+ perf = DETAIL_DWELL_MEDIUM_MS; // 3s of visible dwell on the first story
+ rerender({ id: NEXT });
+
+ // Leaving the first story upgrades it to the 24h tier...
+ expect(detailExpiry(ID)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_MEDIUM_HOURS * HOUR_MS);
+ // ...and landing on the next writes its 12h floor + session entry immediately.
+ expect(detailExpiry(NEXT)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_HOURS * HOUR_MS);
+ expect(getSessionViewedIds().has(NEXT)).toBe(true);
+ });
+
+ it('finalizes on pagehide even without unmount', () => {
+ renderHook(() => useViewDwell(ID));
+
+ perf = DETAIL_DWELL_LONG_MS; // 60s visible
+ act(() => {
+ window.dispatchEvent(new Event('pagehide'));
+ });
+
+ expect(detailExpiry(ID)).toBe(FIXED_NOW + DETAIL_VIEW_TTL_LONG_HOURS * HOUR_MS);
+ });
+});
diff --git a/src/hooks/useViewDwell.ts b/src/hooks/useViewDwell.ts
new file mode 100644
index 0000000..94c32cc
--- /dev/null
+++ b/src/hooks/useViewDwell.ts
@@ -0,0 +1,68 @@
+import { useEffect } from 'react';
+import {
+ DETAIL_VIEW_TTL_HOURS,
+ detailTtlHoursForDwell,
+ markViewedWithTime,
+} from '../utils/viewedItems';
+
+/**
+ * Track how long the active swipe-story panel is actually looked at and persist
+ * a dwell-based hide window for it.
+ *
+ * - On land: writes the 12h floor immediately (preserves the "hide on view"
+ * guarantee and the `< 3s` tier) and adds the item to the session-viewed set.
+ * - While active: accumulates only *visible* time (paused on `visibilitychange`
+ * -> hidden) using a monotonic `performance.now()` clock, so backgrounded /
+ * screen-locked time is not counted as dwell.
+ * - On leave (swipe to a new id / unmount), tab hidden, or `pagehide`: upgrades
+ * the stored expiry to the tier for the total visible dwell. `markViewedWithTime`
+ * merges with `Math.max`, so repeated finalizes are idempotent and never shorten.
+ *
+ * `visibilitychange -> hidden` fires before `pagehide`/freeze (Page Lifecycle
+ * spec) and nulls the open segment, so a frozen/bfcached interval is not counted;
+ * the `pagehide` finalize is a belt-and-suspenders write.
+ */
+export function useViewDwell(activeId: number | undefined): void {
+ useEffect(() => {
+ if (activeId == null) return;
+
+ // 12h floor + session, the moment the panel becomes active.
+ markViewedWithTime(activeId, 'detail', DETAIL_VIEW_TTL_HOURS);
+
+ let accumulated = 0;
+ let segmentStart: number | null =
+ document.visibilityState === 'visible' ? performance.now() : null;
+
+ const dwellMs = () =>
+ accumulated + (segmentStart != null ? performance.now() - segmentStart : 0);
+
+ const finalize = () => {
+ const ttlHours = detailTtlHoursForDwell(dwellMs());
+ // Floor already written on land; only persist when dwell upgrades the tier.
+ if (ttlHours > DETAIL_VIEW_TTL_HOURS) {
+ markViewedWithTime(activeId, 'detail', ttlHours);
+ }
+ };
+
+ const handleVisibility = () => {
+ if (document.visibilityState === 'hidden') {
+ if (segmentStart != null) {
+ accumulated += performance.now() - segmentStart;
+ segmentStart = null;
+ }
+ finalize();
+ } else {
+ segmentStart = performance.now();
+ }
+ };
+
+ document.addEventListener('visibilitychange', handleVisibility);
+ window.addEventListener('pagehide', finalize);
+
+ return () => {
+ finalize();
+ document.removeEventListener('visibilitychange', handleVisibility);
+ window.removeEventListener('pagehide', finalize);
+ };
+ }, [activeId]);
+}
diff --git a/src/utils/viewedItems.test.ts b/src/utils/viewedItems.test.ts
index da98a46..91c8cec 100644
--- a/src/utils/viewedItems.test.ts
+++ b/src/utils/viewedItems.test.ts
@@ -15,6 +15,11 @@ import {
VIEWED_DETAIL_TIMES_KEY,
TITLE_CLICK_TTL_HOURS,
DETAIL_VIEW_TTL_HOURS,
+ DETAIL_VIEW_TTL_MEDIUM_HOURS,
+ DETAIL_VIEW_TTL_LONG_HOURS,
+ DETAIL_DWELL_MEDIUM_MS,
+ DETAIL_DWELL_LONG_MS,
+ detailTtlHoursForDwell,
} from './viewedItems';
describe('viewedItems', () => {
@@ -118,6 +123,23 @@ describe('viewedItems - Time-based functions', () => {
vi.restoreAllMocks();
});
+ describe('detailTtlHoursForDwell', () => {
+ it('returns the short (12h) tier for dwell under 3s', () => {
+ expect(detailTtlHoursForDwell(0)).toBe(DETAIL_VIEW_TTL_HOURS);
+ expect(detailTtlHoursForDwell(DETAIL_DWELL_MEDIUM_MS - 1)).toBe(DETAIL_VIEW_TTL_HOURS);
+ });
+
+ it('returns the medium (24h) tier for dwell from 3s up to 60s', () => {
+ expect(detailTtlHoursForDwell(DETAIL_DWELL_MEDIUM_MS)).toBe(DETAIL_VIEW_TTL_MEDIUM_HOURS);
+ expect(detailTtlHoursForDwell(DETAIL_DWELL_LONG_MS - 1)).toBe(DETAIL_VIEW_TTL_MEDIUM_HOURS);
+ });
+
+ it('returns the long (48h) tier for dwell of 60s or more', () => {
+ expect(detailTtlHoursForDwell(DETAIL_DWELL_LONG_MS)).toBe(DETAIL_VIEW_TTL_LONG_HOURS);
+ expect(detailTtlHoursForDwell(DETAIL_DWELL_LONG_MS * 2)).toBe(DETAIL_VIEW_TTL_LONG_HOURS);
+ });
+ });
+
describe('getFilteredViewedIds', () => {
it('returns empty Set initially', () => {
const ids = getFilteredViewedIds();
@@ -178,6 +200,51 @@ describe('viewedItems - Time-based functions', () => {
expect(ids.has(22222)).toBe(true);
expect(ids.size).toBe(2);
});
+
+ it('treats a stored non-object value (e.g. literal "null") as empty, not a crash', () => {
+ // A corrupt/legacy localStorage value must not crash the Object.entries() walk.
+ localStorage.setItem(VIEWED_DETAIL_TIMES_KEY, 'null');
+
+ expect(() => getFilteredViewedIds()).not.toThrow();
+ expect(getFilteredViewedIds().size).toBe(0);
+ });
+
+ it('discards a stored non-object value instead of crashing markViewedWithTime', () => {
+ // A bare number would otherwise survive into `times[id] = ...`, which throws
+ // in strict mode ("Cannot create property ... on number"). The read path
+ // (getFilteredViewedIds) tolerates it, so this guards the write path.
+ localStorage.setItem(VIEWED_DETAIL_TIMES_KEY, '123');
+
+ expect(() => markViewedWithTime(999, 'detail')).not.toThrow();
+ expect(getFilteredViewedIds().has(999)).toBe(true);
+ });
+
+ it('discards a stored array so its indices never leak in as viewed ids', () => {
+ // An array passes `typeof === 'object'`, so without the Array.isArray guard
+ // Object.entries() would surface its indices ("0", "1") as bogus viewed ids
+ // with whatever expiry sat at those slots.
+ const future = Date.now() + 10 * 60 * 60 * 1000;
+ localStorage.setItem(VIEWED_DETAIL_TIMES_KEY, JSON.stringify([future, future]));
+
+ const ids = getFilteredViewedIds();
+ expect(ids.has(0)).toBe(false);
+ expect(ids.has(1)).toBe(false);
+ expect(ids.size).toBe(0);
+ });
+
+ it('drops a non-number expiry value so the id stays markable (no NaN wedge)', () => {
+ // A corrupt/foreign string value must not survive into the Math.max merge:
+ // it would coerce to NaN, and since NaN !== NaN the skip guard could never
+ // fire — the id would never hide and would be re-written on every view.
+ localStorage.setItem(VIEWED_DETAIL_TIMES_KEY, JSON.stringify({ '123': 'foo' }));
+
+ // Read path excludes the bad entry (not a crash).
+ expect(getFilteredViewedIds().has(123)).toBe(false);
+
+ // A single mark restores a real expiry and hides the id.
+ markViewedWithTime(123, 'detail');
+ expect(getFilteredViewedIds().has(123)).toBe(true);
+ });
});
describe('markViewedWithTime', () => {
@@ -242,6 +309,64 @@ describe('viewedItems - Time-based functions', () => {
expect(getFilteredViewedIds().has(12345)).toBe(true);
});
+
+ it('does not shorten an existing hide window (Math.max merge)', () => {
+ // A long detail view (48h) ...
+ markViewedWithTime(12345, 'detail', DETAIL_VIEW_TTL_LONG_HOURS);
+ const longExpiry = (JSON.parse(localStorage.getItem(VIEWED_DETAIL_TIMES_KEY)!) as Record)['12345'];
+
+ // ... then a later short view (12h) must NOT reduce the stored expiry.
+ markViewedWithTime(12345, 'detail', DETAIL_VIEW_TTL_HOURS);
+ const afterExpiry = (JSON.parse(localStorage.getItem(VIEWED_DETAIL_TIMES_KEY)!) as Record)['12345'];
+
+ expect(afterExpiry).toBe(longExpiry);
+ expect(getFilteredViewedIds().has(12345)).toBe(true);
+ });
+
+ it('extends the hide window when a longer view arrives', () => {
+ markViewedWithTime(12345, 'detail', DETAIL_VIEW_TTL_HOURS); // 12h
+ const shortExpiry = (JSON.parse(localStorage.getItem(VIEWED_DETAIL_TIMES_KEY)!) as Record)['12345'];
+
+ markViewedWithTime(12345, 'detail', DETAIL_VIEW_TTL_LONG_HOURS); // 48h
+ const afterExpiry = (JSON.parse(localStorage.getItem(VIEWED_DETAIL_TIMES_KEY)!) as Record)['12345'];
+
+ expect(afterExpiry).toBeGreaterThan(shortExpiry);
+ });
+
+ it('skips the localStorage write when a re-view cannot extend the window', () => {
+ // The merged expiry is identical whether or not the write is skipped, so the
+ // skip guard can only be protected by asserting on the write itself. Count
+ // writes via a delegating localStorage wrapper (the harness mock exposes
+ // setItem as a get-trap closure, so it can't be spied on the prototype).
+ markViewedWithTime(12345, 'detail', DETAIL_VIEW_TTL_LONG_HOURS); // 48h
+
+ const detailWrites: string[] = [];
+ const real = globalThis.localStorage;
+ const counting = new Proxy(real, {
+ get(t, p, r) {
+ if (p === 'setItem') {
+ return (k: string, v: string) => {
+ if (k === VIEWED_DETAIL_TIMES_KEY) detailWrites.push(k);
+ real.setItem(k, v);
+ };
+ }
+ const passthrough: unknown = Reflect.get(t, p, r);
+ return passthrough;
+ },
+ });
+ Object.defineProperty(globalThis, 'localStorage', { value: counting, configurable: true, writable: true });
+ try {
+ // Shorter re-view (12h < stored 48h) — merge is a no-op, write must be skipped.
+ markViewedWithTime(12345, 'detail', DETAIL_VIEW_TTL_HOURS);
+ expect(detailWrites).toHaveLength(0);
+
+ // A genuinely longer view still persists exactly one write.
+ markViewedWithTime(12345, 'detail', DETAIL_VIEW_TTL_LONG_HOURS * 2);
+ expect(detailWrites).toHaveLength(1);
+ } finally {
+ Object.defineProperty(globalThis, 'localStorage', { value: real, configurable: true, writable: true });
+ }
+ });
});
describe('pruneExpiredViewed', () => {
diff --git a/src/utils/viewedItems.ts b/src/utils/viewedItems.ts
index 90b3306..657ecd9 100644
--- a/src/utils/viewedItems.ts
+++ b/src/utils/viewedItems.ts
@@ -75,122 +75,140 @@ export function useIsViewed(itemId: number | string): boolean {
}
// ============================================================================
-// Time-based viewed tracking (differentiated TTLs for swipe-mode filtering)
+// Time-based viewed tracking (swipe-mode filtering)
+//
+// Each map stores `id -> expiresAt` (absolute ms). An item is hidden from the
+// swipe feed while `expiresAt > now`. Title clicks use a fixed 5-day window;
+// detail views use a dwell-based window (the longer you look, the longer it
+// stays hidden). Storing the expiry — rather than the view time + a fixed TTL —
+// lets each entry carry its own variable lifetime.
// ============================================================================
export const VIEWED_TITLE_TIMES_KEY = 'viewed:times:title';
export const VIEWED_DETAIL_TIMES_KEY = 'viewed:times:detail';
-export const TITLE_CLICK_TTL_HOURS = 120; // 5 days
-export const DETAIL_VIEW_TTL_HOURS = 12;
-
-let titleTimesCache: Record | null = null;
-let detailTimesCache: Record | null = null;
-
-function loadTitleTimes(): Record {
- if (titleTimesCache !== null) return titleTimesCache;
- try {
- const stored = localStorage.getItem(VIEWED_TITLE_TIMES_KEY);
- titleTimesCache = stored ? JSON.parse(stored) as Record : {};
- } catch {
- titleTimesCache = {};
- }
- return titleTimesCache;
+export const TITLE_CLICK_TTL_HOURS = 120; // 5 days
+export const DETAIL_VIEW_TTL_HOURS = 12; // dwell < 3s (short / floor)
+export const DETAIL_VIEW_TTL_MEDIUM_HOURS = 24; // dwell 3-60s
+export const DETAIL_VIEW_TTL_LONG_HOURS = 48; // dwell >= 60s (2 days)
+export const DETAIL_DWELL_MEDIUM_MS = 3_000;
+export const DETAIL_DWELL_LONG_MS = 60_000;
+
+/** Map detail-view dwell time to a hide TTL (hours): longer engagement hides longer. */
+export function detailTtlHoursForDwell(dwellMs: number): number {
+ if (dwellMs >= DETAIL_DWELL_LONG_MS) return DETAIL_VIEW_TTL_LONG_HOURS;
+ if (dwellMs >= DETAIL_DWELL_MEDIUM_MS) return DETAIL_VIEW_TTL_MEDIUM_HOURS;
+ return DETAIL_VIEW_TTL_HOURS;
}
-function saveTitleTimes(): void {
- try {
- localStorage.setItem(VIEWED_TITLE_TIMES_KEY, JSON.stringify(titleTimesCache));
- } catch { /* best-effort */ }
+// Each kind (title / detail) is an `id -> expiresAt` map backed by localStorage
+// with a lazily-built in-memory cache. The factory is the single source of truth
+// for that load/cache/save/reset behavior; `titleTimeMap`/`detailTimeMap` are its
+// two instances.
+function createTimeMap(storageKey: string) {
+ let cache: Record | null = null;
+ return {
+ load(): Record {
+ if (cache !== null) return cache;
+ try {
+ const stored = localStorage.getItem(storageKey);
+ // Tolerate a corrupt/foreign value at our key. Only a plain object is a
+ // valid id->expiresAt map, and only finite-number values are valid
+ // expiries — drop anything else so the rest of the code can assume
+ // `times[id]` is always a number. (A non-number would poison the
+ // Math.max merge with NaN, which `===` can never settle, permanently
+ // wedging that id: never hidden, re-written on every view.)
+ const parsed: unknown = stored ? JSON.parse(stored) : null;
+ const raw = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? parsed as Record
+ : {};
+ const clean: Record = {};
+ for (const [id, expiresAt] of Object.entries(raw)) {
+ if (typeof expiresAt === 'number' && Number.isFinite(expiresAt)) {
+ clean[id] = expiresAt;
+ }
+ }
+ cache = clean;
+ } catch {
+ cache = {};
+ }
+ return cache;
+ },
+ save(): void {
+ try {
+ localStorage.setItem(storageKey, JSON.stringify(cache));
+ } catch { /* best-effort */ }
+ },
+ reset(): void {
+ cache = null;
+ },
+ };
}
-function loadDetailTimes(): Record {
- if (detailTimesCache !== null) return detailTimesCache;
- try {
- const stored = localStorage.getItem(VIEWED_DETAIL_TIMES_KEY);
- detailTimesCache = stored ? JSON.parse(stored) as Record : {};
- } catch {
- detailTimesCache = {};
- }
- return detailTimesCache;
-}
+const titleTimeMap = createTimeMap(VIEWED_TITLE_TIMES_KEY);
+const detailTimeMap = createTimeMap(VIEWED_DETAIL_TIMES_KEY);
-function saveDetailTimes(): void {
- try {
- localStorage.setItem(VIEWED_DETAIL_TIMES_KEY, JSON.stringify(detailTimesCache));
- } catch { /* best-effort */ }
-}
-
-/** Get IDs that should be filtered (hidden) in swipe mode, using per-kind TTLs. */
+/** Get IDs that should be filtered (hidden) in swipe mode — entries not yet expired. */
export function getFilteredViewedIds(): Set {
const now = Date.now();
const result = new Set();
- const titleTimes = loadTitleTimes();
- const titleCutoff = now - TITLE_CLICK_TTL_HOURS * 3_600_000;
- for (const [id, timestamp] of Object.entries(titleTimes)) {
- if (timestamp >= titleCutoff) {
- result.add(Number(id));
- }
- }
-
- const detailTimes = loadDetailTimes();
- const detailCutoff = now - DETAIL_VIEW_TTL_HOURS * 3_600_000;
- for (const [id, timestamp] of Object.entries(detailTimes)) {
- if (timestamp >= detailCutoff) {
- result.add(Number(id));
+ for (const map of [titleTimeMap.load(), detailTimeMap.load()]) {
+ for (const [id, expiresAt] of Object.entries(map)) {
+ if (expiresAt > now) result.add(Number(id));
}
}
return result;
}
-/** Mark viewed with timestamp; persists to permanent + session stores. */
-export function markViewedWithTime(itemId: number | string, kind: 'title' | 'detail' = 'detail'): void {
+/**
+ * Mark viewed with an expiry; persists to the time-based + session stores (and,
+ * for title clicks, the permanent store that drives visual dimming).
+ *
+ * `ttlHours` controls how long the item stays hidden in swipe mode. The stored
+ * expiry is merged with `Math.max`, so re-viewing only ever extends the hide
+ * window — a later or shorter view never shortens an existing one.
+ */
+export function markViewedWithTime(
+ itemId: number | string,
+ kind: 'title' | 'detail' = 'detail',
+ ttlHours = kind === 'title' ? TITLE_CLICK_TTL_HOURS : DETAIL_VIEW_TTL_HOURS,
+): void {
const id = Number(itemId);
if (kind === 'title') markViewed(id);
addToSessionViewed(id);
- if (kind === 'title') {
- const times = loadTitleTimes();
- times[id] = Date.now();
- saveTitleTimes();
- } else {
- const times = loadDetailTimes();
- times[id] = Date.now();
- saveDetailTimes();
- }
+ const map = kind === 'title' ? titleTimeMap : detailTimeMap;
+ const nextExpiry = Date.now() + ttlHours * 3_600_000;
+ const times = map.load();
+ const merged = Math.max(times[id] ?? 0, nextExpiry);
+ // Skip the stringify + write when the merge changes nothing — e.g. re-viewing
+ // an item whose hide window is already longer, or an idempotent re-finalize.
+ if (merged === times[id]) return;
+ times[id] = merged;
+ map.save();
}
export function pruneExpiredViewed(): void {
const now = Date.now();
- const titleTimes = loadTitleTimes();
- const titleCutoff = now - TITLE_CLICK_TTL_HOURS * 3_600_000;
- let pruned = false;
- for (const [id, timestamp] of Object.entries(titleTimes)) {
- if (timestamp < titleCutoff) {
- delete titleTimes[id];
- pruned = true;
- }
- }
- if (pruned) saveTitleTimes();
-
- const detailTimes = loadDetailTimes();
- const detailCutoff = now - DETAIL_VIEW_TTL_HOURS * 3_600_000;
- pruned = false;
- for (const [id, timestamp] of Object.entries(detailTimes)) {
- if (timestamp < detailCutoff) {
- delete detailTimes[id];
- pruned = true;
+ for (const map of [titleTimeMap, detailTimeMap]) {
+ const times = map.load();
+ let pruned = false;
+ for (const [id, expiresAt] of Object.entries(times)) {
+ if (expiresAt <= now) {
+ delete times[id];
+ pruned = true;
+ }
}
+ if (pruned) map.save();
}
- if (pruned) saveDetailTimes();
}
export function clearViewedTimes() {
- titleTimesCache = null;
- detailTimesCache = null;
+ titleTimeMap.reset();
+ detailTimeMap.reset();
try {
localStorage.removeItem(VIEWED_TITLE_TIMES_KEY);
localStorage.removeItem(VIEWED_DETAIL_TIMES_KEY);