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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions e2e/navigation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,19 @@ test.describe('Navigation', () => {
test('navigates to Show HN section', async ({ page }) => {
await page.goto('/#/');

// On mobile, the swipe viewer auto-rewrites / → /item/<id>. Wait for
// this replace-navigation to complete so the subsequent click isn't
// swallowed by WebKit during the transition (Mobile Safari flake).
const isMobile = (page.viewportSize()?.width ?? 1280) < 768;
if (isMobile) {
await page.waitForURL(/\/#\/item\/\d+/, { timeout: 10000 });
}

await page.getByRole('link', { name: /show/i }).click();

// Wait for navigation to fully settle — the "show" link only receives
// bg-accent after the route resolves to /show (or /item/<id> with
// state.from="show"). Without this, on Mobile Safari the old URL
// /#/item/<top-story-id> can match a loose regex prematurely.
// state.from="show").
await expect(page.getByRole('link', { name: 'show', exact: true })).toHaveClass(/bg-accent/, { timeout: 10000 });

await expect(page.getByText('Show HN: Piko – Open-Source Ngrok Alternative in Go').first()).toBeVisible({ timeout: 10000 });
Expand All @@ -48,6 +55,12 @@ test.describe('Navigation', () => {
test('navigates to Ask HN section', async ({ page }) => {
await page.goto('/#/');

// Same mobile stabilization as Show HN test above.
const isMobile = (page.viewportSize()?.width ?? 1280) < 768;
if (isMobile) {
await page.waitForURL(/\/#\/item\/\d+/, { timeout: 10000 });
}

await page.getByRole('link', { name: /ask/i }).click();

// Wait for navigation to fully settle (same pattern as Show HN above).
Expand Down Expand Up @@ -87,13 +100,22 @@ test.describe('Navigation', () => {
test('navigates back to Top from other section', async ({ page }) => {
await page.goto('/#/show');

// On mobile, wait for the show swipe-rewrite to settle before clicking.
const isMobile = (page.viewportSize()?.width ?? 1280) < 768;
if (isMobile) {
await page.waitForURL(/\/#\/item\/\d+/, { timeout: 10000 });
}

await page.getByRole('link', { name: /hackertok/i }).click();

// /#/ on desktop, /#/item/<first-id> on mobile (auto swipe-viewer rewrite).
await expect(page).toHaveURL(/\/#\/(item\/\d+)?$/);
// On mobile, wait for the top swipe-rewrite to settle (ensures top
// stories have loaded and replaced the old show content in the DOM).
if (isMobile) {
await page.waitForURL(/\/#\/item\/12345/, { timeout: 10000 });
} else {
await expect(page).toHaveURL(/\/#\/(item\/\d+)?$/);
}

// On mobile, wait for the swipe-viewer panel to become active before
// asserting visibility (Safari may need an extra frame after route change).
await expectTopStoryVisible(page);
});

Expand Down
46 changes: 21 additions & 25 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import { HashRouter, Routes, Route, useParams, useLocation, useNavigate } from 'react-router-dom';
import { lazy, Suspense, useState, useEffect, type ReactNode } from 'react';
import { useState, useEffect, type ReactNode } from 'react';
import { ThemeProvider } from './context/ThemeContext';
import { ScrollContainerProvider } from './context/ScrollContainerContext';
import { useScrollContainer } from './hooks/useScrollContainer';
import { Header, ErrorBoundary, FullScreenCommentSkeletonPanel, Spinner, StateView, NetworkStatusBar } from './components';
import { Header, ErrorBoundary, FullScreenCommentSkeletonPanel, StateView, NetworkStatusBar } from './components';
import { TooltipProvider } from './components/ui';
import { StoryList } from './pages';
import { useIsMobile } from './hooks/useIsMobile';
import { useDocumentTitle } from './hooks/useDocumentTitle';

// Lazy-loaded route components for code splitting
const ItemDetail = lazy(() => import('./pages/ItemDetail').then(m => ({ default: m.ItemDetail })));
const DomainStories = lazy(() => import('./pages/DomainStories').then(m => ({ default: m.DomainStories })));
const UserProfile = lazy(() => import('./pages/UserProfile').then(m => ({ default: m.UserProfile })));
const UserSubmissions = lazy(() => import('./pages/UserSubmissions').then(m => ({ default: m.UserSubmissions })));
const SwipeStoryViewer = lazy(() => import('./components/SwipeStoryViewer').then(m => ({ default: m.SwipeStoryViewer })));
const SwipeDomainStoryViewer = lazy(() => import('./components/SwipeDomainStoryViewer').then(m => ({ default: m.SwipeDomainStoryViewer })));
const SwipeUserSubmissionsViewer = lazy(() => import('./components/SwipeUserSubmissionsViewer').then(m => ({ default: m.SwipeUserSubmissionsViewer })));
const SwipeCommentViewer = lazy(() => import('./components/SwipeCommentViewer').then(m => ({ default: m.SwipeCommentViewer })));
import { ItemDetail } from './pages/ItemDetail';
import { DomainStories } from './pages/DomainStories';
import { UserProfile } from './pages/UserProfile';
import { UserSubmissions } from './pages/UserSubmissions';
import { SwipeStoryViewer } from './components/SwipeStoryViewer';
import { SwipeDomainStoryViewer } from './components/SwipeDomainStoryViewer';
import { SwipeUserSubmissionsViewer } from './components/SwipeUserSubmissionsViewer';
import { SwipeCommentViewer } from './components/SwipeCommentViewer';
import { NetworkStatusProvider } from './context/NetworkStatusContext';
import { fetchItemOnly } from './api/hn';
import type { FeedType, LocationState } from './types';
Expand Down Expand Up @@ -203,19 +201,17 @@ function App() {
<Header />
<NetworkStatusBar />
<MainContent>
<Suspense fallback={<div className="flex items-center justify-center h-[50vh]"><Spinner size="lg" /></div>}>
<Routes>
<Route path="/" element={<MobileStoryListWrapper type="top" />} />
<Route path="/show" element={<MobileStoryListWrapper type="show" />} />
<Route path="/ask" element={<MobileStoryListWrapper type="ask" />} />
<Route path="/best" element={<MobileStoryListWrapper type="best" />} />
<Route path="/item/:id" element={<MobileItemDetailWrapper />} />
<Route path="/from/*" element={<MobileDomainStoriesWrapper />} />
<Route path="/user/:id" element={<UserProfile />} />
<Route path="/submitted/:id" element={<MobileUserSubmissionsWrapper />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</Suspense>
<Routes>
<Route path="/" element={<MobileStoryListWrapper type="top" />} />
<Route path="/show" element={<MobileStoryListWrapper type="show" />} />
<Route path="/ask" element={<MobileStoryListWrapper type="ask" />} />
<Route path="/best" element={<MobileStoryListWrapper type="best" />} />
<Route path="/item/:id" element={<MobileItemDetailWrapper />} />
<Route path="/from/*" element={<MobileDomainStoriesWrapper />} />
<Route path="/user/:id" element={<UserProfile />} />
<Route path="/submitted/:id" element={<MobileUserSubmissionsWrapper />} />
<Route path="*" element={<NotFoundPage />} />
</Routes>
</MainContent>
</div>
</LocationAwareErrorBoundary>
Expand Down
2 changes: 1 addition & 1 deletion src/components/InfiniteStoryListPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export function InfiniteStoryListPage({
))}
</div>

{hasMore && (
{hasMore && stories.length > 0 && (
<div ref={ref} className="py-4">
{loading && <Spinner />}
</div>
Expand Down
37 changes: 21 additions & 16 deletions src/hooks/usePrefetchItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,32 @@ const MAX_CONCURRENT = 3;
const prefetchQueue = new Map<number, { index: number }>(); // itemId -> { index }
const activePrefetches = new Map<number, AbortController>(); // itemId -> AbortController
let isProcessing = false;
let scheduleTimeout: ReturnType<typeof setTimeout> | null = null;
let cancelSchedule: (() => void) | null = null;
let priorityUnsubscribe: (() => void) | null = null;

// Debounce so all visible items land in the queue before processing starts —
// 200ms is enough for IntersectionObservers to fire and React to flush state.
// Defer to browser idle so prefetches don't compete with initial render/paint.
// Timeout ensures they still start within 2s on busy pages.
function scheduleProcessQueue() {
if (scheduleTimeout) return;
scheduleTimeout = setTimeout(() => {
scheduleTimeout = null;
void processQueue();
}, 200);
if (cancelSchedule) return; // Already scheduled

if (typeof requestIdleCallback !== 'undefined') {
const id = requestIdleCallback(() => {
cancelSchedule = null;
void processQueue();
}, { timeout: 2000 });
cancelSchedule = () => { cancelIdleCallback(id); cancelSchedule = null; };
} else {
// Fallback for environments without requestIdleCallback (SSR, old WebViews)
const id = setTimeout(() => {
cancelSchedule = null;
void processQueue();
}, 200);
cancelSchedule = () => { clearTimeout(id); cancelSchedule = null; };
}
}

function processQueueNow() {
if (scheduleTimeout) {
clearTimeout(scheduleTimeout);
scheduleTimeout = null;
}
cancelSchedule?.();
void processQueue();
}

Expand Down Expand Up @@ -169,10 +177,7 @@ export function usePrefetchItems(currentIndex: number, items: Item[], count = 3)

/** Cancel all in-flight prefetches. Call when navigating to an item. */
export function cancelAllPrefetches() {
if (scheduleTimeout) {
clearTimeout(scheduleTimeout);
scheduleTimeout = null;
}
cancelSchedule?.();

prefetchQueue.clear();

Expand Down
8 changes: 8 additions & 0 deletions src/test/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ globalThis.ResizeObserver = MockResizeObserver;
globalThis.requestAnimationFrame = vi.fn((cb: FrameRequestCallback) => setTimeout(() => cb(performance.now()), 16) as unknown as number);
globalThis.cancelAnimationFrame = vi.fn((id: number) => clearTimeout(id));

// Polyfill requestIdleCallback for jsdom so that Vitest's fake-timer system
// (which natively supports requestIdleCallback) will detect and replace it.
// The implementation here doesn't matter — fake timers override it entirely.
if (typeof globalThis.requestIdleCallback === 'undefined') {
(globalThis as unknown as Record<string, unknown>).requestIdleCallback = function requestIdleCallback() { return 0; };
(globalThis as unknown as Record<string, unknown>).cancelIdleCallback = function cancelIdleCallback() { /* noop */ };
}

// Stub window.scrollTo (not implemented in jsdom)
window.scrollTo = vi.fn() as typeof window.scrollTo;

Expand Down