@open-document/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -0
  3. package/README.zh-TW.md +50 -0
  4. package/bin.js +2 -0
  5. package/dist/build-BWZJ1gvL.js +18 -0
  6. package/dist/cli/bin.d.ts +1 -0
  7. package/dist/cli/bin.js +86 -0
  8. package/dist/config-DBp4mOOf.js +1121 -0
  9. package/dist/config-EBFfKtWH.d.ts +17 -0
  10. package/dist/design-BJLvOcCO.js +53 -0
  11. package/dist/dev-CZtw1oqs.js +24 -0
  12. package/dist/edit-ops-DSdUroVO.js +1225 -0
  13. package/dist/index.d.ts +206 -0
  14. package/dist/index.js +240 -0
  15. package/dist/ops/index.d.ts +160 -0
  16. package/dist/ops/index.js +202 -0
  17. package/dist/preview-DUfQl7Ij.js +23 -0
  18. package/dist/sync-6GTPAt2t.js +86 -0
  19. package/dist/sync-C6CsPmyK.js +3 -0
  20. package/dist/vite/index.d.ts +22 -0
  21. package/dist/vite/index.js +5 -0
  22. package/env.d.ts +51 -0
  23. package/package.json +91 -0
  24. package/skills/apply-comments/SKILL.md +74 -0
  25. package/skills/create-doc/SKILL.md +102 -0
  26. package/skills/create-theme/SKILL.md +184 -0
  27. package/skills/doc-authoring/SKILL.md +354 -0
  28. package/skills/doc-authoring/references/assets.md +47 -0
  29. package/skills/doc-authoring/references/design-system.md +81 -0
  30. package/skills/doc-authoring/references/pagination.md +117 -0
  31. package/skills/doc-authoring/references/tables-and-charts.md +161 -0
  32. package/src/app/app.tsx +42 -0
  33. package/src/app/components/design-panel/design-panel.tsx +318 -0
  34. package/src/app/components/design-panel/design-provider.tsx +121 -0
  35. package/src/app/components/design-panel/use-design.ts +85 -0
  36. package/src/app/components/doc-assets.tsx +129 -0
  37. package/src/app/components/doc-sidebar.tsx +162 -0
  38. package/src/app/components/flow-page.tsx +50 -0
  39. package/src/app/components/image-placeholder.tsx +50 -0
  40. package/src/app/components/inspector/inspector.tsx +426 -0
  41. package/src/app/components/page-frame.tsx +70 -0
  42. package/src/app/components/sidebar/folder-item.tsx +212 -0
  43. package/src/app/components/sidebar/icon-picker.tsx +99 -0
  44. package/src/app/components/sidebar/sidebar.tsx +252 -0
  45. package/src/app/components/table-of-contents.tsx +81 -0
  46. package/src/app/components/theme-toggle.tsx +50 -0
  47. package/src/app/components/themes/markdown.tsx +249 -0
  48. package/src/app/components/themes/theme-preview.tsx +74 -0
  49. package/src/app/components/ui/menu.tsx +139 -0
  50. package/src/app/index.html +12 -0
  51. package/src/app/lib/assets.ts +151 -0
  52. package/src/app/lib/design-presets.ts +109 -0
  53. package/src/app/lib/design.ts +88 -0
  54. package/src/app/lib/doc-preview.tsx +29 -0
  55. package/src/app/lib/docs.ts +26 -0
  56. package/src/app/lib/export-html.ts +309 -0
  57. package/src/app/lib/export-pdf.ts +166 -0
  58. package/src/app/lib/flow-measure.ts +109 -0
  59. package/src/app/lib/flow.test.ts +64 -0
  60. package/src/app/lib/flow.ts +111 -0
  61. package/src/app/lib/folders.ts +192 -0
  62. package/src/app/lib/inspector/fiber.ts +99 -0
  63. package/src/app/lib/outline.ts +109 -0
  64. package/src/app/lib/page-context.tsx +38 -0
  65. package/src/app/lib/print-ready.ts +69 -0
  66. package/src/app/lib/sdk.test.ts +24 -0
  67. package/src/app/lib/sdk.ts +86 -0
  68. package/src/app/lib/themes.ts +31 -0
  69. package/src/app/lib/use-doc-module.ts +53 -0
  70. package/src/app/lib/use-doc-pages.ts +99 -0
  71. package/src/app/lib/utils.ts +6 -0
  72. package/src/app/main.tsx +14 -0
  73. package/src/app/routes/assets.tsx +257 -0
  74. package/src/app/routes/doc.tsx +480 -0
  75. package/src/app/routes/home-shell.tsx +203 -0
  76. package/src/app/routes/home.tsx +269 -0
  77. package/src/app/routes/themes.tsx +121 -0
  78. package/src/app/styles.css +72 -0
  79. package/src/app/virtual.d.ts +30 -0
@@ -0,0 +1,109 @@
1
+ import { type DesignSystem, defaultDesign } from './design';
2
+
3
+ const SANS_SYSTEM = '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif';
4
+ const SANS_HELV = '"Helvetica Neue", Helvetica, Arial, sans-serif';
5
+ const SERIF_GEORGIA = 'Georgia, "Times New Roman", serif';
6
+ const SERIF_TIMES = '"Times New Roman", Times, serif';
7
+ const MONO_SF = 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace';
8
+
9
+ /**
10
+ * Print-safe presets: white or near-white sheets, body type at or above 13px,
11
+ * one accent each. A document that prints is not the place for a dark canvas.
12
+ */
13
+ export const designPresets: DesignSystem[] = [
14
+ defaultDesign,
15
+ {
16
+ palette: {
17
+ bg: '#ffffff',
18
+ text: '#111827',
19
+ muted: '#6b7280',
20
+ accent: '#0f766e',
21
+ rule: '#e5e7eb',
22
+ },
23
+ fonts: { heading: SERIF_GEORGIA, body: SANS_SYSTEM, mono: MONO_SF },
24
+ typeScale: { title: 46, h1: 27, h2: 20, h3: 16, body: 14, caption: 10 },
25
+ margin: 84,
26
+ leading: 1.6,
27
+ radius: 4,
28
+ },
29
+ {
30
+ palette: {
31
+ bg: '#fcfbf7',
32
+ text: '#1c1917',
33
+ muted: '#78716c',
34
+ accent: '#9a3412',
35
+ rule: '#e7e2d6',
36
+ },
37
+ fonts: { heading: SERIF_TIMES, body: SERIF_GEORGIA, mono: MONO_SF },
38
+ typeScale: { title: 44, h1: 26, h2: 19, h3: 15, body: 14, caption: 10 },
39
+ margin: 90,
40
+ leading: 1.65,
41
+ radius: 2,
42
+ },
43
+ {
44
+ palette: {
45
+ bg: '#ffffff',
46
+ text: '#0a0a0a',
47
+ muted: '#737373',
48
+ accent: '#dc2626',
49
+ rule: '#e5e5e5',
50
+ },
51
+ fonts: { heading: SANS_HELV, body: SANS_HELV, mono: MONO_SF },
52
+ typeScale: { title: 52, h1: 30, h2: 21, h3: 16, body: 14, caption: 10 },
53
+ margin: 72,
54
+ leading: 1.5,
55
+ radius: 0,
56
+ },
57
+ {
58
+ palette: {
59
+ bg: '#f8fafc',
60
+ text: '#0f172a',
61
+ muted: '#64748b',
62
+ accent: '#1d4ed8',
63
+ rule: '#dbe2ea',
64
+ },
65
+ fonts: { heading: SANS_SYSTEM, body: SANS_SYSTEM, mono: MONO_SF },
66
+ typeScale: { title: 42, h1: 26, h2: 19, h3: 15, body: 13, caption: 10 },
67
+ margin: 76,
68
+ leading: 1.55,
69
+ radius: 8,
70
+ },
71
+ {
72
+ palette: {
73
+ bg: '#ffffff',
74
+ text: '#18181b',
75
+ muted: '#71717a',
76
+ accent: '#7c3aed',
77
+ rule: '#e4e4e7',
78
+ },
79
+ fonts: { heading: SANS_SYSTEM, body: SANS_SYSTEM, mono: MONO_SF },
80
+ typeScale: { title: 48, h1: 28, h2: 20, h3: 16, body: 15, caption: 11 },
81
+ margin: 96,
82
+ leading: 1.62,
83
+ radius: 12,
84
+ },
85
+ {
86
+ palette: {
87
+ bg: '#ffffff',
88
+ text: '#0b1220',
89
+ muted: '#5b6472',
90
+ accent: '#b45309',
91
+ rule: '#e6e8eb',
92
+ },
93
+ fonts: { heading: MONO_SF, body: SANS_SYSTEM, mono: MONO_SF },
94
+ typeScale: { title: 40, h1: 25, h2: 18, h3: 15, body: 13, caption: 10 },
95
+ margin: 70,
96
+ leading: 1.5,
97
+ radius: 3,
98
+ },
99
+ ];
100
+
101
+ export function shuffleDesign(current?: DesignSystem | null): DesignSystem {
102
+ if (designPresets.length <= 1) return defaultDesign;
103
+ const currentJson = current ? JSON.stringify(current) : null;
104
+ for (let i = 0; i < 8; i++) {
105
+ const pick = designPresets[Math.floor(Math.random() * designPresets.length)];
106
+ if (pick && JSON.stringify(pick) !== currentJson) return pick;
107
+ }
108
+ return designPresets[0] ?? defaultDesign;
109
+ }
@@ -0,0 +1,88 @@
1
+ export type DesignPalette = {
2
+ bg: string;
3
+ text: string;
4
+ muted: string;
5
+ accent: string;
6
+ rule: string;
7
+ };
8
+
9
+ export type DesignFonts = {
10
+ heading: string;
11
+ body: string;
12
+ mono: string;
13
+ };
14
+
15
+ export type DesignTypeScale = {
16
+ title: number;
17
+ h1: number;
18
+ h2: number;
19
+ h3: number;
20
+ body: number;
21
+ caption: number;
22
+ };
23
+
24
+ export type DesignSystem = {
25
+ palette: DesignPalette;
26
+ fonts: DesignFonts;
27
+ typeScale: DesignTypeScale;
28
+ /** Page margin in CSS px — the printable text block's inset from the sheet edge. */
29
+ margin: number;
30
+ /** Body line-height multiplier. Headings tighten this themselves. */
31
+ leading: number;
32
+ radius: number;
33
+ };
34
+
35
+ export function designToCssVars(d: DesignSystem): Record<string, string> {
36
+ return {
37
+ '--od-bg': d.palette.bg,
38
+ '--od-text': d.palette.text,
39
+ '--od-muted': d.palette.muted,
40
+ '--od-accent': d.palette.accent,
41
+ '--od-rule': d.palette.rule,
42
+ '--od-font-heading': d.fonts.heading,
43
+ '--od-font-body': d.fonts.body,
44
+ '--od-font-mono': d.fonts.mono,
45
+ '--od-size-title': `${d.typeScale.title}px`,
46
+ '--od-size-h1': `${d.typeScale.h1}px`,
47
+ '--od-size-h2': `${d.typeScale.h2}px`,
48
+ '--od-size-h3': `${d.typeScale.h3}px`,
49
+ '--od-size-body': `${d.typeScale.body}px`,
50
+ '--od-size-caption': `${d.typeScale.caption}px`,
51
+ '--od-margin': `${d.margin}px`,
52
+ '--od-leading': String(d.leading),
53
+ '--od-radius': `${d.radius}px`,
54
+ };
55
+ }
56
+
57
+ export function cssVarsToString(vars: Record<string, string>): string {
58
+ return Object.entries(vars)
59
+ .map(([k, v]) => ` ${k}: ${v};`)
60
+ .join('\n');
61
+ }
62
+
63
+ export const defaultDesign: DesignSystem = {
64
+ palette: {
65
+ bg: '#ffffff',
66
+ text: '#16181d',
67
+ muted: '#6b7280',
68
+ accent: '#2563eb',
69
+ rule: '#e5e7eb',
70
+ },
71
+ fonts: {
72
+ heading: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
73
+ body: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
74
+ mono: 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace',
75
+ },
76
+ // px at 96dpi — 1pt ≈ 1.333px, so body 14px reads as ~10.5pt on paper.
77
+ typeScale: {
78
+ title: 44,
79
+ h1: 28,
80
+ h2: 20,
81
+ h3: 16,
82
+ body: 14,
83
+ caption: 10,
84
+ },
85
+ margin: 76,
86
+ leading: 1.55,
87
+ radius: 6,
88
+ };
@@ -0,0 +1,29 @@
1
+ import { createElement, type ReactNode } from 'react';
2
+ import { FlowPage } from '../components/flow-page';
3
+ import { type DocEntry, isFlowSection } from './flow';
4
+ import type { DocModule } from './sdk';
5
+
6
+ /**
7
+ * Page 1 of a document without running the flow measurement — a thumbnail only
8
+ * needs what fits above the fold, and the page shell clips the rest.
9
+ */
10
+ export function coverContent(doc: DocModule | null | undefined): ReactNode {
11
+ const entry = (doc?.default as DocEntry[] | undefined)?.[0];
12
+ if (!entry) return null;
13
+ if (!isFlowSection(entry)) return createElement(entry);
14
+ return createElement(FlowPage, {
15
+ section: entry,
16
+ design: doc?.design,
17
+ blockIndices: entry.blocks.map((_, index) => index),
18
+ });
19
+ }
20
+
21
+ /** "9 pages" for fixed docs; flow docs read "3 sections" until they are opened. */
22
+ export function pageCountLabel(doc: DocModule | null | undefined): string {
23
+ const entries = (doc?.default as DocEntry[] | undefined) ?? [];
24
+ if (entries.length === 0) return '0 pages';
25
+ const flowCount = entries.filter(isFlowSection).length;
26
+ if (flowCount === 0) return `${entries.length} pages`;
27
+ const fixed = entries.length - flowCount;
28
+ return fixed > 0 ? `${fixed} + flow` : 'flow';
29
+ }
@@ -0,0 +1,26 @@
1
+ import {
2
+ docCreatedAt as createdAt,
3
+ docIds as ids,
4
+ loadDoc as load,
5
+ docThemes as themes,
6
+ } from 'virtual:open-doc/docs';
7
+ import type { DocModule } from './sdk';
8
+
9
+ export const docIds: string[] = ids;
10
+ export const docCreatedAt: Record<string, number> = createdAt;
11
+ export const docThemes: Record<string, string> = themes;
12
+
13
+ export function docsByTheme(themeId: string): string[] {
14
+ return docIds.filter((id) => docThemes[id] === themeId);
15
+ }
16
+
17
+ export async function loadDoc(id: string): Promise<DocModule> {
18
+ return load(id);
19
+ }
20
+
21
+ export function docChangeIncludes(data: unknown, docId: string): boolean {
22
+ if (!data || typeof data !== 'object') return false;
23
+ const payload = data as { docId?: unknown; docIds?: unknown };
24
+ if (payload.docId === docId) return true;
25
+ return Array.isArray(payload.docIds) && payload.docIds.includes(docId);
26
+ }
@@ -0,0 +1,309 @@
1
+ import { createElement } from 'react';
2
+ import { createRoot, type Root } from 'react-dom/client';
3
+ import { designToCssVars } from './design';
4
+ import { collectOutline, getOutline, PAGE_ATTR, PAGE_INDEX_ATTR, setOutline } from './outline';
5
+ import { DocPageProvider } from './page-context';
6
+ import { nextFrame, waitForFonts, waitForImages } from './print-ready';
7
+ import { type DocModule, type PageGeometry, resolvePageGeometry } from './sdk';
8
+ import type { ExpandedPage } from './use-doc-pages';
9
+
10
+ type AssetEntry = { name: string; bytes: Uint8Array };
11
+
12
+ const ASSET_EXT_RE = /\.(?:png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf)(?:\?[^#]*)?(?:#.*)?$/i;
13
+
14
+ export async function exportDocAsHtml(
15
+ doc: DocModule,
16
+ docId: string,
17
+ pages: ExpandedPage[],
18
+ ): Promise<void> {
19
+ if (pages.length === 0) return;
20
+
21
+ const title = doc.meta?.title ?? docId;
22
+ const geometry = resolvePageGeometry(doc.meta);
23
+ const pagesHtml = await renderPagesToHtml(pages, geometry, doc);
24
+ const bundledCss = collectCss();
25
+ const externalLinks = collectExternalStylesheetLinks();
26
+
27
+ const assets = new Map<string, AssetEntry>();
28
+ const usedNames = new Set<string>();
29
+ const urls = new Set<string>([
30
+ ...findHtmlAssetUrls(pagesHtml.join('\n')),
31
+ ...findCssAssetUrls(bundledCss),
32
+ ]);
33
+
34
+ for (const url of urls) {
35
+ const absolute = toAbsolute(url);
36
+ if (!absolute) continue;
37
+ try {
38
+ const res = await fetch(absolute);
39
+ if (!res.ok) continue;
40
+ const bytes = new Uint8Array(await res.arrayBuffer());
41
+ assets.set(url, { name: uniqueAssetName(absolute, usedNames), bytes });
42
+ } catch {}
43
+ }
44
+
45
+ const html = buildHtml({
46
+ title,
47
+ geometry,
48
+ design: doc.design,
49
+ pagesHtml: pagesHtml.map((page) => rewriteUrls(page, assets, 'html')),
50
+ bundledCss: rewriteUrls(bundledCss, assets, 'css'),
51
+ externalLinks,
52
+ });
53
+ const htmlBytes = new TextEncoder().encode(html);
54
+
55
+ if (assets.size === 0) {
56
+ downloadBlob(new Blob([htmlBytes as BlobPart], { type: 'text/html' }), `${docId}.html`);
57
+ return;
58
+ }
59
+
60
+ const { zipSync } = await import('fflate');
61
+ const zipTree: Record<string, Uint8Array | Record<string, Uint8Array>> = {
62
+ [`${docId}.html`]: htmlBytes,
63
+ assets: {},
64
+ };
65
+ for (const { name, bytes } of assets.values()) {
66
+ (zipTree.assets as Record<string, Uint8Array>)[name] = bytes;
67
+ }
68
+ const zipped = zipSync(zipTree as Parameters<typeof zipSync>[0]);
69
+ downloadBlob(new Blob([zipped as BlobPart], { type: 'application/zip' }), `${docId}.zip`);
70
+ }
71
+
72
+ async function renderPagesToHtml(
73
+ pages: ExpandedPage[],
74
+ geometry: PageGeometry,
75
+ doc: DocModule,
76
+ ): Promise<string[]> {
77
+ const container = document.createElement('div');
78
+ container.setAttribute('aria-hidden', 'true');
79
+ Object.assign(container.style, {
80
+ position: 'fixed',
81
+ left: '-99999px',
82
+ top: '0',
83
+ pointerEvents: 'none',
84
+ });
85
+ document.body.appendChild(container);
86
+
87
+ const designVars = doc.design ? designToCssVars(doc.design) : null;
88
+ const roots: Root[] = [];
89
+ const hosts: HTMLElement[] = [];
90
+ const previousOutline = getOutline();
91
+
92
+ try {
93
+ for (let i = 0; i < pages.length; i++) {
94
+ const page = pages[i];
95
+ if (!page) continue;
96
+ const host = document.createElement('div');
97
+ host.setAttribute(PAGE_ATTR, '');
98
+ host.setAttribute(PAGE_INDEX_ATTR, String(i));
99
+ host.style.width = `${geometry.width}px`;
100
+ host.style.height = `${geometry.height}px`;
101
+ if (designVars) {
102
+ for (const [k, v] of Object.entries(designVars)) host.style.setProperty(k, v);
103
+ }
104
+ container.appendChild(host);
105
+ hosts.push(host);
106
+ const root = createRoot(host);
107
+ root.render(createElement(DocPageProvider, { index: i, total: pages.length }, page.content));
108
+ roots.push(root);
109
+ }
110
+
111
+ await nextFrame();
112
+ await waitForFonts();
113
+ await waitForImages(container);
114
+ setOutline(collectOutline(container));
115
+ await nextFrame();
116
+ await nextFrame();
117
+
118
+ return hosts.map((host) => host.innerHTML);
119
+ } finally {
120
+ for (const root of roots) root.unmount();
121
+ container.remove();
122
+ setOutline(previousOutline);
123
+ }
124
+ }
125
+
126
+ function collectCss(): string {
127
+ const chunks: string[] = [];
128
+ for (const sheet of Array.from(document.styleSheets)) {
129
+ let rules: CSSRuleList | null = null;
130
+ try {
131
+ rules = sheet.cssRules;
132
+ } catch {
133
+ continue;
134
+ }
135
+ if (!rules) continue;
136
+ for (const rule of Array.from(rules)) chunks.push(rule.cssText);
137
+ }
138
+ return chunks.join('\n');
139
+ }
140
+
141
+ function collectExternalStylesheetLinks(): string {
142
+ const links: string[] = [];
143
+ for (const sheet of Array.from(document.styleSheets)) {
144
+ try {
145
+ void sheet.cssRules;
146
+ } catch {
147
+ if (sheet.href) links.push(`<link rel="stylesheet" href="${escapeAttr(sheet.href)}">`);
148
+ }
149
+ }
150
+ return links.join('\n');
151
+ }
152
+
153
+ function findHtmlAssetUrls(html: string): string[] {
154
+ const out: string[] = [];
155
+ for (const m of html.matchAll(/\s(?:src|href)="([^"]+)"/g)) {
156
+ if (looksLikeAsset(m[1])) out.push(m[1]);
157
+ }
158
+ for (const m of html.matchAll(/\ssrcset="([^"]+)"/g)) {
159
+ for (const part of m[1].split(',')) {
160
+ const url = part.trim().split(/\s+/)[0];
161
+ if (url && looksLikeAsset(url)) out.push(url);
162
+ }
163
+ }
164
+ return out;
165
+ }
166
+
167
+ function findCssAssetUrls(css: string): string[] {
168
+ const out: string[] = [];
169
+ for (const m of css.matchAll(/url\(\s*(['"]?)([^)'"]+)\1\s*\)/g)) {
170
+ const url = m[2].trim();
171
+ if (looksLikeAsset(url)) out.push(url);
172
+ }
173
+ return out;
174
+ }
175
+
176
+ function looksLikeAsset(url: string): boolean {
177
+ if (!url) return false;
178
+ if (url.startsWith('data:') || url.startsWith('blob:') || url.startsWith('#')) return false;
179
+ if (url.startsWith('mailto:') || url.startsWith('javascript:')) return false;
180
+ const abs = toAbsolute(url);
181
+ if (!abs) return false;
182
+ try {
183
+ if (new URL(abs).origin !== window.location.origin) return false;
184
+ } catch {
185
+ return false;
186
+ }
187
+ return ASSET_EXT_RE.test(url);
188
+ }
189
+
190
+ function toAbsolute(url: string): string | null {
191
+ try {
192
+ return new URL(url, window.location.href).toString();
193
+ } catch {
194
+ return null;
195
+ }
196
+ }
197
+
198
+ function uniqueAssetName(absoluteUrl: string, used: Set<string>): string {
199
+ let base = 'asset';
200
+ try {
201
+ base = new URL(absoluteUrl).pathname.split('/').pop() || 'asset';
202
+ } catch {}
203
+ if (!used.has(base)) {
204
+ used.add(base);
205
+ return base;
206
+ }
207
+ const hash = shortHash(absoluteUrl);
208
+ const dot = base.lastIndexOf('.');
209
+ const name = dot > 0 ? `${base.slice(0, dot)}-${hash}${base.slice(dot)}` : `${base}-${hash}`;
210
+ used.add(name);
211
+ return name;
212
+ }
213
+
214
+ function shortHash(input: string): string {
215
+ let h = 2166136261;
216
+ for (let i = 0; i < input.length; i++) {
217
+ h ^= input.charCodeAt(i);
218
+ h = Math.imul(h, 16777619);
219
+ }
220
+ return (h >>> 0).toString(36).slice(0, 6);
221
+ }
222
+
223
+ function rewriteUrls(
224
+ source: string,
225
+ assets: Map<string, AssetEntry>,
226
+ kind: 'html' | 'css',
227
+ ): string {
228
+ let out = source;
229
+ for (const [orig, { name }] of assets) {
230
+ out = out.split(orig).join(kind === 'css' ? `./assets/${name}` : `assets/${name}`);
231
+ }
232
+ return out;
233
+ }
234
+
235
+ function buildHtml(opts: {
236
+ title: string;
237
+ geometry: PageGeometry;
238
+ design: DocModule['design'];
239
+ pagesHtml: string[];
240
+ bundledCss: string;
241
+ externalLinks: string;
242
+ }): string {
243
+ const { width, height, css } = opts.geometry;
244
+ const designStyle = opts.design
245
+ ? Object.entries(designToCssVars(opts.design))
246
+ .map(([k, v]) => `${k}: ${v};`)
247
+ .join(' ')
248
+ : '';
249
+
250
+ const pagesMarkup = opts.pagesHtml
251
+ .map(
252
+ (page, i) =>
253
+ `<div class="od-page" ${PAGE_ATTR} ${PAGE_INDEX_ATTR}="${i}"${designStyle ? ` style="${escapeAttr(designStyle)}"` : ''}>${page}</div>`,
254
+ )
255
+ .join('\n');
256
+
257
+ return `<!doctype html>
258
+ <html lang="en">
259
+ <head>
260
+ <meta charset="utf-8">
261
+ <meta name="viewport" content="width=device-width, initial-scale=1">
262
+ <title>${escapeHtml(opts.title)}</title>
263
+ ${opts.externalLinks}
264
+ <style>
265
+ html, body { margin: 0; background: #6b7280; font-family: system-ui, sans-serif; }
266
+ .od-doc { display: flex; flex-direction: column; align-items: center; gap: 24px; padding: 32px 16px 64px; }
267
+ .od-page { width: ${width}px; height: ${height}px; flex: none; position: relative; overflow: hidden; background: #fff; color: #111; box-shadow: 0 1px 3px rgba(0,0,0,.3), 0 8px 24px rgba(0,0,0,.22); }
268
+ @page { size: ${css}; margin: 0; }
269
+ @media print {
270
+ html, body { background: #fff; }
271
+ .od-doc { display: block; padding: 0; gap: 0; }
272
+ .od-page { box-shadow: none; page-break-after: always; break-after: page; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
273
+ .od-page:last-child { page-break-after: auto; break-after: auto; }
274
+ }
275
+ </style>
276
+ <style>${opts.bundledCss}</style>
277
+ </head>
278
+ <body>
279
+ <div class="od-doc">
280
+ ${pagesMarkup}
281
+ </div>
282
+ </body>
283
+ </html>`;
284
+ }
285
+
286
+ function escapeHtml(s: string): string {
287
+ return s
288
+ .replace(/&/g, '&amp;')
289
+ .replace(/</g, '&lt;')
290
+ .replace(/>/g, '&gt;')
291
+ .replace(/"/g, '&quot;')
292
+ .replace(/'/g, '&#39;');
293
+ }
294
+
295
+ function escapeAttr(s: string): string {
296
+ return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
297
+ }
298
+
299
+ function downloadBlob(blob: Blob, filename: string): void {
300
+ const url = URL.createObjectURL(blob);
301
+ const a = document.createElement('a');
302
+ a.href = url;
303
+ a.download = filename;
304
+ a.rel = 'noopener';
305
+ document.body.appendChild(a);
306
+ a.click();
307
+ a.remove();
308
+ setTimeout(() => URL.revokeObjectURL(url), 0);
309
+ }