From 448d378e0dc814a4aedc2bed913b87e60804657c Mon Sep 17 00:00:00 2001 From: therealsama <263038098+therealsama@users.noreply.github.com> Date: Sat, 30 May 2026 17:05:00 +0200 Subject: [PATCH] perf: use requestIdleCallback for prefetch and fix CLS layout shift - Defer comment prefetching with requestIdleCallback (2s timeout fallback) to avoid competing with critical rendering and network requests - Gate load-more sentinel on stories.length > 0 to eliminate CLS 0.145 layout shift caused by sentinel rendering before content - Remove route-level lazy/Suspense to eliminate loading-flash on navigation (+7KB gzip initial load; eliminates 12 chunk fetches on route transitions) - Add requestIdleCallback/cancelIdleCallback stubs to test setup for Vitest fake-timer compatibility --- e2e/navigation.spec.ts | 34 ++++++++++++++---- src/App.tsx | 46 +++++++++++------------- src/components/InfiniteStoryListPage.tsx | 2 +- src/hooks/usePrefetchItem.ts | 37 ++++++++++--------- src/test/setup.ts | 8 +++++ 5 files changed, 79 insertions(+), 48 deletions(-) diff --git a/e2e/navigation.spec.ts b/e2e/navigation.spec.ts index a7cf5b2..781eb55 100644 --- a/e2e/navigation.spec.ts +++ b/e2e/navigation.spec.ts @@ -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/. 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/ with - // state.from="show"). Without this, on Mobile Safari the old URL - // /#/item/ 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 }); @@ -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). @@ -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/ 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); }); diff --git a/src/App.tsx b/src/App.tsx index 38ecf54..f1631bd 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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'; @@ -203,19 +201,17 @@ function App() {
- }> - - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - - + + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + diff --git a/src/components/InfiniteStoryListPage.tsx b/src/components/InfiniteStoryListPage.tsx index 28c2bf2..c6ff583 100644 --- a/src/components/InfiniteStoryListPage.tsx +++ b/src/components/InfiniteStoryListPage.tsx @@ -137,7 +137,7 @@ export function InfiniteStoryListPage({ ))} - {hasMore && ( + {hasMore && stories.length > 0 && (
{loading && }
diff --git a/src/hooks/usePrefetchItem.ts b/src/hooks/usePrefetchItem.ts index b13a7ea..2fd2171 100644 --- a/src/hooks/usePrefetchItem.ts +++ b/src/hooks/usePrefetchItem.ts @@ -10,24 +10,32 @@ const MAX_CONCURRENT = 3; const prefetchQueue = new Map(); // itemId -> { index } const activePrefetches = new Map(); // itemId -> AbortController let isProcessing = false; -let scheduleTimeout: ReturnType | 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(); } @@ -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(); diff --git a/src/test/setup.ts b/src/test/setup.ts index 07540ed..1f46d8f 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -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).requestIdleCallback = function requestIdleCallback() { return 0; }; + (globalThis as unknown as Record).cancelIdleCallback = function cancelIdleCallback() { /* noop */ }; +} + // Stub window.scrollTo (not implemented in jsdom) window.scrollTo = vi.fn() as typeof window.scrollTo;