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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions e2e/fixtures/api-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ import {
mockBestItem1,
mockBestItem2,
mockBestItem3,
mockNewItemIds,
mockNewItem1,
mockNewItem2,
mockNewItem3,
mockDomainItem,
mockPaginationItem1,
mockPaginationItem2,
Expand Down Expand Up @@ -82,6 +86,9 @@ function buildItemsMap(): Record<number, object> {
33001: mockBestItem1,
33002: mockBestItem2,
33003: mockBestItem3,
44001: mockNewItem1,
44002: mockNewItem2,
44003: mockNewItem3,
99999: {
id: 99999,
title: mockShowHNItem1.title,
Expand Down Expand Up @@ -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];

Expand Down
39 changes: 38 additions & 1 deletion e2e/fixtures/mock-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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',
Expand Down
24 changes: 24 additions & 0 deletions e2e/navigation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down
2 changes: 1 addition & 1 deletion e2e/user-profile.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <html>
// and <body> 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
Expand Down
3 changes: 1 addition & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
7 changes: 7 additions & 0 deletions public/manifest.webmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -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" }]
}
]
}
1 change: 1 addition & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ function App() {
<Route path="/show" element={<MobileStoryListWrapper type="show" />} />
<Route path="/ask" element={<MobileStoryListWrapper type="ask" />} />
<Route path="/best" element={<MobileStoryListWrapper type="best" />} />
<Route path="/newest" element={<MobileStoryListWrapper type="newest" />} />
<Route path="/item/:id" element={<MobileItemDetailWrapper />} />
<Route path="/from/*" element={<MobileDomainStoriesWrapper />} />
<Route path="/user/:id" element={<UserProfile />} />
Expand Down
2 changes: 1 addition & 1 deletion src/api/hn.fetchTaggedStories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof vi.fn>).mockResolvedValue({
ok: true,
Expand Down
109 changes: 109 additions & 0 deletions src/api/hn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
fetchAskStories,
fetchTopStories,
fetchBestStories,
fetchNewStories,
fetchFirebaseItem,
fetchItemOnly,
fetchAlgoliaItem,
Expand Down Expand Up @@ -600,6 +601,114 @@ describe('hn API utilities', () => {
});
});

describe('fetchNewStories', () => {
const mockNewIds = [44001, 44002, 44003];
const mockNewItems: Record<number, FirebaseItem> = {
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<number, FirebaseItem> = {
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<number, FirebaseItem> = {
Expand Down
53 changes: 45 additions & 8 deletions src/api/hn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ 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. */
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) {
Expand Down Expand Up @@ -140,10 +142,8 @@ export async function fetchFrontPageForDay(daysAgo = 1): Promise<StoryItem[]> {
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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<StoryItem[]> {
return fetchTaggedStoriesForDay('ask_hn', daysAgo, ASK_EXCLUDE_TITLES);
return fetchTaggedStoriesForDay('ask_hn', daysAgo, HIRING_EXCLUDE_TITLES);
}

export function fetchShowStoriesForDay(daysAgo: number): Promise<StoryItem[]> {
Expand Down
Loading