@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,166 @@
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, sleep, waitForDataWaitfor, waitForFonts, waitForImages } from './print-ready';
7
+ import { type DocModule, resolvePageGeometry } from './sdk';
8
+ import type { ExpandedPage } from './use-doc-pages';
9
+
10
+ const PRINT_ROOT_ID = 'od-print-root';
11
+ const PRINT_STYLE_ID = 'od-print-style';
12
+
13
+ function printStyles(geometry: { width: number; height: number; css: string }): string {
14
+ return `
15
+ @page { size: ${geometry.css}; margin: 0; }
16
+
17
+ @media screen {
18
+ #${PRINT_ROOT_ID} {
19
+ position: fixed !important;
20
+ left: -99999px !important;
21
+ top: 0 !important;
22
+ pointer-events: none !important;
23
+ }
24
+ }
25
+
26
+ @media print {
27
+ html, body {
28
+ margin: 0 !important;
29
+ padding: 0 !important;
30
+ background: #fff !important;
31
+ }
32
+ body > *:not(#${PRINT_ROOT_ID}) { display: none !important; }
33
+ #${PRINT_ROOT_ID} {
34
+ position: static !important;
35
+ left: 0 !important;
36
+ top: 0 !important;
37
+ display: block !important;
38
+ pointer-events: auto !important;
39
+ background: #fff !important;
40
+ }
41
+ #${PRINT_ROOT_ID} .od-print-page {
42
+ width: ${geometry.width}px !important;
43
+ height: ${geometry.height}px !important;
44
+ overflow: hidden;
45
+ position: relative;
46
+ background: #fff;
47
+ color: #000;
48
+ page-break-after: always;
49
+ break-after: page;
50
+ -webkit-print-color-adjust: exact;
51
+ print-color-adjust: exact;
52
+ }
53
+ #${PRINT_ROOT_ID} .od-print-page:last-child {
54
+ page-break-after: auto;
55
+ break-after: auto;
56
+ }
57
+ /* Chromium serializes box-shadow as a PDF transparency group, which makes
58
+ macOS Preview re-composite on every page turn. Paper shadows are chrome,
59
+ not content — drop them for the printed copy. */
60
+ #${PRINT_ROOT_ID} * { box-shadow: none !important; }
61
+ }
62
+ `;
63
+ }
64
+
65
+ export type PdfExportProgress = {
66
+ phase: 'rendering' | 'printing' | 'done';
67
+ current: number;
68
+ total: number;
69
+ /** 0–99 while rendering, 99 during printing, 100 when done. */
70
+ percent: number;
71
+ };
72
+
73
+ export async function exportDocAsPdf(
74
+ doc: DocModule,
75
+ docId: string,
76
+ pages: ExpandedPage[],
77
+ onProgress?: (progress: PdfExportProgress) => void,
78
+ ): Promise<void> {
79
+ if (pages.length === 0) return;
80
+
81
+ const total = pages.length;
82
+ const geometry = resolvePageGeometry(doc.meta);
83
+ onProgress?.({ phase: 'rendering', current: 0, total, percent: 0 });
84
+
85
+ const style = document.createElement('style');
86
+ style.id = PRINT_STYLE_ID;
87
+ style.textContent = printStyles(geometry);
88
+ document.head.appendChild(style);
89
+
90
+ const root = document.createElement('div');
91
+ root.id = PRINT_ROOT_ID;
92
+ root.setAttribute('aria-hidden', 'true');
93
+ document.body.appendChild(root);
94
+
95
+ const designVars = doc.design ? designToCssVars(doc.design) : null;
96
+ const reactRoots: Root[] = [];
97
+
98
+ for (let i = 0; i < pages.length; i++) {
99
+ const page = pages[i];
100
+ if (!page) continue;
101
+ const host = document.createElement('div');
102
+ host.className = 'od-print-page';
103
+ host.setAttribute(PAGE_ATTR, '');
104
+ host.setAttribute(PAGE_INDEX_ATTR, String(i));
105
+ host.style.width = `${geometry.width}px`;
106
+ host.style.height = `${geometry.height}px`;
107
+ if (designVars) {
108
+ for (const [k, v] of Object.entries(designVars)) host.style.setProperty(k, v);
109
+ host.style.background = 'var(--od-bg)';
110
+ host.style.color = 'var(--od-text)';
111
+ }
112
+ root.appendChild(host);
113
+ const r = createRoot(host);
114
+ r.render(createElement(DocPageProvider, { index: i, total }, page.content));
115
+ reactRoots.push(r);
116
+ onProgress?.({
117
+ phase: 'rendering',
118
+ current: i + 1,
119
+ total,
120
+ percent: Math.min(90, ((i + 1) / total) * 90),
121
+ });
122
+ }
123
+
124
+ const previousTitle = document.title;
125
+ const previousOutline = getOutline();
126
+ document.title = doc.meta?.title ?? docId;
127
+
128
+ try {
129
+ await nextFrame();
130
+ await waitForFonts();
131
+ await waitForImages(root);
132
+ await waitForDataWaitfor(root);
133
+
134
+ // A `<TableOfContents>` reads the outline store, which is only filled by a
135
+ // DOM scan. Scan the print copy and let React commit the filled TOC before
136
+ // handing the pages to the print engine.
137
+ setOutline(collectOutline(root));
138
+ await nextFrame();
139
+ await sleep(50);
140
+
141
+ onProgress?.({ phase: 'printing', current: total, total, percent: 99 });
142
+ const printDone = waitForAfterPrint();
143
+ window.print();
144
+ await printDone;
145
+ } finally {
146
+ onProgress?.({ phase: 'done', current: total, total, percent: 100 });
147
+ document.title = previousTitle;
148
+ for (const r of reactRoots) r.unmount();
149
+ root.remove();
150
+ style.remove();
151
+ setOutline(previousOutline);
152
+ }
153
+ }
154
+
155
+ function waitForAfterPrint(timeoutMs = 60_000): Promise<void> {
156
+ return new Promise((resolve) => {
157
+ const cleanup = () => {
158
+ window.removeEventListener('afterprint', onAfter);
159
+ clearTimeout(timer);
160
+ resolve();
161
+ };
162
+ const onAfter = () => cleanup();
163
+ const timer = setTimeout(cleanup, timeoutMs);
164
+ window.addEventListener('afterprint', onAfter, { once: true });
165
+ });
166
+ }
@@ -0,0 +1,109 @@
1
+ import { createElement } from 'react';
2
+ import { createRoot } from 'react-dom/client';
3
+ import { FLOW_BLOCK_ATTR, FlowBlock } from '../components/flow-page';
4
+ import { type DesignSystem, designToCssVars } from './design';
5
+ import type { BlockMetrics, FlowSection } from './flow';
6
+ import { nextFrame, waitForFonts } from './print-ready';
7
+ import type { PageGeometry } from './sdk';
8
+
9
+ const HEADING_TAGS = new Set(['H1', 'H2', 'H3', 'H4']);
10
+
11
+ function metricsFor(el: HTMLElement, height: number): BlockMetrics {
12
+ const inner = el.firstElementChild;
13
+ const tag = inner?.tagName ?? '';
14
+ const declaredKeepNext = inner?.getAttribute('data-od-keep-with-next');
15
+ const declaredKeepPrev = inner?.getAttribute('data-od-keep-with-previous');
16
+ const declaredBreak = inner?.getAttribute('data-od-break-before');
17
+
18
+ return {
19
+ height,
20
+ // A heading alone at the bottom of a page is the most visible layout error
21
+ // in a report, so headings glue to whatever follows them by default.
22
+ keepWithNext: declaredKeepNext !== null ? declaredKeepNext !== 'false' : HEADING_TAGS.has(tag),
23
+ keepWithPrevious: declaredKeepPrev !== null && declaredKeepPrev !== 'false',
24
+ breakBefore: declaredBreak !== null && declaredBreak !== 'false',
25
+ };
26
+ }
27
+
28
+ export type FlowMeasurement = {
29
+ metrics: BlockMetrics[];
30
+ /** Usable height of one page for this section. */
31
+ available: number;
32
+ };
33
+
34
+ /**
35
+ * Renders each section's blocks offscreen at the real page width and reads back
36
+ * their stacked heights. Measuring the live DOM is the only way to know how a
37
+ * paragraph wraps or how tall a table grew.
38
+ */
39
+ export async function measureFlowSections(
40
+ sections: FlowSection[],
41
+ opts: { geometry: PageGeometry; design?: DesignSystem },
42
+ ): Promise<FlowMeasurement[]> {
43
+ if (sections.length === 0) return [];
44
+
45
+ const host = document.createElement('div');
46
+ host.setAttribute('aria-hidden', 'true');
47
+ Object.assign(host.style, {
48
+ position: 'fixed',
49
+ left: '-99999px',
50
+ top: '0',
51
+ pointerEvents: 'none',
52
+ visibility: 'hidden',
53
+ });
54
+ document.body.appendChild(host);
55
+
56
+ const designVars = opts.design ? designToCssVars(opts.design) : null;
57
+ const roots: Array<ReturnType<typeof createRoot>> = [];
58
+ const containers: HTMLElement[] = [];
59
+
60
+ try {
61
+ for (const section of sections) {
62
+ const padding = section.padding ?? opts.design?.margin ?? 76;
63
+ const container = document.createElement('div');
64
+ container.style.width = `${opts.geometry.width - padding * 2}px`;
65
+ container.style.fontFamily = 'var(--od-font-body)';
66
+ container.style.fontSize = 'var(--od-size-body)';
67
+ container.style.lineHeight = 'var(--od-leading)';
68
+ if (designVars) {
69
+ for (const [k, v] of Object.entries(designVars)) container.style.setProperty(k, v);
70
+ }
71
+ host.appendChild(container);
72
+ containers.push(container);
73
+
74
+ const root = createRoot(container);
75
+ root.render(
76
+ section.blocks.map((block, index) =>
77
+ createElement(FlowBlock, { key: index }, block),
78
+ ) as unknown as Parameters<typeof root.render>[0],
79
+ );
80
+ roots.push(root);
81
+ }
82
+
83
+ await nextFrame();
84
+ await waitForFonts();
85
+ await nextFrame();
86
+
87
+ return sections.map((section, sectionIndex) => {
88
+ const container = containers[sectionIndex];
89
+ const padding = section.padding ?? opts.design?.margin ?? 76;
90
+ const nodes = Array.from(
91
+ container.querySelectorAll<HTMLElement>(`:scope > [${FLOW_BLOCK_ATTR}]`),
92
+ );
93
+ const total = container.getBoundingClientRect().height;
94
+ const tops = nodes.map((node) => node.offsetTop);
95
+
96
+ const metrics = nodes.map((node, index) => {
97
+ const next = index + 1 < tops.length ? tops[index + 1] : total;
98
+ // Successive offsets already account for collapsed margins, which is
99
+ // what actually decides where the next block starts.
100
+ return metricsFor(node, Math.max(0, next - tops[index]));
101
+ });
102
+
103
+ return { metrics, available: opts.geometry.height - padding * 2 };
104
+ });
105
+ } finally {
106
+ for (const root of roots) root.unmount();
107
+ host.remove();
108
+ }
109
+ }
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { type BlockMetrics, paginateBlocks } from './flow.ts';
3
+
4
+ const b = (height: number, extra: Partial<BlockMetrics> = {}): BlockMetrics => ({
5
+ height,
6
+ ...extra,
7
+ });
8
+
9
+ describe('paginateBlocks', () => {
10
+ it('fills a page before starting the next', () => {
11
+ const { pages } = paginateBlocks([b(300), b(300), b(300), b(300)], 1000);
12
+ expect(pages).toEqual([[0, 1, 2], [3]]);
13
+ });
14
+
15
+ it('keeps everything on one page when it fits', () => {
16
+ const { pages } = paginateBlocks([b(100), b(100)], 1000);
17
+ expect(pages).toEqual([[0, 1]]);
18
+ });
19
+
20
+ it('never leaves a heading as the last block on a page', () => {
21
+ // The heading fits at the bottom, but its body does not — both move.
22
+ const { pages } = paginateBlocks([b(400), b(400), b(60, { keepWithNext: true }), b(300)], 1000);
23
+ expect(pages).toEqual([
24
+ [0, 1],
25
+ [2, 3],
26
+ ]);
27
+ });
28
+
29
+ it('moves a run of stacked headings together', () => {
30
+ const { pages } = paginateBlocks(
31
+ [b(800), b(50, { keepWithNext: true }), b(50, { keepWithNext: true }), b(300)],
32
+ 1000,
33
+ );
34
+ expect(pages).toEqual([[0], [1, 2, 3]]);
35
+ });
36
+
37
+ it('pulls a figure along with its caption', () => {
38
+ const { pages } = paginateBlocks([b(300), b(600), b(120, { keepWithPrevious: true })], 1000);
39
+ expect(pages).toEqual([[0], [1, 2]]);
40
+ });
41
+
42
+ it('honours an explicit page break', () => {
43
+ const { pages } = paginateBlocks([b(100), b(100, { breakBefore: true }), b(100)], 1000);
44
+ expect(pages).toEqual([[0], [1, 2]]);
45
+ });
46
+
47
+ it('gives an oversized block its own page and reports it', () => {
48
+ const { pages, overflowing } = paginateBlocks([b(200), b(1400), b(200)], 1000);
49
+ expect(pages).toEqual([[0], [1], [2]]);
50
+ expect(overflowing).toEqual([1]);
51
+ });
52
+
53
+ it('does not strand a page when every block wants to keep with the next', () => {
54
+ const { pages } = paginateBlocks(
55
+ [b(600, { keepWithNext: true }), b(600, { keepWithNext: true }), b(600)],
56
+ 1000,
57
+ );
58
+ expect(pages).toEqual([[0], [1], [2]]);
59
+ });
60
+
61
+ it('returns no pages for no blocks', () => {
62
+ expect(paginateBlocks([], 1000)).toEqual({ pages: [], overflowing: [] });
63
+ });
64
+ });
@@ -0,0 +1,111 @@
1
+ import { Children, type ComponentType, Fragment, isValidElement, type ReactNode } from 'react';
2
+ import type { DocEntry, FlowSection } from './sdk';
3
+
4
+ export type { DocEntry, FlowSection };
5
+
6
+ /**
7
+ * Flattens fragments so `flow(<>…</>)` yields one block per element the author
8
+ * wrote, not a single block containing the whole fragment.
9
+ */
10
+ function toBlocks(node: ReactNode): ReactNode[] {
11
+ const out: ReactNode[] = [];
12
+ for (const child of Children.toArray(node)) {
13
+ if (!isValidElement(child)) continue;
14
+ if (child.type === Fragment) {
15
+ out.push(...toBlocks((child.props as { children?: ReactNode }).children));
16
+ continue;
17
+ }
18
+ out.push(child);
19
+ }
20
+ return out;
21
+ }
22
+
23
+ /**
24
+ * Wraps continuous content so the framework paginates it, instead of the author
25
+ * hand-splitting sections into fixed pages. Each direct child is one atomic
26
+ * block — a heading, a paragraph, a table — that never straddles a page break.
27
+ */
28
+ export function flow(
29
+ children: ReactNode,
30
+ opts: { footer?: ComponentType; padding?: number } = {},
31
+ ): FlowSection {
32
+ return { __odFlow: true, blocks: toBlocks(children), ...opts };
33
+ }
34
+
35
+ export function isFlowSection(entry: DocEntry): entry is FlowSection {
36
+ return typeof entry === 'object' && entry !== null && (entry as FlowSection).__odFlow === true;
37
+ }
38
+
39
+ export type BlockMetrics = {
40
+ height: number;
41
+ /** A heading must not be the last block on a page. */
42
+ keepWithNext?: boolean;
43
+ /** A caption must not open a page without the figure it belongs to. */
44
+ keepWithPrevious?: boolean;
45
+ /** Always start a new page before this block. */
46
+ breakBefore?: boolean;
47
+ };
48
+
49
+ export type PaginationResult = {
50
+ /** Block indices per page, in order. */
51
+ pages: number[][];
52
+ /** Blocks taller than one page — they stay whole and overflow. */
53
+ overflowing: number[];
54
+ };
55
+
56
+ /**
57
+ * Greedy top-to-bottom packing: fill a page until the next block would cross
58
+ * the bottom edge, then push that block — plus anything glued to it — onto the
59
+ * next page. Blocks are atomic; nothing is split mid-block.
60
+ */
61
+ export function paginateBlocks(blocks: BlockMetrics[], available: number): PaginationResult {
62
+ const pages: number[][] = [];
63
+ const overflowing: number[] = [];
64
+ let current: number[] = [];
65
+ let used = 0;
66
+
67
+ const heightOf = (indices: number[]) =>
68
+ indices.reduce((sum, index) => sum + (blocks[index]?.height ?? 0), 0);
69
+
70
+ const closePage = () => {
71
+ if (current.length === 0) return;
72
+ pages.push(current);
73
+ current = [];
74
+ used = 0;
75
+ };
76
+
77
+ blocks.forEach((block, index) => {
78
+ if (block.height > available) overflowing.push(index);
79
+
80
+ if (block.breakBefore) closePage();
81
+
82
+ if (current.length > 0 && used + block.height > available) {
83
+ // Everything glued to this block travels with it: trailing headings
84
+ // (keep-with-next) and, when this block is a caption, its figure.
85
+ let splitAt = current.length;
86
+ while (splitAt > 0 && blocks[current[splitAt - 1]]?.keepWithNext) splitAt--;
87
+ if (block.keepWithPrevious && splitAt === current.length) splitAt--;
88
+
89
+ if (splitAt > 0 && splitAt < current.length) {
90
+ const moved = current.slice(splitAt);
91
+ pages.push(current.slice(0, splitAt));
92
+ current = moved;
93
+ used = heightOf(moved);
94
+ } else {
95
+ closePage();
96
+ }
97
+ }
98
+
99
+ current.push(index);
100
+ used += block.height;
101
+ });
102
+
103
+ closePage();
104
+ return { pages, overflowing };
105
+ }
106
+
107
+ /** Blocks of the first flow section, for thumbnails that skip measurement. */
108
+ export function firstFlowBlocks(entries: DocEntry[], limit = 12): ReactNode[] {
109
+ const first = entries.find(isFlowSection);
110
+ return first ? first.blocks.slice(0, limit) : [];
111
+ }
@@ -0,0 +1,192 @@
1
+ import buildManifest from 'virtual:open-doc/folders';
2
+ import { useCallback, useEffect, useState } from 'react';
3
+ import type { Folder, FolderIcon, FoldersManifest } from './sdk';
4
+
5
+ const EMPTY: FoldersManifest = { folders: [], assignments: {} };
6
+
7
+ async function getManifest(): Promise<FoldersManifest> {
8
+ // In dev the manifest is mutable, so read it live from the API — the sidebar
9
+ // must reflect edits immediately. A static build has no server, so it falls
10
+ // back to the snapshot the virtual module baked in from docs/.folders.json.
11
+ if (import.meta.env.DEV) {
12
+ const res = await fetch('/__folders');
13
+ if (!res.ok) throw new Error(`GET /__folders ${res.status}`);
14
+ const raw = (await res.json()) as Partial<FoldersManifest>;
15
+ return { folders: raw.folders ?? [], assignments: raw.assignments ?? {} };
16
+ }
17
+ return { folders: buildManifest.folders ?? [], assignments: buildManifest.assignments ?? {} };
18
+ }
19
+
20
+ async function expectOk(res: Response, label: string): Promise<void> {
21
+ if (res.ok) return;
22
+ let detail = `${res.status}`;
23
+ try {
24
+ const body = (await res.json()) as { error?: string };
25
+ if (body.error) detail = body.error;
26
+ } catch {}
27
+ throw new Error(`${label}: ${detail}`);
28
+ }
29
+
30
+ const jsonInit = (method: string, body: unknown): RequestInit => ({
31
+ method,
32
+ headers: { 'content-type': 'application/json' },
33
+ body: JSON.stringify(body),
34
+ });
35
+
36
+ export type UseFoldersResult = {
37
+ manifest: FoldersManifest;
38
+ loading: boolean;
39
+ create: (name: string, icon: FolderIcon) => Promise<Folder>;
40
+ update: (id: string, patch: { name?: string; icon?: FolderIcon }) => Promise<void>;
41
+ remove: (id: string) => Promise<void>;
42
+ reorder: (ids: string[]) => Promise<void>;
43
+ assign: (docId: string, folderId: string | null) => Promise<void>;
44
+ renameDoc: (docId: string, title: string) => Promise<void>;
45
+ duplicateDoc: (docId: string, newId?: string) => Promise<string>;
46
+ deleteDoc: (docId: string) => Promise<void>;
47
+ refresh: () => Promise<void>;
48
+ };
49
+
50
+ export function useFolders(): UseFoldersResult {
51
+ const [manifest, setManifest] = useState<FoldersManifest>(EMPTY);
52
+ const [loading, setLoading] = useState(true);
53
+
54
+ const refresh = useCallback(async () => {
55
+ setManifest(await getManifest());
56
+ }, []);
57
+
58
+ useEffect(() => {
59
+ let cancelled = false;
60
+ getManifest()
61
+ .then((m) => {
62
+ if (cancelled) return;
63
+ setManifest(m);
64
+ setLoading(false);
65
+ })
66
+ .catch(() => {
67
+ if (!cancelled) setLoading(false);
68
+ });
69
+ return () => {
70
+ cancelled = true;
71
+ };
72
+ }, []);
73
+
74
+ useEffect(() => {
75
+ if (!import.meta.hot) return;
76
+ const handler = () => {
77
+ refresh().catch(() => {});
78
+ };
79
+ import.meta.hot.on('open-doc:files-changed', handler);
80
+ return () => {
81
+ import.meta.hot?.off('open-doc:files-changed', handler);
82
+ };
83
+ }, [refresh]);
84
+
85
+ const create = useCallback(
86
+ async (name: string, icon: FolderIcon) => {
87
+ const res = await fetch('/__folders', jsonInit('POST', { name, icon }));
88
+ await expectOk(res, 'Create folder failed');
89
+ const folder = (await res.json()) as Folder;
90
+ await refresh();
91
+ return folder;
92
+ },
93
+ [refresh],
94
+ );
95
+
96
+ const update = useCallback(
97
+ async (id: string, patch: { name?: string; icon?: FolderIcon }) => {
98
+ await expectOk(
99
+ await fetch(`/__folders/${id}`, jsonInit('PATCH', patch)),
100
+ 'Update folder failed',
101
+ );
102
+ await refresh();
103
+ },
104
+ [refresh],
105
+ );
106
+
107
+ const remove = useCallback(
108
+ async (id: string) => {
109
+ await expectOk(await fetch(`/__folders/${id}`, { method: 'DELETE' }), 'Delete folder failed');
110
+ await refresh();
111
+ },
112
+ [refresh],
113
+ );
114
+
115
+ const reorder = useCallback(
116
+ async (ids: string[]) => {
117
+ const prev = manifest;
118
+ const byId = new Map(prev.folders.map((f) => [f.id, f]));
119
+ const next = ids.map((id) => byId.get(id)).filter((f): f is Folder => Boolean(f));
120
+ if (next.length !== prev.folders.length) return;
121
+ setManifest({ ...prev, folders: next });
122
+ try {
123
+ await expectOk(
124
+ await fetch('/__folders/reorder', jsonInit('PUT', { ids })),
125
+ 'Reorder failed',
126
+ );
127
+ } catch (err) {
128
+ setManifest(prev);
129
+ throw err;
130
+ }
131
+ },
132
+ [manifest],
133
+ );
134
+
135
+ const assign = useCallback(
136
+ async (docId: string, folderId: string | null) => {
137
+ await expectOk(
138
+ await fetch('/__folders/assign', jsonInit('PUT', { docId, folderId })),
139
+ 'Move failed',
140
+ );
141
+ await refresh();
142
+ },
143
+ [refresh],
144
+ );
145
+
146
+ const renameDoc = useCallback(
147
+ async (docId: string, title: string) => {
148
+ await expectOk(
149
+ await fetch(`/__docs/${docId}`, jsonInit('PATCH', { title })),
150
+ 'Rename failed',
151
+ );
152
+ await refresh();
153
+ },
154
+ [refresh],
155
+ );
156
+
157
+ const duplicateDoc = useCallback(
158
+ async (docId: string, newId?: string) => {
159
+ const init: RequestInit =
160
+ newId === undefined ? { method: 'POST' } : jsonInit('POST', { newId });
161
+ const res = await fetch(`/__docs/${docId}/duplicate`, init);
162
+ await expectOk(res, 'Duplicate failed');
163
+ const body = (await res.json()) as { docId?: unknown };
164
+ await refresh();
165
+ if (typeof body.docId !== 'string') throw new Error('duplicate response missing docId');
166
+ return body.docId;
167
+ },
168
+ [refresh],
169
+ );
170
+
171
+ const deleteDoc = useCallback(
172
+ async (docId: string) => {
173
+ await expectOk(await fetch(`/__docs/${docId}`, { method: 'DELETE' }), 'Delete failed');
174
+ await refresh();
175
+ },
176
+ [refresh],
177
+ );
178
+
179
+ return {
180
+ manifest,
181
+ loading,
182
+ create,
183
+ update,
184
+ remove,
185
+ reorder,
186
+ assign,
187
+ renameDoc,
188
+ duplicateDoc,
189
+ deleteDoc,
190
+ refresh,
191
+ };
192
+ }