Skip to content
Open
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
37 changes: 27 additions & 10 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,23 +1,40 @@
language: node_js
node_js:
- "6.9"
- "22"

branches:
only:
- master

cache:
npm: true
directories:
- $HOME/.cache/ms-playwright

before_install:
- npm install -g npm@11
- cd react-app

install:
- npm ci

before_script:
- npm install -g firebase-tools
- npm install -g @angular/cli
- npx playwright install --with-deps chromium

script:
- npm run lint
- npm run typecheck
- npm test
- npm run build
- npm run e2e

after_success:
- firebase use default
- firebase deploy --token $FIREBASE_TOKEN
before_deploy:
- cd ..
- npm install -g firebase-tools

notifications:
email:
on_failure: change
on_success: change
deploy:
provider: script
skip_cleanup: true
script: firebase use default && firebase deploy --only hosting --token $FIREBASE_TOKEN
on:
branch: master
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@

## Offline Support

This app uses [Workbox](https://workboxjs.org/) to generate a service worker as part of the build step to load quickly and work offline.
This app uses [vite-plugin-pwa](https://vite-pwa-org.netlify.app/) ([Workbox](https://developer.chrome.com/docs/workbox)) to generate a service worker as part of the build step to load quickly and work offline.

## Manifest

Expand Down Expand Up @@ -73,16 +73,16 @@ Feel free to send me feedback on [twitter](https://twitter.com/hdjirdeh) or [fil

## Build process

Note: This project has been ejected (with AOT + production settings) in order to customize Webpack configurations.
The app lives in [`react-app/`](react-app) (React 18 + TypeScript + Vite, TanStack Query, React Router, `vite-plugin-pwa`). Use Node 22 / npm 11.

- Clone or download the repo
- `npm install`
- `npm start` to run the application with webpack-dev-server or `npm build` to kick off a fresh build and update the output directory (`dist/`)
- `cd react-app && npm ci`
- `npm run dev` to start the Vite dev server
- `npm run build` to type-check and build to `react-app/dist/` (the Firebase Hosting public dir), including the Workbox service worker
- `npm run preview` to serve the production build locally with the service worker enabled
- `npm test` for Vitest + React Testing Library unit tests, `npm run e2e` for Playwright end-to-end tests (including an offline check)
- `npm run lint` / `npm run typecheck`

Note: Any Service Worker changes will not be reflected when you run the application locally in development. To test service worker changes:
- `npm build`
- `npm run precache` to generate the service worker file
- `npm run static-serve` to load the application along with the service worker asset using [live-server](https://github.com/tapio/live-server)
The original Angular 9 sources under `src/` are kept for side-by-side comparison until cutover is complete.

## Contributors

Expand Down
12 changes: 11 additions & 1 deletion firebase.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,22 @@
"rules": "database.rules.json"
},
"hosting": {
"public": "dist",
"public": "react-app/dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "/@(sw|ngsw-worker).js",
"headers": [{ "key": "Cache-Control", "value": "no-cache" }]
},
{
"source": "/assets/*-*.@(js|css)",
"headers": [{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }]
}
]
}
}
8 changes: 8 additions & 0 deletions react-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
node_modules
dist
dev-dist
coverage
playwright-report
test-results
blob-report
*.local
1 change: 1 addition & 0 deletions react-app/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
22
68 changes: 68 additions & 0 deletions react-app/e2e/fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { test as base, type BrowserContext } from '@playwright/test';

const story = (feed: string, page: number, i: number) => ({
id: page * 1000 + i,
title: `${feed} story ${page}-${i}`,
points: 100 - i,
user: 'pg',
time: 0,
time_ago: '1 hour ago',
comments_count: i,
type: feed === 'jobs' ? 'job' : 'link',
url: `https://example.com/${feed}/${page}/${i}`,
domain: 'example.com',
});

const item = {
id: 42,
title: 'Ask HN: e2e item',
points: 10,
user: 'pg',
time: 0,
time_ago: '2 hours ago',
type: 'ask',
url: 'item?id=42',
content: '<p>Item body</p>',
comments_count: 2,
comments: [
{
id: 1,
level: 0,
user: 'alice',
time: 0,
time_ago: '1 hour ago',
content: 'Parent comment',
comments: [{ id: 2, level: 1, user: 'bob', time: 0, time_ago: '1 hour ago', content: 'Child comment', comments: [] }],
},
],
};

const user = { id: 'pg', created_time: 0, created: '20 years ago', karma: 157316, about: 'Bug fixer.' };

/** Serve deterministic HN API fixtures (node-hnapi + HNPWA) for every request in the context. */
export async function mockHnApi(context: BrowserContext) {
await context.route(/^https:\/\/(node-hnapi\.herokuapp\.com|api\.hnpwa\.com)\//, (route) => {
const url = new URL(route.request().url());
const feed = url.pathname.match(/^\/(news|newest|show|ask|jobs)$/);
const json = (body: unknown, status = 200) =>
route.fulfill({ status, json: body, headers: { 'Access-Control-Allow-Origin': '*' } });
if (feed) {
const page = Number(url.searchParams.get('page') ?? 1);
return json(Array.from({ length: page >= 3 ? 10 : 30 }, (_, i) => story(feed[1], page, i)));
}
if (url.pathname === '/item/42') return json(item);
if (url.pathname === '/v0/user/pg.json') return json(user);
return route.fulfill({ status: 404, body: 'Cannot GET', headers: { 'Access-Control-Allow-Origin': '*' } });
});
// Keep Google Analytics out of the tests.
await context.route(/google-analytics\.com/, (route) => route.fulfill({ status: 204, body: '' }));
}

export const test = base.extend({
context: async ({ context }, provide) => {
await mockHnApi(context);
await provide(context);
},
});

export { expect } from '@playwright/test';
29 changes: 29 additions & 0 deletions react-app/e2e/offline.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { expect, test } from './fixtures';

test.use({ serviceWorkers: 'allow' });

test('app shell and visited pages work offline after the service worker installs', async ({ page, context }) => {
await page.goto('/news/1');
await expect(page.getByText('news story 1-0')).toBeVisible();
await page.evaluate(() => navigator.serviceWorker.ready.then(() => undefined));
// Reload once so the page is controlled and API responses go through the runtime cache.
await page.reload();
await expect(page.getByText('news story 1-0')).toBeVisible();
await expect.poll(() => page.evaluate(() => !!navigator.serviceWorker.controller)).toBe(true);
await page.goto('/item/42');
await expect(page.getByText('Child comment')).toBeVisible();

// Drop the API mocks too: Playwright routes would otherwise still answer while offline.
await context.unrouteAll({ behavior: 'ignoreErrors' });
await context.setOffline(true);

await page.goto('/news/1');
await expect(page.getByText('news story 1-0')).toBeVisible();
await page.goto('/item/42');
await expect(page.getByText('Child comment')).toBeVisible();

// Never visited: the shell still renders, the feed shows the offline error.
await page.goto('/show/1');
await expect(page.locator('#header')).toBeVisible();
await expect(page.getByText('Could not load show stories.')).toBeVisible({ timeout: 15_000 });
});
79 changes: 79 additions & 0 deletions react-app/e2e/routes.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { expect, test } from './fixtures';

test.use({ serviceWorkers: 'block' });

test('redirects / to /news/1', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveURL(/\/news\/1$/);
await expect(page.getByText('news story 1-0')).toBeVisible();
await expect(page.locator('ol > li')).toHaveCount(30);
});

for (const feed of ['news', 'newest', 'show', 'ask', 'jobs']) {
test(`/${feed}/:page renders the ${feed} feed with pagination`, async ({ page }) => {
await page.goto(`/${feed}/1`);
await expect(page.getByText(`${feed} story 1-0`)).toBeVisible();
await expect(page.getByText('‹ Prev')).toHaveCount(0);

await page.getByText('More ›').click();
await expect(page).toHaveURL(new RegExp(`/${feed}/2$`));
await expect(page.getByText(`${feed} story 2-0`)).toBeVisible();
await expect(page.locator('ol')).toHaveAttribute('start', '31');

await page.getByText('‹ Prev').click();
await expect(page).toHaveURL(new RegExp(`/${feed}/1$`));
});
}

test('header nav links switch feeds', async ({ page }) => {
await page.goto('/news/1');
for (const [label, feed] of [
['new', 'newest'],
['show', 'show'],
['ask', 'ask'],
['jobs', 'jobs'],
]) {
await page.locator('.header-nav').getByRole('link', { name: label, exact: true }).click();
await expect(page).toHaveURL(new RegExp(`/${feed}/1$`));
await expect(page.getByText(`${feed} story 1-0`)).toBeVisible();
}
await expect(page.getByText(/These are jobs at startups/)).toBeVisible();
await page.locator('.home-link').click();
await expect(page).toHaveURL(/\/news\/1$/);
});

test('/item/:id lazy-loads item details with collapsible comments', async ({ page }) => {
const chunks: string[] = [];
page.on('request', (req) => chunks.push(new URL(req.url()).pathname));
await page.goto('/news/1');
await expect(page.getByText('news story 1-0')).toBeVisible();
expect(chunks.some((p) => /ItemDetails-.*\.js$/.test(p))).toBe(false);

await page.goto('/item/42');
await expect(page.locator('.laptop .title')).toHaveText('Ask HN: e2e item');
expect(chunks.some((p) => /ItemDetails-.*\.js$/.test(p))).toBe(true);
await expect(page.getByText('Child comment')).toBeVisible();
await page.locator('.meta', { hasText: 'alice' }).getByText('[-]').click();
await expect(page.getByText('Child comment')).toBeHidden();
await page.locator('.meta', { hasText: 'alice' }).getByText('[+]').click();
await expect(page.getByText('Child comment')).toBeVisible();
});

test('/user/:id renders the profile', async ({ page }) => {
await page.goto('/user/pg');
await expect(page.locator('.main-details .name')).toHaveText('pg');
await expect(page.getByText('157316 ★')).toBeVisible();
await expect(page.getByText('Bug fixer.')).toBeVisible();
});

test('theme switching persists across reloads', async ({ page }) => {
await page.goto('/news/1');
await page.getByAltText('Settings').click();
await page.getByLabel('Night').check();
await expect(page.locator('html')).toHaveClass(/\bnight\b/);
await page.getByLabel('Black (AMOLED)').check();
await expect(page.locator('html')).toHaveClass(/\bamoledblack\b/);
await page.reload();
await expect(page.locator('html')).toHaveClass(/\bamoledblack\b/);
await expect(page.locator('#header')).toHaveCSS('background-color', 'rgb(0, 0, 0)');
});
30 changes: 30 additions & 0 deletions react-app/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';

export default tseslint.config(
{ ignores: ['dist', 'dev-dist', 'playwright-report', 'test-results', 'public/ngsw-worker.js'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
},
},
{
// Route config module, not a component module.
files: ['src/routes.tsx'],
rules: { 'react-refresh/only-export-components': 'off' },
}
);
Loading