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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions react/e2e/fixtures/item-details.ts
Original file line number Diff line number Diff line change
@@ -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', '<p>Top-level comment</p>', [
comment(2002, 1, 'bob', '<p>First reply</p>', [comment(2003, 2, 'carol', '<p>Deeply nested reply</p>')]),
]),
{ ...comment(2004, 0, '', ''), deleted: true },
comment(2005, 0, 'dave', '<p>Second top-level <a href="https://example.org">link</a></p>'),
],
};

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: '<p>Cast your vote.</p>',
comments_count: 1,
comments: [comment(4001, 0, 'eve', '<p>Spaces, obviously.</p>')],
poll: [
{ points: 0, content: '' },
{ points: 0, content: '' },
],
};

export const pollOptions: Record<number, PollResult> = {
3002: { points: 30, content: '<p>Tabs</p>' },
3003: { points: 10, content: '<p>Spaces</p>' },
};

export const feed: Story[] = [{ ...story, comments: [] }];

export const items: Record<number, unknown> = { [story.id]: story, [poll.id]: poll, ...pollOptions };
96 changes: 96 additions & 0 deletions react/e2e/item-details.spec.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
80 changes: 80 additions & 0 deletions react/src/item-details/Comment.scss
Original file line number Diff line number Diff line change
@@ -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;
}
}
106 changes: 106 additions & 0 deletions react/src/item-details/Comment.test.tsx
Original file line number Diff line number Diff line change
@@ -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> = {}): CommentModel {
return {
id: 1,
level: 0,
user: 'alice',
time: 0,
time_ago: '2 hours ago',
content: '<p>Top level</p>',
comments: [],
...overrides,
};
}

const tree = makeComment({
comments: [
makeComment({
id: 2,
level: 1,
user: 'bob',
content: '<p>Reply</p>',
comments: [makeComment({ id: 3, level: 2, user: 'carol', content: '<p>Nested reply</p>' })],
}),
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(
<Comment comment={makeComment({ content: '<p>Hi <i>there</i></p><script>alert(1)</script>' })} />
);
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(<Comment comment={tree} />);
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(<Comment comment={makeComment({ deleted: true })} />);
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(<Comment comment={tree} />);
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(<Comment comment={tree} />);
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(<Comment comment={tree} />);
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('[-]');
});
});
57 changes: 57 additions & 0 deletions react/src/item-details/Comment.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="comment">
<div className="deleted-meta">
<span className="collapse">[deleted]</span> | Comment Deleted
</div>
</div>
);
}

return (
<div className="comment">
<div className={collapse ? 'meta meta-collapse' : 'meta'}>
<span
className="collapse"
role="button"
tabIndex={0}
aria-expanded={!collapse}
aria-label={`${collapse ? 'Expand' : 'Collapse'} comment by ${comment.user}`}
onClick={toggle}
onKeyDown={onActivateKey(toggle)}
>
[{collapse ? '+' : '-'}]
</span>{' '}
<NavLink to={`/user/${comment.user}`}>{comment.user}</NavLink>
<span className="time">{comment.time_ago}</span>
</div>
<div className="comment-tree">
<div hidden={collapse}>
<SafeHtml as="p" className="comment-text" html={comment.content} />
<ul className="subtree">
{comment.comments?.map((subComment) => (
<li key={subComment.id}>
<Comment comment={subComment} />
</li>
))}
</ul>
</div>
</div>
</div>
);
}
Loading
Loading