diff --git a/src/components/CommentsSection.tsx b/src/components/CommentsSection.tsx
index 9eaba42..537d8ed 100644
--- a/src/components/CommentsSection.tsx
+++ b/src/components/CommentsSection.tsx
@@ -1,5 +1,6 @@
import { useState } from 'react';
-import { CommentTree, CommentSkeletonTree } from '../components';
+import { CommentTree } from './Comment';
+import { CommentSkeletonTree } from './CommentSkeleton';
import { StateView } from './StateView';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
diff --git a/src/components/FullScreenComment.tsx b/src/components/FullScreenComment.tsx
index 414b292..acc8de6 100644
--- a/src/components/FullScreenComment.tsx
+++ b/src/components/FullScreenComment.tsx
@@ -10,7 +10,7 @@ import { StateView } from './StateView';
// Inner content ONLY — consumer supplies the chrome.
// Mirrors CommentArticle's shape.
-export function FullScreenCommentSkeleton() {
+function FullScreenCommentSkeleton() {
return (
diff --git a/src/components/FullScreenItem.tsx b/src/components/FullScreenItem.tsx
index 854f80c..e6bd2a1 100644
--- a/src/components/FullScreenItem.tsx
+++ b/src/components/FullScreenItem.tsx
@@ -2,7 +2,7 @@ import { useItemWithComments } from '../hooks/useItemWithComments';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
import { isPollOption } from '../api/hn';
-import { CommentSkeletonTree } from '../components';
+import { CommentSkeletonTree } from './CommentSkeleton';
import { CommentsSection } from './CommentsSection';
import { FullScreenChrome } from './FullScreenChrome';
import { ItemArticle } from './ItemArticle';
@@ -12,7 +12,7 @@ import type { StoryItem } from '../types';
// Inner content ONLY — consumer supplies chrome.
// Title h-6 ≤ real h1 to prevent PageStage contraction.
-export function FullScreenItemSkeleton() {
+function FullScreenItemSkeleton() {
return (
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index 10f385e..167d517 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -22,6 +22,7 @@ import { useScrollContainer } from '../hooks/useScrollContainer';
import { useIsMobileLayout } from '../hooks/useIsMobileLayout';
import { usePackedNav, type PackableItem } from '../hooks/usePackedNav';
import { clearListSessionState } from '../utils/itemCache';
+import { FEED_TYPES } from '../config/feedTypes';
import { prefersReducedMotion } from '../utils/prefersReducedMotion';
import {
deriveHeaderState,
@@ -187,11 +188,7 @@ export function Header() {
// Clear all session states so we start fresh (logo = "home/reset" action)
const handleLogoClick = () => {
- clearListSessionState('top');
- clearListSessionState('best');
- clearListSessionState('show');
- clearListSessionState('ask');
- clearListSessionState('newest');
+ for (const type of FEED_TYPES) clearListSessionState(type);
if (location.pathname === '/') {
scrollToTop();
}
diff --git a/src/components/StoryCardSkeleton.tsx b/src/components/StoryCardSkeleton.tsx
index a520bf9..4ff1e14 100644
--- a/src/components/StoryCardSkeleton.tsx
+++ b/src/components/StoryCardSkeleton.tsx
@@ -5,7 +5,7 @@ interface StoryCardSkeletonProps {
// Heights ≤ real card to prevent PageStage contraction.
// Second title bar md:hidden (desktop titles fit one line).
-export function StoryCardSkeleton({
+function StoryCardSkeleton({
titleWidths = [0.8, 0.4],
metaWidths = [0.08, 0.16, 0.1, 0.14, 0.12],
}: StoryCardSkeletonProps) {
diff --git a/src/components/index.ts b/src/components/index.ts
index 3edbca1..2fff051 100644
--- a/src/components/index.ts
+++ b/src/components/index.ts
@@ -1,23 +1,12 @@
export { Header } from './Header';
-export { StoryCard } from './StoryCard';
-export { AuthorByline } from './AuthorByline';
-export { RelativeTime } from './RelativeTime';
-export { StoryCardSkeleton, StoryCardSkeletonList } from './StoryCardSkeleton';
-export { ThemeToggle } from './ThemeToggle';
-export { Spinner } from './Spinner';
-export { Comment, CommentTree } from './Comment';
-export { CommentSkeleton, CommentSkeletonTree, ItemDetailSkeleton } from './CommentSkeleton';
+export { ItemDetailSkeleton } from './CommentSkeleton';
export { ErrorBoundary } from './ErrorBoundary';
export { PageStage } from './PageStage';
export { InfiniteStoryListPage } from './InfiniteStoryListPage';
-export { CommentDetail, CommentDetailSkeleton } from './CommentDetail';
-export { FullScreenChrome } from './FullScreenChrome';
-export { FullScreenItem, FullScreenItemSkeleton, FullScreenItemSkeletonPanel } from './FullScreenItem';
+export { CommentDetail } from './CommentDetail';
export { ItemArticle } from './ItemArticle';
-export { FullScreenComment, FullScreenCommentSkeleton, FullScreenCommentSkeletonPanel } from './FullScreenComment';
+export { FullScreenCommentSkeletonPanel } from './FullScreenComment';
export { CommentsSection } from './CommentsSection';
export { StateView } from './StateView';
export { PollOptionArticle } from './PollOptionArticle';
-export { PollOptions } from './PollOptions';
export { NetworkStatusBar } from './NetworkStatusBar';
-export { ShareButton } from './ShareButton';
diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsx
index e24b30a..db8f283 100644
--- a/src/components/ui/dropdown-menu.tsx
+++ b/src/components/ui/dropdown-menu.tsx
@@ -36,11 +36,10 @@ function DropdownMenuContent({
// 0 padding and the rounded corners would clip into the screen edge.
collisionPadding={collisionPadding}
className={cn(
- // Surface (matches Tooltip's bg/border tokens for visual cohesion)
+ // Surface: the popover bg/border tokens
"z-50 min-w-[7rem] origin-(--radix-dropdown-menu-content-transform-origin)",
"overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md",
- // Same fade/zoom + side-aware slide as TooltipContent — keeps the
- // "popover in this app feels like this" affordance consistent.
+ // Fade/zoom + side-aware slide
"animate-in fade-in-0 zoom-in-95",
"data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
"data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
diff --git a/src/components/ui/index.ts b/src/components/ui/index.ts
index 1fabc45..c68bd72 100644
--- a/src/components/ui/index.ts
+++ b/src/components/ui/index.ts
@@ -5,9 +5,3 @@ export {
DropdownMenuItem,
DropdownMenuTrigger,
} from "./dropdown-menu";
-export {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "./tooltip";
diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsx
deleted file mode 100644
index bbc82d2..0000000
--- a/src/components/ui/tooltip.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import type * as React from "react"
-import { Tooltip as TooltipPrimitive } from "radix-ui"
-
-import { cn } from "@/lib/utils"
-
-function TooltipProvider({
- delayDuration = 0,
- ...props
-}: React.ComponentProps
) {
- return (
-
- )
-}
-
-function Tooltip({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function TooltipTrigger({
- ...props
-}: React.ComponentProps) {
- return
-}
-
-function TooltipContent({
- className,
- sideOffset = 0,
- children,
- ...props
-}: React.ComponentProps) {
- return (
-
-
- {children}
-
-
- )
-}
-
-export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/src/config/feedTypes.ts b/src/config/feedTypes.ts
index 3f6828e..8005b52 100644
--- a/src/config/feedTypes.ts
+++ b/src/config/feedTypes.ts
@@ -1,4 +1,6 @@
-import type { FeedType } from '../types';
+/** Every feed, in nav order. 'top' is the homepage and has no nav tab. */
+export const FEED_TYPES = ['top', 'best', 'show', 'ask', 'newest'] as const;
+export type FeedType = (typeof FEED_TYPES)[number];
// 'top' is intentionally omitted — the homepage title is just "HackerTok".
export const FEED_TYPE_TITLES: Partial> = {
diff --git a/src/hooks/usePrefetchSections.ts b/src/hooks/usePrefetchSections.ts
index 95be4a1..6d7ef22 100644
--- a/src/hooks/usePrefetchSections.ts
+++ b/src/hooks/usePrefetchSections.ts
@@ -4,17 +4,12 @@ import { getCachedFeed, setCachedFeed } from '../utils/feedCache';
import { setCachedItem, getCachedItem } from '../utils/itemCache';
import { waitForPriorityFetch } from '../utils/fetchPriority';
import { getFilteredViewedIds, getSessionViewedIds } from '../utils/viewedItems';
+import { FEED_TYPES } from '../config/feedTypes';
import type { StoryItem, FeedType } from '../types';
-const ALL_SECTIONS: FeedType[] = ['top', 'best', 'show', 'ask', 'newest'];
-const CACHE_FRESH_THRESHOLD = 5 * 60 * 1000; // 5 minutes
-
function getCachedStoriesIfFresh(type: FeedType): StoryItem[] | null {
const cached = getCachedFeed(type);
- if (!cached) return null;
- const age = Date.now() - cached.timestamp;
- if (age >= CACHE_FRESH_THRESHOLD) return null;
- return cached.stories;
+ return cached && !cached.isStale ? cached.stories : null;
}
// The story a feed opens on: the swipe viewer skips stories viewed in an
@@ -69,7 +64,7 @@ export function usePrefetchSections(currentType: FeedType, ready = true) {
useEffect(() => {
if (!ready || hasPrefetchedRef.current) return;
- const sectionsNeedingWork = ALL_SECTIONS.filter(type => {
+ const sectionsNeedingWork = FEED_TYPES.filter(type => {
if (type === currentType) return false;
const stories = getCachedStoriesIfFresh(type);
return !stories || needsThread(stories);
diff --git a/src/index.css b/src/index.css
index 4489d7a..63221ad 100644
--- a/src/index.css
+++ b/src/index.css
@@ -108,7 +108,7 @@ html.dark { color-scheme: dark; }
variables into Tailwind v4's color utility space (`bg-primary`,
`bg-popover`, etc.). These are required because shadcn-emitted
class names depend on `--color-` being declared inside @theme.
- Trimmed to only the aliases consumed by the kept Button + Tooltip +
+ Trimmed to only the aliases consumed by the kept Button +
DropdownMenu variants. */
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
diff --git a/src/test/test-utils.tsx b/src/test/test-utils.tsx
index 0fee0d9..ee918c4 100644
--- a/src/test/test-utils.tsx
+++ b/src/test/test-utils.tsx
@@ -3,33 +3,27 @@ import { render, type RenderOptions } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { ThemeProvider } from '../context/ThemeContext';
import { NetworkStatusProvider } from '../context/NetworkStatusContext';
-import { TooltipProvider } from '../components/ui';
import type { ReactElement, ReactNode } from 'react';
import type { InitialEntry } from 'react-router';
/**
* All providers wrapper for testing — wraps with the production root
* providers needed by virtually any rendered subtree (ThemeProvider >
- * TooltipProvider > NetworkStatusProvider) plus a MemoryRouter for routing
- * context. Intentionally OMITS ScrollContainerProvider (the fourth provider
+ * NetworkStatusProvider) plus a MemoryRouter for routing
+ * context. Intentionally OMITS ScrollContainerProvider (the third provider
* in App.tsx); components that exercise scroll-container behavior wrap it
* locally — see UserProfile.test.tsx — to avoid leaking
* document.documentElement classes from enableSwipeMode / disableSwipeMode
- * across tests. The TooltipProvider is required because Header > ThemeToggle
- * (and any other Tooltip consumer in the rendered subtree) calls Radix's
- * `useTooltipContext` and throws "Tooltip must be used within TooltipProvider"
- * without an ancestor provider.
+ * across tests.
*/
function AllProviders({ children, initialEntries = ['/'] }: { children: ReactNode; initialEntries?: InitialEntry[] }) {
return (
-
-
-
- {children}
-
-
-
+
+
+ {children}
+
+
);
}
diff --git a/src/types.ts b/src/types.ts
index c5caec7..a0a6c5a 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -5,7 +5,9 @@
* We use a discriminated union so TypeScript can narrow by `type`.
*/
-export type FeedType = 'top' | 'show' | 'ask' | 'best' | 'newest';
+import type { FeedType } from './config/feedTypes';
+
+export type { FeedType };
interface ItemBase {
id: number;
@@ -145,18 +147,6 @@ export interface AlgoliaItemResponse {
children: AlgoliaItemChild[];
}
-export interface CachedItem {
- item: Item;
- comments: Comment[];
- timestamp: number;
- isFresh: boolean;
-}
-
-export interface CachedFeed {
- stories: StoryItem[];
- timestamp: number;
-}
-
export interface ListSessionState {
scrollY: number;
storyIds: number[];
diff --git a/src/utils/deriveHeaderState.ts b/src/utils/deriveHeaderState.ts
index 439981f..f68f574 100644
--- a/src/utils/deriveHeaderState.ts
+++ b/src/utils/deriveHeaderState.ts
@@ -1,8 +1,9 @@
+import { FEED_TYPES } from '../config/feedTypes';
import type { LocationState, FeedType } from '../types';
-/** Visible feed tabs (excludes 'top'). Order: Best > Show > Ask > New (never reordered). */
-export const FEED_TABS = ['best', 'show', 'ask', 'newest'] as const;
-export type NavFeedType = (typeof FEED_TABS)[number];
+export type NavFeedType = Exclude;
+/** Visible feed tabs, in FEED_TYPES order: Best > Show > Ask > New. */
+const FEED_TABS = FEED_TYPES.filter((f): f is NavFeedType => f !== 'top');
/** Contextual pills: comments > user > from (priority order, mutually exclusive). */
export type ContextualKey = 'comments' | 'user' | 'from';
From 6fbd4527630e3287effcae63bd373e8d7b1aeedb Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Fri, 27 Nov 2026 01:35:12 +0200
Subject: [PATCH 2/7] refactor: share one Algolia paging hook and key pages by
route param
useDomainInfiniteStories and useUserInfiniteStories were two copies of the
same paging, dedup, cache and staleness logic. Both now wrap
useAlgoliaInfiniteStories and only supply the query, the domain host
filter and the domain cold-start cap.
DomainStories, UserSubmissions and UserProfile are now keyed by their
route param in App.tsx, like the swipe viewers already were, so a new
domain or user remounts the page. That replaces the render-time state
resets and layout-effect ref resets in the three hooks.
Tests that rerendered one hook instance with a new key are replaced by a
remount test, and a new e2e test pins the profile key.
---
e2e/domain-filter.spec.ts | 19 +-
e2e/user-profile.spec.ts | 22 +-
e2e/user-submissions.spec.ts | 16 +-
src/App.tsx | 13 +-
src/hooks/useAlgoliaInfiniteStories.ts | 175 ++++++++++++++
src/hooks/useDomainInfiniteStories.test.ts | 133 +---------
src/hooks/useDomainInfiniteStories.ts | 269 ++++-----------------
src/hooks/useUserInfiniteStories.test.ts | 164 -------------
src/hooks/useUserInfiniteStories.ts | 160 ++----------
src/hooks/useUserProfile.test.ts | 55 -----
src/hooks/useUserProfile.ts | 24 +-
11 files changed, 301 insertions(+), 749 deletions(-)
create mode 100644 src/hooks/useAlgoliaInfiniteStories.ts
diff --git a/e2e/domain-filter.spec.ts b/e2e/domain-filter.spec.ts
index 6fb7108..9187a6f 100644
--- a/e2e/domain-filter.spec.ts
+++ b/e2e/domain-filter.spec.ts
@@ -254,15 +254,9 @@ test.describe('Domain Filter - Pagination', () => {
});
test.describe('Domain Filter - Domain change reset', () => {
- // Desktop-scoped: on mobile, SwipeDomainStoryViewer is keyed by `domain`
- // in App.tsx, which unmounts the old viewer and mounts a fresh one on
- // every domain change — the new instance initializes cleanly through
- // the hook's lazy useState init, so the `if (prevDomain !== domain)`
- // reset block never runs. DomainStories is NOT keyed and stays mounted
- // across /#/from/:a → /#/from/:b transitions, which is the only browser
- // path that exercises the reset block. (Unit tests pin the branch
- // directly; this pins the wiring between StoryCard's hostname pill and
- // the hook.)
+ // Desktop-scoped: pins the `key` on DomainStories in App.tsx. The route
+ // element stays the same across /#/from/:a → /#/from/:b, so without the
+ // key the page would keep the old domain's list state.
test.use({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 });
test.beforeEach(async ({ page }) => {
@@ -275,15 +269,14 @@ test.describe('Domain Filter - Domain change reset', () => {
// Client-side hash change — same mechanism React Router dispatches
// when StoryCard's hostname pill is clicked to cross-link into a
- // different domain. No page reload, so the DomainStories instance
- // stays mounted and the hook re-renders with a new `domain` prop.
+ // different domain. No page reload; only the key remounts the page.
await page.evaluate(() => { window.location.hash = '#/from/example.org'; });
// The default mock returns mockDomainItem (URL: https://example.com/…)
// regardless of the `query` param, so the hook's URL-filter rejects
// every hit for example.org and we land on the empty state. That
- // state rendering is only possible if the reset block cleared the
- // old `stories` array — otherwise the first commit after the hash
+ // state rendering is only possible if the remount dropped the old
+ // `stories` array — otherwise the first commit after the hash
// change would still show the example.com items.
await expect(page.getByText('Google Announces Gemini 3.0 with Extended Context')).not.toBeVisible({ timeout: 5000 });
await expect(page.getByText(/No submissions found from.*example\.org/i)).toBeVisible({ timeout: 10000 });
diff --git a/e2e/user-profile.spec.ts b/e2e/user-profile.spec.ts
index c612425..ad290bb 100644
--- a/e2e/user-profile.spec.ts
+++ b/e2e/user-profile.spec.ts
@@ -1,5 +1,10 @@
import { test, expect } from '@playwright/test';
-import { setupApiMocks, stubNotFoundUser } from './fixtures/api-mocks';
+import {
+ setupApiMocks,
+ stubNotFoundUser,
+ createFirebaseWsHandler,
+ FIREBASE_WS_PATTERN,
+} from './fixtures/api-mocks';
import { waitForSwipeReady } from './fixtures/swipe-helpers';
test.describe('User Profile - Desktop', () => {
@@ -40,6 +45,21 @@ test.describe('User Profile - Desktop', () => {
await expect(page).toHaveTitle('pg | HackerTok');
});
+ test('drops the old profile at once when navigating between two users', async ({ page }) => {
+ // Slow responses keep dang loading long enough to see what shows meanwhile.
+ await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ delayMs: 1500 }));
+ await page.goto('/#/user/pg');
+ await expect(page.getByText('155,555 karma')).toBeVisible({ timeout: 10_000 });
+
+ // Same route element, so only the `key` in App.tsx remounts the page.
+ await page.evaluate(() => { window.location.hash = '#/user/dang'; });
+
+ // pg's profile must not linger while dang's loads.
+ await expect(page.getByText('155,555 karma')).not.toBeVisible({ timeout: 1000 });
+ await expect(page.getByRole('heading', { level: 1, name: 'dang' })).toBeVisible({ timeout: 10_000 });
+ await expect(page.getByText('1 karma', { exact: true })).toBeVisible();
+ });
+
test('"submissions" metadata link navigates to /#/submitted/:id', async ({ page }) => {
await page.goto('/#/user/pg');
diff --git a/e2e/user-submissions.spec.ts b/e2e/user-submissions.spec.ts
index efd36ca..7df6591 100644
--- a/e2e/user-submissions.spec.ts
+++ b/e2e/user-submissions.spec.ts
@@ -109,12 +109,9 @@ test.describe('User Submissions - Desktop', () => {
});
test.describe('User Submissions - User change reset', () => {
- // Desktop-scoped: on mobile, `SwipeUserSubmissionsViewer` is keyed by
- // `username` in `MobileUserSubmissionsWrapper`, so a username change
- // unmounts the old viewer entirely. The reset block in
- // `useUserInfiniteStories` only runs when the same hook instance sees a
- // new `username` prop — that path exists on desktop because
- // `UserSubmissions` is NOT keyed by `username` in App.tsx.
+ // Desktop-scoped: pins the `key` on `UserSubmissions` in App.tsx. The
+ // route element stays the same across users, so without the key the page
+ // would keep the old user's list state.
test.use({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 });
test.beforeEach(async ({ page }) => {
@@ -126,13 +123,12 @@ test.describe('User Submissions - User change reset', () => {
await expect(page.getByText('Beating the Averages')).toBeVisible({ timeout: 10_000 });
// Client-side hash change — same as clicking an author byline link from
- // a comment thread. No reload, so `UserSubmissions` stays mounted and
- // the hook re-renders with the new `username` prop.
+ // a comment thread. No reload; only the key remounts the page.
await page.evaluate(() => { window.location.hash = '#/submitted/dang'; });
// The default mock returns a synthetic "Story by dang" for unknown users.
- // The `pg` story must disappear (proves the reset block ran — otherwise
- // the first commit after the prop change would still show pg's stories).
+ // The `pg` story must disappear (proves the page remounted — otherwise
+ // the first commit after the hash change would still show pg's stories).
await expect(page.getByText('Beating the Averages')).not.toBeVisible({ timeout: 5_000 });
await expect(page.getByText('Story by dang')).toBeVisible({ timeout: 10_000 });
diff --git a/src/App.tsx b/src/App.tsx
index 7839df8..c6048c1 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -9,6 +9,7 @@ import { useCanSwipe } from './hooks/useCanSwipe';
import { useDocumentTitle } from './hooks/useDocumentTitle';
import { ItemDetail } from './pages/ItemDetail';
import { DomainStories } from './pages/DomainStories';
+import { canonicalizeDomain } from './hooks/useDomainInfiniteStories';
import { UserProfile } from './pages/UserProfile';
import { UserSubmissions } from './pages/UserSubmissions';
import { SwipeStoryViewer } from './components/SwipeStoryViewer';
@@ -34,7 +35,8 @@ function MobileDomainStoriesWrapper() {
return ;
}
- return ;
+ // Keyed like the swipe viewers: a new domain gets fresh list state.
+ return ;
}
// Falls through to the desktop list when the URL has no username so
@@ -54,7 +56,12 @@ function MobileUserSubmissionsWrapper() {
return ;
}
- return ;
+ return ;
+}
+
+function UserProfileRoute() {
+ const { id } = useParams<{ id: string }>();
+ return ;
}
// Maps a viewer context to its swipe viewer (priority fromUser → fromDomain → from;
@@ -308,7 +315,7 @@ function App() {
} />
} />
} />
- } />
+ } />
} />
} />
diff --git a/src/hooks/useAlgoliaInfiniteStories.ts b/src/hooks/useAlgoliaInfiniteStories.ts
new file mode 100644
index 0000000..6e76721
--- /dev/null
+++ b/src/hooks/useAlgoliaInfiniteStories.ts
@@ -0,0 +1,175 @@
+import { useState, useCallback, useRef, useEffect } from 'react';
+import { ALGOLIA_API } from '../config/api';
+import { normalizeAlgoliaHit } from '../api/hn';
+import { algoliaPageParams, nextAlgoliaPage, type AlgoliaPageCursor } from '../utils/algoliaPaging';
+import type { StoryItem, AlgoliaHit, AlgoliaSearchResponse } from '../types';
+
+const HITS_PER_PAGE = 50;
+
+interface AlgoliaStoriesCacheEntry {
+ stories: StoryItem[];
+ page: number;
+ before?: number;
+ hasMore: boolean;
+ seenIds: Set;
+}
+
+/** Module-level in-memory cache per key (survives remounts, not persisted). */
+export type AlgoliaStoriesCache = Map;
+
+export interface AlgoliaStoriesSource {
+ cache: AlgoliaStoriesCache;
+ /** `search_by_date` params for `key`, without the paging params. */
+ query: (key: string) => string;
+ /** Keeps only the hits that really match `key`. */
+ accept?: (hit: AlgoliaHit, key: string) => boolean;
+ /**
+ * On a cold start (no story accepted yet), keep paging within one
+ * `loadMore` until a page yields a story, giving up after this many empty
+ * pages in a row. Unset: one page per call.
+ */
+ maxEmptyPagesColdStart?: number;
+}
+
+/**
+ * Paginated stories from Algolia `search_by_date`, deduped across pages and
+ * cached per `key`. `key` is fixed for the hook's lifetime: callers remount
+ * (React `key`) to switch, so state never carries over between keys.
+ */
+export function useAlgoliaInfiniteStories(key: string, source: AlgoliaStoriesSource) {
+ const initialCached = key ? source.cache.get(key) : undefined;
+
+ const [stories, setStories] = useState(initialCached?.stories ?? []);
+ const [loading, setLoading] = useState(!initialCached && !!key);
+ const [error, setError] = useState(null);
+ const [hasMore, setHasMore] = useState(initialCached?.hasMore ?? true);
+
+ const nextPageRef = useRef({ page: initialCached?.page ?? 0, before: initialCached?.before });
+ const seenIdsRef = useRef>(new Set(initialCached?.seenIds ?? []));
+ // Bumped by `reset` so a response for the cleared list is dropped.
+ const versionRef = useRef(0);
+ const inFlightRef = useRef(false);
+ const emptyPageStreakRef = useRef(0);
+ // Mirrors committed `stories` state. Used so `loadMore` can compute the
+ // next list and write the cache synchronously, without either
+ // (a) adding `stories` to useCallback deps (causing spurious re-renders
+ // in downstream effects) or (b) performing a side effect inside the
+ // setStories functional updater (which StrictMode double-invokes in dev,
+ // writing to the cache twice per load).
+ const storiesRef = useRef(initialCached?.stories ?? []);
+
+ const loadMore = useCallback(async () => {
+ if (!key || !hasMore || inFlightRef.current) return;
+ inFlightRef.current = true;
+
+ setLoading(true);
+ setError(null);
+
+ const currentVersion = versionRef.current;
+ const { cache, query, accept, maxEmptyPagesColdStart } = source;
+
+ try {
+ let uniqueStories: StoryItem[];
+ let newHasMore: boolean;
+ // A cold start may page on until a story lands: see maxEmptyPagesColdStart.
+ do {
+ const pageToFetch = nextPageRef.current;
+ const url = `${ALGOLIA_API}/search_by_date?${query(key)}&hitsPerPage=${HITS_PER_PAGE}${algoliaPageParams(pageToFetch)}`;
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch stories: ${response.status}`);
+ }
+
+ if (versionRef.current !== currentVersion) return;
+
+ const data = (await response.json()) as AlgoliaSearchResponse;
+
+ // Second staleness check: `reset` can run while the body parses.
+ if (versionRef.current !== currentVersion) return;
+
+ const hits = accept ? data.hits.filter((hit) => accept(hit, key)) : data.hits;
+
+ // Dedup across pages (Algolia can return overlaps on paginated search_by_date)
+ uniqueStories = hits.map(normalizeAlgoliaHit).filter((s) => {
+ if (seenIdsRef.current.has(s.id)) return false;
+ seenIdsRef.current.add(s.id);
+ return true;
+ });
+
+ const nextPage = nextAlgoliaPage(data, HITS_PER_PAGE, pageToFetch);
+ nextPageRef.current = nextPage ?? { ...pageToFetch, page: data.page + 1 };
+
+ // Cold-start cap. Snapshot before the storiesRef update below so the
+ // check reflects "had we shown anything before this fetch?", not "are
+ // we showing anything after it?".
+ const isColdStart = storiesRef.current.length === 0;
+ if (uniqueStories.length === 0 && isColdStart) {
+ emptyPageStreakRef.current += 1;
+ } else {
+ emptyPageStreakRef.current = 0;
+ }
+ const capReached =
+ maxEmptyPagesColdStart !== undefined && emptyPageStreakRef.current >= maxEmptyPagesColdStart;
+ newHasMore = nextPage !== null && !capReached;
+ } while (
+ maxEmptyPagesColdStart !== undefined &&
+ uniqueStories.length === 0 &&
+ storiesRef.current.length === 0 &&
+ newHasMore
+ );
+ setHasMore(newHasMore);
+
+ // Compute the next list outside any functional updater so setStories stays
+ // pure (StrictMode double-invokes impure updaters). `storiesRef` mirrors
+ // committed state and is safe to read here because inFlightRef guards
+ // against concurrent loadMore runs.
+ const updated = [...storiesRef.current, ...uniqueStories];
+ storiesRef.current = updated;
+ cache.set(key, {
+ stories: updated,
+ ...nextPageRef.current,
+ hasMore: newHasMore,
+ seenIds: new Set(seenIdsRef.current),
+ });
+ setStories(updated);
+ } catch (err) {
+ if (versionRef.current !== currentVersion) return;
+ setError(err instanceof Error ? err.message : String(err));
+ throw err;
+ } finally {
+ // Only clear flags if this fetch is still the current version. After a
+ // `reset`, a newer fetch may own inFlightRef and loading.
+ if (versionRef.current === currentVersion) {
+ inFlightRef.current = false;
+ setLoading(false);
+ }
+ }
+ }, [key, hasMore, source]);
+
+ // Kick off the first fetch when we have no stories for this key.
+ // No cleanup/abort — version counter handles stale responses, and aborting
+ // on cleanup would break StrictMode (mount → abort → skip-because-inFlight).
+ useEffect(() => {
+ if (!key) return;
+ if (stories.length === 0 && !inFlightRef.current) {
+ void loadMore().catch(() => { /* error state set internally */ });
+ }
+ }, [key, stories.length, loadMore]);
+
+ const reset = useCallback(() => {
+ versionRef.current += 1;
+ inFlightRef.current = false;
+ setStories([]);
+ setLoading(!!key);
+ setError(null);
+ setHasMore(true);
+ nextPageRef.current = { page: 0 };
+ seenIdsRef.current = new Set();
+ storiesRef.current = [];
+ emptyPageStreakRef.current = 0;
+ if (key) source.cache.delete(key);
+ }, [key, source]);
+
+ return { stories, loading, error, hasMore, loadMore, reset } as const;
+}
diff --git a/src/hooks/useDomainInfiniteStories.test.ts b/src/hooks/useDomainInfiniteStories.test.ts
index 09c41bc..0797d9f 100644
--- a/src/hooks/useDomainInfiniteStories.test.ts
+++ b/src/hooks/useDomainInfiniteStories.test.ts
@@ -69,19 +69,6 @@ function defer(): Deferred {
return { promise, resolve };
}
-/**
- * A controllable "Response" where json() resolves on demand. Lets us simulate
- * the window between the version check after `await fetch()` and the state
- * mutations that happen after `await response.json()`.
- */
-function fakeResponse(jsonDeferred: Deferred, status = 200): Response {
- return {
- ok: status >= 200 && status < 300,
- status,
- json: () => jsonDeferred.promise as unknown as Promise,
- } as unknown as Response;
-}
-
/** Extracts the URL string from a `fetch` mock's input argument. */
function fetchInputToUrl(input: RequestInfo | URL | undefined): string {
if (!input) return '';
@@ -223,29 +210,25 @@ describe('useDomainInfiniteStories', () => {
expect(result.current.hasMore).toBe(false);
});
- describe('domain-change staleness', () => {
- it('discards stale response that resolves AFTER a rerender to a new domain', async () => {
- // Scenario: user navigates to beta BEFORE alpha's fetch() resolves.
- // The first version check (after await fetch()) must catch it.
+ describe('remount per domain', () => {
+ it('keeps a response that lands after unmount under its own domain', async () => {
+ // Pages remount per domain (React `key`), so a late response from the
+ // old instance must neither reach the new one nor land in its cache.
const deferredByDomain = new Map>();
vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
const url = fetchInputToUrl(input);
const params = new URLSearchParams(url.split('?')[1] ?? '');
- const domain = decodeURIComponent(params.get('query') ?? '');
const d = defer();
- deferredByDomain.set(domain, d);
+ deferredByDomain.set(params.get('query') ?? '', d);
return d.promise;
});
- const { result, rerender } = renderHook(
- ({ domain }: { domain: string }) => useDomainInfiniteStories(domain),
- { initialProps: { domain: 'alpha.com' } },
- );
-
+ const alpha = renderHook(() => useDomainInfiniteStories('alpha.com'));
await waitFor(() => expect(deferredByDomain.has('alpha.com')).toBe(true));
+ alpha.unmount();
- rerender({ domain: 'beta.com' });
+ const beta = renderHook(() => useDomainInfiniteStories('beta.com'));
await waitFor(() => expect(deferredByDomain.has('beta.com')).toBe(true));
await act(async () => {
@@ -257,71 +240,11 @@ describe('useDomainInfiniteStories', () => {
);
});
- await waitFor(() => expect(result.current.loading).toBe(false));
-
- expect(result.current.stories.map((s) => s.id)).toEqual([100, 101]);
- });
-
- it('discards stale response whose json() resolves AFTER a rerender to a new domain', async () => {
- // Scenario: alpha.fetch() has resolved and passed the first version
- // check; we're inside `await response.json()` when the rerender happens.
- // This is the case the single pre-json check would miss; a second check
- // after json() is required.
- const fetchDeferred = new Map>();
- const jsonDeferred = new Map>();
-
- vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
- const url = fetchInputToUrl(input);
- const params = new URLSearchParams(url.split('?')[1] ?? '');
- const domain = decodeURIComponent(params.get('query') ?? '');
- const fd = defer();
- const jd = defer();
- fetchDeferred.set(domain, fd);
- jsonDeferred.set(domain, jd);
- return fd.promise;
- });
-
- const { result, rerender } = renderHook(
- ({ domain }: { domain: string }) => useDomainInfiniteStories(domain),
- { initialProps: { domain: 'alpha.com' } },
- );
-
- await waitFor(() => expect(fetchDeferred.has('alpha.com')).toBe(true));
-
- // Alpha's fetch resolves but json() is still pending.
- await act(async () => {
- fetchDeferred.get('alpha.com')!.resolve(fakeResponse(jsonDeferred.get('alpha.com')!));
- await Promise.resolve();
- await Promise.resolve();
- });
-
- // Rerender to beta while alpha's json() is pending.
- rerender({ domain: 'beta.com' });
- await waitFor(() => expect(fetchDeferred.has('beta.com')).toBe(true));
-
- // Beta's fetch resolves cleanly.
- await act(async () => {
- fetchDeferred.get('beta.com')!.resolve(
- new Response(JSON.stringify(body('beta.com', [100, 101]))),
- );
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- });
-
- // Alpha's stale json() finally resolves — the second version check
- // must discard it.
- await act(async () => {
- jsonDeferred.get('alpha.com')!.resolve(body('alpha.com', [1, 2, 3]));
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- });
-
- await waitFor(() => expect(result.current.loading).toBe(false));
-
- expect(result.current.stories.map((s) => s.id)).toEqual([100, 101]);
+ await waitFor(() => expect(beta.result.current.loading).toBe(false));
+ expect(beta.result.current.stories.map((s) => s.id)).toEqual([100, 101]);
+ const cache = __getDomainCacheForTests();
+ expect(cache.get('beta.com')?.stories.map((s) => s.id)).toEqual([100, 101]);
+ expect(cache.get('alpha.com')?.stories.map((s) => s.id)).toEqual([1, 2, 3]);
});
});
@@ -910,36 +833,6 @@ describe('useDomainInfiniteStories', () => {
}
expect(call).toBe(6);
});
-
- it('resets the streak when the domain changes', async () => {
- const calls = { foo: 0, bar: 0 };
- vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
- const url = fetchInputToUrl(input);
- const targetDomain = url.includes('query=foo') ? 'foo' : 'bar';
- const page = calls[targetDomain]++;
- return Promise.resolve(
- new Response(JSON.stringify(noiseBody(targetDomain, 50, page, 10))),
- );
- });
-
- const { result, rerender } = renderHook(
- ({ domain }: { domain: string }) => useDomainInfiniteStories(domain),
- { initialProps: { domain: 'foo' } },
- );
-
- // foo: 3 noise pages → streak=3, cap reached
- await waitFor(() => expect(result.current.hasMore).toBe(false));
- expect(calls.foo).toBe(3);
-
- // Switch to bar — domain reset block must zero the streak. If it
- // doesn't, the (stale) counter would tip at bar's first noise page
- // and the cap would fire after 1 fetch on the new domain.
- rerender({ domain: 'bar' });
- await waitFor(() => expect(calls.bar).toBeGreaterThan(0));
- await waitFor(() => expect(result.current.loading).toBe(false));
- expect(result.current.hasMore).toBe(false);
- expect(calls.bar).toBe(3);
- });
});
describe('empty domain', () => {
diff --git a/src/hooks/useDomainInfiniteStories.ts b/src/hooks/useDomainInfiniteStories.ts
index 30693c6..e871e0c 100644
--- a/src/hooks/useDomainInfiniteStories.ts
+++ b/src/hooks/useDomainInfiniteStories.ts
@@ -1,10 +1,10 @@
-import { useState, useCallback, useRef, useEffect, useLayoutEffect } from 'react';
-import { ALGOLIA_API } from '../config/api';
-import { normalizeAlgoliaHit } from '../api/hn';
-import { algoliaPageParams, nextAlgoliaPage, type AlgoliaPageCursor } from '../utils/algoliaPaging';
-import type { StoryItem, AlgoliaSearchResponse } from '../types';
+import {
+ useAlgoliaInfiniteStories,
+ type AlgoliaStoriesCache,
+ type AlgoliaStoriesSource,
+} from './useAlgoliaInfiniteStories';
+import type { AlgoliaHit } from '../types';
-const HITS_PER_PAGE = 50;
// On a cold start (no story has been accepted yet), `loadMore` keeps paging
// within one call until a page yields a story, and gives up after this many
// consecutive pages whose hits all fail the host filter. Algolia's URL search
@@ -14,20 +14,11 @@ const HITS_PER_PAGE = 50;
// because nothing else asks for page 2: the desktop list has no sentinel to
// scroll while it's empty, so a first page of noise read as "no submissions"
// even when the next page had them. The cap bounds noisy queries.
-// Only applies while `storiesRef.current.length === 0`; once any real hit
-// lands, deep pagination is unbounded so sparse-but-real domains aren't trimmed.
+// Only applies while no story has been accepted; once any real hit lands,
+// deep pagination is unbounded so sparse-but-real domains aren't trimmed.
const MAX_EMPTY_PAGES_COLD_START = 3;
-interface DomainCacheEntry {
- stories: StoryItem[];
- page: number;
- before?: number;
- hasMore: boolean;
- seenIds: Set;
-}
-
-// Module-level in-memory cache (survives remounts, not persisted).
-const domainCache = new Map();
+const domainCache: AlgoliaStoriesCache = new Map();
/**
* @internal Testing helper to reset the module-level cache between tests.
@@ -57,209 +48,51 @@ export function formatNoSubmissionsTitle(domain: string): string {
return `No submissions found from "${domain}"`;
}
+// `domain` is a hostname (e.g. "github.com") OR a hostname+path
+// (e.g. "github.com/microsoft"). Algolia's URL search can surface hits
+// where the domain appears elsewhere in the URL (other host, path
+// segment, query string), so verify locally. The match must require a
+// `/` boundary after the domain — a bare `startsWith(domain)` would let
+// `github.com.evil.com` surface under `/from/github.com`.
+//
+// Only http(s) URLs are accepted: defense-in-depth against
+// `javascript:`/`data:`/`file:` URLs, which `new URL` happily parses
+// with a `hostname` that would otherwise pass the host check (e.g.
+// `javascript://github.com/%0Aalert(1)` parses with hostname=github.com).
+function isFromDomain(hit: AlgoliaHit, domain: string): boolean {
+ if (!hit.url) return false;
+ try {
+ const parsed = new URL(hit.url);
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
+ // hostname is already lowercase per WHATWG; pathname preserves
+ // case, so lowercase the full string for case-insensitive match
+ // against the (already-lowercased) `domain`. Trailing DNS dot is
+ // stripped for the same reason as the domain prop.
+ const hostname = parsed.hostname.replace(/^www\./, '').replace(/\.$/, '');
+ const fullPath = (hostname + parsed.pathname).toLowerCase();
+ return (
+ fullPath === domain ||
+ fullPath.startsWith(`${domain}/`) ||
+ hostname.endsWith(`.${domain}`)
+ );
+ } catch {
+ return false;
+ }
+}
+
+const domainSource: AlgoliaStoriesSource = {
+ cache: domainCache,
+ query: (domain) => `tags=story&query=${encodeURIComponent(domain)}&restrictSearchableAttributes=url`,
+ accept: isFromDomain,
+ maxEmptyPagesColdStart: MAX_EMPTY_PAGES_COLD_START,
+};
+
/**
- * Paginated domain stories from Algolia URL search.
- * Dedupes, invalidates stale responses, and caches at module level.
+ * Paginated domain stories from Algolia URL search, filtered to the domain.
+ * Remount (React `key`) to change domain.
*/
export function useDomainInfiniteStories(rawDomain: string) {
// Canonicalize at entry so cache key, Algolia query, and filter all key off
// the same form. See `canonicalizeDomain` for the list of normalizations.
- const domain = canonicalizeDomain(rawDomain);
-
- const initialCached = domain ? domainCache.get(domain) : undefined;
-
- const [stories, setStories] = useState(initialCached?.stories ?? []);
- const [loading, setLoading] = useState(!initialCached && !!domain);
- const [error, setError] = useState(null);
- const [hasMore, setHasMore] = useState(initialCached?.hasMore ?? true);
- const [prevDomain, setPrevDomain] = useState(domain);
-
- const nextPageRef = useRef({ page: initialCached?.page ?? 0, before: initialCached?.before });
- const seenIdsRef = useRef>(new Set(initialCached?.seenIds ?? []));
- const versionRef = useRef(0);
- const inFlightRef = useRef(false);
- const emptyPageStreakRef = useRef(0);
- // Mirrors committed `stories` state. Used so `loadMore` can compute the
- // next list and write the domain cache synchronously, without either
- // (a) adding `stories` to useCallback deps (causing spurious re-renders
- // in downstream effects) or (b) performing a side effect inside the
- // setStories functional updater (which StrictMode double-invokes in dev,
- // writing to the cache twice per load).
- const storiesRef = useRef(initialCached?.stories ?? []);
-
- // React pattern for prop-derived state: reset when `domain` changes
- // without waiting for an effect. This runs during render and React
- // re-renders with the new state before committing.
- // https://react.dev/reference/react/useState#storing-information-from-previous-renders
- if (prevDomain !== domain) {
- setPrevDomain(domain);
- const newCached = domain ? domainCache.get(domain) : undefined;
- const newStories = newCached?.stories ?? [];
- setStories(newStories);
- setLoading(!newCached && !!domain);
- setError(null);
- setHasMore(newCached?.hasMore ?? true);
- }
-
- // Reset refs when `domain` changes. useLayoutEffect runs synchronously
- // after commit, before any microtask (Promise.then) can fire — this
- // ensures versionRef is bumped before a stale in-flight fetch can check
- // it. useEffect would leave a gap where resolved fetches slip through.
- useLayoutEffect(() => {
- const cached = domain ? domainCache.get(domain) : undefined;
- nextPageRef.current = { page: cached?.page ?? 0, before: cached?.before };
- seenIdsRef.current = new Set(cached?.seenIds ?? []);
- storiesRef.current = cached?.stories ?? [];
- versionRef.current += 1;
- inFlightRef.current = false;
- emptyPageStreakRef.current = 0;
- }, [domain]);
-
- const loadMore = useCallback(async () => {
- if (!domain || !hasMore || inFlightRef.current) return;
- inFlightRef.current = true;
-
- setLoading(true);
- setError(null);
-
- const currentVersion = versionRef.current;
-
- try {
- let uniqueStories: StoryItem[];
- let newHasMore: boolean;
- // Cold start pages on until a story lands: see MAX_EMPTY_PAGES_COLD_START.
- do {
- const pageToFetch = nextPageRef.current;
- const url = `${ALGOLIA_API}/search_by_date?tags=story&query=${encodeURIComponent(domain)}&restrictSearchableAttributes=url&hitsPerPage=${HITS_PER_PAGE}${algoliaPageParams(pageToFetch)}`;
- const response = await fetch(url);
-
- if (!response.ok) {
- throw new Error(`Failed to fetch stories: ${response.status}`);
- }
-
- if (versionRef.current !== currentVersion) return;
-
- const data = (await response.json()) as AlgoliaSearchResponse;
-
- // Second staleness check: `await response.json()` yields; the domain
- // can change (and bump versionRef) during parse. Without this, the
- // closure-captured `domain` would cause `domainCache.set(domain, ...)`
- // to clobber the old domain's entry with partial data, and the
- // appended stories would land on the new domain's state.
- if (versionRef.current !== currentVersion) return;
-
- // `domain` is a hostname (e.g. "github.com") OR a hostname+path
- // (e.g. "github.com/microsoft"). Algolia's URL search can surface hits
- // where the domain appears elsewhere in the URL (other host, path
- // segment, query string), so verify locally. The match must require a
- // `/` boundary after the domain — a bare `startsWith(domain)` would let
- // `github.com.evil.com` surface under `/from/github.com`.
- //
- // Only http(s) URLs are accepted: defense-in-depth against
- // `javascript:`/`data:`/`file:` URLs, which `new URL` happily parses
- // with a `hostname` that would otherwise pass the host check (e.g.
- // `javascript://github.com/%0Aalert(1)` parses with hostname=github.com).
- const domainSlashPrefix = `${domain}/`;
- const hostDotSuffix = `.${domain}`;
- const domainStories: StoryItem[] = data.hits
- .filter((hit) => {
- if (!hit.url) return false;
- try {
- const parsed = new URL(hit.url);
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
- // hostname is already lowercase per WHATWG; pathname preserves
- // case, so lowercase the full string for case-insensitive match
- // against the (already-lowercased) `domain`. Trailing DNS dot is
- // stripped for the same reason as the domain prop.
- const hostname = parsed.hostname.replace(/^www\./, '').replace(/\.$/, '');
- const fullPath = (hostname + parsed.pathname).toLowerCase();
- return (
- fullPath === domain ||
- fullPath.startsWith(domainSlashPrefix) ||
- hostname.endsWith(hostDotSuffix)
- );
- } catch {
- return false;
- }
- })
- .map(normalizeAlgoliaHit);
-
- // Dedup across pages (Algolia can return overlaps on paginated search_by_date)
- uniqueStories = domainStories.filter((s) => {
- if (seenIdsRef.current.has(s.id)) return false;
- seenIdsRef.current.add(s.id);
- return true;
- });
-
- const nextPage = nextAlgoliaPage(data, HITS_PER_PAGE, pageToFetch);
- nextPageRef.current = nextPage ?? { ...pageToFetch, page: data.page + 1 };
-
- // Cold-start cap. Snapshot before the storiesRef update below so the
- // check reflects "had we shown anything before this fetch?", not "are
- // we showing anything after it?".
- const isColdStart = storiesRef.current.length === 0;
- if (uniqueStories.length === 0 && isColdStart) {
- emptyPageStreakRef.current += 1;
- } else {
- emptyPageStreakRef.current = 0;
- }
- const algoliaHasMore = nextPage !== null;
- const capReached = emptyPageStreakRef.current >= MAX_EMPTY_PAGES_COLD_START;
- newHasMore = algoliaHasMore && !capReached;
- } while (uniqueStories.length === 0 && storiesRef.current.length === 0 && newHasMore);
- setHasMore(newHasMore);
-
- // Compute the next list outside any functional updater so setStories stays
- // pure (StrictMode double-invokes impure updaters). `storiesRef` mirrors
- // committed state and is safe to read here because inFlightRef guards
- // against concurrent loadMore runs for the same domain.
- const updated = [...storiesRef.current, ...uniqueStories];
- storiesRef.current = updated;
- domainCache.set(domain, {
- stories: updated,
- ...nextPageRef.current,
- hasMore: newHasMore,
- seenIds: new Set(seenIdsRef.current),
- });
- setStories(updated);
- } catch (err) {
- if (versionRef.current !== currentVersion) return;
- setError(err instanceof Error ? err.message : String(err));
- throw err;
- } finally {
- // Only clear flags if this fetch is still the current version.
- // If domain changed mid-flight, the reset block already cleared them and
- // started a new fetch — we must not clobber that fetch's inFlightRef.
- if (versionRef.current === currentVersion) {
- inFlightRef.current = false;
- setLoading(false);
- }
- }
- }, [domain, hasMore]);
-
- // Kick off the first fetch when we have no stories for this domain.
- // No cleanup/abort — version counter handles stale responses, and aborting
- // on cleanup would break StrictMode (mount → abort → skip-because-inFlight).
- useEffect(() => {
- if (!domain) return;
- if (stories.length === 0 && !inFlightRef.current) {
- void loadMore().catch(() => { /* error state set internally */ });
- }
- }, [domain, stories.length, loadMore]);
-
- const reset = useCallback(() => {
- versionRef.current += 1;
- inFlightRef.current = false;
- setStories([]);
- setLoading(!!domain);
- setError(null);
- setHasMore(true);
- nextPageRef.current = { page: 0 };
- seenIdsRef.current = new Set();
- storiesRef.current = [];
- emptyPageStreakRef.current = 0;
- if (domain) domainCache.delete(domain);
- }, [domain]);
-
- return { stories, loading, error, hasMore, loadMore, reset } as const;
+ return useAlgoliaInfiniteStories(canonicalizeDomain(rawDomain), domainSource);
}
diff --git a/src/hooks/useUserInfiniteStories.test.ts b/src/hooks/useUserInfiniteStories.test.ts
index 08bd555..9b6e8ab 100644
--- a/src/hooks/useUserInfiniteStories.test.ts
+++ b/src/hooks/useUserInfiniteStories.test.ts
@@ -34,39 +34,6 @@ function fetchInputToUrl(input: RequestInfo | URL | undefined): string {
return input.url;
}
-interface Deferred {
- promise: Promise;
- resolve: (v: T) => void;
-}
-function defer(): Deferred {
- let resolve!: (v: T) => void;
- const promise = new Promise((r) => {
- resolve = r;
- });
- return { promise, resolve };
-}
-
-/**
- * A controllable "Response" where json() resolves on demand. Lets us simulate
- * the window between the version check after `await fetch()` and the state
- * mutations that happen after `await response.json()`. Mirrors the helper in
- * `useDomainInfiniteStories.test.ts`.
- */
-function fakeResponse(jsonDeferred: Deferred, status = 200): Response {
- return {
- ok: status >= 200 && status < 300,
- status,
- json: () => jsonDeferred.promise as unknown as Promise,
- } as unknown as Response;
-}
-
-/** Extracts the author tag value from a `search_by_date?tags=(story,poll),author_X` URL. */
-function authorFromUrl(url: string): string {
- const params = new URLSearchParams(url.split('?')[1] ?? '');
- const tags = params.get('tags') ?? '';
- return /author_([^,]+)/.exec(tags)?.[1] ?? '';
-}
-
describe('formatNoUserSubmissionsTitle', () => {
it('uses "by" instead of "from" for personhood', () => {
expect(formatNoUserSubmissionsTitle('pg')).toBe('No submissions found by "pg"');
@@ -272,137 +239,6 @@ describe('useUserInfiniteStories', () => {
});
});
- describe('username change', () => {
- it('discards stale state and re-fetches when username changes', async () => {
- vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
- const url = fetchInputToUrl(input);
- const isPg = url.includes('author_pg');
- return Promise.resolve(
- new Response(JSON.stringify(body(isPg ? [1, 2] : [10, 11]))),
- );
- });
-
- const { result, rerender } = renderHook(
- ({ username }: { username: string }) => useUserInfiniteStories(username),
- { initialProps: { username: 'pg' } },
- );
-
- await waitFor(() => expect(result.current.stories.map((s) => s.id)).toEqual([1, 2]));
-
- rerender({ username: 'dang' });
- await waitFor(() => expect(result.current.stories.map((s) => s.id)).toEqual([10, 11]));
- });
- });
-
- describe('username-change staleness', () => {
- it('discards stale response that resolves AFTER a rerender to a new username', async () => {
- // Scenario: user navigates to dang BEFORE pg's fetch() resolves. The
- // first version check (after `await fetch()`) must catch it.
- const deferredByUser = new Map>();
-
- vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
- const url = fetchInputToUrl(input);
- const author = authorFromUrl(url);
- const d = defer();
- deferredByUser.set(author, d);
- return d.promise;
- });
-
- const { result, rerender } = renderHook(
- ({ username }: { username: string }) => useUserInfiniteStories(username),
- { initialProps: { username: 'pg' } },
- );
-
- await waitFor(() => expect(deferredByUser.has('pg')).toBe(true));
-
- rerender({ username: 'dang' });
- await waitFor(() => expect(deferredByUser.has('dang')).toBe(true));
-
- await act(async () => {
- deferredByUser.get('pg')!.resolve(
- new Response(JSON.stringify(body([1, 2, 3]))),
- );
- deferredByUser.get('dang')!.resolve(
- new Response(JSON.stringify(body([100, 101]))),
- );
- });
-
- await waitFor(() => expect(result.current.loading).toBe(false));
- expect(result.current.stories.map((s) => s.id)).toEqual([100, 101]);
- });
-
- it('discards stale response whose json() resolves AFTER a rerender to a new username', async () => {
- // Scenario: pg's fetch() has resolved and passed the first version
- // check; we're inside `await response.json()` when the rerender happens.
- // This is the case the single pre-json check would miss; the second
- // check after json() (line 122 of useUserInfiniteStories.ts) catches it.
- // Without the second guard, pg's stale response would clobber dang's
- // committed stories AND poison `userStoriesCache.set(pg, ...)`.
- const fetchDeferred = new Map>();
- const jsonDeferred = new Map>();
-
- vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
- const url = fetchInputToUrl(input);
- const author = authorFromUrl(url);
- const fd = defer();
- const jd = defer();
- fetchDeferred.set(author, fd);
- jsonDeferred.set(author, jd);
- return fd.promise;
- });
-
- const { result, rerender } = renderHook(
- ({ username }: { username: string }) => useUserInfiniteStories(username),
- { initialProps: { username: 'pg' } },
- );
-
- await waitFor(() => expect(fetchDeferred.has('pg')).toBe(true));
-
- // pg's fetch resolves but json() is still pending.
- await act(async () => {
- fetchDeferred.get('pg')!.resolve(fakeResponse(jsonDeferred.get('pg')!));
- await Promise.resolve();
- await Promise.resolve();
- });
-
- // Rerender to dang while pg's json() is pending.
- rerender({ username: 'dang' });
- await waitFor(() => expect(fetchDeferred.has('dang')).toBe(true));
-
- // dang's fetch resolves cleanly (real Response, .json() resolves
- // synchronously after the fetch).
- await act(async () => {
- fetchDeferred.get('dang')!.resolve(
- new Response(JSON.stringify(body([100, 101]))),
- );
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- });
-
- // pg's stale json() finally resolves — the second version check must
- // discard it. Without it, pg's [1, 2, 3] would overwrite dang's
- // [100, 101] AND `userStoriesCache.set('pg', ...)` would poison the
- // cache with whatever pg's response was.
- await act(async () => {
- jsonDeferred.get('pg')!.resolve(body([1, 2, 3]));
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- });
-
- await waitFor(() => expect(result.current.loading).toBe(false));
-
- expect(result.current.stories.map((s) => s.id)).toEqual([100, 101]);
- // Cache for pg was never written; dang's entry is the only one present.
- expect(__getUserStoriesCacheForTests().has('pg')).toBe(false);
- expect(
- __getUserStoriesCacheForTests().get('dang')?.stories.map((s) => s.id),
- ).toEqual([100, 101]);
- });
- });
-
describe('reset', () => {
it('clears state, removes the cache entry, and triggers a fresh fetch', async () => {
vi.spyOn(globalThis, 'fetch')
diff --git a/src/hooks/useUserInfiniteStories.ts b/src/hooks/useUserInfiniteStories.ts
index cc539a8..c0dc24c 100644
--- a/src/hooks/useUserInfiniteStories.ts
+++ b/src/hooks/useUserInfiniteStories.ts
@@ -1,21 +1,10 @@
-import { useState, useCallback, useRef, useEffect, useLayoutEffect } from 'react';
-import { ALGOLIA_API } from '../config/api';
-import { normalizeAlgoliaHit } from '../api/hn';
-import { algoliaPageParams, nextAlgoliaPage, type AlgoliaPageCursor } from '../utils/algoliaPaging';
-import type { StoryItem, AlgoliaSearchResponse } from '../types';
+import {
+ useAlgoliaInfiniteStories,
+ type AlgoliaStoriesCache,
+ type AlgoliaStoriesSource,
+} from './useAlgoliaInfiniteStories';
-const HITS_PER_PAGE = 50;
-
-interface UserCacheEntry {
- stories: StoryItem[];
- page: number;
- before?: number;
- hasMore: boolean;
- seenIds: Set;
-}
-
-// Module-level in-memory cache (see useDomainInfiniteStories).
-const userStoriesCache = new Map();
+const userStoriesCache: AlgoliaStoriesCache = new Map();
/**
* @internal Testing helper to reset the module-level cache between tests.
@@ -34,136 +23,19 @@ export function formatNoUserSubmissionsTitle(username: string): string {
return `No submissions found by "${username}"`;
}
+const userSource: AlgoliaStoriesSource = {
+ cache: userStoriesCache,
+ // tags=(story,poll),author_X: stories or polls (an OR group) AND
+ // authored by X, as HN's /submitted lists both. search_by_date returns
+ // chronological newest-first, matching HN's /submitted ordering.
+ query: (username) => `tags=(story,poll),author_${encodeURIComponent(username)}`,
+};
+
/**
* Paginated user stories from Algolia (`author_X` tag, exact match).
* No local filter needed — every hit belongs to the user.
+ * Remount (React `key`) to change user.
*/
export function useUserInfiniteStories(username: string) {
- const initialCached = username ? userStoriesCache.get(username) : undefined;
-
- const [stories, setStories] = useState(initialCached?.stories ?? []);
- const [loading, setLoading] = useState(!initialCached && !!username);
- const [error, setError] = useState(null);
- const [hasMore, setHasMore] = useState(initialCached?.hasMore ?? true);
- const [prevUsername, setPrevUsername] = useState(username);
-
- const nextPageRef = useRef({ page: initialCached?.page ?? 0, before: initialCached?.before });
- const seenIdsRef = useRef>(new Set(initialCached?.seenIds ?? []));
- const versionRef = useRef(0);
- const inFlightRef = useRef(false);
- // Mirrors committed stories (keeps cache write out of setStories updater).
- const storiesRef = useRef(initialCached?.stories ?? []);
-
- // Prop-derived state: reset when `username` changes without waiting for
- // an effect. https://react.dev/reference/react/useState#storing-information-from-previous-renders
- if (prevUsername !== username) {
- setPrevUsername(username);
- const newCached = username ? userStoriesCache.get(username) : undefined;
- const newStories = newCached?.stories ?? [];
- setStories(newStories);
- setLoading(!newCached && !!username);
- setError(null);
- setHasMore(newCached?.hasMore ?? true);
- }
-
- // Reset refs when `username` changes. useLayoutEffect runs synchronously
- // after commit, before any microtask — ensures versionRef is bumped
- // before a stale in-flight fetch can check it.
- useLayoutEffect(() => {
- const cached = username ? userStoriesCache.get(username) : undefined;
- nextPageRef.current = { page: cached?.page ?? 0, before: cached?.before };
- seenIdsRef.current = new Set(cached?.seenIds ?? []);
- storiesRef.current = cached?.stories ?? [];
- versionRef.current += 1;
- inFlightRef.current = false;
- }, [username]);
-
- const loadMore = useCallback(async () => {
- if (!username || !hasMore || inFlightRef.current) return;
- inFlightRef.current = true;
-
- setLoading(true);
- setError(null);
-
- const currentVersion = versionRef.current;
-
- try {
- const pageToFetch = nextPageRef.current;
- // tags=(story,poll),author_X: stories or polls (an OR group) AND
- // authored by X, as HN's /submitted lists both. search_by_date returns
- // chronological newest-first, matching HN's /submitted ordering.
- const url = `${ALGOLIA_API}/search_by_date?tags=(story,poll),author_${encodeURIComponent(username)}&hitsPerPage=${HITS_PER_PAGE}${algoliaPageParams(pageToFetch)}`;
- const response = await fetch(url);
-
- if (!response.ok) {
- throw new Error(`Failed to fetch stories: ${response.status}`);
- }
-
- if (versionRef.current !== currentVersion) return;
-
- const data = (await response.json()) as AlgoliaSearchResponse;
-
- // Second staleness check (see useDomainInfiniteStories).
- if (versionRef.current !== currentVersion) return;
-
- const userStories: StoryItem[] = data.hits.map(normalizeAlgoliaHit);
-
- // Dedup across pages (Algolia can return overlaps on paginated search_by_date)
- const uniqueStories = userStories.filter((s) => {
- if (seenIdsRef.current.has(s.id)) return false;
- seenIdsRef.current.add(s.id);
- return true;
- });
-
- const nextPage = nextAlgoliaPage(data, HITS_PER_PAGE, pageToFetch);
- nextPageRef.current = nextPage ?? { ...pageToFetch, page: data.page + 1 };
-
- const newHasMore = nextPage !== null;
- setHasMore(newHasMore);
-
- // Compute outside updater to keep setStories pure (StrictMode-safe).
- const updated = [...storiesRef.current, ...uniqueStories];
- storiesRef.current = updated;
- userStoriesCache.set(username, {
- stories: updated,
- ...nextPageRef.current,
- hasMore: newHasMore,
- seenIds: new Set(seenIdsRef.current),
- });
- setStories(updated);
- } catch (err) {
- if (versionRef.current !== currentVersion) return;
- setError(err instanceof Error ? err.message : String(err));
- throw err;
- } finally {
- if (versionRef.current === currentVersion) {
- inFlightRef.current = false;
- setLoading(false);
- }
- }
- }, [username, hasMore]);
-
- // Kick off the first fetch when we have no stories for this user.
- // No cleanup/abort — version counter handles stale responses.
- useEffect(() => {
- if (!username) return;
- if (stories.length === 0 && !inFlightRef.current) {
- void loadMore().catch(() => { /* error state set internally */ });
- }
- }, [username, stories.length, loadMore]);
-
- const reset = useCallback(() => {
- versionRef.current += 1;
- inFlightRef.current = false;
- setStories([]);
- setLoading(!!username);
- setError(null);
- setHasMore(true);
- nextPageRef.current = { page: 0 };
- seenIdsRef.current = new Set();
- storiesRef.current = [];
- if (username) userStoriesCache.delete(username);
- }, [username]);
-
- return { stories, loading, error, hasMore, loadMore, reset } as const;
+ return useAlgoliaInfiniteStories(username, userSource);
}
diff --git a/src/hooks/useUserProfile.test.ts b/src/hooks/useUserProfile.test.ts
index a7f6faf..f16ec1c 100644
--- a/src/hooks/useUserProfile.test.ts
+++ b/src/hooks/useUserProfile.test.ts
@@ -119,61 +119,6 @@ describe('useUserProfile', () => {
});
});
- describe('username change', () => {
- it('discards stale state when username changes between renders', async () => {
- vi.spyOn(hnSdk, 'readUser').mockImplementation(async (username) => {
- const id = username;
- return profileBody({ id, karma: id === 'pg' ? 1 : 2 });
- });
-
- const { result, rerender } = renderHook(
- ({ username }: { username: string }) => useUserProfile(username),
- { initialProps: { username: 'pg' } },
- );
-
- await waitFor(() => expect(result.current.profile?.id).toBe('pg'));
-
- rerender({ username: 'dang' });
- await waitFor(() => expect(result.current.profile?.id).toBe('dang'));
- expect(result.current.profile?.karma).toBe(2);
- });
-
- it('does not commit a stale in-flight response when username changes mid-fetch', async () => {
- let resolvePg!: (value: UserProfile | null) => void;
- const pgPromise = new Promise((resolve) => {
- resolvePg = resolve;
- });
-
- vi.spyOn(hnSdk, 'readUser').mockImplementation(async (username) => {
- if (username === 'pg') return pgPromise;
- return profileBody({ id: 'dang', karma: 999 });
- });
-
- const { result, rerender } = renderHook(
- ({ username }: { username: string }) => useUserProfile(username),
- { initialProps: { username: 'pg' } },
- );
-
- expect(result.current.loading).toBe(true);
-
- rerender({ username: 'dang' });
-
- await waitFor(() => expect(result.current.profile?.id).toBe('dang'));
- expect(result.current.profile?.karma).toBe(999);
-
- await act(async () => {
- resolvePg(profileBody({ id: 'pg', karma: 1 }));
- await Promise.resolve();
- await Promise.resolve();
- });
-
- expect(result.current.profile?.id).toBe('dang');
- expect(result.current.profile?.karma).toBe(999);
- expect(__getUserProfileCacheForTests().get('pg')).toBeUndefined();
- expect(__getUserProfileCacheForTests().get('dang')?.karma).toBe(999);
- });
- });
-
describe('refresh', () => {
it('clears the cache entry and re-fetches', async () => {
const spy = vi.spyOn(hnSdk, 'readUser')
diff --git a/src/hooks/useUserProfile.ts b/src/hooks/useUserProfile.ts
index 47f777e..3f092c7 100644
--- a/src/hooks/useUserProfile.ts
+++ b/src/hooks/useUserProfile.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { hnSdk } from '../api/hnSdk';
import { NotFoundError } from '../api/hn';
import type { UserProfile } from '../types';
@@ -30,6 +30,7 @@ interface UseUserProfileResult {
/**
* Firebase user profile fetch with cache and not-found handling.
* Case-sensitive — caller must preserve case from the route param.
+ * Remount (React `key`) to change user.
*/
export function useUserProfile(username: string): UseUserProfileResult {
const cached = username ? userProfileCache.get(username) : undefined;
@@ -38,29 +39,10 @@ export function useUserProfile(username: string): UseUserProfileResult {
const [loading, setLoading] = useState(!cached && !!username);
const [error, setError] = useState(null);
const [isNotFound, setIsNotFound] = useState(false);
- const [prevUsername, setPrevUsername] = useState(username);
+ // Bumped by `refresh` so the response it replaces is dropped.
const versionRef = useRef(0);
- // Prop-derived state: reset when username changes without waiting for an
- // effect. Mirrors `useDomainInfiniteStories`' pattern.
- // https://react.dev/reference/react/useState#storing-information-from-previous-renders
- if (prevUsername !== username) {
- setPrevUsername(username);
- const newCached = username ? userProfileCache.get(username) : undefined;
- setProfile(newCached ?? null);
- setLoading(!newCached && !!username);
- setError(null);
- setIsNotFound(false);
- }
-
- // Bump version when username changes so in-flight fetches for the old user
- // are discarded. useLayoutEffect (not useEffect) so the bump happens
- // synchronously after commit, before any stale fetch microtask can fire.
- useLayoutEffect(() => {
- versionRef.current += 1;
- }, [username]);
-
const load = useCallback(async () => {
if (!username) return;
const currentVersion = versionRef.current;
From 786e043f9bacdabaca551d3c95907bad5f2f664f Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Fri, 27 Nov 2026 01:39:53 +0200
Subject: [PATCH 3/7] refactor: share error helpers and dedupe viewer and
thread handling
---
src/api/hn.ts | 3 +-
src/components/SwipeStoryViewer.tsx | 124 +++++++++++--------------
src/hooks/useAlgoliaInfiniteStories.ts | 3 +-
src/hooks/useCommentDetail.ts | 5 +-
src/hooks/useInfiniteStories.ts | 3 +-
src/hooks/useItemWithComments.ts | 80 ++++++++--------
src/hooks/useSiblingComments.ts | 5 +-
src/hooks/useUserProfile.ts | 3 +-
src/utils/errors.ts | 10 ++
src/utils/share.ts | 3 +-
10 files changed, 118 insertions(+), 121 deletions(-)
create mode 100644 src/utils/errors.ts
diff --git a/src/api/hn.ts b/src/api/hn.ts
index 2748a16..653c701 100644
--- a/src/api/hn.ts
+++ b/src/api/hn.ts
@@ -1,5 +1,6 @@
import { ALGOLIA_API } from '../config/api';
import { hnSdk } from './hnSdk';
+import { errorMessage } from '../utils/errors';
import type { Item, StoryItem, Comment, AlgoliaHit, AlgoliaComment, AlgoliaSearchResponse, FirebaseItem, PrefetchResult, AlgoliaItemResponse, AlgoliaItemChild, PollOption, PollOptionItem } from '../types';
export class NotFoundError extends Error {
@@ -585,7 +586,7 @@ async function fetchThread(
if (!raw) throw err;
const item = threadItem(raw, await pollOptionsRead);
signal?.throwIfAborted();
- throw new CommentsError(err instanceof Error ? err.message : String(err), item);
+ throw new CommentsError(errorMessage(err), item);
});
const [raw, comments] = await Promise.all([itemRead, commentsRead]);
diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx
index f4d2663..430f5ee 100644
--- a/src/components/SwipeStoryViewer.tsx
+++ b/src/components/SwipeStoryViewer.tsx
@@ -1,4 +1,4 @@
-import { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback } from 'react';
+import { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback, type ComponentProps } from 'react';
import { useNavigate, useLocation } from 'react-router';
import { useInfiniteStories } from '../hooks/useInfiniteStories';
import { useSwipeScroll } from '../hooks/useSwipeScroll';
@@ -15,8 +15,33 @@ import { useViewDwell } from '../hooks/useViewDwell';
import { FEED_TYPE_TITLES } from '../config/feedTypes';
import { FullScreenItem, FullScreenItemSkeletonPanel } from './FullScreenItem';
import { StateView } from './StateView';
+import { errorMessage } from '../utils/errors';
import type { StoryItem, FeedType, LocationState } from '../types';
+// History navigation carries the state we wrote (`from` for feeds,
+// `fromDomain` for domain swipe, `fromUser` for user submissions).
+function namesViewer(state: LocationState | null | undefined): boolean {
+ return !!(state?.from ?? state?.fromDomain ?? state?.fromUser);
+}
+
+function SwipeSkeleton() {
+ return (
+
+ );
+}
+
+function SwipeStateView(props: Omit, 'className'>) {
+ return (
+
+
+
+ );
+}
+
interface SwipeStoryViewerCoreProps {
/** Story data from the consumer's data source (feed, domain, etc.) */
stories: StoryItem[];
@@ -91,8 +116,7 @@ export function SwipeStoryViewerCore({
const [anchorStoryId, setAnchorStoryId] = useState(() => {
// A matching snapshot counts as history nav: on a stateless reload `locationState`
// is null, so `isRestoringPosition` is what suppresses the index-0 anchor.
- const isHistoryNav = isRestoringPosition ||
- !!(locationState?.from ?? locationState?.fromDomain ?? locationState?.fromUser);
+ const isHistoryNav = isRestoringPosition || namesViewer(locationState);
return isHistoryNav ? null : initialItemIdNum ?? null;
});
const lastInitialStoryIdRef = useRef(initialItemId);
@@ -290,7 +314,7 @@ export function SwipeStoryViewerCore({
// Only update state if this is still the story we want
if (initialItemIdNum === fetchedStoryIdRef.current) {
setInjectedLoading(false);
- setInjectedError(err instanceof Error ? err.message : 'Story not found');
+ setInjectedError(errorMessage(err, 'Story not found'));
setIsInjectedItemNotFound(err instanceof NotFoundError);
}
});
@@ -383,31 +407,26 @@ export function SwipeStoryViewerCore({
savedScrollYOnHideRef.current = window.scrollY;
persistSnapshot();
};
+
+ const restoreSavedPosition = () => {
+ const targetIndex = savedIndexOnHideRef.current;
+ if (targetIndex === null) return;
+ savedIndexOnHideRef.current = null;
+ scrollToIndex(targetIndex);
+ // Restore scrollY after panel activation
+ window.scrollTo(0, savedScrollYOnHideRef.current);
+ };
// Restore position when page is shown from bfcache (persisted=true)
// This fires BEFORE first paint, preventing flash of wrong item
const handlePageShow = (event: PageTransitionEvent) => {
- if (event.persisted && savedIndexOnHideRef.current !== null) {
- const targetIndex = savedIndexOnHideRef.current;
- savedIndexOnHideRef.current = null;
- scrollToIndex(targetIndex);
- // Restore scrollY after panel activation
- window.scrollTo(0, savedScrollYOnHideRef.current);
- }
+ if (event.persisted) restoreSavedPosition();
};
// Fallback: visibilitychange for non-bfcache cases (tab switches, etc)
const handleVisibilityChange = () => {
- if (document.visibilityState === 'hidden') {
- savedIndexOnHideRef.current = currentIndexRef.current;
- savedScrollYOnHideRef.current = window.scrollY;
- persistSnapshot();
- } else if (document.visibilityState === 'visible' && savedIndexOnHideRef.current !== null) {
- const targetIndex = savedIndexOnHideRef.current;
- savedIndexOnHideRef.current = null;
- scrollToIndex(targetIndex);
- window.scrollTo(0, savedScrollYOnHideRef.current);
- }
+ if (document.visibilityState === 'hidden') handlePageHide();
+ else if (document.visibilityState === 'visible') restoreSavedPosition();
};
window.addEventListener('pagehide', handlePageHide);
@@ -443,10 +462,8 @@ export function SwipeStoryViewerCore({
lastInitialStoryIdRef.current = initialItemId;
if (initialItemId) {
- // History navigation carries our previously-written state (`from` for feeds,
- // `fromDomain` for domain swipe, `fromUser` for user submissions) — any
- // of those signals "don't reorder, return to the same position".
- const isHistoryNavigation = !!(locationState?.from ?? locationState?.fromDomain ?? locationState?.fromUser);
+ // History navigation: don't reorder, return to the same position.
+ const isHistoryNavigation = namesViewer(locationState);
if (isHistoryNavigation) {
// History navigation (browser back/forward, return from external)
@@ -583,15 +600,12 @@ export function SwipeStoryViewerCore({
if (injectedError) {
return (
-
- void navigate(0) }}
- className="swipe-state-center"
- />
-
+ void navigate(0) }}
+ />
);
}
@@ -606,42 +620,18 @@ export function SwipeStoryViewerCore({
// If anchor story isn't resolved yet (not in feed, not injected), show loading skeleton
// This ensures we wait for fetchItemOnly to complete before deciding what to show
if (!anchorInFeed && !anchorIsInjected) {
- return (
-
- );
+ return ;
}
}
- // Initial loading state (also show when fetching injected story)
- if (mergedStories.length === 0 && (loading || injectedLoading)) {
- return (
-
- );
- }
-
- if (error && mergedStories.length === 0 && !isRetrying) {
- return (
-
- { resetRetry(); void loadMore().catch(() => { /* error state set internally */ }); } }} className="swipe-state-center" />
-
- );
+ // Initial loading state (also while fetching the injected story or auto-retrying)
+ if (mergedStories.length === 0 && (loading || injectedLoading || (error && isRetrying))) {
+ return ;
}
- if (error && mergedStories.length === 0 && isRetrying) {
+ if (error && mergedStories.length === 0) {
return (
-
+ { resetRetry(); void loadMore().catch(() => { /* error state set internally */ }); } }} />
);
}
@@ -658,11 +648,7 @@ export function SwipeStoryViewerCore({
!injectedError &&
!initialItemId
) {
- return (
-
-
-
- );
+ return ;
}
// Virtualization: render heavy content (FullScreenItem ≈ 100+ DOM nodes) only for
diff --git a/src/hooks/useAlgoliaInfiniteStories.ts b/src/hooks/useAlgoliaInfiniteStories.ts
index 6e76721..54fbb3c 100644
--- a/src/hooks/useAlgoliaInfiniteStories.ts
+++ b/src/hooks/useAlgoliaInfiniteStories.ts
@@ -2,6 +2,7 @@ import { useState, useCallback, useRef, useEffect } from 'react';
import { ALGOLIA_API } from '../config/api';
import { normalizeAlgoliaHit } from '../api/hn';
import { algoliaPageParams, nextAlgoliaPage, type AlgoliaPageCursor } from '../utils/algoliaPaging';
+import { errorMessage } from '../utils/errors';
import type { StoryItem, AlgoliaHit, AlgoliaSearchResponse } from '../types';
const HITS_PER_PAGE = 50;
@@ -135,7 +136,7 @@ export function useAlgoliaInfiniteStories(key: string, source: AlgoliaStoriesSou
setStories(updated);
} catch (err) {
if (versionRef.current !== currentVersion) return;
- setError(err instanceof Error ? err.message : String(err));
+ setError(errorMessage(err));
throw err;
} finally {
// Only clear flags if this fetch is still the current version. After a
diff --git a/src/hooks/useCommentDetail.ts b/src/hooks/useCommentDetail.ts
index 7aa7cca..aec6f9f 100644
--- a/src/hooks/useCommentDetail.ts
+++ b/src/hooks/useCommentDetail.ts
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { fetchCommentItem, fetchCommentReplies, fetchFirebaseItem, normalizeAlgoliaItemChildren } from '../api/hn';
+import { errorMessage, isAbortError } from '../utils/errors';
import type { Comment } from '../types';
function countComments(comments: Comment[]): number {
@@ -140,8 +141,8 @@ export function useCommentDetail(
}
}
} catch (err) {
- if (signal.aborted || (err instanceof Error && err.name === 'AbortError')) return;
- setError(err instanceof Error ? err.message : String(err));
+ if (signal.aborted || isAbortError(err)) return;
+ setError(errorMessage(err));
setLoading(false);
throw err;
}
diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts
index 11ff916..5423284 100644
--- a/src/hooks/useInfiniteStories.ts
+++ b/src/hooks/useInfiniteStories.ts
@@ -9,6 +9,7 @@ import { useState, useCallback, useRef, useLayoutEffect } from 'react';
import { fetchTopStories, fetchFrontPageForDay, fetchBestStories, fetchNewStories, fetchShowStories, fetchAskStories, fetchAskStoriesForDay, fetchShowStoriesForDay } from '../api/hn';
import { getCachedFeed, setCachedFeed } from '../utils/feedCache';
import { getListSessionState, saveListSessionState, clearListSessionState } from '../utils/itemCache';
+import { errorMessage } from '../utils/errors';
import type { StoryItem, FeedType, ListSessionState } from '../types';
interface InitialState {
@@ -320,7 +321,7 @@ export function useInfiniteStories(type: FeedType = 'top') {
} catch (err) {
// Stale-response guard: only surface errors from the current request.
if (versionRef.current === currentVersion) {
- setError(err instanceof Error ? err.message : String(err));
+ setError(errorMessage(err));
throw err;
}
} finally {
diff --git a/src/hooks/useItemWithComments.ts b/src/hooks/useItemWithComments.ts
index 855321d..36fe98d 100644
--- a/src/hooks/useItemWithComments.ts
+++ b/src/hooks/useItemWithComments.ts
@@ -3,6 +3,7 @@ import { fetchItemAndComments, fetchItemOnly, fetchItemWithComments, isPollOptio
import { getCachedItem, setCachedItem } from '../utils/itemCache';
import { registerPriorityFetch, unregisterPriorityFetch } from '../utils/fetchPriority';
import { useNetworkStatus } from './useNetworkStatus';
+import { errorMessage, isAbortError } from '../utils/errors';
import type { Item, Comment, StoryItem, PrefetchResult } from '../types';
interface UseItemWithCommentsOptions {
@@ -90,6 +91,22 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
const [isNotFound, setIsNotFound] = useState(false);
const [commentsError, setCommentsError] = useState(null);
+ // A comments fetch reads the item too. `base` is the caller's copy of the
+ // item, cached with the thread. Callers settle `commentsLoading` themselves.
+ const applyThread = useCallback((base: Item | null, { item: fetchedItem, comments: commentsData }: PrefetchResult) => {
+ setItem(current => withFetchedFields(current, fetchedItem));
+ setComments(commentsData);
+ setCommentsError(null);
+ const fullItem = withFetchedFields(base, fetchedItem);
+ if (fullItem) setCachedItem(itemId, fullItem, commentsData);
+ }, [itemId]);
+
+ // A failed comments fetch: the item stays usable, with the error surfaced.
+ const applyThreadError = useCallback((err: unknown) => {
+ setItem(current => withFailedFetchFields(current, err));
+ setCommentsError(errorMessage(err, 'Failed to load comments'));
+ }, []);
+
// Ref to the main effect's AbortController so the reconnect handler can abort stale fetches
const controllerRef = useRef(null);
// Releases the main effect's priority registration. The reconnect handler
@@ -198,8 +215,8 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
}
return itemData;
} catch (err) {
- if (!controller.signal.aborted && !(err instanceof Error && err.name === 'AbortError')) {
- setError(err instanceof Error ? err.message : String(err));
+ if (!controller.signal.aborted && !isAbortError(err)) {
+ setError(errorMessage(err));
setIsNotFound(err instanceof NotFoundError);
setItemLoading(false);
setCommentsLoading(false);
@@ -219,28 +236,20 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
}
try {
- const { item: fetchedItem, comments: commentsData } = await (commentsRead ?? fetchItemWithComments(itemId, controller.signal));
+ const thread = await (commentsRead ?? fetchItemWithComments(itemId, controller.signal));
if (!controller.signal.aborted) {
- setItem(current => withFetchedFields(current, fetchedItem));
- setComments(commentsData);
+ applyThread(itemData, thread);
setCommentsLoading(false);
- setCommentsError(null);
-
- const fullItem = withFetchedFields(itemData, fetchedItem);
- if (fullItem) {
- setCachedItem(itemId, fullItem, commentsData);
- }
// Unregister priority so section prefetch and other lower-priority
// fetches can proceed.
releasePriority();
}
} catch (err) {
- if (!controller.signal.aborted && !(err instanceof Error && err.name === 'AbortError')) {
+ if (!controller.signal.aborted && !isAbortError(err)) {
// Comments failed but item succeeded — still usable, but surface the error.
- setItem(current => withFailedFetchFields(current, err));
+ applyThreadError(err);
setCommentsLoading(false);
- setCommentsError(err instanceof Error ? err.message : 'Failed to load comments');
console.warn('Failed to load comments:', err);
// Unregister priority even on failure so prefetchers aren't blocked forever
@@ -280,7 +289,8 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
controllerRef.current = null;
releasePriority();
};
- }, [itemId, deferComments]); // All other values read via Effect Events
+ // The apply helpers change only with itemId; all other values are read via Effect Events.
+ }, [itemId, deferComments, applyThread, applyThreadError]);
// Reconnect: when going online with a stale comment fetch hanging, abort it and retry.
// The main effect's fetch may be pending indefinitely (TCP doesn't fail instantly on
@@ -318,20 +328,15 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
setCommentsLoading(true);
void fetchItemWithComments(itemId, controller.signal)
- .then(({ item: fetchedItem, comments: commentsData }) => {
+ .then(thread => {
if (controller.signal.aborted) return;
- setItem(current => withFetchedFields(current, fetchedItem));
- setComments(commentsData);
+ applyThread(item, thread);
setCommentsLoading(false);
- setCommentsError(null);
- const fullItem = withFetchedFields(item, fetchedItem);
- if (fullItem) setCachedItem(itemId, fullItem, commentsData);
})
.catch(err => {
- if (controller.signal.aborted || (err instanceof Error && err.name === 'AbortError')) return;
- setItem(current => withFailedFetchFields(current, err));
+ if (controller.signal.aborted || isAbortError(err)) return;
+ applyThreadError(err);
setCommentsLoading(false);
- setCommentsError(err instanceof Error ? err.message : 'Failed to load comments');
})
.finally(() => releasePriority?.());
@@ -339,7 +344,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
controller.abort();
if (controllerRef.current === controller) controllerRef.current = null;
};
- }, [isOnline, itemId]);
+ }, [isOnline, itemId, applyThread, applyThreadError]);
// Combined loading state for backward compatibility
const loading = itemLoading && commentsLoading;
@@ -358,7 +363,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
itemData = await fetchItemOnly(itemId);
setItem(itemData);
} catch (err) {
- setError(err instanceof Error ? err.message : String(err));
+ setError(errorMessage(err));
setIsNotFound(err instanceof NotFoundError);
setItemLoading(false);
setCommentsLoading(false);
@@ -369,19 +374,14 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
if (fetchesComments(itemData)) {
try {
// Its read of the item carries a poll's options, which fetchItemOnly's doesn't.
- const { item: fetchedItem, comments: commentsData } = await fetchItemWithComments(itemId);
- const fullItem = withFetchedFields(itemData, fetchedItem) ?? itemData;
- setItem(fullItem);
- setComments(commentsData);
- setCachedItem(itemId, fullItem, commentsData);
+ applyThread(itemData, await fetchItemWithComments(itemId));
} catch (err) {
// The item loaded, so the page can show it with the comments error.
- setItem(withFailedFetchFields(itemData, err) ?? itemData);
- setCommentsError(err instanceof Error ? err.message : 'Failed to load comments');
+ applyThreadError(err);
}
}
setCommentsLoading(false);
- }, [itemId]);
+ }, [itemId, applyThread, applyThreadError]);
// Behind the comments section's retry. `commentsError` stays set until the
// fetch settles: the section shows its skeleton for it, and clearing it
@@ -389,18 +389,12 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
// useAutoRetry counts the attempt.
const retryComments = useCallback(async () => {
try {
- const { item: fetchedItem, comments: commentsData } = await fetchItemWithComments(itemId);
- setItem(current => withFetchedFields(current, fetchedItem));
- setComments(commentsData);
- setCommentsError(null);
- const fullItem = withFetchedFields(item, fetchedItem);
- if (fullItem) setCachedItem(itemId, fullItem, commentsData);
+ applyThread(item, await fetchItemWithComments(itemId));
} catch (err) {
- setItem(current => withFailedFetchFields(current, err));
- setCommentsError(err instanceof Error ? err.message : 'Failed to load comments');
+ applyThreadError(err);
throw err;
}
- }, [itemId, item]);
+ }, [itemId, item, applyThread, applyThreadError]);
return {
item,
diff --git a/src/hooks/useSiblingComments.ts b/src/hooks/useSiblingComments.ts
index 1ac198e..158558e 100644
--- a/src/hooks/useSiblingComments.ts
+++ b/src/hooks/useSiblingComments.ts
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { fetchFirebaseItem, fetchHiddenCommentIds } from '../api/hn';
+import { errorMessage, isAbortError } from '../utils/errors';
const NO_IDS: ReadonlySet = new Set();
@@ -70,8 +71,8 @@ export function useSiblingComments(commentId: number | string): UseSiblingCommen
);
}
} catch (err) {
- if (signal.aborted || (err instanceof Error && err.name === 'AbortError')) return;
- setError(err instanceof Error ? err.message : String(err));
+ if (signal.aborted || isAbortError(err)) return;
+ setError(errorMessage(err));
setLoading(false);
throw err;
}
diff --git a/src/hooks/useUserProfile.ts b/src/hooks/useUserProfile.ts
index 3f092c7..1514262 100644
--- a/src/hooks/useUserProfile.ts
+++ b/src/hooks/useUserProfile.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { hnSdk } from '../api/hnSdk';
import { NotFoundError } from '../api/hn';
+import { errorMessage } from '../utils/errors';
import type { UserProfile } from '../types';
// Module-level profile cache (session-lifetime, not persisted).
@@ -64,7 +65,7 @@ export function useUserProfile(username: string): UseUserProfileResult {
setIsNotFound(true);
setError(err.message);
} else {
- setError(err instanceof Error ? err.message : String(err));
+ setError(errorMessage(err));
}
} finally {
if (versionRef.current === currentVersion) {
diff --git a/src/utils/errors.ts b/src/utils/errors.ts
new file mode 100644
index 0000000..851f29a
--- /dev/null
+++ b/src/utils/errors.ts
@@ -0,0 +1,10 @@
+/** The message to show for a caught value; `fallback` when it isn't an Error. */
+export function errorMessage(err: unknown, fallback?: string): string {
+ if (err instanceof Error) return err.message;
+ return fallback ?? String(err);
+}
+
+/** True for the rejection of an aborted fetch (or a dismissed share sheet). */
+export function isAbortError(err: unknown): boolean {
+ return err instanceof Error && err.name === 'AbortError';
+}
diff --git a/src/utils/share.ts b/src/utils/share.ts
index 148dda0..acc9615 100644
--- a/src/utils/share.ts
+++ b/src/utils/share.ts
@@ -1,3 +1,4 @@
+import { isAbortError } from './errors';
/**
* Sharing an item, with a clipboard path for the browsers that have no share
* sheet. Kept out of the component so the capability matrix — which is most of
@@ -51,7 +52,7 @@ export async function shareOrCopy(data: { title: string; url: string }): Promise
} catch (error) {
// Dismissal arrives as an exception, so it has to be told apart from a
// real fault before anything is treated as one.
- if (error instanceof Error && error.name === 'AbortError') return 'dismissed';
+ if (isAbortError(error)) return 'dismissed';
// Anything else (no activation, an earlier share still pending, an
// OS-level refusal) still leaves the reader wanting the URL, so fall
// through rather than dead-ending.
From 49224f3c9076136d49b2c2bcf57de41d2578baf8 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Fri, 27 Nov 2026 12:05:47 +0200
Subject: [PATCH 4/7] refactor: drop redundant resetKey and merge duplicate
skeleton and day search
- Remove InfiniteStoryListPage's resetKey and the reset branch in
useStaggerCascadeSlots. The list pages are keyed by feed, domain and
user, each equal to the resetKey they passed, so a new context
remounts the list and the reset could no longer run.
- Replace CommentDetailSkeleton and FullScreenCommentSkeleton, which
differed only in their bottom margin, with one CommentArticleSkeleton
that takes CommentArticle's articleClassName.
- Merge fetchFrontPageForDay and fetchTaggedStoriesForDay into one
Algolia day search. excludeTitles only ever got the hiring titles, so
it becomes excludeHiring and uses isHiringThread.
---
src/api/hn.fetchTaggedStories.test.ts | 9 +--
src/api/hn.ts | 80 ++++++++-----------
src/components/CommentDetail.tsx | 27 +------
src/components/CommentSkeleton.tsx | 24 ++++++
src/components/FullScreenComment.tsx | 28 +------
src/components/InfiniteStoryListPage.test.tsx | 3 -
src/components/InfiniteStoryListPage.tsx | 8 +-
src/hooks/useStaggerCascadeSlots.test.ts | 53 ------------
src/hooks/useStaggerCascadeSlots.ts | 19 +----
src/pages/DomainStories.tsx | 1 -
src/pages/StoryList.tsx | 1 -
src/pages/UserSubmissions.tsx | 1 -
12 files changed, 70 insertions(+), 184 deletions(-)
diff --git a/src/api/hn.fetchTaggedStories.test.ts b/src/api/hn.fetchTaggedStories.test.ts
index 8badab8..de3ea96 100644
--- a/src/api/hn.fetchTaggedStories.test.ts
+++ b/src/api/hn.fetchTaggedStories.test.ts
@@ -67,7 +67,7 @@ describe('fetchTaggedStoriesForDay', () => {
expect(result[2].points).toBe(10);
});
- it('filters titles when excludeTitles is provided', async () => {
+ it('filters hiring threads with excludeHiring', async () => {
const hits = [
makeHit(1, 'Ask HN: Who is hiring? (May 2026)', 300, ['ask_hn']),
makeHit(2, 'Ask HN: Real question', 100, ['ask_hn']),
@@ -78,16 +78,13 @@ describe('fetchTaggedStoriesForDay', () => {
json: async () => mockAlgoliaResponse(hits),
});
- const result = await fetchTaggedStoriesForDay('ask_hn', 1, [
- 'who is hiring',
- 'who wants to be hired',
- ]);
+ const result = await fetchTaggedStoriesForDay('ask_hn', 1, true);
expect(result).toHaveLength(1);
expect(result[0].title).toBe('Ask HN: Real question');
});
- it('does not filter when excludeTitles is empty', async () => {
+ it('does not filter without excludeHiring', async () => {
const hits = [
makeHit(1, 'Show HN: Something', 100, ['show_hn']),
makeHit(2, 'Show HN: Who is hiring helper', 50, ['show_hn']),
diff --git a/src/api/hn.ts b/src/api/hn.ts
index 653c701..04d72e4 100644
--- a/src/api/hn.ts
+++ b/src/api/hn.ts
@@ -128,32 +128,38 @@ export async function fetchTopStories(limit = 20): Promise {
return stories;
}
-// Algolia's front_page tag only shows the CURRENT front page, not historical.
-// So we fetch stories created on `daysAgo` sorted by points (best approximation).
-export async function fetchFrontPageForDay(daysAgo = 1): Promise {
+/**
+ * One day of stories from Algolia matching `tags`, most points first. Used
+ * where the Firebase ranked lists run out.
+ */
+async function fetchAlgoliaDay(
+ tags: string,
+ daysAgo: number,
+ label: string,
+ keep: (hit: AlgoliaHit) => boolean = () => true,
+): Promise {
const { start, end } = getDayRange(daysAgo);
-
- // story,poll is an OR group: polls are tagged `poll`, not `story`. It still
- // leaves out jobs and comments; relevance sort factors in points.
- const url = `${ALGOLIA_API}/search?tags=(story,poll)&numericFilters=created_at_i>=${start},created_at_i<${end}&hitsPerPage=30`;
-
+ const url = `${ALGOLIA_API}/search?tags=${tags}&numericFilters=created_at_i>=${start},created_at_i<${end}&hitsPerPage=30`;
+
const response = await fetch(url);
if (!response.ok) {
- throw new Error(`Failed to fetch front page stories: ${response.status}`);
+ throw new Error(`Failed to fetch ${label} stories: ${response.status}`);
}
-
+
const data = await response.json() as AlgoliaSearchResponse;
-
- const filtered = data.hits.filter((hit) => {
- if (hit.type === 'job' || hit._tags?.includes('job')) {
- return false;
- }
- return !isHiringThread(hit.title);
- });
-
- const sorted = filtered.sort((a, b) => (b.points || 0) - (a.points || 0));
-
- return sorted.map(normalizeAlgoliaHit);
+ return data.hits
+ .filter(keep)
+ .sort((a, b) => (b.points || 0) - (a.points || 0))
+ .map(normalizeAlgoliaHit);
+}
+
+// Algolia's front_page tag only shows the CURRENT front page, not historical.
+// So we fetch stories created on `daysAgo` sorted by points (best approximation).
+// story,poll is an OR group: polls are tagged `poll`, not `story`. It still
+// leaves out jobs and comments; relevance sort factors in points.
+export function fetchFrontPageForDay(daysAgo = 1): Promise {
+ return fetchAlgoliaDay('(story,poll)', daysAgo, 'front page', hit =>
+ hit.type !== 'job' && !hit._tags?.includes('job') && !isHiringThread(hit.title));
}
export function fetchBestStories(offset = 0, limit = 30) {
@@ -250,35 +256,13 @@ export function fetchAskStories(offset = 0) {
return fetchRankedStories('askstories', offset, { limit: 20, type: 'ask', excludeHiring: true });
}
-/**
- * Fetch stories for a specific day from Algolia, filtered by tag.
- * Used for historical fallback when Firebase ranked lists are exhausted.
- */
-export async function fetchTaggedStoriesForDay(
+/** One day of Ask HN or Show HN stories from Algolia. */
+export function fetchTaggedStoriesForDay(
tag: 'ask_hn' | 'show_hn',
daysAgo: number,
- excludeTitles?: string[],
+ excludeHiring = false,
): Promise {
- const { start, end } = getDayRange(daysAgo);
- const url = `${ALGOLIA_API}/search?tags=story,${tag}&numericFilters=created_at_i>=${start},created_at_i<${end}&hitsPerPage=30`;
-
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Failed to fetch ${tag} stories: ${response.status}`);
- }
-
- const data = await response.json() as AlgoliaSearchResponse;
-
- let hits = data.hits;
- if (excludeTitles && excludeTitles.length > 0) {
- hits = hits.filter((hit) => {
- const title = (hit.title || '').toLowerCase();
- return !excludeTitles.some(t => title.includes(t));
- });
- }
-
- const sorted = hits.sort((a, b) => (b.points || 0) - (a.points || 0));
- return sorted.map(normalizeAlgoliaHit);
+ return fetchAlgoliaDay(`story,${tag}`, daysAgo, tag, excludeHiring ? hit => !isHiringThread(hit.title) : undefined);
}
const HIRING_EXCLUDE_TITLES = [
@@ -292,7 +276,7 @@ function isHiringThread(title: string | undefined): boolean {
}
export function fetchAskStoriesForDay(daysAgo: number): Promise {
- return fetchTaggedStoriesForDay('ask_hn', daysAgo, HIRING_EXCLUDE_TITLES);
+ return fetchTaggedStoriesForDay('ask_hn', daysAgo, true);
}
export function fetchShowStoriesForDay(daysAgo: number): Promise {
diff --git a/src/components/CommentDetail.tsx b/src/components/CommentDetail.tsx
index 919c645..5ddfc63 100644
--- a/src/components/CommentDetail.tsx
+++ b/src/components/CommentDetail.tsx
@@ -3,7 +3,7 @@ import { useNavigate, useLocation } from 'react-router';
import { useCommentDetail } from '../hooks/useCommentDetail';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
-import { CommentSkeletonTree } from './CommentSkeleton';
+import { CommentArticleSkeleton } from './CommentSkeleton';
import { CommentArticle } from './CommentArticle';
import { PageStage } from './PageStage';
import { StateView } from './StateView';
@@ -20,27 +20,6 @@ interface CommentDetailProps {
};
}
-/** Skeleton matching CommentArticle's shape. Chrome stays with the parent. */
-function CommentDetailSkeleton() {
- return (
-
- );
-}
-
export function CommentDetail({ commentId, initialData }: CommentDetailProps) {
const { comment, replies, moreRepliesLoading, itemId, itemTitle, itemTitleLoading, itemAuthor, loading, error, retry } = useCommentDetail(commentId, initialData);
const navigate = useNavigate();
@@ -83,7 +62,7 @@ export function CommentDetail({ commentId, initialData }: CommentDetailProps) {
if (error && !comment) {
return (
-
+
);
}
@@ -95,7 +74,7 @@ export function CommentDetail({ commentId, initialData }: CommentDetailProps) {
'transitioning' so progressive rendering shows the seeded
byline + text without a skeleton flash. Cold load (no
initialData) still skeletons normally. */}
- }>
+ }>
{comment && (
+
+
+
+
+
+
+ );
+}
+
// Inner content ONLY (chrome from consumer).
// Title h-6 ≤ real h1 to prevent PageStage contraction.
export function ItemDetailSkeleton() {
diff --git a/src/components/FullScreenComment.tsx b/src/components/FullScreenComment.tsx
index acc8de6..6ca29e1 100644
--- a/src/components/FullScreenComment.tsx
+++ b/src/components/FullScreenComment.tsx
@@ -3,38 +3,16 @@ import { useCommentDetail } from '../hooks/useCommentDetail';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
import { CommentArticle } from './CommentArticle';
-import { CommentSkeletonTree } from './CommentSkeleton';
+import { CommentArticleSkeleton } from './CommentSkeleton';
import { FullScreenChrome } from './FullScreenChrome';
import { PageStage } from './PageStage';
import { StateView } from './StateView';
-// Inner content ONLY — consumer supplies the chrome.
-// Mirrors CommentArticle's shape.
-function FullScreenCommentSkeleton() {
- return (
-
- );
-}
-
// Bare-context wrapper — supplies chrome around skeleton.
export function FullScreenCommentSkeletonPanel() {
return (
-
+
);
}
@@ -88,7 +66,7 @@ export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenComme
{/* loading={!comment} prevents skeleton flash on retry.
No triggerWhen — offscreen cascade ok. */}
- }>
+ }>
{comment && (
{
return (
);
}
diff --git a/src/components/InfiniteStoryListPage.tsx b/src/components/InfiniteStoryListPage.tsx
index 323eec3..28812df 100644
--- a/src/components/InfiniteStoryListPage.tsx
+++ b/src/components/InfiniteStoryListPage.tsx
@@ -33,11 +33,6 @@ export interface StoryCardExtras {
interface InfiniteStoryListPageProps {
result: InfiniteStoryListResult;
- /**
- * Stable primitive key for context changes. Resets cascade state
- * so the new feed gets a fresh cold-load entrance.
- */
- resetKey: string;
storyCardExtras?: StoryCardExtras;
/** Empty-state title. Omit to skip empty rendering. */
emptyTitle?: string;
@@ -52,14 +47,13 @@ const PRELOAD_MARGIN_PX = 200;
*/
export function InfiniteStoryListPage({
result,
- resetKey,
storyCardExtras,
emptyTitle,
failTitle = 'Failed to load items',
}: InfiniteStoryListPageProps) {
const { stories, loading, error, hasMore, loadMore } = result;
- const getSlot = useStaggerCascadeSlots(loading, stories.length, resetKey);
+ const getSlot = useStaggerCascadeSlots(loading, stories.length);
const { ref, inView } = useInView({
threshold: 0,
diff --git a/src/hooks/useStaggerCascadeSlots.test.ts b/src/hooks/useStaggerCascadeSlots.test.ts
index 4918edf..66f2bea 100644
--- a/src/hooks/useStaggerCascadeSlots.test.ts
+++ b/src/hooks/useStaggerCascadeSlots.test.ts
@@ -123,57 +123,4 @@ describe('useStaggerCascadeSlots', () => {
expect(result.current(30)).toEqual({ appendIdx: 0 });
expect(result.current(49)).toEqual({ appendIdx: 19 });
});
-
- describe('resetKey', () => {
- // Without resetKey, navigating from /top (with appended batches)
- // to a cached /best would inherit /top's boundary AND batchStart,
- // routing the first ~20 best cards through `stageIdx` (snap, no
- // animation in 'done' state) and the rest through `appendIdx`
- // with the wrong baseline. The reset collapses everything so the
- // new context starts fresh.
- it('resets boundary and batchStart when resetKey changes', () => {
- const { result, rerender } = renderHook(
- ({ loading, count, key }: { loading: boolean; count: number; key: string }) =>
- useStaggerCascadeSlots(loading, count, key),
- { initialProps: { loading: true, count: 0, key: 'top' } },
- );
-
- // Cold load + first append on /top.
- rerender({ loading: false, count: 20, key: 'top' });
- rerender({ loading: true, count: 20, key: 'top' });
- rerender({ loading: false, count: 40, key: 'top' });
- expect(result.current(20)).toEqual({ appendIdx: 0 });
-
- // Switch to /best — same hook instance, new context.
- rerender({ loading: false, count: 30, key: 'best' });
- // Boundary re-captures on the post-reset commit at the new
- // count (30), so the first 30 best cards get stageIdx.
- expect(result.current(0)).toEqual({ stageIdx: 0 });
- expect(result.current(29)).toEqual({ stageIdx: 29 });
-
- // Best then appends cleanly with batch-relative appendIdx.
- rerender({ loading: true, count: 30, key: 'best' });
- rerender({ loading: false, count: 50, key: 'best' });
- expect(result.current(30)).toEqual({ appendIdx: 0 });
- expect(result.current(49)).toEqual({ appendIdx: 19 });
- });
-
- it('does NOT reset when resetKey stays the same across re-renders', () => {
- // Re-renders with stable resetKey are the common case; the
- // reset path must not fire on every render or the cascade
- // would never advance.
- const { result, rerender } = renderHook(
- ({ loading, count, key }: { loading: boolean; count: number; key: string }) =>
- useStaggerCascadeSlots(loading, count, key),
- { initialProps: { loading: true, count: 0, key: 'top' } },
- );
-
- rerender({ loading: false, count: 20, key: 'top' });
- rerender({ loading: false, count: 20, key: 'top' });
- rerender({ loading: false, count: 20, key: 'top' });
-
- expect(result.current(0)).toEqual({ stageIdx: 0 });
- expect(result.current(19)).toEqual({ stageIdx: 19 });
- });
- });
});
diff --git a/src/hooks/useStaggerCascadeSlots.ts b/src/hooks/useStaggerCascadeSlots.ts
index 8a27de5..57f572d 100644
--- a/src/hooks/useStaggerCascadeSlots.ts
+++ b/src/hooks/useStaggerCascadeSlots.ts
@@ -21,30 +21,19 @@ export interface CascadeSlot {
* or `appendIdx` (per-batch infinite-scroll cascade).
*
* `batchStart` resets to 0 per batch so appended cards don't inherit
- * the prior batch's cap. `resetKey` collapses state on context change
- * (MUST be a primitive). `StoryCard` snapshots its slot at mount.
+ * the prior batch's cap. `StoryCard` snapshots its slot at mount. Callers
+ * remount on context change (the list pages are keyed by feed, domain and
+ * user), so state never carries over to a new feed.
*/
export function useStaggerCascadeSlots(
loading: boolean,
count: number,
- resetKey?: unknown,
): (index: number) => CascadeSlot {
const [initialBoundary, setInitialBoundary] = useState(null);
const [batchStart, setBatchStart] = useState(0);
const wasLoadingRef = useRef(loading);
- const resetKeyRef = useRef(resetKey);
useEffect(() => {
- if (resetKeyRef.current !== resetKey) {
- resetKeyRef.current = resetKey;
- setInitialBoundary(null);
- setBatchStart(0);
- // Re-baseline the loading edge so the next false→true on the
- // new context captures batchStart cleanly.
- wasLoadingRef.current = loading;
- return;
- }
-
if (initialBoundary === null && !loading && count > 0) {
setInitialBoundary(count);
}
@@ -54,7 +43,7 @@ export function useStaggerCascadeSlots(
if (!wasLoading && loading) {
setBatchStart(count);
}
- }, [loading, count, initialBoundary, resetKey]);
+ }, [loading, count, initialBoundary]);
return useCallback(
(index: number): CascadeSlot => {
diff --git a/src/pages/DomainStories.tsx b/src/pages/DomainStories.tsx
index ae83ef6..b00bf1f 100644
--- a/src/pages/DomainStories.tsx
+++ b/src/pages/DomainStories.tsx
@@ -41,7 +41,6 @@ export function DomainStories() {
return (
diff --git a/src/pages/StoryList.tsx b/src/pages/StoryList.tsx
index ad42879..318d62b 100644
--- a/src/pages/StoryList.tsx
+++ b/src/pages/StoryList.tsx
@@ -52,7 +52,6 @@ export function StoryList({ type }: { type: FeedType }) {
return (
);
diff --git a/src/pages/UserSubmissions.tsx b/src/pages/UserSubmissions.tsx
index 8da6d16..253eed4 100644
--- a/src/pages/UserSubmissions.tsx
+++ b/src/pages/UserSubmissions.tsx
@@ -36,7 +36,6 @@ export function UserSubmissions() {
return (
Date: Fri, 27 Nov 2026 12:05:47 +0200
Subject: [PATCH 5/7] test: cover top feed day paging, session resume and list
end
Pins loadMore behavior the next commit refactors: the top feed's walk
back through earlier days and its 5-empty-day limit, resuming a saved
top session on the next earlier day, and best/newest stopping at the
end of their list.
---
...useInfiniteStories.algoliaFallback.test.ts | 63 +++++++++++++++++++
src/hooks/useInfiniteStories.test.ts | 12 ++++
2 files changed, 75 insertions(+)
diff --git a/src/hooks/useInfiniteStories.algoliaFallback.test.ts b/src/hooks/useInfiniteStories.algoliaFallback.test.ts
index 8d034f4..d95c27f 100644
--- a/src/hooks/useInfiniteStories.algoliaFallback.test.ts
+++ b/src/hooks/useInfiniteStories.algoliaFallback.test.ts
@@ -253,3 +253,66 @@ describe('useInfiniteStories – Ask/Show Algolia fallback', () => {
expect(result.current.stories.length).toBeGreaterThan(2);
});
});
+
+describe('useInfiniteStories – top feed earlier days', () => {
+ const originalFetch = globalThis.fetch;
+
+ beforeEach(() => {
+ clearFeedCache();
+ clearListSessionState('top');
+ __resetFetchCachesForTests();
+ vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue([1, 2, 3]);
+ vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => makeFirebaseItem(Number(id)));
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ clearFeedCache();
+ clearListSessionState('top');
+ vi.restoreAllMocks();
+ });
+
+ it('follows the front page with the first earlier day that has unseen stories', async () => {
+ globalThis.fetch = vi.fn()
+ .mockResolvedValueOnce(mockAlgoliaResponse([]))
+ .mockResolvedValueOnce(mockAlgoliaResponse([makeAlgoliaHit(2, 'story', 300), makeAlgoliaHit(1001, 'story')]));
+ const { result } = renderHook(() => useInfiniteStories('top'));
+
+ await act(() => result.current.loadMore());
+ expect(result.current.stories.map(s => s.id)).toEqual([1, 2, 3]);
+
+ await act(() => result.current.loadMore());
+ expect(result.current.stories.map(s => s.id)).toEqual([1, 2, 3, 1001]);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('tries up to 5 empty days per loadMore call', async () => {
+ globalThis.fetch = vi.fn().mockResolvedValue(mockAlgoliaResponse([]));
+ const { result } = renderHook(() => useInfiniteStories('top'));
+
+ await act(() => result.current.loadMore());
+ await act(() => result.current.loadMore());
+
+ expect(result.current.stories).toHaveLength(3);
+ expect(fetch).toHaveBeenCalledTimes(5);
+ expect(result.current.hasMore).toBe(true);
+ });
+
+ it('resumes a saved session at the next earlier day', async () => {
+ const { result: first } = renderHook(() => useInfiniteStories('top'));
+ globalThis.fetch = vi.fn().mockResolvedValue(mockAlgoliaResponse([makeAlgoliaHit(1001, 'story')]));
+ await act(() => first.current.loadMore());
+ await act(() => first.current.loadMore());
+ act(() => first.current.saveSessionState(0));
+
+ globalThis.fetch = vi.fn().mockResolvedValue(mockAlgoliaResponse([makeAlgoliaHit(1002, 'story')]));
+ const { result } = renderHook(() => useInfiniteStories('top'));
+ expect(result.current.isFromSession).toBe(true);
+ await act(() => result.current.loadMore());
+
+ expect(result.current.stories.map(s => s.id)).toEqual([1, 2, 3, 1001, 1002]);
+ const url = new URL(vi.mocked(fetch).mock.calls[0]?.[0] as string);
+ const twoDaysAgo = Math.floor(Date.now() / 1000) - 2 * 86400;
+ expect(Number(url.searchParams.get('numericFilters')?.match(/created_at_i>=(\d+)/)?.[1])).toBeLessThanOrEqual(twoDaysAgo);
+ });
+});
diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts
index 1dc4411..6d39e64 100644
--- a/src/hooks/useInfiniteStories.test.ts
+++ b/src/hooks/useInfiniteStories.test.ts
@@ -161,6 +161,18 @@ describe('useInfiniteStories', () => {
expect(getCachedFeed('top')).toMatchObject({ timestamp: hourAgo, isStale: true });
});
+ it.each(['best', 'newest'])('stops at the end of the %s list', async (type) => {
+ vi.mocked(hnSdk.readRankedIds).mockResolvedValue(rankedIds.slice(0, 40));
+ const { result } = renderHook(() => useInfiniteStories(type));
+
+ await act(() => result.current.loadMore());
+ expect(result.current.hasMore).toBe(true);
+ await act(() => result.current.loadMore());
+
+ expect(result.current.stories).toHaveLength(40);
+ expect(result.current.hasMore).toBe(false);
+ });
+
describe('revalidation', () => {
function seedStaleFeed(type: FeedType) {
// A cached order the live ranking (1, 2, 3, …) has moved on from.
From 24aeb889a469f0d4d8e2db4cc43dc5fe1053d175 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Fri, 27 Nov 2026 12:06:22 +0200
Subject: [PATCH 6/7] refactor: extract loadMore paging helpers in
useInfiniteStories
The seen-story filter was written five times, the first-page cache
refresh and the keep-or-append list update three times, and the
day-by-day Algolia loop twice. loadMore now uses takeUnseen,
showStories, loadRankedPage and loadDays, and each feed branch is a
few lines. The corrupt-session check is computed once.
The feed branches, the phase and position model and the saved session
format are unchanged, so sessions saved before this still restore.
---
src/hooks/useInfiniteStories.ts | 269 ++++++++++----------------------
1 file changed, 82 insertions(+), 187 deletions(-)
diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts
index 5423284..c902247 100644
--- a/src/hooks/useInfiniteStories.ts
+++ b/src/hooks/useInfiniteStories.ts
@@ -84,15 +84,14 @@ export function useInfiniteStories(type: FeedType = 'top') {
initialState.sessionState?.hasMore ?? true
);
+ const session = initialState.sessionState;
+ // A session past position 200 without a phase is a corrupt blob: start over.
+ const isCorruptSession = !!session && !session.phase && session.position > 200;
// For top: 0 = current front page (Firebase), 1+ = days ago (Algolia)
// For best: tracks offset into the list
- // Safety fallback: if phase is missing but position > 200, it's a corrupt session blob
- const safePosition = (() => {
- const session = initialState.sessionState;
- if (session && !session.phase && session.position > 200) return 0;
- return session?.position ?? 0;
- })();
- const positionRef = useRef(safePosition);
+ const positionRef = useRef(isCorruptSession ? 0 : session?.position ?? 0);
+ // For ask/show: tracks whether we've exhausted Firebase and moved to Algolia
+ const phaseRef = useRef<'firebase' | 'algolia'>(isCorruptSession ? 'firebase' : session?.phase ?? 'firebase');
const seenIdsRef = useRef>(
new Set(initialState.sessionState?.seenIds)
);
@@ -107,15 +106,6 @@ export function useInfiniteStories(type: FeedType = 'top') {
useLayoutEffect(() => {
storiesRef.current = stories;
}, [stories]);
- // For ask/show: tracks whether we've exhausted Firebase and moved to Algolia
- const phaseRef = useRef<'firebase' | 'algolia'>(
- (() => {
- const session = initialState.sessionState;
- if (!session) return 'firebase';
- if (!session.phase && session.position > 200) return 'firebase';
- return session.phase ?? 'firebase';
- })()
- );
const loadMore = useCallback(async () => {
if (loading || !hasMore || inFlightRef.current) return;
@@ -136,187 +126,92 @@ export function useInfiniteStories(type: FeedType = 'top') {
return kept;
};
+ const takeUnseen = (page: StoryItem[]) => page.filter(story => {
+ if (seenIdsRef.current.has(story.id)) return false;
+ seenIdsRef.current.add(story.id);
+ return true;
+ });
+
+ // A refresh rebuilds the list even with nothing new on it: the cached
+ // stories past the kept ones are no longer in seenIds, so the next page
+ // would repeat them.
+ const showStories = (kept: StoryItem[] | null, unseen: StoryItem[]) => {
+ if (kept) {
+ setStories([...kept, ...unseen]);
+ } else if (unseen.length > 0) {
+ setStories(prev => [...prev, ...unseen]);
+ }
+ };
+
+ // One page of a Firebase ranked list, from positionRef. Resolves to the
+ // list's hasMore, or null when a newer request took over.
+ const loadRankedPage = async (
+ fetchPage: (offset: number) => Promise<{ stories: StoryItem[]; nextOffset: number; hasMore: boolean }>,
+ ) => {
+ const isRevalidating = hasStaleCacheRef.current && positionRef.current === 0;
+ const page = await fetchPage(positionRef.current);
+
+ if (versionRef.current !== currentVersion) return null;
+ if (isRevalidating && page.stories.length === 0) throw emptyRefreshError(type);
+
+ const kept = isRevalidating ? startRevalidation() : null;
+ const unseen = takeUnseen(page.stories);
+
+ // Fresh once the first page arrives, even if every story on it was
+ // kept: the swipe viewer calls loadMore for as long as isFromCache is set.
+ if (positionRef.current === 0 && page.stories.length > 0) {
+ setCachedFeed(type, page.stories);
+ setIsFromCache(false);
+ hasStaleCacheRef.current = false;
+ }
+
+ positionRef.current = page.nextOffset;
+ showStories(kept, unseen);
+ return page.hasMore;
+ };
+
+ // Walks back a day at a time from positionRef (days ago) until a day has
+ // unseen stories, trying at most maxEmptyDays.
+ const loadDays = async (fetchDay: (daysAgo: number) => Promise, maxEmptyDays: number) => {
+ let unseen: StoryItem[] = [];
+ for (let attempts = 0; unseen.length === 0 && attempts < maxEmptyDays && positionRef.current < 365; attempts++) {
+ const day = await fetchDay(positionRef.current);
+ if (versionRef.current !== currentVersion) return;
+ unseen = takeUnseen(day);
+ positionRef.current += 1;
+ }
+
+ if (unseen.length === 0 && positionRef.current >= 365) {
+ setHasMore(false);
+ } else {
+ showStories(null, unseen);
+ }
+ };
+
try {
if (type === 'top') {
- let newStories: StoryItem[] = [];
- // Set once a refresh's page arrives, which then rebuilds the list even
- // with nothing new on it: the cached stories past the kept ones are no
- // longer in seenIds, so the next page would repeat them.
- let kept: StoryItem[] | null = null;
- const isRevalidating = hasStaleCacheRef.current && positionRef.current === 0;
-
if (positionRef.current === 0) {
- const frontPage = await fetchTopStories(20);
-
- if (versionRef.current !== currentVersion) return;
- if (isRevalidating && frontPage.length === 0) throw emptyRefreshError(type);
-
- if (isRevalidating) {
- kept = startRevalidation();
- }
-
- newStories = frontPage.filter(story => {
- if (seenIdsRef.current.has(story.id)) {
- return false;
- }
- seenIdsRef.current.add(story.id);
- return true;
- });
-
- // Fresh once the page arrives, even if every story on it was kept:
- // the swipe viewer calls loadMore for as long as isFromCache is set.
- if (frontPage.length > 0) {
- setCachedFeed(type, frontPage);
- setIsFromCache(false);
- hasStaleCacheRef.current = false;
- }
-
// Next load will be yesterday. By design, today's stories ranked
// past the top 20 are never shown: the feed is HN's front page,
// then each earlier (UTC) day's front page from Algolia.
- positionRef.current = 1;
+ await loadRankedPage(async () => ({ stories: await fetchTopStories(20), nextOffset: 1, hasMore: true }));
} else {
- let attempts = 0;
- const maxAttempts = 5; // Try up to 5 days if current day has no stories
-
- while (newStories.length === 0 && attempts < maxAttempts && positionRef.current < 365) {
- const dayStories = await fetchFrontPageForDay(positionRef.current);
-
- if (versionRef.current !== currentVersion) return;
-
- const uniqueStories = dayStories.filter(story => {
- if (seenIdsRef.current.has(story.id)) {
- return false;
- }
- seenIdsRef.current.add(story.id);
- return true;
- });
-
- newStories = uniqueStories;
- positionRef.current += 1;
- attempts += 1;
- }
- }
-
- if (versionRef.current !== currentVersion) return;
-
- if (newStories.length === 0 && positionRef.current >= 365) {
- setHasMore(false);
- } else if (kept) {
- setStories([...kept, ...newStories]);
- } else if (newStories.length > 0) {
- setStories(prev => [...prev, ...newStories]);
+ await loadDays(fetchFrontPageForDay, 5);
}
} else if (type === 'best' || type === 'newest') {
- // Offset-based pagination via Firebase /beststories or /newstories.
- const isRevalidatingBest = hasStaleCacheRef.current && positionRef.current === 0;
- const fetchFn = type === 'best' ? fetchBestStories : fetchNewStories;
- const result = await fetchFn(positionRef.current, 30);
-
- if (versionRef.current !== currentVersion) return;
- if (isRevalidatingBest && result.stories.length === 0) throw emptyRefreshError(type);
-
- // As in the top branch.
- const kept = isRevalidatingBest ? startRevalidation() : null;
-
- const uniqueStories = result.stories.filter(story => {
- if (seenIdsRef.current.has(story.id)) {
- return false;
- }
- seenIdsRef.current.add(story.id);
- return true;
- });
-
- // By the fetched page, as in the top branch.
- if (positionRef.current === 0 && result.stories.length > 0) {
- setCachedFeed(type, result.stories);
- setIsFromCache(false);
- hasStaleCacheRef.current = false;
- }
-
- positionRef.current = result.nextOffset;
- setHasMore(result.hasMore);
-
- if (kept) {
- setStories([...kept, ...uniqueStories]);
- } else if (uniqueStories.length > 0) {
- setStories(prev => [...prev, ...uniqueStories]);
- }
- } else if (type === 'show' || type === 'ask') {
- const isRevalidating = hasStaleCacheRef.current && positionRef.current === 0;
-
- if (phaseRef.current === 'firebase') {
- const fetchFn = type === 'show' ? fetchShowStories : fetchAskStories;
- const result = await fetchFn(positionRef.current);
-
- if (versionRef.current !== currentVersion) return;
- if (isRevalidating && result.stories.length === 0) throw emptyRefreshError(type);
-
- // As in the top branch.
- const kept = isRevalidating ? startRevalidation() : null;
-
- const uniqueStories = result.stories.filter(story => {
- if (seenIdsRef.current.has(story.id)) {
- return false;
- }
- seenIdsRef.current.add(story.id);
- return true;
- });
-
- // By the fetched page, as in the top branch.
- if (positionRef.current === 0 && result.stories.length > 0) {
- setCachedFeed(type, result.stories);
- setIsFromCache(false);
- hasStaleCacheRef.current = false;
- }
-
- positionRef.current = result.nextOffset;
-
- // Boundary: Firebase exhausted → transition to Algolia
- if (!result.hasMore) {
- phaseRef.current = 'algolia';
- positionRef.current = 1; // Start with yesterday
- // Do NOT call setHasMore(false) — Algolia has more content
- }
-
- if (kept) {
- setStories([...kept, ...uniqueStories]);
- } else if (uniqueStories.length > 0) {
- setStories(prev => [...prev, ...uniqueStories]);
- }
- } else {
- // Algolia phase: fetch day-by-day
- const fetchDayFn = type === 'ask' ? fetchAskStoriesForDay : fetchShowStoriesForDay;
- let newStories: StoryItem[] = [];
- let attempts = 0;
- const maxAttempts = 14;
-
- while (newStories.length === 0 && attempts < maxAttempts && positionRef.current < 365) {
- const dayStories = await fetchDayFn(positionRef.current);
-
- if (versionRef.current !== currentVersion) return;
-
- const uniqueStories = dayStories.filter(story => {
- if (seenIdsRef.current.has(story.id)) {
- return false;
- }
- seenIdsRef.current.add(story.id);
- return true;
- });
-
- newStories = uniqueStories;
- positionRef.current += 1;
- attempts += 1;
- }
-
- if (versionRef.current !== currentVersion) return;
-
- if (newStories.length === 0 && positionRef.current >= 365) {
- setHasMore(false);
- } else if (newStories.length > 0) {
- setStories(prev => [...prev, ...newStories]);
- }
+ const fetchPage = type === 'best' ? fetchBestStories : fetchNewStories;
+ const listHasMore = await loadRankedPage(offset => fetchPage(offset, 30));
+ if (listHasMore !== null) setHasMore(listHasMore);
+ } else if (phaseRef.current === 'firebase') {
+ const listHasMore = await loadRankedPage(type === 'show' ? fetchShowStories : fetchAskStories);
+ // Firebase exhausted: carry on from Algolia, which has more, starting
+ // with yesterday.
+ if (listHasMore === false) {
+ phaseRef.current = 'algolia';
+ positionRef.current = 1;
}
+ } else {
+ await loadDays(type === 'ask' ? fetchAskStoriesForDay : fetchShowStoriesForDay, 14);
}
} catch (err) {
// Stale-response guard: only surface errors from the current request.
From 7bc050669ba1113e9541e4f6170f44ee92a8de89 Mon Sep 17 00:00:00 2001
From: therealsama <263038098+therealsama@users.noreply.github.com>
Date: Fri, 27 Nov 2026 15:18:05 +0200
Subject: [PATCH 7/7] test: remove duplicate and can't-fail tests
Remove 187 unit tests and 30 e2e tests that duplicate a remaining test,
restate the implementation, test library behavior, or cannot fail
(only `not.toThrow`, or only assert fixture data). Coverage moves by
0.1% at most; the lines no longer run had no assertions on them.
Also remove two things only those tests used: the unused
`__getUserStoriesCacheForTests` export, and the combined `loading`
field of `useItemWithComments`, which no component reads.
---
e2e/accessibility.spec.ts | 10 -
e2e/comment-detail.spec.ts | 19 --
e2e/comment-swipe.spec.ts | 53 -----
e2e/domain-filter.spec.ts | 93 +-------
e2e/header-overflow.spec.ts | 42 ----
e2e/item-detail.spec.ts | 23 --
e2e/mobile-swipe.spec.ts | 89 -------
e2e/navigation.spec.ts | 33 ---
e2e/story-browsing.spec.ts | 14 --
e2e/theme-toggle.spec.ts | 22 --
e2e/user-profile.spec.ts | 19 --
e2e/viewed-items.spec.ts | 21 --
src/api/hn.fetchTaggedStories.test.ts | 27 ---
src/api/hn.test.ts | 225 ------------------
src/components/Comment.test.tsx | 45 +---
src/components/CommentArticle.test.tsx | 20 --
src/components/CommentDetail.test.tsx | 2 +-
src/components/ErrorBoundary.test.tsx | 9 -
src/components/FullScreenComment.test.tsx | 29 ---
src/components/FullScreenItem.test.tsx | 8 -
src/components/Header.test.tsx | 25 --
src/components/InfiniteStoryListPage.test.tsx | 23 --
src/components/NetworkStatusBar.test.tsx | 6 -
src/components/PageStage.test.tsx | 57 -----
src/components/StateView.test.tsx | 15 --
src/components/StoryCard.test.tsx | 75 ------
src/components/SwipeCommentViewer.test.tsx | 33 ---
src/components/ThemeToggle.test.tsx | 10 -
src/context/ScrollContainerContext.test.tsx | 35 ---
src/hooks/useCanSwipe.test.ts | 41 +---
src/hooks/useCommentDetail.test.ts | 8 -
src/hooks/useDomainInfiniteStories.test.ts | 54 -----
...useInfiniteStories.algoliaFallback.test.ts | 19 --
src/hooks/useInfiniteStories.test.ts | 50 ----
src/hooks/useIsMobileLayout.test.ts | 34 +--
src/hooks/useItemWithComments.test.tsx | 201 +---------------
src/hooks/useItemWithComments.ts | 5 -
src/hooks/usePackedNav.test.ts | 13 -
src/hooks/usePrefetchItem.test.ts | 215 +----------------
src/hooks/useScrollDirection.test.ts | 14 --
src/hooks/useScrollRestore.test.ts | 17 --
src/hooks/useSiblingComments.test.ts | 25 --
src/hooks/useStaggerCascadeSlots.test.ts | 12 -
src/hooks/useSwipeScroll.test.ts | 39 ---
src/hooks/useTheme.test.tsx | 24 --
src/hooks/useUserInfiniteStories.test.ts | 176 +-------------
src/hooks/useUserInfiniteStories.ts | 5 -
src/hooks/useViewDwell.test.tsx | 9 -
src/pages/ItemDetail.test.tsx | 38 ---
src/pages/UserProfile.test.tsx | 25 --
src/pages/UserSubmissions.test.tsx | 10 -
src/utils/feedCache.test.ts | 16 --
src/utils/fetchPriority.test.ts | 10 -
src/utils/itemCache.test.ts | 49 ----
src/utils/sanitize.test.ts | 65 -----
src/utils/share.test.ts | 4 -
src/utils/swipePosition.test.ts | 12 -
src/utils/touchActiveStates.test.ts | 9 -
src/utils/viewedItems.test.ts | 32 ---
59 files changed, 25 insertions(+), 2288 deletions(-)
diff --git a/e2e/accessibility.spec.ts b/e2e/accessibility.spec.ts
index ceee1d6..cdf178f 100644
--- a/e2e/accessibility.spec.ts
+++ b/e2e/accessibility.spec.ts
@@ -157,16 +157,6 @@ test.describe('Accessibility', () => {
await expect(page.getByText('Lost in the feed')).toHaveCount(0);
});
- test('external links have valid URLs', async ({ page }) => {
- await page.goto('/#/');
-
- const externalLink = page.getByRole('link', { name: 'Rust Is the Future of JavaScript Infrastructure' });
- await expect(externalLink).toBeVisible();
-
- const href = await externalLink.getAttribute('href');
- expect(href).toContain('https://example.com');
- });
-
test('best stories page has no critical accessibility violations', async ({ page, makeAxeBuilder }) => {
await page.goto('/#/best');
diff --git a/e2e/comment-detail.spec.ts b/e2e/comment-detail.spec.ts
index 52227dc..54ce9eb 100644
--- a/e2e/comment-detail.spec.ts
+++ b/e2e/comment-detail.spec.ts
@@ -72,25 +72,6 @@ test.describe('Comment Detail', () => {
});
});
-test.describe('Comment Detail - Desktop', () => {
- test.use({ viewport: { width: 1280, height: 720 } });
-
- test.beforeEach(async ({ page }) => {
- await setupApiMocks(page);
- });
-
- test('shows comment detail page on desktop', async ({ page }) => {
- await page.goto('/#/item/1001');
-
- await expect(page.getByText('patio11').first()).toBeVisible();
- await expect(page.getByText(/wasm-bindgen/i).first()).toBeVisible();
-
- // Mobile-only swipe container must not appear at desktop width.
- const swipeContainer = page.locator('.swipe-snap-container');
- await expect(swipeContainer).not.toBeVisible();
- });
-});
-
test.describe('Comment Detail - Error + Retry', () => {
test.use({ viewport: { width: 1280, height: 720 } });
diff --git a/e2e/comment-swipe.spec.ts b/e2e/comment-swipe.spec.ts
index 68322a9..dd708e7 100644
--- a/e2e/comment-swipe.spec.ts
+++ b/e2e/comment-swipe.spec.ts
@@ -57,17 +57,6 @@ test.describe('Mobile Comment Swipe Viewer', () => {
await expect(page).toHaveURL(/\/item\/1001/, { timeout: 5000 });
});
- test('shows comment content in swipe viewer on mobile', async ({ page }) => {
- await page.goto('/#/item/1001');
-
- const swipeContainer = page.getByTestId('swipe-container');
- await expect(swipeContainer).toBeVisible();
-
- await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 });
-
- await expectActiveSwipePanelText(page, /wasm-bindgen/i);
- });
-
test('loads sibling comments as swipeable panels', async ({ page }) => {
await page.goto('/#/item/1001');
@@ -78,21 +67,6 @@ test.describe('Mobile Comment Swipe Viewer', () => {
await expect(panels).toHaveCount(4);
});
- test('can swipe to next sibling comment', async ({ page }) => {
- await page.goto('/#/item/1001');
-
- await waitForSwipeReady(page, 4);
-
- 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\/1002/, { timeout: 5000 });
-
- 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');
@@ -156,25 +130,6 @@ test.describe('Mobile Comment Swipe Viewer', () => {
await expect(page).toHaveURL(/\/item\/1001/, { timeout: 5000 });
});
- test('shows parent and story links in comment', async ({ page }) => {
- await page.goto('/#/item/1001');
-
- await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 });
-
- const parentLink = page.getByRole('link', { name: 'parent' }).first();
- await expect(parentLink).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 expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 });
-
- await expect(page.getByText('comments').first()).toBeVisible();
- });
-
test('swipe uses replaceState — no extra history entries', async ({ page }) => {
await page.goto('/#/item/1001');
@@ -342,14 +297,6 @@ test.describe('Mobile Comment Swipe Viewer', () => {
await expect(page.getByText('Failed to load comments').first()).toBeVisible({ timeout: 30000 });
});
- test('sets document title to "Comment by {author}" for the current comment', async ({ page }) => {
- await page.goto('/#/item/1001');
-
- await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 });
-
- await expect(page).toHaveTitle(/Comment by patio11/);
- });
-
test('clicking item title link navigates to story viewer, not comment viewer', async ({ page }) => {
await page.goto('/#/item/1001');
diff --git a/e2e/domain-filter.spec.ts b/e2e/domain-filter.spec.ts
index 9187a6f..d601444 100644
--- a/e2e/domain-filter.spec.ts
+++ b/e2e/domain-filter.spec.ts
@@ -12,34 +12,6 @@ import {
setOfflineAndWaitForBar,
} from './fixtures/layout-helpers';
-test.describe('Domain Filter', () => {
- test.beforeEach(async ({ page }) => {
- await setupApiMocks(page);
- });
-
- test('displays items filtered by domain', async ({ page }) => {
- await page.goto('/#/from/example.com');
-
- // Two valid landing URLs:
- // - Desktop: stays at /#/from/example.com (DomainStories list).
- // - Mobile: SwipeDomainStoryViewer immediately replaceState()s
- // to /#/item/:firstId (objectID '77777' from the mock). This
- // rewrite races Playwright's first poll, so a strict
- // /#/from/example.com regex deterministically loses on mobile.
- // Same pattern as the empty-domain test at the bottom of this
- // file, which uses /\/#\/(item\/\d+)?$/ for the same reason.
- await expect(page).toHaveURL(/\/#\/(from\/example\.com|item\/77777)/);
-
- // Story-title visibility is the load-bearing assertion: the title
- // appears whether the desktop list or the mobile swipe panel
- // rendered, and it only appears if the domain filter actually
- // worked (the mock filters on `?query=example.com`).
- await expect(page.getByText('Google Announces Gemini 3.0 with Extended Context').first()).toBeVisible({ timeout: 10000 });
-
- await expect(page.getByText(/example\.com/i).first()).toBeVisible();
- });
-});
-
test.describe('Domain Filter - Edge Cases', () => {
test.beforeEach(async ({ page }) => {
await setupApiMocks(page);
@@ -54,12 +26,6 @@ test.describe('Domain Filter - Edge Cases', () => {
await expect(page).toHaveTitle(/unknown-domain\.xyz.*HackerTok/);
});
-
- test('domain with subdomain works', async ({ page }) => {
- await page.goto('/#/from/blog.example.com');
-
- await expect(page).toHaveURL(/\/#\/from\/blog\.example\.com/);
- });
});
test.describe('Domain Filter - Centered state layouts', () => {
@@ -89,10 +55,10 @@ test.describe('Domain Filter - Header "from" button', () => {
// story" and "browser back restores the list" tests below click
// StoryCard links inside DomainStories, which only renders on desktop —
// on mobile, SwipeDomainStoryViewer replaces the URL with /#/item/:id
- // before any list card is visible. The earlier "visible + active" and
- // "hidden on non-domain pages" assertions would also hold on mobile
- // (Header's `isFromActive` stays true across the URL rewrite via
- // state.fromDomain), but they are kept here for locality. The mobile
+ // before any list card is visible. The "visible + active" assertions
+ // would also hold on mobile (Header's `isFromActive` stays true across
+ // the URL rewrite via state.fromDomain), but they are kept here for
+ // locality. The mobile
// rewrite path is covered by "updates URL to /item/:id and carries
// fromDomain state on swipe" in the Mobile Swipe describe below.
test.use({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 });
@@ -114,16 +80,6 @@ test.describe('Domain Filter - Header "from" button', () => {
await expect(page.getByRole('link', { name: 'ask', exact: true })).not.toHaveClass(/bg-accent/);
});
- test('"from" button is hidden on non-domain pages', async ({ page }) => {
- const fromButton = page.locator('header nav span', { hasText: 'from' });
-
- await page.goto('/#/');
- await expect(fromButton).toHaveCount(0);
-
- await page.goto('/#/best');
- await expect(fromButton).toHaveCount(0);
- });
-
test('"from" button stays active after opening a story\'s comments from a domain list', async ({ page }) => {
// Desktop: StoryCard inside DomainStories renders the domain as fromDomain,
// so the "comments" link carries state.fromDomain instead of state.from.
@@ -369,36 +325,11 @@ test.describe('Domain Filter - Mobile Swipe', () => {
// desktop list (SwipeStoryViewerCore vs DomainStories) with different copy
// ("Failed to load item" singular vs "Failed to load items" plural) and
// different surrounding markup (swipe-snap-container). The "Algolia Error
- // Handling" describe below pins the desktop path; these mirror it for the
+ // Handling" describe below pins the desktop path; this mirrors it for the
// mobile swipe wiring so a regression in either codepath is caught.
// Auto-retry exhausts 3 backoff attempts (2s+4s+8s ≈ 14s) before showing
// error UI, hence the per-test timeout override.
- test('shows error state when Algolia returns 503 on mobile swipe', async ({ page }) => {
- test.setTimeout(60000);
-
- await page.route(`${ALGOLIA_API}/search_by_date*`, async (route) => {
- await route.fulfill({ status: 503, json: { message: 'Service unavailable' } });
- });
-
- await page.goto('/#/from/example.com');
-
- // Mobile copy is singular ("item") — the desktop test's regex
- // `/Failed to load items/` would not match here, so an exact assertion
- // pins the mobile branch specifically.
- await expect(page.getByText('Failed to load item', { exact: true })).toBeVisible({ timeout: 30000 });
- // Mobile's StateView omits the `description` prop, so the default copy
- // ("We couldn't load this content. Please try again.") renders alongside
- // the action label. Use the button role to disambiguate from that text.
- await expect(page.getByRole('button', { name: /try again/i })).toBeVisible();
-
- // Confirm the error UI is rendered inside the swipe viewer's container,
- // not the desktop list's wrapper. Catches a regression that flips
- // `useCanSwipe` — its width half or its pointer half — and leaks the
- // desktop list into a phone.
- await expect(page.getByTestId('swipe-container')).toBeVisible();
- });
-
test('recovers after retry when Algolia temporarily fails on mobile swipe', async ({ page }) => {
test.setTimeout(60000);
@@ -499,20 +430,6 @@ test.describe('Domain Filter - Algolia Error Handling', () => {
// Auto-retry exhausts 3 backoff attempts (2s+4s+8s) before surfacing error.
test.setTimeout(60000);
- test('shows error state when Algolia returns 503', async ({ page }) => {
- await setupApiMocks(page);
-
- await page.route(`${ALGOLIA_API}/search_by_date*`, async (route) => {
- await route.fulfill({ status: 503, json: { message: 'Service unavailable' } });
- });
-
- await page.goto('/#/from/example.com');
-
- // 30s timeout covers the 2+4+8 backoff plus slack.
- await expect(page.getByText(/Failed to load items/)).toBeVisible({ timeout: 30000 });
- await expect(page.getByText(/try again/i)).toBeVisible();
- });
-
test('recovers after retry when Algolia temporarily fails', async ({ page }) => {
await setupApiMocks(page);
diff --git a/e2e/header-overflow.spec.ts b/e2e/header-overflow.spec.ts
index 8772c3c..7e6e14d 100644
--- a/e2e/header-overflow.spec.ts
+++ b/e2e/header-overflow.spec.ts
@@ -74,32 +74,6 @@ test.describe('Header overflow — More dropdown', () => {
const userPill = (page: Page) =>
page.locator('header nav span', { hasText: 'user' });
- test('shows the "More tabs" trigger when nav items overflow', async ({ page }) => {
- await page.goto('/#/submitted/pg');
- await expect(userPill(page)).toBeVisible();
-
- const moreBtn = page.getByRole('button', { name: 'More tabs' });
- await expect(moreBtn).toBeVisible();
- await expect(moreBtn).toHaveAttribute('aria-haspopup', 'menu');
- // Closed menus must NOT mount their portal content.
- await expect(page.getByRole('menuitem')).toHaveCount(0);
- });
-
- test('opens the menu on click and reveals hidden feed tabs as menuitems', async ({ page }) => {
- await page.goto('/#/submitted/pg');
- await expect(userPill(page)).toBeVisible();
-
- await page.getByRole('button', { name: 'More tabs' }).click();
-
- // Asserting on menuitem visibility is the strongest "menu actually
- // opened" signal. We avoid asserting `aria-expanded='true'` on the
- // trigger because Radix re-applies props via a Slot wrapper on open,
- // which can briefly invalidate any stored locator handle in Playwright
- // even though the underlying button is still in the DOM. The menuitem
- // existence test is the user-facing contract.
- await expect(page.getByRole('menuitem').first()).toBeVisible();
- });
-
test('clicking a hidden feed in the menu navigates to that route', async ({ page }) => {
await page.goto('/#/submitted/pg');
await expect(userPill(page)).toBeVisible();
@@ -390,19 +364,3 @@ test.describe('Header overflow — the trigger stays a target', () => {
expect(box.height).toBeCloseTo(pill.height, 0);
});
});
-
-test.describe('Theme toggle — accessible label', () => {
- test.beforeEach(async ({ page }) => {
- await setupApiMocks(page);
- });
-
- test('theme toggle button has an accessible label describing the action', async ({ page }) => {
- await page.goto('/#/');
- await expect(
- page.getByText('Rust Is the Future of JavaScript Infrastructure').first(),
- ).toBeVisible();
-
- const toggle = page.getByTestId('theme-toggle');
- await expect(toggle).toHaveAccessibleName(/switch to (system|light|dark)/i);
- });
-});
diff --git a/e2e/item-detail.spec.ts b/e2e/item-detail.spec.ts
index 032de60..d46cc35 100644
--- a/e2e/item-detail.spec.ts
+++ b/e2e/item-detail.spec.ts
@@ -31,19 +31,6 @@ test.describe('Item Detail', () => {
await expect(page.getByText('tptacek').first()).toBeVisible();
});
- test('can expand and collapse replies', async ({ page }) => {
- await page.goto('/#/item/12345');
-
- await expect(page.getByText('patio11').first()).toBeVisible({ timeout: 10000 });
-
- await page.getByText(/1 reply/i).first().click();
- await expect(page.getByText('tptacek').first()).toBeVisible();
-
- // Trunk line button collapses the whole subtree, not just the immediate child.
- await page.getByRole('button', { name: /collapse replies/i }).first().click();
- await expect(page.getByText('tptacek').first()).not.toBeVisible();
- });
-
test('handles item not found', async ({ page }) => {
// 99999999 returns null in the mock — exercises the not-found branch.
await page.goto('/#/item/99999999');
@@ -238,16 +225,6 @@ test.describe('Item Detail - Desktop', () => {
await setupApiMocks(page);
});
- test('shows full item detail page on desktop', async ({ page }) => {
- await page.goto('/#/item/12345');
-
- // Mobile-only swipe container must not appear at desktop width.
- const swipeContainer = page.locator('.swipe-snap-container');
- await expect(swipeContainer).not.toBeVisible();
-
- await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible();
- });
-
test('back from item detail returns to item list', async ({ page }) => {
await page.goto('/#/');
await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible();
diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts
index 23129d1..5e6d6db 100644
--- a/e2e/mobile-swipe.spec.ts
+++ b/e2e/mobile-swipe.spec.ts
@@ -50,15 +50,6 @@ test.describe('Mobile Swipe Viewer', () => {
});
});
- test('shows swipe viewer with item on mobile', async ({ page }) => {
- await page.goto('/#/');
-
- const swipeContainer = page.getByTestId('swipe-container');
- await expect(swipeContainer).toBeVisible();
-
- await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure');
- });
-
test('can swipe to next item', async ({ page }) => {
await page.goto('/#/');
@@ -651,12 +642,6 @@ test.describe('Mobile Direct Item Access', () => {
await setupApiMocks(page);
});
- test('can access item directly via URL on mobile', async ({ page }) => {
- await page.goto('/#/item/12345');
-
- await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure');
- });
-
test('displays Ask HN body text in mobile swipe view', async ({ page }) => {
// Navigate to Ask HN item (88888 - has text content but no URL)
// On mobile this renders via FullScreenItem.jsx, not ItemDetail.jsx
@@ -843,71 +828,6 @@ test.describe('Mobile Direct Item Access', () => {
await expect(activePanel.getByText('The Art of Finishing Projects')).toHaveCount(0);
});
- test('loads more items when swiping near the end', async ({ page }) => {
- // The swipe viewer triggers loadMore() when within 5 items of the end
- // or when fewer than 10 items are loaded. With only 3 top items in
- // the initial batch, it should auto-load pagination items.
-
- await page.goto('/#/');
- await expectActiveSwipePanelText(page, 'Rust Is the Future of JavaScript Infrastructure');
-
- const container = page.getByTestId('swipe-container');
-
- // The auto-load fires immediately (stories.length < 10) at index 0,
- // adding pagination items before any swipe. Wait for those panels so
- // DOM mutations from appending stories don't overlap with the scroll
- // (Firefox re-snaps on snap-child changes during scroll-settle).
- await waitForSwipeReady(page, 6);
-
- const panelWidth = await container.evaluate((el) => el.getBoundingClientRect().width);
-
- // Swipe to the last item in the initial batch
- await smoothScrollAndAwaitSettled(container, panelWidth * 2);
-
- // Use expect.poll to tolerate brief state transitions
- // from loading-panel toggles at the tail of the container.
- await expect.poll(() => container.evaluate(
- (el) => {
- const panels = el.children;
- for (let i = 0; i < panels.length; i++) {
- if (panels[i].classList.contains('active')) return i;
- }
- return -1;
- }
- ), { timeout: 10000 }).toBe(2);
-
- await expect(page).toHaveURL(/\/item\/12347/, { timeout: 5000 });
-
- // The total panel count should be more than the initial 3
- const panelCount = await page.locator('[data-testid="swipe-panel"]').count();
- expect(panelCount).toBeGreaterThan(3);
- });
-
- test('displays Ask HN body text when swiping through feed (Algolia story_text)', async ({ page }) => {
- // Regression: stories loaded from Algolia search (used by /ask, /show, /)
- // carry body text in the `story_text` field. normalizeAlgoliaHit must map
- // it to `text` so FullScreenItem can render it. Previously, this field was
- // dropped, causing body text to be missing on mobile (but not desktop,
- // which always re-fetches from Firebase).
-
- await page.goto('/#/ask');
-
- // The /ask route auto-navigates to /item/ once stories load,
- // which remounts SwipeStoryViewer. Wait for that transition to complete so
- // we scroll the final instance (not the transient one from /ask).
- await expect(page).toHaveURL(/\/item\/\d+/);
-
- await waitForSwipeReady(page, 2);
-
- // Mock Ask HN items sorted by gravity: item1 (88888, has story_text) ranks
- // first (higher score), item2 (88887, no text) is second. The body text
- // should be visible at index 0 without swiping.
-
- // The body text should be visible — this comes from Algolia's story_text
- // field, NOT from a Firebase re-fetch (which is the point of the test).
- await expect(page.getByText(/curious what side projects everyone is working on/i)).toBeVisible();
- });
-
test('keeps the Ask HN body after visiting the author and going Back, and after a reload', async ({ page }) => {
// The saved swipe position stores stories without their body, and the
// restored copy is what the panel renders.
@@ -930,15 +850,6 @@ test.describe('Mobile Direct Item Access', () => {
await expect(body()).toBeVisible();
});
- test('navigating directly to a comment shows comment in swipe viewer', async ({ page }) => {
- await page.goto('/#/item/1001');
-
- // Comment author renders inside the swipe viewer — not the "not a story" guard.
- await expectActiveSwipePanelText(page, 'patio11', { timeout: 10000 });
-
- await expect(page).toHaveURL(/\/item\/1001/);
- });
-
test('opens job items on the item page', async ({ page }) => {
// The swipe viewer only takes stories, and no feed lists jobs, so a direct
// link to one gets the item page, as on desktop.
diff --git a/e2e/navigation.spec.ts b/e2e/navigation.spec.ts
index ecf7823..7d0a97c 100644
--- a/e2e/navigation.spec.ts
+++ b/e2e/navigation.spec.ts
@@ -149,18 +149,6 @@ test.describe('Navigation', () => {
await expectTopStoryVisible(page);
});
- test('logo click returns to homepage', async ({ page }) => {
- await page.goto('/#/show');
-
- const logo = page.getByRole('link', { name: /hackertok|hn|logo/i }).first();
- await logo.click();
-
- await expect(page).toHaveURL(/\/#\/(item\/\d+)?$/);
-
- // Homepage title is plain "HackerTok" — no section prefix.
- await expect(page).toHaveTitle(/HackerTok/);
- });
-
test('browser back button works', async ({ page }) => {
await page.goto('/#/');
await expectTopStoryVisible(page);
@@ -188,27 +176,6 @@ test.describe('Navigation', () => {
await expect(page).toHaveURL(/\/#\/(item\/\d+)?$/);
await expectTopStoryVisible(page);
});
-
- test('direct URL navigation works', async ({ page }) => {
- await page.goto('/#/ask');
-
- await expect(page.getByText('Ask HN:', { exact: false }).first()).toBeVisible({ timeout: 10000 });
- });
-});
-
-test.describe('Navigation - Header Visibility', () => {
- test.use({ viewport: { width: 375, height: 667 }, hasTouch: true });
-
- test.beforeEach(async ({ page }) => {
- await setupApiMocks(page);
- });
-
- test('header is visible initially', async ({ page }) => {
- await page.goto('/#/');
-
- const header = page.locator('header').first();
- await expect(header).toBeVisible();
- });
});
test.describe('Navigation - Viewport Resize Transition', () => {
diff --git a/e2e/story-browsing.spec.ts b/e2e/story-browsing.spec.ts
index 1c2c866..b2d7c1a 100644
--- a/e2e/story-browsing.spec.ts
+++ b/e2e/story-browsing.spec.ts
@@ -65,20 +65,6 @@ test.describe('Item Browsing - Desktop', () => {
await setupApiMocks(page);
});
- test('shows scrollable list on desktop', async ({ page }, testInfo) => {
- if (testInfo.project.name === 'mobile') {
- test.skip();
- return;
- }
-
- await page.goto('/#/');
-
- const swipeContainer = page.getByTestId('swipe-container');
- await expect(swipeContainer).not.toBeVisible();
-
- await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible();
- });
-
test('infinite scroll loads more items at bottom', async ({ page }, testInfo) => {
if (testInfo.project.name === 'mobile') {
test.skip();
diff --git a/e2e/theme-toggle.spec.ts b/e2e/theme-toggle.spec.ts
index 5d7bfc9..8bffb47 100644
--- a/e2e/theme-toggle.spec.ts
+++ b/e2e/theme-toggle.spec.ts
@@ -73,28 +73,6 @@ test.describe('Theme cycle button', () => {
});
test.describe('Theme - System mode', () => {
- test('system mode (default) resolves to the OS dark preference', async ({ page }) => {
- await page.emulateMedia({ colorScheme: 'dark' });
- await setupApiMocks(page);
- await page.addInitScript(() => localStorage.clear());
- await page.goto('/#/');
-
- const html = page.locator('html');
- await expect(html).toHaveClass(/dark/);
- await expect(html).not.toHaveClass(/light/);
- });
-
- test('system mode (default) resolves to the OS light preference', async ({ page }) => {
- await page.emulateMedia({ colorScheme: 'light' });
- await setupApiMocks(page);
- await page.addInitScript(() => localStorage.clear());
- await page.goto('/#/');
-
- const html = page.locator('html');
- await expect(html).toHaveClass(/light/);
- await expect(html).not.toHaveClass(/dark/);
- });
-
test('follows the OS dark preference without an error when site storage is blocked', async ({ page }) => {
await page.emulateMedia({ colorScheme: 'dark' });
await setupApiMocks(page);
diff --git a/e2e/user-profile.spec.ts b/e2e/user-profile.spec.ts
index ad290bb..ee640f8 100644
--- a/e2e/user-profile.spec.ts
+++ b/e2e/user-profile.spec.ts
@@ -1,7 +1,6 @@
import { test, expect } from '@playwright/test';
import {
setupApiMocks,
- stubNotFoundUser,
createFirebaseWsHandler,
FIREBASE_WS_PATTERN,
} from './fixtures/api-mocks';
@@ -103,24 +102,6 @@ test.describe('User Profile - Desktop', () => {
await expect(fromPill).toHaveCount(0);
await expect(commentsPill).toHaveCount(0);
});
-
- test('shows not-found state for an unknown user', async ({ page }) => {
- // Override the user route BEFORE navigation so the first fetch returns
- // null. `setupApiMocks`'s default falls through to a synthesized profile
- // for unknown ids, which would never trigger the not-found branch.
- await stubNotFoundUser(page, 'nope');
-
- await page.goto('/#/user/nope');
-
- await expect(page.getByText('User not found')).toBeVisible();
- await expect(page.getByText(/no user with the id "nope" exists/i)).toBeVisible();
-
- // Action button surfaces a path back to home so the user is not stranded.
- await expect(page.getByRole('link', { name: /back to home/i })).toBeVisible();
-
- // Document title reflects the error state, mirroring ItemDetail's pattern.
- await expect(page).toHaveTitle('User not found | HackerTok');
- });
});
test.describe('User Profile - Mobile', () => {
diff --git a/e2e/viewed-items.spec.ts b/e2e/viewed-items.spec.ts
index 74ec920..45ba384 100644
--- a/e2e/viewed-items.spec.ts
+++ b/e2e/viewed-items.spec.ts
@@ -13,27 +13,6 @@ test.describe('Viewed Items', () => {
});
});
- test('viewed items persist across page reload', async ({ page }) => {
- // '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() + 12 * 60 * 60 * 1000 };
- localStorage.setItem('viewed:times:detail', JSON.stringify(viewed));
- });
-
- await page.goto('/#/');
-
- await expect(page.getByText('Rust Is the Future of JavaScript Infrastructure').first()).toBeVisible();
-
- const viewedItems = await page.evaluate(() => {
- const stored = localStorage.getItem('viewed:times:detail');
- return stored ? JSON.parse(stored) : null;
- });
-
- expect(viewedItems).toBeTruthy();
- expect(viewedItems['12345']).toBeGreaterThan(0);
- });
-
test('viewed items have visual indication', async ({ browser, baseURL }) => {
// Fresh context bypasses the beforeEach clear so seeding survives.
const context = await browser.newContext({ baseURL, viewport: { width: 1280, height: 720 } });
diff --git a/src/api/hn.fetchTaggedStories.test.ts b/src/api/hn.fetchTaggedStories.test.ts
index de3ea96..2cbd250 100644
--- a/src/api/hn.fetchTaggedStories.test.ts
+++ b/src/api/hn.fetchTaggedStories.test.ts
@@ -84,21 +84,6 @@ describe('fetchTaggedStoriesForDay', () => {
expect(result[0].title).toBe('Ask HN: Real question');
});
- it('does not filter without excludeHiring', async () => {
- const hits = [
- makeHit(1, 'Show HN: Something', 100, ['show_hn']),
- makeHit(2, 'Show HN: Who is hiring helper', 50, ['show_hn']),
- ];
- (fetch as ReturnType).mockResolvedValue({
- ok: true,
- json: async () => mockAlgoliaResponse(hits),
- });
-
- const result = await fetchTaggedStoriesForDay('show_hn', 1);
-
- expect(result).toHaveLength(2);
- });
-
it('throws on non-OK response', async () => {
(fetch as ReturnType).mockResolvedValue({
ok: false,
@@ -123,18 +108,6 @@ describe('fetchTaggedStoriesForDay', () => {
expect(url).toContain('numericFilters=created_at_i>=');
expect(url).toContain('hitsPerPage=30');
});
-
- it('correctly maps show_hn tag to type "show"', async () => {
- const hits = [makeHit(1, 'Show HN: Test', 100, ['show_hn'])];
- (fetch as ReturnType).mockResolvedValue({
- ok: true,
- json: async () => mockAlgoliaResponse(hits),
- });
-
- const result = await fetchTaggedStoriesForDay('show_hn', 1);
-
- expect(result[0].type).toBe('show');
- });
});
describe('fetchAskStoriesForDay', () => {
diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts
index a97d001..d8d1954 100644
--- a/src/api/hn.test.ts
+++ b/src/api/hn.test.ts
@@ -37,16 +37,6 @@ const mockFirebaseItem: FirebaseItem = {
type: 'story',
};
-const mockCommentItem: FirebaseItem = {
- id: 1001,
- by: 'patio11',
- text: 'The wasm-bindgen approach is really interesting.',
- time: Math.floor(Date.now() / 1000) - 1800,
- parent: 12345,
- kids: [2001],
- type: 'comment',
-};
-
describe('hn API utilities', () => {
beforeEach(() => {
__resetFetchCachesForTests();
@@ -136,20 +126,6 @@ describe('hn API utilities', () => {
expect(formatTimeAgo(now - 365 * 24 * 60 * 60 * 1000)).toBe('1 year ago');
expect(formatTimeAgo(now - 2 * 365 * 24 * 60 * 60 * 1000)).toBe('2 years ago');
});
-
- it('uses singular form for 1 unit', () => {
- const now = Date.now();
- expect(formatTimeAgo(now - 1 * 60 * 1000)).toBe('1 minute ago');
- expect(formatTimeAgo(now - 1 * 60 * 60 * 1000)).toBe('1 hour ago');
- expect(formatTimeAgo(now - 1 * 24 * 60 * 60 * 1000)).toBe('1 day ago');
- });
-
- it('uses plural form for > 1 unit', () => {
- const now = Date.now();
- expect(formatTimeAgo(now - 2 * 60 * 1000)).toBe('2 minutes ago');
- expect(formatTimeAgo(now - 2 * 60 * 60 * 1000)).toBe('2 hours ago');
- expect(formatTimeAgo(now - 2 * 24 * 60 * 60 * 1000)).toBe('2 days ago');
- });
});
describe('formatAbsoluteTime', () => {
@@ -191,15 +167,6 @@ describe('hn API utilities', () => {
expect(result).toContain('21');
expect(result).toMatch(/\d{1,2}:\d{2}/);
});
-
- it('handles timestamps from different years', () => {
- const ts = new Date('2024-12-25T08:00:00Z').getTime();
- const result = formatAbsoluteTime(ts);
- // Locale-invariant: year + day-of-month. Month text would be "Dec" /
- // "Dez." / "déc." / "12月" depending on host locale.
- expect(result).toContain('2024');
- expect(result).toContain('25');
- });
});
describe('formatAbsoluteDate', () => {
@@ -291,11 +258,6 @@ describe('hn API utilities', () => {
expect(getHostname('https://www.google.com/search')).toBe('google.com');
});
- it('handles various protocols', () => {
- expect(getHostname('http://example.com')).toBe('example.com');
- expect(getHostname('https://example.com')).toBe('example.com');
- });
-
it('includes first path segment for GitHub URLs', () => {
expect(getHostname('https://github.com/facebook/react')).toBe('github.com/facebook');
expect(getHostname('https://github.com/vercel/next.js')).toBe('github.com/vercel');
@@ -379,23 +341,6 @@ describe('hn API utilities', () => {
expect(result.text).toBeUndefined();
});
- it('sets text to undefined when story_text is absent', () => {
- const hit = {
- objectID: '12345',
- title: 'Rust Is the Future of JavaScript Infrastructure',
- url: 'https://leerob.io/blog/rust',
- points: 284,
- author: 'leerob',
- created_at_i: nowSec - 3600,
- num_comments: 137,
- _tags: ['story', 'front_page'],
- };
-
- const result = normalizeAlgoliaHit(hit);
-
- expect(result.text).toBeUndefined();
- });
-
it('passes through empty story_text as empty string', () => {
const hit = {
objectID: '34567',
@@ -481,15 +426,6 @@ describe('hn API utilities', () => {
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => mockShowItems[Number(id)] ?? null);
});
- it('returns normalized Show HN items', async () => {
- const result = await fetchShowStories(0);
-
- expect(result.stories).toBeDefined();
- expect(result.stories.length).toBeGreaterThan(0);
- expect(result.hasMore).toBeDefined();
- expect(result.nextOffset).toBe(20);
- });
-
it('returns items with show type', async () => {
const result = await fetchShowStories(0);
@@ -498,18 +434,6 @@ describe('hn API utilities', () => {
});
});
- it('returns items with expected properties', async () => {
- const result = await fetchShowStories(0);
- const item = result.stories[0];
-
- expect(item).toHaveProperty('id');
- expect(item).toHaveProperty('title');
- expect(item).toHaveProperty('points');
- expect(item).toHaveProperty('author');
- expect(item).toHaveProperty('createdAt');
- expect(item).toHaveProperty('commentCount');
- });
-
it('returns items in ranked order (same order as ID list)', async () => {
const result = await fetchShowStories(0);
@@ -519,13 +443,6 @@ describe('hn API utilities', () => {
expect(result.stories[2].id).toBe(99997);
});
- it('returns correct pagination info', async () => {
- const result = await fetchShowStories(0);
-
- expect(result.nextOffset).toBe(20);
- expect(result.hasMore).toBe(false);
- });
-
it('paginates by offset', async () => {
const manyIds = Array.from({ length: 25 }, (_, i) => 90000 + i);
vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(manyIds);
@@ -568,15 +485,6 @@ describe('hn API utilities', () => {
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => mockAskItems[Number(id)] ?? null);
});
- it('returns normalized Ask HN items', async () => {
- const result = await fetchAskStories(0);
-
- expect(result.stories).toBeDefined();
- expect(result.stories.length).toBeGreaterThan(0);
- expect(result.hasMore).toBeDefined();
- expect(result.nextOffset).toBe(20);
- });
-
it('returns items with ask type', async () => {
const result = await fetchAskStories(0);
@@ -585,26 +493,6 @@ describe('hn API utilities', () => {
});
});
- it('returns items with expected properties', async () => {
- const result = await fetchAskStories(0);
- const item = result.stories[0];
-
- expect(item).toHaveProperty('id');
- expect(item).toHaveProperty('title');
- expect(item).toHaveProperty('points');
- expect(item).toHaveProperty('author');
- expect(item).toHaveProperty('createdAt');
- expect(item).toHaveProperty('commentCount');
- });
-
- it('handles Ask HN posts without URL', async () => {
- const result = await fetchAskStories(0);
-
- result.stories.forEach(item => {
- expect(item.url === null || item.url === undefined).toBe(true);
- });
- });
-
it('returns items in ranked order (same order as ID list)', async () => {
const result = await fetchAskStories(0);
@@ -614,13 +502,6 @@ describe('hn API utilities', () => {
expect(result.stories[2].id).toBe(88886);
});
- it('returns correct pagination info', async () => {
- const result = await fetchAskStories(0);
-
- expect(result.nextOffset).toBe(20);
- expect(result.hasMore).toBe(false);
- });
-
it('paginates by offset', async () => {
const manyIds = Array.from({ length: 25 }, (_, i) => 80000 + i);
vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(manyIds);
@@ -670,15 +551,6 @@ describe('hn API utilities', () => {
expect(hnSdk.readRankedIds).toHaveBeenCalledWith('newstories');
});
- it('returns normalized items', async () => {
- const result = await fetchNewStories(0);
-
- expect(result.stories).toBeDefined();
- expect(result.stories.length).toBeGreaterThan(0);
- expect(result.hasMore).toBeDefined();
- expect(result.nextOffset).toBe(30);
- });
-
it('returns items with story type', async () => {
const result = await fetchNewStories(0);
@@ -687,18 +559,6 @@ describe('hn API utilities', () => {
});
});
- it('returns items with expected properties', async () => {
- const result = await fetchNewStories(0);
- const item = result.stories[0];
-
- expect(item).toHaveProperty('id');
- expect(item).toHaveProperty('title');
- expect(item).toHaveProperty('points');
- expect(item).toHaveProperty('author');
- expect(item).toHaveProperty('createdAt');
- expect(item).toHaveProperty('commentCount');
- });
-
it('returns items in reverse-chronological (ID-list) order', async () => {
const result = await fetchNewStories(0);
@@ -773,33 +633,6 @@ describe('hn API utilities', () => {
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => mockTopItems[Number(id)] ?? null);
});
- it('returns normalized items from ranked list', async () => {
- const result = await fetchTopStories(20);
-
- expect(result).toBeDefined();
- expect(result.length).toBeGreaterThan(0);
- });
-
- it('returns items with expected properties', async () => {
- const result = await fetchTopStories(20);
- const item = result[0];
-
- expect(item).toHaveProperty('id');
- expect(item).toHaveProperty('title');
- expect(item).toHaveProperty('url');
- expect(item).toHaveProperty('points');
- expect(item).toHaveProperty('author');
- expect(item).toHaveProperty('createdAt');
- expect(item).toHaveProperty('commentCount');
- expect(item).toHaveProperty('type');
- });
-
- it('uses default limit of 20', async () => {
- const result = await fetchTopStories();
-
- expect(result.length).toBeLessThanOrEqual(20);
- });
-
it('returns items in ranked order (same as ID list)', async () => {
const result = await fetchTopStories(20);
@@ -820,26 +653,6 @@ describe('hn API utilities', () => {
}));
});
- it('returns items with pagination info', async () => {
- const result = await fetchBestStories(0, 30);
-
- expect(result).toHaveProperty('stories');
- expect(result).toHaveProperty('hasMore');
- expect(result).toHaveProperty('nextOffset');
- });
-
- it('returns normalized item format', async () => {
- const result = await fetchBestStories(0, 30);
- const item = result.stories[0];
-
- expect(item).toHaveProperty('id');
- expect(item).toHaveProperty('title');
- expect(item).toHaveProperty('points');
- expect(item).toHaveProperty('author');
- expect(item).toHaveProperty('createdAt');
- expect(item).toHaveProperty('commentCount');
- });
-
it('paginates correctly by offset', async () => {
const firstPage = await fetchBestStories(0, 2);
expect(firstPage.nextOffset).toBe(2);
@@ -873,7 +686,6 @@ describe('hn API utilities', () => {
beforeEach(() => {
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => {
if (Number(id) === 12345) return mockFirebaseItem;
- if (Number(id) === 1001) return mockCommentItem;
return null;
});
});
@@ -886,14 +698,6 @@ describe('hn API utilities', () => {
expect(result.title).toBe('Rust Is the Future of JavaScript Infrastructure');
});
- it('fetches a comment by ID', async () => {
- const result = await fetchFirebaseItem(1001);
-
- expect(result).toBeDefined();
- expect(result.id).toBe(1001);
- expect(result.by).toBe('patio11');
- });
-
it('supports AbortSignal for cancellation', async () => {
const controller = new AbortController();
controller.abort();
@@ -950,14 +754,6 @@ describe('hn API utilities', () => {
expect(result.id).toBe(12345);
});
- it('defaults commentCount to 0 when descendants missing', async () => {
- const result = await fetchItemOnly(12345);
- expect(result.type).not.toBe('comment');
- if (result.type === 'comment' || result.type === 'pollopt') throw new Error('unexpected');
-
- expect(result.type !== 'job' ? result.commentCount : 0).toBe(137);
- });
-
it('reads a poll option with its poll\'s title', async () => {
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => (
Number(id) === 126810
@@ -1075,10 +871,6 @@ describe('hn API utilities', () => {
expect(formatTimeAgo(0)).toBe('');
});
- it('formatTimeAgo handles negative timestamp', () => {
- expect(() => formatTimeAgo(-1000000)).not.toThrow();
- });
-
it('getHostname handles URLs with port numbers', () => {
expect(getHostname('https://localhost:3000/path')).toBe('localhost');
expect(getHostname('https://example.com:8080/page')).toBe('example.com');
@@ -1088,10 +880,6 @@ describe('hn API utilities', () => {
expect(getHostname('https://blog.example.com/post')).toBe('blog.example.com');
expect(getHostname('https://api.v2.example.com')).toBe('api.v2.example.com');
});
-
- it('getHostname handles IP addresses', () => {
- expect(getHostname('http://192.168.1.1/admin')).toBe('192.168.1.1');
- });
});
describe('fetchAlgoliaItem', () => {
@@ -1106,14 +894,6 @@ describe('hn API utilities', () => {
expect(result.parent_id).toBe(12345);
});
- it('returns children array', async () => {
- const result = await fetchAlgoliaItem(1001);
-
- expect(result.children).toHaveLength(1);
- expect(result.children[0].id).toBe(2001);
- expect(result.children[0].author).toBe('tptacek');
- });
-
it('supports AbortSignal for cancellation', async () => {
const controller = new AbortController();
controller.abort();
@@ -1165,11 +945,6 @@ describe('hn API utilities', () => {
expect(result[0].author).toBe('user1');
expect(result[1].author).toBe('user3');
});
-
- it('handles empty children array', () => {
- const result = normalizeAlgoliaItemChildren([]);
- expect(result).toEqual([]);
- });
});
describe('fetchItemWithComments', () => {
diff --git a/src/components/Comment.test.tsx b/src/components/Comment.test.tsx
index 3948037..f1b3906 100644
--- a/src/components/Comment.test.tsx
+++ b/src/components/Comment.test.tsx
@@ -49,24 +49,6 @@ describe('Comment', () => {
});
describe('rendering', () => {
- it('renders comment author', () => {
- render();
-
- expect(screen.getByText('testuser')).toBeInTheDocument();
- });
-
- it('renders comment content', () => {
- render();
-
- expect(screen.getByText('This is a test comment')).toBeInTheDocument();
- });
-
- it('renders relative time', () => {
- render();
-
- expect(screen.getByText(/hour ago/i)).toBeInTheDocument();
- });
-
it('marks the byline chevron as aria-hidden', () => {
render();
@@ -152,12 +134,11 @@ describe('Comment', () => {
expect(screen.queryByText('OP')).not.toBeInTheDocument();
});
- // 'unknown' / '' story author must NOT decorate every fallback comment
- // author — without `isKnownAuthor(storyAuthor)`, '' === '' would surface
- // the badge for every anonymous comment.
+ // 'unknown' story author must NOT decorate every fallback comment
+ // author — without `isKnownAuthor(storyAuthor)`, 'unknown' === 'unknown'
+ // would surface the badge for every anonymous comment.
it.each([
{ label: 'literal "unknown"', storyAuthor: 'unknown' },
- { label: 'empty string', storyAuthor: '' },
])(
'does not render OP badge when storyAuthor is the $label',
({ storyAuthor }) => {
@@ -194,14 +175,11 @@ describe('Comment', () => {
});
// Integration smoke test for the sanitize → dangerouslySetInnerHTML
- // path. utils/sanitize.test.ts covers sanitizeHtml exhaustively; these
- // assertions just pin that each rewritten URL family actually reaches
- // the rendered DOM via Comment.tsx (catches a refactor that bypasses
- // the rewriter for one branch).
+ // path. utils/sanitize.test.ts covers sanitizeHtml exhaustively
+ // (every URL family); this just pins that a rewritten link actually
+ // reaches the rendered DOM via Comment.tsx.
it.each([
{ kind: 'item', sourcePath: 'item?id=99999', expectedHref: '#/item/99999', expectedText: 'item:99999' },
- { kind: 'user', sourcePath: 'user?id=pg', expectedHref: '#/user/pg', expectedText: 'user:pg' },
- { kind: 'submitted', sourcePath: 'submitted?id=pg', expectedHref: '#/submitted/pg', expectedText: 'submitted:pg' },
])(
'rewrites HN $kind links in the rendered DOM',
({ sourcePath, expectedHref, expectedText }) => {
@@ -250,17 +228,6 @@ describe('Comment', () => {
expect(screen.getByText(/1 reply/i)).toBeInTheDocument();
});
- it('gates replies behind expand button at all depths', () => {
- render();
-
- expect(screen.getByText('Parent comment')).toBeInTheDocument();
- expect(screen.queryByText('Child comment')).not.toBeInTheDocument();
- expect(screen.getByText(/1 reply/i)).toBeInTheDocument();
-
- fireEvent.click(screen.getByText(/1 reply/i));
- expect(screen.getByText('Child comment')).toBeInTheDocument();
- });
-
it('shows direct children count, not total descendants', () => {
const deepComment = createComment({
id: 10,
diff --git a/src/components/CommentArticle.test.tsx b/src/components/CommentArticle.test.tsx
index fe1d129..1800420 100644
--- a/src/components/CommentArticle.test.tsx
+++ b/src/components/CommentArticle.test.tsx
@@ -115,14 +115,6 @@ describe('CommentArticle', () => {
expect(screen.queryByRole('link', { name: /some story/i })).not.toBeInTheDocument();
});
- it('shows the resolved title link (no skeleton) once itemTitle arrives', () => {
- renderArticle({ loading: false });
-
- expect(
- screen.getByRole('link', { name: 'Some story' }),
- ).toHaveAttribute('href', '/item/12345');
- });
-
it('keeps the placeholder, not the "story" fallback, while the title is still loading', () => {
render(
{
expect(screen.queryByText('OP')).not.toBeInTheDocument();
});
- it.each([
- { label: 'literal "unknown"', storyAuthor: 'unknown' },
- { label: 'empty string', storyAuthor: '' },
- ])(
- 'does not render OP badge when storyAuthor is the $label',
- ({ storyAuthor }) => {
- renderArticle({ storyAuthor });
-
- expect(screen.queryByLabelText('Original poster')).not.toBeInTheDocument();
- },
- );
-
// Sibling-pattern regression — see AuthorByline.tsx for rationale.
it('keeps the author Link accessible name unchanged when OP', () => {
renderArticle({ storyAuthor: 'patio11' });
diff --git a/src/components/CommentDetail.test.tsx b/src/components/CommentDetail.test.tsx
index 3f99c16..a754bdd 100644
--- a/src/components/CommentDetail.test.tsx
+++ b/src/components/CommentDetail.test.tsx
@@ -23,7 +23,7 @@ describe('CommentDetail', () => {
});
// Content rendering (author, text, parent link, title link, replies) is tested
- // in FullScreenComment.test.tsx. These tests focus on CommentDetail-specific behavior:
+ // in CommentArticle.test.tsx and FullScreenComment.test.tsx. These tests focus on CommentDetail-specific behavior:
// routing integration, progressive rendering, skeleton, and document title.
it('shows skeleton while loading', () => {
diff --git a/src/components/ErrorBoundary.test.tsx b/src/components/ErrorBoundary.test.tsx
index 8921701..522c25f 100644
--- a/src/components/ErrorBoundary.test.tsx
+++ b/src/components/ErrorBoundary.test.tsx
@@ -21,15 +21,6 @@ function ResetKeyHarness({ children }: { children: React.ReactNode }) {
}
describe('ErrorBoundary', () => {
- it('renders children when there is no error', () => {
- render(
-
- ok
- ,
- );
- expect(screen.getByText('ok')).toBeInTheDocument();
- });
-
it('renders error fallback when a child throws', () => {
// Suppress React's error boundary console noise
const spy = vi.spyOn(console, 'error').mockImplementation(vi.fn());
diff --git a/src/components/FullScreenComment.test.tsx b/src/components/FullScreenComment.test.tsx
index df83d7d..c25693c 100644
--- a/src/components/FullScreenComment.test.tsx
+++ b/src/components/FullScreenComment.test.tsx
@@ -45,35 +45,6 @@ describe('FullScreenComment', () => {
expect(screen.getByText(/wasm-bindgen/i)).toBeInTheDocument();
});
- it('renders parent link', async () => {
- render();
-
- const parentLink = await screen.findByRole('link', { name: 'parent' });
- expect(parentLink).toBeInTheDocument();
- expect(parentLink).toHaveAttribute('href', '/item/12345');
- });
-
- it('renders item title link after background fetch', async () => {
- render();
-
- await waitFor(() => {
- expect(screen.getByText('Rust Is the Future of JavaScript Infrastructure')).toBeInTheDocument();
- });
-
- const itemLink = screen.getByRole('link', { name: 'Rust Is the Future of JavaScript Infrastructure' });
- expect(itemLink).toHaveAttribute('href', '/item/12345');
- });
-
- it('renders replies', async () => {
- render();
-
- await waitFor(() => {
- expect(screen.getByText('tptacek')).toBeInTheDocument();
- });
-
- expect(screen.getByText(/DX improvements/i)).toBeInTheDocument();
- });
-
it('shows skeleton while loading', () => {
render();
diff --git a/src/components/FullScreenItem.test.tsx b/src/components/FullScreenItem.test.tsx
index 778ff12..7586b46 100644
--- a/src/components/FullScreenItem.test.tsx
+++ b/src/components/FullScreenItem.test.tsx
@@ -32,14 +32,6 @@ describe('FullScreenItem', () => {
});
describe('viewed state', () => {
- it('shows unviewed title color by default', async () => {
- render();
-
- const heading = await screen.findByRole('heading', { level: 1 });
- expect(heading).toHaveClass('text-foreground');
- expect(heading).not.toHaveClass('text-viewed');
- });
-
it('shows viewed title color when story was previously viewed', async () => {
markViewed(12345);
render();
diff --git a/src/components/Header.test.tsx b/src/components/Header.test.tsx
index 3a6bb93..d62bd55 100644
--- a/src/components/Header.test.tsx
+++ b/src/components/Header.test.tsx
@@ -103,11 +103,6 @@ describe('Header', () => {
const linkRe = new RegExp(label, 'i');
const getLink = () => screen.getByRole('link', { name: linkRe });
- it(`renders the ${key} navigation link`, () => {
- render();
- expect(getLink()).toBeInTheDocument();
- });
-
it(`highlights ${key} on ${route} route`, () => {
render(, { initialEntries: [route] });
expect(getLink()).toHaveAttribute('aria-current', 'page');
@@ -358,24 +353,6 @@ describe('Header', () => {
});
expect(indicator).toHaveAttribute('aria-current', 'page');
});
-
- it('marks the active contextual pill (user) with aria-current="page"', () => {
- render(, { initialEntries: ['/submitted/pg'] });
-
- const indicator = screen.getByText('user', {
- selector: 'header nav span',
- });
- expect(indicator).toHaveAttribute('aria-current', 'page');
- });
-
- it('marks the active contextual pill (from) with aria-current="page"', () => {
- render(, { initialEntries: ['/from/example.com'] });
-
- const indicator = screen.getByText('from', {
- selector: 'header nav span',
- });
- expect(indicator).toHaveAttribute('aria-current', 'page');
- });
});
describe('nav DOM order', () => {
@@ -455,8 +432,6 @@ describe('Header', () => {
it.each([
['/best', 'best'],
- ['/show', 'show'],
- ['/ask', 'ask'],
['/newest', 'newest'],
['/submitted/pg', 'user'],
['/from/example.com', 'from'],
diff --git a/src/components/InfiniteStoryListPage.test.tsx b/src/components/InfiniteStoryListPage.test.tsx
index ec80fb7..5943150 100644
--- a/src/components/InfiniteStoryListPage.test.tsx
+++ b/src/components/InfiniteStoryListPage.test.tsx
@@ -7,7 +7,6 @@ import { createStoryItem } from '../test/factories';
import {
InfiniteStoryListPage,
type InfiniteStoryListResult,
- type StoryCardExtras,
} from './InfiniteStoryListPage';
// `useAutoRetry` triggers a backoff schedule (2/4/8s) on every render
@@ -37,7 +36,6 @@ function makeResult(
function renderPage(props: {
result: InfiniteStoryListResult;
- storyCardExtras?: StoryCardExtras;
emptyTitle?: string;
failTitle?: string;
}) {
@@ -51,7 +49,6 @@ function renderPage(props: {
element={
@@ -343,24 +340,4 @@ describe('InfiniteStoryListPage', () => {
expect(onLoadMore).toHaveBeenCalledTimes(3);
});
});
-
- describe('storyCardExtras forwarding', () => {
- it('forwards fromUser into the story card byline so links carry the origin', () => {
- const stories = [
- createStoryItem({ id: 12345, title: 'User submission', commentCount: 7 }),
- ];
-
- renderPage({
- result: makeResult({ stories, hasMore: false }),
- storyCardExtras: { fromUser: 'leerob' },
- });
-
- // href is the easiest assertion against `to={`/item/${id}`}`. The
- // location.state forwarding (which carries `fromUser`) is
- // exercised by StoryCard.test.tsx; we only need to confirm the
- // prop survives the boundary here.
- const commentsLink = screen.getByRole('link', { name: /7 comments/ });
- expect(commentsLink).toHaveAttribute('href', '/item/12345');
- });
- });
});
diff --git a/src/components/NetworkStatusBar.test.tsx b/src/components/NetworkStatusBar.test.tsx
index 42e0507..05d5824 100644
--- a/src/components/NetworkStatusBar.test.tsx
+++ b/src/components/NetworkStatusBar.test.tsx
@@ -76,12 +76,6 @@ describe('NetworkStatusBar', () => {
).toBe('0px');
});
- it('does not show "Back online" if never went offline', () => {
- mockUseNetworkStatus.mockReturnValue({ isOnline: true });
- const { container } = render();
- expect(container.firstChild).toBeNull();
- });
-
it('resets --network-bar-height on unmount', () => {
mockUseNetworkStatus.mockReturnValue({ isOnline: false });
const { unmount } = render();
diff --git a/src/components/PageStage.test.tsx b/src/components/PageStage.test.tsx
index ca3f05b..e239287 100644
--- a/src/components/PageStage.test.tsx
+++ b/src/components/PageStage.test.tsx
@@ -180,61 +180,4 @@ describe('PageStage', () => {
expect(wrapper).toHaveClass('fade-skeleton');
expect(wrapper).not.toHaveClass('play-real');
});
-
- it('resets to skeleton when loading flips back to true', () => {
- const { rerender } = render(
- skel }>
- content
- ,
- );
-
- // Land in 'done'.
- act(() => {
- vi.advanceTimersByTime(1300);
- });
- const wrapper = screen.getByTestId('real').closest('.page-stage')!;
- expect(wrapper).toHaveClass('fade-skeleton');
- expect(wrapper).not.toHaveClass('play-real');
-
- // Refresh: loading flips back to true. Wrapper must reset to
- // 'skeleton' (no fade-skeleton, no play-real) and re-mount the
- // overlay so the next fetch shows a skeleton instead of stale
- // content.
- rerender(
- skel }>
-
content
- ,
- );
-
- expect(wrapper).not.toHaveClass('fade-skeleton');
- expect(wrapper).not.toHaveClass('play-real');
- expect(screen.getByTestId('skel')).toBeInTheDocument();
- });
-
- // Regression for the CSS opacity-scope bug: the
- // .page-stage:not(.fade-skeleton) .stagger-fade { opacity: 0 } rule
- // is scoped so it ONLY applies in the 'skeleton' state. Without that
- // scope, removing play-real at t=1200ms would unset the animation
- // property and elements would snap back to opacity 0. This test
- // pins the post-cascade class projection — if the wrapper ever
- // KEEPS play-real (or LOSES fade-skeleton) in 'done', infinite-
- // scroll appended cards would either keep animating or jump to
- // opacity 0.
- it('reaches done with `fade-skeleton` set and `play-real` cleared', () => {
- render(
-
skel}>
-
- content
-
- ,
- );
-
- act(() => {
- vi.advanceTimersByTime(1300);
- });
-
- const wrapper = screen.getByTestId('real').closest('.page-stage')!;
- expect(wrapper.className).toContain('fade-skeleton');
- expect(wrapper.className).not.toContain('play-real');
- });
});
diff --git a/src/components/StateView.test.tsx b/src/components/StateView.test.tsx
index 9b10e94..0e1ca9c 100644
--- a/src/components/StateView.test.tsx
+++ b/src/components/StateView.test.tsx
@@ -19,26 +19,11 @@ describe('StateView', () => {
// pass nothing get a sensible default. Pin the text so a future copy
// change is intentional rather than silent.
- it('uses default title for "not-found" when no title prop is provided', () => {
- render(
);
- expect(screen.getByText('Item not found')).toBeInTheDocument();
- });
-
it('uses default title for "error" when no title prop is provided', () => {
render(
);
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});
- it('uses default title for "empty" when no title prop is provided', () => {
- render(
);
- expect(screen.getByText('No comments yet.')).toBeInTheDocument();
- });
-
- it('uses default title for "deleted" when no title prop is provided', () => {
- render(
);
- expect(screen.getByText('Comment deleted')).toBeInTheDocument();
- });
-
it('uses default description for "end" when no description prop is provided', () => {
render(
);
expect(screen.getByText("You've reached the end")).toBeInTheDocument();
diff --git a/src/components/StoryCard.test.tsx b/src/components/StoryCard.test.tsx
index e4305eb..30c2db2 100644
--- a/src/components/StoryCard.test.tsx
+++ b/src/components/StoryCard.test.tsx
@@ -48,58 +48,12 @@ describe('StoryCard', () => {
});
describe('rendering', () => {
- it('renders story title', () => {
- render(
);
-
- expect(screen.getByText('Rust Is the Future of JavaScript Infrastructure')).toBeInTheDocument();
- });
-
- it('renders hostname for external links', () => {
- render(
);
-
- // getByRole('link', { name }) — Globe icon is aria-hidden, so the
- // link's accessible name is just the hostname (no "Globe " prefix).
- expect(screen.getByRole('link', { name: 'example.com' })).toBeInTheDocument();
- });
-
- it('renders points count', () => {
- render(
);
-
- expect(screen.getByText(/100/)).toBeInTheDocument();
- });
-
- it('renders author name', () => {
- render(
);
-
- // User icon is aria-hidden — link's accessible name is just the handle.
- expect(screen.getByRole('link', { name: 'testuser' })).toBeInTheDocument();
- });
-
- it('renders comment count', () => {
- render(
);
-
- expect(screen.getByText(/42/)).toBeInTheDocument();
- });
-
it('renders relative time', () => {
render(
);
expect(screen.getByText(/hour ago/i)).toBeInTheDocument();
});
- // Pin the responsive variant — a refactor that drops md:text-xl
- // back to text-base degrades the visual anchor at desktop width.
- it('renders title with responsive size classes (text-lg md:text-xl)', () => {
- render(
);
-
- const titleLink = screen.getByRole('link', { name: mockStory.title });
- const title = titleLink.closest('h2');
- expect(title).not.toBeNull();
- expect(title).toHaveClass('text-lg');
- expect(title).toHaveClass('md:text-xl');
- expect(title).toHaveClass('font-semibold');
- });
-
it('renders "0 points" when points is missing (Algolia/Firebase oddity)', () => {
// Algolia can omit points (or send null) for very old items. The
// `?? 0` fallback keeps the meta-row column count stable; dropping
@@ -172,13 +126,6 @@ describe('StoryCard', () => {
});
describe('viewed state', () => {
- it('applies unviewed styles by default', () => {
- render(
);
-
- const titleLink = screen.getByRole('link', { name: /Ask HN/i });
- expect(titleLink).toHaveClass('text-foreground');
- });
-
it('applies viewed styles when story was previously title-clicked', () => {
markViewedWithTime(mockTextStory.id, 'title');
render(
);
@@ -318,28 +265,6 @@ describe('StoryCard', () => {
});
describe('navigation state', () => {
- it('passes listType in navigation state for internal title links', () => {
- render(
);
-
- const titleLink = screen.getByRole('link', { name: /Ask HN/i });
- // React Router Link renders with the destination path
- expect(titleLink).toHaveAttribute('href', expect.stringContaining('/item/67890'));
- });
-
- it('passes listType in navigation state for comments links', () => {
- render(
);
-
- const commentsLink = screen.getByRole('link', { name: /42 comments/i });
- expect(commentsLink).toHaveAttribute('href', expect.stringContaining('/item/12345'));
- });
-
- it('defaults listType to top when not specified', () => {
- render(
);
-
- const titleLink = screen.getByRole('link', { name: /Ask HN/i });
- expect(titleLink).toHaveAttribute('href', expect.stringContaining('/item/67890'));
- });
-
it('writes state.fromDomain (not state.from) when fromDomain prop is set', () => {
// Mount under a Routes tree so we can follow the click and read
// back what landed in location.state via StateEchoer.
diff --git a/src/components/SwipeCommentViewer.test.tsx b/src/components/SwipeCommentViewer.test.tsx
index a4776ed..6e3fd83 100644
--- a/src/components/SwipeCommentViewer.test.tsx
+++ b/src/components/SwipeCommentViewer.test.tsx
@@ -40,23 +40,6 @@ describe('SwipeCommentViewer', () => {
server.resetHandlers();
});
- it('renders swipe container with skeleton while loading', async () => {
- render(
, {
- initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }],
- });
-
- const container = screen.getByTestId('swipe-container');
- expect(container).toBeInTheDocument();
-
- const panels = screen.getAllByTestId('swipe-panel');
- expect(panels.length).toBeGreaterThanOrEqual(1);
-
- // Let async updates settle to avoid act() warnings
- await waitFor(() => {
- expect(screen.getAllByTestId('swipe-panel').length).toBeGreaterThanOrEqual(1);
- });
- });
-
it('does not throw on a back-forward cache restore with site storage blocked', async () => {
window.scrollTo = vi.fn();
render(
, {
@@ -112,22 +95,6 @@ describe('SwipeCommentViewer', () => {
expect(window.scrollTo).toHaveBeenLastCalledWith(0, 500);
});
- it('renders sibling comment panels after loading', async () => {
- render(
, {
- initialEntries: [{ pathname: '/item/1001', state: { isComment: true } }],
- });
-
- // Parent 12345 has kids: [1001, 1002, 1003, 1004] → 4 panels.
- await waitFor(() => {
- const panels = screen.getAllByTestId('swipe-panel');
- expect(panels.length).toBe(4);
- });
-
- await waitFor(() => {
- expect(screen.getByText('patio11')).toBeInTheDocument();
- });
- });
-
it('shows error state when Firebase fetch fails', async () => {
vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Server Error'));
diff --git a/src/components/ThemeToggle.test.tsx b/src/components/ThemeToggle.test.tsx
index 571f86e..b5a8c0d 100644
--- a/src/components/ThemeToggle.test.tsx
+++ b/src/components/ThemeToggle.test.tsx
@@ -31,16 +31,6 @@ function renderToggle() {
}
describe('ThemeToggle', () => {
- it('shows the System icon and the "switch to Light" label by default', () => {
- renderToggle();
-
- expect(screen.getByTestId('icon-sunmoon')).toBeInTheDocument();
- expect(screen.getByTestId('theme-toggle')).toHaveAttribute(
- 'aria-label',
- 'Theme: System. Switch to Light.',
- );
- });
-
it('cycles icon + label on click: system → light → dark → system', () => {
renderToggle();
const button = screen.getByTestId('theme-toggle');
diff --git a/src/context/ScrollContainerContext.test.tsx b/src/context/ScrollContainerContext.test.tsx
index c20bf34..3bcbc10 100644
--- a/src/context/ScrollContainerContext.test.tsx
+++ b/src/context/ScrollContainerContext.test.tsx
@@ -1,5 +1,4 @@
import { describe, it, expect } from 'vitest';
-import { render, screen } from '@testing-library/react';
import { renderHook, act } from '@testing-library/react';
import type { ReactNode } from 'react';
import { ScrollContainerProvider } from './ScrollContainerContext';
@@ -11,8 +10,6 @@ describe('ScrollContainerContext', () => {
const { result } = renderHook(() => useScrollContainer());
expect(result.current.isSwipeMode).toBe(false);
- expect(typeof result.current.enableSwipeMode).toBe('function');
- expect(typeof result.current.disableSwipeMode).toBe('function');
});
it('default functions are no-ops', () => {
@@ -34,16 +31,6 @@ describe('ScrollContainerContext', () => {
expect(result.current.isSwipeMode).toBe(false);
});
- it('enableSwipeMode sets isSwipeMode to true', () => {
- const { result } = renderHook(() => useScrollContainer(), { wrapper });
-
- act(() => {
- result.current.enableSwipeMode();
- });
-
- expect(result.current.isSwipeMode).toBe(true);
- });
-
it('disableSwipeMode sets isSwipeMode to false', () => {
const { result } = renderHook(() => useScrollContainer(), { wrapper });
@@ -60,16 +47,6 @@ describe('ScrollContainerContext', () => {
expect(result.current.isSwipeMode).toBe(false);
});
- it('enableSwipeMode adds swipe-mode class to body', () => {
- const { result } = renderHook(() => useScrollContainer(), { wrapper });
-
- act(() => {
- result.current.enableSwipeMode();
- });
-
- expect(document.body.classList.contains('swipe-mode')).toBe(true);
- });
-
it('disableSwipeMode removes swipe-mode class from body', () => {
const { result } = renderHook(() => useScrollContainer(), { wrapper });
@@ -86,16 +63,4 @@ describe('ScrollContainerContext', () => {
expect(document.body.classList.contains('swipe-mode')).toBe(false);
});
});
-
- describe('ScrollContainerProvider', () => {
- it('renders children', () => {
- render(
-
- Test Child
-
- );
-
- expect(screen.getByTestId('child')).toBeInTheDocument();
- });
- });
});
diff --git a/src/hooks/useCanSwipe.test.ts b/src/hooks/useCanSwipe.test.ts
index d1fb74d..14c0685 100644
--- a/src/hooks/useCanSwipe.test.ts
+++ b/src/hooks/useCanSwipe.test.ts
@@ -1,23 +1,18 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
+import { renderHook } from '@testing-library/react';
// Answers per query, because this hook asks two and they disagree — that is the
// whole point of it. Installed before the import: the module caches one
// MediaQueryList per query on first use.
const answers = new Map
();
-const listeners = new Map void)[]>();
const matchMediaMock = vi.fn((query: string) => ({
get matches() {
return answers.get(query) ?? false;
},
media: query,
- addEventListener: (_event: string, callback: () => void) => {
- listeners.set(query, [...(listeners.get(query) ?? []), callback]);
- },
- removeEventListener: (_event: string, callback: () => void) => {
- listeners.set(query, (listeners.get(query) ?? []).filter(l => l !== callback));
- },
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
}));
window.matchMedia = matchMediaMock as unknown as typeof window.matchMedia;
@@ -27,16 +22,9 @@ const TOUCH = '(pointer: coarse) and (hover: none)';
const { useCanSwipe } = await import('./useCanSwipe');
-function fire(query: string) {
- act(() => {
- (listeners.get(query) ?? []).forEach(l => l());
- });
-}
-
describe('useCanSwipe', () => {
beforeEach(() => {
answers.clear();
- listeners.clear();
});
it('asks for a finger as well as a width', () => {
@@ -71,27 +59,4 @@ describe('useCanSwipe', () => {
const { result } = renderHook(() => useCanSwipe());
expect(result.current).toBe(false);
});
-
- it('follows a pointer that changes mid-session', () => {
- // A tablet with a keyboard case attached reports a fine pointer from then
- // on, and has to be moved off a gesture it can no longer perform.
- answers.set(DESKTOP, false);
- answers.set(TOUCH, true);
- const { result } = renderHook(() => useCanSwipe());
- expect(result.current).toBe(true);
-
- answers.set(TOUCH, false);
- fire(TOUCH);
- expect(result.current).toBe(false);
- });
-
- it('drops both listeners on unmount', () => {
- const { unmount } = renderHook(() => useCanSwipe());
- expect(listeners.get(DESKTOP)).toHaveLength(1);
- expect(listeners.get(TOUCH)).toHaveLength(1);
-
- unmount();
- expect(listeners.get(DESKTOP)).toHaveLength(0);
- expect(listeners.get(TOUCH)).toHaveLength(0);
- });
});
diff --git a/src/hooks/useCommentDetail.test.ts b/src/hooks/useCommentDetail.test.ts
index 05fb9c6..ca24499 100644
--- a/src/hooks/useCommentDetail.test.ts
+++ b/src/hooks/useCommentDetail.test.ts
@@ -53,14 +53,6 @@ describe('useCommentDetail', () => {
expect(result.current.error).toBeNull();
});
- it('fetches item title in background', async () => {
- const { result } = renderHook(() => useCommentDetail(1001));
-
- await waitFor(() => {
- expect(result.current.itemTitle).toBe('Rust Is the Future of JavaScript Infrastructure');
- });
- });
-
it('reports the item title as loading until its fetch settles', async () => {
let resolveStory!: (item: FirebaseItem) => void;
vi.spyOn(hnSdk, 'readItem').mockImplementation(() => new Promise(resolve => { resolveStory = resolve; }));
diff --git a/src/hooks/useDomainInfiniteStories.test.ts b/src/hooks/useDomainInfiniteStories.test.ts
index 0797d9f..355d705 100644
--- a/src/hooks/useDomainInfiniteStories.test.ts
+++ b/src/hooks/useDomainInfiniteStories.test.ts
@@ -140,16 +140,12 @@ describe('canonicalizeDomain', () => {
// this the helper strips only one `/` and one `.`, which leaves residue
// for inputs that mix them (e.g. `foo.com/.` → `foo.com/` on the old
// single-strip pipeline).
- ['collapses interleaved trailing dot+slash (./)', 'github.com./', 'github.com'],
['collapses interleaved trailing slash+dot (/.)', 'github.com/.', 'github.com'],
- ['collapses multiple trailing dots', 'github.com..', 'github.com'],
- ['collapses multiple trailing slashes', 'github.com//', 'github.com'],
['collapses arbitrary trailing run of dots and slashes', 'github.com...//.', 'github.com'],
// Multi-level www. prefixes are fully stripped. This closes a latent
// drift between wrappers (one canonicalization pass) and the hook
// (which re-canonicalizes its input) for `www.www.X`-style inputs.
['collapses doubled leading www.', 'www.www.example.com', 'example.com'],
- ['collapses triple leading www.', 'www.www.www.example.com', 'example.com'],
['collapses mixed-case doubled leading www. (case-insensitive)', 'WWW.Www.Example.COM', 'example.com'],
['preserves www-lookalike after a legitimate www strip', 'www.www2.example.com', 'www2.example.com'],
])('%s', (_label, input, expected) => {
@@ -162,23 +158,11 @@ describe('canonicalizeDomain', () => {
// form) would drift from the hook's cache key (written from the two-pass
// form) for any input where a second pass produces a different result.
it.each([
- ['github.com'],
- ['GitHub.COM'],
- ['github.com/'],
- ['github.com.'],
- ['www.github.com'],
- ['Www.GitHub.com'],
['WWW.GitHub.COM./'],
['github.com/Microsoft'],
- ['www2.example.com'],
- ['api.www.example.com'],
- [''],
// The inputs that originally motivated the idempotency fix:
['www.www.example.com'],
- ['www.www.www.example.com'],
- ['github.com./'],
['github.com/.'],
- ['github.com..'],
['github.com...//.'],
])('is idempotent for %s', (input) => {
const once = canonicalizeDomain(input);
@@ -295,13 +279,6 @@ describe('useDomainInfiniteStories', () => {
it('shares the cache across trailing-slash variants of the same domain', async () => {
await expectRemountHitsCache('alpha.com', 'alpha.com/');
});
-
- // Direct hits like `/from/www.alpha.com` share the canonical form
- // `alpha.com` with `/from/alpha.com`; the second mount must hit the
- // cache and skip the fetch (same invariant as the trailing-slash test).
- it('shares the cache across www.-prefixed variants of the same domain', async () => {
- await expectRemountHitsCache('alpha.com', 'www.alpha.com');
- });
});
describe('error handling', () => {
@@ -512,11 +489,6 @@ describe('useDomainInfiniteStories', () => {
expect(ids).toEqual([1]);
});
- it('treats trailing DNS dot as equivalent (domain prop side)', async () => {
- const ids = await loadDomain('github.com.', ['https://github.com/foo']);
- expect(ids).toEqual([1]);
- });
-
// Regression: the URL-hostname side strips `^www\.` before comparing.
// Without mirroring the same strip on the domain prop, a route like
// `/from/www.example.com` would never match a hit from `example.com`
@@ -532,32 +504,6 @@ describe('useDomainInfiniteStories', () => {
expect(ids).toEqual([1]);
});
- it('matches www-prefixed URL against a www-prefixed domain prop', async () => {
- const ids = await loadDomain('www.example.com', [
- 'https://www.example.com/foo',
- ]);
- expect(ids).toEqual([1]);
- });
-
- it('canonicalizes www. prop case-insensitively (Www./WWW. variants)', async () => {
- // The strip is `^www\.` case-insensitive; `Www.Foo.com` should
- // canonicalize identically to `www.foo.com` → `foo.com`.
- const ids = await loadDomain('WWW.Example.com/', [
- 'https://example.com/foo',
- ]);
- expect(ids).toEqual([1]);
- });
-
- // Guards against an over-eager strip: the `^www\.` anchor must require a
- // literal leading "www." — a domain like "www2.example.com" is a separate
- // host and should NOT collapse to `example.com`.
- it('does not strip www-lookalike prefixes (www2., ww., www-cdn.)', async () => {
- const ids = await loadDomain('www2.example.com', [
- 'https://example.com/foo',
- ]);
- expect(ids).toEqual([]);
- });
-
// Defense in depth: WHATWG `new URL` parses non-special schemes such
// that `javascript://github.com/%0Aalert(1)` yields hostname=github.com.
// Without the protocol allowlist, such hits would surface under
diff --git a/src/hooks/useInfiniteStories.algoliaFallback.test.ts b/src/hooks/useInfiniteStories.algoliaFallback.test.ts
index d95c27f..72f0359 100644
--- a/src/hooks/useInfiniteStories.algoliaFallback.test.ts
+++ b/src/hooks/useInfiniteStories.algoliaFallback.test.ts
@@ -133,25 +133,6 @@ describe('useInfiniteStories – Ask/Show Algolia fallback', () => {
expect(result.current.hasMore).toBe(true); // Still has more (not at 365)
});
- it('sets hasMore=false after reaching 365 days with no results', async () => {
- const smallList = [1];
- vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(smallList);
- vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => makeFirebaseItem(Number(id)));
-
- globalThis.fetch = vi.fn().mockResolvedValue(mockAlgoliaResponse([]));
-
- const { result } = renderHook(() => useInfiniteStories('ask'));
-
- // Exhaust Firebase
- await act(() => result.current.loadMore());
-
- // Simulate being at day 364 by manipulating position via session restore
- // Instead, we'll just call loadMore many times; but that's slow.
- // Let's verify the boundary by testing positionRef >= 365 path via session restore.
- // This is covered more practically by the session restore test below.
- expect(result.current.hasMore).toBe(true);
- });
-
it('reset() returns to firebase phase', async () => {
const smallList = [1, 2];
vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(smallList);
diff --git a/src/hooks/useInfiniteStories.test.ts b/src/hooks/useInfiniteStories.test.ts
index 6d39e64..ed044cd 100644
--- a/src/hooks/useInfiniteStories.test.ts
+++ b/src/hooks/useInfiniteStories.test.ts
@@ -44,18 +44,6 @@ describe('useInfiniteStories', () => {
vi.restoreAllMocks();
});
- it('loads stories on first loadMore when no cache', async () => {
- const { result } = renderHook(() => useInfiniteStories('top'));
-
- expect(result.current.stories).toHaveLength(0);
- expect(result.current.hasMore).toBe(true);
-
- await act(() => result.current.loadMore());
-
- expect(result.current.stories.length).toBeGreaterThan(0);
- expect(result.current.loading).toBe(false);
- });
-
it('initializes from cache and marks isFromCache', () => {
const cached = Array.from({ length: 20 }, (_, i) =>
createStoryItem({ id: i + 1, title: `Cached Story ${i + 1}` }),
@@ -69,44 +57,6 @@ describe('useInfiniteStories', () => {
expect(result.current.loading).toBe(false);
});
- it('replaces stories on revalidation when loadMore is called early (position 0)', async () => {
- const cached = Array.from({ length: 20 }, (_, i) =>
- createStoryItem({ id: i + 1, title: `Cached Story ${i + 1}` }),
- );
- setCachedFeed('top', cached);
-
- const { result } = renderHook(() => useInfiniteStories('top'));
-
- // Starts from cache
- expect(result.current.stories).toHaveLength(20);
- expect(result.current.isFromCache).toBe(true);
-
- // First loadMore triggers revalidation (replaces stories)
- await act(() => result.current.loadMore());
-
- expect(result.current.isFromCache).toBe(false);
- // Stories are replaced with fresh data from MSW (default handler returns 20 stories)
- expect(result.current.stories.length).toBeGreaterThan(0);
- });
-
- it('appends stories on second loadMore after revalidation', async () => {
- const cached = Array.from({ length: 20 }, (_, i) =>
- createStoryItem({ id: i + 1, title: `Cached Story ${i + 1}` }),
- );
- setCachedFeed('top', cached);
-
- const { result } = renderHook(() => useInfiniteStories('top'));
-
- // First loadMore: revalidation (replace)
- await act(() => result.current.loadMore());
- const afterRevalidation = result.current.stories.length;
-
- // Second loadMore: should APPEND, not replace
- await act(() => result.current.loadMore());
-
- expect(result.current.stories.length).toBeGreaterThanOrEqual(afterRevalidation);
- });
-
it('starts one request when loadMore is called twice before re-rendering', async () => {
const { result } = renderHook(() => useInfiniteStories('top'));
diff --git a/src/hooks/useIsMobileLayout.test.ts b/src/hooks/useIsMobileLayout.test.ts
index e76e518..7be652d 100644
--- a/src/hooks/useIsMobileLayout.test.ts
+++ b/src/hooks/useIsMobileLayout.test.ts
@@ -1,21 +1,15 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
+import { renderHook } from '@testing-library/react';
// Installed before the import: the module caches its MediaQueryList on first
// use. `currentMatches` is the query's answer, and the query is the desktop side.
let currentMatches = false;
-const listeners: (() => void)[] = [];
const matchMediaMock = vi.fn((query: string) => ({
get matches() { return currentMatches; },
media: query,
- addEventListener: (_event: string, callback: () => void) => {
- listeners.push(callback);
- },
- removeEventListener: (_event: string, callback: () => void) => {
- const idx = listeners.indexOf(callback);
- if (idx !== -1) listeners.splice(idx, 1);
- },
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
}));
window.matchMedia = matchMediaMock as unknown as typeof window.matchMedia;
@@ -24,7 +18,6 @@ const { useIsMobileLayout } = await import('./useIsMobileLayout');
describe('useIsMobileLayout', () => {
beforeEach(() => {
- listeners.length = 0;
currentMatches = false;
});
@@ -46,25 +39,4 @@ describe('useIsMobileLayout', () => {
const { result } = renderHook(() => useIsMobileLayout());
expect(result.current).toBe(true);
});
-
- it('updates when the media query changes', () => {
- currentMatches = true;
- const { result } = renderHook(() => useIsMobileLayout());
- expect(result.current).toBe(false);
-
- act(() => {
- currentMatches = false;
- listeners.forEach(l => l());
- });
-
- expect(result.current).toBe(true);
- });
-
- it('cleans up its listener on unmount', () => {
- const { unmount } = renderHook(() => useIsMobileLayout());
- expect(listeners).toHaveLength(1);
-
- unmount();
- expect(listeners).toHaveLength(0);
- });
});
diff --git a/src/hooks/useItemWithComments.test.tsx b/src/hooks/useItemWithComments.test.tsx
index 1ad2b1f..8da2da2 100644
--- a/src/hooks/useItemWithComments.test.tsx
+++ b/src/hooks/useItemWithComments.test.tsx
@@ -7,7 +7,7 @@ import { _resetForTesting, isPriorityFetchActive } from '../utils/fetchPriority'
import { server } from '../mocks/server';
import { hnSdk } from '../api/hnSdk';
import { ALGOLIA_API } from '../config/api';
-import type { Comment, FirebaseItem } from '../types';
+import type { FirebaseItem } from '../types';
import { createStoryItem, createComment } from '../test/factories';
import { NetworkStatusProvider } from '../context/NetworkStatusContext';
import type { ReactNode } from 'react';
@@ -70,18 +70,6 @@ describe('useItemWithComments', () => {
expect(result.current.item!.id).toBe(12345);
});
- it('returns cached data without fetching', async () => {
- setCachedItem(12345, testItem, testComments);
-
- const { result } = renderHook(() => useItemWithComments(12345));
-
- // Cache hit must skip the loading flash entirely.
- expect(result.current.itemLoading).toBe(false);
- expect(result.current.commentsLoading).toBe(false);
- expect(result.current.item).toEqual(testItem);
- expect(result.current.comments).toEqual(testComments);
- });
-
it('reads the cache when it mounts, not on every render', () => {
setCachedItem(12345, testItem, testComments);
const cached = localStorage.getItem(`${ITEM_CACHE_KEY_PREFIX}12345`);
@@ -186,41 +174,6 @@ describe('useItemWithComments', () => {
});
});
- describe('cache sync after prefetch', () => {
- it('syncs comments from cache when prefetch completes after mount', async () => {
- const { result } = renderHook(() =>
- useItemWithComments(12345, {
- initialItem: testItem,
- deferComments: true
- })
- );
-
- expect(result.current.comments).toBeNull();
-
- // Background prefetch fills the cache while the hook is still deferred.
- await act(async () => {
- setCachedItem(12345, testItem, testComments);
- });
-
- const { result: result2, rerender } = renderHook(
- ({ deferComments }) => useItemWithComments(12345, {
- initialItem: testItem,
- deferComments
- }),
- { initialProps: { deferComments: true } }
- );
-
- expect(getCachedItem(12345)?.comments).toEqual(testComments);
-
- // Flipping deferComments off must pick up the prefetched cache, not refetch.
- rerender({ deferComments: false });
-
- await waitFor(() => {
- expect(result2.current.comments).toEqual(testComments);
- });
- });
- });
-
describe('priority fetch lifecycle', () => {
it('registers priority on fetch start and unregisters on success', async () => {
expect(isPriorityFetchActive()).toBe(false);
@@ -324,31 +277,6 @@ describe('useItemWithComments', () => {
AbortController.prototype.abort = originalAbort;
});
- it('aborts fetch when itemId changes', async () => {
- const abortSpy = vi.fn();
- const originalAbort = AbortController.prototype.abort;
- AbortController.prototype.abort = function() {
- abortSpy();
- return originalAbort.call(this);
- };
-
- const { result, rerender } = renderHook(
- ({ itemId }) => useItemWithComments(itemId),
- { initialProps: { itemId: 12345 } }
- );
-
- rerender({ itemId: 99999 });
-
- expect(abortSpy).toHaveBeenCalled();
-
- AbortController.prototype.abort = originalAbort;
-
- // Let async updates settle to avoid act() warnings
- await waitFor(() => {
- expect(result.current.itemLoading).toBe(false);
- });
- });
-
it('does NOT abort when deferComments changes to true (same itemId)', async () => {
// Mobile swipe scenario: item at index 0 starts fetching, then the user
// swipes away so it becomes deferred. The in-flight fetch must complete
@@ -444,69 +372,7 @@ describe('useItemWithComments', () => {
});
});
- describe('refresh function', () => {
- it('provides a refresh function that reloads data', async () => {
- const { result } = renderHook(() => useItemWithComments(12345));
-
- await waitFor(() => {
- expect(result.current.item).toBeTruthy();
- });
-
- await act(async () => {
- await result.current.refresh();
- });
-
- expect(result.current.item).toBeTruthy();
- expect(typeof result.current.refresh).toBe('function');
- });
- });
-
- describe('loading states', () => {
- it('has separate loading states for item and comments', async () => {
- const { result } = renderHook(() => useItemWithComments(12345));
-
- expect(result.current.itemLoading).toBe(true);
- expect(result.current.commentsLoading).toBe(true);
-
- await waitFor(() => {
- expect(result.current.itemLoading).toBe(false);
- expect(result.current.commentsLoading).toBe(false);
- });
- });
-
- it('combined loading is true only when both are loading', async () => {
- setCachedItem(12345, testItem, null as unknown as Comment[]); // Item cached, no comments
-
- const { result } = renderHook(() => useItemWithComments(12345));
-
- // `loading` is itemLoading && commentsLoading; one false ⇒ combined false.
- expect(result.current.loading).toBe(false);
- });
- });
-
describe('stale cache revalidation', () => {
- it('revalidates when cache is stale', async () => {
- // Hand-write a stale entry (10m old) past the freshness threshold so
- // the hook serves it immediately AND fires a background revalidation.
- const CACHE_KEY = `${ITEM_CACHE_KEY_PREFIX}12345`;
- const staleData = {
- item: testItem,
- comments: testComments,
- timestamp: Date.now() - (10 * 60 * 1000),
- };
- localStorage.setItem(CACHE_KEY, JSON.stringify(staleData));
-
- const { result } = renderHook(() => useItemWithComments(12345));
-
- expect(result.current.item).toEqual(testItem);
-
- await waitFor(() => {
- expect(result.current.commentsLoading).toBe(false);
- });
-
- expect(result.current.item).toBeTruthy();
- });
-
function seedStaleCache() {
localStorage.setItem(`${ITEM_CACHE_KEY_PREFIX}12345`, JSON.stringify({
item: testItem,
@@ -833,40 +699,6 @@ describe('useItemWithComments', () => {
globalThis.fetch = origFetch;
});
- it('does not retry when commentsError is set (useAutoRetry handles that)', async () => {
- server.use(
- http.get(`${ALGOLIA_API}/search`, () => {
- return HttpResponse.json({ hits: [], nbHits: 0, page: 0, nbPages: 0, hitsPerPage: 200 });
- })
- );
-
- const { result } = renderHook(
- () => useItemWithComments(12345, { initialItem: testItem }),
- { wrapper: networkWrapper }
- );
-
- // Empty list resolves loading; reconnect handler should now treat
- // comments as "not stuck" and stay out of useAutoRetry's territory.
- await waitFor(() => {
- expect(result.current.commentsLoading).toBe(false);
- });
-
- const fetchSpy = vi.fn();
- const origFetch = globalThis.fetch;
- globalThis.fetch = (...args) => {
- fetchSpy();
- return origFetch(...args);
- };
-
- act(() => { window.dispatchEvent(new Event('offline')); });
- act(() => { window.dispatchEvent(new Event('online')); });
-
- await act(async () => { await new Promise(r => setTimeout(r, 50)); });
- expect(fetchSpy).not.toHaveBeenCalled();
-
- globalThis.fetch = origFetch;
- });
-
it('sets commentsError when reconnect fetch fails', async () => {
// First fetch hangs forever — simulates offline.
server.use(
@@ -1101,37 +933,6 @@ describe('useItemWithComments', () => {
});
describe('refresh loading states', () => {
- it('sets itemLoading and commentsLoading to true during refresh', async () => {
- const { result } = renderHook(() =>
- useItemWithComments(12345, { initialItem: testItem })
- );
-
- await waitFor(() => {
- expect(result.current.commentsLoading).toBe(false);
- });
- expect(result.current.itemLoading).toBe(false);
-
- // Slow the refresh fetch so the synchronous loading flip is observable.
- vi.spyOn(hnSdk, 'readItem').mockImplementation(async () => {
- await new Promise(r => setTimeout(r, 200));
- return mockFirebaseStory;
- });
-
- // Loading states must flip BEFORE the await, not after the fetch settles.
- let refreshPromise: Promise;
- act(() => {
- refreshPromise = result.current.refresh();
- });
-
- expect(result.current.itemLoading).toBe(true);
- expect(result.current.commentsLoading).toBe(true);
-
- await act(async () => { await refreshPromise!; });
-
- expect(result.current.itemLoading).toBe(false);
- expect(result.current.commentsLoading).toBe(false);
- });
-
it('clears error and commentsError during refresh', async () => {
vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Network error'));
diff --git a/src/hooks/useItemWithComments.ts b/src/hooks/useItemWithComments.ts
index 36fe98d..a94aa23 100644
--- a/src/hooks/useItemWithComments.ts
+++ b/src/hooks/useItemWithComments.ts
@@ -18,7 +18,6 @@ interface UseItemWithCommentsOptions {
interface UseItemWithCommentsResult {
item: Item | null;
comments: Comment[] | null;
- loading: boolean;
itemLoading: boolean;
commentsLoading: boolean;
error: string | null;
@@ -346,9 +345,6 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
};
}, [isOnline, itemId, applyThread, applyThreadError]);
- // Combined loading state for backward compatibility
- const loading = itemLoading && commentsLoading;
-
// Refetch behind the error states' retry action. No gesture reaches this: the
// root contains its overscroll, so there is no pull-to-refresh.
const refresh = useCallback(async () => {
@@ -399,7 +395,6 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
return {
item,
comments,
- loading,
itemLoading,
commentsLoading,
error,
diff --git a/src/hooks/usePackedNav.test.ts b/src/hooks/usePackedNav.test.ts
index e352dc1..a51497d 100644
--- a/src/hooks/usePackedNav.test.ts
+++ b/src/hooks/usePackedNav.test.ts
@@ -110,19 +110,6 @@ describe('usePackedNav', () => {
expect(exact.result.current.showOverflow).toBe(false);
});
- it('reaches the 3-visible state when the overflow trigger is cheap enough', () => {
- // With a tiny overflow trigger (40px, e.g. an icon-only "more" button),
- // there's room to show 3 items + the trigger when ask alone is the
- // overflow. Container 270 → budget 230. comments+best+show = 220 ≤ 230
- // fits. + 4 + ask (50) = 274 > 230 → stops. visible=[c,b,s], hidden=[a].
- const { result } = renderHook(() =>
- usePackedNav(makeFakeRef(270), ITEMS_4, { overflowWidth: 40, gap: 4 }),
- );
- expect(keys(result.current.visible)).toEqual(['comments', 'best', 'show']);
- expect(keys(result.current.hidden)).toEqual(['ask']);
- expect(result.current.showOverflow).toBe(true);
- });
-
it('handles empty input', () => {
const { result } = renderHook(() =>
usePackedNav(makeFakeRef(400), [] as TestItem[], { overflowWidth: 105, gap: 4 }),
diff --git a/src/hooks/usePrefetchItem.test.ts b/src/hooks/usePrefetchItem.test.ts
index 28e00c9..41da5b7 100644
--- a/src/hooks/usePrefetchItem.test.ts
+++ b/src/hooks/usePrefetchItem.test.ts
@@ -5,11 +5,10 @@ import {
usePrefetchItems,
cancelAllPrefetches
} from './usePrefetchItem';
-import { setCachedItem, getCachedItem } from '../utils/itemCache';
+import { getCachedItem } from '../utils/itemCache';
import * as fetchPriority from '../utils/fetchPriority';
import * as hn from '../api/hn';
-import type { Item, Comment } from '../types';
-import { createStoryItem } from '../test/factories';
+import type { Item } from '../types';
// Vitest's fake requestIdleCallback types a callback scheduled with `timeout`
// as a "Timeout", so its own cancelIdleCallback() throws a type mismatch.
@@ -37,64 +36,6 @@ describe('usePrefetchItem', () => {
restoreRealTimers();
});
- describe('startPrefetch and stopPrefetch', () => {
- it('returns startPrefetch and stopPrefetch functions', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- expect(typeof result.current.startPrefetch).toBe('function');
- expect(typeof result.current.stopPrefetch).toBe('function');
- });
-
- it('adds item to queue when startPrefetch called', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- expect(() => {
- act(() => {
- result.current.startPrefetch(12345, 0);
- });
- }).not.toThrow();
-
- // Calling again with same ID should not error (deduplication)
- expect(() => {
- act(() => {
- result.current.startPrefetch(12345, 0);
- });
- }).not.toThrow();
- });
-
- it('skips items with fresh cache', () => {
- setCachedItem(12345, createStoryItem({ id: 12345, title: 'Cached' }), [] as Comment[]);
-
- const { result } = renderHook(() => usePrefetchItem());
-
- expect(() => {
- act(() => {
- result.current.startPrefetch(12345, 0);
- });
- }).not.toThrow();
- });
-
- it('removes item from queue when stopPrefetch called', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- act(() => {
- result.current.startPrefetch(12345, 0);
- });
-
- act(() => {
- result.current.stopPrefetch();
- });
-
- // Re-adding the same id must succeed; if stopPrefetch left it queued,
- // the dedup short-circuit would silently swallow this call.
- expect(() => {
- act(() => {
- result.current.startPrefetch(12345, 0);
- });
- }).not.toThrow();
- });
- });
-
describe('queue processing', () => {
it('processes queue after debounce delay', async () => {
const spy = vi.spyOn(hn, 'prefetchItemComments');
@@ -201,65 +142,6 @@ describe('usePrefetchItems', () => {
restoreRealTimers();
});
- const mockItems = [
- createStoryItem({ id: 1, title: 'Item 1' }),
- createStoryItem({ id: 2, title: 'Item 2' }),
- createStoryItem({ id: 3, title: 'Item 3' }),
- createStoryItem({ id: 4, title: 'Item 4' }),
- createStoryItem({ id: 5, title: 'Item 5' }),
- ];
-
- it('prefetches items ahead of current index', () => {
- expect(() => {
- renderHook(() => usePrefetchItems(0, mockItems, 3));
- }).not.toThrow();
- });
-
- it('does not prefetch current item', () => {
- expect(() => {
- renderHook(() => usePrefetchItems(0, mockItems, 3));
- }).not.toThrow();
- });
-
- it('respects count parameter', () => {
- expect(() => {
- renderHook(() => usePrefetchItems(0, mockItems, 2));
- }).not.toThrow();
- });
-
- it('does not exceed array bounds', () => {
- expect(() => {
- renderHook(() => usePrefetchItems(3, mockItems, 5));
- }).not.toThrow();
- });
-
- it('skips already-prefetched items', () => {
- const { rerender } = renderHook(
- ({ index }) => usePrefetchItems(index, mockItems, 2),
- { initialProps: { index: 0 } }
- );
-
- // Re-rendering at a new index re-enqueues already-pending IDs; dedup
- // should swallow them without raising.
- expect(() => {
- rerender({ index: 1 });
- }).not.toThrow();
- });
-
- it('skips items with fresh cache', () => {
- setCachedItem(2, createStoryItem({ id: 2, title: 'Item 2' }), [] as Comment[]);
-
- expect(() => {
- renderHook(() => usePrefetchItems(0, mockItems, 3));
- }).not.toThrow();
- });
-
- it('handles empty items array', () => {
- expect(() => {
- renderHook(() => usePrefetchItems(0, [], 3));
- }).not.toThrow();
- });
-
it('handles undefined items', () => {
expect(() => {
renderHook(() => usePrefetchItems(0, undefined as unknown as Item[], 3));
@@ -278,25 +160,6 @@ describe('cancelAllPrefetches', () => {
restoreRealTimers();
});
- it('clears pending queue', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- act(() => {
- result.current.startPrefetch(12345, 0);
- result.current.startPrefetch(12346, 1);
- result.current.startPrefetch(12347, 2);
- });
-
- cancelAllPrefetches();
-
- // Queue should be empty — items can be re-added without error
- expect(() => {
- act(() => {
- result.current.startPrefetch(12345, 0);
- });
- }).not.toThrow();
- });
-
it('aborts active prefetches', async () => {
// Hang the fetch so cancelAllPrefetches has something in flight to abort.
const spy = vi.spyOn(hn, 'prefetchItemComments').mockReturnValue(new Promise(() => { /* never resolves */ }));
@@ -318,14 +181,6 @@ describe('cancelAllPrefetches', () => {
spy.mockRestore();
});
-
- it('can be called multiple times safely', () => {
- expect(() => {
- cancelAllPrefetches();
- cancelAllPrefetches();
- cancelAllPrefetches();
- }).not.toThrow();
- });
});
describe('edge cases', () => {
@@ -340,72 +195,6 @@ describe('edge cases', () => {
restoreRealTimers();
});
- it('handles item with id 0', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- // ID 0 is falsy but should still work
- expect(() => {
- act(() => {
- result.current.startPrefetch(0, 0);
- });
- }).not.toThrow();
- });
-
- it('handles negative index gracefully', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- expect(() => {
- act(() => {
- result.current.startPrefetch(12345, -1);
- });
- }).not.toThrow();
- });
-
- it('handles very large index values', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- expect(() => {
- act(() => {
- result.current.startPrefetch(12345, Number.MAX_SAFE_INTEGER);
- });
- }).not.toThrow();
- });
-
- it('stopPrefetch is safe when nothing was started', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- expect(() => {
- act(() => {
- result.current.stopPrefetch();
- });
- }).not.toThrow();
- });
-
- it('handles rapid start/stop cycles', () => {
- const { result } = renderHook(() => usePrefetchItem());
-
- expect(() => {
- act(() => {
- for (let i = 0; i < 100; i++) {
- result.current.startPrefetch(i, i);
- result.current.stopPrefetch();
- }
- });
- }).not.toThrow();
- });
-
- it('usePrefetchItems handles items with missing id', () => {
- const itemsWithMissingId = [
- { id: 1, title: 'Item 1' },
- { title: 'Item without ID' }, // Missing id
- { id: 3, title: 'Item 3' },
- ] as unknown as Item[];
-
- expect(() => {
- renderHook(() => usePrefetchItems(0, itemsWithMissingId, 3));
- }).not.toThrow();
- });
-
it('usePrefetchItems handles null item in array', () => {
const itemsWithNull = [
{ id: 1, title: 'Item 1' },
diff --git a/src/hooks/useScrollDirection.test.ts b/src/hooks/useScrollDirection.test.ts
index cf8c0b9..66e9399 100644
--- a/src/hooks/useScrollDirection.test.ts
+++ b/src/hooks/useScrollDirection.test.ts
@@ -69,20 +69,6 @@ describe('useScrollDirection', () => {
});
});
- it('ignores small scroll changes below threshold', async () => {
- const { result } = renderHook(() => useScrollDirection());
-
- // 5px is below the 10px direction-flip threshold; should not register.
- act(() => {
- window.scrollY = 5;
- window.dispatchEvent(new Event('scroll'));
- });
-
- await waitFor(() => {
- expect(result.current.scrollDirection).toBe('up');
- });
- });
-
it('cleans up scroll listener on unmount', () => {
const removeEventListenerSpy = vi.spyOn(window, 'removeEventListener');
diff --git a/src/hooks/useScrollRestore.test.ts b/src/hooks/useScrollRestore.test.ts
index f576382..7f2925e 100644
--- a/src/hooks/useScrollRestore.test.ts
+++ b/src/hooks/useScrollRestore.test.ts
@@ -258,23 +258,6 @@ describe('useScrollRestore', () => {
});
describe('saveScrollPosition', () => {
- it('writes the current window.scrollY to storage under the supplied key', () => {
- const { result } = renderHook(() =>
- useScrollRestore('domain:github.com', true),
- );
-
- act(() => {
- Object.defineProperty(window, 'scrollY', {
- value: 750,
- writable: true,
- configurable: true,
- });
- result.current.saveScrollPosition();
- });
-
- expect(readScrollPosition('domain:github.com')).toBe(750);
- });
-
it('is a no-op when key is undefined', () => {
const { result } = renderHook(() => useScrollRestore(undefined, true));
diff --git a/src/hooks/useSiblingComments.test.ts b/src/hooks/useSiblingComments.test.ts
index c426984..cff13d9 100644
--- a/src/hooks/useSiblingComments.test.ts
+++ b/src/hooks/useSiblingComments.test.ts
@@ -48,19 +48,6 @@ describe('useSiblingComments', () => {
expect(result.current.currentIndex).toBe(0);
});
- it('fetches siblings from parent kids list', async () => {
- // Default MSW handlers: 1001's parent is 12345, whose kids = [1001, 1002, 1003, 1004].
- const { result } = renderHook(() => useSiblingComments(1001));
-
- await waitFor(() => {
- expect(result.current.loading).toBe(false);
- });
-
- expect(result.current.siblingIds).toEqual([1001, 1002, 1003, 1004]);
- expect(result.current.currentIndex).toBe(0);
- expect(result.current.error).toBeNull();
- });
-
it('sets correct currentIndex for non-first sibling', async () => {
const { result } = renderHook(() => useSiblingComments(1002));
@@ -177,18 +164,6 @@ describe('useSiblingComments', () => {
expect(result.current.error).toBeTruthy();
});
- it('sets error on network failure', async () => {
- vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Failed to fetch'));
-
- const { result } = renderHook(() => useSiblingComments(1001));
-
- await waitFor(() => {
- expect(result.current.loading).toBe(false);
- });
-
- expect(result.current.error).toBeTruthy();
- });
-
it('aborts in-flight fetches on unmount', async () => {
const abortSpy = vi.spyOn(AbortController.prototype, 'abort');
diff --git a/src/hooks/useStaggerCascadeSlots.test.ts b/src/hooks/useStaggerCascadeSlots.test.ts
index 66f2bea..aedc46b 100644
--- a/src/hooks/useStaggerCascadeSlots.test.ts
+++ b/src/hooks/useStaggerCascadeSlots.test.ts
@@ -15,18 +15,6 @@ describe('useStaggerCascadeSlots', () => {
expect(result.current(5)).toEqual({ stageIdx: 5 });
});
- it('keeps cards in the initial batch on stageIdx after the boundary latches', () => {
- const { result, rerender } = renderHook(
- ({ loading, count }) => useStaggerCascadeSlots(loading, count),
- { initialProps: { loading: true, count: 0 } },
- );
-
- rerender({ loading: false, count: 20 });
-
- expect(result.current(0)).toEqual({ stageIdx: 0 });
- expect(result.current(19)).toEqual({ stageIdx: 19 });
- });
-
// Critical regression: the previous boundary-relative formulation
// made batch 2 start at `appendIdx 20` (575ms+ delay before the
// first card landed — the "spinner clears, then a pause" symptom).
diff --git a/src/hooks/useSwipeScroll.test.ts b/src/hooks/useSwipeScroll.test.ts
index 677cbe1..5e4e602 100644
--- a/src/hooks/useSwipeScroll.test.ts
+++ b/src/hooks/useSwipeScroll.test.ts
@@ -236,21 +236,6 @@ describe('useSwipeScroll', () => {
expect(history.scrollRestoration).toBe('manual');
});
- it('updates the JS scroll indicator when scroll timelines are unavailable', () => {
- mockInnerHeight = 400;
- mockScrollHeight = 1000;
- render(createElement(TestHarness), { wrapper: Wrapper });
-
- expect(document.body.style.getPropertyValue('--swipe-scroll-progress')).toBe('0');
-
- mockScrollY = 300;
- act(() => {
- window.dispatchEvent(new Event('scroll'));
- });
-
- expect(Number(document.body.style.getPropertyValue('--swipe-scroll-progress'))).toBeCloseTo(0.5);
- });
-
it('uses the visual viewport height for fallback progress and updates on visual viewport resize', () => {
mockInnerHeight = 400;
mockVisualViewportHeight = 500;
@@ -497,30 +482,6 @@ describe('useSwipeScroll', () => {
act(() => { vi.runAllTimers(); });
});
- it('preserves per-panel scroll position across swipes (reduced motion)', async () => {
- reducedMotionValue = true;
- render(createElement(TestHarness), { wrapper: Wrapper });
-
- // User scrolled down on panel 0
- mockScrollY = 200;
-
- // Swipe forward to panel 1
- vi.mocked(window.scrollTo).mockClear();
- swipeGesture(getContainer(), 'left', 150);
-
- // Panel 1 starts at top (no saved position)
- expect(window.scrollTo).toHaveBeenCalledWith(0, 0);
- act(() => { vi.runAllTimers(); });
- await act(async () => { /* flush */ });
-
- // Swipe back to panel 0
- vi.mocked(window.scrollTo).mockClear();
- swipeGesture(getContainer(), 'right', 150);
-
- // Panel 0's position (200) should be restored
- expect(window.scrollTo).toHaveBeenCalledWith(0, 200);
- });
-
it('suppresses the scroll indicator during a deep forward panel swap', async () => {
reducedMotionValue = true;
mockInnerHeight = 400;
diff --git a/src/hooks/useTheme.test.tsx b/src/hooks/useTheme.test.tsx
index 20f3e61..75753a2 100644
--- a/src/hooks/useTheme.test.tsx
+++ b/src/hooks/useTheme.test.tsx
@@ -20,15 +20,6 @@ describe('useTheme', () => {
spy.mockRestore();
});
- it('exposes mode, theme, setMode and cycleMode', () => {
- const { result } = renderHook(() => useTheme(), { wrapper });
-
- expect(result.current.mode).toBeDefined();
- expect(result.current.theme).toBeDefined();
- expect(typeof result.current.setMode).toBe('function');
- expect(typeof result.current.cycleMode).toBe('function');
- });
-
it('defaults to system mode, resolving to light when the OS is not dark', () => {
const { result } = renderHook(() => useTheme(), { wrapper });
@@ -36,21 +27,6 @@ describe('useTheme', () => {
expect(result.current.theme).toBe('light');
});
- it('cycleMode advances system → light → dark → system', () => {
- const { result } = renderHook(() => useTheme(), { wrapper });
-
- expect(result.current.mode).toBe('system');
-
- act(() => result.current.cycleMode());
- expect(result.current.mode).toBe('light');
-
- act(() => result.current.cycleMode());
- expect(result.current.mode).toBe('dark');
-
- act(() => result.current.cycleMode());
- expect(result.current.mode).toBe('system');
- });
-
it('persists the selected mode to localStorage', () => {
const { result } = renderHook(() => useTheme(), { wrapper });
diff --git a/src/hooks/useUserInfiniteStories.test.ts b/src/hooks/useUserInfiniteStories.test.ts
index 9b6e8ab..a6c613f 100644
--- a/src/hooks/useUserInfiniteStories.test.ts
+++ b/src/hooks/useUserInfiniteStories.test.ts
@@ -1,14 +1,11 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { renderHook, waitFor, act } from '@testing-library/react';
-import { StrictMode } from 'react';
+import { renderHook, waitFor } from '@testing-library/react';
import {
useUserInfiniteStories,
- formatNoUserSubmissionsTitle,
__resetUserStoriesCacheForTests,
- __getUserStoriesCacheForTests,
} from './useUserInfiniteStories';
-function body(ids: number[], page = 0, nbPages = 1) {
+function body(ids: number[]) {
return {
hits: ids.map((id) => ({
objectID: String(id),
@@ -21,8 +18,8 @@ function body(ids: number[], page = 0, nbPages = 1) {
_tags: ['story'],
})),
nbHits: ids.length,
- nbPages,
- page,
+ nbPages: 1,
+ page: 0,
hitsPerPage: 50,
};
}
@@ -34,16 +31,6 @@ function fetchInputToUrl(input: RequestInfo | URL | undefined): string {
return input.url;
}
-describe('formatNoUserSubmissionsTitle', () => {
- it('uses "by" instead of "from" for personhood', () => {
- expect(formatNoUserSubmissionsTitle('pg')).toBe('No submissions found by "pg"');
- });
-
- it('preserves username case verbatim', () => {
- expect(formatNoUserSubmissionsTitle('PaulG')).toBe('No submissions found by "PaulG"');
- });
-});
-
describe('useUserInfiniteStories', () => {
beforeEach(() => {
__resetUserStoriesCacheForTests();
@@ -53,20 +40,6 @@ describe('useUserInfiniteStories', () => {
vi.restoreAllMocks();
});
- it('loads stories for a user on mount', async () => {
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
- new Response(JSON.stringify(body([1, 2, 3]))),
- );
-
- const { result } = renderHook(() => useUserInfiniteStories('pg'));
-
- await waitFor(() => expect(result.current.loading).toBe(false));
-
- expect(result.current.stories.map((s) => s.id)).toEqual([1, 2, 3]);
- expect(result.current.error).toBeNull();
- expect(result.current.hasMore).toBe(false);
- });
-
it('queries Algolia for the stories and polls by the author, preserving username case', async () => {
const fetchSpy = vi
.spyOn(globalThis, 'fetch')
@@ -98,33 +71,6 @@ describe('useUserInfiniteStories', () => {
expect(calls).toBe(1);
});
- describe('updater purity', () => {
- it('writes the user cache exactly once per successful load under StrictMode', async () => {
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
- new Response(JSON.stringify(body([1, 2, 3]))),
- );
-
- const cache = __getUserStoriesCacheForTests();
- const originalSet = Map.prototype.set;
- let setCount = 0;
- Map.prototype.set = function (this: Map, key, value) {
- if (this === cache) setCount += 1;
- return originalSet.call(this, key, value);
- };
-
- try {
- const { result } = renderHook(() => useUserInfiniteStories('pg'), {
- wrapper: StrictMode,
- });
- await waitFor(() => expect(result.current.stories.length).toBe(3));
- } finally {
- Map.prototype.set = originalSet;
- }
-
- expect(setCount).toBe(1);
- });
- });
-
describe('cache', () => {
it('returns cached stories synchronously on remount and skips the fetch', async () => {
const fetchSpy = vi
@@ -149,120 +95,6 @@ describe('useUserInfiniteStories', () => {
});
});
- describe('error handling', () => {
- it('sets error on fetch rejection, releases inFlight, and supports manual retry', async () => {
- const fetchSpy = vi
- .spyOn(globalThis, 'fetch')
- .mockRejectedValueOnce(new Error('network down'))
- .mockResolvedValueOnce(new Response(JSON.stringify(body([1, 2]))));
-
- const { result } = renderHook(() => useUserInfiniteStories('pg'));
-
- await waitFor(() => expect(result.current.loading).toBe(false));
- expect(result.current.error).toBe('network down');
- expect(result.current.stories).toEqual([]);
- expect(fetchSpy).toHaveBeenCalledTimes(1);
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- expect(result.current.error).toBeNull();
- expect(result.current.stories.map((s) => s.id)).toEqual([1, 2]);
- expect(fetchSpy).toHaveBeenCalledTimes(2);
- });
-
- it('sets error when the response status is not ok', async () => {
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
- new Response('Service Unavailable', { status: 503 }),
- );
-
- const { result } = renderHook(() => useUserInfiniteStories('pg'));
-
- await waitFor(() => expect(result.current.loading).toBe(false));
- expect(result.current.error).toMatch(/503/);
- expect(result.current.stories).toEqual([]);
- });
- });
-
- describe('dedup across pages', () => {
- it('does not include the same story id twice when it appears on consecutive pages', async () => {
- let call = 0;
- vi.spyOn(globalThis, 'fetch').mockImplementation(() => {
- const page = call++;
- return Promise.resolve(
- new Response(
- JSON.stringify(page === 0 ? body([1, 2], 0, 2) : body([2, 3], 1, 2)),
- ),
- );
- });
-
- const { result } = renderHook(() => useUserInfiniteStories('pg'));
-
- await waitFor(() => expect(result.current.stories.map((s) => s.id)).toEqual([1, 2]));
- expect(result.current.hasMore).toBe(true);
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- expect(result.current.stories.map((s) => s.id)).toEqual([1, 2, 3]);
- expect(result.current.hasMore).toBe(false);
- });
- });
-
- describe('more submissions than search returns', () => {
- it('loads past the last page from the oldest story so far', async () => {
- const hit = (id: number, createdAt: number) => ({ ...body([id]).hits[0], created_at_i: createdAt });
- const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
- const filter = new URL(fetchInputToUrl(input)).searchParams.get('numericFilters');
- // Search stops at 1,000 hits and caps nbPages to match, so its last
- // page doesn't reach nbHits.
- return Promise.resolve(Response.json(filter === null
- ? { hits: [hit(1, 300), hit(2, 200)], nbHits: 1500, nbPages: 1, page: 0, hitsPerPage: 50 }
- : { hits: [hit(2, 200), hit(3, 100)], nbHits: 2, nbPages: 1, page: 0, hitsPerPage: 50 }));
- });
-
- const { result } = renderHook(() => useUserInfiniteStories('pg'));
- await waitFor(() => expect(result.current.stories.map((s) => s.id)).toEqual([1, 2]));
- expect(result.current.hasMore).toBe(true);
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- const nextUrl = new URL(fetchInputToUrl(fetchSpy.mock.calls[1]?.[0]));
- expect(nextUrl.searchParams.get('numericFilters')).toBe('created_at_i<=200');
- expect(nextUrl.searchParams.get('page')).toBe('0');
- expect(result.current.stories.map((s) => s.id)).toEqual([1, 2, 3]);
- expect(result.current.hasMore).toBe(false);
- });
- });
-
- describe('reset', () => {
- it('clears state, removes the cache entry, and triggers a fresh fetch', async () => {
- vi.spyOn(globalThis, 'fetch')
- .mockResolvedValueOnce(new Response(JSON.stringify(body([1, 2, 3]))))
- .mockResolvedValueOnce(new Response(JSON.stringify(body([10, 11]))));
-
- const { result } = renderHook(() => useUserInfiniteStories('pg'));
-
- await waitFor(() => expect(result.current.stories.length).toBe(3));
- expect(__getUserStoriesCacheForTests().has('pg')).toBe(true);
-
- act(() => {
- result.current.reset();
- });
-
- expect(__getUserStoriesCacheForTests().has('pg')).toBe(false);
-
- await waitFor(() =>
- expect(result.current.stories.map((s) => s.id)).toEqual([10, 11]),
- );
- expect(__getUserStoriesCacheForTests().has('pg')).toBe(true);
- });
- });
-
describe('empty username', () => {
it('does not fetch and stays in idle state', async () => {
const fetchSpy = vi
diff --git a/src/hooks/useUserInfiniteStories.ts b/src/hooks/useUserInfiniteStories.ts
index c0dc24c..a01e130 100644
--- a/src/hooks/useUserInfiniteStories.ts
+++ b/src/hooks/useUserInfiniteStories.ts
@@ -13,11 +13,6 @@ export function __resetUserStoriesCacheForTests() {
userStoriesCache.clear();
}
-/** @internal Exposes cache for test assertions. */
-export function __getUserStoriesCacheForTests() {
- return userStoriesCache;
-}
-
/** Centralized empty-state title for user submission pages. */
export function formatNoUserSubmissionsTitle(username: string): string {
return `No submissions found by "${username}"`;
diff --git a/src/hooks/useViewDwell.test.tsx b/src/hooks/useViewDwell.test.tsx
index 2f1308d..db13b38 100644
--- a/src/hooks/useViewDwell.test.tsx
+++ b/src/hooks/useViewDwell.test.tsx
@@ -88,15 +88,6 @@ describe('useViewDwell', () => {
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));
diff --git a/src/pages/ItemDetail.test.tsx b/src/pages/ItemDetail.test.tsx
index c298e25..4016338 100644
--- a/src/pages/ItemDetail.test.tsx
+++ b/src/pages/ItemDetail.test.tsx
@@ -3,7 +3,6 @@ import { screen, waitFor, fireEvent, act } from '@testing-library/react';
import { render } from '../test/test-utils';
import { Routes, Route } from 'react-router';
import { ItemDetail } from './ItemDetail';
-import { clearViewed, markViewed, isViewed } from '../utils/viewedItems';
import { http, HttpResponse } from 'msw';
import { server } from '../mocks/server';
import { hnSdk } from '../api/hnSdk';
@@ -35,7 +34,6 @@ function renderItemDetail(itemId: number) {
describe('ItemDetail', () => {
beforeEach(() => {
- clearViewed();
vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => {
if (Number(id) === 12345) return defaultItem;
return null;
@@ -47,42 +45,6 @@ describe('ItemDetail', () => {
server.resetHandlers();
});
- describe('viewed state', () => {
- it('shows unviewed title color by default', async () => {
- renderItemDetail(12345);
-
- const heading = await screen.findByRole('heading', { level: 1 });
- expect(heading).toHaveClass('text-foreground');
- expect(heading).not.toHaveClass('text-viewed');
- });
-
- it('shows viewed title color when item was previously viewed', async () => {
- markViewed(12345);
- renderItemDetail(12345);
-
- const heading = await screen.findByRole('heading', { level: 1 });
- expect(heading).toHaveClass('text-viewed');
- expect(heading).not.toHaveClass('text-foreground');
- });
-
- it('marks item as viewed and updates title color on external link click', async () => {
- renderItemDetail(12345);
-
- const titleLink = await screen.findByRole('link', { name: 'Rust Is the Future of JavaScript Infrastructure' });
- expect(titleLink.closest('h1')).toHaveClass('text-foreground');
-
- fireEvent.click(titleLink);
-
- await waitFor(() => {
- expect(titleLink.closest('h1')).toHaveClass('text-viewed');
- });
-
- // Persistence side of the contract — class change alone wouldn't
- // catch a regression that skips the storage write.
- expect(isViewed(12345)).toBe(true);
- });
- });
-
describe('back-to-home action on not-found', () => {
beforeEach(() => {
vi.spyOn(hnSdk, 'readItem').mockResolvedValue(null);
diff --git a/src/pages/UserProfile.test.tsx b/src/pages/UserProfile.test.tsx
index 01d34b6..cbb3262 100644
--- a/src/pages/UserProfile.test.tsx
+++ b/src/pages/UserProfile.test.tsx
@@ -16,13 +16,6 @@ const mockUserProfile: UserProfileType = {
submitted: [12345, 99999, 88888],
};
-const mockMinimalUser: UserProfileType = {
- id: 'minimaluser',
- created: 1160418092,
- karma: 1,
- submitted: [],
-};
-
function renderProfile(username: string) {
// ScrollContainerProvider matches the production tree (App.tsx wraps the
// router in it). Without it, `useScrollContainer()` returns its noop
@@ -44,7 +37,6 @@ describe('UserProfile', () => {
document.body.classList.remove('swipe-mode');
vi.spyOn(hnSdk, 'readUser').mockImplementation(async (username) => {
if (username === 'leerob') return mockUserProfile;
- if (username === 'minimaluser') return mockMinimalUser;
if (username === 'pg') return { id: 'pg', created: 1160418092, karma: 155555, submitted: [12345] };
return null;
});
@@ -90,23 +82,6 @@ describe('UserProfile', () => {
});
});
- it('renders the "submissions" metadata link to /submitted/:id', async () => {
- renderProfile('leerob');
-
- const link = await screen.findByRole('link', { name: 'submissions' });
- expect(link).toHaveAttribute('href', '/submitted/leerob');
- });
-
- it('does not render the about section when profile.about is missing', async () => {
- renderProfile('minimaluser');
-
- await waitFor(() => {
- expect(
- screen.getByRole('heading', { level: 1, name: 'minimaluser' }),
- ).toBeInTheDocument();
- });
- });
-
it('preserves username case (HN is case-sensitive)', async () => {
vi.spyOn(hnSdk, 'readUser').mockImplementation(async (username) => ({
id: username,
diff --git a/src/pages/UserSubmissions.test.tsx b/src/pages/UserSubmissions.test.tsx
index 2f10213..7b9c38f 100644
--- a/src/pages/UserSubmissions.test.tsx
+++ b/src/pages/UserSubmissions.test.tsx
@@ -85,14 +85,4 @@ describe('UserSubmissions', () => {
expect(screen.getByText('No user specified')).toBeInTheDocument();
});
-
- it('passes fromUser to StoryCard so its byline links carry the origin', async () => {
- renderSubmissions('leerob');
-
- // Asserts only href here — react-router synthesizes href from `to`,
- // but `state` is only set at navigation time. State assertion lives
- // in StoryCard.test.tsx.
- const commentsLink = await screen.findByRole('link', { name: /137 comments/ });
- expect(commentsLink).toHaveAttribute('href', '/item/12345');
- });
});
diff --git a/src/utils/feedCache.test.ts b/src/utils/feedCache.test.ts
index e19878f..eced764 100644
--- a/src/utils/feedCache.test.ts
+++ b/src/utils/feedCache.test.ts
@@ -16,14 +16,6 @@ describe('feedCache', () => {
];
describe('setCachedFeed', () => {
- it('stores stories that can be retrieved', () => {
- setCachedFeed('top', mockStories);
-
- const result = getCachedFeed('top')!;
- expect(result).not.toBeNull();
- expect(result.stories).toEqual(mockStories);
- });
-
it('stores different cache types separately', () => {
setCachedFeed('top', [createStoryItem({ id: 1, title: 'Top Story' })]);
setCachedFeed('best', [createStoryItem({ id: 2, title: 'Best Story' })]);
@@ -67,14 +59,6 @@ describe('feedCache', () => {
expect(result.timestamp).toBeDefined();
expect(typeof result.isStale).toBe('boolean');
});
-
- it('marks cache as fresh when recently created', () => {
- setCachedFeed('top', mockStories);
-
- const result = getCachedFeed('top')!;
-
- expect(result.isStale).toBe(false);
- });
});
describe('clearFeedCache', () => {
diff --git a/src/utils/fetchPriority.test.ts b/src/utils/fetchPriority.test.ts
index 0210ec3..9a12aa4 100644
--- a/src/utils/fetchPriority.test.ts
+++ b/src/utils/fetchPriority.test.ts
@@ -14,16 +14,6 @@ describe('fetchPriority', () => {
});
describe('registerPriorityFetch / unregisterPriorityFetch', () => {
- it('tracks single priority fetch', () => {
- expect(isPriorityFetchActive()).toBe(false);
-
- registerPriorityFetch();
- expect(isPriorityFetchActive()).toBe(true);
-
- unregisterPriorityFetch();
- expect(isPriorityFetchActive()).toBe(false);
- });
-
it('handles multiple concurrent priority fetches (ref counting)', () => {
registerPriorityFetch();
registerPriorityFetch();
diff --git a/src/utils/itemCache.test.ts b/src/utils/itemCache.test.ts
index fc767c4..eee54b2 100644
--- a/src/utils/itemCache.test.ts
+++ b/src/utils/itemCache.test.ts
@@ -92,11 +92,6 @@ describe('itemCache', () => {
expect(getCachedItem('123')).not.toBeNull();
});
- it('returns null for null/undefined itemId', () => {
- expect(getCachedItem(null as unknown as string)).toBeNull();
- expect(getCachedItem(undefined as unknown as string)).toBeNull();
- });
-
it('handles cache entry with missing timestamp', () => {
localStorage.setItem(`${ITEM_CACHE_KEY_PREFIX}123`, JSON.stringify({
item: mockItem,
@@ -112,14 +107,6 @@ describe('itemCache', () => {
});
describe('setCachedItem', () => {
- it('stores item that can be retrieved', () => {
- setCachedItem(123, mockItem, mockComments);
-
- const result = getCachedItem(123)!;
- expect(result.item).toEqual(mockItem);
- expect(result.comments).toEqual(mockComments);
- });
-
it('stores different items separately', () => {
const item1 = createStoryItem({ id: 1, title: 'Item 1' });
const item2 = createStoryItem({ id: 2, title: 'Item 2' });
@@ -325,13 +312,6 @@ describe('sessionStorage - List Session State', () => {
expect(getListSessionState('top')!.position).toBe(1);
expect(getListSessionState('best')!.position).toBe(2);
});
-
- it('converts Set to Array for storage', () => {
- saveListSessionState('top', mockState);
-
- const stored = JSON.parse(sessionStorage.getItem(`${FEED_SESSION_KEY_PREFIX}top`)!) as { seenIds?: unknown };
- expect(Array.isArray(stored.seenIds)).toBe(true);
- });
});
describe('getListSessionState', () => {
@@ -339,16 +319,6 @@ describe('sessionStorage - List Session State', () => {
expect(getListSessionState('top')).toBeNull();
});
- it('converts seenIds Array back to Set', () => {
- saveListSessionState('top', mockState);
-
- const result = getListSessionState('top')!;
-
- expect(result.seenIds instanceof Set).toBe(true);
- expect(result.seenIds.has(1)).toBe(true);
- expect(result.seenIds.has(2)).toBe(true);
- });
-
it('expires session after 30 minutes', () => {
saveListSessionState('top', mockState);
@@ -403,24 +373,5 @@ describe('sessionStorage - List Session State', () => {
expect(getListSessionState('top')).toBeNull();
expect(getListSessionState('best')).not.toBeNull();
});
-
- it('does not throw for non-existent session', () => {
- expect(() => clearListSessionState('nonexistent' as never)).not.toThrow();
- });
-
- it('handles empty seenIds array', () => {
- saveListSessionState('top', { ...mockState, seenIds: new Set() });
-
- const result = getListSessionState('top')!;
- expect(result.seenIds).toEqual(new Set());
- expect(result.seenIds.size).toBe(0);
- });
-
- it('handles special characters in feedType', () => {
- saveListSessionState('top/special' as never, mockState);
-
- const result = getListSessionState('top/special' as never)!;
- expect(result).not.toBeNull();
- });
});
});
diff --git a/src/utils/sanitize.test.ts b/src/utils/sanitize.test.ts
index cb9fa91..9afdd0e 100644
--- a/src/utils/sanitize.test.ts
+++ b/src/utils/sanitize.test.ts
@@ -54,13 +54,6 @@ describe('sanitizeHtml', () => {
expect(result).toContain('line1\nline2
');
});
- it('preserves the inner wrapper so `.comment-content pre code` styles still apply', () => {
- const html = ' foo
';
- const result = sanitizeHtml(html);
- expect(result).toContain('');
- expect(result).toContain('');
- });
-
it('handles bare (no child) by dedenting the directly', () => {
const html = ' line1\n line2
';
const result = sanitizeHtml(html);
@@ -178,11 +171,6 @@ describe('sanitizeHtml', () => {
expect(result).not.toContain('noopener');
});
- it('preserves relative URLs', () => {
- const result = sanitizeHtml('about');
- expect(result).toContain('href="/about"');
- });
-
it('preserves hash URLs', () => {
const result = sanitizeHtml('section');
expect(result).toContain('href="#section"');
@@ -295,11 +283,6 @@ describe('sanitizeHtml', () => {
expect(result).toContain('Foil_(narrative)).');
});
- it('excludes trailing semicolon from auto-linked URL', () => {
- const result = sanitizeHtml('url: https://example.com;');
- expect(result).toContain('href="https://example.com"');
- });
-
it('excludes trailing punctuation from URL with path', () => {
const result = sanitizeHtml('https://example.com/path?q=1#frag.');
expect(result).toContain('href="https://example.com/path?q=1#frag"');
@@ -346,11 +329,6 @@ describe('sanitizeHtml', () => {
});
describe('attribute filtering', () => {
- it('preserves href', () => {
- const result = sanitizeHtml('text');
- expect(result).toContain('href="https://example.com"');
- });
-
it('removes class and id, which could restyle the page or shadow its ids', () => {
const result = sanitizeHtml('text
');
expect(result).not.toContain('class=');
@@ -474,21 +452,6 @@ describe('sanitizeHtml', () => {
expect(result).toContain('href="#/user/foo_bar-baz"');
});
- it('rewrites http variant', () => {
- const result = sanitizeHtml('link');
- expect(result).toContain('href="#/user/pg"');
- });
-
- it('rewrites www subdomain variant', () => {
- const result = sanitizeHtml('link');
- expect(result).toContain('href="#/user/pg"');
- });
-
- it('rewrites /user/?id=X with trailing slash on path', () => {
- const result = sanitizeHtml('link');
- expect(result).toContain('href="#/user/pg"');
- });
-
it('leaves /user with no id unchanged', () => {
const result = sanitizeHtml('link');
expect(result).toContain('href="https://news.ycombinator.com/user"');
@@ -522,11 +485,6 @@ describe('sanitizeHtml', () => {
expect(result).toContain('href="#/submitted/PaulG"');
});
- it('rewrites /submitted/?id=X with trailing slash on path', () => {
- const result = sanitizeHtml('link');
- expect(result).toContain('href="#/submitted/pg"');
- });
-
it('leaves /submitted with no id unchanged', () => {
const result = sanitizeHtml('link');
expect(result).toContain('href="https://news.ycombinator.com/submitted"');
@@ -597,11 +555,6 @@ describe('sanitizeHtml', () => {
expect(result).toContain('href="#/show"');
});
- it('rewrites self /#/newest', () => {
- const result = sanitizeHtml('link');
- expect(result).toContain('href="#/newest"');
- });
-
it('rewrites self /#/user/', () => {
const result = sanitizeHtml('link');
expect(result).toContain('href="#/user/pg"');
@@ -698,24 +651,6 @@ describe('sanitizeHtml', () => {
expect(result).toContain('>/show');
});
- it('replaces auto-linkified HN /ask with /ask', () => {
- const url = 'https://news.ycombinator.com/ask';
- const result = sanitizeHtml(`${url}`);
- expect(result).toContain('>/ask');
- });
-
- it('replaces auto-linkified HN /best with /best', () => {
- const url = 'https://news.ycombinator.com/best';
- const result = sanitizeHtml(`${url}`);
- expect(result).toContain('>/best');
- });
-
- it('replaces auto-linkified HN /newest with /newest', () => {
- const url = 'https://news.ycombinator.com/newest';
- const result = sanitizeHtml(`${url}`);
- expect(result).toContain('>/newest');
- });
-
it('replaces auto-linkified self hash item URL with item:', () => {
const url = 'https://hackertok.github.io/#/item/47816960';
const result = sanitizeHtml(`${url}`);
diff --git a/src/utils/share.test.ts b/src/utils/share.test.ts
index 8413b8d..d599dad 100644
--- a/src/utils/share.test.ts
+++ b/src/utils/share.test.ts
@@ -31,10 +31,6 @@ describe('itemPermalink', () => {
it('builds an absolute hash-route URL on the current origin', () => {
expect(itemPermalink(42)).toBe(`${window.location.origin}/#/item/42`);
});
-
- it('accepts a string id without reformatting it', () => {
- expect(itemPermalink('42')).toBe(`${window.location.origin}/#/item/42`);
- });
});
describe('canShareOrCopy', () => {
diff --git a/src/utils/swipePosition.test.ts b/src/utils/swipePosition.test.ts
index 076f9d3..1a84689 100644
--- a/src/utils/swipePosition.test.ts
+++ b/src/utils/swipePosition.test.ts
@@ -42,13 +42,6 @@ describe('swipePosition', () => {
expect(result.savedAt).toBe(Date.now());
});
- it('rewrites index window-relative so stories[index].id === storyId', () => {
- saveSwipePosition({ viewer: { from: 'top' }, storyId: 2, index: 1, scrollY: 0, stories });
-
- const result = readSwipePosition()!;
- expect(result.stories[result.index].id).toBe(2);
- });
-
it('returns null when nothing is stored', () => {
expect(readSwipePosition()).toBeNull();
});
@@ -247,10 +240,5 @@ describe('swipePosition', () => {
expect(readSwipePosition({ viewer: { from: 'top' } })).toBeNull();
expect(readSwipePosition({ viewer: { from: 'best' } })?.storyId).toBe(3);
});
-
- it('does not throw when nothing is stored', () => {
- expect(() => clearSwipePosition()).not.toThrow();
- expect(() => clearSwipePosition({ from: 'top' })).not.toThrow();
- });
});
});
diff --git a/src/utils/touchActiveStates.test.ts b/src/utils/touchActiveStates.test.ts
index 245b228..381d08a 100644
--- a/src/utils/touchActiveStates.test.ts
+++ b/src/utils/touchActiveStates.test.ts
@@ -19,13 +19,4 @@ describe('enableTouchActiveStates', () => {
{ passive: true },
);
});
-
- it('does nothing when a touch actually arrives', () => {
- enableTouchActiveStates();
-
- // Anything this handler did would run on every touch, including mid-swipe.
- const event = new Event('touchstart', { bubbles: true, cancelable: true });
- expect(() => document.dispatchEvent(event)).not.toThrow();
- expect(event.defaultPrevented).toBe(false);
- });
});
diff --git a/src/utils/viewedItems.test.ts b/src/utils/viewedItems.test.ts
index e35b845..329477e 100644
--- a/src/utils/viewedItems.test.ts
+++ b/src/utils/viewedItems.test.ts
@@ -35,11 +35,6 @@ describe('viewedItems', () => {
expect(isViewed(12345)).toBe(false);
});
- it('returns true for viewed item', () => {
- markViewed(12345);
- expect(isViewed(12345)).toBe(true);
- });
-
it('handles string IDs', () => {
markViewed('12345');
expect(isViewed('12345')).toBe(true);
@@ -60,25 +55,6 @@ describe('viewedItems', () => {
expect(isViewed(99999)).toBe(true);
});
- it('handles multiple different items', () => {
- markViewed(1);
- markViewed(2);
- markViewed(3);
-
- expect(isViewed(1)).toBe(true);
- expect(isViewed(2)).toBe(true);
- expect(isViewed(3)).toBe(true);
- expect(isViewed(4)).toBe(false);
- });
-
- it('is idempotent - marking same item twice has no effect', () => {
- markViewed(12345);
- expect(isViewed(12345)).toBe(true);
-
- markViewed(12345);
- expect(isViewed(12345)).toBe(true);
- });
-
it('evicts oldest entries when exceeding 50K cap', () => {
// Seed 50K IDs via localStorage, then let clearViewed invalidate the cache
const ids = Array.from({ length: 50_000 }, (_, i) => i + 1);
@@ -538,14 +514,6 @@ describe('viewedItems - Session storage functions', () => {
});
describe('addToSessionViewed', () => {
- it('adds an item ID to session storage', () => {
- expect(getSessionViewedIds().has(12345)).toBe(false);
-
- addToSessionViewed(12345);
-
- expect(getSessionViewedIds().has(12345)).toBe(true);
- });
-
it('handles string IDs', () => {
addToSessionViewed('12345');