From 44b2dd99521ba698ae40d1bff8bf5d06ba08911c Mon Sep 17 00:00:00 2001
From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Date: Tue, 6 Oct 2026 14:04:20 +0000
Subject: [PATCH] feature: React item details and recursive comments with poll
results, tests and e2e (migration phase 4)
Co-Authored-By: Vibha Seshadri
---
react/e2e/fixtures/item-details.ts | 53 ++++
react/e2e/item-details.spec.ts | 96 +++++++
react/src/item-details/Comment.scss | 80 ++++++
react/src/item-details/Comment.test.tsx | 106 ++++++++
react/src/item-details/Comment.tsx | 57 ++++
react/src/item-details/ItemDetails.scss | 146 ++++++++++
react/src/item-details/ItemDetails.test.tsx | 283 ++++++++++++++++++++
react/src/item-details/ItemDetails.tsx | 163 ++++++++++-
8 files changed, 980 insertions(+), 4 deletions(-)
create mode 100644 react/e2e/fixtures/item-details.ts
create mode 100644 react/e2e/item-details.spec.ts
create mode 100644 react/src/item-details/Comment.scss
create mode 100644 react/src/item-details/Comment.test.tsx
create mode 100644 react/src/item-details/Comment.tsx
create mode 100644 react/src/item-details/ItemDetails.scss
create mode 100644 react/src/item-details/ItemDetails.test.tsx
diff --git a/react/e2e/fixtures/item-details.ts b/react/e2e/fixtures/item-details.ts
new file mode 100644
index 000000000..c7789938d
--- /dev/null
+++ b/react/e2e/fixtures/item-details.ts
@@ -0,0 +1,53 @@
+import type { Comment, PollResult, Story } from '../../src/shared/models';
+
+function comment(id: number, level: number, user: string, content: string, comments: Comment[] = []): Comment {
+ return { id, level, user, time: 1700000000, time_ago: `${level + 1} hours ago`, content, comments };
+}
+
+export const story: Story = {
+ id: 1001,
+ title: 'Mocked story with comments',
+ points: 256,
+ user: 'pg',
+ time: 1700000000,
+ time_ago: '5 hours ago',
+ type: 'link',
+ url: 'https://example.com/article',
+ domain: 'example.com',
+ content: '',
+ comments_count: 4,
+ comments: [
+ comment(2001, 0, 'alice', 'Top-level comment
', [
+ comment(2002, 1, 'bob', 'First reply
', [comment(2003, 2, 'carol', 'Deeply nested reply
')]),
+ ]),
+ { ...comment(2004, 0, '', ''), deleted: true },
+ comment(2005, 0, 'dave', 'Second top-level link
'),
+ ],
+};
+
+export const poll: Story = {
+ id: 3001,
+ title: 'Mocked poll: tabs or spaces?',
+ points: 80,
+ user: 'pollster',
+ time: 1700000000,
+ time_ago: '1 day ago',
+ type: 'poll',
+ url: 'item?id=3001',
+ content: 'Cast your vote.
',
+ comments_count: 1,
+ comments: [comment(4001, 0, 'eve', 'Spaces, obviously.
')],
+ poll: [
+ { points: 0, content: '' },
+ { points: 0, content: '' },
+ ],
+};
+
+export const pollOptions: Record = {
+ 3002: { points: 30, content: 'Tabs
' },
+ 3003: { points: 10, content: 'Spaces
' },
+};
+
+export const feed: Story[] = [{ ...story, comments: [] }];
+
+export const items: Record = { [story.id]: story, [poll.id]: poll, ...pollOptions };
diff --git a/react/e2e/item-details.spec.ts b/react/e2e/item-details.spec.ts
new file mode 100644
index 000000000..25715ee77
--- /dev/null
+++ b/react/e2e/item-details.spec.ts
@@ -0,0 +1,96 @@
+import { expect, test } from '@playwright/test';
+import { mockHnApi } from './support/mock-api';
+import { feed, items, poll, story } from './fixtures/item-details';
+
+function itemHandler(url: URL) {
+ const id = Number(url.pathname.split('/').pop());
+ return items[id] ?? {};
+}
+
+test.describe('item details', () => {
+ test('opens a story from the feed and shows its comment tree', async ({ page }) => {
+ await mockHnApi(page, { '/news': () => feed, '/item/': itemHandler });
+ await page.goto('/news/1');
+ await page.goto(`/item/${story.id}`);
+
+ const details = page.getByTestId('item-details');
+ await expect(details).toHaveAttribute('data-item-id', String(story.id));
+ const header = details.locator('.laptop');
+ await expect(header.getByRole('link', { name: story.title })).toHaveAttribute('href', story.url!);
+ await expect(header.locator('.domain')).toHaveText('(example.com)');
+ await expect(header.locator('.subtext')).toContainText('256 points by pg');
+ await expect(header.locator('.subtext')).toContainText('4 comments');
+
+ const list = details.locator('ul.comment-list');
+ await expect(list.locator(':scope > li')).toHaveCount(3);
+ await expect(list.getByText('Deeply nested reply')).toBeVisible();
+ await expect(list.locator('.deleted-meta')).toHaveText(/\[deleted\]\s*\| Comment Deleted/);
+
+ await page.goBack();
+ await expect(page).toHaveURL(/\/news\/1$/);
+ });
+
+ test('collapses and expands comment subtrees with mouse and keyboard', async ({ page }) => {
+ await mockHnApi(page, { '/item/': itemHandler });
+ await page.goto(`/item/${story.id}`);
+
+ const toggle = page.getByRole('button', { name: 'Collapse comment by alice' });
+ await expect(toggle).toHaveText('[-]');
+ await toggle.click();
+ const expand = page.getByRole('button', { name: 'Expand comment by alice' });
+ await expect(expand).toHaveText('[+]');
+ await expect(page.getByText('Top-level comment')).toBeHidden();
+ await expect(page.getByText('Deeply nested reply')).toBeHidden();
+ await expect(page.getByText('Second top-level')).toBeVisible();
+
+ await expand.click();
+ await expect(page.getByText('Deeply nested reply')).toBeVisible();
+
+ const nested = page.getByRole('button', { name: 'Collapse comment by bob' });
+ await nested.focus();
+ await page.keyboard.press('Enter');
+ await expect(page.getByText('First reply')).toBeHidden();
+ await expect(page.getByText('Top-level comment')).toBeVisible();
+ await page.keyboard.press('Space');
+ await expect(page.getByText('First reply')).toBeVisible();
+ });
+
+ test('renders poll results with proportional bars', async ({ page }) => {
+ await mockHnApi(page, { '/item/': itemHandler });
+ await page.goto(`/item/${poll.id}`);
+
+ const options = page.locator('.pollContent');
+ await expect(options).toHaveCount(2);
+ await expect(options.nth(0)).toContainText('Tabs');
+ await expect(options.nth(0).locator('.subtext')).toHaveText('30 points');
+ await expect(options.nth(1)).toContainText('Spaces');
+ const widths = await options
+ .locator('.pollBar')
+ .evaluateAll((bars) => bars.map((bar) => (bar as HTMLElement).style.width));
+ expect(widths).toEqual(['75%', '25%']);
+ await expect(page.locator('.laptop').getByRole('link', { name: poll.title })).toHaveAttribute(
+ 'href',
+ `/item/${poll.id}`
+ );
+ await expect(page.locator('p.subject')).toHaveText('Cast your vote.');
+ });
+
+ test('mobile back button returns to the previous page', async ({ page }) => {
+ await page.setViewportSize({ width: 375, height: 740 });
+ await mockHnApi(page, { '/news': () => feed, '/item/': itemHandler });
+ await page.goto('/news/1');
+ await page.goto(`/item/${story.id}`);
+ const back = page.getByRole('button', { name: 'Back' });
+ await expect(back).toBeVisible();
+ await expect(page.locator('.laptop')).toBeHidden();
+ await back.click();
+ await expect(page).toHaveURL(/\/news\/1$/);
+ });
+
+ test('shows an error when the API fails', async ({ page }) => {
+ await mockHnApi(page, {});
+ await page.goto('/item/999');
+ await expect(page.getByRole('alert')).toContainText('Could not load item comments.');
+ await expect(page.getByTestId('item-details')).toHaveAttribute('data-item-id', '999');
+ });
+});
diff --git a/react/src/item-details/Comment.scss b/react/src/item-details/Comment.scss
new file mode 100644
index 000000000..73926a4bb
--- /dev/null
+++ b/react/src/item-details/Comment.scss
@@ -0,0 +1,80 @@
+@use '../styles/media' as *;
+
+.comment {
+ a {
+ font-weight: bold;
+ text-decoration: none;
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+
+ .meta {
+ font-size: 13px;
+ color: #696969;
+ font-weight: bold;
+ letter-spacing: 0.5px;
+ margin-bottom: 8px;
+ a {
+ text-decoration: none;
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+ .time {
+ padding-left: 5px;
+ }
+
+ @media #{$mobile-only} {
+ font-size: 14px;
+ margin-bottom: 10px;
+ .time {
+ padding: 0;
+ float: right;
+ }
+ }
+ }
+
+ .meta-collapse {
+ margin-bottom: 20px;
+ }
+
+ .deleted-meta {
+ font-size: 12px;
+ font-weight: bold;
+ letter-spacing: 0.5px;
+ margin: 30px 0;
+ a {
+ text-decoration: none;
+ }
+ }
+
+ .collapse {
+ font-size: 13px;
+ letter-spacing: 2px;
+ cursor: pointer;
+ }
+
+ .comment-tree {
+ margin-left: 24px;
+
+ @media #{$tablet-only} {
+ margin-left: 8px;
+ }
+ }
+
+ .comment-text {
+ font-size: 15px;
+ margin-top: 0;
+ margin-bottom: 20px;
+ word-wrap: break-word;
+ line-height: 1.5em;
+ }
+
+ .subtree {
+ margin-left: 0;
+ padding: 0;
+ list-style-type: none;
+ }
+}
diff --git a/react/src/item-details/Comment.test.tsx b/react/src/item-details/Comment.test.tsx
new file mode 100644
index 000000000..055e8ac30
--- /dev/null
+++ b/react/src/item-details/Comment.test.tsx
@@ -0,0 +1,106 @@
+import { fireEvent, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { Comment as CommentModel } from '../shared/models';
+import { renderWithProviders } from '../test/renderWithProviders';
+import { Comment } from './Comment';
+
+function makeComment(overrides: Partial = {}): CommentModel {
+ return {
+ id: 1,
+ level: 0,
+ user: 'alice',
+ time: 0,
+ time_ago: '2 hours ago',
+ content: 'Top level
',
+ comments: [],
+ ...overrides,
+ };
+}
+
+const tree = makeComment({
+ comments: [
+ makeComment({
+ id: 2,
+ level: 1,
+ user: 'bob',
+ content: 'Reply
',
+ comments: [makeComment({ id: 3, level: 2, user: 'carol', content: 'Nested reply
' })],
+ }),
+ makeComment({ id: 4, level: 1, deleted: true, user: '', content: '' }),
+ ],
+});
+
+describe('Comment', () => {
+ it('renders meta, sanitized content and a link to the user', () => {
+ const { container } = renderWithProviders(
+ Hi there
' })} />
+ );
+ expect(container.querySelector('.meta')).not.toHaveClass('meta-collapse');
+ expect(screen.getByRole('link', { name: 'alice' })).toHaveAttribute('href', '/user/alice');
+ expect(container.querySelector('.time')).toHaveTextContent('2 hours ago');
+ const text = container.querySelector('p.comment-text')!;
+ expect(text.querySelector('i')).toHaveTextContent('there');
+ expect(text.innerHTML).not.toMatch(/script/);
+ });
+
+ it('renders a nested comment tree', () => {
+ const { container } = renderWithProviders();
+ expect(container.querySelectorAll('.comment')).toHaveLength(4);
+ const nested = container.querySelector('.subtree .subtree')!;
+ expect(within(nested as HTMLElement).getByText('Nested reply')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'carol' })).toHaveAttribute('href', '/user/carol');
+ });
+
+ it('renders deleted comments', () => {
+ const { container } = renderWithProviders();
+ expect(container.querySelector('.deleted-meta')).toHaveTextContent('[deleted] | Comment Deleted');
+ expect(container.querySelector('.meta')).toBeNull();
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ });
+
+ it('collapses and expands on click, keeping the subtree mounted', async () => {
+ const user = userEvent.setup();
+ const { container } = renderWithProviders();
+ const toggle = screen.getByRole('button', { name: 'Collapse comment by alice' });
+ expect(toggle).toHaveTextContent('[-]');
+ expect(toggle).toHaveAttribute('aria-expanded', 'true');
+
+ await user.click(toggle);
+ expect(toggle).toHaveTextContent('[+]');
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ expect(toggle).toHaveAccessibleName('Expand comment by alice');
+ expect(container.querySelector('.meta')).toHaveClass('meta-collapse');
+ const body = container.querySelector('.comment-tree > div')!;
+ expect(body).not.toBeVisible();
+ expect(body).toHaveAttribute('hidden');
+ expect(body.querySelector('.subtree')).toHaveTextContent('Nested reply');
+
+ await user.click(toggle);
+ expect(toggle).toHaveTextContent('[-]');
+ expect(body).toBeVisible();
+ });
+
+ it('only collapses its own subtree', async () => {
+ const user = userEvent.setup();
+ renderWithProviders();
+ await user.click(screen.getByRole('button', { name: 'Collapse comment by bob' }));
+ expect(screen.getByText('Top level')).toBeVisible();
+ expect(screen.getByText('Reply')).not.toBeVisible();
+ expect(screen.getByRole('button', { name: 'Collapse comment by alice' })).toHaveTextContent('[-]');
+ });
+
+ it('toggles with Enter and Space and ignores other keys', async () => {
+ const user = userEvent.setup();
+ renderWithProviders();
+ const toggle = screen.getByRole('button', { name: 'Collapse comment by alice' });
+ expect(toggle).toHaveAttribute('tabindex', '0');
+
+ toggle.focus();
+ await user.keyboard('{Enter}');
+ expect(toggle).toHaveTextContent('[+]');
+ await user.keyboard(' ');
+ expect(toggle).toHaveTextContent('[-]');
+ fireEvent.keyDown(toggle, { key: 'a' });
+ expect(toggle).toHaveTextContent('[-]');
+ });
+});
diff --git a/react/src/item-details/Comment.tsx b/react/src/item-details/Comment.tsx
new file mode 100644
index 000000000..25bcbc5d7
--- /dev/null
+++ b/react/src/item-details/Comment.tsx
@@ -0,0 +1,57 @@
+import { useState } from 'react';
+import { NavLink } from 'react-router-dom';
+import type { Comment as CommentModel } from '../shared/models';
+import { SafeHtml } from '../shared/components/SafeHtml/SafeHtml';
+import { onActivateKey } from '../shared/utils/a11y';
+import './Comment.scss';
+
+export interface CommentProps {
+ comment: CommentModel;
+}
+
+export function Comment({ comment }: CommentProps) {
+ const [collapse, setCollapse] = useState(false);
+ const toggle = () => setCollapse((value) => !value);
+
+ if (comment.deleted) {
+ return (
+
+
+ [deleted] | Comment Deleted
+
+
+ );
+ }
+
+ return (
+
+
+
+ [{collapse ? '+' : '-'}]
+ {' '}
+ {comment.user}
+ {comment.time_ago}
+
+
+
+
+
+ {comment.comments?.map((subComment) => (
+ -
+
+
+ ))}
+
+
+
+
+ );
+}
diff --git a/react/src/item-details/ItemDetails.scss b/react/src/item-details/ItemDetails.scss
new file mode 100644
index 000000000..8fc75247c
--- /dev/null
+++ b/react/src/item-details/ItemDetails.scss
@@ -0,0 +1,146 @@
+@use '../styles/media' as *;
+
+.item-view.main-content {
+ position: relative;
+ width: 100%;
+ min-height: 100vh;
+ -webkit-transition: opacity 0.2s ease;
+ transition: opacity 0.2s ease;
+ box-sizing: border-box;
+ padding: 8px 0;
+ z-index: 0;
+}
+
+.item-view {
+ .item {
+ box-sizing: border-box;
+ padding: 10px 40px 0 40px;
+ z-index: 0;
+
+ @media #{$tablet-only} {
+ padding: 10px 20px 0 40px;
+ }
+
+ @media #{$mobile-only} {
+ box-sizing: border-box;
+ padding: 110px 15px 0 15px;
+ }
+ }
+
+ .head-margin {
+ margin-bottom: 15px;
+ }
+
+ p {
+ margin: 2px 0;
+ }
+
+ .subject {
+ word-wrap: break-word;
+ margin-top: 20px;
+ }
+
+ a {
+ cursor: pointer;
+ text-decoration: none;
+ }
+
+ .laptop {
+ @media #{$mobile-only} {
+ display: none;
+ }
+ }
+
+ .mobile {
+ @media #{$laptop-only} {
+ display: none;
+ }
+ }
+
+ .title {
+ font-size: 16px;
+ font-family: Verdana, Geneva, sans-serif;
+
+ @media #{$mobile-only} {
+ font-size: 15px;
+ }
+ }
+
+ .title-block {
+ text-align: center;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ overflow: hidden;
+ margin: 0 75px;
+ }
+
+ .back-button {
+ @media #{$mobile-only} {
+ position: absolute;
+ top: 52%;
+ width: 0.6rem;
+ height: 0.6rem;
+ background: transparent;
+ box-shadow: 0 0 0 lightgray;
+ transition: all 200ms ease;
+ left: 4%;
+ transform: translate3d(0, -50%, 0) rotate(-135deg);
+ cursor: pointer;
+ }
+ }
+
+ .subtext {
+ font-size: 12px;
+ font-weight: bold;
+ letter-spacing: 0.5px;
+
+ a:hover {
+ text-decoration: underline;
+ }
+ }
+
+ .domain {
+ letter-spacing: 0.5px;
+ }
+
+ .item-details {
+ padding: 10px;
+ }
+
+ .item-header {
+ padding-bottom: 10px;
+
+ @media #{$mobile-only} {
+ padding: 10px 0 10px 0;
+ position: fixed;
+ width: 100%;
+ left: 0;
+ top: 62px;
+ }
+ }
+
+ .pollResults {
+ margin-bottom: 1em;
+ }
+
+ .pollContent {
+ * {
+ padding-bottom: 0;
+ margin-bottom: -1em;
+ margin-top: 1em;
+ }
+ .pollBar {
+ height: 10px;
+ margin-bottom: 1em;
+ }
+ }
+
+ .comment-list {
+ list-style-type: none;
+ padding: 10px 0;
+ }
+
+ li {
+ display: list-item;
+ }
+}
diff --git a/react/src/item-details/ItemDetails.test.tsx b/react/src/item-details/ItemDetails.test.tsx
new file mode 100644
index 000000000..c0b5483d6
--- /dev/null
+++ b/react/src/item-details/ItemDetails.test.tsx
@@ -0,0 +1,283 @@
+import { act, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { Route, Routes, useNavigate } from 'react-router-dom';
+import type { Story } from '../shared/models';
+import { fetchItemContent } from '../shared/services/hackernewsApi';
+import { renderWithProviders } from '../test/renderWithProviders';
+import ItemDetails from './ItemDetails';
+
+vi.mock('../shared/services/hackernewsApi');
+const mockFetchItemContent = vi.mocked(fetchItemContent);
+
+function makeStory(overrides: Partial & { text?: string } = {}): Story {
+ return {
+ id: 42,
+ title: 'A story',
+ points: 120,
+ user: 'pg',
+ time: 0,
+ time_ago: '3 hours ago',
+ type: 'link',
+ url: 'https://example.com/post',
+ domain: 'example.com',
+ content: '',
+ comments_count: 2,
+ comments: [
+ {
+ id: 100,
+ level: 0,
+ user: 'alice',
+ time: 0,
+ time_ago: '2 hours ago',
+ content: 'First!
',
+ comments: [
+ {
+ id: 101,
+ level: 1,
+ user: 'bob',
+ time: 0,
+ time_ago: '1 hour ago',
+ content: 'Reply
',
+ comments: [],
+ },
+ ],
+ },
+ ],
+ ...overrides,
+ };
+}
+
+function GoTo({ to }: { to: string }) {
+ const navigate = useNavigate();
+ return ;
+}
+
+function renderItem(route = '/item/42') {
+ return renderWithProviders(
+ <>
+
+ } />
+ elsewhere} />
+
+
+ >,
+ { route }
+ );
+}
+
+const laptopHeader = () => screen.getByTestId('laptop-header');
+const mobileHeader = () => document.querySelector('.mobile.item-header') as HTMLElement;
+
+beforeEach(() => {
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+});
+
+describe('ItemDetails', () => {
+ it('shows the loader while loading and scrolls to top on mount', () => {
+ mockFetchItemContent.mockReturnValue(new Promise(() => {}));
+ renderItem();
+ const root = screen.getByTestId('item-details');
+ expect(root).toHaveAttribute('data-item-id', '42');
+ expect(root).toHaveClass('main-content');
+ expect(screen.getByRole('status')).toHaveTextContent('Loading...');
+ expect(window.scrollTo).toHaveBeenCalledWith(0, 0);
+ expect(mockFetchItemContent).toHaveBeenCalledWith(42, expect.any(AbortSignal));
+ });
+
+ it('shows the error message when loading fails', async () => {
+ mockFetchItemContent.mockRejectedValue(new Error('boom'));
+ renderItem();
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load item comments.');
+ expect(screen.queryByRole('status')).not.toBeInTheDocument();
+ expect(screen.getByTestId('item-details')).toHaveAttribute('data-item-id', '42');
+ });
+
+ it('ignores AbortError rejections', async () => {
+ mockFetchItemContent.mockRejectedValue(new DOMException('aborted', 'AbortError'));
+ renderItem();
+ await act(async () => {});
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.getByRole('status')).toBeInTheDocument();
+ });
+
+ it('renders a loaded story with external links, subtext and comments', async () => {
+ mockFetchItemContent.mockResolvedValue(makeStory());
+ const { container } = renderItem();
+ await screen.findAllByText('A story');
+
+ const header = laptopHeader();
+ expect(header).toHaveClass('laptop', 'item-header');
+ expect(header).not.toHaveClass('head-margin');
+ const title = within(header).getByRole('link', { name: 'A story' });
+ expect(title).toHaveAttribute('href', 'https://example.com/post');
+ expect(title).not.toHaveAttribute('target');
+ expect(title).not.toHaveAttribute('rel');
+ expect(header.querySelector('.domain')).toHaveTextContent('(example.com)');
+
+ const subtext = header.querySelector('.subtext')!;
+ expect(subtext).toHaveTextContent('120 points by pg 3 hours ago | 2 comments');
+ expect(within(subtext as HTMLElement).getByRole('link', { name: 'pg' })).toHaveAttribute('href', '/user/pg');
+ expect(within(subtext as HTMLElement).getByRole('link', { name: '2 comments' })).toHaveAttribute(
+ 'href',
+ '/item/42'
+ );
+ expect(subtext.querySelector('.item-details')).not.toBeNull();
+
+ expect(within(mobileHeader()).getByRole('link', { name: 'A story' })).toHaveAttribute(
+ 'href',
+ 'https://example.com/post'
+ );
+ expect(container.querySelector('.pollResults')).toBeNull();
+
+ const list = container.querySelector('ul.comment-list')!;
+ expect(list.children).toHaveLength(1);
+ expect(within(list as HTMLElement).getByText('First!')).toBeInTheDocument();
+ expect(list.querySelector('.subtree')).toHaveTextContent('Reply');
+ });
+
+ it('opens external links in a new tab when the setting is on', async () => {
+ localStorage.setItem('openLinkInNewTab', 'true');
+ mockFetchItemContent.mockResolvedValue(makeStory());
+ renderItem();
+ await screen.findAllByText('A story');
+ for (const link of screen.getAllByRole('link', { name: 'A story' })) {
+ expect(link).toHaveAttribute('target', '_blank');
+ expect(link).toHaveAttribute('rel', 'noopener');
+ }
+ });
+
+ it('uses internal links for stories without an http url and sanitizes content', async () => {
+ localStorage.setItem('openLinkInNewTab', 'true');
+ mockFetchItemContent.mockResolvedValue(
+ makeStory({
+ type: 'ask',
+ url: 'item?id=42',
+ domain: undefined,
+ comments_count: 0,
+ comments: [],
+ text: 'has text',
+ content: 'Ask body bold
',
+ })
+ );
+ const { container } = renderItem();
+ await screen.findAllByText('A story');
+
+ for (const link of screen.getAllByRole('link', { name: 'A story' })) {
+ expect(link).toHaveAttribute('href', '/item/42');
+ expect(link).not.toHaveAttribute('target');
+ expect(link).toHaveClass('title', 'active');
+ }
+ const header = laptopHeader();
+ expect(header).not.toHaveClass('item-header');
+ expect(header).toHaveClass('head-margin');
+ expect(header.querySelector('.domain')).toBeNull();
+ expect(header.querySelector('.subtext')).toHaveTextContent('| discuss');
+
+ const subject = container.querySelector('p.subject')!;
+ expect(subject.querySelector('b')).toHaveTextContent('bold');
+ expect(subject.innerHTML).not.toMatch(/script|onerror/);
+ expect(container.querySelector('ul.comment-list')).toBeEmptyDOMElement();
+ });
+
+ it('renders job items without points, user or comment count', async () => {
+ mockFetchItemContent.mockResolvedValue(
+ makeStory({ type: 'job', comments_count: 0, comments: [], points: 0, user: '' })
+ );
+ renderItem();
+ await screen.findAllByText('A story');
+ const header = laptopHeader();
+ expect(header).toHaveClass('item-header');
+ const subtext = header.querySelector('.subtext')!;
+ expect(subtext).toHaveTextContent(/^\s*3 hours ago\s*$/);
+ expect(subtext).not.toHaveTextContent('points');
+ expect(subtext.querySelector('.item-details')).toBeNull();
+ });
+
+ it('treats a missing comment count as no comments', async () => {
+ mockFetchItemContent.mockResolvedValue(makeStory({ comments_count: undefined, comments: undefined }));
+ const { container } = renderItem();
+ await screen.findAllByText('A story');
+ expect(laptopHeader()).not.toHaveClass('item-header');
+ expect(laptopHeader().querySelector('.subtext')).toHaveTextContent('| discuss');
+ expect(container.querySelector('ul.comment-list')).toBeEmptyDOMElement();
+ });
+
+ it('renders poll results with proportional bars', async () => {
+ mockFetchItemContent.mockResolvedValue(
+ makeStory({
+ type: 'poll',
+ url: 'item?id=42',
+ poll: [
+ { content: 'Yes
', points: 30 },
+ { content: 'No', points: 10 },
+ ],
+ poll_votes_count: 40,
+ })
+ );
+ renderItem();
+ const options = await screen.findAllByTestId('poll-option');
+ expect(options).toHaveLength(2);
+ expect(options[0]).toHaveTextContent('Yes');
+ expect(options[0].innerHTML).not.toMatch(/script/);
+ expect(options[0].querySelector('.subtext')).toHaveTextContent('30 points');
+ expect(options[0].querySelector('.pollBar')!.style.width).toBe('75%');
+ expect(options[1].querySelector('.subtext')).toHaveTextContent('10 points');
+ expect(options[1].querySelector('.pollBar')!.style.width).toBe('25%');
+ });
+
+ it('uses a zero-width bar when a poll has no votes', async () => {
+ mockFetchItemContent.mockResolvedValue(
+ makeStory({ type: 'poll', poll: [{ content: 'Maybe', points: 0 }], poll_votes_count: 0 })
+ );
+ renderItem();
+ const [option] = await screen.findAllByTestId('poll-option');
+ expect(option.querySelector('.pollBar')!.style.width).toBe('0%');
+ });
+
+ it('goes back with the mobile back button (click and keyboard)', async () => {
+ const user = userEvent.setup();
+ mockFetchItemContent.mockResolvedValue(makeStory());
+ renderWithProviders(
+
+ } />
+ } />
+ ,
+ { route: '/news/1' }
+ );
+ await user.click(screen.getByRole('button', { name: 'go /item/42' }));
+ await screen.findAllByText('A story');
+ await user.click(screen.getByRole('button', { name: 'Back' }));
+ expect(screen.getByTestId('location')).toHaveTextContent('/news/1');
+
+ await user.click(screen.getByRole('button', { name: 'go /item/42' }));
+ await screen.findAllByText('A story');
+ screen.getByRole('button', { name: 'Back' }).focus();
+ await user.keyboard('{Enter}');
+ expect(screen.getByTestId('location')).toHaveTextContent('/news/1');
+ });
+
+ it('aborts and refetches when the id changes', async () => {
+ const user = userEvent.setup();
+ mockFetchItemContent.mockImplementation((id) =>
+ Promise.resolve(makeStory({ id, title: `Story ${id}`, comments: [] }))
+ );
+ renderItem('/item/42');
+ await screen.findAllByText('Story 42');
+ const firstSignal = mockFetchItemContent.mock.calls[0][1]!;
+
+ await user.click(screen.getByRole('button', { name: 'go /item/43' }));
+ expect(screen.getByTestId('item-details')).toHaveAttribute('data-item-id', '43');
+ await screen.findAllByText('Story 43');
+ expect(screen.queryByText('Story 42')).not.toBeInTheDocument();
+ expect(firstSignal.aborted).toBe(true);
+ expect(mockFetchItemContent).toHaveBeenLastCalledWith(43, expect.any(AbortSignal));
+ });
+
+ it('aborts the request on unmount', async () => {
+ mockFetchItemContent.mockReturnValue(new Promise(() => {}));
+ const { unmount } = renderItem();
+ const signal = mockFetchItemContent.mock.calls[0][1]!;
+ unmount();
+ await waitFor(() => expect(signal.aborted).toBe(true));
+ });
+});
diff --git a/react/src/item-details/ItemDetails.tsx b/react/src/item-details/ItemDetails.tsx
index 818ef0804..711d02218 100644
--- a/react/src/item-details/ItemDetails.tsx
+++ b/react/src/item-details/ItemDetails.tsx
@@ -1,11 +1,166 @@
-import { useParams } from 'react-router-dom';
+import { useEffect, useState } from 'react';
+import { NavLink, useNavigate, useParams } from 'react-router-dom';
+import type { Story } from '../shared/models';
+import type { Settings } from '../shared/models';
+import { fetchItemContent } from '../shared/services/hackernewsApi';
+import { useSettings } from '../shared/services/useSettings';
+import { formatCommentCount } from '../shared/utils/comment';
+import { onActivateKey } from '../shared/utils/a11y';
+import { Loader } from '../shared/components/Loader/Loader';
+import { ErrorMessage } from '../shared/components/ErrorMessage/ErrorMessage';
+import { SafeHtml } from '../shared/components/SafeHtml/SafeHtml';
+import { Comment } from './Comment';
+import './ItemDetails.scss';
+
+/** Angular's template also reads `item.text` (not part of the shared Story model). */
+type ItemDetailsStory = Story & { text?: string };
+
+interface ItemState {
+ id: string | undefined;
+ item?: ItemDetailsStory;
+ error?: string;
+}
+
+const ERROR_MESSAGE = 'Could not load item comments.';
+
+function hasUrl(item: Story): boolean {
+ return item.url?.indexOf('http') === 0;
+}
+
+function pollBarWidth(points: number, total: number | undefined): string {
+ return total ? `${(points / total) * 100}%` : '0%';
+}
+
+function TitleLink({ item, settings }: { item: Story; settings: Settings }) {
+ if (hasUrl(item)) {
+ return (
+
+ {item.title}
+
+ );
+ }
+ return (
+
+ {item.title}
+
+ );
+}
-// Placeholder route target; item details & comments are implemented in migration phase 4.
export default function ItemDetails() {
const { id } = useParams();
+ const navigate = useNavigate();
+ const { settings } = useSettings();
+ const [state, setState] = useState({ id });
+
+ useEffect(() => {
+ window.scrollTo(0, 0);
+ }, []);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ fetchItemContent(Number(id), controller.signal).then(
+ (item) => setState({ id, item }),
+ (error: unknown) => {
+ if (error instanceof DOMException && error.name === 'AbortError') {
+ return;
+ }
+ setState({ id, error: ERROR_MESSAGE });
+ }
+ );
+ return () => controller.abort();
+ }, [id]);
+
+ const current = state.id === id ? state : { id };
+ const { item, error } = current;
+ const goBack = () => navigate(-1);
+
return (
-
-
Item {id}
+
+ {!item && !error &&
}
+ {!item && error &&
}
+
+ {item && (
+
+
+
0 || item.type === 'job') && 'item-header',
+ item.text && 'head-margin',
+ ]
+ .filter(Boolean)
+ .join(' ')}
+ data-testid="laptop-header"
+ >
+
+
+ {hasUrl(item) && item.domain && (
+ <>
+ {' '}
+ ({item.domain})
+ >
+ )}
+
+
+ {item.type !== 'job' && (
+
+ {item.points} points by {item.user}
+
+ )}{' '}
+
+ {item.time_ago}
+ {item.type !== 'job' && (
+
+ {' | '}
+
+ {formatCommentCount(item.comments_count ?? 0)}
+
+
+ )}
+
+
+
+ {item.type === 'poll' && (
+
+ {item.poll?.map((pollResult, i) => (
+
+
+
{pollResult.points} points
+
+
+ ))}
+
+ )}
+
+
+ {item.comments?.map((comment) => (
+ -
+
+
+ ))}
+
+
+ )}
);
}