diff --git a/public/404.html b/404.html
similarity index 100%
rename from public/404.html
rename to 404.html
diff --git a/e2e/csp.spec.ts b/e2e/csp.spec.ts
index 18d5a4a..7734acf 100644
--- a/e2e/csp.spec.ts
+++ b/e2e/csp.spec.ts
@@ -66,4 +66,15 @@ test.describe('Content-Security-Policy', () => {
});
expect(await readViolations(page)).toEqual([]);
});
+
+ test('covers the 404.html redirect shell', async ({ page, request }) => {
+ // Pages serves 404.html for every unknown path, so it is a second entry
+ // document and needs the same policy.
+ const html = await (await request.get('/404.html')).text();
+ expect(html).toMatch(/ {
test.beforeEach(async ({ page }) => {
@@ -265,3 +266,27 @@ test.describe('Item Detail - Desktop', () => {
await expect(page.getByText('SQLite Does Not Do Full FSYNC by Default').first()).toBeVisible();
});
});
+
+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' },
+ },
+ }));
+ });
+
+ test('centers the notice between the header and the offline bar', async ({ page, context }) => {
+ 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 expectLocatorCenteredBetweenChrome(heading.locator('xpath=..'));
+ });
+});
diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts
index 21d1be6..b24e20e 100644
--- a/src/api/hn.test.ts
+++ b/src/api/hn.test.ts
@@ -941,6 +941,12 @@ describe('hn API utilities', () => {
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' });
+
+ expect((await fetchItemOnly(126810)).type).toBe('pollopt');
+ });
});
describe('error handling', () => {
diff --git a/src/api/hn.ts b/src/api/hn.ts
index b624a1e..14f9e64 100644
--- a/src/api/hn.ts
+++ b/src/api/hn.ts
@@ -85,9 +85,10 @@ function normalizeFirebaseItem(fbItem: FirebaseItem): Item {
// Firebase doesn't distinguish ask/show — they're all type='story'.
// Only the Algolia path (via _tags) can set 'ask'/'show' sub-types.
+ // A poll reads as a story, without its options.
return {
...base,
- type: 'story' as const,
+ type: fbItem.type === 'pollopt' ? 'pollopt' : 'story',
title: fbItem.title ?? '',
url: fbItem.url,
text: fbItem.text,
@@ -231,6 +232,11 @@ 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' } {
+ return item.type === 'pollopt';
+}
+
function normalizeFirebaseToStoryItem(fb: FirebaseItem): StoryItem {
return {
id: fb.id,
diff --git a/src/components/FullScreenComment.tsx b/src/components/FullScreenComment.tsx
index b85f9dd..414b292 100644
--- a/src/components/FullScreenComment.tsx
+++ b/src/components/FullScreenComment.tsx
@@ -62,7 +62,7 @@ export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenComme
if (error && !isRetrying) {
return (
-
+
void retry().catch(() => { /* error state set internally */ }) }} />
);
@@ -78,7 +78,7 @@ export function FullScreenComment({ commentId, onAuthorLoaded }: FullScreenComme
const isDeletedLeaf = !!comment && !comment.author && !comment.text && replies.length === 0 && !moreRepliesLoading;
if (!loading && (!comment || isDeletedLeaf)) {
return (
-
+
);
diff --git a/src/components/FullScreenItem.test.tsx b/src/components/FullScreenItem.test.tsx
index e33afaf..cc8f9be 100644
--- a/src/components/FullScreenItem.test.tsx
+++ b/src/components/FullScreenItem.test.tsx
@@ -82,4 +82,12 @@ 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' });
+ render(
);
+
+ expect(await screen.findByRole('heading', { name: "Poll options aren't supported" })).toBeInTheDocument();
+ expect(screen.queryByRole('heading', { level: 1 })).not.toBeInTheDocument();
+ });
});
diff --git a/src/components/FullScreenItem.tsx b/src/components/FullScreenItem.tsx
index 74c513c..82d45f1 100644
--- a/src/components/FullScreenItem.tsx
+++ b/src/components/FullScreenItem.tsx
@@ -1,11 +1,13 @@
import { useItemWithComments } from '../hooks/useItemWithComments';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
+import { isPollOption } from '../api/hn';
import { CommentSkeletonTree } from '../components';
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';
@@ -71,7 +73,7 @@ export function FullScreenItem({ itemId, initialItem, isPriority = true, deferCo
if (error && !isRetrying) {
return (
-
+
+
);
}
+ if (!itemLoading && item && isPollOption(item)) {
+ return (
+
+ );
+ }
+
return (
{/* `triggerWhen={isPriority}` holds the entrance animation
diff --git a/src/components/PollOptionNotSupported.tsx b/src/components/PollOptionNotSupported.tsx
new file mode 100644
index 0000000..73cef0a
--- /dev/null
+++ b/src/components/PollOptionNotSupported.tsx
@@ -0,0 +1,22 @@
+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/StateView.tsx b/src/components/StateView.tsx
index e0fa58f..15aef5c 100644
--- a/src/components/StateView.tsx
+++ b/src/components/StateView.tsx
@@ -112,9 +112,9 @@ function EmptyScene({ compact }: { compact?: boolean }) {
return (
{/* Rising thought dots — start at box opening (y≈55) and float above */}
-
-
-
+
+
+
{/* Floating particles */}
diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx
index 10fac93..486d5e0 100644
--- a/src/components/SwipeStoryViewer.test.tsx
+++ b/src/components/SwipeStoryViewer.test.tsx
@@ -88,6 +88,27 @@ 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' }),
+ );
+
+ render(
+
,
+ );
+
+ await waitFor(() => expect(activePanel()?.getAttribute('data-item-id')).toBe('126810'));
+ expect(document.title).toBe("Poll options aren't supported | HackerTok");
+ });
});
describe('SwipeStoryViewerCore — mount-snapshot filtering', () => {
diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx
index b899fea..7b9e81c 100644
--- a/src/components/SwipeStoryViewer.tsx
+++ b/src/components/SwipeStoryViewer.tsx
@@ -7,13 +7,14 @@ import { usePrefetchSections } from '../hooks/usePrefetchSections';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
-import { fetchItemOnly, NotFoundError } from '../api/hn';
+import { fetchItemOnly, isPollOption, NotFoundError } from '../api/hn';
import { getFilteredViewedIds, getSessionViewedIds } from '../utils/viewedItems';
import { readSwipePosition, saveSwipePosition, clearSwipePosition } from '../utils/swipePosition';
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';
@@ -222,6 +223,7 @@ 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);
@@ -720,7 +722,7 @@ export function SwipeStoryViewerCore({
`.active` sets display:block, so the centering lives on an inner box. */}
{showErrorPanel && (
-
+
{
expect(ids).toHaveLength(50);
});
+ it('keeps a stale cache stale when saving the session', () => {
+ const hourAgo = Date.now() - 60 * 60 * 1000;
+ setCachedFeed('top', [1, 2, 3].map(id => createStoryItem({ id })), hourAgo);
+ const { result } = renderHook(() => useInfiniteStories('top'));
+
+ act(() => result.current.saveSessionState(0));
+
+ expect(getCachedFeed('top')).toMatchObject({ timestamp: hourAgo, isStale: true });
+ });
+
describe('revalidation', () => {
function seedStaleFeed(type: FeedType) {
// A cached order the live ranking (1, 2, 3, …) has moved on from.
diff --git a/src/hooks/useInfiniteStories.ts b/src/hooks/useInfiniteStories.ts
index 4a8c243..11ff916 100644
--- a/src/hooks/useInfiniteStories.ts
+++ b/src/hooks/useInfiniteStories.ts
@@ -170,7 +170,10 @@ export function useInfiniteStories(type: FeedType = 'top') {
hasStaleCacheRef.current = false;
}
- positionRef.current = 1; // Next load will be yesterday
+ // Next load will be yesterday. By design, today's stories ranked
+ // past the top 20 are never shown: the feed is HN's front page,
+ // then each earlier (UTC) day's front page from Algolia.
+ positionRef.current = 1;
} else {
let attempts = 0;
const maxAttempts = 5; // Try up to 5 days if current day has no stories
@@ -371,9 +374,13 @@ export function useInfiniteStories(type: FeedType = 'top') {
phase: phaseRef.current,
});
- // Also update the stories cache with current full list (for session reconstruction)
- if (stories.length > 0) {
- setCachedFeed(type, stories);
+ // Also update the stories cache with current full list (for session
+ // reconstruction). Keep the cached timestamp: the list is no newer than
+ // its last fetch, and re-stamping it would let a stale list pass as fresh.
+ // No cache entry means the list is over a day old, or storage failed.
+ const fetchedAt = getCachedFeed(type)?.timestamp;
+ if (stories.length > 0 && fetchedAt !== undefined) {
+ setCachedFeed(type, stories, fetchedAt);
}
}, [type, stories, hasMore]);
diff --git a/src/hooks/useItemWithComments.test.tsx b/src/hooks/useItemWithComments.test.tsx
index d153623..1c37b80 100644
--- a/src/hooks/useItemWithComments.test.tsx
+++ b/src/hooks/useItemWithComments.test.tsx
@@ -548,6 +548,18 @@ describe('useItemWithComments', () => {
expect(getCachedItem(12345)?.item).toEqual(testItem);
});
+ it('takes the poll option type from the revalidation over a copy cached as a story', async () => {
+ vi.spyOn(hnSdk, 'readItem').mockResolvedValue({ id: 12345, text: 'Yes', by: 'pg', score: 30, time: mockFirebaseStory.time, type: 'pollopt' });
+ seedStaleCache();
+
+ const { result } = renderHook(() => useItemWithComments(12345));
+
+ await waitFor(() => {
+ expect(result.current.item?.type).toBe('pollopt');
+ });
+ expect(getCachedItem(12345)?.item.type).toBe('pollopt');
+ });
+
it('fetches when cache has no comments', async () => {
const CACHE_KEY = `${ITEM_CACHE_KEY_PREFIX}12345`;
const partialData = {
@@ -1031,6 +1043,28 @@ describe('useItemWithComments', () => {
});
});
+ describe('a poll option', () => {
+ it('fetches no comments, and releases priority once it loads', async () => {
+ const readItem = vi.spyOn(hnSdk, 'readItem').mockResolvedValue({
+ id: 126810, text: 'Yes, ban them', by: 'pg', score: 30, time: 1204403652, type: 'pollopt',
+ });
+ let commentSearches = 0;
+ server.use(
+ http.get(`${ALGOLIA_API}/search`, () => {
+ commentSearches++;
+ return HttpResponse.json({ hits: [], nbPages: 0 });
+ }),
+ );
+
+ const { result } = renderHook(() => useItemWithComments(126810));
+
+ await waitFor(() => expect(result.current.item?.type).toBe('pollopt'));
+ expect(isPriorityFetchActive()).toBe(false);
+ expect(readItem).toHaveBeenCalledTimes(1);
+ expect(commentSearches).toBe(0);
+ });
+ });
+
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 f45380d..fd6ee39 100644
--- a/src/hooks/useItemWithComments.ts
+++ b/src/hooks/useItemWithComments.ts
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef, useEffectEvent, useCallback } from 'react';
-import { fetchItemOnly, fetchCommentsForItem, fetchItemWithComments, NotFoundError } from '../api/hn';
+import { fetchItemOnly, fetchCommentsForItem, fetchItemWithComments, isPollOption, NotFoundError } from '../api/hn';
import { getCachedItem, setCachedItem } from '../utils/itemCache';
import { registerPriorityFetch, unregisterPriorityFetch } from '../utils/fetchPriority';
import { useNetworkStatus } from './useNetworkStatus';
@@ -40,8 +40,11 @@ function withText(item: Item | null | undefined, source: Item | null | undefined
// 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.
+// 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 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' ||
fetched.id !== item.id || !fetched.title) {
return withText(item, fetched);
@@ -56,6 +59,12 @@ function withFetchedFields(item: Item | null | undefined, fetched: Item): Item |
};
}
+// A comment's replies come from useCommentDetail (Algolia /items), and a poll
+// option has no comments.
+function fetchesComments(item: Item): boolean {
+ return item.type !== 'comment' && !isPollOption(item);
+}
+
export function useItemWithComments(itemId: number | string, { initialItem = null, skipOrderingCompletion = false, isPriority = true, deferComments = false }: UseItemWithCommentsOptions = {}): UseItemWithCommentsResult {
const [initialCache] = useState(() => getCachedItem(itemId));
@@ -241,13 +250,12 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
} else if (needsFullFetch) {
const itemData = hasItem ?? await loadItem();
- // Comment items use a different fetch path (useCommentDetail via Algolia /items).
- if (itemData && itemData.type !== 'comment' && !controller.signal.aborted) {
+ if (itemData && fetchesComments(itemData) && !controller.signal.aborted) {
await loadComments(itemData, false);
}
}
- // A comment item fetches nothing more. After an abort, whoever
- // aborted releases it.
+ // A comment item or poll option fetches nothing more. After an abort,
+ // whoever aborted releases it.
if (!controller.signal.aborted) releasePriority();
}
@@ -288,7 +296,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
const { commentsLoading, comments, commentsError, item, deferComments } = getReconnectSnapshot();
// Only act when comments are stuck loading (hanging fetch, no error surfaced)
- if (!commentsLoading || comments || commentsError || !item || item.type === 'comment' || deferComments) return;
+ if (!commentsLoading || comments || commentsError || !item || !fetchesComments(item) || deferComments) return;
// Abort the hanging fetch so its promise settles (AbortError, swallowed by the effect)
controllerRef.current?.abort();
@@ -348,8 +356,7 @@ export function useItemWithComments(itemId: number | string, { initialItem = nul
}
setItemLoading(false);
- // Comment items use a different fetch path (useCommentDetail via Algolia /items)
- if (itemData.type !== 'comment') {
+ if (fetchesComments(itemData)) {
try {
const commentsData = await fetchCommentsForItem(itemId);
setComments(commentsData);
diff --git a/src/hooks/usePrefetchItem.test.ts b/src/hooks/usePrefetchItem.test.ts
index 7ec5515..6a18282 100644
--- a/src/hooks/usePrefetchItem.test.ts
+++ b/src/hooks/usePrefetchItem.test.ts
@@ -136,6 +136,28 @@ describe('usePrefetchItem', () => {
expect(spy.mock.calls[1][0]).toBe(99999);
spy.mockRestore();
});
+
+ it('keeps tracking a restarted prefetch after the aborted one settles', async () => {
+ const settle: (() => void)[] = [];
+ const spy = vi.spyOn(hn, 'prefetchItemComments').mockImplementation(
+ () => new Promise(resolve => { settle.push(() => resolve(null)); }));
+ const { result } = renderHook(() => usePrefetchItem());
+
+ act(() => { result.current.startPrefetch(12345, 0); });
+ await act(async () => { vi.advanceTimersByTime(250); });
+ act(() => { result.current.stopPrefetch(); });
+ act(() => { result.current.startPrefetch(12345, 0); });
+ await act(async () => { vi.advanceTimersByTime(250); });
+ expect(spy).toHaveBeenCalledTimes(2);
+
+ // The first, aborted fetch settles while the second is still in flight.
+ await act(async () => { settle[0](); });
+ act(() => { result.current.startPrefetch(12345, 0); });
+ await act(async () => { vi.advanceTimersByTime(250); });
+
+ expect(spy).toHaveBeenCalledTimes(2);
+ spy.mockRestore();
+ });
});
describe('priority fetch integration', () => {
diff --git a/src/hooks/usePrefetchItem.ts b/src/hooks/usePrefetchItem.ts
index 2fd2171..9d54adf 100644
--- a/src/hooks/usePrefetchItem.ts
+++ b/src/hooks/usePrefetchItem.ts
@@ -84,7 +84,11 @@ async function processQueue() {
// Don't await — let prefetches run in parallel, refilling the queue
// as each completes.
void doPrefetch(bestId, controller).finally(() => {
- activePrefetches.delete(bestId);
+ // A stop-then-restart can register a newer prefetch for this id
+ // before this aborted one settles; leave that one tracked.
+ if (activePrefetches.get(bestId) === controller) {
+ activePrefetches.delete(bestId);
+ }
processQueueNow();
});
}
diff --git a/src/index.css b/src/index.css
index 7f28689..44a121f 100644
--- a/src/index.css
+++ b/src/index.css
@@ -461,6 +461,17 @@ html.dark { color-scheme: dark; }
min-height: 100%;
}
+/* A state (not found, error, …) in place of a swipe panel's content. The
+ active panel only has a min-height, so a percentage would resolve to
+ nothing; the state takes the panel's box under the header and centers in it. */
+.full-screen-state {
+ width: 100%;
+ min-height: calc(var(--swipe-viewport-height, 100vh) - var(--header-height) - var(--network-bar-height));
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
/* Browsers chain the document's top overscroll into pull-to-refresh, which
reloads the SPA and costs the reader their feed position. `contain` blocks the
chain but keeps the rubber-band `none` would remove. On the root because only
diff --git a/src/pages/ItemDetail.test.tsx b/src/pages/ItemDetail.test.tsx
index 8cbf075..b27ff26 100644
--- a/src/pages/ItemDetail.test.tsx
+++ b/src/pages/ItemDetail.test.tsx
@@ -96,6 +96,15 @@ 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' });
+ 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");
+ });
+
describe('comments that keep failing', () => {
afterEach(() => {
vi.useRealTimers();
diff --git a/src/pages/ItemDetail.tsx b/src/pages/ItemDetail.tsx
index b950356..6050bfd 100644
--- a/src/pages/ItemDetail.tsx
+++ b/src/pages/ItemDetail.tsx
@@ -1,7 +1,8 @@
import { useParams } from 'react-router';
import { useEffect } from 'react';
import { useItemWithComments } from '../hooks/useItemWithComments';
-import { ItemDetailSkeleton, CommentDetail, StateView, CommentsSection, ItemArticle, PageStage } from '../components';
+import { isPollOption } from '../api/hn';
+import { ItemDetailSkeleton, CommentDetail, StateView, CommentsSection, ItemArticle, PageStage, PollOptionNotSupported, POLL_OPTION_TITLE } from '../components';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useNetworkStatus } from '../hooks/useNetworkStatus';
import { useAutoRetry } from '../hooks/useAutoRetry';
@@ -19,6 +20,7 @@ export function ItemDetail() {
const documentTitle = (!id || isNotFound || (!itemLoading && !item))
? 'Item not found'
: error ? 'Failed to load item'
+ : item && isPollOption(item) ? POLL_OPTION_TITLE
: (item && 'title' in item ? item.title : undefined);
useDocumentTitle(documentTitle);
@@ -73,6 +75,14 @@ export function ItemDetail() {
return ;
}
+ if (!itemLoading && item && isPollOption(item)) {
+ return (
+
+ );
+ }
+
return (
{/* `loading={itemLoading || commentsLoading}` holds the skeleton
diff --git a/src/types.ts b/src/types.ts
index be3a77a..6e208fb 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -14,7 +14,9 @@ interface ItemBase {
}
export interface StoryItem extends ItemBase {
- type: 'story' | 'ask' | 'show';
+ // 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';
title: string;
url?: string;
text?: string;
diff --git a/src/utils/feedCache.ts b/src/utils/feedCache.ts
index e4ee2fa..4f29cff 100644
--- a/src/utils/feedCache.ts
+++ b/src/utils/feedCache.ts
@@ -32,10 +32,11 @@ export function getCachedFeed(type: FeedType): { stories: StoryItem[]; timestamp
}
}
-export function setCachedFeed(type: FeedType, stories: StoryItem[]): void {
+/** `timestamp` is when the list was fetched; it decides freshness. */
+export function setCachedFeed(type: FeedType, stories: StoryItem[], timestamp = Date.now()): void {
try {
const key = `${FEED_CACHE_KEY_PREFIX}${type}`;
- const data = { stories, timestamp: Date.now() };
+ const data = { stories, timestamp };
setLocalStorageItem(key, JSON.stringify(data));
} catch { /* best-effort */ }
}
diff --git a/src/utils/sanitize.ts b/src/utils/sanitize.ts
index 4f93abe..59dd5a3 100644
--- a/src/utils/sanitize.ts
+++ b/src/utils/sanitize.ts
@@ -133,7 +133,7 @@ function parseHn(parsed: URL): RouteTarget | null {
function parseSelf(parsed: URL): RouteTarget | null {
// Two URL forms exist in the wild because of the redirect script in
- // index.html / public/404.html:
+ // index.html / 404.html:
// - hash form (canonical): https://hackertok.github.io/#/item/47816960
// - non-hash form: https://hackertok.github.io/item/47816960
// Normalize to a single `inAppPath` and match path-segment regexes.
diff --git a/vite.config.js b/vite.config.js
index 03e0401..7eeb240 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -170,6 +170,12 @@ export default defineConfig({
},
build: {
rollupOptions: {
+ // 404.html is an entry, not a public/ file, so html-meta-csp hashes its
+ // redirect script: public/ is copied verbatim and would ship it with no CSP.
+ input: {
+ index: fileURLToPath(new URL('./index.html', import.meta.url)),
+ 404: fileURLToPath(new URL('./404.html', import.meta.url)),
+ },
output: {
manualChunks(id) {
if (id.includes('node_modules/firebase') || id.includes('node_modules/@firebase')) {