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 6fb7108..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. @@ -254,15 +210,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 +225,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 }); @@ -376,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); @@ -506,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 c612425..ee640f8 100644 --- a/e2e/user-profile.spec.ts +++ b/e2e/user-profile.spec.ts @@ -1,5 +1,9 @@ import { test, expect } from '@playwright/test'; -import { setupApiMocks, stubNotFoundUser } from './fixtures/api-mocks'; +import { + setupApiMocks, + createFirebaseWsHandler, + FIREBASE_WS_PATTERN, +} from './fixtures/api-mocks'; import { waitForSwipeReady } from './fixtures/swipe-helpers'; test.describe('User Profile - Desktop', () => { @@ -40,6 +44,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'); @@ -83,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/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/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/App.tsx b/src/App.tsx index e963c31..c6048c1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -4,12 +4,12 @@ import { ThemeProvider } from './context/ThemeContext'; import { ScrollContainerProvider } from './context/ScrollContainerContext'; import { useScrollContainer } from './hooks/useScrollContainer'; import { Header, ErrorBoundary, FullScreenCommentSkeletonPanel, StateView, NetworkStatusBar } from './components'; -import { TooltipProvider } from './components/ui'; import { StoryList } from './pages'; 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'; @@ -35,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 @@ -55,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; @@ -280,47 +286,45 @@ function LocationAwareErrorBoundary({ children }: { children: ReactNode }) { function App() { return ( - - - - - - - - - - - + + + + + + + + + ); } diff --git a/src/api/hn.fetchTaggedStories.test.ts b/src/api/hn.fetchTaggedStories.test.ts index 8badab8..2cbd250 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,30 +78,12 @@ 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 () => { - 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, @@ -126,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 d30dcd0..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', () => { @@ -1611,7 +1386,7 @@ describe('hn API utilities', () => { return firebaseItems.find(fb => fb.id === Number(id)) ?? null; }); - await expect(fetchCommentReplies(liveReply, controller.signal)).rejects.toThrow('Aborted'); + await expect(fetchCommentReplies(liveReply, controller.signal)).rejects.toMatchObject({ name: 'AbortError' }); expect(fetchSpy).not.toHaveBeenCalled(); }); diff --git a/src/api/hn.ts b/src/api/hn.ts index a179289..04d72e4 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 { @@ -20,37 +21,23 @@ export class CommentsError extends Error { } } -let bestStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; -let showStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; -let askStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; -let newStoriesCache: { ids: number[] | null; timestamp: number } = { ids: null, timestamp: 0 }; +const rankedIdsCache = new Map(); let storyCommentsCache: { storyId: number; comments: Promise; timestamp: number } | null = null; const CACHE_TTL = 5 * 60 * 1000; // 5 minutes /** @internal Testing helper to reset module-level caches between tests. */ export function __resetFetchCachesForTests() { - bestStoriesCache = { ids: null, timestamp: 0 }; - showStoriesCache = { ids: null, timestamp: 0 }; - askStoriesCache = { ids: null, timestamp: 0 }; - newStoriesCache = { ids: null, timestamp: 0 }; + rankedIdsCache.clear(); storyCommentsCache = null; threadDownloads.clear(); } +const SECONDS_PER_DAY = 86_400; + +// Unix time has no leap seconds, so every UTC day is exactly SECONDS_PER_DAY. function getDayRange(daysAgo = 0) { - const now = new Date(); - const startOfToday = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())); - - const targetDay = new Date(startOfToday); - targetDay.setUTCDate(targetDay.getUTCDate() - daysAgo); - - const nextDay = new Date(targetDay); - nextDay.setUTCDate(nextDay.getUTCDate() + 1); - - return { - start: Math.floor(targetDay.getTime() / 1000), - end: Math.floor(nextDay.getTime() / 1000), - }; + const day = Math.floor(Date.now() / (SECONDS_PER_DAY * 1000)) - daysAgo; + return { start: day * SECONDS_PER_DAY, end: (day + 1) * SECONDS_PER_DAY }; } // Feed endpoints only return stories (polls among them). @@ -111,15 +98,7 @@ function normalizeFirebaseItem(fbItem: FirebaseItem): Item { // Firebase doesn't distinguish ask/show — they're all type='story'. // Only the Algolia path (via _tags) can set 'ask'/'show' sub-types. // A poll's options are separate items, read with its comments. - return { - ...base, - type: fbItem.type === 'poll' ? 'poll' : 'story', - title: fbItem.title ?? '', - url: fbItem.url, - text: fbItem.text, - points: fbItem.score ?? 0, - commentCount: fbItem.descendants ?? 0, - }; + return normalizeFirebaseToStoryItem(fbItem); } /** @@ -140,8 +119,7 @@ export async function fetchTopStories(limit = 20): Promise { if (stories.length >= limit) break; if (!item || item.deleted || item.dead) continue; if (item.type === 'job') continue; - const title = (item.title ?? '').toLowerCase(); - if (title.includes('who is hiring') || title.includes('who wants to be hired')) continue; + if (isHiringThread(item.title)) continue; stories.push(normalizeFirebaseToStoryItem(item)); } cursor += batchIds.length; @@ -150,112 +128,48 @@ 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; - } - const title = (hit.title || '').toLowerCase(); - if (title.includes('who is hiring') || - title.includes('who wants to be hired')) { - return false; - } - return true; - }); - - 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); } -export async function fetchBestStories(offset = 0, limit = 30) { - const now = Date.now(); - - if (!bestStoriesCache.ids || (now - bestStoriesCache.timestamp) >= CACHE_TTL) { - bestStoriesCache = { ids: await hnSdk.readRankedIds('beststories'), timestamp: now }; - } - - const allIds = bestStoriesCache.ids ?? []; - const pageIds = allIds.slice(offset, offset + limit); - - if (pageIds.length === 0) { - return { stories: [] as StoryItem[], hasMore: false, nextOffset: offset }; - } - - const fetched = await Promise.all( - pageIds.map((id: number) => hnSdk.readItem(id).catch(() => null)) - ); - - // The whoishiring threads are type='story', not 'job', so the job filter - // alone lets them through when they rank among the best. - const stories = fetched - .filter((fb): fb is FirebaseItem => - fb != null && - !fb.deleted && - !fb.dead && - fb.type !== 'job' && - !isHiringThread(fb.title) - ) - .map(fb => normalizeFirebaseToStoryItem(fb)); - - return { - stories, - hasMore: offset + limit < allIds.length, - nextOffset: offset + limit, - }; +// 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)); } -// Newest feed: reverse-chronological submissions from HN `newstories` (≤500, -// HN's hard cap). Mirrors fetchBestStories' offset pagination, including the -// whoishiring filter. -export async function fetchNewStories(offset = 0, limit = 30) { - const now = Date.now(); - - if (!newStoriesCache.ids || (now - newStoriesCache.timestamp) >= CACHE_TTL) { - newStoriesCache = { ids: await hnSdk.readRankedIds('newstories'), timestamp: now }; - } - - const allIds = newStoriesCache.ids ?? []; - const pageIds = allIds.slice(offset, offset + limit); - - if (pageIds.length === 0) { - return { stories: [] as StoryItem[], hasMore: false, nextOffset: offset }; - } - - const fetched = await Promise.all( - pageIds.map((id: number) => hnSdk.readItem(id).catch(() => null)) - ); - - const stories = fetched - .filter((fb): fb is FirebaseItem => - fb != null && - !fb.deleted && - !fb.dead && - fb.type !== 'job' && - !isHiringThread(fb.title) - ) - .map(fb => normalizeFirebaseToStoryItem(fb)); +export function fetchBestStories(offset = 0, limit = 30) { + return fetchRankedStories('beststories', offset, { limit, excludeJobs: true, excludeHiring: true }); +} - return { - stories, - hasMore: offset + limit < allIds.length, - nextOffset: offset + limit, - }; +// Newest feed: reverse-chronological submissions from HN `newstories` (≤500, +// HN's hard cap), filtered like the best feed. +export function fetchNewStories(offset = 0, limit = 30) { + return fetchRankedStories('newstories', offset, { limit, excludeJobs: true, excludeHiring: true }); } /** A poll option has no title or comments, so it gets a page of its own. */ @@ -277,21 +191,31 @@ function normalizeFirebaseToStoryItem(fb: FirebaseItem): StoryItem { }; } +async function readRankedIdsCached(list: string): Promise { + const now = Date.now(); + const cached = rankedIdsCache.get(list); + if (cached && now - cached.timestamp < CACHE_TTL) return cached.ids; + const ids = await hnSdk.readRankedIds(list); + rankedIdsCache.set(list, { ids, timestamp: now }); + return ids; +} + +interface RankedPageOptions { + limit: number; + /** Firebase can't tell ask/show from story, so the list sets it. Polls keep theirs. */ + type?: 'show' | 'ask'; + excludeJobs?: boolean; + // The whoishiring threads are type='story', not 'job', so the job filter + // alone lets them through. + excludeHiring?: boolean; +} + async function fetchRankedStories( list: string, - cache: { ids: number[] | null; timestamp: number }, - type: 'show' | 'ask', - offset = 0, - limit = 20, - excludeTitles?: string[], + offset: number, + { limit, type, excludeJobs = false, excludeHiring = false }: RankedPageOptions, ) { - const now = Date.now(); - if (!cache.ids || (now - cache.timestamp) >= CACHE_TTL) { - cache.ids = await hnSdk.readRankedIds(list); - cache.timestamp = now; - } - - const allIds = cache.ids ?? []; + const allIds = await readRankedIdsCached(list); const pageIds = allIds.slice(offset, offset + limit); if (pageIds.length === 0) { @@ -307,9 +231,13 @@ async function fetchRankedStories( fb != null && !fb.deleted && !fb.dead && - !excludeTitles?.some(t => (fb.title ?? '').toLowerCase().includes(t)) + !(excludeJobs && fb.type === 'job') && + !(excludeHiring && isHiringThread(fb.title)) ) - .map(fb => ({ ...normalizeFirebaseToStoryItem(fb), type: fb.type === 'poll' ? 'poll' as const : type })); + .map(fb => { + const story = normalizeFirebaseToStoryItem(fb); + return type && story.type !== 'poll' ? { ...story, type } : story; + }); return { stories, @@ -319,44 +247,22 @@ async function fetchRankedStories( } export function fetchShowStories(offset = 0) { - return fetchRankedStories('showstories', showStoriesCache, 'show', offset); + return fetchRankedStories('showstories', offset, { limit: 20, type: 'show' }); } // Ask excludes the whoishiring threads, matching fetchAskStoriesForDay. Show is // left unfiltered: a Show HN title mentioning hiring is a real project. export function fetchAskStories(offset = 0) { - return fetchRankedStories('askstories', askStoriesCache, 'ask', offset, 20, HIRING_EXCLUDE_TITLES); + 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 = [ @@ -370,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 { @@ -378,9 +284,7 @@ export function fetchShowStoriesForDay(daysAgo: number): Promise { } export async function fetchFirebaseItem(id: number | string, signal?: AbortSignal): Promise { - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } + signal?.throwIfAborted(); const item = await hnSdk.readItem(id); if (item == null) { throw new NotFoundError(`Item ${id} not found`); @@ -395,9 +299,7 @@ export async function fetchFirebaseItem(id: number | string, signal?: AbortSigna */ export async function fetchHiddenCommentIds(ids: number[], keepId: number, signal?: AbortSignal): Promise> { const items = await Promise.all(ids.map(id => hnSdk.readItem(id).catch(() => null))); - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } + signal?.throwIfAborted(); return new Set(ids.filter((id, i) => { const item = items[i]; return id !== keepId && !!item && !item.kids?.length && (!!item.dead || !!item.deleted); @@ -637,9 +539,7 @@ async function itemOnly(raw: FirebaseItem): Promise { // order, but HN's pages sort by points; the sort is stable, so ties keep it. async function fetchPollOptions(parts: number[], signal?: AbortSignal): Promise { const items = await Promise.all(parts.map(id => hnSdk.readItem(id))); - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } + signal?.throwIfAborted(); return items .filter((item): item is FirebaseItem => item != null && !item.deleted && !item.dead) .map(item => ({ id: item.id, text: item.text ?? '', points: item.score ?? 0 })) @@ -669,14 +569,12 @@ async function fetchThread( const raw = await itemRead.catch(() => null); if (!raw) throw err; const item = threadItem(raw, await pollOptionsRead); - if (signal?.aborted) throw new DOMException('Aborted', 'AbortError'); - throw new CommentsError(err instanceof Error ? err.message : String(err), item); + signal?.throwIfAborted(); + throw new CommentsError(errorMessage(err), item); }); const [raw, comments] = await Promise.all([itemRead, commentsRead]); - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } + signal?.throwIfAborted(); const [commentTree, pollOptions] = await Promise.all([ buildOrderedCommentTree(comments, itemId, raw.kids, signal), @@ -769,9 +667,7 @@ export async function prefetchItemComments(id: number | string, signal?: AbortSi /** The comment tree plus the item it hangs off, which the ordering reads anyway. */ export async function fetchItemWithComments(id: number | string, signal: AbortSignal | null = null): Promise { - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } + signal?.throwIfAborted(); return downloadThread(Number(id), signal ?? undefined).thread; } @@ -888,16 +784,12 @@ async function hasRepliesOutsideItemTree(id: number, signal?: AbortSignal): Prom export async function fetchCommentReplies(item: AlgoliaItemResponse, signal?: AbortSignal): Promise { if (item.story_id == null) return normalizeAlgoliaItemChildren(item.children ?? []); const mayHaveMore = !!item.children?.length || await hasRepliesOutsideItemTree(item.id, signal); - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } + signal?.throwIfAborted(); if (!mayHaveMore) return []; // Null for a thread bigger than search returns, which keeps the item tree's replies. const storyComments = await fetchStoryComments(item.story_id); - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } + signal?.throwIfAborted(); const replies = flattenAlgoliaItemChildren(item.children ?? []); const seen = new Set(replies.map(c => c.objectID)); @@ -927,9 +819,8 @@ export function normalizeAlgoliaItemChildren(children: AlgoliaItemChild[]): Comm } // Format timestamp as a localized absolute date string for tooltips. -// Guards reject null/undefined/zero (`!timestamp`), NaN, AND ±Infinity — -// the latter would otherwise slip through (`!Infinity` is false, -// `isNaN(Infinity)` is false) and make the formatter throw a RangeError. +// Guards reject null/undefined/zero (`!timestamp`), and `isFinite` rejects NaN +// and ±Infinity, which would otherwise make the formatter throw a RangeError. // The formatter is built once: Date#toLocaleString builds a new one per call, // which showed up in swipe profiles (every comment renders a timestamp). const absoluteTimeFormat = new Intl.DateTimeFormat(undefined, { @@ -937,14 +828,14 @@ const absoluteTimeFormat = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit', }); export function formatAbsoluteTime(timestamp: number): string { - if (!timestamp || !isFinite(timestamp) || isNaN(timestamp)) return ''; + if (!timestamp || !isFinite(timestamp)) return ''; return absoluteTimeFormat.format(timestamp); } // Long-month date-only (e.g. "October 9, 2006") for profile creation dates // where minute precision isn't meaningful. export function formatAbsoluteDate(timestamp: number): string { - if (!timestamp || !isFinite(timestamp) || isNaN(timestamp)) return ''; + if (!timestamp || !isFinite(timestamp)) return ''; return new Date(timestamp).toLocaleString(undefined, { year: 'numeric', month: 'long', day: 'numeric', }); @@ -953,13 +844,13 @@ export function formatAbsoluteDate(timestamp: number): string { // Safe ISO string for