diff --git a/e2e/fixtures/api-mocks.ts b/e2e/fixtures/api-mocks.ts index a31d079..886d88a 100644 --- a/e2e/fixtures/api-mocks.ts +++ b/e2e/fixtures/api-mocks.ts @@ -18,6 +18,10 @@ import { mockBestItem1, mockBestItem2, mockBestItem3, + mockNewItemIds, + mockNewItem1, + mockNewItem2, + mockNewItem3, mockDomainItem, mockPaginationItem1, mockPaginationItem2, @@ -82,6 +86,9 @@ function buildItemsMap(): Record { 33001: mockBestItem1, 33002: mockBestItem2, 33003: mockBestItem3, + 44001: mockNewItem1, + 44002: mockNewItem2, + 44003: mockNewItem3, 99999: { id: 99999, title: mockShowHNItem1.title, @@ -171,6 +178,7 @@ function resolveFirebasePath( if (p === 'v0/topstories') return mockTopItemIds; if (p === 'v0/beststories') return mockBestItemIds; + if (p === 'v0/newstories') return mockNewItemIds; if (p === 'v0/showstories') return [99999, 99998]; if (p === 'v0/askstories') return [88888, 88887]; diff --git a/e2e/fixtures/mock-data.ts b/e2e/fixtures/mock-data.ts index 9dd4cec..06c1a2c 100644 --- a/e2e/fixtures/mock-data.ts +++ b/e2e/fixtures/mock-data.ts @@ -157,7 +157,7 @@ export const mockBestItem1 = { export const mockBestItem2 = { id: 33002, title: 'How We Scaled to 1M Users with PostgreSQL', - url: 'https://techblog.example.dev/postgres-scale', + url: 'https://techblog.example.com/postgres-scale', by: 'alexgarcia', score: 389, time: now() - 7200, @@ -176,6 +176,43 @@ export const mockBestItem3 = { type: 'story', }; +export const mockNewItemIds = [44001, 44002, 44003]; + +// Newest items use distinct IDs/titles so the /newest route is observably +// different from /top and /best (guards against a mock leak in the nav test). +// Titles deliberately avoid the whoishiring monthly-thread phrases. +export const mockNewItem1 = { + id: 44001, + title: 'Just Shipped: A Tiny Static Site Generator in Rust', + url: 'https://example.com/tiny-ssg-rust', + by: 'freshdev', + score: 8, + time: now() - 120, + descendants: 2, + type: 'story', +}; + +export const mockNewItem2 = { + id: 44002, + title: 'Show HN: I Built a CLI to Track My Reading', + url: 'https://example.com/reading-cli', + by: 'bookworm', + score: 15, + time: now() - 240, + descendants: 5, + type: 'story', +}; + +export const mockNewItem3 = { + id: 44003, + title: 'Ask HN: What Small Habits Improved Your Coding?', + by: 'curiouscoder', + score: 4, + time: now() - 360, + descendants: 3, + type: 'story', +}; + export const mockDomainItem = { objectID: '77777', title: 'Google Announces Gemini 3.0 with Extended Context', diff --git a/e2e/navigation.spec.ts b/e2e/navigation.spec.ts index fb7fc6d..e30024f 100644 --- a/e2e/navigation.spec.ts +++ b/e2e/navigation.spec.ts @@ -97,6 +97,30 @@ test.describe('Navigation', () => { await expect(page.getByRole('link', { name: 'show', exact: true })).not.toHaveClass(/bg-accent/); }); + test('navigates to New section', async ({ page }) => { + await page.goto('/#/'); + + await expect(page.locator('header')).toBeVisible(); + + // force: true so the click hits the header link rather than an + // intercepting story card on mobile widths. + const newLink = page.getByRole('link', { name: /new/i }); + await newLink.scrollIntoViewIfNeeded(); + await newLink.click({ force: true }); + + await expect(page).toHaveURL(/\/#\/(newest|item\/)/); + + await expect(page).toHaveTitle(/New.*HackerTok|HackerTok/); + + // Newest-specific content (not just URL/title) — guards against a mock leak. + await expect(page.getByText('Just Shipped: A Tiny Static Site Generator in Rust')).toBeVisible(); + + await expect(page.getByRole('link', { name: 'new', exact: true })).toHaveClass(/bg-accent/); + await expect(page.getByRole('link', { name: 'best', exact: true })).not.toHaveClass(/bg-accent/); + await expect(page.getByRole('link', { name: 'ask', exact: true })).not.toHaveClass(/bg-accent/); + await expect(page.getByRole('link', { name: 'show', exact: true })).not.toHaveClass(/bg-accent/); + }); + test('navigates back to Top from other section', async ({ page }) => { await page.goto('/#/show'); diff --git a/e2e/user-profile.spec.ts b/e2e/user-profile.spec.ts index 41c6589..479348c 100644 --- a/e2e/user-profile.spec.ts +++ b/e2e/user-profile.spec.ts @@ -113,7 +113,7 @@ test.describe('User Profile - Mobile', () => { test('clears swipe-mode after mount on direct /user/:id load', async ({ page }) => { // index.html's bootstrap script optimistically adds `swipe-mode` to // and for ANY `#/...` route on mobile (the regex - // `^#\/(show|ask|best|item\/)?` is not end-anchored and the group is + // `^#\/(show|ask|best|newest|item\/)?` is not end-anchored and the group is // optional, so `#/user/pg` matches via the empty-group fallback). That // class sets `overflow: clip` on the body, which would wedge the // vertically scrollable profile if nothing cleared it. UserProfile's diff --git a/index.html b/index.html index f6ba38f..939b38f 100644 --- a/index.html +++ b/index.html @@ -105,8 +105,7 @@ (function() { var isMobile = window.innerWidth < 768; var hash = window.location.hash || '#/'; - // Swipe routes: /, /show, /ask, /best, /item/* - var isSwipeRoute = /^#\/(show|ask|best|item\/)?/.test(hash); + var isSwipeRoute = /^#\/(show|ask|best|newest|item\/)?/.test(hash); if (isMobile && isSwipeRoute) { document.documentElement.classList.add('swipe-mode'); document.body.classList.add('swipe-mode'); diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest index e8bcbf0..df71a64 100644 --- a/public/manifest.webmanifest +++ b/public/manifest.webmanifest @@ -69,6 +69,13 @@ "description": "Community projects and demos", "url": "/#/show", "icons": [{ "src": "/icons/icon-192.png", "sizes": "192x192" }] + }, + { + "name": "New Stories", + "short_name": "New", + "description": "The latest stories as they're posted", + "url": "/#/newest", + "icons": [{ "src": "/icons/icon-192.png", "sizes": "192x192" }] } ] } diff --git a/src/App.tsx b/src/App.tsx index 8682179..ff82d9f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -234,6 +234,7 @@ function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/api/hn.fetchTaggedStories.test.ts b/src/api/hn.fetchTaggedStories.test.ts index 66f212b..8badab8 100644 --- a/src/api/hn.fetchTaggedStories.test.ts +++ b/src/api/hn.fetchTaggedStories.test.ts @@ -153,7 +153,7 @@ describe('fetchAskStoriesForDay', () => { const hits = [ makeHit(1, 'Ask HN: Who is hiring? (May 2026)', 300, ['ask_hn']), makeHit(2, 'Ask HN: Good question', 100, ['ask_hn']), - makeHit(3, 'Ask HN: Freelancer? Seeking Freelancer', 80, ['ask_hn']), + makeHit(3, 'Ask HN: Who wants to be hired? (May 2026)', 80, ['ask_hn']), ]; (fetch as ReturnType).mockResolvedValue({ ok: true, diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index ac352f4..04c95da 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -10,6 +10,7 @@ import { fetchAskStories, fetchTopStories, fetchBestStories, + fetchNewStories, fetchFirebaseItem, fetchItemOnly, fetchAlgoliaItem, @@ -600,6 +601,114 @@ describe('hn API utilities', () => { }); }); + describe('fetchNewStories', () => { + const mockNewIds = [44001, 44002, 44003]; + const mockNewItems: Record = { + 44001: { id: 44001, title: 'A brand new Rust web framework', url: 'https://example.com/rust', by: 'newuser1', score: 5, time: Math.floor(Date.now() / 1000) - 300, descendants: 2, type: 'story' }, + 44002: { id: 44002, title: 'Show HN: My weekend hardware hack', url: 'https://example.com/hw', by: 'newuser2', score: 12, time: Math.floor(Date.now() / 1000) - 180, descendants: 4, type: 'story' }, + 44003: { id: 44003, title: 'Ask HN: How do you stay focused?', text: 'Curious', by: 'newuser3', score: 3, time: Math.floor(Date.now() / 1000) - 60, descendants: 1, type: 'story' }, + }; + + beforeEach(() => { + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(mockNewIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => mockNewItems[Number(id)] ?? null); + }); + + it('reads the newstories ranked list', async () => { + await fetchNewStories(0); + 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); + + result.stories.forEach(item => { + expect(item.type).toBe('story'); + }); + }); + + 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); + + expect(result.stories.length).toBe(3); + expect(result.stories[0].id).toBe(44001); + expect(result.stories[1].id).toBe(44002); + expect(result.stories[2].id).toBe(44003); + }); + + it('paginates by offset', async () => { + const manyIds = Array.from({ length: 35 }, (_, i) => 40000 + i); + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(manyIds); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => ({ + id: Number(id), title: `Item ${id}`, by: 'user', score: 10, time: Math.floor(Date.now() / 1000), descendants: 0, type: 'story', + })); + + const result1 = await fetchNewStories(0); + expect(result1.nextOffset).toBe(30); + expect(result1.hasMore).toBe(true); + + const result2 = await fetchNewStories(result1.nextOffset); + expect(result2.stories.length).toBe(5); + expect(result2.hasMore).toBe(false); + }); + + it('filters out job posts', async () => { + const idsWithJob = [44001, 44900, 44002]; + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(idsWithJob); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 44900) { + return { id: 44900, title: 'Acme Corp (YC S26) Is Hiring Engineers', url: 'https://acme.example', by: 'acmehr', score: 1, time: Math.floor(Date.now() / 1000), descendants: 0, type: 'job' }; + } + return mockNewItems[Number(id)] ?? null; + }); + + const result = await fetchNewStories(0); + + expect(result.stories.map(s => s.id)).not.toContain(44900); + expect(result.stories.map(s => s.id)).toEqual([44001, 44002]); + }); + + it('filters out the monthly whoishiring threads', async () => { + const idsWithHiring = [44001, 44910, 44911, 44002]; + vi.spyOn(hnSdk, 'readRankedIds').mockResolvedValue(idsWithHiring); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + const hiring: Record = { + 44910: { id: 44910, title: 'Ask HN: Who is hiring? (July 2026)', by: 'whoishiring', score: 100, time: Math.floor(Date.now() / 1000), descendants: 500, type: 'story' }, + 44911: { id: 44911, title: 'Ask HN: Who wants to be hired? (July 2026)', by: 'whoishiring', score: 80, time: Math.floor(Date.now() / 1000), descendants: 200, type: 'story' }, + }; + return hiring[Number(id)] ?? mockNewItems[Number(id)] ?? null; + }); + + const result = await fetchNewStories(0); + const ids = result.stories.map(s => s.id); + + expect(ids).not.toContain(44910); + expect(ids).not.toContain(44911); + expect(ids).toEqual([44001, 44002]); + }); + }); + describe('fetchTopStories', () => { const mockTopIds = [12345, 12346, 12347]; const mockTopItems: Record = { diff --git a/src/api/hn.ts b/src/api/hn.ts index e0be408..687eb1b 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -12,6 +12,7 @@ export class NotFoundError 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 CACHE_TTL = 5 * 60 * 1000; // 5 minutes /** @internal Testing helper to reset module-level caches between tests. */ @@ -19,6 +20,7 @@ export function __resetFetchCachesForTests() { bestStoriesCache = { ids: null, timestamp: 0 }; showStoriesCache = { ids: null, timestamp: 0 }; askStoriesCache = { ids: null, timestamp: 0 }; + newStoriesCache = { ids: null, timestamp: 0 }; } function getDayRange(daysAgo = 0) { @@ -140,10 +142,8 @@ export async function fetchFrontPageForDay(daysAgo = 1): Promise { return false; } const title = (hit.title || '').toLowerCase(); - if (title.includes('who is hiring') || - title.includes('who wants to be hired') || - title.includes('freelancer?') || - title.includes('seeking freelancer')) { + if (title.includes('who is hiring') || + title.includes('who wants to be hired')) { return false; } return true; @@ -183,6 +183,45 @@ export async function fetchBestStories(offset = 0, limit = 30) { }; } +// Newest feed: reverse-chronological submissions from HN `newstories` (≤500, +// HN's hard cap). Mirrors fetchBestStories' offset pagination but additionally +// filters the whoishiring bot's monthly threads (they are type='story', not +// 'job', so the job filter alone misses them). Reuses HIRING_EXCLUDE_TITLES. +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' && + !HIRING_EXCLUDE_TITLES.some(t => (fb.title ?? '').toLowerCase().includes(t)) + ) + .map(fb => normalizeFirebaseToStoryItem(fb)); + + return { + stories, + hasMore: offset + limit < allIds.length, + nextOffset: offset + limit, + }; +} + function normalizeFirebaseToStoryItem(fb: FirebaseItem): StoryItem { return { id: fb.id, @@ -271,15 +310,13 @@ export async function fetchTaggedStoriesForDay( return sorted.map(normalizeAlgoliaHit); } -const ASK_EXCLUDE_TITLES = [ +const HIRING_EXCLUDE_TITLES = [ 'who is hiring', 'who wants to be hired', - 'freelancer?', - 'seeking freelancer', ]; export function fetchAskStoriesForDay(daysAgo: number): Promise { - return fetchTaggedStoriesForDay('ask_hn', daysAgo, ASK_EXCLUDE_TITLES); + return fetchTaggedStoriesForDay('ask_hn', daysAgo, HIRING_EXCLUDE_TITLES); } export function fetchShowStoriesForDay(daysAgo: number): Promise { diff --git a/src/components/Header.test.tsx b/src/components/Header.test.tsx index 949defd..b8ff46e 100644 --- a/src/components/Header.test.tsx +++ b/src/components/Header.test.tsx @@ -71,36 +71,41 @@ describe('Header', () => { // The feed-agnostic "no nav state on item page" case lives outside the // parameterised block — it doesn't depend on which feed we ask about, // only that no feed should ever light up without explicit context. - const FEEDS = ['best', 'show', 'ask'] as const; - describe.each(FEEDS)('%s feed tab', (feed) => { - const linkRe = new RegExp(feed, 'i'); + const FEEDS = [ + { key: 'best', label: 'best', route: '/best' }, + { key: 'show', label: 'show', route: '/show' }, + { key: 'ask', label: 'ask', route: '/ask' }, + { key: 'newest', label: 'new', route: '/newest' }, + ] as const; + describe.each(FEEDS)('$key feed tab', ({ key, label, route }) => { + const linkRe = new RegExp(label, 'i'); const getLink = () => screen.getByRole('link', { name: linkRe }); - it(`renders the ${feed} navigation link`, () => { + it(`renders the ${key} navigation link`, () => { render(
); expect(getLink()).toBeInTheDocument(); }); - it(`highlights ${feed} on /${feed} route`, () => { - render(
, { initialEntries: [`/${feed}`] }); + it(`highlights ${key} on ${route} route`, () => { + render(
, { initialEntries: [route] }); expect(getLink()).toHaveAttribute('aria-current', 'page'); }); - it(`does not highlight ${feed} on home route`, () => { + it(`does not highlight ${key} on home route`, () => { render(
, { initialEntries: ['/'] }); expect(getLink()).not.toHaveAttribute('aria-current'); }); - it(`highlights ${feed} on item detail when state.from=${feed}`, () => { + it(`highlights ${key} on item detail when state.from=${key}`, () => { render(
, { initialEntries: [ - { pathname: '/item/12345', state: { from: feed } }, + { pathname: '/item/12345', state: { from: key } }, ], }); expect(getLink()).toHaveAttribute('aria-current', 'page'); }); - it(`does not highlight ${feed} on item detail when state.from=top`, () => { + it(`does not highlight ${key} on item detail when state.from=top`, () => { render(
, { initialEntries: [ { pathname: '/item/12345', state: { from: 'top' } }, @@ -116,8 +121,8 @@ describe('Header', () => { // agnostic so we assert against every feed in a single render. render(
, { initialEntries: ['/item/12345'] }); - for (const feed of FEEDS) { - const link = screen.getByRole('link', { name: new RegExp(feed, 'i') }); + for (const { label } of FEEDS) { + const link = screen.getByRole('link', { name: new RegExp(label, 'i') }); expect(link).not.toHaveAttribute('aria-current'); } }); @@ -295,18 +300,18 @@ describe('Header', () => { // feed would render BOTH the orange "comments" pill AND an orange // "Best" pill, doubling up the active treatment. it.each(FEEDS)( - 'does not highlight %s feed tab in comment view, even when state.from matches', - (feed) => { + 'does not highlight $key feed tab in comment view, even when state.from matches', + ({ key, label }) => { render(
, { initialEntries: [ { pathname: '/item/12345', - state: { from: feed, isComment: true }, + state: { from: key, isComment: true }, }, ], }); - const link = screen.getByRole('link', { name: new RegExp(feed, 'i') }); + const link = screen.getByRole('link', { name: new RegExp(label, 'i') }); expect(link).not.toHaveAttribute('aria-current'); }, ); @@ -355,9 +360,9 @@ describe('Header', () => { // Locks the canonical packing rule: when an active contextual pill // exists, it lives at index 0 of the