Repository navigation
feat(frontend): prerender static HTML so page is readable with JavaScript disabled #347
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
36823aa
755f7c0
cbad8e1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| import fs from 'node:fs'; | ||
| import path from 'node:path'; | ||
| import { fileURLToPath } from 'node:url'; | ||
| import { createServer } from 'vite'; | ||
| import React from 'react'; | ||
| import { renderToString } from 'react-dom/server'; | ||
|
|
||
| const __dirname = path.dirname(fileURLToPath(import.meta.url)); | ||
| const rootDir = path.resolve(__dirname, '..'); | ||
| const distDir = path.resolve(rootDir, 'dist'); | ||
| const htmlPath = path.resolve(distDir, 'index.html'); | ||
| const evidencePath = path.resolve(rootDir, 'public/data/evidence.json'); | ||
|
|
||
| if (!fs.existsSync(htmlPath)) { | ||
| console.error('Error: dist/index.html not found. Run "vite build" first.'); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| if (!fs.existsSync(evidencePath)) { | ||
| console.error('Error: public/data/evidence.json not found.'); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| const server = await createServer({ | ||
| root: rootDir, | ||
| server: { middlewareMode: true }, | ||
| appType: 'custom', | ||
| }); | ||
|
|
||
| try { | ||
| const { App } = await server.ssrLoadModule('/src/App.tsx'); | ||
| const { validateEvidence } = await server.ssrLoadModule('/src/data/validate.ts'); | ||
| const { summarize } = await server.ssrLoadModule('/src/data/facts.ts'); | ||
|
|
||
| const rawEvidence = JSON.parse(fs.readFileSync(evidencePath, 'utf8')); | ||
| const evidence = validateEvidence(rawEvidence); | ||
| const facts = summarize(evidence); | ||
|
|
||
| const appHtml = renderToString( | ||
| React.createElement(App, { initialData: { evidence, facts } }), | ||
| ); | ||
|
|
||
| let template = fs.readFileSync(htmlPath, 'utf8'); | ||
|
|
||
| if (!template.includes('<div id="root"></div>')) { | ||
| console.error('Error: <div id="root"></div> placeholder not found in dist/index.html'); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| const serialized = JSON.stringify(rawEvidence).replace(/</g, '\\u003c'); | ||
| const embeddedScript = `<script id="__OVL_EVIDENCE__" type="application/json">${serialized}</script>`; | ||
|
|
||
| template = template.replace( | ||
| '<div id="root"></div>', | ||
| () => `<div id="root">${appHtml}</div>\n ${embeddedScript}`, | ||
| ); | ||
|
|
||
| fs.writeFileSync(htmlPath, template, 'utf8'); | ||
| console.log(`Prerendered static HTML into dist/index.html (${appHtml.length} chars).`); | ||
| } finally { | ||
| await server.close(); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,19 +14,36 @@ import { Downloads } from './components/Downloads'; | |
| import { Faq } from './components/Faq'; | ||
| import { Footer } from './components/Footer'; | ||
|
|
||
| export const App: React.FC = () => { | ||
| const [loaded, setLoaded] = useState<{ evidence: EvidenceData; facts: Facts } | null>(null); | ||
| export interface AppProps { | ||
| initialData?: { evidence: EvidenceData; facts: Facts }; | ||
| } | ||
|
|
||
| export const App: React.FC<AppProps> = ({ initialData }) => { | ||
| const [loaded, setLoaded] = useState<{ evidence: EvidenceData; facts: Facts } | null>( | ||
| () => initialData ?? null, | ||
| ); | ||
| const [error, setError] = useState<string | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| let active = true; | ||
|
|
||
| async function loadEvidence() { | ||
| let res: Response; | ||
| try { | ||
| const res = await fetch('data/evidence.json'); | ||
| res = await fetch('data/evidence.json'); | ||
| if (!res.ok) { | ||
| throw new SnapshotError(`Failed to load evidence.json: HTTP ${res.status}`); | ||
| } | ||
| } catch (err) { | ||
| // A network failure says nothing about the evidence. If the prerendered report is | ||
| // already up, and its embedded snapshot passed validation, keep showing it. | ||
| if (active && !initialData) { | ||
| setError(err instanceof Error ? err.message : String(err)); | ||
| } | ||
| return; | ||
| } | ||
| // Evidence that arrives but fails validation still replaces the page with the error. | ||
| try { | ||
|
Comment on lines
+45
to
+46
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep the report when reading the response body fails. If the connection fails after successful response headers, That rejection reaches the second catch, which sets Read the body with
|
||
| const evidence = validateEvidence(await res.json()); | ||
| const facts = summarize(evidence); | ||
| if (active) { | ||
|
|
@@ -43,7 +60,7 @@ export const App: React.FC = () => { | |
| return () => { | ||
| active = false; | ||
| }; | ||
| }, []); | ||
| }, [initialData]); | ||
|
|
||
| if (error) { | ||
| return <SnapshotProblem message={error} />; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,10 @@ | ||
| import { StrictMode } from 'react'; | ||
| import { createRoot } from 'react-dom/client'; | ||
| import { createRoot, hydrateRoot } from 'react-dom/client'; | ||
| import App from './App'; | ||
| import { applyTheme, initialTheme } from './theme'; | ||
| import { validateEvidence } from './data/validate'; | ||
| import { summarize } from './data/facts'; | ||
| import type { EvidenceData } from './data/contracts'; | ||
| import './styles/base.css'; | ||
|
|
||
| const root = document.getElementById('root'); | ||
|
|
@@ -10,8 +13,29 @@ if (!root) throw new Error('root element missing'); | |
| // Before the first paint, so the loading and error states follow the reader's theme too. | ||
| applyTheme(initialTheme()); | ||
|
|
||
| createRoot(root).render( | ||
| <StrictMode> | ||
| <App /> | ||
| </StrictMode>, | ||
| ); | ||
| let initialData: { evidence: EvidenceData; facts: ReturnType<typeof summarize> } | undefined; | ||
| const embedded = document.getElementById('__OVL_EVIDENCE__'); | ||
| if (embedded?.textContent) { | ||
| try { | ||
| const evidence = validateEvidence(JSON.parse(embedded.textContent)); | ||
| const facts = summarize(evidence); | ||
| initialData = { evidence, facts }; | ||
| } catch { | ||
| // If embedded snapshot is invalid or missing, App falls back to client fetch. | ||
| } | ||
| } | ||
|
|
||
| if (root.hasChildNodes() && initialData) { | ||
| hydrateRoot( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use the same first-render theme on the server and client. For a reader with Initialize Header with the prerendered theme. Read the saved preference after mount, and do not persist the default before that read. The early theme application to
|
||
| root, | ||
| <StrictMode> | ||
| <App initialData={initialData} /> | ||
| </StrictMode>, | ||
| ); | ||
| } else { | ||
| createRoot(root).render( | ||
| <StrictMode> | ||
| <App initialData={initialData} /> | ||
| </StrictMode>, | ||
| ); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -43,6 +43,31 @@ test.describe('OpenVerifiableLLM Site', () => { | |
| await expect(page.getByText('541d49c97b87cd4ed0acb90b4327535ee20b8c11c452e2583d460154e9d980de')).toBeVisible(); | ||
| }); | ||
|
|
||
| test('with JavaScript disabled, the prerendered page renders all sections and content', async ({ browser }) => { | ||
| const context = await browser.newContext({ javaScriptEnabled: false }); | ||
| const page = await context.newPage(); | ||
| await page.goto('/'); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Build the site before the Playwright run.
Make
Suggested fix
|
||
|
|
||
| // Verify key headings and intro are visible without JS | ||
| await expect(page.getByRole('heading', { level: 1 })).toHaveText('OpenVerifiableLLM'); | ||
| await expect(page.getByText(/is a language model whose training anyone can recompute/)).toBeVisible(); | ||
| await expect(page.getByRole('complementary', { name: 'Key facts' }).first()).toBeVisible(); | ||
|
|
||
| // Verify all primary sections are present in static HTML | ||
| await expect(page.locator('#how')).toBeVisible(); | ||
| await expect(page.locator('#overview')).toBeVisible(); | ||
| await expect(page.locator('#timeline')).toBeVisible(); | ||
| await expect(page.locator('#check')).toBeVisible(); | ||
| await expect(page.locator('#downloads')).toBeVisible(); | ||
| await expect(page.locator('#faq')).toBeVisible(); | ||
|
|
||
| // Verify evidence numbers are rendered | ||
| await expect(page.getByText('7,232,582', { exact: true })).toBeVisible(); | ||
| await expect(page.getByText('Project: 37 / 37 matched')).toBeVisible(); | ||
|
|
||
| await context.close(); | ||
| }); | ||
|
|
||
| test('copy button provides visual feedback and clipboard content', async ({ page, context }) => { | ||
| await context.grantPermissions(['clipboard-read', 'clipboard-write']); | ||
| await page.goto('/'); | ||
|
|
@@ -72,7 +97,7 @@ test.describe('OpenVerifiableLLM Site', () => { | |
|
|
||
| test('a stored dark theme applies before the evidence loads, and on the error page', async ({ page }) => { | ||
| await page.addInitScript(() => localStorage.setItem('ovl-theme', 'dark')); | ||
| await page.route('**/data/evidence.json', route => route.fulfill({ status: 500, body: '{}' })); | ||
| await page.route('**/data/evidence.json', route => route.fulfill({ json: {} })); | ||
| await page.goto('/'); | ||
| await expect(page.getByRole('alert')).toBeVisible(); | ||
| await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark'); | ||
|
|
@@ -221,21 +246,43 @@ test.describe('OpenVerifiableLLM Site', () => { | |
| expect(inView).toBe(true); | ||
| }); | ||
|
|
||
| test('handles snapshot load errors gracefully', async ({ page }) => { | ||
| await page.route('**/data/evidence.json', (route) => { | ||
| route.fulfill({ | ||
| status: 500, | ||
| contentType: 'application/json', | ||
| body: JSON.stringify({ error: 'Internal Server Error' }), | ||
| }); | ||
| }); | ||
| test('keeps the prerendered report when evidence.json cannot be fetched', async ({ page }) => { | ||
| await page.route('**/data/evidence.json', route => | ||
| route.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ error: 'Internal Server Error' }) }), | ||
| ); | ||
| await page.goto('/'); | ||
| await expect(page.getByRole('heading', { level: 1 })).toHaveText('OpenVerifiableLLM'); | ||
| await expect(page.getByText('Project: 37 / 37 matched')).toBeVisible(); | ||
| await page.waitForTimeout(500); | ||
| await expect(page.getByRole('alert')).toHaveCount(0); | ||
| }); | ||
|
|
||
| test('replaces the page with the error when the fetched evidence is invalid', async ({ page }) => { | ||
| await page.route('**/data/evidence.json', route => route.fulfill({ json: { error: 'not evidence' } })); | ||
| await page.goto('/'); | ||
| await expect(page.getByRole('alert')).toBeVisible(); | ||
| await expect(page.getByRole('heading', { level: 1, name: 'Snapshot unavailable or invalid' })).toBeVisible(); | ||
| await expect(page.getByRole('button', { name: 'Retry loading snapshot' })).toBeVisible(); | ||
| }); | ||
|
|
||
| for (const saved of [null, 'light', 'dark'] as const) { | ||
| test(`hydrates without errors when the saved theme is ${saved ?? 'unset'}`, async ({ page }) => { | ||
| const errors: string[] = []; | ||
| page.on('pageerror', error => errors.push(error.message)); | ||
| page.on('console', message => { | ||
| if (message.type() === 'error') errors.push(message.text()); | ||
| }); | ||
| if (saved) await page.addInitScript(theme => localStorage.setItem('ovl-theme', theme), saved); | ||
| await page.goto('/'); | ||
| const expected = saved === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'; | ||
| await expect(page.getByRole('button', { name: expected })).toBeVisible(); | ||
| if (saved === 'dark') await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark'); | ||
| else await expect(page.locator('html')).not.toHaveAttribute('data-theme', 'dark'); | ||
| await page.waitForTimeout(500); | ||
| expect(errors).toEqual([]); | ||
| }); | ||
| } | ||
|
|
||
| const viewports = [ | ||
| { name: 'desktop', width: 1440, height: 900 }, | ||
| { name: 'laptop', width: 1024, height: 768 }, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keep the report visible when the snapshot request fails.
initialDataalready contains validated evidence. The mount effect still requestsdata/evidence.json. If that request returns HTTP 503,errortakes precedence overloadedand replaces the report withSnapshotProblem.Skip the request when
initialDatais present. Keep the existing fetch and error handling for client-only loads withoutinitialData.