diff --git a/react/e2e/fixtures/user.ts b/react/e2e/fixtures/user.ts new file mode 100644 index 000000000..a405947a6 --- /dev/null +++ b/react/e2e/fixtures/user.ts @@ -0,0 +1,41 @@ +/** Shapes match the live node-hnapi `/user/` and feed responses (the user endpoint is mocked; it 404s live). */ +export const USERS = { + pg: { + id: 'pg', + created_time: 1160418092, + created: '20 years ago', + karma: 157316, + avg: null, + about: 'Bug fixer. paulgraham.com', + }, + dang: { + id: 'dang', + created_time: 1191529364, + created: '19 years ago', + karma: 30000, + avg: null, + }, + dhouston: { + id: 'dhouston', + created_time: 1175714200, + created: '19 years ago', + karma: 8642, + avg: null, + about: 'Founder of Dropbox.', + }, +} as const; + +export const NEWS_FEED = [ + { + id: 8863, + title: 'My YC app: Dropbox - Throw away your USB drive', + points: 104, + user: 'dhouston', + time: 1175714200, + time_ago: '19 years ago', + comments_count: 71, + type: 'link', + url: 'http://www.getdropbox.com/u/2/screencast.html', + domain: 'getdropbox.com', + }, +]; diff --git a/react/e2e/user.spec.ts b/react/e2e/user.spec.ts new file mode 100644 index 000000000..c259e2b48 --- /dev/null +++ b/react/e2e/user.spec.ts @@ -0,0 +1,90 @@ +import { expect, test } from '@playwright/test'; +import type { Page } from '@playwright/test'; +import { mockHnApi } from './support/mock-api'; +import { NEWS_FEED, USERS } from './fixtures/user'; + +async function mockUsers(page: Page) { + await mockHnApi(page, { + '/news': () => NEWS_FEED, + '/user/': (url) => { + const id = decodeURIComponent(url.pathname.slice('/user/'.length)); + return USERS[id as keyof typeof USERS] ?? { error: 'unknown user' }; + }, + }); +} + +test.describe('user profile', () => { + test('/user/:id renders id, karma, created and sanitized about', async ({ page }) => { + await mockUsers(page); + await page.goto('/user/pg'); + const profile = page.getByTestId('user-profile'); + await expect(profile).toHaveAttribute('data-user-id', 'pg'); + await expect(profile.locator('.main-details .name')).toHaveText('pg'); + await expect(profile.locator('.main-details .right')).toHaveText('157316 ★'); + await expect(profile.locator('.main-details .age')).toHaveText('Created 20 years ago'); + const about = profile.locator('.other-details p'); + await expect(about).toContainText('Bug fixer.'); + await expect(about.getByRole('link', { name: 'paulgraham.com' })).toHaveAttribute( + 'href', + 'https://paulgraham.com' + ); + await expect(about.locator('script')).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as { __xss?: boolean }).__xss)).toBeUndefined(); + // Desktop viewport hides the mobile header. + await expect(profile.locator('.item-header')).toBeHidden(); + }); + + test('omits the about section when the user has none', async ({ page }) => { + await mockUsers(page); + await page.goto('/user/dang'); + await expect(page.locator('.main-details .right')).toHaveText('30000 ★'); + await expect(page.locator('.other-details')).toHaveCount(0); + }); + + test('shows the error state when the user cannot be loaded', async ({ page }) => { + await mockHnApi(page, {}); + await page.goto('/user/nobody'); + await expect(page.getByRole('alert')).toContainText('Could not load user nobody.'); + await expect(page.getByTestId('user-profile')).toHaveAttribute('data-user-id', 'nobody'); + }); + + test('client-side navigation from the feed to a user and back', async ({ page }) => { + await page.setViewportSize({ width: 375, height: 812 }); + await mockUsers(page); + await page.goto('/news/1'); + await expect(page.getByTestId('feed')).toBeVisible(); + + const userLink = page.locator('a[href="/user/dhouston"]'); + // The feed list lands in a parallel phase; fall back to an in-app history navigation until it renders user links. + if ((await userLink.count()) > 0) { + await userLink.first().click(); + } else { + await page.evaluate(() => { + window.history.pushState({}, '', '/user/pg'); + window.dispatchEvent(new PopStateEvent('popstate')); + }); + } + const profile = page.getByTestId('user-profile'); + await expect(profile.locator('.main-details .name')).toBeVisible(); + const id = await profile.getAttribute('data-user-id'); + await expect(profile.locator('.item-header')).toContainText(`Profile: ${id}`); + + const back = page.getByRole('button', { name: 'Go back' }); + await back.focus(); + await page.keyboard.press('Enter'); + await expect(page).toHaveURL(/\/news\/1$/); + await expect(page.getByTestId('feed')).toBeVisible(); + }); + + test('changing the user id in-app refetches the profile', async ({ page }) => { + await mockUsers(page); + await page.goto('/user/pg'); + await expect(page.locator('.main-details .name')).toHaveText('pg'); + await page.evaluate(() => { + window.history.pushState({}, '', '/user/dang'); + window.dispatchEvent(new PopStateEvent('popstate')); + }); + await expect(page.locator('.main-details .name')).toHaveText('dang'); + await expect(page.locator('.main-details .right')).toHaveText('30000 ★'); + }); +}); diff --git a/react/src/user/UserProfile.scss b/react/src/user/UserProfile.scss new file mode 100644 index 000000000..d3339be18 --- /dev/null +++ b/react/src/user/UserProfile.scss @@ -0,0 +1,85 @@ +@use '../styles/media' as *; + +.profile { + padding: 30px; + + pre { + white-space: pre-wrap; + } + + @media #{$mobile-only} { + padding: 110px 15px 0 15px; + + .title-block { + font-size: 15px; + text-align: center; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + margin: 0 75px; + } + + .back-button { + 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; + } + + .item-header { + background-color: #fff; + padding: 10px 0 10px 0; + position: fixed; + width: 100%; + left: 0; + top: 62px; + height: 20px; + } + } + + @media #{$laptop-only} { + .mobile { + display: none; + } + } + + .main-details { + .name { + font-weight: bold; + font-size: 32px; + letter-spacing: 2px; + } + + .age { + font-weight: bold; + color: #696969; + padding-bottom: 0; + } + + .right { + float: right; + font-weight: bold; + font-size: 32px; + letter-spacing: 2px; + } + + @media #{$mobile-only} { + margin-top: 20px; + + .name, + .right { + font-size: 18px; + } + } + } + + .other-details { + word-wrap: break-word; + } +} diff --git a/react/src/user/UserProfile.test.tsx b/react/src/user/UserProfile.test.tsx new file mode 100644 index 000000000..d7ddee7af --- /dev/null +++ b/react/src/user/UserProfile.test.tsx @@ -0,0 +1,173 @@ +import { act, fireEvent, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { Link, Route, Routes } from 'react-router-dom'; +import { vi } from 'vitest'; +import type { User } from '../shared/models'; +import { fetchUser } from '../shared/services/hackernewsApi'; +import { renderWithProviders } from '../test/renderWithProviders'; +import UserProfile from './UserProfile'; + +vi.mock('../shared/services/hackernewsApi'); + +const mockFetchUser = vi.mocked(fetchUser); + +const pg: User = { + id: 'pg', + created: '19 years ago', + karma: 157316, + avg: 4.2, + about: 'Bug fixer. paulgraham.com', +}; + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +function renderProfile(route = '/user/pg') { + return renderWithProviders( + <> + + } /> + open pg} /> + + dang + , + { route } + ); +} + +describe('UserProfile', () => { + it('shows the loader while loading and keeps the root data attributes', () => { + mockFetchUser.mockReturnValue(new Promise(() => {})); + renderProfile(); + expect(screen.getByRole('status')).toHaveTextContent('Loading...'); + const root = screen.getByTestId('user-profile'); + expect(root).toHaveAttribute('data-user-id', 'pg'); + expect(mockFetchUser).toHaveBeenCalledWith('pg', expect.any(AbortSignal)); + expect(root.querySelector('.profile')).toBeNull(); + }); + + it('renders the loaded profile with about', async () => { + mockFetchUser.mockResolvedValue(pg); + renderProfile(); + const root = screen.getByTestId('user-profile'); + await waitFor(() => expect(root.querySelector('.profile')).not.toBeNull()); + expect(screen.queryByRole('status')).toBeNull(); + expect(root.querySelector('.item-header.mobile .title-block')).toHaveTextContent('Profile: pg'); + expect(root.querySelector('.main-details .name')).toHaveTextContent('pg'); + expect(root.querySelector('.main-details .right')).toHaveTextContent('157316 ★'); + expect(root.querySelector('.main-details .age')).toHaveTextContent('Created 19 years ago'); + const about = root.querySelector('.other-details p')!; + expect(about).toHaveTextContent('Bug fixer. paulgraham.com'); + expect(about.querySelector('a')).toHaveAttribute('href', 'https://paulgraham.com'); + expect(root).toHaveAttribute('data-user-id', 'pg'); + }); + + it('omits other-details when the user has no about', async () => { + mockFetchUser.mockResolvedValue({ ...pg, about: undefined }); + renderProfile(); + await screen.findByText('Created 19 years ago'); + expect(screen.getByTestId('user-profile').querySelector('.other-details')).toBeNull(); + }); + + it('sanitizes the about html', async () => { + mockFetchUser.mockResolvedValue({ + ...pg, + about: 'hi', + }); + renderProfile(); + await screen.findByText('hi'); + const about = screen.getByTestId('user-profile').querySelector('.other-details p')!; + expect(about.innerHTML).not.toMatch(/script|onerror/); + }); + + it('shows the error message when loading fails', async () => { + mockFetchUser.mockRejectedValue(new Error('HN API request failed with status 404')); + renderProfile(); + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('Could not load user pg.'); + expect(screen.queryByRole('status')).toBeNull(); + expect(screen.getByTestId('user-profile')).toHaveAttribute('data-user-id', 'pg'); + }); + + it('ignores AbortError rejections', async () => { + mockFetchUser.mockRejectedValue(new DOMException('aborted', 'AbortError')); + renderProfile(); + await act(async () => {}); + expect(screen.queryByRole('alert')).toBeNull(); + expect(screen.getByRole('status')).toBeInTheDocument(); + }); + + it('navigates back on click and via keyboard', async () => { + mockFetchUser.mockResolvedValue(pg); + renderProfile('/news/1'); + const user = userEvent.setup(); + + await user.click(screen.getByRole('link', { name: 'open pg' })); + const back = await screen.findByRole('button', { name: 'Go back' }); + expect(back).toHaveClass('back-button'); + expect(back).toHaveAttribute('tabindex', '0'); + await user.click(back); + expect(screen.getByTestId('location')).toHaveTextContent('/news/1'); + + await user.click(screen.getByRole('link', { name: 'open pg' })); + (await screen.findByRole('button', { name: 'Go back' })).focus(); + await user.keyboard('{Enter}'); + expect(screen.getByTestId('location')).toHaveTextContent('/news/1'); + + await user.click(screen.getByRole('link', { name: 'open pg' })); + (await screen.findByRole('button', { name: 'Go back' })).focus(); + await user.keyboard(' '); + expect(screen.getByTestId('location')).toHaveTextContent('/news/1'); + + await user.click(screen.getByRole('link', { name: 'open pg' })); + fireEvent.keyDown(await screen.findByRole('button', { name: 'Go back' }), { key: 'a' }); + expect(screen.getByTestId('location')).toHaveTextContent('/user/pg'); + }); + + it('aborts and refetches when the id changes, ignoring the stale response', async () => { + const first = deferred(); + const second = deferred(); + mockFetchUser.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise); + renderProfile(); + const firstSignal = mockFetchUser.mock.calls[0][1]!; + expect(firstSignal.aborted).toBe(false); + + await userEvent.setup().click(screen.getByRole('link', { name: 'dang' })); + expect(firstSignal.aborted).toBe(true); + expect(mockFetchUser).toHaveBeenLastCalledWith('dang', expect.any(AbortSignal)); + expect(screen.getByTestId('user-profile')).toHaveAttribute('data-user-id', 'dang'); + + await act(async () => first.resolve(pg)); + expect(screen.getByRole('status')).toBeInTheDocument(); + expect(screen.queryByText('Created 19 years ago')).toBeNull(); + + await act(async () => second.resolve({ id: 'dang', created: '16 years ago', karma: 30000 })); + expect(screen.getByText('Profile: dang')).toBeInTheDocument(); + expect(screen.getByText('30000 ★')).toBeInTheDocument(); + }); + + it('does not show an error for a request rejected after the id changed', async () => { + const first = deferred(); + mockFetchUser.mockReturnValueOnce(first.promise).mockResolvedValueOnce({ ...pg, id: 'dang' }); + renderProfile(); + await userEvent.setup().click(screen.getByRole('link', { name: 'dang' })); + await act(async () => first.reject(new Error('network down'))); + expect(screen.queryByRole('alert')).toBeNull(); + expect(await screen.findByText('Profile: dang')).toBeInTheDocument(); + }); + + it('aborts the request on unmount', () => { + mockFetchUser.mockReturnValue(new Promise(() => {})); + const { unmount } = renderProfile(); + const signal = mockFetchUser.mock.calls[0][1]!; + unmount(); + expect(signal.aborted).toBe(true); + }); +}); diff --git a/react/src/user/UserProfile.tsx b/react/src/user/UserProfile.tsx index 014626792..17419df6f 100644 --- a/react/src/user/UserProfile.tsx +++ b/react/src/user/UserProfile.tsx @@ -1,11 +1,77 @@ -import { useParams } from 'react-router-dom'; +import { useEffect, useState } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; +import { ErrorMessage } from '../shared/components/ErrorMessage/ErrorMessage'; +import { Loader } from '../shared/components/Loader/Loader'; +import { SafeHtml } from '../shared/components/SafeHtml/SafeHtml'; +import type { User } from '../shared/models'; +import { fetchUser } from '../shared/services/hackernewsApi'; +import { onActivateKey } from '../shared/utils/a11y'; +import './UserProfile.scss'; + +interface UserState { + id: string; + user?: User; + errorMessage?: string; +} + +function isAbortError(error: unknown): boolean { + return error instanceof DOMException && error.name === 'AbortError'; +} -// Placeholder route target; the user profile is implemented in migration phase 5. export default function UserProfile() { - const { id } = useParams(); + const { id = '' } = useParams(); + const navigate = useNavigate(); + const [state, setState] = useState({ id }); + + useEffect(() => { + const controller = new AbortController(); + fetchUser(id, controller.signal).then( + (user) => setState({ id, user }), + (error: unknown) => { + if (!controller.signal.aborted && !isAbortError(error)) { + setState({ id, errorMessage: `Could not load user ${id}.` }); + } + } + ); + return () => controller.abort(); + }, [id]); + + // Ignore results belonging to a previous id while the new one loads. + const { user, errorMessage } = state.id === id ? state : {}; + + const goBack = () => navigate(-1); + return (
-

User {id}

+ {!user && !errorMessage && } + {!user && errorMessage && } + {user && ( +
+
+

+ + Profile: {user.id} +

+
+
+ {user.id} + {user.karma} ★ +

Created {user.created}

+
+ {user.about && ( +
+ +
+ )} +
+ )}
); }