@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,426 @@
1
+ import { Check, Loader2, MessageSquarePlus, X } from 'lucide-react';
2
+ import {
3
+ type CSSProperties,
4
+ useCallback,
5
+ useEffect,
6
+ useLayoutEffect,
7
+ useRef,
8
+ useState,
9
+ } from 'react';
10
+ import { createPortal } from 'react-dom';
11
+ import { candidateLocs, formatLocs } from '../../lib/inspector/fiber';
12
+
13
+ type TextPart = { kind: 'text'; index: number; value: string } | { kind: 'markup'; label: string };
14
+
15
+ type ResolvedTarget = {
16
+ line: number;
17
+ column: number;
18
+ editable: boolean;
19
+ text: string;
20
+ parts: TextPart[];
21
+ reason?: string;
22
+ };
23
+
24
+ export const LOC_ATTR = 'data-od-loc';
25
+
26
+ export type InspectorTarget = {
27
+ line: number;
28
+ column: number;
29
+ anchor: HTMLElement;
30
+ tag: string;
31
+ };
32
+
33
+ // Same visual language as open-slide's inspector: dashed on hover, solid on
34
+ // selection, both in the same blue.
35
+ const FRAME_STYLE: Record<'hover' | 'selected', CSSProperties> = {
36
+ hover: { outline: '1.5px dashed #3b82f6', background: 'rgba(59,130,246,0.05)' },
37
+ selected: { outline: '2px solid #3b82f6', background: 'rgba(59,130,246,0.1)' },
38
+ };
39
+
40
+ function normalize(value: string): string {
41
+ return value.replace(/\s+/g, ' ').trim();
42
+ }
43
+
44
+ function targetFrom(el: Element | null): InspectorTarget | null {
45
+ const host = (el as HTMLElement | null)?.closest?.(`[${LOC_ATTR}]`) as HTMLElement | null;
46
+ const raw = host?.getAttribute(LOC_ATTR);
47
+ if (!host || !raw) return null;
48
+ const [line, column] = raw.split(':').map(Number);
49
+ if (!Number.isFinite(line) || !Number.isFinite(column)) return null;
50
+ return { line, column, anchor: host, tag: host.tagName.toLowerCase() };
51
+ }
52
+
53
+ type Rect = { left: number; top: number; width: number; height: number };
54
+
55
+ function sameRect(a: Rect | null, b: Rect) {
56
+ return (
57
+ a !== null &&
58
+ a.left === b.left &&
59
+ a.top === b.top &&
60
+ a.width === b.width &&
61
+ a.height === b.height
62
+ );
63
+ }
64
+
65
+ function Frame({
66
+ anchor,
67
+ container,
68
+ variant,
69
+ }: {
70
+ anchor: HTMLElement | null;
71
+ container: HTMLElement;
72
+ variant: 'hover' | 'selected';
73
+ }) {
74
+ const [rect, setRect] = useState<Rect | null>(null);
75
+
76
+ // Deliberately no dependency array. Opening a side pane re-zooms and re-centres
77
+ // the pages, which moves the anchor without resizing it — ResizeObserver never
78
+ // sees that, and the zoom lands a frame after the observer would have fired.
79
+ // Measuring after every render is what keeps the frame on its element; the
80
+ // value comparison below stops that from looping.
81
+ useLayoutEffect(() => {
82
+ if (!anchor?.isConnected) {
83
+ setRect(null);
84
+ return;
85
+ }
86
+ // The overlay is absolutely positioned inside the scroller, so its origin
87
+ // is the content box — frames live in content coordinates and scroll along
88
+ // with the pages.
89
+ const measure = () => {
90
+ const a = anchor.getBoundingClientRect();
91
+ const c = container.getBoundingClientRect();
92
+ const next = {
93
+ left: a.left - c.left + container.scrollLeft,
94
+ top: a.top - c.top + container.scrollTop,
95
+ width: a.width,
96
+ height: a.height,
97
+ };
98
+ setRect((prev) => (sameRect(prev, next) ? prev : next));
99
+ };
100
+
101
+ measure();
102
+ const ro = new ResizeObserver(measure);
103
+ ro.observe(anchor);
104
+ ro.observe(container);
105
+ container.addEventListener('scroll', measure, { passive: true });
106
+ return () => {
107
+ ro.disconnect();
108
+ container.removeEventListener('scroll', measure);
109
+ };
110
+ });
111
+
112
+ if (!rect) return null;
113
+ return (
114
+ <div
115
+ aria-hidden
116
+ className="pointer-events-none absolute rounded-[2px]"
117
+ style={{ ...rect, ...FRAME_STYLE[variant] }}
118
+ />
119
+ );
120
+ }
121
+
122
+ type Props = {
123
+ docId: string;
124
+ /** The scroll container the pages live in. */
125
+ containerRef: React.RefObject<HTMLDivElement | null>;
126
+ onExit: () => void;
127
+ };
128
+
129
+ export function Inspector({ docId, containerRef, onExit }: Props) {
130
+ const [container, setContainer] = useState<HTMLElement | null>(null);
131
+ const [hover, setHover] = useState<InspectorTarget | null>(null);
132
+ const [selected, setSelected] = useState<InspectorTarget | null>(null);
133
+ const [target, setTarget] = useState<ResolvedTarget | null>(null);
134
+ const [drafts, setDrafts] = useState<Record<number, string>>({});
135
+ const [note, setNote] = useState('');
136
+ const [busy, setBusy] = useState(false);
137
+ const [status, setStatus] = useState<string | null>(null);
138
+ const panelRef = useRef<HTMLElement>(null);
139
+
140
+ useLayoutEffect(() => setContainer(containerRef.current), [containerRef]);
141
+
142
+ const insidePanel = useCallback(
143
+ (node: EventTarget | null) => panelRef.current?.contains(node as Node) ?? false,
144
+ [],
145
+ );
146
+
147
+ useEffect(() => {
148
+ if (!container) return;
149
+
150
+ const onMove = (e: PointerEvent) => {
151
+ if (insidePanel(e.target)) return;
152
+ setHover(targetFrom(e.target as Element));
153
+ };
154
+ const onClick = (e: MouseEvent) => {
155
+ if (insidePanel(e.target)) return;
156
+ const target = targetFrom(e.target as Element);
157
+ if (!target) return;
158
+ e.preventDefault();
159
+ e.stopPropagation();
160
+ setSelected(target);
161
+ setStatus(null);
162
+ setNote('');
163
+ };
164
+ const onKey = (e: KeyboardEvent) => {
165
+ if (e.key !== 'Escape') return;
166
+ if (selected) {
167
+ setSelected(null);
168
+ return;
169
+ }
170
+ onExit();
171
+ };
172
+
173
+ container.addEventListener('pointermove', onMove, true);
174
+ container.addEventListener('click', onClick, true);
175
+ window.addEventListener('keydown', onKey, true);
176
+ return () => {
177
+ container.removeEventListener('pointermove', onMove, true);
178
+ container.removeEventListener('click', onClick, true);
179
+ window.removeEventListener('keydown', onKey, true);
180
+ };
181
+ }, [container, insidePanel, onExit, selected]);
182
+
183
+ // Read the element's text from source, not from the DOM: only source can say
184
+ // whether it is a single editable text child or markup we must not touch.
185
+ useEffect(() => {
186
+ if (!selected) {
187
+ setTarget(null);
188
+ setDrafts({});
189
+ return;
190
+ }
191
+ let cancelled = false;
192
+ const params = new URLSearchParams({
193
+ docId,
194
+ locs: formatLocs(candidateLocs(selected.anchor)),
195
+ shown: normalize(selected.anchor.textContent ?? '').slice(0, 400),
196
+ });
197
+ fetch(`/__edit/text?${params}`)
198
+ .then((res) => res.json())
199
+ .then((body: ResolvedTarget & { error?: string }) => {
200
+ if (cancelled) return;
201
+ if (body.error) {
202
+ setTarget(null);
203
+ setStatus(body.error);
204
+ return;
205
+ }
206
+ // Last line of defence: every run the source offers has to be visible
207
+ // in the element the user clicked. A drifted resolution would
208
+ // otherwise let a save rewrite someone else's words.
209
+ const shownText = normalize(selected.anchor.textContent ?? '');
210
+ const runs = (body.parts ?? []).filter((part) => part.kind === 'text');
211
+ const belongs =
212
+ runs.length > 0 &&
213
+ runs.every((part) => part.kind === 'text' && shownText.includes(normalize(part.value)));
214
+ setTarget(
215
+ body.editable && !belongs
216
+ ? { ...body, editable: false, reason: 'source text does not match this element' }
217
+ : body,
218
+ );
219
+ setDrafts({});
220
+ })
221
+ .catch(() => {
222
+ if (!cancelled) setStatus('could not read source');
223
+ });
224
+ return () => {
225
+ cancelled = true;
226
+ };
227
+ }, [selected, docId]);
228
+
229
+ const textParts = (target?.parts ?? []).filter(
230
+ (part): part is Extract<TextPart, { kind: 'text' }> => part.kind === 'text',
231
+ );
232
+ const dirty = textParts.filter(
233
+ (part) => drafts[part.index] !== undefined && drafts[part.index] !== part.value,
234
+ );
235
+
236
+ const saveText = async () => {
237
+ if (!target || dirty.length === 0 || busy) return;
238
+ setBusy(true);
239
+ try {
240
+ for (const part of dirty) {
241
+ const res = await fetch('/__edit/text', {
242
+ method: 'PUT',
243
+ headers: { 'content-type': 'application/json' },
244
+ body: JSON.stringify({
245
+ docId,
246
+ line: target.line,
247
+ column: target.column,
248
+ index: part.index,
249
+ expected: part.value,
250
+ text: drafts[part.index],
251
+ }),
252
+ });
253
+ const body = (await res.json()) as { ok?: boolean; error?: string };
254
+ if (!res.ok || !body.ok) {
255
+ setStatus(body.error ?? 'Save failed');
256
+ return;
257
+ }
258
+ }
259
+ setStatus('Saved to source');
260
+ // Editing shifts what follows, so the captured location is good for one
261
+ // write. Reselect to edit again.
262
+ setSelected(null);
263
+ } finally {
264
+ setBusy(false);
265
+ }
266
+ };
267
+
268
+ const saveComment = async () => {
269
+ if (!selected || note.trim() === '' || busy) return;
270
+ setBusy(true);
271
+ try {
272
+ const res = await fetch('/__edit/comment', {
273
+ method: 'POST',
274
+ headers: { 'content-type': 'application/json' },
275
+ body: JSON.stringify({
276
+ docId,
277
+ line: target?.line ?? selected.line,
278
+ column: target?.column ?? selected.column,
279
+ note,
280
+ hint: selected.tag,
281
+ }),
282
+ });
283
+ const body = (await res.json()) as { ok?: boolean; error?: string };
284
+ if (res.ok && body.ok) {
285
+ setNote('');
286
+ setStatus('Marked in source — run /apply-comments');
287
+ } else {
288
+ setStatus(body.error ?? 'Could not add comment');
289
+ }
290
+ } finally {
291
+ setBusy(false);
292
+ }
293
+ };
294
+
295
+ const overlay = container
296
+ ? createPortal(
297
+ <>
298
+ <div className="pointer-events-none absolute inset-0 z-30">
299
+ <Frame
300
+ anchor={hover?.anchor === selected?.anchor ? null : (hover?.anchor ?? null)}
301
+ container={container}
302
+ variant="hover"
303
+ />
304
+ <Frame anchor={selected?.anchor ?? null} container={container} variant="selected" />
305
+ </div>
306
+ <div className="pointer-events-none sticky bottom-3 z-40 mx-auto w-fit rounded-full bg-foreground/90 px-3 py-1.5 text-[11px] text-background">
307
+ {selected ? 'Esc to deselect' : 'Click an element · Esc to exit'}
308
+ </div>
309
+ </>,
310
+ container,
311
+ )
312
+ : null;
313
+
314
+ return (
315
+ <>
316
+ {overlay}
317
+ {selected && (
318
+ <aside
319
+ ref={panelRef}
320
+ className="flex w-72 flex-none flex-col border-border border-l bg-background"
321
+ >
322
+ <header className="flex h-10 flex-none items-center justify-between border-border border-b px-3">
323
+ <span className="font-mono text-[11px] text-muted-foreground">
324
+ &lt;{selected.tag}&gt; · {target?.line ?? selected.line}:
325
+ {target?.column ?? selected.column}
326
+ </span>
327
+ <button
328
+ type="button"
329
+ aria-label="Close"
330
+ onClick={() => setSelected(null)}
331
+ className="flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
332
+ >
333
+ <X className="size-3.5" />
334
+ </button>
335
+ </header>
336
+
337
+ <div className="min-h-0 flex-1 overflow-y-auto p-3">
338
+ <span className="block text-[10px] text-muted-foreground uppercase tracking-wider">
339
+ Text
340
+ </span>
341
+ {target === null ? (
342
+ <div className="grid h-16 place-items-center">
343
+ <Loader2 className="size-3.5 animate-spin text-muted-foreground" />
344
+ </div>
345
+ ) : target.editable ? (
346
+ <>
347
+ <div className="mt-1 space-y-1.5">
348
+ {target.parts.map((part, index) =>
349
+ part.kind === 'markup' ? (
350
+ <div
351
+ // biome-ignore lint/suspicious/noArrayIndexKey: parts are positional
352
+ key={`m${index}`}
353
+ className="rounded border border-border border-dashed px-2 py-1 font-mono text-[10px] text-muted-foreground"
354
+ title="Markup is kept as written"
355
+ >
356
+ {part.label}
357
+ </div>
358
+ ) : (
359
+ <textarea
360
+ key={`t${part.index}`}
361
+ value={drafts[part.index] ?? part.value}
362
+ onChange={(e) =>
363
+ setDrafts((prev) => ({ ...prev, [part.index]: e.target.value }))
364
+ }
365
+ onKeyDown={(e) => {
366
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) void saveText();
367
+ }}
368
+ rows={Math.min(
369
+ 6,
370
+ Math.ceil((drafts[part.index] ?? part.value).length / 28) + 1,
371
+ )}
372
+ className="w-full resize-y rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none focus:border-foreground/40"
373
+ />
374
+ ),
375
+ )}
376
+ </div>
377
+ <button
378
+ type="button"
379
+ onClick={saveText}
380
+ disabled={busy || dirty.length === 0}
381
+ className="mt-1.5 flex w-full items-center justify-center gap-1.5 rounded bg-primary px-2 py-1.5 text-primary-foreground text-xs disabled:opacity-50"
382
+ >
383
+ {busy ? (
384
+ <Loader2 className="size-3 animate-spin" />
385
+ ) : (
386
+ <Check className="size-3" />
387
+ )}
388
+ {dirty.length > 1 ? `Save ${dirty.length} edits` : 'Save text'}
389
+ </button>
390
+ </>
391
+ ) : (
392
+ <p className="mt-1 rounded border border-border bg-muted px-2 py-1.5 text-[11px] text-muted-foreground">
393
+ {target.reason ?? 'Not editable here.'}
394
+ </p>
395
+ )}
396
+
397
+ <span className="mt-4 block text-[10px] text-muted-foreground uppercase tracking-wider">
398
+ Comment for the agent
399
+ </span>
400
+ <textarea
401
+ value={note}
402
+ onChange={(e) => setNote(e.target.value)}
403
+ onKeyDown={(e) => {
404
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) void saveComment();
405
+ }}
406
+ rows={3}
407
+ placeholder="make this bold, shorten to one line…"
408
+ className="mt-1 w-full resize-y rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none placeholder:text-muted-foreground/60 focus:border-foreground/40"
409
+ />
410
+ <button
411
+ type="button"
412
+ onClick={saveComment}
413
+ disabled={busy || note.trim() === ''}
414
+ className="mt-1.5 flex w-full items-center justify-center gap-1.5 rounded border border-border px-2 py-1.5 text-xs transition-colors hover:bg-accent disabled:opacity-50"
415
+ >
416
+ <MessageSquarePlus className="size-3" />
417
+ Mark comment
418
+ </button>
419
+
420
+ {status && <p className="mt-2 text-[11px] text-muted-foreground">{status}</p>}
421
+ </div>
422
+ </aside>
423
+ )}
424
+ </>
425
+ );
426
+ }
@@ -0,0 +1,70 @@
1
+ import type { CSSProperties, ReactNode } from 'react';
2
+ import { cn } from '@/lib/utils';
3
+ import { type DesignSystem, designToCssVars } from '../lib/design';
4
+ import { PAGE_ATTR, PAGE_INDEX_ATTR } from '../lib/outline';
5
+ import { DocPageProvider } from '../lib/page-context';
6
+ import type { PageGeometry } from '../lib/sdk';
7
+
8
+ type Props = {
9
+ index: number;
10
+ total: number;
11
+ geometry: PageGeometry;
12
+ scale: number;
13
+ design?: DesignSystem;
14
+ flat?: boolean;
15
+ className?: string;
16
+ children: ReactNode;
17
+ };
18
+
19
+ /**
20
+ * One sheet of paper. The inner node always lays out at the page's true pixel
21
+ * size — authors write absolute px against A4 — and only the wrapper shrinks,
22
+ * so a page looks identical on screen, in the PDF, and in the HTML export.
23
+ */
24
+ export function PageFrame({
25
+ index,
26
+ total,
27
+ geometry,
28
+ scale,
29
+ design,
30
+ flat = false,
31
+ className,
32
+ children,
33
+ }: Props) {
34
+ const designVars = design ? designToCssVars(design) : undefined;
35
+
36
+ return (
37
+ <div
38
+ className={cn(
39
+ 'relative flex-none overflow-hidden bg-white text-black',
40
+ !flat && 'shadow-[0_1px_3px_rgba(0,0,0,.28),0_10px_28px_-6px_rgba(0,0,0,.28)]',
41
+ className,
42
+ )}
43
+ style={{ width: geometry.width * scale, height: geometry.height * scale }}
44
+ >
45
+ <div
46
+ {...{ [PAGE_ATTR]: '', [PAGE_INDEX_ATTR]: index }}
47
+ style={
48
+ {
49
+ width: geometry.width,
50
+ height: geometry.height,
51
+ transform: `scale(${scale})`,
52
+ transformOrigin: 'top left',
53
+ overflow: 'hidden',
54
+ position: 'relative',
55
+ // A page must render identically wherever it is embedded. The
56
+ // thumbnail rail wraps pages in a <button>, whose default
57
+ // `text-align: center` would otherwise leak into the content.
58
+ textAlign: 'start',
59
+ ...(designVars ?? {}),
60
+ ...(designVars ? { background: 'var(--od-bg)', color: 'var(--od-text)' } : {}),
61
+ } as CSSProperties
62
+ }
63
+ >
64
+ <DocPageProvider index={index} total={total}>
65
+ {children}
66
+ </DocPageProvider>
67
+ </div>
68
+ </div>
69
+ );
70
+ }
@@ -0,0 +1,212 @@
1
+ import { FileText, Image, MoreHorizontal, Palette, PencilLine, Trash2 } from 'lucide-react';
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import type { Folder, FolderIcon } from '../../lib/sdk';
4
+ import { cn } from '../../lib/utils';
5
+ import { Menu, MenuItem, MenuSeparator } from '../ui/menu';
6
+ import { IconPicker } from './icon-picker';
7
+
8
+ export const DOC_DND_MIME = 'application/x-open-doc-id';
9
+
10
+ export type FolderRow =
11
+ | { kind: 'all' }
12
+ | { kind: 'themes' }
13
+ | { kind: 'assets' }
14
+ | { kind: 'draft' }
15
+ | {
16
+ kind: 'folder';
17
+ folder: Folder;
18
+ onRename: (name: string) => void;
19
+ onChangeIcon: (icon: FolderIcon) => void;
20
+ onDelete: () => void;
21
+ };
22
+
23
+ export function FolderIconChip({ icon }: { icon: FolderIcon }) {
24
+ if (icon.type === 'emoji') {
25
+ return (
26
+ <span className="grid size-5 shrink-0 place-items-center text-[13px] leading-none">
27
+ {icon.value}
28
+ </span>
29
+ );
30
+ }
31
+ return (
32
+ <span
33
+ className="size-3 shrink-0 rounded-[3px] ring-1 ring-black/10"
34
+ style={{ background: icon.value }}
35
+ />
36
+ );
37
+ }
38
+
39
+ const STATIC_ICON = {
40
+ all: FileText,
41
+ themes: Palette,
42
+ assets: Image,
43
+ } as const;
44
+
45
+ export function FolderItem({
46
+ row,
47
+ count,
48
+ selected,
49
+ onSelect,
50
+ onDropDoc,
51
+ }: {
52
+ row: FolderRow;
53
+ count: number;
54
+ selected: boolean;
55
+ onSelect: () => void;
56
+ onDropDoc: (docId: string) => void;
57
+ }) {
58
+ const [renaming, setRenaming] = useState(false);
59
+ const [draft, setDraft] = useState('');
60
+ const [dragOver, setDragOver] = useState(false);
61
+ const inputRef = useRef<HTMLInputElement>(null);
62
+
63
+ useEffect(() => {
64
+ if (renaming) inputRef.current?.select();
65
+ }, [renaming]);
66
+
67
+ const label =
68
+ row.kind === 'folder'
69
+ ? row.folder.name
70
+ : row.kind === 'all'
71
+ ? 'Documents'
72
+ : row.kind === 'themes'
73
+ ? 'Themes'
74
+ : row.kind === 'assets'
75
+ ? 'Assets'
76
+ : 'Unfiled';
77
+
78
+ const acceptsDrop = row.kind === 'folder' || row.kind === 'draft';
79
+
80
+ const commitRename = () => {
81
+ if (row.kind !== 'folder') return;
82
+ const next = draft.trim();
83
+ setRenaming(false);
84
+ if (next && next !== row.folder.name) row.onRename(next);
85
+ };
86
+
87
+ return (
88
+ // biome-ignore lint/a11y/noStaticElementInteractions: drop target wraps the button, which stays the keyboard path
89
+ <div
90
+ className={cn(
91
+ 'group relative flex items-center gap-2 rounded-md px-2 py-1.5 transition-colors',
92
+ selected ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent/60',
93
+ dragOver && 'ring-1 ring-foreground/40',
94
+ )}
95
+ onDragOver={(e) => {
96
+ if (!acceptsDrop || !e.dataTransfer.types.includes(DOC_DND_MIME)) return;
97
+ e.preventDefault();
98
+ e.dataTransfer.dropEffect = 'move';
99
+ setDragOver(true);
100
+ }}
101
+ onDragLeave={() => setDragOver(false)}
102
+ onDrop={(e) => {
103
+ if (!acceptsDrop) return;
104
+ const docId = e.dataTransfer.getData(DOC_DND_MIME);
105
+ setDragOver(false);
106
+ if (!docId) return;
107
+ e.preventDefault();
108
+ onDropDoc(docId);
109
+ }}
110
+ >
111
+ {row.kind === 'folder' ? (
112
+ <Menu
113
+ placement="right-start"
114
+ trigger={(props) => (
115
+ <button
116
+ type="button"
117
+ aria-label="Change icon"
118
+ className="shrink-0 transition-transform hover:scale-110"
119
+ {...props}
120
+ >
121
+ <FolderIconChip icon={row.folder.icon} />
122
+ </button>
123
+ )}
124
+ >
125
+ {() => (
126
+ <div className="p-1">
127
+ <IconPicker value={row.folder.icon} onChange={row.onChangeIcon} />
128
+ </div>
129
+ )}
130
+ </Menu>
131
+ ) : row.kind === 'draft' ? (
132
+ <FolderIconChip icon={{ type: 'color', value: '#9ca3af' }} />
133
+ ) : (
134
+ (() => {
135
+ const Icon = STATIC_ICON[row.kind];
136
+ return <Icon className="size-3.5 shrink-0" />;
137
+ })()
138
+ )}
139
+
140
+ {renaming && row.kind === 'folder' ? (
141
+ <input
142
+ ref={inputRef}
143
+ value={draft}
144
+ onChange={(e) => setDraft(e.target.value)}
145
+ onBlur={commitRename}
146
+ onKeyDown={(e) => {
147
+ if (e.nativeEvent.isComposing) return;
148
+ if (e.key === 'Enter') commitRename();
149
+ if (e.key === 'Escape') setRenaming(false);
150
+ }}
151
+ maxLength={40}
152
+ className="min-w-0 flex-1 bg-transparent text-[13px] outline-none"
153
+ />
154
+ ) : (
155
+ <button
156
+ type="button"
157
+ onClick={onSelect}
158
+ className="min-w-0 flex-1 truncate text-left text-[13px]"
159
+ >
160
+ {label}
161
+ </button>
162
+ )}
163
+
164
+ <span className="font-mono text-[10px] text-muted-foreground tabular-nums group-hover:opacity-0">
165
+ {String(count).padStart(2, '0')}
166
+ </span>
167
+
168
+ {row.kind === 'folder' && import.meta.env.DEV && (
169
+ <div className="absolute right-1.5 opacity-0 transition-opacity group-hover:opacity-100">
170
+ <Menu
171
+ trigger={(props) => (
172
+ <button
173
+ type="button"
174
+ aria-label={`${row.folder.name} options`}
175
+ className="flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-background hover:text-foreground aria-expanded:bg-background"
176
+ {...props}
177
+ >
178
+ <MoreHorizontal className="size-3.5" />
179
+ </button>
180
+ )}
181
+ >
182
+ {(close) => (
183
+ <>
184
+ <MenuItem
185
+ onClick={() => {
186
+ setDraft(row.folder.name);
187
+ setRenaming(true);
188
+ close();
189
+ }}
190
+ >
191
+ <PencilLine className="size-3.5" />
192
+ Rename
193
+ </MenuItem>
194
+ <MenuSeparator />
195
+ <MenuItem
196
+ destructive
197
+ onClick={() => {
198
+ close();
199
+ row.onDelete();
200
+ }}
201
+ >
202
+ <Trash2 className="size-3.5" />
203
+ Delete folder
204
+ </MenuItem>
205
+ </>
206
+ )}
207
+ </Menu>
208
+ </div>
209
+ )}
210
+ </div>
211
+ );
212
+ }