@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,480 @@
1
+ import {
2
+ ArrowLeft,
3
+ Check,
4
+ Download,
5
+ FileCode2,
6
+ FileText,
7
+ Loader2,
8
+ Maximize,
9
+ Minimize,
10
+ Minus,
11
+ MousePointerClick,
12
+ MoveHorizontal,
13
+ Palette,
14
+ Plus,
15
+ Scan,
16
+ } from 'lucide-react';
17
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
18
+ import { Link, useParams } from 'react-router-dom';
19
+ import { DesignPanel } from '../components/design-panel/design-panel';
20
+ import { DesignProvider } from '../components/design-panel/design-provider';
21
+ import { DocSidebar } from '../components/doc-sidebar';
22
+ import { Inspector } from '../components/inspector/inspector';
23
+ import { PageFrame } from '../components/page-frame';
24
+ import { Menu, MenuItem } from '../components/ui/menu';
25
+ import { exportDocAsHtml } from '../lib/export-html';
26
+ import { exportDocAsPdf } from '../lib/export-pdf';
27
+ import { collectOutline, type OutlineEntry, setOutline, useDocOutline } from '../lib/outline';
28
+ import { nextFrame, waitForFonts } from '../lib/print-ready';
29
+ import { resolvePageGeometry } from '../lib/sdk';
30
+ import { useDocModule } from '../lib/use-doc-module';
31
+ import { useDocPages } from '../lib/use-doc-pages';
32
+ import { cn } from '../lib/utils';
33
+
34
+ type DownloadFormat = 'pdf' | 'html';
35
+
36
+ const DOWNLOAD_LABEL: Record<DownloadFormat, string> = {
37
+ pdf: 'PDF',
38
+ html: 'HTML',
39
+ };
40
+
41
+ const DOWNLOAD_FORMATS = [
42
+ { format: 'pdf' as const, label: 'PDF', hint: 'True page size, print-ready', icon: FileText },
43
+ { format: 'html' as const, label: 'HTML', hint: 'Self-contained, printable', icon: FileCode2 },
44
+ ];
45
+
46
+ const GUTTER = 48;
47
+ /** Breathing room left above a heading the outline jumped to. */
48
+ const HEADING_TOP_INSET = 28;
49
+ const MIN_SCALE = 0.25;
50
+ const MAX_SCALE = 2;
51
+ const PAGE_GAP = 24;
52
+
53
+ export function Doc() {
54
+ const { docId } = useParams<{ docId: string }>();
55
+ const state = useDocModule(docId);
56
+ const doc = state.doc;
57
+
58
+ const rootRef = useRef<HTMLDivElement>(null);
59
+ const scrollRef = useRef<HTMLDivElement>(null);
60
+ const pagesRef = useRef<HTMLDivElement>(null);
61
+ const [available, setAvailable] = useState({ width: 0, height: 0 });
62
+ const [zoomMode, setZoomMode] = useState<'auto' | 'fit-width' | 'fit-page'>('auto');
63
+ const [manualScale, setManualScale] = useState<number | null>(null);
64
+ const [currentPage, setCurrentPage] = useState(1);
65
+ const [download, setDownload] = useState<{ format: DownloadFormat; percent: number } | null>(
66
+ null,
67
+ );
68
+ const [downloaded, setDownloaded] = useState<DownloadFormat | null>(null);
69
+ const [designOpen, setDesignOpen] = useState(false);
70
+ const [inspecting, setInspecting] = useState(false);
71
+ const [isFullscreen, setIsFullscreen] = useState(false);
72
+
73
+ const geometry = useMemo(() => resolvePageGeometry(doc?.meta), [doc?.meta]);
74
+ const { pages, measuring } = useDocPages(doc, geometry);
75
+ const outline = useDocOutline();
76
+
77
+ const clamp = (value: number) => Math.max(MIN_SCALE, Math.min(MAX_SCALE, value));
78
+ const fitWidthScale = available.width ? clamp(available.width / geometry.width) : 1;
79
+ // Fit page is bounded by both axes so the whole sheet lands inside the pane.
80
+ const fitPageScale = available.height
81
+ ? clamp(Math.min(available.width / geometry.width, available.height / geometry.height))
82
+ : 1;
83
+ // Auto keeps a page at its true size unless the window is too narrow to hold
84
+ // it; the explicit fit modes may go past 100%.
85
+ const scale =
86
+ manualScale ??
87
+ (zoomMode === 'fit-width'
88
+ ? fitWidthScale
89
+ : zoomMode === 'fit-page'
90
+ ? fitPageScale
91
+ : Math.min(1, fitWidthScale));
92
+
93
+ // biome-ignore lint/correctness/useExhaustiveDependencies: state.status re-runs this once the scroll container mounts — during loading the ref is null and nothing measures.
94
+ useLayoutEffect(() => {
95
+ const el = scrollRef.current;
96
+ if (!el) return;
97
+ const measure = () => {
98
+ const width = el.clientWidth - GUTTER * 2;
99
+ const height = el.clientHeight - GUTTER * 2;
100
+ if (width > 0 && height > 0) setAvailable({ width, height });
101
+ };
102
+ measure();
103
+ const ro = new ResizeObserver(measure);
104
+ ro.observe(el);
105
+ return () => ro.disconnect();
106
+ }, [geometry.width, geometry.height, state.status]);
107
+
108
+ // Headings only exist once the pages are in the DOM at their final metrics,
109
+ // so the scan waits for fonts — a late-loading face reflows headings and
110
+ // would otherwise strand the outline on stale text.
111
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `doc` re-scans on hot reload, when the module identity changes but the status stays 'ready'.
112
+ useEffect(() => {
113
+ if (state.status !== 'ready' || measuring) return;
114
+ let cancelled = false;
115
+ (async () => {
116
+ await nextFrame();
117
+ await waitForFonts();
118
+ await nextFrame();
119
+ const root = pagesRef.current;
120
+ if (cancelled || !root) return;
121
+ setOutline(collectOutline(root));
122
+ })();
123
+ return () => {
124
+ cancelled = true;
125
+ };
126
+ }, [state.status, doc, measuring]);
127
+
128
+ // A full-size page is taller than the viewport, so intersection ratios never
129
+ // cross a useful threshold. Track the page that owns the top third of the
130
+ // viewport instead — that's the sheet the reader is on.
131
+ // biome-ignore lint/correctness/useExhaustiveDependencies: zooming changes every page's offsetTop, so `scale` forces a re-measure of which page owns the marker.
132
+ useEffect(() => {
133
+ const root = scrollRef.current;
134
+ const container = pagesRef.current;
135
+ if (!root || !container || pages.length === 0) return;
136
+
137
+ let frame = 0;
138
+ const update = () => {
139
+ frame = 0;
140
+ const marker = root.scrollTop + root.clientHeight / 3;
141
+ const frames = Array.from(container.children) as HTMLElement[];
142
+ let page = 1;
143
+ frames.forEach((el, index) => {
144
+ if (el.offsetTop <= marker) page = index + 1;
145
+ });
146
+ setCurrentPage(page);
147
+ };
148
+ const onScroll = () => {
149
+ if (frame) return;
150
+ frame = requestAnimationFrame(update);
151
+ };
152
+
153
+ update();
154
+ root.addEventListener('scroll', onScroll, { passive: true });
155
+ return () => {
156
+ root.removeEventListener('scroll', onScroll);
157
+ if (frame) cancelAnimationFrame(frame);
158
+ };
159
+ }, [pages.length, scale]);
160
+
161
+ const scrollToPage = useCallback((page: number) => {
162
+ const frame = pagesRef.current?.children[page - 1];
163
+ frame?.scrollIntoView({ behavior: 'smooth', block: 'start' });
164
+ }, []);
165
+
166
+ // Land the heading near the top of the reading pane, not centred — the reader
167
+ // wants what follows the heading, and centring buries half of it.
168
+ const scrollToEntry = useCallback((entry: OutlineEntry) => {
169
+ const root = scrollRef.current;
170
+ const target = root?.querySelector<HTMLElement>(`#${CSS.escape(entry.id)}`);
171
+ if (root && target) {
172
+ const offset = target.getBoundingClientRect().top - root.getBoundingClientRect().top;
173
+ root.scrollTo({ top: root.scrollTop + offset - HEADING_TOP_INSET, behavior: 'smooth' });
174
+ return;
175
+ }
176
+ const frame = pagesRef.current?.children[entry.page - 1];
177
+ frame?.scrollIntoView({ behavior: 'smooth', block: 'start' });
178
+ }, []);
179
+
180
+ const activeOutlineId = useMemo(() => {
181
+ const onPage = outline.filter((entry) => entry.page === currentPage);
182
+ return onPage[0]?.id ?? null;
183
+ }, [outline, currentPage]);
184
+
185
+ const runDownload = async (format: DownloadFormat) => {
186
+ if (!doc || !docId || download) return;
187
+ setDownload({ format, percent: 0 });
188
+ try {
189
+ if (format === 'pdf') {
190
+ await exportDocAsPdf(doc, docId, pages, (progress) =>
191
+ setDownload({ format, percent: progress.percent }),
192
+ );
193
+ } else {
194
+ await exportDocAsHtml(doc, docId, pages);
195
+ }
196
+ setDownloaded(format);
197
+ setTimeout(() => setDownloaded(null), 2000);
198
+ } finally {
199
+ setDownload(null);
200
+ }
201
+ };
202
+
203
+ const zoom = (delta: number) => {
204
+ setManualScale((prev) =>
205
+ Math.min(MAX_SCALE, Math.max(MIN_SCALE, Number(((prev ?? scale) + delta).toFixed(2)))),
206
+ );
207
+ };
208
+
209
+ const fitTo = (mode: 'fit-width' | 'fit-page') => {
210
+ setManualScale(null);
211
+ setZoomMode(mode);
212
+ };
213
+
214
+ const actualSize = () => {
215
+ setZoomMode('auto');
216
+ setManualScale(1);
217
+ };
218
+
219
+ const toggleFullscreen = useCallback(() => {
220
+ if (document.fullscreenElement) {
221
+ void document.exitFullscreen();
222
+ return;
223
+ }
224
+ void rootRef.current?.requestFullscreen?.().catch(() => {});
225
+ }, []);
226
+
227
+ useEffect(() => {
228
+ const onChange = () => setIsFullscreen(Boolean(document.fullscreenElement));
229
+ document.addEventListener('fullscreenchange', onChange);
230
+ return () => document.removeEventListener('fullscreenchange', onChange);
231
+ }, []);
232
+
233
+ useEffect(() => {
234
+ const onKeyDown = (e: KeyboardEvent) => {
235
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
236
+ const target = e.target as HTMLElement | null;
237
+ if (target?.closest('input, textarea, select, [contenteditable]')) return;
238
+ if (e.key === 'f' || e.key === 'F') {
239
+ e.preventDefault();
240
+ toggleFullscreen();
241
+ }
242
+ };
243
+ window.addEventListener('keydown', onKeyDown);
244
+ return () => window.removeEventListener('keydown', onKeyDown);
245
+ }, [toggleFullscreen]);
246
+
247
+ if (state.status === 'error') {
248
+ return (
249
+ <Centered>
250
+ <p className="font-medium text-sm">Could not load “{docId}”.</p>
251
+ <p className="mt-1 text-muted-foreground text-xs">{state.error.message}</p>
252
+ <BackLink />
253
+ </Centered>
254
+ );
255
+ }
256
+
257
+ if (state.status === 'loading' || !doc) {
258
+ return (
259
+ <Centered>
260
+ <Loader2 className="size-4 animate-spin text-muted-foreground" />
261
+ </Centered>
262
+ );
263
+ }
264
+
265
+ const view = (
266
+ <div ref={rootRef} className="flex h-screen flex-col bg-background text-foreground">
267
+ <header className="flex h-12 flex-none items-center gap-3 border-b border-border px-3">
268
+ <Link
269
+ to="/"
270
+ className="flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
271
+ aria-label="Back to documents"
272
+ >
273
+ <ArrowLeft className="size-4" />
274
+ </Link>
275
+ <div className="min-w-0 flex-1">
276
+ <h1 className="truncate font-medium text-sm">{doc.meta?.title ?? docId}</h1>
277
+ {doc.meta?.subtitle && (
278
+ <p className="truncate text-muted-foreground text-xs">{doc.meta.subtitle}</p>
279
+ )}
280
+ </div>
281
+
282
+ <span className="hidden font-mono text-muted-foreground text-xs tabular-nums sm:inline">
283
+ {currentPage} / {pages.length}
284
+ </span>
285
+
286
+ <div className="flex items-center gap-0.5 rounded-md border border-border px-1 py-0.5">
287
+ <IconButton label="Zoom out" onClick={() => zoom(-0.1)}>
288
+ <Minus className="size-3.5" />
289
+ </IconButton>
290
+ <button
291
+ type="button"
292
+ onClick={actualSize}
293
+ title="Actual size (100%)"
294
+ className="w-11 rounded text-center font-mono text-[11px] tabular-nums transition-colors hover:bg-accent"
295
+ >
296
+ {Math.round(scale * 100)}%
297
+ </button>
298
+ <IconButton label="Zoom in" onClick={() => zoom(0.1)}>
299
+ <Plus className="size-3.5" />
300
+ </IconButton>
301
+ <IconButton
302
+ label="Fit width"
303
+ onClick={() => fitTo('fit-width')}
304
+ active={manualScale === null && zoomMode === 'fit-width'}
305
+ >
306
+ <MoveHorizontal className="size-3.5" />
307
+ </IconButton>
308
+ <IconButton
309
+ label="Fit page"
310
+ onClick={() => fitTo('fit-page')}
311
+ active={manualScale === null && zoomMode === 'fit-page'}
312
+ >
313
+ <Scan className="size-3.5" />
314
+ </IconButton>
315
+ </div>
316
+
317
+ <IconButton
318
+ label={isFullscreen ? 'Exit fullscreen (F)' : 'Fullscreen (F)'}
319
+ onClick={toggleFullscreen}
320
+ >
321
+ {isFullscreen ? <Minimize className="size-4" /> : <Maximize className="size-4" />}
322
+ </IconButton>
323
+
324
+ {import.meta.env.DEV && (
325
+ <button
326
+ type="button"
327
+ onClick={() => setInspecting((on) => !on)}
328
+ title="Inspect and edit on the page"
329
+ className={cn(
330
+ 'flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs transition-colors hover:bg-accent',
331
+ inspecting && 'border-transparent bg-[#3b82f6] text-white hover:bg-[#3b82f6]',
332
+ )}
333
+ >
334
+ <MousePointerClick className="size-3.5" />
335
+ Inspect
336
+ </button>
337
+ )}
338
+ {import.meta.env.DEV && (
339
+ <button
340
+ type="button"
341
+ onClick={() => setDesignOpen((open) => !open)}
342
+ className={cn(
343
+ 'flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs transition-colors hover:bg-accent',
344
+ designOpen && 'bg-accent',
345
+ )}
346
+ >
347
+ <Palette className="size-3.5" />
348
+ Design
349
+ </button>
350
+ )}
351
+ <Menu
352
+ trigger={(props) => (
353
+ <button
354
+ type="button"
355
+ disabled={download !== null}
356
+ className="flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1.5 text-primary-foreground text-xs transition-opacity hover:opacity-90 disabled:opacity-70 aria-expanded:opacity-90"
357
+ {...props}
358
+ >
359
+ {download ? (
360
+ <Loader2 className="size-3.5 animate-spin" />
361
+ ) : downloaded ? (
362
+ <Check className="size-3.5" />
363
+ ) : (
364
+ <Download className="size-3.5" />
365
+ )}
366
+ {download
367
+ ? `${DOWNLOAD_LABEL[download.format]} ${Math.round(download.percent)}%`
368
+ : 'Download'}
369
+ </button>
370
+ )}
371
+ >
372
+ {(close) =>
373
+ DOWNLOAD_FORMATS.map(({ format, label, hint, icon: Icon }) => (
374
+ <MenuItem
375
+ key={format}
376
+ onClick={() => {
377
+ close();
378
+ void runDownload(format);
379
+ }}
380
+ >
381
+ <Icon className="size-3.5 flex-none" />
382
+ <span className="flex-1">
383
+ {label}
384
+ <span className="block text-[10px] text-muted-foreground">{hint}</span>
385
+ </span>
386
+ </MenuItem>
387
+ ))
388
+ }
389
+ </Menu>
390
+ </header>
391
+
392
+ <div className="flex min-h-0 flex-1">
393
+ <DocSidebar
394
+ docId={docId ?? ''}
395
+ pages={pages}
396
+ geometry={geometry}
397
+ design={doc.design}
398
+ currentPage={currentPage}
399
+ entries={outline}
400
+ activeId={activeOutlineId}
401
+ onSelectPage={scrollToPage}
402
+ onSelectEntry={scrollToEntry}
403
+ />
404
+ <div ref={scrollRef} className="relative min-w-0 flex-1 overflow-auto bg-canvas">
405
+ <div
406
+ ref={pagesRef}
407
+ className="flex flex-col items-center"
408
+ style={{ gap: PAGE_GAP, padding: `${GUTTER}px ${GUTTER}px ${GUTTER * 1.5}px` }}
409
+ >
410
+ {pages.map((page, index) => (
411
+ <PageFrame
412
+ key={page.key}
413
+ index={index}
414
+ total={pages.length}
415
+ geometry={geometry}
416
+ scale={scale}
417
+ design={doc.design}
418
+ >
419
+ {page.content}
420
+ </PageFrame>
421
+ ))}
422
+ </div>
423
+ </div>
424
+ {inspecting && docId && (
425
+ <Inspector docId={docId} containerRef={scrollRef} onExit={() => setInspecting(false)} />
426
+ )}
427
+ {designOpen && <DesignPanel onClose={() => setDesignOpen(false)} />}
428
+ </div>
429
+ </div>
430
+ );
431
+
432
+ // The design panel writes back to source through the dev server, so it only
433
+ // exists while `open-doc dev` is running.
434
+ if (!import.meta.env.DEV || !docId) return view;
435
+ return <DesignProvider docId={docId}>{view}</DesignProvider>;
436
+ }
437
+
438
+ function IconButton({
439
+ label,
440
+ onClick,
441
+ active = false,
442
+ children,
443
+ }: {
444
+ label: string;
445
+ onClick: () => void;
446
+ active?: boolean;
447
+ children: React.ReactNode;
448
+ }) {
449
+ return (
450
+ <button
451
+ type="button"
452
+ aria-label={label}
453
+ aria-pressed={active}
454
+ title={label}
455
+ onClick={onClick}
456
+ className={cn(
457
+ 'flex size-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',
458
+ active && 'bg-accent text-foreground',
459
+ )}
460
+ >
461
+ {children}
462
+ </button>
463
+ );
464
+ }
465
+
466
+ function Centered({ children }: { children: React.ReactNode }) {
467
+ return (
468
+ <div className="grid h-screen place-items-center bg-background text-center text-foreground">
469
+ <div>{children}</div>
470
+ </div>
471
+ );
472
+ }
473
+
474
+ function BackLink() {
475
+ return (
476
+ <Link to="/" className="mt-4 inline-block text-muted-foreground text-xs underline">
477
+ Back to documents
478
+ </Link>
479
+ );
480
+ }
@@ -0,0 +1,203 @@
1
+ import { Menu as MenuIcon } from 'lucide-react';
2
+ import { useCallback, useMemo } from 'react';
3
+ import { Outlet, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
4
+ import {
5
+ ALL_DOCS_ID,
6
+ ASSETS_ID,
7
+ DRAFT_ID,
8
+ Sidebar,
9
+ THEMES_ID,
10
+ } from '../components/sidebar/sidebar';
11
+ import { ThemeToggle } from '../components/theme-toggle';
12
+ import { Menu, MenuItem } from '../components/ui/menu';
13
+ import { useAssetCount } from '../lib/assets';
14
+ import { docIds } from '../lib/docs';
15
+ import { useFolders } from '../lib/folders';
16
+ import type { FoldersManifest } from '../lib/sdk';
17
+ import { themes } from '../lib/themes';
18
+
19
+ export type HomeOutletContext = {
20
+ manifest: FoldersManifest;
21
+ loading: boolean;
22
+ /** Documents with no folder assignment. */
23
+ draftDocs: string[];
24
+ docsByFolder: Record<string, string[]>;
25
+ /** ALL_DOCS_ID, DRAFT_ID, a folder id, THEMES_ID, or ASSETS_ID. */
26
+ selectedId: string;
27
+ selectFolder: (id: string) => void;
28
+ assign: (docId: string, folderId: string | null) => Promise<void>;
29
+ renameDoc: (docId: string, title: string) => Promise<void>;
30
+ duplicateDoc: (docId: string, newId?: string) => Promise<string>;
31
+ deleteDoc: (docId: string) => Promise<void>;
32
+ };
33
+
34
+ function pathToSelectedId(pathname: string, search: URLSearchParams): string {
35
+ if (pathname === '/themes' || pathname.startsWith('/themes/')) return THEMES_ID;
36
+ if (pathname === '/assets') return ASSETS_ID;
37
+ return search.get('f') ?? ALL_DOCS_ID;
38
+ }
39
+
40
+ export function HomeShell() {
41
+ const {
42
+ manifest,
43
+ loading,
44
+ create,
45
+ update,
46
+ remove,
47
+ reorder,
48
+ assign,
49
+ renameDoc,
50
+ duplicateDoc,
51
+ deleteDoc,
52
+ } = useFolders();
53
+ const navigate = useNavigate();
54
+ const location = useLocation();
55
+ const [searchParams] = useSearchParams();
56
+ const assetCount = useAssetCount();
57
+
58
+ const selectedId = pathToSelectedId(location.pathname, searchParams);
59
+
60
+ const selectFolder = useCallback(
61
+ (id: string) => {
62
+ if (id === THEMES_ID) navigate('/themes');
63
+ else if (id === ASSETS_ID) navigate('/assets');
64
+ else if (id === ALL_DOCS_ID) navigate('/');
65
+ else navigate(`/?f=${encodeURIComponent(id)}`);
66
+ },
67
+ [navigate],
68
+ );
69
+
70
+ const { draftDocs, docsByFolder } = useMemo(() => {
71
+ const byFolder: Record<string, string[]> = {};
72
+ const draft: string[] = [];
73
+ const known = new Set(manifest.folders.map((f) => f.id));
74
+ for (const id of docIds) {
75
+ const folderId = manifest.assignments[id];
76
+ if (folderId && known.has(folderId)) {
77
+ byFolder[folderId] ??= [];
78
+ byFolder[folderId].push(id);
79
+ } else {
80
+ draft.push(id);
81
+ }
82
+ }
83
+ return { draftDocs: draft, docsByFolder: byFolder };
84
+ }, [manifest]);
85
+
86
+ const countFor = (folderId: string | null) =>
87
+ folderId === null ? draftDocs.length : (docsByFolder[folderId]?.length ?? 0);
88
+
89
+ const ctx: HomeOutletContext = {
90
+ manifest,
91
+ loading,
92
+ draftDocs,
93
+ docsByFolder,
94
+ selectedId,
95
+ selectFolder,
96
+ assign,
97
+ renameDoc,
98
+ duplicateDoc,
99
+ deleteDoc,
100
+ };
101
+
102
+ const isAssetsRoute = location.pathname === '/assets';
103
+
104
+ return (
105
+ <div className="flex h-dvh overflow-hidden bg-background text-foreground">
106
+ <div className="hidden md:block">
107
+ <Sidebar
108
+ folders={manifest.folders}
109
+ countFor={countFor}
110
+ allCount={docIds.length}
111
+ themesCount={themes.length}
112
+ assetsCount={assetCount}
113
+ selectedId={selectedId}
114
+ onSelect={selectFolder}
115
+ onCreate={create}
116
+ onRename={(id, name) => update(id, { name })}
117
+ onChangeIcon={(id, icon) => update(id, { icon })}
118
+ onDelete={async (id) => {
119
+ if (selectedId === id) selectFolder(ALL_DOCS_ID);
120
+ await remove(id).catch(() => {});
121
+ }}
122
+ onDropToFolder={(folderId, docId) => void assign(docId, folderId)}
123
+ onDropToDraft={(docId) => void assign(docId, null)}
124
+ onReorder={(ids) => void reorder(ids).catch(() => {})}
125
+ />
126
+ </div>
127
+
128
+ <div className="relative flex min-w-0 flex-1 flex-col overflow-y-auto bg-canvas">
129
+ <div className="flex items-center justify-between border-border border-b bg-background px-4 py-3 md:hidden">
130
+ <h1 className="font-semibold text-base tracking-tight">open-doc</h1>
131
+ <div className="-mr-1 flex items-center gap-0.5">
132
+ <ThemeToggle />
133
+ <Menu
134
+ trigger={(props) => (
135
+ <button
136
+ type="button"
137
+ aria-label="Menu"
138
+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent"
139
+ {...props}
140
+ >
141
+ <MenuIcon className="size-4" />
142
+ </button>
143
+ )}
144
+ >
145
+ {(close) => (
146
+ <>
147
+ <MenuItem
148
+ active={selectedId !== THEMES_ID && selectedId !== ASSETS_ID}
149
+ onClick={() => {
150
+ selectFolder(ALL_DOCS_ID);
151
+ close();
152
+ }}
153
+ >
154
+ Documents
155
+ </MenuItem>
156
+ <MenuItem
157
+ active={selectedId === DRAFT_ID}
158
+ onClick={() => {
159
+ selectFolder(DRAFT_ID);
160
+ close();
161
+ }}
162
+ >
163
+ Unfiled
164
+ </MenuItem>
165
+ <MenuItem
166
+ active={selectedId === THEMES_ID}
167
+ onClick={() => {
168
+ selectFolder(THEMES_ID);
169
+ close();
170
+ }}
171
+ >
172
+ Themes
173
+ </MenuItem>
174
+ {import.meta.env.DEV && (
175
+ <MenuItem
176
+ active={selectedId === ASSETS_ID}
177
+ onClick={() => {
178
+ selectFolder(ASSETS_ID);
179
+ close();
180
+ }}
181
+ >
182
+ Assets
183
+ </MenuItem>
184
+ )}
185
+ </>
186
+ )}
187
+ </Menu>
188
+ </div>
189
+ </div>
190
+
191
+ <div
192
+ className={
193
+ isAssetsRoute
194
+ ? 'flex min-h-0 flex-1 flex-col'
195
+ : 'mx-auto w-full max-w-[1180px] px-5 py-8 md:px-10 md:py-10'
196
+ }
197
+ >
198
+ <Outlet context={ctx} />
199
+ </div>
200
+ </div>
201
+ </div>
202
+ );
203
+ }