diff --git a/e2e/fixtures/api-mocks.ts b/e2e/fixtures/api-mocks.ts index d42cf25..65061d5 100644 --- a/e2e/fixtures/api-mocks.ts +++ b/e2e/fixtures/api-mocks.ts @@ -404,8 +404,8 @@ export async function setupApiMocks(page: Page) { } else if (tags.includes('front_page')) { hits = [mockAlgoliaItem1, mockAlgoliaItem2, mockAlgoliaItem3]; nbHits = 3; - } else if (tags === 'story') { - // Day-based pagination (tags=story + numericFilters) — distinct items + } else if (tags === '(story,poll)') { + // Day-based pagination (tags=(story,poll) + numericFilters) — distinct items // from the 'front_page' branch above so pagination is observable. hits = [mockPaginationItem1, mockPaginationItem2, mockPaginationItem3]; nbHits = 3; @@ -445,7 +445,7 @@ export async function setupApiMocks(page: Page) { // Algolia: Search by date endpoint. Two callers share this URL: // - `useDomainInfiniteStories` issues `?query=` (no `tags`) - // - `useUserInfiniteStories` issues `?tags=story,author_` (no `query`) + // - `useUserInfiniteStories` issues `?tags=(story,poll),author_` (no `query`) // The author branch is matched FIRST so the absence of a `tags` substring // can never be mis-routed to the domain branch. await page.route(`${ALGOLIA_API}/search_by_date*`, async (route) => { diff --git a/e2e/fixtures/mock-data.ts b/e2e/fixtures/mock-data.ts index 777bd83..57cde00 100644 --- a/e2e/fixtures/mock-data.ts +++ b/e2e/fixtures/mock-data.ts @@ -377,7 +377,7 @@ export const mockUserProfile = { }; // User-submitted stories (Algolia format) returned by the -// `tags=story,author_pg` branch of `search_by_date`. Distinct objectIDs (66666, +// `tags=(story,poll),author_pg` branch of `search_by_date`. Distinct objectIDs (66666, // 66667) so tests asserting URL rewrites or back-navigation can pin specific // indices without colliding with top/best/show/ask/domain mock IDs. export const mockUserStory1 = { diff --git a/e2e/item-detail.spec.ts b/e2e/item-detail.spec.ts index 3fcc3e1..032de60 100644 --- a/e2e/item-detail.spec.ts +++ b/e2e/item-detail.spec.ts @@ -1,6 +1,5 @@ import { test, expect } from '@playwright/test'; import { createFirebaseWsHandler, FIREBASE_WS_PATTERN, setupApiMocks } from './fixtures/api-mocks'; -import { expectLocatorCenteredBetweenChrome, setOfflineAndWaitForBar } from './fixtures/layout-helpers'; test.describe('Item Detail', () => { test.beforeEach(async ({ page }) => { @@ -267,26 +266,61 @@ test.describe('Item Detail - Desktop', () => { }); }); +const pollItems = { + 126809: { id: 126809, title: 'Poll: Ban Polls?', by: 'pg', score: 46, time: 1204403652, descendants: 0, parts: [126810, 126811], type: 'poll' }, + 126810: { id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, poll: 126809, type: 'pollopt' }, + 126811: { id: 126811, text: 'No, leave them', by: 'pg', score: 10, time: 1204403652, poll: 126809, type: 'pollopt' }, +}; + +test.describe('Item Detail - Poll', () => { + test.beforeEach(async ({ page }) => { + await setupApiMocks(page); + // Registered last, so it wins over setupApiMocks' handler. + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ itemOverrides: pollItems })); + }); + + test("lists a poll's options with their points and shares", async ({ page }) => { + await page.goto('/#/item/126809'); + + await expect(page.getByRole('heading', { level: 1, name: 'Poll: Ban Polls?' })).toBeVisible({ timeout: 10_000 }); + const options = page.getByRole('region', { name: 'Poll options' }).getByRole('listitem'); + await expect(options).toHaveText([/Yes, ban them\s*30 points · 75%/, /No, leave them\s*10 points · 25%/]); + }); + + test('shows its options when its comments fail to load', async ({ page }) => { + await page.route('**/search*', async (route) => { + const tags = new URL(route.request().url()).searchParams.get('tags') ?? ''; + if (tags.includes('story_126809')) { + await route.fulfill({ status: 503, json: { message: 'Service temporarily unavailable' } }); + return; + } + await route.fallback(); + }); + + await page.goto('/#/item/126809'); + + await expect(page.getByRole('region', { name: 'Poll options' }).getByRole('listitem')).toHaveCount(2, { timeout: 10_000 }); + }); +}); + test.describe('Item Detail - Poll option on a phone', () => { test.use({ viewport: { width: 375, height: 667 }, hasTouch: true }); test.beforeEach(async ({ page }) => { await setupApiMocks(page); // Registered last, so it wins over setupApiMocks' handler. - await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ - itemOverrides: { - 126810: { id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, poll: 126809, type: 'pollopt' }, - }, - })); + await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ itemOverrides: pollItems })); }); - test('centers the notice between the header and the offline bar', async ({ page, context }) => { + // The swipe viewer only holds stories, so a poll option opens as a page. + test('opens as a page that links to its poll', async ({ page }) => { await page.goto('/#/item/126810'); - const heading = page.getByRole('heading', { name: "Poll options aren't supported" }); - await expect(heading).toBeVisible({ timeout: 10_000 }); - await setOfflineAndWaitForBar(page, context); + await expect(page.getByText('Yes, ban them', { exact: true })).toBeVisible({ timeout: 10_000 }); + await expect(page.getByTestId('swipe-container')).toHaveCount(0); - await expectLocatorCenteredBetweenChrome(heading.locator('xpath=..')); + await page.getByRole('link', { name: 'Poll: Ban Polls?' }).click(); + await expect(page).toHaveURL(/\/item\/126809$/); + await expect(page.getByRole('region', { name: 'Poll options' }).getByRole('listitem')).toHaveCount(2); }); }); diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index b9a4c88..23129d1 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -1090,7 +1090,7 @@ test.describe('Mobile Swipe Viewer - Back past the cached page', () => { async function goBackToStory21(page: Page) { await page.route(`${ALGOLIA_API}/search*`, async (route) => { const tags = new URL(route.request().url()).searchParams.get('tags'); - if (tags === 'story') { + if (tags === '(story,poll)') { await route.abort(); } else { await route.fallback(); diff --git a/src/App.tsx b/src/App.tsx index 9af2e81..e963c31 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -129,9 +129,10 @@ export function MobileStoryRoute({ feed }: { feed?: FeedType }) { // Branch 5: Direct URL (no state) → resolve type first. The story viewer // must be the element Branch 4 renders for `{ from: 'top' }`: the first // swipe writes that state, and a different element there would remount - // the viewer and drop the story this link opened. A job has no comments - // to swipe through and no feed lists it, so it gets the item page. - if (resolvedType === 'job') return ; + // the viewer and drop the story this link opened. A job or poll option has + // no comments to swipe through and no feed lists it, so it gets the item + // page. + if (resolvedType === 'page') return ; if (resolvedType === 'story') return renderSwipeViewer({ from: 'top' }, id, feedEntries); return ; } @@ -180,10 +181,10 @@ function ItemNotFound() { } // Resolves item type for a direct URL hit on mobile (no `location.state`): -// a comment re-routes to Branch 1, a job reports `'job'`, and anything else -// reports `'story'` so the wrapper mounts the story viewer. -function useResolveDirectLink(id: string | undefined, enabled: boolean): 'story' | 'job' | null { - const [resolved, setResolved] = useState<{ id: string; type: 'story' | 'job' } | null>(null); +// a comment re-routes to Branch 1, a job or poll option reports `'page'`, and +// anything else reports `'story'` so the wrapper mounts the story viewer. +function useResolveDirectLink(id: string | undefined, enabled: boolean): 'story' | 'page' | null { + const [resolved, setResolved] = useState<{ id: string; type: 'story' | 'page' } | null>(null); const navigate = useNavigate(); useEffect(() => { @@ -197,7 +198,7 @@ function useResolveDirectLink(id: string | undefined, enabled: boolean): 'story' // Navigate with state so MobileStoryRoute Branch 1 picks it up void navigate(`/item/${id}`, { replace: true, state: { isComment: true } }); } else { - setResolved({ id, type: item.type === 'job' ? 'job' : 'story' }); + setResolved({ id, type: item.type === 'job' || item.type === 'pollopt' ? 'page' : 'story' }); } }) .catch(() => { diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index b24e20e..d5ef3a7 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -11,10 +11,11 @@ import { fetchTopStories, fetchBestStories, fetchNewStories, + fetchFrontPageForDay, fetchFirebaseItem, fetchItemOnly, fetchAlgoliaItem, - fetchCommentsForItem, + fetchItemWithComments, fetchCommentReplies, normalizeAlgoliaItemChildren, NotFoundError, @@ -326,6 +327,21 @@ describe('hn API utilities', () => { describe('normalizeAlgoliaHit', () => { const nowSec = Math.floor(Date.now() / 1000); + it('types a poll, which Algolia tags `poll` rather than `story`', () => { + const hit = { + objectID: '5640988', + title: 'Poll: Do you have a 3d printer?', + url: null, + points: 186, + author: 'pg', + created_at_i: 1367444459, + num_comments: 275, + _tags: ['poll', 'author_pg'], + }; + + expect(normalizeAlgoliaHit(hit).type).toBe('poll'); + }); + it('maps story_text to text field', () => { const hit = { objectID: '88888', @@ -915,7 +931,7 @@ describe('hn API utilities', () => { it('normalizes Firebase item format', async () => { const result = await fetchItemOnly(12345); expect(result.type).not.toBe('comment'); - if (result.type === 'comment') throw new Error('unexpected'); + if (result.type === 'comment' || result.type === 'pollopt') throw new Error('unexpected'); expect(result.points).toBe(284); expect(result.author).toBe('leerob'); @@ -937,15 +953,120 @@ describe('hn API utilities', () => { it('defaults commentCount to 0 when descendants missing', async () => { const result = await fetchItemOnly(12345); expect(result.type).not.toBe('comment'); - if (result.type === 'comment') throw new Error('unexpected'); + if (result.type === 'comment' || result.type === 'pollopt') throw new Error('unexpected'); expect(result.type !== 'job' ? result.commentCount : 0).toBe(137); }); - it('keeps a poll option typed as one', async () => { - vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, type: 'pollopt' }); + it('reads a poll option with its poll\'s title', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => ( + Number(id) === 126810 + ? { id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, poll: 126809, type: 'pollopt' } + : { id: 126809, title: 'Poll: Ban Polls?', by: 'pg', time: 1204403652, parts: [126810], type: 'poll' } + )); + + expect(await fetchItemOnly(126810)).toEqual({ + id: 126810, + type: 'pollopt', + text: 'Yes, ban them', + points: 30, + author: 'pg', + createdAt: 1204403652 * 1000, + poll: 126809, + pollTitle: 'Poll: Ban Polls?', + }); + }); + + it('still reads a poll option when its poll can\'t be read', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 126809) throw new Error('Offline'); + return { id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, poll: 126809, type: 'pollopt' }; + }); + + const option = await fetchItemOnly(126810); + + expect(option).toMatchObject({ type: 'pollopt', poll: 126809 }); + expect(option).not.toHaveProperty('pollTitle'); + }); + }); + + describe('fetchFrontPageForDay', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("includes a day's polls, which Algolia doesn't tag as stories", async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ + hits: [ + { objectID: '1', title: 'A story', url: 'https://example.com', points: 10, author: 'a', created_at_i: 1700000000, num_comments: 1, _tags: ['story'] }, + { objectID: '2', title: 'Poll: Tabs or spaces?', url: null, points: 50, author: 'b', created_at_i: 1700000000, num_comments: 9, _tags: ['poll'] }, + ], + nbHits: 2, + })); + + const stories = await fetchFrontPageForDay(1); + + expect(new URL(fetchSpy.mock.calls[0]?.[0] as string).searchParams.get('tags')).toBe('(story,poll)'); + expect(stories.map(s => [s.id, s.type])).toEqual([[2, 'poll'], [1, 'story']]); + }); + }); + + describe('poll options', () => { + const poll: FirebaseItem = { + id: 126809, title: 'Poll: Ban Polls?', by: 'pg', score: 46, time: 1204403652, descendants: 1, + parts: [126810, 126811, 126812, 126813], kids: [126900], type: 'poll', + }; + const options: FirebaseItem[] = [ + { id: 126810, text: 'Yes, ban them; I'm tired', by: 'pg', score: 12, time: 1204403652, poll: 126809, type: 'pollopt' }, + { id: 126811, text: 'No, leave them', by: 'pg', score: 30, time: 1204403652, poll: 126809, type: 'pollopt' }, + { id: 126812, by: 'pg', time: 1204403652, poll: 126809, type: 'pollopt', deleted: true }, + { id: 126813, text: 'Only on Fridays', by: 'pg', score: 12, time: 1204403652, poll: 126809, type: 'pollopt' }, + ]; + const comment = { objectID: '126900', author: 'dang', comment_text: 'Polls are fine', created_at_i: 1204403700, parent_id: 126809 }; + + function mockPoll(readOption: (id: number) => Promise = async id => options.find(o => o.id === id) ?? null) { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => (Number(id) === poll.id ? poll : readOption(Number(id)))); + vi.spyOn(globalThis, 'fetch').mockImplementation(async () => Response.json({ hits: [comment], nbHits: 1, nbPages: 1 })); + } + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('come with a poll\'s comments, most points first as on HN, ties in poll order, without deleted ones', async () => { + mockPoll(); + + const { item } = await fetchItemWithComments(poll.id); + + expect(item).toMatchObject({ type: 'poll', title: 'Poll: Ban Polls?', points: 46 }); + expect(item.type === 'poll' && item.pollOptions).toEqual([ + { id: 126811, text: 'No, leave them', points: 30 }, + { id: 126810, text: 'Yes, ban them; I'm tired', points: 12 }, + { id: 126813, text: 'Only on Fridays', points: 12 }, + ]); + }); + + it('are all left out when one of them fails, rather than misstate the shares, and the comments still come', async () => { + mockPoll(async id => { + if (id === 126811) throw new Error('Offline'); + return options.find(o => o.id === id) ?? null; + }); + + const { item, comments } = await fetchItemWithComments(poll.id); + + expect(item).toMatchObject({ type: 'poll', title: 'Poll: Ban Polls?' }); + expect(item).not.toHaveProperty('pollOptions'); + expect(comments.map(c => [c.id, c.text])).toEqual([[126900, 'Polls are fine']]); + }); + + it('aren\'t read for the item alone', async () => { + mockPoll(); + + const item = await fetchItemOnly(poll.id); - expect((await fetchItemOnly(126810)).type).toBe('pollopt'); + expect(item.type).toBe('poll'); + expect(item).not.toHaveProperty('pollOptions'); + expect(hnSdk.readItem).toHaveBeenCalledTimes(1); }); }); @@ -1051,7 +1172,7 @@ describe('hn API utilities', () => { }); }); - describe('fetchCommentsForItem', () => { + describe('fetchItemWithComments', () => { describe('replies to a comment search leaves out', () => { const itemId = 9000; @@ -1092,7 +1213,7 @@ describe('hn API utilities', () => { { id: 102, type: 'comment', by: 'eve', text: '[flagged]', dead: true, time: 1700000150, parent: itemId, kids: [202, 201] }, ]); - const comments = await fetchCommentsForItem(itemId); + const { comments } = await fetchItemWithComments(itemId); expect(comments.map(c => c.id)).toEqual([101, 102, 103]); expect(comments[1]).toMatchObject({ author: 'eve', text: '[flagged]', createdAt: 1700000150 * 1000 }); @@ -1106,7 +1227,7 @@ describe('hn API utilities', () => { { id: 102, type: 'comment', by: 'eve', text: 'Praise the iLord.', dead: true, time: 1700000150, parent: itemId, kids: [201, 202] }, ]); - const comments = await fetchCommentsForItem(itemId); + const { comments } = await fetchItemWithComments(itemId); expect(comments[1]).toMatchObject({ id: 102, author: 'eve', text: '[flagged]' }); }); @@ -1116,7 +1237,7 @@ describe('hn API utilities', () => { { id: 102, type: 'comment', deleted: true, time: 1700000150, parent: itemId, kids: [201, 202] }, ]); - const comments = await fetchCommentsForItem(itemId); + const { comments } = await fetchItemWithComments(itemId); expect(comments.map(c => c.id)).toEqual([101, 102, 103]); expect(comments[1]).toMatchObject({ deleted: true, author: '', text: '' }); @@ -1136,7 +1257,7 @@ describe('hn API utilities', () => { ], ); - const comments = await fetchCommentsForItem(itemId); + const { comments } = await fetchItemWithComments(itemId); expect(comments.map(c => c.id)).toEqual([101, 102]); expect(comments[1].children.map(c => c.id)).toEqual([201]); @@ -1146,7 +1267,7 @@ describe('hn API utilities', () => { it('drops the replies when Firebase does not have their parent either', async () => { mockThread([]); - const comments = await fetchCommentsForItem(itemId); + const { comments } = await fetchItemWithComments(itemId); expect(comments.map(c => c.id)).toEqual([101, 103]); expect(comments.flatMap(c => c.children)).toEqual([]); @@ -1204,7 +1325,7 @@ describe('hn API utilities', () => { // nbPages is capped at 1,000 hits / 200 per page, so it no longer covers nbHits. mockAlgolia({ nbHits: 1500, nbPages: 5 }); - const comments = await fetchCommentsForItem(itemId); + const { comments } = await fetchItemWithComments(itemId); expect(comments.map(c => c.id)).toEqual([101, 102, 104]); expect(comments[0].text).toBe('From search'); @@ -1214,7 +1335,7 @@ describe('hn API utilities', () => { it('keeps the search results when the item tree fails', async () => { mockAlgolia({ nbHits: 1500, nbPages: 5 }, { treeStatus: 500 }); - const comments = await fetchCommentsForItem(itemId); + const { comments } = await fetchItemWithComments(itemId); expect(comments.map(c => c.id)).toEqual([101, 102]); }); @@ -1222,7 +1343,7 @@ describe('hn API utilities', () => { it('skips the item tree when search has every comment', async () => { const mockFetch = mockAlgolia({ nbHits: 2, nbPages: 1 }); - await fetchCommentsForItem(itemId); + await fetchItemWithComments(itemId); expect(mockFetch).toHaveBeenCalledTimes(1); expect(urlOf(mockFetch.mock.calls[0][0])).toContain('/search?'); diff --git a/src/api/hn.ts b/src/api/hn.ts index 14f9e64..dc0ea88 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -1,6 +1,6 @@ import { ALGOLIA_API } from '../config/api'; import { hnSdk } from './hnSdk'; -import type { Item, StoryItem, Comment, AlgoliaHit, AlgoliaComment, AlgoliaSearchResponse, FirebaseItem, PrefetchResult, AlgoliaItemResponse, AlgoliaItemChild } from '../types'; +import type { Item, StoryItem, Comment, AlgoliaHit, AlgoliaComment, AlgoliaSearchResponse, FirebaseItem, PrefetchResult, AlgoliaItemResponse, AlgoliaItemChild, PollOption, PollOptionItem } from '../types'; export class NotFoundError extends Error { constructor(message: string) { @@ -9,6 +9,17 @@ export class NotFoundError extends Error { } } +/** The comments couldn't be read, but the item they hang off was, with a poll's options. */ +export class CommentsError extends Error { + readonly item: Item; + + constructor(message: string, item: Item) { + super(message); + this.name = 'CommentsError'; + this.item = item; + } +} + 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 }; @@ -41,7 +52,7 @@ function getDayRange(daysAgo = 0) { }; } -// Feed endpoints only return stories. +// Feed endpoints only return stories (polls among them). export function normalizeAlgoliaHit(hit: AlgoliaHit): StoryItem { return { id: parseInt(hit.objectID, 10), @@ -52,7 +63,10 @@ export function normalizeAlgoliaHit(hit: AlgoliaHit): StoryItem { author: hit.author, createdAt: hit.created_at_i * 1000, commentCount: hit.num_comments || 0, - type: hit._tags?.includes('ask_hn') ? 'ask' : hit._tags?.includes('show_hn') ? 'show' : 'story', + type: hit._tags?.includes('poll') ? 'poll' + : hit._tags?.includes('ask_hn') ? 'ask' + : hit._tags?.includes('show_hn') ? 'show' + : 'story', }; } @@ -83,12 +97,22 @@ function normalizeFirebaseItem(fbItem: FirebaseItem): Item { }; } + if (fbItem.type === 'pollopt') { + return { + ...base, + type: 'pollopt' as const, + text: fbItem.text ?? '', + points: fbItem.score ?? 0, + poll: fbItem.poll ?? 0, + }; + } + // 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 reads as a story, without its options. + // A poll's options are separate items, read with its comments. return { ...base, - type: fbItem.type === 'pollopt' ? 'pollopt' : 'story', + type: fbItem.type === 'poll' ? 'poll' : 'story', title: fbItem.title ?? '', url: fbItem.url, text: fbItem.text, @@ -130,8 +154,9 @@ export async function fetchTopStories(limit = 20): Promise { export async function fetchFrontPageForDay(daysAgo = 1): Promise { const { start, end } = getDayRange(daysAgo); - // story tag excludes jobs/comments/polls; relevance sort factors in points. - const url = `${ALGOLIA_API}/search?tags=story&numericFilters=created_at_i>=${start},created_at_i<${end}&hitsPerPage=30`; + // 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 response = await fetch(url); if (!response.ok) { @@ -232,15 +257,15 @@ export async function fetchNewStories(offset = 0, limit = 30) { }; } -/** A poll option has no title or comments, so its page shows a notice instead. */ -export function isPollOption(item: Item): item is StoryItem & { type: 'pollopt' } { +/** A poll option has no title or comments, so it gets a page of its own. */ +export function isPollOption(item: Item): item is PollOptionItem { return item.type === 'pollopt'; } function normalizeFirebaseToStoryItem(fb: FirebaseItem): StoryItem { return { id: fb.id, - type: 'story', + type: fb.type === 'poll' ? 'poll' : 'story', title: fb.title ?? '', url: fb.url, text: fb.text, @@ -283,7 +308,7 @@ async function fetchRankedStories( !fb.dead && !excludeTitles?.some(t => (fb.title ?? '').toLowerCase().includes(t)) ) - .map(fb => ({ ...normalizeFirebaseToStoryItem(fb), type: type })); + .map(fb => ({ ...normalizeFirebaseToStoryItem(fb), type: fb.type === 'poll' ? 'poll' as const : type })); return { stories, @@ -622,11 +647,68 @@ async function buildOrderedCommentTree( return buildCommentTree(comments, itemId, kidsOrder); } -/** Fetch item metadata only (no comments). */ +/** Fetch item metadata only (no comments). A poll's options come with its comments. */ export async function fetchItemOnly(id: number | string, signal?: AbortSignal): Promise { const itemId = Number(id); - const item = await fetchFirebaseItem(itemId, signal); - return normalizeFirebaseItem(item); + const item = normalizeFirebaseItem(await fetchFirebaseItem(itemId, signal)); + if (!isPollOption(item) || !item.poll) return item; + + // Its page links to the poll by title. Without one the link still works. + const poll = await hnSdk.readItem(item.poll).catch(() => null); + return poll?.title ? { ...item, pollTitle: poll.title } : item; +} + +// Every option is read: a poll missing one would misstate the others' shares, +// so one failed read fails them all. Deleted and flagged options are left out. +// Not batched: reads share one WebSocket, so batches would only add round +// trips (seconds, for HN's biggest poll). +// They come in HN's order, most points first. The API calls `parts` display +// 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'); + } + 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 })) + .sort((a, b) => b.points - a.points); +} + +function threadItem(raw: FirebaseItem, pollOptions: PollOption[] | undefined): Item { + const item = normalizeFirebaseItem(raw); + return item.type === 'poll' && pollOptions ? { ...item, pollOptions } : item; +} + +// The item, normalized, with its comments in HN's order. A poll's options are +// its content, so they're read too, while the comments are put in order. +// Options that can't be read leave the poll without them rather than cost it +// its comments; a copy cached that way reads them again. Comments that can't +// be read don't cost a poll its options: the CommentsError carries them. +async function fetchThread(itemId: number, signal?: AbortSignal, maxOrderingDepth = Infinity): Promise { + const itemRead = fetchFirebaseItem(itemId, signal); + const pollOptionsRead = itemRead + .then(raw => (raw.type === 'poll' ? fetchPollOptions(raw.parts ?? [], signal) : undefined)) + .catch(() => undefined); + const commentsRead = fetchAllCommentsAlgolia(itemId, signal).catch(async (err: unknown) => { + if (signal?.aborted) throw err; + 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); + }); + const [raw, comments] = await Promise.all([itemRead, commentsRead]); + + if (signal?.aborted) { + throw new DOMException('Aborted', 'AbortError'); + } + + const [commentTree, pollOptions] = await Promise.all([ + buildOrderedCommentTree(comments, itemId, raw.kids, signal, maxOrderingDepth), + pollOptionsRead, + ]); + return { item: threadItem(raw, pollOptions), comments: commentTree }; } // Batched to avoid overwhelming the API. Items that fail or don't exist are @@ -669,56 +751,23 @@ async function fetchKidsOrdering(commentIds: number[], signal?: AbortSignal): Pr */ export async function prefetchItemComments(id: number | string, signal?: AbortSignal, maxOrderingDepth = Infinity): Promise { try { - const itemId = Number(id); - if (signal?.aborted) return null; - - const [item, comments] = await Promise.all([ - fetchFirebaseItem(itemId, signal), - fetchAllCommentsAlgolia(itemId, signal), - ]); - - if (signal?.aborted) return null; - if (!item) return null; - - const commentTree = await buildOrderedCommentTree(comments, itemId, item.kids, signal, maxOrderingDepth); - - if (signal?.aborted) return null; - - return { - item: normalizeFirebaseItem(item), - comments: commentTree, - }; + + const result = await fetchThread(Number(id), signal, maxOrderingDepth); + + return signal?.aborted ? null : result; } catch { return null; } } -export async function fetchCommentsForItem(id: number | string, signal: AbortSignal | null = null): Promise { - return (await fetchItemWithComments(id, signal)).comments; -} - /** 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 { - const itemId = Number(id); - if (signal?.aborted) { throw new DOMException('Aborted', 'AbortError'); } - const [item, comments] = await Promise.all([ - fetchFirebaseItem(itemId, signal ?? undefined), - fetchAllCommentsAlgolia(itemId, signal ?? undefined), - ]); - - if (signal?.aborted) { - throw new DOMException('Aborted', 'AbortError'); - } - - return { - item: normalizeFirebaseItem(item), - comments: await buildOrderedCommentTree(comments, itemId, item.kids, signal ?? undefined), - }; + return fetchThread(Number(id), signal ?? undefined); } // Algolia /items/{id} returns the full nested children tree in one request. diff --git a/src/components/FullScreenItem.test.tsx b/src/components/FullScreenItem.test.tsx index cc8f9be..778ff12 100644 --- a/src/components/FullScreenItem.test.tsx +++ b/src/components/FullScreenItem.test.tsx @@ -83,11 +83,11 @@ describe('FullScreenItem', () => { }); }); - it('says a poll option is not supported instead of showing it', async () => { - vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, type: 'pollopt' }); + it('shows "Item not found" for a poll option, which has its own page', async () => { + vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, poll: 126809, type: 'pollopt' }); render(); - expect(await screen.findByRole('heading', { name: "Poll options aren't supported" })).toBeInTheDocument(); + expect(await screen.findByText('Item not found')).toBeInTheDocument(); expect(screen.queryByRole('heading', { level: 1 })).not.toBeInTheDocument(); }); }); diff --git a/src/components/FullScreenItem.tsx b/src/components/FullScreenItem.tsx index 82d45f1..7e508e5 100644 --- a/src/components/FullScreenItem.tsx +++ b/src/components/FullScreenItem.tsx @@ -7,7 +7,6 @@ import { CommentsSection } from './CommentsSection'; import { FullScreenChrome } from './FullScreenChrome'; import { ItemArticle } from './ItemArticle'; import { PageStage } from './PageStage'; -import { PollOptionNotSupported } from './PollOptionNotSupported'; import { StateView } from './StateView'; import type { StoryItem } from '../types'; @@ -88,7 +87,9 @@ export function FullScreenItem({ itemId, initialItem, isPriority = true, deferCo return ; } - if (!itemLoading && (!item || item.type === 'comment')) { + // The swipe viewer only gets stories and jobs: a poll option, like a + // comment, has no story to show here. + if (!itemLoading && (!item || item.type === 'comment' || isPollOption(item))) { return (
@@ -96,14 +97,6 @@ export function FullScreenItem({ itemId, initialItem, isPriority = true, deferCo ); } - if (!itemLoading && item && isPollOption(item)) { - return ( -
- -
- ); - } - return ( {/* `triggerWhen={isPriority}` holds the entrance animation @@ -115,7 +108,7 @@ export function FullScreenItem({ itemId, initialItem, isPriority = true, deferCo skeleton={} triggerWhen={isPriority} > - {item && item.type !== 'comment' && ( + {item && item.type !== 'comment' && !isPollOption(item) && ( <>
diff --git a/src/components/ItemArticle.test.tsx b/src/components/ItemArticle.test.tsx index b0b7370..b40eb92 100644 --- a/src/components/ItemArticle.test.tsx +++ b/src/components/ItemArticle.test.tsx @@ -1,5 +1,5 @@ -import { describe, it, expect, beforeEach } from 'vitest'; -import { screen, fireEvent } from '@testing-library/react'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { screen, fireEvent, within } from '@testing-library/react'; import { render } from '../test/test-utils'; import { ItemArticle } from './ItemArticle'; import { clearViewed, clearViewedTimes, clearSessionViewed, isViewed, VIEWED_TITLE_TIMES_KEY, VIEWED_SESSION_KEY } from '../utils/viewedItems'; @@ -144,4 +144,74 @@ describe('ItemArticle', () => { expect(screen.queryByText(/99\s+comments/)).not.toBeInTheDocument(); }); }); + + describe('a poll', () => { + const optionRows = () => within(screen.getByRole('region', { name: 'Poll options' })).getAllByRole('listitem'); + + it('lists its options in order with their points and shares, the leader marked', () => { + render(friends', points: 299 }, + { id: 3, text: 'Nano', points: 0 }, + ] })} />); + + expect(optionRows().map(row => row.textContent)).toEqual([ + 'Vim1 point · <1%', + 'Emacs & friends299 points · 100%', + 'Nano0 points · 0%', + ]); + expect(optionRows().map(row => row.hasAttribute('data-leading'))).toEqual([false, true, false]); + }); + + it('marks no leader before anyone has voted', () => { + render(); + + expect(optionRows().map(row => row.textContent)).toEqual(['Yes0 points · 0%', 'No0 points · 0%']); + expect(optionRows().some(row => row.hasAttribute('data-leading'))).toBe(false); + }); + + it('shows the first 10 of a long poll until asked for all', () => { + const pollOptions = Array.from({ length: 13 }, (_, i) => ({ id: i + 1, text: `Option ${i + 1}`, points: 1 })); + render(); + + expect(optionRows()).toHaveLength(10); + const toggle = screen.getByRole('button', { name: 'Show all 13 options' }); + expect(toggle).toHaveAttribute('aria-expanded', 'false'); + + fireEvent.click(toggle); + expect(optionRows()).toHaveLength(13); + expect(screen.getByRole('button', { name: 'Show fewer options' })).toHaveAttribute('aria-expanded', 'true'); + }); + + it('keeps the toggle where it was when collapsing from far down the options', () => { + const pollOptions = Array.from({ length: 13 }, (_, i) => ({ id: i + 1, text: `Option ${i + 1}`, points: 1 })); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Show all 13 options' })); + const toggle = screen.getByRole('button', { name: 'Show fewer options' }); + vi.spyOn(toggle, 'getBoundingClientRect') + .mockReturnValueOnce({ top: 600 } as DOMRect) + .mockReturnValueOnce({ top: -2000 } as DOMRect); + const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation(vi.fn()); + + try { + fireEvent.click(toggle); + + expect(optionRows()).toHaveLength(10); + expect(scrollBy).toHaveBeenCalledExactlyOnceWith(0, -2600); + } finally { + scrollBy.mockRestore(); + } + }); + + it('shows every option of a poll of up to 12', () => { + const pollOptions = Array.from({ length: 12 }, (_, i) => ({ id: i + 1, text: `Option ${i + 1}`, points: 1 })); + render(); + + expect(optionRows()).toHaveLength(12); + expect(screen.queryByRole('button', { name: /options/ })).not.toBeInTheDocument(); + }); + }); }); diff --git a/src/components/ItemArticle.tsx b/src/components/ItemArticle.tsx index 05f5d80..7822853 100644 --- a/src/components/ItemArticle.tsx +++ b/src/components/ItemArticle.tsx @@ -7,20 +7,22 @@ import { useIsViewed, markViewedWithTime } from '../utils/viewedItems'; import { itemPermalink } from '../utils/share'; import { metaItemClass, metaPillClass } from '../lib/classes'; import { AuthorByline } from './AuthorByline'; +import { PollOptions } from './PollOptions'; import { RelativeTime } from './RelativeTime'; import { ShareButton } from './ShareButton'; -import type { Item } from '../types'; +import type { JobItem, StoryItem } from '../types'; interface ItemArticleProps { - item: Item & { title: string; points: number; url?: string; commentCount?: number }; + item: StoryItem | JobItem; className?: string; } -/** Shared item header (title, meta, text). */ +/** Shared item header (title, meta, text, a poll's options). */ export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-border' }: ItemArticleProps) { const viewed = useIsViewed(item.id); const hostname = getHostname(item.url); const commentCount = item.type !== 'job' ? (item.commentCount ?? 0) : 0; + const pollOptions = item.type === 'poll' ? item.pollOptions : undefined; // Gate the outbound href to http(s) so javascript:/data: URLs can't reach the // DOM; anything else degrades to plain text. Keep it ONE `startsWith` — a `||` @@ -89,6 +91,8 @@ export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-borde dangerouslySetInnerHTML={{ __html: sanitizedText }} /> )} + + {pollOptions && pollOptions.length > 0 && } ); } diff --git a/src/components/PollOptionArticle.tsx b/src/components/PollOptionArticle.tsx new file mode 100644 index 0000000..3804cc1 --- /dev/null +++ b/src/components/PollOptionArticle.tsx @@ -0,0 +1,62 @@ +import { useMemo } from 'react'; +import { Link } from 'react-router'; +import { ChevronUp, Clock, Vote } from 'lucide-react'; +import { htmlToText, sanitizeHtml } from '../utils/sanitize'; +import { itemPermalink } from '../utils/share'; +import { metaItemClass, metaPillClass } from '../lib/classes'; +import { AuthorByline } from './AuthorByline'; +import { RelativeTime } from './RelativeTime'; +import { ShareButton } from './ShareButton'; +import type { PollOptionItem } from '../types'; + +interface PollOptionArticleProps { + option: PollOptionItem; +} + +/** + * A poll option on its own page: its points, a link to its poll, and its text, + * which HN shows like a comment's. + */ +export function PollOptionArticle({ option }: PollOptionArticleProps) { + const sanitizedText = useMemo(() => sanitizeHtml(option.text), [option.text]); + const plainText = useMemo(() => htmlToText(option.text), [option.text]); + + return ( +
+
+ + + {option.points} {option.points === 1 ? 'point' : 'points'} + + + + + + + + + + {option.poll > 0 && ( + // min-w-0 max-w-full enables truncation; shrink-0 keeps icon visible. + + + {option.pollTitle ?? 'poll'} + + )} + + +
+ + {sanitizedText && ( +
+ )} +
+ ); +} diff --git a/src/components/PollOptionNotSupported.tsx b/src/components/PollOptionNotSupported.tsx deleted file mode 100644 index 73cef0a..0000000 --- a/src/components/PollOptionNotSupported.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { StateView } from './StateView'; - -interface PollOptionNotSupportedProps { - action?: { label: string; to?: string; onClick?: () => void }; - className?: string; -} - -/** The notice's heading, and the tab title while it shows. */ -export const POLL_OPTION_TITLE = "Poll options aren't supported"; - -/** Shown in place of a poll option (see `isPollOption`). */ -export function PollOptionNotSupported({ action, className }: PollOptionNotSupportedProps) { - return ( - - ); -} diff --git a/src/components/PollOptions.tsx b/src/components/PollOptions.tsx new file mode 100644 index 0000000..3d2579f --- /dev/null +++ b/src/components/PollOptions.tsx @@ -0,0 +1,92 @@ +import { useMemo, useRef, useState } from 'react'; +import { flushSync } from 'react-dom'; +import { ChevronDown, ChevronUp } from 'lucide-react'; +import { sanitizeHtml } from '../utils/sanitize'; +import type { PollOption } from '../types'; + +// HN's biggest poll has 253 options, so a long one shows its top few until +// asked: the comments are under it. +const COLLAPSE_ABOVE = 12; +const COLLAPSED_COUNT = 10; + +interface PollOptionsProps { + options: PollOption[]; +} + +/** + * A poll's options in the order given (HN's: most points first), each with its + * points and share of all of them. + */ +export function PollOptions({ options }: PollOptionsProps) { + const [expanded, setExpanded] = useState(false); + const toggleRef = useRef(null); + const total = options.reduce((sum, option) => sum + option.points, 0); + const top = Math.max(0, ...options.map(option => option.points)); + const collapsible = options.length > COLLAPSE_ABOVE; + const shown = collapsible && !expanded ? options.slice(0, COLLAPSED_COUNT) : options; + + const toggle = () => { + const topBefore = toggleRef.current?.getBoundingClientRect().top ?? 0; + flushSync(() => setExpanded(!expanded)); + // Collapsing pulls the toggle up past every option it hides, which would + // leave the reader far down the comments: keep it where it was. + const moved = (toggleRef.current?.getBoundingClientRect().top ?? 0) - topBefore; + if (expanded && moved !== 0) window.scrollBy(0, moved); + }; + + return ( +
+
    + {shown.map(option => ( + 0 ? option.points / total : 0} + leading={top > 0 && option.points === top} + /> + ))} +
+ {collapsible && ( + + )} +
+ ); +} + +interface PollOptionRowProps { + option: PollOption; + share: number; + leading: boolean; +} + +function PollOptionRow({ option, share, leading }: PollOptionRowProps) { + const sanitizedText = useMemo(() => sanitizeHtml(option.text), [option.text]); + const percent = Math.round(share * 100); + + return ( +
  • + {/* The fill repeats the share the row spells out. */} +
    +
    +
    +
    + {option.points} {option.points === 1 ? 'point' : 'points'} + · + {percent === 0 && option.points > 0 ? '<1' : percent}% +
    +
    +
  • + ); +} diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index 486d5e0..395b3f1 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -89,10 +89,10 @@ describe('SwipeStoryViewerCore', () => { expect(title.closest('div')).toHaveClass('swipe-state-center'); }); - it("titles the tab after the notice on a poll option's panel", async () => { - vi.mocked(fetchItemOnly).mockResolvedValueOnce( - createStoryItem({ id: 126810, type: 'pollopt', title: '', url: undefined, text: 'Yes, ban them' }), - ); + it('refuses to inject a poll option as a story', async () => { + vi.mocked(fetchItemOnly).mockResolvedValueOnce({ + id: 126810, type: 'pollopt', text: 'Yes, ban them', points: 30, author: 'pg', createdAt: 1204403652000, poll: 126809, + }); render( { />, ); - await waitFor(() => expect(activePanel()?.getAttribute('data-item-id')).toBe('126810')); - expect(document.title).toBe("Poll options aren't supported | HackerTok"); + expect(await screen.findByRole('heading', { name: 'This item is not a story' })).toBeInTheDocument(); + expect(screen.queryByTestId('fsi')).not.toBeInTheDocument(); + expect(document.title).toBe('Item not available | HackerTok'); }); }); diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 7b9e81c..5bc3b87 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -14,7 +14,6 @@ import { isCacheFresh } from '../utils/feedCache'; import { useViewDwell } from '../hooks/useViewDwell'; import { FEED_TYPE_TITLES } from '../config/feedTypes'; import { FullScreenItem, FullScreenItemSkeletonPanel } from './FullScreenItem'; -import { POLL_OPTION_TITLE } from './PollOptionNotSupported'; import { StateView } from './StateView'; import type { StoryItem, FeedType, LocationState } from '../types'; @@ -215,7 +214,7 @@ export function SwipeStoryViewerCore({ // Get current story for document title (updates as user swipes) const currentStory = mergedStories[currentIndex]; - const isNonStoryError = injectedError === 'job' || injectedError === 'comment'; + const isNonStoryError = injectedError === 'job' || injectedError === 'comment' || injectedError === 'pollopt'; const isInjectedNotFound = injectedError && (isNonStoryError || isInjectedItemNotFound); const isAtEndError = error && !loading && mergedStories.length > 0 && currentIndex >= mergedStories.length - 1; @@ -223,7 +222,6 @@ export function SwipeStoryViewerCore({ ? (isInjectedNotFound ? (isNonStoryError ? 'Item not available' : 'Item not found') : 'Failed to load item') : (error && mergedStories.length === 0) ? 'Failed to load item' : isOnline && isAtEndError && giveUp ? 'Failed to load item' - : currentStory && isPollOption(currentStory) ? POLL_OPTION_TITLE : (currentStory?.title || titleFallback); useDocumentTitle(documentTitle); @@ -274,10 +272,10 @@ export function SwipeStoryViewerCore({ // Race condition guard: user may have swiped to another story while fetching. // Only update state if this fetch result matches the story we're still waiting for. if (fetchedItem.id === fetchedStoryIdRef.current) { - // Only inject stories (not comments or jobs) - if (fetchedItem.type === 'comment' || fetchedItem.type === 'job') { + // Only inject stories (not comments, jobs or poll options) + if (fetchedItem.type === 'comment' || fetchedItem.type === 'job' || isPollOption(fetchedItem)) { setInjectedLoading(false); - setInjectedError(fetchedItem.type === 'job' ? 'job' : 'comment'); + setInjectedError(fetchedItem.type); return; } setInjectedStory(fetchedItem); diff --git a/src/components/index.ts b/src/components/index.ts index 952e160..3edbca1 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -17,6 +17,7 @@ export { ItemArticle } from './ItemArticle'; export { FullScreenComment, FullScreenCommentSkeleton, FullScreenCommentSkeletonPanel } from './FullScreenComment'; export { CommentsSection } from './CommentsSection'; export { StateView } from './StateView'; -export { PollOptionNotSupported, POLL_OPTION_TITLE } from './PollOptionNotSupported'; +export { PollOptionArticle } from './PollOptionArticle'; +export { PollOptions } from './PollOptions'; export { NetworkStatusBar } from './NetworkStatusBar'; export { ShareButton } from './ShareButton'; diff --git a/src/hooks/useItemWithComments.test.tsx b/src/hooks/useItemWithComments.test.tsx index 1c37b80..1ba5570 100644 --- a/src/hooks/useItemWithComments.test.tsx +++ b/src/hooks/useItemWithComments.test.tsx @@ -937,7 +937,7 @@ describe('useItemWithComments', () => { expect(result.current.commentsLoading).toBe(true); - // Both endpoints must fail since fetchCommentsForItem touches Firebase too. + // Both endpoints must fail since fetchItemWithComments touches Firebase too. vi.spyOn(hnSdk, 'readItem').mockRejectedValue(new Error('Offline')); server.use( http.get(`${ALGOLIA_API}/search`, () => { @@ -1065,6 +1065,87 @@ describe('useItemWithComments', () => { }); }); + describe('a poll', () => { + const pollFirebase: FirebaseItem = { + id: 126809, title: 'Poll: Ban Polls?', by: 'pg', score: 46, time: 1204403652, descendants: 0, + parts: [126810, 126811], type: 'poll', + }; + const pollOptions = [ + { id: 126810, text: 'Yes, ban them', points: 30 }, + { id: 126811, text: 'No, leave them', points: 10 }, + ]; + // How a feed (Algolia) delivers it: no options. + const feedPoll = createStoryItem({ id: 126809, title: 'Poll: Ban Polls?', author: 'pg', points: 46, commentCount: 0, type: 'poll' }); + + beforeEach(() => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === pollFirebase.id) return pollFirebase; + const option = pollOptions.find(o => o.id === Number(id)); + return option ? { id: option.id, text: option.text, score: option.points, by: 'pg', time: 1204403652, poll: 126809, type: 'pollopt' } : null; + }); + }); + + it("takes a feed copy's options from the comments fetch, and caches them", async () => { + const { result } = renderHook(() => useItemWithComments(126809, { initialItem: feedPoll })); + + await waitFor(() => expect(result.current.commentsLoading).toBe(false)); + expect(result.current.item).toEqual({ ...feedPoll, pollOptions }); + expect(getCachedItem(126809)?.item).toEqual({ ...feedPoll, pollOptions }); + }); + + it('takes them from a prefetch that lands after a feed copy mounted', async () => { + const { result, rerender } = renderHook( + ({ deferComments }) => useItemWithComments(126809, { initialItem: feedPoll, deferComments, skipOrderingCompletion: true }), + { initialProps: { deferComments: true } }, + ); + + await act(async () => { + setCachedItem(126809, { ...feedPoll, pollOptions }, [], 1); + }); + rerender({ deferComments: false }); + + await waitFor(() => expect(result.current.item).toEqual({ ...feedPoll, pollOptions })); + expect(hnSdk.readItem).not.toHaveBeenCalled(); + }); + + it('reads them again over a fresh cached copy that lacks them, keeping its comments up', async () => { + setCachedItem(126809, feedPoll, [], 3); + + const { result } = renderHook(() => useItemWithComments(126809)); + + expect(result.current.commentsLoading).toBe(false); + await waitFor(() => expect(result.current.item).toEqual({ ...feedPoll, pollOptions })); + expect(getCachedItem(126809)?.item).toEqual({ ...feedPoll, pollOptions }); + }); + + it('shows them when the comments fail to load, without caching the poll', async () => { + server.use(http.get(`${ALGOLIA_API}/search`, () => new HttpResponse(null, { status: 503 }))); + + const { result } = renderHook(() => useItemWithComments(126809, { initialItem: feedPoll })); + + await waitFor(() => expect(result.current.commentsError).toBe('Failed to fetch comments: 503')); + expect(result.current.item).toEqual({ ...feedPoll, pollOptions }); + expect(getCachedItem(126809)).toBeNull(); + }); + + it('gets them back when a failed load is retried', async () => { + const readItem = vi.mocked(hnSdk.readItem); + const read = readItem.getMockImplementation()!; + readItem.mockRejectedValueOnce(new Error('Offline')); + + const { result } = renderHook(() => useItemWithComments(126809)); + await waitFor(() => expect(result.current.error).toBe('Offline')); + + readItem.mockImplementation(read); + await act(async () => { + await result.current.refresh(); + }); + + expect(result.current.item).toMatchObject({ type: 'poll', pollOptions }); + expect(getCachedItem(126809)?.item).toMatchObject({ type: 'poll', pollOptions }); + }); + }); + describe('refresh loading states', () => { it('sets itemLoading and commentsLoading to true during refresh', async () => { const { result } = renderHook(() => diff --git a/src/hooks/useItemWithComments.ts b/src/hooks/useItemWithComments.ts index fd6ee39..be4b5a7 100644 --- a/src/hooks/useItemWithComments.ts +++ b/src/hooks/useItemWithComments.ts @@ -1,9 +1,9 @@ import { useState, useEffect, useRef, useEffectEvent, useCallback } from 'react'; -import { fetchItemOnly, fetchCommentsForItem, fetchItemWithComments, isPollOption, NotFoundError } from '../api/hn'; +import { fetchItemOnly, fetchItemWithComments, isPollOption, CommentsError, NotFoundError } from '../api/hn'; import { getCachedItem, setCachedItem } from '../utils/itemCache'; import { registerPriorityFetch, unregisterPriorityFetch } from '../utils/fetchPriority'; import { useNetworkStatus } from './useNetworkStatus'; -import type { Item, Comment } from '../types'; +import type { Item, Comment, StoryItem } from '../types'; interface UseItemWithCommentsOptions { /** Pre-loaded item data (avoids the redundant item fetch). */ @@ -31,23 +31,30 @@ interface UseItemWithCommentsResult { } // Swipe-position snapshots store stories without `text` (see swipePosition.ts), -// so an initialItem can lack a body that another copy of the item has. -function withText(item: Item | null | undefined, source: Item | null | undefined): Item | null { +// and feeds don't carry a poll's options, so an initialItem can lack fields +// that another copy of the item has. +function withCachedFields(item: Item | null | undefined, source: Item | null | undefined): Item | null { if (!item) return null; - if (item.text !== undefined || source?.id !== item.id || source.text === undefined) return item; - return { ...item, text: source.text }; + if (source?.id !== item.id) return item; + const filled = item.text === undefined && source.text !== undefined ? { ...item, text: source.text } : item; + if (!isStory(filled) || filled.pollOptions || source.type !== 'poll' || !source.pollOptions) return filled; + return { ...filled, type: 'poll', pollOptions: source.pollOptions }; } -// The comments fetch reads the item too, so it has newer points, comment count -// and title than a cached or restored copy. The rest stays: Firebase calls -// Ask/Show posts `story`, and a deleted story comes back without a title. A -// fetched poll option's type wins: copies cached before it had one call it a -// story. +function isStory(item: Item): item is StoryItem { + return item.type !== 'comment' && item.type !== 'job' && !isPollOption(item); +} + +// The comments fetch reads the item too, so it has newer points, comment +// count, title and poll options than a cached or restored copy. The rest +// stays: Firebase calls Ask/Show posts `story`, and a deleted story comes back +// without a title. A fetched poll or poll option's type wins: copies cached +// before HackerTok knew them call them stories. function withFetchedFields(item: Item | null | undefined, fetched: Item): Item | null { if (item && isPollOption(fetched) && fetched.id === item.id) return fetched; - if (!item || item.type === 'comment' || item.type === 'job' || fetched.type !== 'story' || + if (!item || !isStory(item) || (fetched.type !== 'story' && fetched.type !== 'poll') || fetched.id !== item.id || !fetched.title) { - return withText(item, fetched); + return withCachedFields(item, fetched); } return { ...item, @@ -56,9 +63,16 @@ function withFetchedFields(item: Item | null | undefined, fetched: Item): Item | text: fetched.text ?? item.text, points: fetched.points, commentCount: fetched.commentCount, + ...(fetched.type === 'poll' && { type: 'poll', pollOptions: fetched.pollOptions ?? item.pollOptions }), }; } +// A comments fetch that fails still brings the item it read, so a poll shows +// its options. Not cached: the cache holds an item with its comments. +function withFailedFetchFields(item: Item | null, err: unknown): Item | null { + return err instanceof CommentsError ? withFetchedFields(item, err.item) : item; +} + // A comment's replies come from useCommentDetail (Algolia /items), and a poll // option has no comments. function fetchesComments(item: Item): boolean { @@ -69,7 +83,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul const [initialCache] = useState(() => getCachedItem(itemId)); // Lazy initialization from cache or initialItem for instant render - const [item, setItem] = useState(() => withText(initialItem, initialCache?.item) ?? initialCache?.item ?? null); + const [item, setItem] = useState(() => withCachedFields(initialItem, initialCache?.item) ?? initialCache?.item ?? null); const [comments, setComments] = useState(() => initialCache?.comments ?? null); const [itemLoading, setItemLoading] = useState(!initialItem && !initialCache?.item); @@ -117,7 +131,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul const cached = getCachedItem(itemId); - const hasItem = withText(initialItem, cached?.item) ?? cached?.item; + const hasItem = withCachedFields(initialItem, cached?.item) ?? cached?.item; const stateHasDifferentItem = currentItem && String(currentItemId) !== String(itemId); @@ -130,6 +144,9 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul if (cached.item && (!currentItem || stateHasDifferentItem)) { setItem(cached.item); setItemLoading(false); + } else if (cached.item) { + // A feed's copy, held since before the prefetch: it has no poll options. + setItem(current => withCachedFields(current, cached.item)); } } else if (stateHasDifferentItem) { // itemId changed and the new item isn't (freshly) cached — reset to a @@ -138,19 +155,21 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul const validInitialItem = initialItem && String(initialItem.id) === String(itemId) ? initialItem : null; - setItem(withText(validInitialItem, cached?.item)); + setItem(withCachedFields(validInitialItem, cached?.item)); setItemLoading(!validInitialItem); setComments(null); setCommentsLoading(true); setCommentsError(null); } - const needsFullFetch = !cached?.isFresh || !hasItem || !cached?.comments; + // A poll whose options failed to load with its comments reads them again. + const lacksPollOptions = hasItem?.type === 'poll' && !hasItem.pollOptions; + const needsFullFetch = !cached?.isFresh || !hasItem || !cached?.comments || lacksPollOptions; // Mobile swipe mode skips ordering completion — users swipe fast and deep // order isn't visible. const needsOrderingCompletion = !skipOrderingCompletion && cached?.isFresh && cached?.orderedDepth < 3; - if (cached?.isFresh && hasItem && cached?.comments && cached?.orderedDepth >= 3) { + if (cached?.isFresh && hasItem && cached?.comments && cached?.orderedDepth >= 3 && !lacksPollOptions) { return; } @@ -230,6 +249,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul } catch (err) { if (!controller.signal.aborted && !(err instanceof Error && err.name === 'AbortError')) { // Comments failed but item succeeded — still usable, but surface the error. + setItem(current => withFailedFetchFields(current, err)); setCommentsLoading(false); setCommentsError(err instanceof Error ? err.message : 'Failed to load comments'); console.warn('Failed to load comments:', err); @@ -320,6 +340,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul }) .catch(err => { if (controller.signal.aborted || (err instanceof Error && err.name === 'AbortError')) return; + setItem(current => withFailedFetchFields(current, err)); setCommentsLoading(false); setCommentsError(err instanceof Error ? err.message : 'Failed to load comments'); }) @@ -358,11 +379,15 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul if (fetchesComments(itemData)) { try { - const commentsData = await fetchCommentsForItem(itemId); + // Its read of the item carries a poll's options, which fetchItemOnly's doesn't. + const { item: fetchedItem, comments: commentsData } = await fetchItemWithComments(itemId); + const fullItem = withFetchedFields(itemData, fetchedItem) ?? itemData; + setItem(fullItem); setComments(commentsData); - setCachedItem(itemId, itemData, commentsData); + setCachedItem(itemId, fullItem, commentsData); } catch (err) { // The item loaded, so the page can show it with the comments error. + setItem(withFailedFetchFields(itemData, err) ?? itemData); setCommentsError(err instanceof Error ? err.message : 'Failed to load comments'); } } @@ -382,6 +407,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul const fullItem = withFetchedFields(item, fetchedItem); if (fullItem) setCachedItem(itemId, fullItem, commentsData, 3); } catch (err) { + setItem(current => withFailedFetchFields(current, err)); setCommentsError(err instanceof Error ? err.message : 'Failed to load comments'); throw err; } diff --git a/src/hooks/useUserInfiniteStories.test.ts b/src/hooks/useUserInfiniteStories.test.ts index 9d5239e..08bd555 100644 --- a/src/hooks/useUserInfiniteStories.test.ts +++ b/src/hooks/useUserInfiniteStories.test.ts @@ -60,7 +60,7 @@ function fakeResponse(jsonDeferred: Deferred, status = 200): Response { } as unknown as Response; } -/** Extracts the author tag value from a `search_by_date?tags=story,author_X` URL. */ +/** Extracts the author tag value from a `search_by_date?tags=(story,poll),author_X` URL. */ function authorFromUrl(url: string): string { const params = new URLSearchParams(url.split('?')[1] ?? ''); const tags = params.get('tags') ?? ''; @@ -100,7 +100,7 @@ describe('useUserInfiniteStories', () => { expect(result.current.hasMore).toBe(false); }); - it('queries Algolia with the AND-tagged author filter and preserves username case', async () => { + it('queries Algolia for the stories and polls by the author, preserving username case', async () => { const fetchSpy = vi .spyOn(globalThis, 'fetch') .mockResolvedValue(new Response(JSON.stringify(body([1])))); @@ -108,9 +108,9 @@ describe('useUserInfiniteStories', () => { const { result } = renderHook(() => useUserInfiniteStories('PaulG')); await waitFor(() => expect(result.current.loading).toBe(false)); - const url = fetchInputToUrl(fetchSpy.mock.calls[0]?.[0]); - expect(url).toContain('search_by_date'); - expect(url).toMatch(/tags=story%2Cauthor_PaulG|tags=story,author_PaulG/); + const url = new URL(fetchInputToUrl(fetchSpy.mock.calls[0]?.[0])); + expect(url.pathname).toContain('search_by_date'); + expect(url.searchParams.get('tags')).toBe('(story,poll),author_PaulG'); }); it('returns empty list and hasMore=false on the first round-trip when the user has no stories (no cap loop)', async () => { diff --git a/src/hooks/useUserInfiniteStories.ts b/src/hooks/useUserInfiniteStories.ts index 7ab7ffd..cc539a8 100644 --- a/src/hooks/useUserInfiniteStories.ts +++ b/src/hooks/useUserInfiniteStories.ts @@ -89,10 +89,10 @@ export function useUserInfiniteStories(username: string) { try { const pageToFetch = nextPageRef.current; - // tags=story,author_X is an AND filter: only stories AND authored by X. - // search_by_date returns chronological newest-first, matching HN's - // /submitted ordering. - const url = `${ALGOLIA_API}/search_by_date?tags=story,author_${encodeURIComponent(username)}&hitsPerPage=${HITS_PER_PAGE}${algoliaPageParams(pageToFetch)}`; + // tags=(story,poll),author_X: stories or polls (an OR group) AND + // authored by X, as HN's /submitted lists both. search_by_date returns + // chronological newest-first, matching HN's /submitted ordering. + const url = `${ALGOLIA_API}/search_by_date?tags=(story,poll),author_${encodeURIComponent(username)}&hitsPerPage=${HITS_PER_PAGE}${algoliaPageParams(pageToFetch)}`; const response = await fetch(url); if (!response.ok) { diff --git a/src/index.css b/src/index.css index 44a121f..4489d7a 100644 --- a/src/index.css +++ b/src/index.css @@ -843,6 +843,33 @@ body.swipe-mode.is-swiping .app-header { border-radius: 8px; } +/* ── Poll options ─────────────────────────────────────────────────── */ + +/* Under the poll's body (or its meta row), with the story body's spacing. + Each option is a bordered row whose fill is its share of the points; the + leader's fill is stronger. */ +.poll { + margin-top: 18px; +} + +.poll-option { + position: relative; + overflow: hidden; + padding: 10px 14px; + border: 1px solid var(--border); + border-radius: 8px; +} + +.poll-option-fill { + position: absolute; + inset: 0 auto 0 0; + background: color-mix(in oklch, var(--accent) 10%, transparent); +} + +.poll-option[data-leading] .poll-option-fill { + background: color-mix(in oklch, var(--accent) 22%, transparent); +} + /* ── OP badge ─────────────────────────────────────────────────────── */ /* Soft-tinted accent pill (shadcn-ghost treatment) rendered next to diff --git a/src/pages/ItemDetail.test.tsx b/src/pages/ItemDetail.test.tsx index b27ff26..c298e25 100644 --- a/src/pages/ItemDetail.test.tsx +++ b/src/pages/ItemDetail.test.tsx @@ -96,13 +96,19 @@ describe('ItemDetail', () => { }); }); - it('says a poll option is not supported instead of showing it', async () => { - vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, type: 'pollopt' }); + it('shows a poll option on its own page, linked to its poll', async () => { + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => ( + Number(id) === 126810 + ? { id: 126810, text: 'Yes, ban them

    I'm tired of polls', by: 'pg', score: 30, time: 1204403652, poll: 126809, type: 'pollopt' } + : { id: 126809, title: 'Poll: Ban Polls?', by: 'pg', score: 46, time: 1204403652, parts: [126810], type: 'poll' } + )); renderItemDetail(126810); - expect(await screen.findByRole('heading', { name: "Poll options aren't supported" })).toBeInTheDocument(); - expect(screen.queryByRole('heading', { level: 1 })).not.toBeInTheDocument(); - expect(document.title).toBe("Poll options aren't supported | HackerTok"); + // Its paragraphs kept, as in a comment. + expect((await screen.findByText('Yes, ban them')).innerHTML).toBe("Yes, ban them

    I'm tired of polls

    "); + expect(screen.getByText('30 points')).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /Poll: Ban Polls\?/ })).toHaveAttribute('href', '/item/126809'); + expect(document.title).toBe("Yes, ban them I'm tired of polls | HackerTok"); }); describe('comments that keep failing', () => { diff --git a/src/pages/ItemDetail.tsx b/src/pages/ItemDetail.tsx index 6050bfd..266fc30 100644 --- a/src/pages/ItemDetail.tsx +++ b/src/pages/ItemDetail.tsx @@ -2,10 +2,11 @@ import { useParams } from 'react-router'; import { useEffect } from 'react'; import { useItemWithComments } from '../hooks/useItemWithComments'; import { isPollOption } from '../api/hn'; -import { ItemDetailSkeleton, CommentDetail, StateView, CommentsSection, ItemArticle, PageStage, PollOptionNotSupported, POLL_OPTION_TITLE } from '../components'; +import { ItemDetailSkeleton, CommentDetail, StateView, CommentsSection, ItemArticle, PageStage, PollOptionArticle } from '../components'; import { useDocumentTitle } from '../hooks/useDocumentTitle'; import { useNetworkStatus } from '../hooks/useNetworkStatus'; import { useAutoRetry } from '../hooks/useAutoRetry'; +import { htmlToText } from '../utils/sanitize'; export function ItemDetail() { const { id } = useParams(); @@ -20,7 +21,8 @@ export function ItemDetail() { const documentTitle = (!id || isNotFound || (!itemLoading && !item)) ? 'Item not found' : error ? 'Failed to load item' - : item && isPollOption(item) ? POLL_OPTION_TITLE + // A poll option's text is its title, as on HN. + : item && isPollOption(item) ? (htmlToText(item.text) || 'Poll option') : (item && 'title' in item ? item.title : undefined); useDocumentTitle(documentTitle); @@ -77,8 +79,8 @@ export function ItemDetail() { if (!itemLoading && item && isPollOption(item)) { return ( -
    - +
    +
    ); } @@ -94,7 +96,7 @@ export function ItemDetail() { loading={itemLoading || commentsLoading} skeleton={} > - {item && item.type !== 'comment' && ( + {item && item.type !== 'comment' && !isPollOption(item) && ( <>
    diff --git a/src/types.ts b/src/types.ts index 6e208fb..f4b5c9b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -13,15 +13,26 @@ interface ItemBase { createdAt: number; } +/** One choice in a poll. `text` is HN's HTML; sanitize before rendering. */ +export interface PollOption { + id: number; + text: string; + points: number; +} + export interface StoryItem extends ItemBase { - // A poll is a story. A poll option ('pollopt') rides along as one only so - // its page can say it isn't supported. - type: 'story' | 'ask' | 'show' | 'pollopt'; + type: 'story' | 'ask' | 'show' | 'poll'; title: string; url?: string; text?: string; points: number; commentCount: number; + /** + * A poll's options in HN's order, most points first. Only the comments + * fetch reads them, so feed copies and polls whose options haven't loaded + * leave it out. + */ + pollOptions?: PollOption[]; } export interface CommentItem extends ItemBase { @@ -38,7 +49,17 @@ export interface JobItem extends ItemBase { points: number; } -export type Item = StoryItem | CommentItem | JobItem; +/** A poll option opened on its own. It has no title or comments. */ +export interface PollOptionItem extends ItemBase { + type: 'pollopt'; + text: string; + points: number; + poll: number; + /** Left out when the poll couldn't be read. */ + pollTitle?: string; +} + +export type Item = StoryItem | CommentItem | JobItem | PollOptionItem; export interface Comment { id: number; @@ -97,6 +118,10 @@ export interface FirebaseItem { dead?: boolean; deleted?: boolean; parent?: number; + /** A poll's option ids. The API calls this display order, but HN lists options by points. */ + parts?: number[]; + /** A poll option's poll. */ + poll?: number; } // Algolia /items/{id} endpoint - returns item with full children tree diff --git a/src/utils/sanitize.test.ts b/src/utils/sanitize.test.ts index 939f878..cb9fa91 100644 --- a/src/utils/sanitize.test.ts +++ b/src/utils/sanitize.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import DOMPurify from 'dompurify'; -import { sanitizeHtml } from './sanitize'; +import { htmlToText, sanitizeHtml } from './sanitize'; describe('sanitizeHtml', () => { describe('basic functionality', () => { @@ -894,6 +894,14 @@ describe('sanitizeHtml', () => { }); }); +// A real poll option's text (34180944), and code blocks as HN writes them: `

    `.
    +describe('htmlToText', () => {
    +  it('keeps a space between paragraphs and code blocks', () => {
    +    expect(htmlToText('Lenovo T14

    Lenovo T480/490')).toBe('Lenovo T14 Lenovo T480/490'); + expect(htmlToText('A fast one:

    x =\n  1
    ')).toBe('A fast one: x = 1'); + }); +}); + // The link-rewriting hook lives on a private DOMPurify instance so it does // not leak to the default singleton that other code might import. If this // test ever fails, the hook has been re-attached to the global instance and diff --git a/src/utils/sanitize.ts b/src/utils/sanitize.ts index 59dd5a3..639c044 100644 --- a/src/utils/sanitize.ts +++ b/src/utils/sanitize.ts @@ -375,3 +375,15 @@ export function sanitizeHtml(html: string | null | undefined): string { const sanitized = DOMPurify.sanitize(html, PURIFY_CONFIG); return DOMPurify.sanitize(autoLinkUrls(sanitized), PURIFY_CONFIG); } + +/** + * HN's HTML as plain text, entities decoded, for a tab title or share sheet. + * A parsed document is inert: nothing in it loads or runs. + */ +export function htmlToText(html: string | null | undefined): string { + if (!html) return ''; + const body = new DOMParser().parseFromString(html, 'text/html').body; + // textContent runs paragraphs together: `a

    b` would read "ab". + body.querySelectorAll('p, pre, br').forEach(block => block.before(' ')); + return (body.textContent ?? '').replace(/\s+/g, ' ').trim(); +}