@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,99 @@
1
+ export type SourceLoc = { line: number; column: number };
2
+
3
+ type DebugSource = { fileName?: string; lineNumber?: number; columnNumber?: number };
4
+
5
+ type Fiber = {
6
+ type?: unknown;
7
+ return?: Fiber | null;
8
+ stateNode?: unknown;
9
+ _debugSource?: DebugSource | null;
10
+ };
11
+
12
+ const LOC_ATTR = 'data-od-loc';
13
+
14
+ function fiberOf(el: HTMLElement): Fiber | null {
15
+ const key = Object.keys(el).find((k) => k.startsWith('__reactFiber$'));
16
+ return key ? ((el as unknown as Record<string, Fiber>)[key] ?? null) : null;
17
+ }
18
+
19
+ function locFromAttr(value: string | null): SourceLoc | null {
20
+ if (!value) return null;
21
+ const [line, column] = value.split(':').map(Number);
22
+ if (!Number.isFinite(line) || !Number.isFinite(column)) return null;
23
+ return { line, column };
24
+ }
25
+
26
+ function debugLoc(fiber: Fiber): (SourceLoc & { file?: string }) | null {
27
+ const source = fiber._debugSource;
28
+ if (!source || typeof source.lineNumber !== 'number' || typeof source.columnNumber !== 'number') {
29
+ return null;
30
+ }
31
+ return { line: source.lineNumber, column: source.columnNumber, file: source.fileName };
32
+ }
33
+
34
+ /**
35
+ * Source locations to try for the clicked element, innermost first.
36
+ *
37
+ * The DOM only carries a loc for host elements, so a `<td>` rendered by a local
38
+ * `<Td>text</Td>` helper points at the helper's definition — where the text
39
+ * isn't. Walking the fiber's `return` chain surfaces the call site, which is
40
+ * where the author actually wrote the words.
41
+ *
42
+ * React's `_debugSource` counts lines against the module *after* the dev
43
+ * transforms prepend their preamble, so it never matches our loc tags
44
+ * directly. Rather than hard-coding that offset, calibrate it from any fiber
45
+ * that carries both values.
46
+ */
47
+ export function candidateLocs(el: HTMLElement, maxDepth = 12): SourceLoc[] {
48
+ const domLoc = locFromAttr(el.closest(`[${LOC_ATTR}]`)?.getAttribute(LOC_ATTR) ?? null);
49
+ const candidates: SourceLoc[] = domLoc ? [domLoc] : [];
50
+
51
+ let fiber = fiberOf(el);
52
+ const chain: Fiber[] = [];
53
+ for (let depth = 0; fiber && depth < maxDepth; depth++) {
54
+ chain.push(fiber);
55
+ fiber = fiber.return ?? null;
56
+ }
57
+
58
+ // Calibrate against a fiber that carries both values — that one is provably
59
+ // in the document's own source file, which also tells us which file the rest
60
+ // of the chain has to belong to.
61
+ let calibration: { line: number; column: number; file?: string } | null = null;
62
+ for (const node of chain) {
63
+ const source = debugLoc(node);
64
+ const host = node.stateNode instanceof HTMLElement ? node.stateNode : null;
65
+ const tagged = locFromAttr(host?.getAttribute(LOC_ATTR) ?? null);
66
+ if (source && tagged) {
67
+ calibration = {
68
+ line: source.line - tagged.line,
69
+ column: source.column - tagged.column,
70
+ file: source.file,
71
+ };
72
+ break;
73
+ }
74
+ }
75
+ if (!calibration) return candidates;
76
+
77
+ for (const node of chain) {
78
+ const source = debugLoc(node);
79
+ if (!source) continue;
80
+ // Fibers from the framework's own components (FlowPage, PageFrame, …) carry
81
+ // line numbers from *their* files. Mapping those through the document's
82
+ // offset lands on unrelated elements, which is how an edit ends up
83
+ // rewriting the wrong text.
84
+ if (calibration.file && source.file !== calibration.file) continue;
85
+ const loc = {
86
+ line: source.line - calibration.line,
87
+ column: source.column - calibration.column,
88
+ };
89
+ if (loc.line < 1 || loc.column < 0) continue;
90
+ if (candidates.some((c) => c.line === loc.line && c.column === loc.column)) continue;
91
+ candidates.push(loc);
92
+ }
93
+
94
+ return candidates;
95
+ }
96
+
97
+ export function formatLocs(locs: SourceLoc[]): string {
98
+ return locs.map((loc) => `${loc.line}:${loc.column}`).join(',');
99
+ }
@@ -0,0 +1,109 @@
1
+ import { useSyncExternalStore } from 'react';
2
+
3
+ export type OutlineEntry = {
4
+ id: string;
5
+ text: string;
6
+ level: number;
7
+ /** 1-based page the heading sits on. */
8
+ page: number;
9
+ };
10
+
11
+ const HEADING_SELECTOR = 'h1, h2, h3, [data-od-heading]';
12
+
13
+ export const PAGE_ATTR = 'data-od-page';
14
+ export const PAGE_INDEX_ATTR = 'data-od-page-index';
15
+
16
+ function levelOf(el: Element): number {
17
+ const declared = el.getAttribute('data-od-level');
18
+ if (declared) {
19
+ const n = Number(declared);
20
+ if (Number.isFinite(n)) return Math.min(3, Math.max(1, Math.round(n)));
21
+ }
22
+ const tag = el.tagName.toLowerCase();
23
+ if (tag === 'h1') return 1;
24
+ if (tag === 'h2') return 2;
25
+ if (tag === 'h3') return 3;
26
+ return 2;
27
+ }
28
+
29
+ function textOf(el: Element): string {
30
+ const labelled = el.getAttribute('data-od-heading');
31
+ if (labelled && labelled !== 'true' && labelled.trim() !== '') return labelled.trim();
32
+ return (el.textContent ?? '').replace(/\s+/g, ' ').trim();
33
+ }
34
+
35
+ /**
36
+ * Walks rendered page frames and returns their headings in document order.
37
+ * Headings inside a rendered table of contents are skipped so a TOC never
38
+ * lists itself, and every collected heading gets a stable `id` so the sidebar
39
+ * and in-document TOC can anchor to it.
40
+ */
41
+ export function collectOutline(root: ParentNode): OutlineEntry[] {
42
+ const entries: OutlineEntry[] = [];
43
+ const frames = Array.from(root.querySelectorAll<HTMLElement>(`[${PAGE_ATTR}]`));
44
+ frames.forEach((frame, fallbackIndex) => {
45
+ const declared = Number(frame.getAttribute(PAGE_INDEX_ATTR));
46
+ const page = (Number.isFinite(declared) ? declared : fallbackIndex) + 1;
47
+ const headings = Array.from(frame.querySelectorAll<HTMLElement>(HEADING_SELECTOR));
48
+ for (const el of headings) {
49
+ if (el.closest('[data-od-toc]')) continue;
50
+ if (el.getAttribute('data-od-outline') === 'skip') continue;
51
+ const text = textOf(el);
52
+ if (!text) continue;
53
+ const id = el.id || `od-h-${entries.length + 1}`;
54
+ if (!el.id) el.id = id;
55
+ entries.push({ id, text, level: levelOf(el), page });
56
+ }
57
+ });
58
+ return entries;
59
+ }
60
+
61
+ // Shared through globalThis for the same reason as the page context: the
62
+ // viewer writes the outline from the source copy of this module, while a
63
+ // document's `<TableOfContents>` reads it from the published bundle.
64
+ const GLOBAL_KEY = '__open_doc_outline_store__';
65
+ type OutlineStore = { snapshot: OutlineEntry[]; listeners: Set<() => void> };
66
+ type GlobalWithStore = typeof globalThis & { [GLOBAL_KEY]?: OutlineStore };
67
+ const g = globalThis as GlobalWithStore;
68
+ if (!g[GLOBAL_KEY]) {
69
+ g[GLOBAL_KEY] = { snapshot: [], listeners: new Set() };
70
+ }
71
+ const store = g[GLOBAL_KEY];
72
+
73
+ function sameOutline(a: OutlineEntry[], b: OutlineEntry[]): boolean {
74
+ if (a.length !== b.length) return false;
75
+ return a.every((entry, i) => {
76
+ const other = b[i];
77
+ return (
78
+ other !== undefined &&
79
+ entry.id === other.id &&
80
+ entry.text === other.text &&
81
+ entry.level === other.level &&
82
+ entry.page === other.page
83
+ );
84
+ });
85
+ }
86
+
87
+ export function setOutline(entries: OutlineEntry[]): void {
88
+ if (sameOutline(store.snapshot, entries)) return;
89
+ store.snapshot = entries;
90
+ for (const listener of store.listeners) listener();
91
+ }
92
+
93
+ export function getOutline(): OutlineEntry[] {
94
+ return store.snapshot;
95
+ }
96
+
97
+ function subscribe(listener: () => void): () => void {
98
+ store.listeners.add(listener);
99
+ return () => store.listeners.delete(listener);
100
+ }
101
+
102
+ /**
103
+ * The document's headings, filled in after the pages render. Empty on the first
104
+ * pass — a `<TableOfContents>` renders its rows on the second, once the scan
105
+ * has run.
106
+ */
107
+ export function useDocOutline(): OutlineEntry[] {
108
+ return useSyncExternalStore(subscribe, getOutline, getOutline);
109
+ }
@@ -0,0 +1,38 @@
1
+ import { type Context, createContext, type ReactNode, useContext, useMemo } from 'react';
2
+
3
+ type PageContextValue = { index: number; total: number };
4
+
5
+ // Stored on globalThis so the dev (src) and published (dist) copies of this
6
+ // module share one context instance — a document imports `@open-document/core`
7
+ // (dist) while the viewer imports the source, so without this the provider
8
+ // writes to one context and the hook reads from another.
9
+ const GLOBAL_KEY = '__open_doc_page_context__';
10
+ type GlobalWithCtx = typeof globalThis & {
11
+ [GLOBAL_KEY]?: Context<PageContextValue | null>;
12
+ };
13
+ const g = globalThis as GlobalWithCtx;
14
+ if (!g[GLOBAL_KEY]) {
15
+ g[GLOBAL_KEY] = createContext<PageContextValue | null>(null);
16
+ }
17
+ const PageContext = g[GLOBAL_KEY];
18
+
19
+ export function DocPageProvider({
20
+ index,
21
+ total,
22
+ children,
23
+ }: PageContextValue & { children?: ReactNode }) {
24
+ const value = useMemo(() => ({ index, total }), [index, total]);
25
+ return <PageContext.Provider value={value}>{children}</PageContext.Provider>;
26
+ }
27
+
28
+ /** 1-based page number of the page currently rendering. `0` outside a page. */
29
+ export function useDocPageNumber(): number {
30
+ const ctx = useContext(PageContext);
31
+ return ctx ? ctx.index + 1 : 0;
32
+ }
33
+
34
+ /** Total page count of the document being rendered. `0` outside a page. */
35
+ export function useDocPageCount(): number {
36
+ const ctx = useContext(PageContext);
37
+ return ctx ? ctx.total : 0;
38
+ }
@@ -0,0 +1,69 @@
1
+ const DEFAULT_WAITFOR_TIMEOUT_MS = 10_000;
2
+
3
+ // `document.fonts.ready` already waits for every in-flight face. Never call
4
+ // `face.load()` on the rest: unloaded faces were never requested by CSS, and
5
+ // `load()` ignores `unicode-range`, so a subsetted CJK family (hundreds of
6
+ // faces) would be force-downloaded in full and hang the tab.
7
+ export async function waitForFonts(): Promise<void> {
8
+ if (!('fonts' in document)) return;
9
+ await document.fonts.ready;
10
+ }
11
+
12
+ export async function waitForImages(root: ParentNode, timeoutMs = 10_000): Promise<void> {
13
+ const images = Array.from(root.querySelectorAll('img'));
14
+ const pending = images.filter((img) => !img.complete);
15
+ if (pending.length === 0) return;
16
+ await Promise.race([
17
+ Promise.all(
18
+ pending.map(
19
+ (img) =>
20
+ new Promise<void>((resolve) => {
21
+ img.addEventListener('load', () => resolve(), { once: true });
22
+ img.addEventListener('error', () => resolve(), { once: true });
23
+ }),
24
+ ),
25
+ ),
26
+ sleep(timeoutMs),
27
+ ]);
28
+ }
29
+
30
+ export async function waitForDataWaitfor(
31
+ root: HTMLElement,
32
+ timeoutMs = DEFAULT_WAITFOR_TIMEOUT_MS,
33
+ ): Promise<void> {
34
+ const targets = Array.from(root.querySelectorAll<HTMLElement>('[data-waitfor]'));
35
+ if (targets.length === 0) return;
36
+ const deadline = performance.now() + timeoutMs;
37
+ await Promise.all(
38
+ targets.map(async (el) => {
39
+ const selector = el.getAttribute('data-waitfor');
40
+ if (!selector) return;
41
+ while (performance.now() < deadline) {
42
+ try {
43
+ if (el.querySelector(selector)) return;
44
+ } catch {
45
+ return; // invalid selector — skip rather than hang
46
+ }
47
+ await nextFrame();
48
+ }
49
+ }),
50
+ );
51
+ }
52
+
53
+ export function sleep(ms: number): Promise<void> {
54
+ return new Promise((resolve) => setTimeout(resolve, ms));
55
+ }
56
+
57
+ export function nextFrame(): Promise<void> {
58
+ // rAF in real tabs; setTimeout fallback for hidden/throttled tabs.
59
+ return new Promise((resolve) => {
60
+ let settled = false;
61
+ const settle = () => {
62
+ if (settled) return;
63
+ settled = true;
64
+ resolve();
65
+ };
66
+ requestAnimationFrame(settle);
67
+ setTimeout(settle, 50);
68
+ });
69
+ }
@@ -0,0 +1,24 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { PAGE_SIZES, resolvePageGeometry } from './sdk.ts';
3
+
4
+ describe('resolvePageGeometry', () => {
5
+ it('defaults to portrait A4', () => {
6
+ expect(resolvePageGeometry()).toEqual({
7
+ width: PAGE_SIZES.A4.width,
8
+ height: PAGE_SIZES.A4.height,
9
+ css: PAGE_SIZES.A4.css,
10
+ });
11
+ });
12
+
13
+ it('swaps the axes for landscape and marks the @page descriptor', () => {
14
+ const geo = resolvePageGeometry({ pageSize: 'Letter', orientation: 'landscape' });
15
+ expect(geo.width).toBe(PAGE_SIZES.Letter.height);
16
+ expect(geo.height).toBe(PAGE_SIZES.Letter.width);
17
+ expect(geo.css).toBe(`${PAGE_SIZES.Letter.css} landscape`);
18
+ });
19
+
20
+ it('falls back to A4 for an unknown page size', () => {
21
+ const geo = resolvePageGeometry({ pageSize: 'B4' as never });
22
+ expect(geo.width).toBe(PAGE_SIZES.A4.width);
23
+ });
24
+ });
@@ -0,0 +1,86 @@
1
+ import type { ComponentType, ReactNode } from 'react';
2
+ import type { DesignSystem } from './design.ts';
3
+
4
+ export type PageSizeName = 'A4' | 'Letter' | 'A5' | 'Legal';
5
+
6
+ export type Orientation = 'portrait' | 'landscape';
7
+
8
+ /**
9
+ * Page dimensions in CSS pixels at 96dpi — the unit authors write in — paired
10
+ * with the physical `@page size` used when printing. Keeping both means a page
11
+ * laid out at 794×1123 on screen maps to a real A4 sheet with no rescaling.
12
+ */
13
+ export const PAGE_SIZES: Record<PageSizeName, { width: number; height: number; css: string }> = {
14
+ A4: { width: 794, height: 1123, css: '210mm 297mm' },
15
+ Letter: { width: 816, height: 1056, css: '8.5in 11in' },
16
+ A5: { width: 559, height: 794, css: '148mm 210mm' },
17
+ Legal: { width: 816, height: 1344, css: '8.5in 14in' },
18
+ };
19
+
20
+ export const DEFAULT_PAGE_SIZE: PageSizeName = 'A4';
21
+
22
+ export type PageGeometry = {
23
+ width: number;
24
+ height: number;
25
+ /** Value for the `@page { size: … }` descriptor, orientation included. */
26
+ css: string;
27
+ };
28
+
29
+ export type DocPage = ComponentType;
30
+
31
+ /**
32
+ * A run of continuous content the framework paginates itself. Build one with
33
+ * `flow(...)` and put it in the page array alongside fixed pages.
34
+ */
35
+ export type FlowSection = {
36
+ readonly __odFlow: true;
37
+ blocks: ReactNode[];
38
+ /** Rendered on every page the section expands into. */
39
+ footer?: ComponentType;
40
+ /** Page padding override in px; defaults to the design's `margin`. */
41
+ padding?: number;
42
+ };
43
+
44
+ /** What a document's default export may contain: fixed pages, flow sections, or both. */
45
+ export type DocEntry = DocPage | FlowSection;
46
+
47
+ export type DocMeta = {
48
+ title?: string;
49
+ subtitle?: string;
50
+ author?: string;
51
+ pageSize?: PageSizeName;
52
+ orientation?: Orientation;
53
+ /** Id of a theme under `themes/` this document was built from. Adds a back-link. */
54
+ theme?: string;
55
+ /** ISO 8601 timestamp. Set once at scaffold time; used to sort the doc list. */
56
+ createdAt?: string;
57
+ };
58
+
59
+ export type FolderIcon = { type: 'emoji'; value: string } | { type: 'color'; value: string };
60
+
61
+ export type Folder = {
62
+ id: string;
63
+ name: string;
64
+ icon: FolderIcon;
65
+ };
66
+
67
+ export type FoldersManifest = {
68
+ folders: Folder[];
69
+ assignments: Record<string, string>;
70
+ };
71
+
72
+ export type DocModule = {
73
+ default: DocEntry[];
74
+ meta?: DocMeta;
75
+ design?: DesignSystem;
76
+ };
77
+
78
+ export function resolvePageGeometry(meta?: DocMeta): PageGeometry {
79
+ const size = PAGE_SIZES[meta?.pageSize ?? DEFAULT_PAGE_SIZE] ?? PAGE_SIZES[DEFAULT_PAGE_SIZE];
80
+ const landscape = meta?.orientation === 'landscape';
81
+ return {
82
+ width: landscape ? size.height : size.width,
83
+ height: landscape ? size.width : size.height,
84
+ css: landscape ? `${size.css} landscape` : size.css,
85
+ };
86
+ }
@@ -0,0 +1,31 @@
1
+ import { loadThemeDemo as load, themes as raw } from 'virtual:open-doc/themes';
2
+ import type { DesignSystem } from './design';
3
+ import type { DocPage } from './sdk';
4
+
5
+ export type ThemeMeta = {
6
+ id: string;
7
+ name: string;
8
+ description: string;
9
+ /** Frontmatter hint — 'A4' | 'Letter' | … or '' when the theme doesn't say. */
10
+ pageSize: string;
11
+ /** Frontmatter hint — 'light' | 'dark' | '' */
12
+ mode: string;
13
+ body: string;
14
+ hasDemo: boolean;
15
+ };
16
+
17
+ export type ThemeDemoModule = {
18
+ default: DocPage[];
19
+ design?: DesignSystem;
20
+ };
21
+
22
+ export const themes: ThemeMeta[] = raw;
23
+
24
+ export function findTheme(id: string | undefined): ThemeMeta | undefined {
25
+ if (!id) return undefined;
26
+ return themes.find((t) => t.id === id);
27
+ }
28
+
29
+ export async function loadThemeDemo(id: string): Promise<ThemeDemoModule> {
30
+ return load(id);
31
+ }
@@ -0,0 +1,53 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { docChangeIncludes, loadDoc } from './docs';
3
+ import type { DocModule } from './sdk';
4
+
5
+ export type DocState =
6
+ | { status: 'loading'; doc: null; error: null }
7
+ | { status: 'ready'; doc: DocModule; error: null }
8
+ | { status: 'error'; doc: null; error: Error };
9
+
10
+ const LOADING: DocState = { status: 'loading', doc: null, error: null };
11
+
12
+ export function useDocModule(docId: string | undefined): DocState {
13
+ const [state, setState] = useState<DocState>(LOADING);
14
+
15
+ useEffect(() => {
16
+ if (!docId) return;
17
+ let cancelled = false;
18
+
19
+ const read = () => {
20
+ loadDoc(docId)
21
+ .then((doc) => {
22
+ if (!cancelled) setState({ status: 'ready', doc, error: null });
23
+ })
24
+ .catch((err: unknown) => {
25
+ if (cancelled) return;
26
+ setState({
27
+ status: 'error',
28
+ doc: null,
29
+ error: err instanceof Error ? err : new Error(String(err)),
30
+ });
31
+ });
32
+ };
33
+
34
+ setState(LOADING);
35
+ read();
36
+
37
+ if (!import.meta.hot)
38
+ return () => {
39
+ cancelled = true;
40
+ };
41
+
42
+ const onChange = (data: unknown) => {
43
+ if (docChangeIncludes(data, docId)) read();
44
+ };
45
+ import.meta.hot.on('open-doc:doc-changed', onChange);
46
+ return () => {
47
+ cancelled = true;
48
+ import.meta.hot?.off('open-doc:doc-changed', onChange);
49
+ };
50
+ }, [docId]);
51
+
52
+ return state;
53
+ }
@@ -0,0 +1,99 @@
1
+ import { createElement, type ReactNode, useEffect, useMemo, useState } from 'react';
2
+ import { FlowPage } from '../components/flow-page';
3
+ import type { DesignSystem } from './design';
4
+ import { type DocEntry, type FlowSection, isFlowSection, paginateBlocks } from './flow';
5
+ import { measureFlowSections } from './flow-measure';
6
+ import type { DocModule, PageGeometry } from './sdk';
7
+
8
+ export type ExpandedPage = {
9
+ key: string;
10
+ content: ReactNode;
11
+ };
12
+
13
+ type Plan = {
14
+ /** Section index → block indices per page. */
15
+ bySection: number[][][];
16
+ overflowing: Array<{ section: number; block: number }>;
17
+ };
18
+
19
+ const EMPTY_PLAN: Plan = { bySection: [], overflowing: [] };
20
+
21
+ function entriesOf(doc: DocModule | null): DocEntry[] {
22
+ return (doc?.default ?? []) as DocEntry[];
23
+ }
24
+
25
+ /**
26
+ * Turns the authored entry list into the pages actually rendered: fixed page
27
+ * components pass through, flow sections expand into as many pages as their
28
+ * measured content needs.
29
+ */
30
+ export function useDocPages(
31
+ doc: DocModule | null,
32
+ geometry: PageGeometry,
33
+ ): { pages: ExpandedPage[]; measuring: boolean; overflowing: Plan['overflowing'] } {
34
+ const entries = useMemo(() => entriesOf(doc), [doc]);
35
+ const sections = useMemo(() => entries.filter(isFlowSection), [entries]);
36
+ const design = doc?.design as DesignSystem | undefined;
37
+
38
+ const [plan, setPlan] = useState<Plan>(EMPTY_PLAN);
39
+ const [measuring, setMeasuring] = useState(sections.length > 0);
40
+
41
+ useEffect(() => {
42
+ if (sections.length === 0) {
43
+ setPlan(EMPTY_PLAN);
44
+ setMeasuring(false);
45
+ return;
46
+ }
47
+ let cancelled = false;
48
+ setMeasuring(true);
49
+ measureFlowSections(sections, { geometry, design })
50
+ .then((measurements) => {
51
+ if (cancelled) return;
52
+ const bySection: number[][][] = [];
53
+ const overflowing: Plan['overflowing'] = [];
54
+ measurements.forEach((measurement, sectionIndex) => {
55
+ const result = paginateBlocks(measurement.metrics, measurement.available);
56
+ bySection.push(result.pages);
57
+ for (const block of result.overflowing) {
58
+ overflowing.push({ section: sectionIndex, block });
59
+ }
60
+ });
61
+ setPlan({ bySection, overflowing });
62
+ setMeasuring(false);
63
+ })
64
+ .catch(() => {
65
+ if (!cancelled) setMeasuring(false);
66
+ });
67
+ return () => {
68
+ cancelled = true;
69
+ };
70
+ }, [sections, geometry, design]);
71
+
72
+ const pages = useMemo(() => {
73
+ const out: ExpandedPage[] = [];
74
+ let sectionIndex = -1;
75
+
76
+ entries.forEach((entry, entryIndex) => {
77
+ if (!isFlowSection(entry)) {
78
+ const Page = entry;
79
+ out.push({ key: `p${entryIndex}`, content: createElement(Page) });
80
+ return;
81
+ }
82
+ sectionIndex++;
83
+ const section = entry as FlowSection;
84
+ // Before measurement lands, render the section as a single page so the
85
+ // viewer shows something rather than flashing empty.
86
+ const chunks = plan.bySection[sectionIndex] ?? [section.blocks.map((_, i) => i)];
87
+ chunks.forEach((blockIndices, pageIndex) => {
88
+ out.push({
89
+ key: `f${entryIndex}-${pageIndex}`,
90
+ content: createElement(FlowPage, { section, design, blockIndices }),
91
+ });
92
+ });
93
+ });
94
+
95
+ return out;
96
+ }, [entries, plan, design]);
97
+
98
+ return { pages, measuring, overflowing: plan.overflowing };
99
+ }
@@ -0,0 +1,6 @@
1
+ import { type ClassValue, clsx } from 'clsx';
2
+ import { twMerge } from 'tailwind-merge';
3
+
4
+ export function cn(...inputs: ClassValue[]): string {
5
+ return twMerge(clsx(inputs));
6
+ }
@@ -0,0 +1,14 @@
1
+ import { ThemeProvider } from 'next-themes';
2
+ import { StrictMode } from 'react';
3
+ import { createRoot } from 'react-dom/client';
4
+ import { App } from './app';
5
+ import './styles.css';
6
+
7
+ // biome-ignore lint/style/noNonNullAssertion: #root is guaranteed by index.html
8
+ createRoot(document.getElementById('root')!).render(
9
+ <StrictMode>
10
+ <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
11
+ <App />
12
+ </ThemeProvider>
13
+ </StrictMode>,
14
+ );