From a23a4b5b4821f57d9a314b5e3d70dbeb546dd7bf Mon Sep 17 00:00:00 2001 From: Mudit Gupta Date: Thu, 19 Nov 2026 22:08:51 +0400 Subject: [PATCH 1/9] fix(web): versions from before a document went live open in the version viewer History listed every version, but selecting one from before the document went live asked for a Y.Doc that was never captured, so it showed 'not found'. The versions list now says which versions are bundled checkpoints; selecting an older one opens it in the legacy read-only viewer, which already renders its stored HTML. Co-Authored-By: Claude Sonnet 5.5 --- apps/api/src/live/checkpoint.test.ts | 18 +++++++++++++++ apps/api/src/routes/documents.ts | 2 ++ apps/web/src/live/LiveEditor.tsx | 6 +++-- apps/web/src/live/versionStorage.test.ts | 29 ++++++++++++++++++++++++ apps/web/src/live/versionStorage.ts | 20 +++++++++++++++- apps/web/src/routes/document.tsx | 4 +++- packages/api-types/src/index.ts | 3 +++ 7 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 apps/web/src/live/versionStorage.test.ts diff --git a/apps/api/src/live/checkpoint.test.ts b/apps/api/src/live/checkpoint.test.ts index 8464083f..4b2af71c 100644 --- a/apps/api/src/live/checkpoint.test.ts +++ b/apps/api/src/live/checkpoint.test.ts @@ -139,6 +139,24 @@ describe('checkpoints', () => { }); }); + it('versions from before the document went live are listed as not bundled', async () => { + await withStorage(async (storage) => { + const app = createApp({ storage, notifier: new NoopNotifier() }); + const legacy = await publish(storage, { content: '

Before live.

', format: 'html' }); + const live = await publish(storage, { content: SOURCE, format: 'markdown', documentId: legacy.documentId }); + const list = (await (await app.request(`/api/documents/${legacy.documentId}/versions`)).json()) as { + versions: { id: string; versionNumber: number; bundled?: boolean }[]; + }; + const byNumber = new Map(list.versions.map((v) => [v.versionNumber, v])); + expect(byNumber.get(legacy.versionNumber)!.bundled).toBe(false); + expect(byNumber.get(live.versionNumber)!.bundled).toBe(true); + // The old version has no Y.Doc to preview, but its HTML still renders. + expect((await app.request(`/api/versions/${legacy.versionId}/ydoc`)).status).toBe(404); + const html = await app.request(`/api/versions/${legacy.versionId}/content`); + expect(await html.text()).toContain('Before live.'); + }); + }); + it('compare diffs the Markdown exports', async () => { await withStorage(async (storage) => { const app = createApp({ storage, notifier: new NoopNotifier() }); diff --git a/apps/api/src/routes/documents.ts b/apps/api/src/routes/documents.ts index cbc3da03..4bf1cc3c 100644 --- a/apps/api/src/routes/documents.ts +++ b/apps/api/src/routes/documents.ts @@ -342,6 +342,7 @@ export function registerDocumentRoutes( versionNote: versions.versionNote, sizeBytes: versions.sizeBytes, createdAt: versions.createdAt, + bundleKey: versions.bundleKey, }) .from(versions) .where(eq(versions.documentId, docId)) @@ -355,6 +356,7 @@ export function registerDocumentRoutes( versionNote: r.versionNote, sizeBytes: r.sizeBytes, createdAt: r.createdAt.toISOString(), + bundled: r.bundleKey !== null, })), }, 200 diff --git a/apps/web/src/live/LiveEditor.tsx b/apps/web/src/live/LiveEditor.tsx index 0039491e..70862bee 100644 --- a/apps/web/src/live/LiveEditor.tsx +++ b/apps/web/src/live/LiveEditor.tsx @@ -21,6 +21,8 @@ export type LiveEditorProps = { theme: 'light' | 'dark'; /** Shown on this viewer's cursor to everyone else. */ userName: string; + /** Opens a version from before the document went live in the version viewer. */ + onOpenLegacyVersion?: (versionNumber: number) => void; }; /** @@ -58,7 +60,7 @@ function LiveEditorView(props: LiveEditorProps & { live: LiveProvider }) { ); } -function TabEditor({ live, tabId, documentId, readOnly, theme, userName }: LiveEditorProps & { live: LiveProvider; tabId: string }) { +function TabEditor({ live, tabId, documentId, readOnly, theme, userName, onOpenLegacyVersion }: LiveEditorProps & { live: LiveProvider; tabId: string }) { const [historyOpen, setHistoryOpen] = useState(false); const editor = useCreateBlockNote( @@ -66,7 +68,7 @@ function TabEditor({ live, tabId, documentId, readOnly, theme, userName }: LiveE schema: primerSchema, // Until comments ship, the comment mark must still be known, or // y-prosemirror would delete commented text. - extensions: [commentMarkExtension, YjsVersioningExtension({ storage: new PrimerVersionStorage(documentId) })], + extensions: [commentMarkExtension, YjsVersioningExtension({ storage: new PrimerVersionStorage(documentId, onOpenLegacyVersion) })], collaboration: { provider: { awareness: live.provider.awareness ?? undefined }, fragment: live.doc.getXmlFragment(tabFragmentName(tabId)), diff --git a/apps/web/src/live/versionStorage.test.ts b/apps/web/src/live/versionStorage.test.ts new file mode 100644 index 00000000..9fcaddd8 --- /dev/null +++ b/apps/web/src/live/versionStorage.test.ts @@ -0,0 +1,29 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { PrimerVersionStorage } from './versionStorage.ts'; + +afterEach(() => vi.unstubAllGlobals()); + +describe('version history', () => { + it('a version from before the document went live opens in the version viewer', async () => { + const urls: string[] = []; + vi.stubGlobal('fetch', async (input: RequestInfo | URL) => { + urls.push(String(input)); + return Response.json({ + versions: [ + { id: 'v2', versionNumber: 2, versionNote: null, sizeBytes: 1, createdAt: '2026-11-19T00:00:00Z', bundled: true }, + { id: 'v1', versionNumber: 1, versionNote: null, sizeBytes: 1, createdAt: '2026-11-18T00:00:00Z', bundled: false }, + ], + }); + }); + const opened: number[] = []; + const storage = new PrimerVersionStorage('doc-1', (n) => opened.push(n)); + const listed = await storage.list(new AbortController().signal); + expect(listed.ok && listed.value.snapshots.map((s) => s.id)).toEqual(['v2', 'v1']); + + const abort = new AbortController(); + void storage.getContent('v1', abort.signal).catch(() => undefined); + abort.abort(); + expect(opened).toEqual([1]); + expect(urls.some((u) => u.includes('/ydoc'))).toBe(false); + }); +}); diff --git a/apps/web/src/live/versionStorage.ts b/apps/web/src/live/versionStorage.ts index acdf43fe..4e434d90 100644 --- a/apps/web/src/live/versionStorage.ts +++ b/apps/web/src/live/versionStorage.ts @@ -14,14 +14,26 @@ import { api } from '../lib/fetch.ts'; * BlockNote previews in a fork of the document. Saving names the checkpoint * with its note; restoring is a new edit made by the server. Versions are * never deleted, so `remove` is left out. + * + * Versions from before the document went live have no Y.Doc to preview. They + * stay in the list, and selecting one hands its number to `openLegacy`, which + * shows it in the read-only version viewer (rendered HTML in its sandboxed + * frame), the same as for any legacy document. */ export class PrimerVersionStorage implements VersionStorage { - constructor(private readonly documentId: string) {} + private readonly legacy = new Map(); + + constructor( + private readonly documentId: string, + private readonly openLegacy: (versionNumber: number) => void = () => undefined, + ) {} async list(signal: AbortSignal): Promise> { const res = await call(`/api/documents/${this.documentId}/versions`, { signal }); if (!res.ok) return res; const body = (await res.value.json()) as VersionsListResponse; + this.legacy.clear(); + for (const v of body.versions) if (v.bundled === false) this.legacy.set(v.id, v.versionNumber); return { ok: true, value: { @@ -36,6 +48,12 @@ export class PrimerVersionStorage implements VersionStorage { } async getContent(id: string, signal: AbortSignal): Promise> { + const legacyNumber = this.legacy.get(id); + if (legacyNumber !== undefined) { + this.openLegacy(legacyNumber); + // The viewer replaces the editor, so this preview never settles. + return new Promise((_, reject) => signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))); + } const res = await call(`/api/versions/${id}/ydoc`, { signal }); if (!res.ok) return res; return { ok: true, value: new Uint8Array(await res.value.arrayBuffer()) }; diff --git a/apps/web/src/routes/document.tsx b/apps/web/src/routes/document.tsx index a2183ed3..2c04b1f3 100644 --- a/apps/web/src/routes/document.tsx +++ b/apps/web/src/routes/document.tsx @@ -96,12 +96,13 @@ export function DocumentSurface(props: { readOnly: boolean; theme: 'light' | 'dark'; userName: string; + onOpenLegacyVersion?: (versionNumber: number) => void; frame: () => ReactNode; }) { if (!props.live) return <>{props.frame()}; return ( Loading editor…}> - + ); } @@ -1033,6 +1034,7 @@ function DocumentPageInner() { readOnly={!canEdit} theme={theme} userName={me.data?.displayName ?? 'Someone'} + onOpenLegacyVersion={(n) => navigate(`/d/${docId}/v/${n}`)} frame={() => currentVersionId && ( Date: Thu, 19 Nov 2026 22:11:34 +0400 Subject: [PATCH 2/9] feat: print and PDF, and a static rendering that follows light and dark The static rendering (a checkpoint's static.html) carried BlockNote's structural CSS but no colours, so a share or a checkpoint view in dark mode was dark text on white. It now has a small stylesheet that follows the companion's data-theme in Primer and the viewer's colour scheme on a share. Print / PDF is /d/:docId/print: a sandboxed frame on /api/documents/:docId/print, which serves a checkpoint's static.html (or the live state, rendered by the same code) with a print stylesheet and a script that opens the print dialog; print is always light. A test pins that a share link of a live document serves the published checkpoint, not live state. Co-Authored-By: Claude Sonnet 5.5 --- apps/api/src/auth/scopes.ts | 1 + apps/api/src/live/bundle.ts | 37 +++++++++++++--- apps/api/src/live/checkpoint.test.ts | 23 ++++++++++ apps/api/src/live/export.ts | 28 ++++++++++++- apps/api/src/routes/documents.ts | 41 +++++++++++++++++- apps/api/src/routes/externalShare.test.ts | 51 +++++++++++++++++++++++ apps/web/src/App.tsx | 2 + apps/web/src/components/HeaderActions.tsx | 6 ++- apps/web/src/lib/documentActionsMenu.ts | 2 + apps/web/src/routes/document.tsx | 7 +++- apps/web/src/routes/print.tsx | 35 ++++++++++++++++ 11 files changed, 224 insertions(+), 9 deletions(-) create mode 100644 apps/web/src/routes/print.tsx diff --git a/apps/api/src/auth/scopes.ts b/apps/api/src/auth/scopes.ts index 19d1cb42..1379181f 100644 --- a/apps/api/src/auth/scopes.ts +++ b/apps/api/src/auth/scopes.ts @@ -38,6 +38,7 @@ export const ROUTE_SCOPES: readonly ScopedRoute[] = [ { method: 'GET', path: '/api/events/stream', scope: 'documents:read' }, { method: 'GET', path: '/api/documents/:documentId/status', scope: 'documents:read' }, { method: 'GET', path: '/api/documents/:docId/export', scope: 'documents:read', upcoming: true }, + { method: 'GET', path: '/api/documents/:docId/print', scope: 'documents:read' }, { method: 'GET', path: '/api/versions/:versionId/ydoc', scope: 'documents:read', upcoming: true }, { method: 'GET', path: '/api/files/:fileId', scope: 'documents:read', upcoming: true }, diff --git a/apps/api/src/live/bundle.ts b/apps/api/src/live/bundle.ts index 8235bc62..6edadef6 100644 --- a/apps/api/src/live/bundle.ts +++ b/apps/api/src/live/bundle.ts @@ -42,6 +42,35 @@ export function exportFileOf(format: string): 'export.md' | 'export.txt' { return format === 'text' ? 'export.txt' : 'export.md'; } +/** The static rendering of a document state, served like any version's content. */ +export async function renderStatic(doc: Y.Doc, title: string): Promise<{ html: string; served: string }> { + const html = await exportHtml(doc, title); + const served = transformHtml(html, { themeManaged: true }); + if (!served.ok) throw new Error(`static rendering failed: ${served.message}`); + return { html, served: served.html }; +} + +const PRINT_CSS = + '@page{margin:16mm}html,body{background:#fff!important;color:#000!important}a{color:inherit}' + + 'h1,h2,h3,h4{break-after:avoid}img,table,pre,blockquote{break-inside:avoid}'; + +// Runs in the sandboxed frame (the only place a served page can open the print +// dialog): once loaded, and again whenever the host asks. +const PRINT_JS = + "(function(){var go=function(){setTimeout(function(){window.print()},150)};" + + "if(document.readyState==='complete')go();else addEventListener('load',go);" + + "addEventListener('message',function(e){if(e.source===parent&&e.data==='primer:print')window.print()})})();"; + +/** A static rendering made printable: light colours, page margins, and a script that opens the print dialog. */ +export function printable(staticHtml: string): string { + const head = staticHtml.lastIndexOf(''); + const body = staticHtml.lastIndexOf(''); + if (head < 0 || body < 0) throw new Error('static rendering has no head or body'); + return ( + staticHtml.slice(0, head) + `` + staticHtml.slice(head, body) + `` + staticHtml.slice(body) + ); +} + export async function renderBundle( storage: Storage, opts: { versionId: string; documentId: string; title: string; state: Uint8Array }, @@ -50,15 +79,13 @@ export async function renderBundle( Y.applyUpdate(doc, opts.state); try { const { format } = trustedMeta(doc, opts.documentId); - const html = await exportHtml(doc, opts.title); - const served = transformHtml(html, { themeManaged: true }); - if (!served.ok) throw new Error(`static rendering failed: ${served.message}`); + const { html, served } = await renderStatic(doc, opts.title); const exported = format === 'text' ? exportText(doc, opts.documentId) : await exportMarkdown(doc, opts.documentId); const files: Record = { 'state.ydoc': opts.state, [exportFileOf(format)]: exported, 'export.html': html, - 'static.html': served.html, + 'static.html': served, 'threads.json': JSON.stringify(await openThreads(opts.documentId)), 'files.json': JSON.stringify(await referencedFiles(doc, opts.documentId)), }; @@ -73,7 +100,7 @@ export async function renderBundle( if (name === 'static.html') staticBytes = bytes.byteLength; await storage.put(key + name, bytes); } - return { bundleKey: key, staticKey: `${key}static.html`, staticBytes, staticHtml: served.html }; + return { bundleKey: key, staticKey: `${key}static.html`, staticBytes, staticHtml: served }; } finally { doc.destroy(); } diff --git a/apps/api/src/live/checkpoint.test.ts b/apps/api/src/live/checkpoint.test.ts index 4b2af71c..320aaf01 100644 --- a/apps/api/src/live/checkpoint.test.ts +++ b/apps/api/src/live/checkpoint.test.ts @@ -157,6 +157,29 @@ describe('checkpoints', () => { }); }); + it('print renders the checkpoint or the live state, light and sandboxed', async () => { + await withStorage(async (storage) => { + const app = createApp({ storage, notifier: new NoopNotifier() }); + const { documentId } = await publish(storage, { content: SOURCE, format: 'markdown' }); + const checkpoint = (await (await app.request(`/api/documents/${documentId}/checkpoints`, { method: 'POST', headers: CSRF_HEADERS })).json()) as CheckpointResponse; + await setText(documentId, 'Then tabs.', 'Then tabs, and comments.'); + + const frozen = await app.request(`/api/documents/${documentId}/print?version=${checkpoint.versionNumber}`); + expect(frozen.status).toBe(200); + const frozenHtml = await frozen.text(); + expect(frozenHtml).toContain('Then tabs.'); + expect(frozenHtml).not.toContain('and comments'); + expect(frozenHtml).toContain('window.print()'); + expect(frozenHtml).toContain('@page'); + expect(frozen.headers.get('content-security-policy')).toContain("connect-src 'none'"); + + const live = await (await app.request(`/api/documents/${documentId}/print`)).text(); + expect(live).toContain('Then tabs, and comments.'); + + expect((await app.request(`/api/documents/${documentId}/print?version=99`)).status).toBe(404); + }); + }); + it('compare diffs the Markdown exports', async () => { await withStorage(async (storage) => { const app = createApp({ storage, notifier: new NoopNotifier() }); diff --git a/apps/api/src/live/export.ts b/apps/api/src/live/export.ts index 8a79b86d..50ad69f4 100644 --- a/apps/api/src/live/export.ts +++ b/apps/api/src/live/export.ts @@ -60,7 +60,7 @@ export async function exportHtml(doc: Y.Doc, title = ''): Promise { } return ( '' + - `${escapeHtml(title)}` + + `${escapeHtml(title)}` + `
${body}
` ); } @@ -199,6 +199,32 @@ export function plainText(block: PrimerBlock): string { return [own, ...children].filter((t) => t.length > 0).join('\n'); } +/** + * What the static rendering needs beyond BlockNote's structural stylesheet, + * which ships no colours: a readable page, and light or dark to match + * wherever it is shown. In Primer the companion sets `data-theme` on ``; + * a share opened on its own follows the viewer's colour scheme. + */ +const STATIC_CSS = ` +body{margin:0;padding:24px 16px;background:#fff;color:#171717;font-family:Inter,system-ui,-apple-system,"Segoe UI",sans-serif} +.bn-container{max-width:760px;margin:0 auto} +.primer-tab-title{margin:2.2em 0 .6em} +a{color:#6d28d9} +pre,code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace} +table{border-collapse:collapse}td,th{border:1px solid #d4d4d4;padding:4px 8px} +img,video{max-width:100%} +.primer-chip{border-radius:4px;background:#ede9fe;color:#4c1d95;padding:0 4px} +html[data-theme="dark"] body{background:#0a0a0a;color:#e5e5e5} +html[data-theme="dark"] a{color:#c4b5fd} +html[data-theme="dark"] td,html[data-theme="dark"] th{border-color:#404040} +html[data-theme="dark"] .primer-chip{background:#3b2a6b;color:#ddd6fe} +@media (prefers-color-scheme: dark){ +html:not([data-theme]) body{background:#0a0a0a;color:#e5e5e5} +html:not([data-theme]) a{color:#c4b5fd} +html:not([data-theme]) td,html:not([data-theme]) th{border-color:#404040} +html:not([data-theme]) .primer-chip{background:#3b2a6b;color:#ddd6fe} +}`; + let css: string | null = null; function blocknoteCss(): string { css ??= readFileSync(createRequire(import.meta.url).resolve('@blocknote/core/style.css'), 'utf8'); diff --git a/apps/api/src/routes/documents.ts b/apps/api/src/routes/documents.ts index 4bf1cc3c..2c6568f5 100644 --- a/apps/api/src/routes/documents.ts +++ b/apps/api/src/routes/documents.ts @@ -8,7 +8,7 @@ import type { CheckpointResponse, DocFileUploadResponse, ExportFormat, Refusal, RestoreCheckpointResponse, } from '@polygonlabs/primer-api-types'; import { docFiles, documents, versions, users } from '../db/schema.ts'; -import { exportFileOf, readBundleFile } from '../live/bundle.ts'; +import { exportFileOf, printable, readBundleFile, renderStatic } from '../live/bundle.ts'; import { createCheckpoint, restoreCheckpoint } from '../live/checkpoint.ts'; import { exportHtml, exportMarkdown, exportText } from '../live/export.ts'; import { withLiveDocument } from '../live/instance.ts'; @@ -16,6 +16,7 @@ import { ensureSigningKey } from '../live/signing.ts'; import { MAX_BYTES } from '../upload/validate.ts'; import { db } from '../db/client.ts'; import { actorName } from '../lib/actors.ts'; +import { artifactCsp } from '../lib/pagePolicy.ts'; import { logger } from '../logger.ts'; import { validateUpload } from '../upload/validate.ts'; import { @@ -512,6 +513,44 @@ export function registerDocumentRoutes( }); }); + // The page behind "Print / PDF" (M10d): the static rendering, made printable + // and served like any version's content (sandboxed frame, artifact CSP). + // Without `?version=` it renders the live state now, by the same code that + // renders a checkpoint's `static.html`; with it, that checkpoint's bundle. + app.get('/api/documents/:docId/print', async (c) => { + const docId = c.req.param('docId'); + const access = await docAccess(docId, c.get('user')); + if (!access) return c.json({ error: 'not_found' }, 404); + if (!access.format) return notLive(c); + const versionParam = c.req.query('version'); + let html: string; + if (versionParam !== undefined) { + const number = Number(versionParam); + const [version] = Number.isInteger(number) + ? await db + .select({ bundleKey: versions.bundleKey }) + .from(versions) + .where(and(eq(versions.documentId, docId), eq(versions.versionNumber, number))) + : []; + if (!version?.bundleKey) return c.json({ error: 'not_found' }, 404); + html = new TextDecoder().decode(await readBundleFile(deps.storage, version.bundleKey, 'static.html')); + } else { + await ensureSigningKey(deps.storage); + html = (await withLiveDocument(docId, (doc) => renderStatic(doc, access.title))).served; + } + return new Response(printable(html), { + status: 200, + headers: { + 'content-type': 'text/html; charset=utf-8', + 'content-security-policy': artifactCsp('standard'), + 'x-frame-options': 'SAMEORIGIN', + 'x-content-type-options': 'nosniff', + 'referrer-policy': 'no-referrer', + 'cache-control': 'private, no-store', + }, + }); + }); + // A file placed in a live document (image, video, audio, file blocks). The // document stores the opaque `primer-blob://`, never a link. app.post('/api/documents/:docId/files', async (c) => { diff --git a/apps/api/src/routes/externalShare.test.ts b/apps/api/src/routes/externalShare.test.ts index ccb4fe36..603ed59b 100644 --- a/apps/api/src/routes/externalShare.test.ts +++ b/apps/api/src/routes/externalShare.test.ts @@ -16,6 +16,12 @@ import { generateShareToken } from '../external/tokens.ts'; import { _resetRateLimiterForTests } from '../lib/rateLimiter.ts'; import { artifactCsp } from '../lib/pagePolicy.ts'; import { CSRF_HEADERS } from '../test/harness.ts'; +import { MOCK_USER } from '../auth/resolver.ts'; +import { publishDocument } from '../lib/publish.ts'; +import { readBlocks } from '../live/editor.ts'; +import { withLiveDoc } from '../live/live.testlib.ts'; +import { originFor } from '../live/origin.ts'; +import { applyPlan } from '../live/pipeline.ts'; class CaptureNotifier extends NoopNotifier { override readonly emailEnabled = true; @@ -188,6 +194,51 @@ describe('external share public routes', () => { } finally { await rm(f.root, { recursive: true, force: true }); } }); + it('share link of a live doc serves the published checkpoint, not live state', async () => { + const f = await fixture(); + try { + const storage = new FilesystemStorage(f.root); + const published = await publishDocument(storage, { + actor: MOCK_USER, + title: 'Live plan', + filename: 'plan.md', + format: 'markdown', + content: new TextEncoder().encode('# Plan\n\nShip the editor first.\n'), + }); + if (!published.ok) throw new Error('publish refused'); + const checkpoint = await f.app.request(`/api/documents/${published.documentId}/checkpoints`, { method: 'POST', headers: CSRF_HEADERS }); + const { versionId } = (await checkpoint.json()) as { versionId: string }; + + // The document moves on after the share was published. + const blockId = await withLiveDoc(published.documentId, (doc) => readBlocks(doc, 'main').find((b) => JSON.stringify(b.content).includes('Ship'))!.id); + await applyPlan(published.documentId, originFor(MOCK_USER), { + onConflict: 'refuse', + edits: [{ + target: { tabId: 'main', blockId }, + inverse: false, + build: (tr, at) => { + tr.replaceWith(at!.pos + 2, at!.pos + at!.node.firstChild!.nodeSize, tr.doc.type.schema.text('Secret draft change.')); + }, + }], + }); + + const shareToken = generateShareToken(); + const shareId = uuidv7(); + await db.insert(externalShares).values({ id: shareId, documentId: published.documentId, shareToken, createdBy: 'mock-user-1', publishedVersionId: versionId }); + await db.insert(externalRecipients).values({ + id: uuidv7(), shareId, email: 'client@example.com', addedBy: 'mock-user-1', + expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), + }); + const cookie = await authenticate({ ...f, shareToken }); + const content = await f.app.request(`/api/share/${shareToken}/content`, { headers: { cookie } }); + expect(content.status).toBe(200); + const html = await content.text(); + expect(html).toContain('Ship the editor first.'); + expect(html).not.toContain('Secret draft change.'); + expect(content.headers.get('content-security-policy')).toBe(artifactCsp('standard')); + } finally { await rm(f.root, { recursive: true, force: true }); } + }); + it('content without a session 302s to the branded landing page', async () => { const f = await fixture(); try { diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 112be00a..39016e2a 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -11,9 +11,11 @@ import { NotFoundPage } from './routes/notFound.tsx'; import CompareSelectPage from './routes/compareSelect.tsx'; import ComparePage from './routes/compare.tsx'; import { SharePage } from './routes/share.tsx'; +import { PrintPage } from './routes/print.tsx'; const router = createBrowserRouter([ { path: '/share/:shareToken', element: }, + { path: '/d/:docId/print', element: }, { element: , children: [ diff --git a/apps/web/src/components/HeaderActions.tsx b/apps/web/src/components/HeaderActions.tsx index 914f7df1..b1b49f00 100644 --- a/apps/web/src/components/HeaderActions.tsx +++ b/apps/web/src/components/HeaderActions.tsx @@ -33,7 +33,7 @@ interface Props { /** Live documents: saves a checkpoint of the current state. */ onSaveCheckpoint?: () => Promise; /** Live documents: downloads the content in a format. */ - onExport?: (format: 'markdown' | 'html') => void; + onExport?: (format: 'markdown' | 'html' | 'print') => void; } type MenuState = 'closed' | 'menu' | 'confirm'; @@ -141,6 +141,10 @@ export function HeaderActions({ setMenuState('closed'); onExport?.('html'); }, + 'export-print': () => { + setMenuState('closed'); + onExport?.('print'); + }, delete: () => setMenuState('confirm'), }; diff --git a/apps/web/src/lib/documentActionsMenu.ts b/apps/web/src/lib/documentActionsMenu.ts index 395df202..4d59f943 100644 --- a/apps/web/src/lib/documentActionsMenu.ts +++ b/apps/web/src/lib/documentActionsMenu.ts @@ -4,6 +4,7 @@ export type MenuItemId = | 'download-html' | 'export-markdown' | 'export-html' + | 'export-print' | 'notebooklm' | 'copy' | 'download' @@ -36,6 +37,7 @@ export function buildMenuItems({ isUploader, includeShare = false, live = false items.push( { id: 'export-markdown', label: 'Export Markdown' }, { id: 'export-html', label: 'Export HTML' }, + { id: 'export-print', label: 'Print / PDF' }, { id: 'separator' }, ); } diff --git a/apps/web/src/routes/document.tsx b/apps/web/src/routes/document.tsx index 2c04b1f3..66c0aab2 100644 --- a/apps/web/src/routes/document.tsx +++ b/apps/web/src/routes/document.tsx @@ -839,7 +839,12 @@ function DocumentPageInner() { return { kind: 'success', message: `Checkpoint v${checkpoint.versionNumber} saved` }; } - function exportAs(format: 'markdown' | 'html') { + function exportAs(format: 'markdown' | 'html' | 'print') { + if (format === 'print') { + const version = requestedNumber !== undefined ? `?version=${requestedNumber}` : ''; + window.open(`/d/${docId}/print${version}`, '_blank', 'noopener,noreferrer'); + return; + } const params = new URLSearchParams({ format: format === 'html' ? 'html' : document.format === 'text' ? 'text' : 'markdown' }); if (requestedNumber !== undefined) params.set('version', String(requestedNumber)); const a = window.document.createElement('a'); diff --git a/apps/web/src/routes/print.tsx b/apps/web/src/routes/print.tsx new file mode 100644 index 00000000..db658067 --- /dev/null +++ b/apps/web/src/routes/print.tsx @@ -0,0 +1,35 @@ +import { useRef } from 'react'; +import { useParams, useSearchParams } from 'react-router-dom'; +import { useDocumentTitle } from '../lib/useDocumentTitle.ts'; +import { extractCanonicalDocId } from '../lib/docIdParam.ts'; + +/** + * "Print / PDF" for a live document: the server's static rendering in a + * sandboxed frame, which opens the browser's print dialog once it has loaded + * (the frame is the only place a served page may do that). The page's own + * chrome never prints; the button asks the frame to print again. + */ +export function PrintPage() { + const { docId: raw = '' } = useParams(); + const [params] = useSearchParams(); + const docId = extractCanonicalDocId(raw); + const frame = useRef(null); + useDocumentTitle('Print'); + if (!docId) return null; + const version = params.get('version'); + const src = `/api/documents/${docId}/print${version ? `?version=${encodeURIComponent(version)}` : ''}`; + return ( +
+
+ +
+