diff --git a/react/src/shared/models/comment.ts b/react/src/shared/models/comment.ts
new file mode 100644
index 000000000..8eede6b99
--- /dev/null
+++ b/react/src/shared/models/comment.ts
@@ -0,0 +1,10 @@
+export interface Comment {
+ id: number;
+ level: number;
+ user: string;
+ time: number;
+ time_ago: string;
+ content: string;
+ deleted?: boolean;
+ comments: Comment[];
+}
diff --git a/react/src/shared/models/feed-type.test.ts b/react/src/shared/models/feed-type.test.ts
new file mode 100644
index 000000000..6b2c2f385
--- /dev/null
+++ b/react/src/shared/models/feed-type.test.ts
@@ -0,0 +1,7 @@
+import { FEED_NAMES } from '.';
+
+describe('FEED_NAMES', () => {
+ it('lists every HN feed in nav order', () => {
+ expect(FEED_NAMES).toEqual(['news', 'newest', 'show', 'ask', 'jobs']);
+ });
+});
diff --git a/react/src/shared/models/feed-type.ts b/react/src/shared/models/feed-type.ts
new file mode 100644
index 000000000..d0cf217eb
--- /dev/null
+++ b/react/src/shared/models/feed-type.ts
@@ -0,0 +1,6 @@
+/** Angular's `FeedType`: the item kinds a story can be. Renamed to avoid clashing with route feed names. */
+export type ItemType = 'poll' | 'story' | 'job';
+
+export type FeedName = 'news' | 'newest' | 'show' | 'ask' | 'jobs';
+
+export const FEED_NAMES: readonly FeedName[] = ['news', 'newest', 'show', 'ask', 'jobs'];
diff --git a/react/src/shared/models/index.ts b/react/src/shared/models/index.ts
new file mode 100644
index 000000000..ab7ed7ac4
--- /dev/null
+++ b/react/src/shared/models/index.ts
@@ -0,0 +1,7 @@
+export type { Comment } from './comment';
+export type { FeedName, ItemType } from './feed-type';
+export { FEED_NAMES } from './feed-type';
+export type { PollResult } from './poll-result';
+export type { Settings } from './settings';
+export type { Story } from './story';
+export type { User } from './user';
diff --git a/react/src/shared/models/poll-result.ts b/react/src/shared/models/poll-result.ts
new file mode 100644
index 000000000..86a8a60b9
--- /dev/null
+++ b/react/src/shared/models/poll-result.ts
@@ -0,0 +1,4 @@
+export interface PollResult {
+ points: number;
+ content: string;
+}
diff --git a/react/src/shared/models/settings.ts b/react/src/shared/models/settings.ts
new file mode 100644
index 000000000..11b447e4b
--- /dev/null
+++ b/react/src/shared/models/settings.ts
@@ -0,0 +1,9 @@
+import type { Theme } from '../services/settings';
+
+export interface Settings {
+ showSettings: boolean;
+ openLinkInNewTab: boolean;
+ theme: Theme;
+ titleFontSize: string;
+ listSpacing: string;
+}
diff --git a/react/src/shared/models/story.ts b/react/src/shared/models/story.ts
new file mode 100644
index 000000000..c9898f971
--- /dev/null
+++ b/react/src/shared/models/story.ts
@@ -0,0 +1,23 @@
+import type { Comment } from './comment';
+import type { ItemType } from './feed-type';
+import type { PollResult } from './poll-result';
+
+export interface Story {
+ id: number;
+ title: string;
+ points: number;
+ user: string;
+ time: number;
+ time_ago: string;
+ /** node-hnapi also returns 'link' (stories with a URL), 'ask' and 'comment'. */
+ type: ItemType | 'link' | 'ask' | 'comment';
+ url?: string;
+ domain?: string;
+ content?: string;
+ comments?: Comment[];
+ comments_count?: number;
+ poll?: PollResult[];
+ poll_votes_count?: number;
+ deleted?: boolean;
+ dead?: boolean;
+}
diff --git a/react/src/shared/models/user.ts b/react/src/shared/models/user.ts
new file mode 100644
index 000000000..22d7dfb45
--- /dev/null
+++ b/react/src/shared/models/user.ts
@@ -0,0 +1,9 @@
+export interface User {
+ id: string;
+ /** Typo kept from the Angular model for parity. */
+ crated_time?: number;
+ created: string;
+ karma: number;
+ avg?: number;
+ about?: string;
+}
diff --git a/react/src/shared/services/SettingsProvider.test.tsx b/react/src/shared/services/SettingsProvider.test.tsx
new file mode 100644
index 000000000..9cd6c4e54
--- /dev/null
+++ b/react/src/shared/services/SettingsProvider.test.tsx
@@ -0,0 +1,137 @@
+import { act, render, renderHook, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import { mockMatchMedia, type MatchMediaMock } from '../../test/matchMedia';
+import { SettingsProvider } from './SettingsProvider';
+import { useSettings } from './useSettings';
+
+function Consumer() {
+ const { settings, toggleSettings, toggleOpenLinksInNewTab, setTheme, setFont, setSpacing } = useSettings();
+ return (
+
+
+
+
+
+
+
+
+ );
+}
+
+function renderConsumer() {
+ return render(
+
+
+
+ );
+}
+
+function currentSettings() {
+ return JSON.parse(screen.getByTestId('settings').textContent ?? '{}');
+}
+
+describe('SettingsProvider / useSettings', () => {
+ let media: MatchMediaMock;
+
+ beforeEach(() => {
+ media = mockMatchMedia(false);
+ });
+
+ afterEach(() => {
+ media.restore();
+ });
+
+ it('initialises from defaults and persists the system theme on first load', () => {
+ renderConsumer();
+ expect(currentSettings()).toEqual({
+ showSettings: false,
+ openLinkInNewTab: false,
+ theme: 'default',
+ titleFontSize: '16',
+ listSpacing: '0',
+ });
+ expect(localStorage.getItem('theme')).toBe('default');
+ expect(localStorage.getItem('openLinkInNewTab')).toBeNull();
+ expect(localStorage.getItem('titleFontSize')).toBeNull();
+ expect(localStorage.getItem('listSpacing')).toBeNull();
+ });
+
+ it('persists the dark system theme on first load', () => {
+ media.setMatches(true);
+ renderConsumer();
+ expect(currentSettings().theme).toBe('night');
+ expect(localStorage.getItem('theme')).toBe('night');
+ });
+
+ it('keeps a previously saved theme', () => {
+ media.setMatches(true);
+ localStorage.setItem('theme', 'amoledblack');
+ localStorage.setItem('titleFontSize', '24');
+ renderConsumer();
+ expect(currentSettings()).toMatchObject({ theme: 'amoledblack', titleFontSize: '24' });
+ expect(localStorage.getItem('theme')).toBe('amoledblack');
+ });
+
+ it('toggleSettings flips showSettings without persisting', async () => {
+ const user = userEvent.setup();
+ renderConsumer();
+ await user.click(screen.getByRole('button', { name: 'toggle settings' }));
+ expect(currentSettings().showSettings).toBe(true);
+ await user.click(screen.getByRole('button', { name: 'toggle settings' }));
+ expect(currentSettings().showSettings).toBe(false);
+ expect(Object.keys(localStorage)).toEqual(['theme']);
+ });
+
+ it('toggleOpenLinksInNewTab flips and persists the value as JSON', async () => {
+ const user = userEvent.setup();
+ renderConsumer();
+ await user.click(screen.getByRole('button', { name: 'toggle new tab' }));
+ expect(currentSettings().openLinkInNewTab).toBe(true);
+ expect(localStorage.getItem('openLinkInNewTab')).toBe('true');
+ await user.click(screen.getByRole('button', { name: 'toggle new tab' }));
+ expect(currentSettings().openLinkInNewTab).toBe(false);
+ expect(localStorage.getItem('openLinkInNewTab')).toBe('false');
+ });
+
+ it('setTheme, setFont and setSpacing update state and persist', async () => {
+ const user = userEvent.setup();
+ renderConsumer();
+ await user.click(screen.getByRole('button', { name: 'black theme' }));
+ await user.click(screen.getByRole('button', { name: 'font 20' }));
+ await user.click(screen.getByRole('button', { name: 'spacing 10' }));
+ expect(currentSettings()).toMatchObject({ theme: 'amoledblack', titleFontSize: '20', listSpacing: '10' });
+ expect(localStorage.getItem('theme')).toBe('amoledblack');
+ expect(localStorage.getItem('titleFontSize')).toBe('20');
+ expect(localStorage.getItem('listSpacing')).toBe('10');
+ });
+
+ it('follows system colour scheme changes and unsubscribes on unmount', () => {
+ localStorage.setItem('theme', 'amoledblack');
+ const { unmount } = renderConsumer();
+ expect(media.listenerCount()).toBe(1);
+
+ act(() => media.setMatches(true));
+ expect(currentSettings().theme).toBe('night');
+ expect(localStorage.getItem('theme')).toBe('night');
+
+ act(() => media.setMatches(false));
+ expect(currentSettings().theme).toBe('default');
+ expect(localStorage.getItem('theme')).toBe('default');
+
+ unmount();
+ expect(media.listenerCount()).toBe(0);
+ });
+
+ it('works without matchMedia support', () => {
+ media.restore();
+ renderConsumer();
+ expect(currentSettings().theme).toBe('default');
+ expect(localStorage.getItem('theme')).toBe('default');
+ });
+
+ it('useSettings throws a descriptive error outside SettingsProvider', () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(() => renderHook(() => useSettings())).toThrow('useSettings must be used within a .');
+ });
+});
diff --git a/react/src/shared/services/SettingsProvider.tsx b/react/src/shared/services/SettingsProvider.tsx
new file mode 100644
index 000000000..954c2e11c
--- /dev/null
+++ b/react/src/shared/services/SettingsProvider.tsx
@@ -0,0 +1,67 @@
+import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
+
+import type { Settings } from '../models';
+import {
+ DARK_SCHEME_QUERY,
+ getSavedTheme,
+ getSystemTheme,
+ loadSettings,
+ saveListSpacing,
+ saveOpenLinkInNewTab,
+ saveTheme,
+ saveTitleFontSize,
+ type Theme,
+} from './settings';
+import { SettingsContext, type SettingsContextValue } from './settingsContext';
+
+export function SettingsProvider({ children }: { children: ReactNode }) {
+ const [settings, setSettings] = useState(loadSettings);
+
+ const setTheme = useCallback((theme: Theme) => {
+ saveTheme(theme);
+ setSettings((current) => ({ ...current, theme }));
+ }, []);
+
+ const toggleSettings = useCallback(() => {
+ setSettings((current) => ({ ...current, showSettings: !current.showSettings }));
+ }, []);
+
+ const { openLinkInNewTab } = settings;
+ const toggleOpenLinksInNewTab = useCallback(() => {
+ saveOpenLinkInNewTab(!openLinkInNewTab);
+ setSettings((current) => ({ ...current, openLinkInNewTab: !openLinkInNewTab }));
+ }, [openLinkInNewTab]);
+
+ const setFont = useCallback((titleFontSize: string) => {
+ saveTitleFontSize(titleFontSize);
+ setSettings((current) => ({ ...current, titleFontSize }));
+ }, []);
+
+ const setSpacing = useCallback((listSpacing: string) => {
+ saveListSpacing(listSpacing);
+ setSettings((current) => ({ ...current, listSpacing }));
+ }, []);
+
+ useEffect(() => {
+ if (getSavedTheme() === null) {
+ setTheme(getSystemTheme());
+ }
+ }, [setTheme]);
+
+ useEffect(() => {
+ if (typeof window.matchMedia !== 'function') {
+ return;
+ }
+ const darkScheme = window.matchMedia(DARK_SCHEME_QUERY);
+ const handleChange = (event: MediaQueryListEvent) => setTheme(event.matches ? 'night' : 'default');
+ darkScheme.addEventListener('change', handleChange);
+ return () => darkScheme.removeEventListener('change', handleChange);
+ }, [setTheme]);
+
+ const value = useMemo(
+ () => ({ settings, toggleSettings, toggleOpenLinksInNewTab, setTheme, setFont, setSpacing }),
+ [settings, toggleSettings, toggleOpenLinksInNewTab, setTheme, setFont, setSpacing]
+ );
+
+ return {children};
+}
diff --git a/react/src/shared/services/hackernewsApi.test.ts b/react/src/shared/services/hackernewsApi.test.ts
new file mode 100644
index 000000000..4534ddf95
--- /dev/null
+++ b/react/src/shared/services/hackernewsApi.test.ts
@@ -0,0 +1,152 @@
+import type { Story } from '../models';
+import { fetchFeed, fetchItemContent, fetchPollContent, fetchUser, HN_API_BASE_URL } from './hackernewsApi';
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+}
+
+function mockFetch(handler: (url: string, init?: RequestInit) => Response | Promise) {
+ return vi
+ .spyOn(globalThis, 'fetch')
+ .mockImplementation((input: RequestInfo | URL, init?: RequestInit) =>
+ Promise.resolve(handler(String(input), init))
+ );
+}
+
+const story: Story = {
+ id: 1,
+ title: 'Hello',
+ points: 10,
+ user: 'pg',
+ time: 1,
+ time_ago: '1 hour ago',
+ type: 'link',
+ url: 'https://example.com',
+ domain: 'example.com',
+ comments_count: 0,
+};
+
+describe('hackernewsApi', () => {
+ it('uses the node-hnapi base URL', () => {
+ expect(HN_API_BASE_URL).toBe('https://node-hnapi.herokuapp.com');
+ });
+
+ it('fetchFeed GETs /{feedType}?page={page}', async () => {
+ const fetchSpy = mockFetch(() => jsonResponse([story]));
+ await expect(fetchFeed('newest', 3)).resolves.toEqual([story]);
+ expect(fetchSpy).toHaveBeenCalledWith(`${HN_API_BASE_URL}/newest?page=3`, { signal: undefined });
+ });
+
+ it('passes the abort signal to fetch', async () => {
+ const fetchSpy = mockFetch(() => jsonResponse([]));
+ const controller = new AbortController();
+ await fetchFeed('news', 1, controller.signal);
+ expect(fetchSpy).toHaveBeenCalledWith(`${HN_API_BASE_URL}/news?page=1`, { signal: controller.signal });
+ });
+
+ it('fetchItemContent GETs /item/{id} and returns non-poll items untouched', async () => {
+ const fetchSpy = mockFetch(() => jsonResponse(story));
+ await expect(fetchItemContent(1)).resolves.toEqual(story);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(fetchSpy).toHaveBeenCalledWith(`${HN_API_BASE_URL}/item/1`, { signal: undefined });
+ });
+
+ it('fetchItemContent loads every poll option in parallel and sums the votes', async () => {
+ const poll: Story = {
+ ...story,
+ id: 100,
+ type: 'poll',
+ poll: [
+ { points: 0, content: '' },
+ { points: 0, content: '' },
+ { points: 0, content: '' },
+ ],
+ };
+ const options: Record = {
+ '101': { points: 5, content: 'A' },
+ '102': { points: 7, content: 'B' },
+ '103': { points: 1, content: 'C' },
+ };
+ const fetchSpy = mockFetch((url) => {
+ const id = url.split('/').pop() as string;
+ return jsonResponse(id === '100' ? poll : options[id]);
+ });
+
+ const result = await fetchItemContent(100);
+
+ expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
+ `${HN_API_BASE_URL}/item/100`,
+ `${HN_API_BASE_URL}/item/101`,
+ `${HN_API_BASE_URL}/item/102`,
+ `${HN_API_BASE_URL}/item/103`,
+ ]);
+ expect(result.poll).toEqual([options['101'], options['102'], options['103']]);
+ expect(result.poll_votes_count).toBe(13);
+ });
+
+ it('fetchItemContent treats a poll without options as zero votes', async () => {
+ const fetchSpy = mockFetch(() => jsonResponse({ ...story, type: 'poll' }));
+ const result = await fetchItemContent(1);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(result.poll).toEqual([]);
+ expect(result.poll_votes_count).toBe(0);
+ });
+
+ it('fetchItemContent rejects when a poll option fails to load', async () => {
+ mockFetch((url) =>
+ url.endsWith('/item/1')
+ ? jsonResponse({ ...story, type: 'poll', poll: [{ points: 0, content: '' }] })
+ : jsonResponse({}, 500)
+ );
+ await expect(fetchItemContent(1)).rejects.toThrow('HN API request to /item/2 failed with status 500');
+ });
+
+ it('fetchPollContent GETs /item/{id}', async () => {
+ const fetchSpy = mockFetch(() => jsonResponse({ points: 3, content: 'Yes' }));
+ await expect(fetchPollContent(42)).resolves.toEqual({ points: 3, content: 'Yes' });
+ expect(fetchSpy).toHaveBeenCalledWith(`${HN_API_BASE_URL}/item/42`, { signal: undefined });
+ });
+
+ it('fetchUser GETs /user/{id}', async () => {
+ const user = { id: 'pg', created: '19 years ago', karma: 1, avg: 0, about: 'hi' };
+ const fetchSpy = mockFetch(() => jsonResponse(user));
+ await expect(fetchUser('pg')).resolves.toEqual(user);
+ expect(fetchSpy).toHaveBeenCalledWith(`${HN_API_BASE_URL}/user/pg`, { signal: undefined });
+ });
+
+ it('rejects on non-2xx responses', async () => {
+ mockFetch(() => jsonResponse({ error: 'nope' }, 404));
+ await expect(fetchUser('nobody')).rejects.toThrow('HN API request to /user/nobody failed with status 404');
+ });
+
+ it('rejects on network failure', async () => {
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('Failed to fetch'));
+ await expect(fetchFeed('news', 1)).rejects.toThrow('Failed to fetch');
+ });
+
+ it('rejects with an AbortError without fetching when the signal is already aborted', async () => {
+ const fetchSpy = mockFetch(() => jsonResponse([]));
+ const controller = new AbortController();
+ controller.abort();
+ await expect(fetchFeed('news', 1, controller.signal)).rejects.toMatchObject({ name: 'AbortError' });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('falls back to a DOMException AbortError when the signal has no reason', async () => {
+ const signal = { aborted: true, reason: undefined } as AbortSignal;
+ await expect(fetchItemContent(1, signal)).rejects.toMatchObject({ name: 'AbortError' });
+ });
+
+ it('propagates the AbortError when aborted mid-flight', async () => {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(
+ (_input, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(init.signal?.reason));
+ })
+ );
+ const controller = new AbortController();
+ const pending = fetchUser('pg', controller.signal);
+ controller.abort();
+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
+ });
+});
diff --git a/react/src/shared/services/hackernewsApi.ts b/react/src/shared/services/hackernewsApi.ts
new file mode 100644
index 000000000..807ff7834
--- /dev/null
+++ b/react/src/shared/services/hackernewsApi.ts
@@ -0,0 +1,39 @@
+import type { FeedName, PollResult, Story, User } from '../models';
+
+export const HN_API_BASE_URL = 'https://node-hnapi.herokuapp.com';
+
+async function getJson(path: string, signal?: AbortSignal): Promise {
+ if (signal?.aborted) {
+ throw signal.reason ?? new DOMException('The operation was aborted.', 'AbortError');
+ }
+ const response = await fetch(`${HN_API_BASE_URL}${path}`, { signal });
+ if (!response.ok) {
+ throw new Error(`HN API request to ${path} failed with status ${response.status}`);
+ }
+ return (await response.json()) as T;
+}
+
+export function fetchFeed(feedType: FeedName, page: number, signal?: AbortSignal): Promise {
+ return getJson(`/${feedType}?page=${page}`, signal);
+}
+
+export async function fetchItemContent(id: number, signal?: AbortSignal): Promise {
+ const story = await getJson(`/item/${id}`, signal);
+ if (story.type === 'poll') {
+ const optionCount = story.poll?.length ?? 0;
+ const results = await Promise.all(
+ Array.from({ length: optionCount }, (_, i) => fetchPollContent(story.id + i + 1, signal))
+ );
+ story.poll = results;
+ story.poll_votes_count = results.reduce((total, result) => total + result.points, 0);
+ }
+ return story;
+}
+
+export function fetchPollContent(id: number, signal?: AbortSignal): Promise {
+ return getJson(`/item/${id}`, signal);
+}
+
+export function fetchUser(id: string, signal?: AbortSignal): Promise {
+ return getJson(`/user/${id}`, signal);
+}
diff --git a/react/src/shared/services/settings.test.ts b/react/src/shared/services/settings.test.ts
new file mode 100644
index 000000000..6abb8a7e3
--- /dev/null
+++ b/react/src/shared/services/settings.test.ts
@@ -0,0 +1,135 @@
+import { mockMatchMedia, type MatchMediaMock } from '../../test/matchMedia';
+import {
+ DARK_SCHEME_QUERY,
+ getSavedTheme,
+ getSystemTheme,
+ loadSettings,
+ saveListSpacing,
+ saveOpenLinkInNewTab,
+ saveTheme,
+ saveTitleFontSize,
+ STORAGE_KEYS,
+ THEMES,
+} from './settings';
+
+describe('settings', () => {
+ let media: MatchMediaMock;
+
+ beforeEach(() => {
+ media = mockMatchMedia(false);
+ });
+
+ afterEach(() => {
+ media.restore();
+ });
+
+ it('exposes the Angular theme values, storage keys and media query', () => {
+ expect(THEMES).toEqual([
+ { value: 'default', label: 'Default' },
+ { value: 'night', label: 'Night' },
+ { value: 'amoledblack', label: 'Black (AMOLED)' },
+ ]);
+ expect(STORAGE_KEYS).toEqual({
+ openLinkInNewTab: 'openLinkInNewTab',
+ theme: 'theme',
+ titleFontSize: 'titleFontSize',
+ listSpacing: 'listSpacing',
+ });
+ expect(DARK_SCHEME_QUERY).toBe('(prefers-color-scheme: dark)');
+ });
+
+ describe('getSystemTheme', () => {
+ it('returns default for a light system scheme', () => {
+ expect(getSystemTheme()).toBe('default');
+ expect(media.matchMedia).toHaveBeenCalledWith(DARK_SCHEME_QUERY);
+ });
+
+ it('returns night for a dark system scheme', () => {
+ media.setMatches(true);
+ expect(getSystemTheme()).toBe('night');
+ });
+
+ it('returns default when matchMedia is unavailable', () => {
+ media.restore();
+ expect(getSystemTheme()).toBe('default');
+ });
+ });
+
+ describe('getSavedTheme', () => {
+ it('returns null when nothing is saved', () => {
+ expect(getSavedTheme()).toBeNull();
+ });
+
+ it('returns a saved known theme', () => {
+ localStorage.setItem('theme', 'amoledblack');
+ expect(getSavedTheme()).toBe('amoledblack');
+ });
+
+ it('ignores unknown values', () => {
+ localStorage.setItem('theme', 'sepia');
+ expect(getSavedTheme()).toBeNull();
+ });
+ });
+
+ describe('loadSettings', () => {
+ it('uses the Angular defaults with an empty storage and light system scheme', () => {
+ expect(loadSettings()).toEqual({
+ showSettings: false,
+ openLinkInNewTab: false,
+ theme: 'default',
+ titleFontSize: '16',
+ listSpacing: '0',
+ });
+ });
+
+ it('falls back to the night theme for a dark system scheme', () => {
+ media.setMatches(true);
+ expect(loadSettings().theme).toBe('night');
+ });
+
+ it('reads saved values', () => {
+ localStorage.setItem('openLinkInNewTab', 'true');
+ localStorage.setItem('theme', 'night');
+ localStorage.setItem('titleFontSize', '20');
+ localStorage.setItem('listSpacing', '10');
+ expect(loadSettings()).toEqual({
+ showSettings: false,
+ openLinkInNewTab: true,
+ theme: 'night',
+ titleFontSize: '20',
+ listSpacing: '10',
+ });
+ });
+
+ it('prefers a saved theme over the system scheme', () => {
+ media.setMatches(true);
+ localStorage.setItem('theme', 'default');
+ expect(loadSettings().theme).toBe('default');
+ });
+
+ it.each([
+ ['false', false],
+ ['not json', false],
+ ['"true"', false],
+ ])('parses openLinkInNewTab %s as %s', (raw, expected) => {
+ localStorage.setItem('openLinkInNewTab', raw);
+ expect(loadSettings().openLinkInNewTab).toBe(expected);
+ });
+ });
+
+ describe('persistence', () => {
+ it('serialises values exactly like the Angular service', () => {
+ saveTheme('amoledblack');
+ saveOpenLinkInNewTab(true);
+ saveTitleFontSize('18');
+ saveListSpacing('5');
+ expect(localStorage.getItem('theme')).toBe('amoledblack');
+ expect(localStorage.getItem('openLinkInNewTab')).toBe('true');
+ expect(localStorage.getItem('titleFontSize')).toBe('18');
+ expect(localStorage.getItem('listSpacing')).toBe('5');
+
+ saveOpenLinkInNewTab(false);
+ expect(localStorage.getItem('openLinkInNewTab')).toBe('false');
+ });
+ });
+});
diff --git a/react/src/shared/services/settings.ts b/react/src/shared/services/settings.ts
new file mode 100644
index 000000000..24a30f063
--- /dev/null
+++ b/react/src/shared/services/settings.ts
@@ -0,0 +1,72 @@
+import type { Settings } from '../models';
+
+/** Exact Angular theme class names. */
+export type Theme = 'default' | 'night' | 'amoledblack';
+
+export const THEMES: readonly { value: Theme; label: string }[] = [
+ { value: 'default', label: 'Default' },
+ { value: 'night', label: 'Night' },
+ { value: 'amoledblack', label: 'Black (AMOLED)' },
+];
+
+export const STORAGE_KEYS = {
+ openLinkInNewTab: 'openLinkInNewTab',
+ theme: 'theme',
+ titleFontSize: 'titleFontSize',
+ listSpacing: 'listSpacing',
+} as const;
+
+export const DARK_SCHEME_QUERY = '(prefers-color-scheme: dark)';
+
+function isTheme(value: string | null): value is Theme {
+ return THEMES.some((theme) => theme.value === value);
+}
+
+export function getSystemTheme(): Theme {
+ const prefersDark = typeof window.matchMedia === 'function' && window.matchMedia(DARK_SCHEME_QUERY).matches;
+ return prefersDark ? 'night' : 'default';
+}
+
+/** The persisted theme, or null when none (or an unknown value) is saved. */
+export function getSavedTheme(): Theme | null {
+ const saved = localStorage.getItem(STORAGE_KEYS.theme);
+ return isTheme(saved) ? saved : null;
+}
+
+function loadOpenLinkInNewTab(): boolean {
+ const saved = localStorage.getItem(STORAGE_KEYS.openLinkInNewTab);
+ if (!saved) {
+ return false;
+ }
+ try {
+ return JSON.parse(saved) === true;
+ } catch {
+ return false;
+ }
+}
+
+export function loadSettings(): Settings {
+ return {
+ showSettings: false,
+ openLinkInNewTab: loadOpenLinkInNewTab(),
+ theme: getSavedTheme() ?? getSystemTheme(),
+ titleFontSize: localStorage.getItem(STORAGE_KEYS.titleFontSize) || '16',
+ listSpacing: localStorage.getItem(STORAGE_KEYS.listSpacing) || '0',
+ };
+}
+
+export function saveTheme(theme: Theme): void {
+ localStorage.setItem(STORAGE_KEYS.theme, theme);
+}
+
+export function saveOpenLinkInNewTab(value: boolean): void {
+ localStorage.setItem(STORAGE_KEYS.openLinkInNewTab, JSON.stringify(value));
+}
+
+export function saveTitleFontSize(value: string): void {
+ localStorage.setItem(STORAGE_KEYS.titleFontSize, value);
+}
+
+export function saveListSpacing(value: string): void {
+ localStorage.setItem(STORAGE_KEYS.listSpacing, value);
+}
diff --git a/react/src/shared/services/settingsContext.ts b/react/src/shared/services/settingsContext.ts
new file mode 100644
index 000000000..d9405db1d
--- /dev/null
+++ b/react/src/shared/services/settingsContext.ts
@@ -0,0 +1,15 @@
+import { createContext } from 'react';
+
+import type { Settings } from '../models';
+import type { Theme } from './settings';
+
+export interface SettingsContextValue {
+ settings: Settings;
+ toggleSettings(): void;
+ toggleOpenLinksInNewTab(): void;
+ setTheme(theme: Theme): void;
+ setFont(fontSize: string): void;
+ setSpacing(listSpace: string): void;
+}
+
+export const SettingsContext = createContext(null);
diff --git a/react/src/shared/services/useSettings.ts b/react/src/shared/services/useSettings.ts
new file mode 100644
index 000000000..fe9c3f9ac
--- /dev/null
+++ b/react/src/shared/services/useSettings.ts
@@ -0,0 +1,11 @@
+import { useContext } from 'react';
+
+import { SettingsContext, type SettingsContextValue } from './settingsContext';
+
+export function useSettings(): SettingsContextValue {
+ const context = useContext(SettingsContext);
+ if (!context) {
+ throw new Error('useSettings must be used within a .');
+ }
+ return context;
+}
diff --git a/react/src/shared/utils/comment.test.ts b/react/src/shared/utils/comment.test.ts
new file mode 100644
index 000000000..ee9413e90
--- /dev/null
+++ b/react/src/shared/utils/comment.test.ts
@@ -0,0 +1,13 @@
+import { formatCommentCount } from './comment';
+
+describe('formatCommentCount', () => {
+ it.each([
+ [0, 'discuss'],
+ [-3, 'discuss'],
+ [1, '1 comment'],
+ [2, '2 comments'],
+ [128, '128 comments'],
+ ])('formats %i as "%s"', (count, expected) => {
+ expect(formatCommentCount(count)).toBe(expected);
+ });
+});
diff --git a/react/src/shared/utils/comment.ts b/react/src/shared/utils/comment.ts
new file mode 100644
index 000000000..e4aa49a17
--- /dev/null
+++ b/react/src/shared/utils/comment.ts
@@ -0,0 +1,6 @@
+export function formatCommentCount(count: number): string {
+ if (count > 0) {
+ return `${count} ${count === 1 ? 'comment' : 'comments'}`;
+ }
+ return 'discuss';
+}
diff --git a/react/src/test/matchMedia.ts b/react/src/test/matchMedia.ts
new file mode 100644
index 000000000..b8cc315ab
--- /dev/null
+++ b/react/src/test/matchMedia.ts
@@ -0,0 +1,60 @@
+import { vi } from 'vitest';
+
+type ChangeListener = (event: MediaQueryListEvent) => void;
+
+export interface MatchMediaMock {
+ /** The spy installed as `window.matchMedia`. */
+ matchMedia: ReturnType;
+ /** Updates `matches` and notifies `change` listeners, like the OS switching colour scheme. */
+ setMatches(matches: boolean): void;
+ /** Number of currently registered `change` listeners. */
+ listenerCount(): number;
+ /** Removes the mock, restoring jsdom's original (absent) `matchMedia`. */
+ restore(): void;
+}
+
+/** Installs a controllable `window.matchMedia` (jsdom has none). Every query shares the same `matches` state. */
+export function mockMatchMedia(initialMatches = false): MatchMediaMock {
+ const original = Object.getOwnPropertyDescriptor(window, 'matchMedia');
+ const listeners = new Set();
+ let matches = initialMatches;
+
+ const matchMedia = vi.fn((media: string) => {
+ const mql = {
+ get matches() {
+ return matches;
+ },
+ media,
+ onchange: null,
+ addEventListener: (type: string, listener: ChangeListener) => {
+ if (type === 'change') listeners.add(listener);
+ },
+ removeEventListener: (type: string, listener: ChangeListener) => {
+ if (type === 'change') listeners.delete(listener);
+ },
+ addListener: (listener: ChangeListener) => listeners.add(listener),
+ removeListener: (listener: ChangeListener) => listeners.delete(listener),
+ dispatchEvent: () => true,
+ };
+ return mql as unknown as MediaQueryList;
+ });
+
+ Object.defineProperty(window, 'matchMedia', { configurable: true, writable: true, value: matchMedia });
+
+ return {
+ matchMedia,
+ setMatches(next: boolean) {
+ matches = next;
+ const event = { matches: next, media: '' } as MediaQueryListEvent;
+ [...listeners].forEach((listener) => listener(event));
+ },
+ listenerCount: () => listeners.size,
+ restore() {
+ if (original) {
+ Object.defineProperty(window, 'matchMedia', original);
+ } else {
+ delete (window as { matchMedia?: unknown }).matchMedia;
+ }
+ },
+ };
+}