diff --git a/e2e/fixtures/mock-data.ts b/e2e/fixtures/mock-data.ts index 06c1a2c..777bd83 100644 --- a/e2e/fixtures/mock-data.ts +++ b/e2e/fixtures/mock-data.ts @@ -326,7 +326,7 @@ export const mockAlgoliaCommentItem1004 = { children: [], }; -// Job item — type=job triggers SwipeStoryViewer's "not a story" error path on mobile. +// Job item — a direct link opens it on the item page on mobile too. export const mockJobItem = { id: 55555, type: 'job', diff --git a/e2e/mobile-swipe.spec.ts b/e2e/mobile-swipe.spec.ts index 4338dff..b9a4c88 100644 --- a/e2e/mobile-swipe.spec.ts +++ b/e2e/mobile-swipe.spec.ts @@ -431,15 +431,16 @@ test.describe('Mobile Swipe Viewer', () => { }); test('a feed refresh that lands after a swipe keeps the story on screen', async ({ page }) => { - // An hour-old cached Top feed in the reverse of the live order, and Firebase - // reads that take 1.5s, so the refresh lands after the swipe. + // A minute-old cached Top feed in the reverse of the live order, which opens + // at once and still refreshes, and Firebase reads that take 1.5s, so the + // refresh lands after the swipe. await page.routeWebSocket(FIREBASE_WS_PATTERN, createFirebaseWsHandler({ delayMs: 1500 })); await page.addInitScript((ids) => { const stories = [...ids].reverse().map((id) => ({ id, type: 'story', title: `Cached story ${id}`, url: `https://example.com/${id}`, points: 1, author: 'someone', createdAt: Date.now() - 3_600_000, commentCount: 0, })); - localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 3_600_000 })); + localStorage.setItem('feed:top', JSON.stringify({ stories, timestamp: Date.now() - 60_000 })); }, mockTopItemIds); await page.goto('/#/'); @@ -938,16 +939,17 @@ test.describe('Mobile Direct Item Access', () => { await expect(page).toHaveURL(/\/item\/1001/); }); - test('shows not-available message for job items', async ({ page }) => { - // Job items (type: 'job') are not stories — SwipeStoryViewer shows an error. - // Flow: MobileItemResolver fetches item → type is 'job' (not 'comment') → - // renders SwipeStoryViewer → it fetches again → detects type === 'job' → - // sets injectedError('job') → renders error UI. + test('opens job items on the item page', async ({ page }) => { + // The swipe viewer only takes stories, and no feed lists jobs, so a direct + // link to one gets the item page, as on desktop. await page.goto('/#/item/55555'); - await expect(page.getByText('This item is not a story')).toBeVisible({ timeout: 10000 }); - await expect(page.getByRole('link', { name: /back to home/i })).toBeVisible(); - await expect(page).toHaveTitle(/Item not available.*HackerTok/); + await expect(page.getByRole('heading', { name: 'YC Startup Is Hiring Engineers' })).toBeVisible({ timeout: 10000 }); + await expect(page).toHaveTitle(/YC Startup Is Hiring Engineers.*HackerTok/); + await expect(page.getByTestId('swipe-container')).toHaveCount(0); + // index.html adds swipe-mode before paint for any /item/:id. + await expect(page.locator('html')).not.toHaveClass(/swipe-mode/); + await expect(page.locator('body')).not.toHaveClass(/swipe-mode/); }); test('restores swipe position on the main feed after a full page reload', async ({ page }) => { diff --git a/src/App.test.tsx b/src/App.test.tsx index d2390f1..7dce0d6 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -46,6 +46,9 @@ vi.mock('./components/SwipeUserSubmissionsViewer', () => ({
), })); +vi.mock('./pages/ItemDetail', () => ({ + ItemDetail: () =>
, +})); // The resolver fallback (Branch 5) calls fetchItemOnly; keep it pending so the // resolver stays on its skeleton — a deterministic signal that we did NOT take @@ -186,6 +189,17 @@ describe('MobileStoryRoute — direct link', () => { expect(viewer).toHaveAttribute('data-item', '12345'); expect(viewer).toHaveAttribute('data-mounted-item', '88888'); }); + + it('opens a job on the item page, since the story viewer only takes stories', async () => { + vi.mocked(fetchItemOnly).mockResolvedValueOnce({ + id: 77777, type: 'job', title: 'Acme Is Hiring', author: 'acme', createdAt: 0, points: 1, + }); + + renderWrapper(77777); + + expect(await screen.findByTestId('item-detail')).toBeInTheDocument(); + expect(screen.queryByTestId('feed-viewer')).toBeNull(); + }); }); describe('MobileStoryRoute — ids that are not numbers', () => { diff --git a/src/App.tsx b/src/App.tsx index 8a698db..9af2e81 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -111,7 +111,7 @@ export function MobileStoryRoute({ feed }: { feed?: FeedType }) { const viewer = canSwipe && isNumericId ? pickSwipeViewer(location.state as LocationState | null, recovered, id, feedEntries) : null; - const isResolvedStory = useResolveDirectLink(id, canSwipe && isNumericId && !viewer); + const resolvedType = useResolveDirectLink(id, canSwipe && isNumericId && !viewer); if (feed) { // key={feed}: a list mounts for each feed, so Back to one restores its @@ -129,8 +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. - if (isResolvedStory) return renderSwipeViewer({ from: 'top' }, id, feedEntries); + // 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 ; + if (resolvedType === 'story') return renderSwipeViewer({ from: 'top' }, id, feedEntries); return ; } @@ -178,10 +180,10 @@ function ItemNotFound() { } // Resolves item type for a direct URL hit on mobile (no `location.state`): -// a comment re-routes to Branch 1, and anything else reports `true` so the -// wrapper mounts the story viewer. -function useResolveDirectLink(id: string | undefined, enabled: boolean): boolean { - const [storyId, setStoryId] = useState(null); +// 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); const navigate = useNavigate(); useEffect(() => { @@ -195,19 +197,19 @@ function useResolveDirectLink(id: string | undefined, enabled: boolean): boolean // Navigate with state so MobileStoryRoute Branch 1 picks it up void navigate(`/item/${id}`, { replace: true, state: { isComment: true } }); } else { - setStoryId(id); + setResolved({ id, type: item.type === 'job' ? 'job' : 'story' }); } }) .catch(() => { if (controller.signal.aborted) return; // Default to story viewer on error (it has its own error handling) - setStoryId(id); + setResolved({ id, type: 'story' }); }); return () => controller.abort(); }, [id, enabled, navigate]); - return storyId !== null && storyId === id; + return resolved && resolved.id === id ? resolved.type : null; } function MobileItemResolverSkeleton() { diff --git a/src/api/hn.test.ts b/src/api/hn.test.ts index 4248d43..21d1be6 100644 --- a/src/api/hn.test.ts +++ b/src/api/hn.test.ts @@ -1342,8 +1342,20 @@ describe('hn API utilities', () => { expect(rootReplies.map(c => c.id)).toEqual([201, 202]); expect(liveReplyReplies.map(c => c.id)).toEqual([302]); expect(fetchSpy).toHaveBeenCalledTimes(1); - // 201 and its reply 302 to see whether to search, then each missing parent once. - expect(readItem.mock.calls.map(([id]) => Number(id)).sort()).toEqual([201, 202, 302, 302]); + // 201 and its reply 302 to see whether to search, then each missing + // parent once, and 101 to order its two replies. + expect(readItem.mock.calls.map(([id]) => Number(id)).sort()).toEqual([101, 201, 202, 302, 302]); + }); + + it('orders the replies the way HN ranks them', async () => { + const { readItem } = mockStory(); + readItem.mockImplementation(async (id) => Number(id) === 101 + ? { id: 101, type: 'comment', by: 'alice', time: 1700000100, parent: storyId, kids: [202, 201] } + : firebaseItems.find(fb => fb.id === Number(id)) ?? null); + + const replies = await fetchCommentReplies(item); + + expect(replies.map(c => c.id)).toEqual([202, 201]); }); it('reads the story again after a failed read', async () => { diff --git a/src/api/hn.ts b/src/api/hn.ts index d6a8f3e..b624a1e 100644 --- a/src/api/hn.ts +++ b/src/api/hn.ts @@ -749,11 +749,23 @@ export async function fetchCommentItem(id: number | string, signal?: AbortSignal text: firebaseCommentText(item) ?? null, created_at_i: item.time ?? 0, parent_id: item.parent ?? null, - story_id: replies[0]?.story_id ?? null, + story_id: replies[0]?.story_id ?? await findStoryId(item.parent, signal), children: replies.map(reply => ({ ...reply, parent_id: item.id })), }; } +// The story a comment is on, up its parent chain: Firebase keeps flagged and +// deleted comments, which Algolia 404s. Null when a read fails. +async function findStoryId(parentId: number | undefined, signal?: AbortSignal): Promise { + for (let id = parentId, hops = 0; id != null && hops < 100; hops++) { + const parent = await fetchFirebaseItem(id, signal).catch(() => null); + if (!parent) return null; + if (parent.type !== 'comment') return parent.id; + id = parent.parent; + } + return null; +} + // A story's comments from search, with the flagged and deleted parents it // leaves out. Null for a thread bigger than search returns. Comments next to // each other in the swipe viewer share one read, so no caller's signal ends it. @@ -789,8 +801,9 @@ async function hasRepliesOutsideItemTree(id: number, signal?: AbortSignal): Prom /** * A comment's replies, with the flagged and deleted ones that have live - * replies. Algolia's item tree leaves those out along with their replies, so - * they come from the story's comments, as in the story thread. + * replies, in HN's order. Algolia's item tree leaves those out along with + * their replies, so they come from the story's comments, as in the story + * thread. Both come in creation order, so the order comes from Firebase. */ export async function fetchCommentReplies(item: AlgoliaItemResponse, signal?: AbortSignal): Promise { if (item.story_id == null) return normalizeAlgoliaItemChildren(item.children ?? []); @@ -800,15 +813,24 @@ export async function fetchCommentReplies(item: AlgoliaItemResponse, signal?: Ab } if (!mayHaveMore) return []; + // Null for a thread bigger than search returns, which keeps the item tree's replies. const storyComments = await fetchStoryComments(item.story_id); if (signal?.aborted) { throw new DOMException('Aborted', 'AbortError'); } - if (!storyComments) return normalizeAlgoliaItemChildren(item.children ?? []); const replies = flattenAlgoliaItemChildren(item.children ?? []); const seen = new Set(replies.map(c => c.objectID)); - return buildCommentTree([...replies, ...storyComments.filter(c => !seen.has(c.objectID))], item.id); + const comments = [...replies, ...(storyComments ?? []).filter(c => !seen.has(c.objectID))]; + const kidsOrder = await fetchKidsOrdering(parentsWithSiblings(buildCommentTree(comments, item.id), item.id), signal); + return buildCommentTree(comments, item.id, kidsOrder); +} + +// The ids in a reply tree whose replies need ordering: those with more than one. +function parentsWithSiblings(replies: Comment[], parentId: number, into: number[] = []): number[] { + if (replies.length > 1) into.push(parentId); + for (const reply of replies) parentsWithSiblings(reply.children, reply.id, into); + return into; } export function normalizeAlgoliaItemChildren(children: AlgoliaItemChild[]): Comment[] { diff --git a/src/components/SwipeStoryViewer.test.tsx b/src/components/SwipeStoryViewer.test.tsx index eaa8779..10fac93 100644 --- a/src/components/SwipeStoryViewer.test.tsx +++ b/src/components/SwipeStoryViewer.test.tsx @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, screen, within } from '@testing-library/react'; +import { act, screen, waitFor, within } from '@testing-library/react'; import { render } from '../test/test-utils'; -import { SwipeStoryViewerCore } from './SwipeStoryViewer'; +import { SwipeStoryViewer, SwipeStoryViewerCore } from './SwipeStoryViewer'; import { createStoryItem } from '../test/factories'; import { clearViewed, @@ -12,7 +12,7 @@ import { VIEWED_DETAIL_TIMES_KEY, } from '../utils/viewedItems'; import { saveSwipePosition, readSwipePosition } from '../utils/swipePosition'; -import { fetchItemOnly } from '../api/hn'; +import { fetchItemOnly, fetchTopStories } from '../api/hn'; import type * as HnApi from '../api/hn'; import type { LocationState } from '../types'; @@ -30,8 +30,11 @@ vi.mock('./FullScreenItem', () => ({ vi.mock('../api/hn', async (importOriginal) => ({ ...(await importOriginal()), fetchItemOnly: vi.fn(() => new Promise(() => { /* never resolves */ })), + fetchTopStories: vi.fn(), })); +vi.mock('../hooks/usePrefetchSections', () => ({ usePrefetchSections: vi.fn() })); + // Swipes commit synchronously under reduced motion, without the Web Animations // API that jsdom lacks. vi.mock('../utils/prefersReducedMotion', () => ({ prefersReducedMotion: () => true })); @@ -749,4 +752,66 @@ describe('SwipeStoryViewerCore — viewed marks on landing', () => { expect(markedIds()).toEqual([1]); }); -}); \ No newline at end of file +}); + +describe('SwipeStoryViewer — opening a feed from an old cache', () => { + // An hour-old cache, whose first story is second on HN now. + const cachedIds = Array.from({ length: 12 }, (_, i) => i + 1); + + beforeEach(() => { + localStorage.setItem('feed:top', JSON.stringify({ + stories: cachedIds.map(id => createStoryItem({ id })), + timestamp: Date.now() - 3_600_000, + })); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('waits for the refresh instead of keeping the cached first story', async () => { + vi.mocked(fetchTopStories).mockResolvedValue([13, ...cachedIds].map(id => createStoryItem({ id }))); + render(); + + expect(screen.getByTestId('fsi-skeleton')).toBeInTheDocument(); + expect(screen.queryByTestId('fsi')).not.toBeInTheDocument(); + await waitFor(() => expect(activePanel()).toHaveAttribute('data-item-id', '13')); + }); + + it('shows the cache when the refresh fails', async () => { + vi.mocked(fetchTopStories).mockRejectedValue(new Error('Failed to fetch')); + render(); + + await waitFor(() => expect(activePanel()).toHaveAttribute('data-item-id', '1')); + }); + + it('shows the cache once the app goes offline, where the refresh never settles', () => { + vi.mocked(fetchTopStories).mockReturnValue(new Promise(() => { /* never resolves */ })); + render(); + expect(screen.getByTestId('fsi-skeleton')).toBeInTheDocument(); + expect(screen.queryByTestId('fsi')).not.toBeInTheDocument(); + + act(() => { + window.dispatchEvent(new Event('offline')); + }); + + expect(activePanel()).toHaveAttribute('data-item-id', '1'); + }); + + it('shows the cache after three seconds when the refresh stalls online', () => { + vi.useFakeTimers(); + vi.mocked(fetchTopStories).mockReturnValue(new Promise(() => { /* never resolves */ })); + render(); + + act(() => { + vi.advanceTimersByTime(2_999); + }); + expect(screen.getByTestId('fsi-skeleton')).toBeInTheDocument(); + expect(screen.queryByTestId('fsi')).not.toBeInTheDocument(); + + act(() => { + vi.advanceTimersByTime(1); + }); + expect(activePanel()).toHaveAttribute('data-item-id', '1'); + }); +}); diff --git a/src/components/SwipeStoryViewer.tsx b/src/components/SwipeStoryViewer.tsx index 4d630b4..b899fea 100644 --- a/src/components/SwipeStoryViewer.tsx +++ b/src/components/SwipeStoryViewer.tsx @@ -10,6 +10,7 @@ import { useAutoRetry } from '../hooks/useAutoRetry'; import { fetchItemOnly, 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'; @@ -738,9 +739,29 @@ interface SwipeStoryViewerProps { initialItemId?: string; } +const NO_STORIES: StoryItem[] = []; +const STALE_CACHE_WAIT_MS = 3000; + /** Feed-backed swipe viewer wrapping SwipeStoryViewerCore. */ export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps) { const { stories, loading, error, hasMore, loadMore, isFromCache, isFromSession, keepOnRevalidate } = useInfiniteStories(type); + const { isOnline } = useNetworkStatus(); + + // The refresh below keeps the story on screen, so a feed opened from a cache + // over five minutes old would stay on its old first story, which the logo + // then replaces. Opening a feed waits for the refresh instead, and shows the + // cache if the refresh fails, the app is offline, or three seconds pass, as + // on a stalled connection, where Firebase waits with no timeout. A story URL + // shows that story either way. + const [hidesStaleCache, setHidesStaleCache] = useState( + () => initialItemId == null && isFromCache && !isCacheFresh(type), + ); + if (hidesStaleCache && (!isFromCache || !!error || !isOnline)) setHidesStaleCache(false); + useEffect(() => { + if (!hidesStaleCache) return; + const timer = setTimeout(() => setHidesStaleCache(false), STALE_CACHE_WAIT_MS); + return () => clearTimeout(timer); + }, [hidesStaleCache]); // Prefetch other sections in background for instant tab switching usePrefetchSections(type); @@ -759,8 +780,8 @@ export function SwipeStoryViewer({ type, initialItemId }: SwipeStoryViewerProps) return ( { expect(result.current.comment).toBeNull(); }); + it('finds the story of a flagged comment with no replies up its parent chain', async () => { + const now = Math.floor(Date.now() / 1000); + const items: FirebaseItem[] = [ + mockStoryItem, + { id: 1001, type: 'comment', by: 'patio11', text: 'Root', time: now - 1800, parent: 12345, kids: [2001] }, + { id: 2001, type: 'comment', by: 'tptacek', text: 'Reply', time: now - 900, parent: 1001, kids: [4001] }, + { id: 4001, type: 'comment', by: 'eve', text: 'Killed text', dead: true, time: now - 300, parent: 2001 }, + ]; + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => items.find(item => item.id === Number(id)) ?? null); + + const { result } = renderHook(() => useCommentDetail(4001)); + + await waitFor(() => { + expect(result.current.itemTitle).toBe('Rust Is the Future of JavaScript Infrastructure'); + }); + expect(result.current.itemId).toBe(12345); + expect(result.current.comment).toMatchObject({ id: 4001, parentId: 2001 }); + }); + + describe("HN's order, which Algolia's item tree doesn't keep", () => { + const now = Math.floor(Date.now() / 1000); + const reply = (id: number, parentId: number, age: number, children: object[] = []) => + ({ id, author: `user${id}`, text: 'Reply', created_at_i: now - age, parent_id: parentId, children }); + + function mockComment(children: object[], firebaseItems: FirebaseItem[], storyComments: () => Response | Promise) { + server.use( + http.get(`${ALGOLIA_API}/items/:id`, () => HttpResponse.json({ ...mockAlgoliaCommentItem, children })), + http.get(`${ALGOLIA_API}/search`, storyComments), + ); + vi.spyOn(hnSdk, 'readItem').mockImplementation(async (id) => { + if (Number(id) === 12345) return mockStoryItem; + return firebaseItems.find(item => item.id === Number(id)) ?? null; + }); + } + + it("puts the replies in it without waiting for the story's comments", async () => { + mockComment( + [reply(2001, 1001, 900), reply(2002, 1001, 800)], + [{ id: 1001, type: 'comment', by: 'patio11', time: now - 1800, parent: 12345, kids: [2002, 2001] }], + () => new Promise(() => { /* never loads */ }), + ); + + const { result } = renderHook(() => useCommentDetail(1001)); + + await waitFor(() => { + expect(result.current.replies.map(c => c.id)).toEqual([2002, 2001]); + }); + expect(result.current.moreRepliesLoading).toBe(true); + }); + + it("puts nested replies in it once the story's comments load", async () => { + mockComment( + [reply(2001, 1001, 900, [reply(3001, 2001, 700), reply(3002, 2001, 600)])], + [{ id: 2001, type: 'comment', by: 'user2001', time: now - 900, parent: 1001, kids: [3002, 3001] }], + () => HttpResponse.json({ hits: [], nbHits: 0, nbPages: 0 }), + ); + + const { result } = renderHook(() => useCommentDetail(1001)); + + await waitFor(() => { + expect(result.current.loading).toBe(false); + expect(result.current.moreRepliesLoading).toBe(false); + }); + expect(result.current.replies[0].children.map(c => c.id)).toEqual([3002, 3001]); + }); + }); + it('keeps an Algolia server error as an error without asking Firebase', async () => { server.use( http.get(`${ALGOLIA_API}/items/:id`, () => new HttpResponse(null, { status: 500 })), diff --git a/src/hooks/useCommentDetail.ts b/src/hooks/useCommentDetail.ts index 77e8564..7aa7cca 100644 --- a/src/hooks/useCommentDetail.ts +++ b/src/hooks/useCommentDetail.ts @@ -6,6 +6,11 @@ function countComments(comments: Comment[]): number { return comments.reduce((count, comment) => count + 1 + countComments(comment.children), 0); } +function orderByKids(replies: Comment[], kids: number[]): Comment[] { + const rank = new Map(kids.map((id, i) => [id, i])); + return [...replies].sort((a, b) => (rank.get(a.id) ?? kids.length) - (rank.get(b.id) ?? kids.length)); +} + interface CommentData { id: number; author: string; @@ -86,13 +91,26 @@ export function useCommentDetail( setMoreRepliesLoading(!!item.story_id); setLoading(false); + // The item tree has replies in creation order. HN's order for the ones + // shown comes from the comment's Firebase item, sooner than the story's + // comments below, which order the rest. + if ((item.children?.length ?? 0) > 1) { + void fetchFirebaseItem(item.id, signal).then( + ({ kids }) => { + if (!signal.aborted && kids) setReplies(shown => orderByKids(shown, kids)); + }, + () => { /* creation order stays */ }, + ); + } + // Algolia's item tree leaves out flagged and deleted replies along with - // the replies under them. Those fill in once the story's comments are read. + // the replies under them. Those fill in, and nested replies take HN's + // order, once the story's comments are read. if (item.story_id) { void fetchCommentReplies(item, signal).then( all => { if (signal.aborted) return; - setReplies(shown => (countComments(all) > countComments(shown) ? all : shown)); + setReplies(shown => (countComments(all) >= countComments(shown) ? all : shown)); setMoreRepliesLoading(false); }, () => { diff --git a/src/utils/sanitize.test.ts b/src/utils/sanitize.test.ts index 39e9113..939f878 100644 --- a/src/utils/sanitize.test.ts +++ b/src/utils/sanitize.test.ts @@ -284,6 +284,17 @@ describe('sanitizeHtml', () => { expect(result).toContain('href="https://example.com"'); }); + it('keeps balanced parentheses in an auto-linked URL', () => { + const result = sanitizeHtml('See https://en.wikipedia.org/wiki/Foil_(narrative) for more'); + expect(result).toContain('href="https://en.wikipedia.org/wiki/Foil_(narrative)"'); + }); + + it('excludes the parenthesis around a URL that has its own pair', () => { + const result = sanitizeHtml('(see https://en.wikipedia.org/wiki/Foil_(narrative)).'); + expect(result).toContain('href="https://en.wikipedia.org/wiki/Foil_(narrative)"'); + expect(result).toContain('Foil_(narrative)).'); + }); + it('excludes trailing semicolon from auto-linked URL', () => { const result = sanitizeHtml('url: https://example.com;'); expect(result).toContain('href="https://example.com"'); diff --git a/src/utils/sanitize.ts b/src/utils/sanitize.ts index d959293..4f93abe 100644 --- a/src/utils/sanitize.ts +++ b/src/utils/sanitize.ts @@ -307,11 +307,12 @@ DOMPurify.addHook('afterSanitizeAttributes', (node) => { // Match URLs and emails in a single pass (module-level to avoid // recompilation). The URL branch ends with a character-class that // excludes common trailing punctuation so "Visit https://x.com." -// links only "https://x.com". +// links only "https://x.com". Parentheses count only in balanced pairs, +// so "(see https://x.com/Foo_(bar))" links "https://x.com/Foo_(bar)". // The email branch requires alphanumeric segments separated by // dots/special chars — rejecting leading/trailing/consecutive dots // and bare-special-char local parts (e.g. `.@`, `..@`, `%@`). -const LINKABLE = /(https?:\/\/[^\s<>]*[^\s<>.,;:!?'")\]}>]|[a-zA-Z0-9]+(?:[._%+-][a-zA-Z0-9]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,})/g; +const LINKABLE = /(https?:\/\/(?:[^\s<>()]|\([^\s<>()]*\))*(?:[^\s<>.,;:!?'"()\]}>]|\([^\s<>()]*\))|[a-zA-Z0-9]+(?:[._%+-][a-zA-Z0-9]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,})/g; function autoLinkUrls(html: string): string { if (typeof document === 'undefined') return html;