devnonla-ui 0.8.0 → 0.9.1

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 (59) hide show
  1. package/README.md +31 -4
  2. package/package.json +3 -3
  3. package/src/app/App.tsx +5 -1
  4. package/src/app/context.ts +5 -3
  5. package/src/button/Button.tsx +2 -2
  6. package/src/button/ButtonCopy.tsx +2 -2
  7. package/src/card/Card.tsx +81 -0
  8. package/src/chat/AgentChatbox.tsx +1 -1
  9. package/src/chat/AgentPanel.tsx +1 -1
  10. package/src/chat/message-ui/ChatError.tsx +2 -2
  11. package/src/chat/message-ui/ChatInput.tsx +5 -5
  12. package/src/chat/message-ui/ChatMarkdown.tsx +8 -7
  13. package/src/chat/message-ui/ChatThinking.tsx +3 -3
  14. package/src/chat/message-ui/ChatUserMessage.tsx +3 -3
  15. package/src/chat/message-ui/MermaidBlock.tsx +68 -39
  16. package/src/chat/tool-ui/BackgroundTasksBar.tsx +3 -3
  17. package/src/chat/tool-ui/CallAgentToolUI.tsx +3 -3
  18. package/src/chat/tool-ui/ChatToolCall.tsx +4 -4
  19. package/src/chat/tool-ui/GetCurrentTimeToolUI.tsx +2 -2
  20. package/src/chat/tool-ui/ReadSkillToolUI.tsx +2 -2
  21. package/src/chat/tool-ui/RunJsToolUI.tsx +2 -2
  22. package/src/chat/tool-ui/ToolUiTrailing.tsx +3 -3
  23. package/src/chat/tool-ui/WebFetchToolUI.tsx +2 -2
  24. package/src/checkbox/Checkbox.tsx +17 -4
  25. package/src/codeblock/CodeBlock.tsx +2 -2
  26. package/src/datepicker/DatePicker.tsx +3 -3
  27. package/src/desktop/DesktopHeader.tsx +1 -1
  28. package/src/desktop/DesktopIcon.tsx +2 -2
  29. package/src/desktop/DesktopWindow.tsx +51 -29
  30. package/src/empty/Empty.tsx +8 -5
  31. package/src/form/FormItem.tsx +1 -1
  32. package/src/form-layout/FormLayout.tsx +1 -1
  33. package/src/icon/SolarIcon.tsx +39 -0
  34. package/src/icon/solar.ts +172 -0
  35. package/src/index.ts +24 -12
  36. package/src/input/EditableInput.tsx +3 -3
  37. package/src/input/Input.tsx +3 -3
  38. package/src/lib/sizes.ts +9 -6
  39. package/src/lib/surface.ts +1 -1
  40. package/src/markdown-editor/MarkdownDiff.tsx +211 -0
  41. package/src/markdown-editor/MarkdownEditor.tsx +301 -0
  42. package/src/markdown-editor/MarkdownPreview.tsx +346 -0
  43. package/src/markdown-editor/MarkdownSource.tsx +72 -0
  44. package/src/markdown-editor/blocks.ts +329 -0
  45. package/src/markdown-editor/diff.ts +296 -0
  46. package/src/menu/Menu.tsx +3 -3
  47. package/src/pagination/Pagination.tsx +8 -7
  48. package/src/segmented/Segmented.tsx +2 -2
  49. package/src/select/Select.tsx +192 -63
  50. package/src/sidebar/Sidebar.tsx +9 -8
  51. package/src/spin/Spin.tsx +17 -11
  52. package/src/styles.css +265 -110
  53. package/src/switch/Switch.tsx +17 -3
  54. package/src/table/Table.tsx +61 -26
  55. package/src/theme-toggle/ThemeToggle.tsx +33 -0
  56. package/src/theme.ts +72 -0
  57. package/src/timepicker/TimePicker.tsx +1 -1
  58. package/src/icon/FluentIcon.tsx +0 -28
  59. package/src/icon/fluent.ts +0 -75
@@ -0,0 +1,301 @@
1
+ import { type CSSProperties, type MouseEvent, type ReactNode, useCallback, useMemo, useRef, useState } from "react";
2
+ import { SolarIcon } from "../icon/SolarIcon";
3
+ import { cn } from "../lib/cn";
4
+ import { Segmented } from "../segmented/Segmented";
5
+ import { appendTextBlock, cleanupDoc, joinMarkdownDoc, type MarkdownDoc, parseMarkdownDoc, readInlineEdit, splitListItem } from "./blocks";
6
+ import { diffMarkdown } from "./diff";
7
+ import { MarkdownDiff, type MarkdownDiffLayout } from "./MarkdownDiff";
8
+ import { MarkdownPreview } from "./MarkdownPreview";
9
+ import { MarkdownSource } from "./MarkdownSource";
10
+
11
+ export type MarkdownEditorMode = "preview" | "edit" | "diff";
12
+ export type { MarkdownDiffLayout };
13
+
14
+ export type MarkdownEditorProps = {
15
+ /** Current markdown. In diff mode this is the modified version. */
16
+ value?: string;
17
+ defaultValue?: string;
18
+ onChange?: (value: string) => void;
19
+ /** Earlier version. Enables the Diff view. */
20
+ original?: string;
21
+ mode?: MarkdownEditorMode;
22
+ defaultMode?: MarkdownEditorMode;
23
+ onModeChange?: (mode: MarkdownEditorMode) => void;
24
+ /** Monaco-style layout. Side by side is the default. */
25
+ diffLayout?: MarkdownDiffLayout;
26
+ defaultDiffLayout?: MarkdownDiffLayout;
27
+ onDiffLayoutChange?: (layout: MarkdownDiffLayout) => void;
28
+ readOnly?: boolean;
29
+ placeholder?: string;
30
+ title?: ReactNode;
31
+ originalLabel?: ReactNode;
32
+ modifiedLabel?: ReactNode;
33
+ className?: string;
34
+ style?: CSSProperties;
35
+ };
36
+
37
+ type EditSession = {
38
+ index: number;
39
+ doc: MarkdownDoc;
40
+ /** Restored on blur when an appended paragraph is still empty. */
41
+ revert?: string;
42
+ caret?: "start" | "end";
43
+ };
44
+
45
+ function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void): [T, (next: T) => void] {
46
+ const [uncontrolled, setUncontrolled] = useState(defaultValue);
47
+ const isControlled = value !== undefined;
48
+ const current = isControlled ? (value as T) : uncontrolled;
49
+ const set = useCallback(
50
+ (next: T) => {
51
+ if (!isControlled) setUncontrolled(next);
52
+ onChange?.(next);
53
+ },
54
+ [isControlled, onChange],
55
+ );
56
+ return [current, set];
57
+ }
58
+
59
+ /**
60
+ * Markdown editor in the style of Cursor's document editor.
61
+ *
62
+ * Preview renders the document. Click a heading, list item, or paragraph to edit that text in place.
63
+ * Mermaid fences render as diagrams and stay view only.
64
+ * Edit is the full-file text buffer. Diff compares `original` and `value` like Monaco.
65
+ * `readOnly` locks editing and hides the mode switcher, so preview can show a finished document.
66
+ */
67
+ export function MarkdownEditor({
68
+ value: valueProp,
69
+ defaultValue = "",
70
+ onChange,
71
+ original,
72
+ mode: modeProp,
73
+ defaultMode = "preview",
74
+ onModeChange,
75
+ diffLayout: layoutProp,
76
+ defaultDiffLayout = "side-by-side",
77
+ onDiffLayoutChange,
78
+ readOnly = false,
79
+ placeholder = "Write markdown…",
80
+ title,
81
+ originalLabel = "Original",
82
+ modifiedLabel = "Modified",
83
+ className,
84
+ style,
85
+ }: MarkdownEditorProps) {
86
+ const [value, setValue] = useControllable(valueProp, defaultValue, onChange);
87
+ const [mode, setMode] = useControllable(modeProp, defaultMode, onModeChange);
88
+ const [layout, setLayout] = useControllable(layoutProp, defaultDiffLayout, onDiffLayoutChange);
89
+ const [session, setSession] = useState<EditSession | null>(null);
90
+
91
+ const sessionRef = useRef<EditSession | null>(session);
92
+ sessionRef.current = session;
93
+ const valueRef = useRef(value);
94
+ const seenProp = useRef(value);
95
+ const switching = useRef(false);
96
+
97
+ let live = session;
98
+ if (value !== seenProp.current) {
99
+ seenProp.current = value;
100
+ const current = sessionRef.current;
101
+ const same = current ? joinMarkdownDoc(current.doc) === value : false;
102
+ if (current && !same) {
103
+ live = null;
104
+ sessionRef.current = null;
105
+ setSession(null);
106
+ }
107
+ valueRef.current = value;
108
+ }
109
+
110
+ const emit = useCallback(
111
+ (next: string) => {
112
+ if (next === valueRef.current) return;
113
+ valueRef.current = next;
114
+ setValue(next);
115
+ },
116
+ [setValue],
117
+ );
118
+
119
+ const currentDoc = (): MarkdownDoc => {
120
+ const current = sessionRef.current;
121
+ if (!current) return parseMarkdownDoc(valueRef.current);
122
+ const block = current.doc.blocks[current.index];
123
+ if (current.revert !== undefined && block?.kind === "text" && block.body.trim() === "") return parseMarkdownDoc(current.revert);
124
+ return current.doc;
125
+ };
126
+
127
+ const startEdit = (index: number): boolean => {
128
+ if (readOnly || mode !== "preview") return false;
129
+ const doc = currentDoc();
130
+ const block = doc.blocks[index];
131
+ if (!block || block.kind === "mermaid") return false;
132
+ const next: EditSession = { index, doc };
133
+ sessionRef.current = next;
134
+ setSession(next);
135
+ const joined = joinMarkdownDoc(doc);
136
+ if (joined !== valueRef.current) emit(joined);
137
+ return true;
138
+ };
139
+
140
+ const updateBody = (body: string) => {
141
+ const current = sessionRef.current;
142
+ if (!current) return;
143
+ const blocks = current.doc.blocks.map((block, index) => (index === current.index ? { ...block, body } : block));
144
+ const next: EditSession = { ...current, doc: { ...current.doc, blocks } };
145
+ sessionRef.current = next;
146
+ setSession(next);
147
+ emit(joinMarkdownDoc(next.doc));
148
+ };
149
+
150
+ const commit = () => {
151
+ const current = sessionRef.current;
152
+ if (!current) return;
153
+ const block = current.doc.blocks[current.index];
154
+ sessionRef.current = null;
155
+ setSession(null);
156
+ if (current.revert !== undefined && block?.kind === "text" && block.body.trim() === "") {
157
+ emit(current.revert);
158
+ return;
159
+ }
160
+ const next = joinMarkdownDoc(cleanupDoc(current.doc));
161
+ if (next !== valueRef.current) emit(next);
162
+ };
163
+
164
+ const enterList = (before: string, after: string) => {
165
+ const current = sessionRef.current;
166
+ if (!current) return;
167
+ const block = current.doc.blocks[current.index];
168
+ if (!block) return;
169
+ const view = readInlineEdit(block.body);
170
+ if (view.kind !== "list") return;
171
+ switching.current = true;
172
+ if (before.trim() === "" && after.trim() === "") {
173
+ const blocks = current.doc.blocks.slice();
174
+ blocks[current.index] = { ...block, body: "" };
175
+ const next: EditSession = { ...current, doc: { ...current.doc, blocks }, caret: "start" };
176
+ sessionRef.current = next;
177
+ setSession(next);
178
+ emit(joinMarkdownDoc(next.doc));
179
+ return;
180
+ }
181
+ const split = splitListItem(current.doc, current.index, before, after);
182
+ if (!split) {
183
+ switching.current = false;
184
+ return;
185
+ }
186
+ const next: EditSession = { index: split.index, doc: split.doc, revert: current.revert, caret: "start" };
187
+ sessionRef.current = next;
188
+ setSession(next);
189
+ emit(joinMarkdownDoc(split.doc));
190
+ };
191
+
192
+ const onBlurBlock = () => {
193
+ if (switching.current) {
194
+ switching.current = false;
195
+ return;
196
+ }
197
+ commit();
198
+ };
199
+
200
+ const onEditMouseDown = (index: number, event: MouseEvent) => {
201
+ const current = sessionRef.current;
202
+ if (!current || current.index === index) return;
203
+ if (event.target instanceof Element && event.target.closest("a, button, textarea, input")) return;
204
+ const block = current.doc.blocks[index];
205
+ if (!block || block.kind === "mermaid") return;
206
+ event.preventDefault();
207
+ if (startEdit(index)) switching.current = true;
208
+ };
209
+
210
+ const append = () => {
211
+ if (readOnly) return;
212
+ const current = sessionRef.current;
213
+ if (current) {
214
+ const block = current.doc.blocks[current.index];
215
+ if (block?.kind === "text" && block.body.trim() === "" && current.index === current.doc.blocks.length - 1) return;
216
+ }
217
+ const base = currentDoc();
218
+ const doc = appendTextBlock(base);
219
+ const next: EditSession = { index: doc.blocks.length - 1, doc, revert: joinMarkdownDoc(base) };
220
+ sessionRef.current = next;
221
+ setSession(next);
222
+ emit(joinMarkdownDoc(doc));
223
+ };
224
+
225
+ const changeMode = (next: MarkdownEditorMode) => {
226
+ if (next === "diff" && original === undefined) return;
227
+ commit();
228
+ setMode(next);
229
+ };
230
+
231
+ const doc = live?.doc ?? parseMarkdownDoc(valueRef.current);
232
+ const model = useMemo(() => (mode === "diff" && original !== undefined ? diffMarkdown(original, value) : null), [mode, original, value]);
233
+ const showModes = !readOnly;
234
+ const showHeader = Boolean(title) || showModes || model !== null;
235
+
236
+ return (
237
+ <div role="region" className={cn("nonla-markdown-editor flex h-full min-h-96 flex-col overflow-hidden rounded-xl border border-border bg-card text-foreground", className)} style={style} aria-label={typeof title === "string" ? title : "Markdown editor"}>
238
+ {showHeader ? (
239
+ <div className="flex h-10 shrink-0 items-center justify-between gap-3 border-b border-border px-2">
240
+ <div className="min-w-0 truncate px-1 text-sm font-medium">{title}</div>
241
+ <div className="flex shrink-0 items-center gap-2">
242
+ {model ? (
243
+ <span className="font-mono text-xs">
244
+ {model.added === 0 && model.removed === 0 ? (
245
+ <span className="text-muted-foreground">No changes</span>
246
+ ) : (
247
+ <>
248
+ <span className="text-success">+{model.added}</span> <span className="text-destructive">−{model.removed}</span>
249
+ </>
250
+ )}
251
+ </span>
252
+ ) : null}
253
+ {mode === "diff" && original !== undefined ? (
254
+ <Segmented
255
+ size="small"
256
+ value={layout}
257
+ onChange={setLayout}
258
+ options={[
259
+ { label: "Inline", value: "inline" },
260
+ { label: "Split", value: "side-by-side" },
261
+ ]}
262
+ />
263
+ ) : null}
264
+ {showModes ? (
265
+ <Segmented
266
+ size="small"
267
+ value={mode}
268
+ onChange={changeMode}
269
+ options={[
270
+ { label: "Preview", value: "preview", icon: <SolarIcon name="eye-linear" size={14} /> },
271
+ { label: "Edit", value: "edit", icon: <SolarIcon name="pen-linear" size={14} /> },
272
+ { label: "Diff", value: "diff", icon: <SolarIcon name="transfer-horizontal-linear" size={14} />, disabled: original === undefined },
273
+ ]}
274
+ />
275
+ ) : null}
276
+ </div>
277
+ </div>
278
+ ) : null}
279
+ <div className="min-h-0 flex-1">
280
+ {mode === "edit" ? <MarkdownSource value={value} onChange={emit} readOnly={readOnly} placeholder={placeholder} /> : null}
281
+ {mode === "preview" ? (
282
+ <MarkdownPreview
283
+ doc={doc}
284
+ editingIndex={live?.index ?? null}
285
+ readOnly={readOnly}
286
+ placeholder={placeholder}
287
+ onStartEdit={startEdit}
288
+ onEditMouseDown={onEditMouseDown}
289
+ onChangeBody={updateBody}
290
+ onBlurBlock={onBlurBlock}
291
+ onEnterList={enterList}
292
+ caret={live?.caret}
293
+ onAppend={append}
294
+ />
295
+ ) : null}
296
+ {mode === "diff" && model ? <MarkdownDiff model={model} layout={layout} originalLabel={originalLabel} modifiedLabel={modifiedLabel} /> : null}
297
+ {mode === "diff" && !model ? <p className="px-4 py-6 text-sm text-muted-foreground">Pass original to compare two versions.</p> : null}
298
+ </div>
299
+ </div>
300
+ );
301
+ }
@@ -0,0 +1,346 @@
1
+ import { type MouseEvent, type ReactNode, useLayoutEffect, useRef } from "react";
2
+ import ReactMarkdown, { type Components } from "react-markdown";
3
+ import remarkGfm from "remark-gfm";
4
+ import { ChatMarkdownTable } from "../chat/message-ui/ChatMarkdownTable";
5
+ import { MermaidBlock } from "../chat/message-ui/MermaidBlock";
6
+ import { Checkbox } from "../checkbox/Checkbox";
7
+ import { CodeBlock } from "../codeblock/CodeBlock";
8
+ import { cn } from "../lib/cn";
9
+ import { OverlayScroll } from "../scroll/OverlayScroll";
10
+ import { type InlineEdit, type MarkdownBlock, type MarkdownDoc, readFence, readInlineEdit, writeInlineEdit } from "./blocks";
11
+
12
+ const documentClass = cn(
13
+ "min-w-0 text-[15px] leading-7 text-foreground",
14
+ "[&_h1]:my-0 [&_h1]:text-[32px] [&_h1]:leading-tight [&_h1]:font-bold [&_h1]:tracking-tight",
15
+ "[&_h2]:my-0 [&_h2]:text-[24px] [&_h2]:leading-tight [&_h2]:font-bold [&_h2]:tracking-tight",
16
+ "[&_h3]:my-0 [&_h3]:text-[20px] [&_h3]:leading-snug [&_h3]:font-semibold",
17
+ "[&_h4]:my-0 [&_h4]:text-[18px] [&_h4]:leading-snug [&_h4]:font-semibold",
18
+ "[&_h5]:my-0 [&_h5]:text-[16px] [&_h5]:leading-snug [&_h5]:font-semibold",
19
+ "[&_h6]:my-0 [&_h6]:text-[15px] [&_h6]:leading-snug [&_h6]:font-semibold",
20
+ "[&_p]:my-0",
21
+ "[&_ul]:my-1 [&_ul]:list-disc [&_ul]:pl-6",
22
+ "[&_ol]:my-1 [&_ol]:list-decimal [&_ol]:pl-6",
23
+ "[&_ul.contains-task-list]:list-none",
24
+ "[&_li]:my-0.5",
25
+ "[&_li.task-list-item]:relative",
26
+ "[&_li.task-list-item>.nonla-md-task-check]:absolute [&_li.task-list-item>.nonla-md-task-check]:top-1 [&_li.task-list-item>.nonla-md-task-check]:-left-5",
27
+ "[&_blockquote]:my-1 [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground",
28
+ "[&_a]:text-link [&_a]:underline-offset-[3px] hover:[&_a]:underline",
29
+ "[&_hr]:my-2 [&_hr]:border-border",
30
+ "[&_strong]:font-semibold",
31
+ "[&_img]:my-1 [&_img]:max-w-full [&_img]:rounded-lg",
32
+ );
33
+
34
+ const previewComponents: Components = {
35
+ code({ className, children }) {
36
+ const match = /language-(\w+)/.exec(className || "");
37
+ const lang = match?.[1] ?? "";
38
+ const codeText = String(children).replace(/\n$/, "");
39
+ const isBlock = codeText.includes("\n") || !!match;
40
+ if (!isBlock) {
41
+ return <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-[0.9em]">{children}</code>;
42
+ }
43
+ if (lang.toLowerCase() === "mermaid") return <MermaidView code={codeText} />;
44
+ return <CodeBlock code={codeText} language={lang || undefined} className="my-2" />;
45
+ },
46
+ table({ children }) {
47
+ return <ChatMarkdownTable>{children}</ChatMarkdownTable>;
48
+ },
49
+ a({ href, children, ...props }) {
50
+ return (
51
+ <a href={href} target="_blank" rel="noopener noreferrer" {...props}>
52
+ {children}
53
+ </a>
54
+ );
55
+ },
56
+ input({ type, checked }) {
57
+ if (type !== "checkbox") return <input type={type} checked={checked} readOnly />;
58
+ return (
59
+ <span className="nonla-md-task-check pointer-events-none inline-flex h-7 items-center">
60
+ <Checkbox checked={Boolean(checked)} tabIndex={-1} />
61
+ </span>
62
+ );
63
+ },
64
+ };
65
+
66
+ function MermaidView({ code }: { code: string }) {
67
+ if (!code.trim()) {
68
+ return <div className="rounded-xl border border-dashed border-border px-4 py-6 text-center text-xs text-muted-foreground">Empty diagram</div>;
69
+ }
70
+ return <MermaidBlock className="my-0">{code}</MermaidBlock>;
71
+ }
72
+
73
+ function headingClass(level: number): string {
74
+ if (level === 1) return "text-[32px] font-bold leading-tight tracking-tight";
75
+ if (level === 2) return "text-[24px] font-bold leading-tight tracking-tight";
76
+ if (level === 3) return "text-[20px] font-semibold leading-snug";
77
+ if (level === 4) return "text-[18px] font-semibold leading-snug";
78
+ if (level === 5) return "text-[16px] font-semibold leading-snug";
79
+ return "text-[15px] font-semibold leading-snug";
80
+ }
81
+
82
+ function BlockEditor({ value, mono, className, caret = "end", onChange, onBlur, onEnter }: { value: string; mono?: boolean; className?: string; caret?: "start" | "end"; onChange: (value: string) => void; onBlur: () => void; onEnter?: (before: string, after: string) => void }) {
83
+ const ref = useRef<HTMLTextAreaElement>(null);
84
+
85
+ useLayoutEffect(() => {
86
+ const el = ref.current;
87
+ if (!el) return;
88
+ el.focus();
89
+ const pos = caret === "start" ? 0 : el.value.length;
90
+ el.setSelectionRange(pos, pos);
91
+ }, []);
92
+
93
+ useLayoutEffect(() => {
94
+ const el = ref.current;
95
+ if (!el) return;
96
+ el.style.height = "auto";
97
+ el.style.height = `${el.scrollHeight}px`;
98
+ }, [value]);
99
+
100
+ return (
101
+ <textarea
102
+ ref={ref}
103
+ data-md-editor="block"
104
+ value={value}
105
+ rows={1}
106
+ spellCheck={!mono}
107
+ onChange={(event) => onChange(event.target.value)}
108
+ onBlur={onBlur}
109
+ onKeyDown={(event) => {
110
+ if (event.key === "Escape") {
111
+ event.preventDefault();
112
+ event.currentTarget.blur();
113
+ return;
114
+ }
115
+ if (event.key === "Enter" && onEnter && !event.shiftKey && !event.nativeEvent.isComposing) {
116
+ event.preventDefault();
117
+ const el = event.currentTarget;
118
+ onEnter(value.slice(0, el.selectionStart), value.slice(el.selectionEnd));
119
+ return;
120
+ }
121
+ if (event.key !== "Tab") return;
122
+ event.preventDefault();
123
+ const el = event.currentTarget;
124
+ const start = el.selectionStart;
125
+ const end = el.selectionEnd;
126
+ const next = `${value.slice(0, start)} ${value.slice(end)}`;
127
+ onChange(next);
128
+ const pos = start + 2;
129
+ requestAnimationFrame(() => {
130
+ el.selectionStart = pos;
131
+ el.selectionEnd = pos;
132
+ });
133
+ }}
134
+ className={cn(
135
+ "block w-full resize-none overflow-hidden border-0 bg-transparent p-0 text-[15px] leading-7 text-foreground shadow-none outline-none ring-0 placeholder:text-placeholder focus:outline-none focus:ring-0",
136
+ mono && "font-mono text-[13px] leading-5",
137
+ className,
138
+ )}
139
+ aria-label="Edit markdown"
140
+ />
141
+ );
142
+ }
143
+
144
+ function interactiveTarget(target: EventTarget | null): boolean {
145
+ return target instanceof Element && !!target.closest("a, button, textarea, input");
146
+ }
147
+
148
+ export type MarkdownPreviewProps = {
149
+ doc: MarkdownDoc;
150
+ editingIndex: number | null;
151
+ readOnly?: boolean;
152
+ placeholder?: string;
153
+ onStartEdit: (index: number) => boolean;
154
+ onEditMouseDown: (index: number, event: MouseEvent) => void;
155
+ onChangeBody: (body: string) => void;
156
+ onBlurBlock: () => void;
157
+ onEnterList: (before: string, after: string) => void;
158
+ /** Where the caret goes when an edit starts. */
159
+ caret?: "start" | "end";
160
+ onAppend: () => void;
161
+ };
162
+
163
+ type MdNode = {
164
+ type: string;
165
+ value?: string;
166
+ children?: MdNode[];
167
+ };
168
+
169
+ /** A single Enter stays a visible line after the block editor closes. */
170
+ function remarkKeepLineBreaks() {
171
+ return (tree: MdNode) => {
172
+ breakParagraphLines(tree);
173
+ };
174
+ }
175
+
176
+ function breakParagraphLines(node: MdNode) {
177
+ if (!node.children) return;
178
+ if (node.type === "paragraph" || node.type === "heading") {
179
+ splitInlineBreaks(node);
180
+ return;
181
+ }
182
+ for (const child of node.children) breakParagraphLines(child);
183
+ }
184
+
185
+ function splitInlineBreaks(node: MdNode) {
186
+ if (!node.children) return;
187
+ node.children = node.children.flatMap((child) => {
188
+ if (child.type === "inlineCode" || child.type === "code") return [child];
189
+ splitInlineBreaks(child);
190
+ return splitSoftBreaks(child);
191
+ });
192
+ }
193
+
194
+ function splitSoftBreaks(node: MdNode): MdNode[] {
195
+ if (node.type !== "text" || !node.value?.includes("\n")) return [node];
196
+ const parts = node.value.split("\n");
197
+ const out: MdNode[] = [];
198
+ for (let index = 0; index < parts.length; index++) {
199
+ if (index > 0) out.push({ type: "break" });
200
+ const part = parts[index] ?? "";
201
+ if (part.length > 0) out.push({ type: "text", value: part });
202
+ }
203
+ return out;
204
+ }
205
+
206
+ function RichText({ source }: { source: string }) {
207
+ return (
208
+ <div className={documentClass}>
209
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkKeepLineBreaks]} components={previewComponents}>
210
+ {source}
211
+ </ReactMarkdown>
212
+ </div>
213
+ );
214
+ }
215
+
216
+ function ListItem({ view, children }: { view: Extract<InlineEdit, { kind: "list" }>; children: ReactNode }) {
217
+ const level = Math.floor(view.indent.length / 2);
218
+ const ordinal = Number(/^(\d+)/.exec(view.marker)?.[1] ?? "1");
219
+ return (
220
+ <div className="flex items-start gap-1.5" style={level > 0 ? { marginLeft: `${level * 1.25}rem` } : undefined}>
221
+ {view.task ? (
222
+ <span className="pointer-events-none inline-flex h-7 w-5 shrink-0 items-center justify-center">
223
+ <Checkbox checked={view.checked} tabIndex={-1} />
224
+ </span>
225
+ ) : view.ordered ? (
226
+ <span className="w-6 shrink-0 text-right text-[15px] leading-7 tabular-nums">{ordinal}.</span>
227
+ ) : (
228
+ <span className="flex h-7 w-5 shrink-0 items-center justify-center" aria-hidden>
229
+ <span className="size-1.5 rounded-full bg-current" />
230
+ </span>
231
+ )}
232
+ <div className="min-w-0 flex-1">{children}</div>
233
+ </div>
234
+ );
235
+ }
236
+
237
+ function isListBlock(block: MarkdownBlock): boolean {
238
+ return block.kind === "text" && readInlineEdit(block.body).kind === "list";
239
+ }
240
+
241
+ function headingGap(level: number): string {
242
+ if (level <= 2) return "mt-6";
243
+ if (level === 3) return "mt-5";
244
+ if (level === 4) return "mt-4";
245
+ return "mt-3";
246
+ }
247
+
248
+ function spaceBefore(block: MarkdownBlock, prev?: MarkdownBlock): string {
249
+ if (!prev) return "";
250
+ if (isListBlock(block) && isListBlock(prev)) return "mt-0.5";
251
+ if (block.kind === "text") {
252
+ const view = readInlineEdit(block.body);
253
+ if (view.kind === "heading") return headingGap(view.level);
254
+ }
255
+ if (prev.kind === "text" && readInlineEdit(prev.body).kind === "heading") return "mt-2";
256
+ return "mt-3";
257
+ }
258
+
259
+ function BlockBody({ block }: { block: MarkdownBlock }): ReactNode {
260
+ if (block.kind === "mermaid") {
261
+ const fence = readFence(block.body);
262
+ return <MermaidView code={fence?.code ?? block.body} />;
263
+ }
264
+ if (block.kind === "code") {
265
+ const fence = readFence(block.body);
266
+ if (!fence) return <CodeBlock code={block.body} className="my-0" />;
267
+ return <CodeBlock code={fence.code} language={fence.lang || undefined} className="my-0" />;
268
+ }
269
+ const view = readInlineEdit(block.body);
270
+ if (view.kind === "list") {
271
+ return (
272
+ <ListItem view={view}>
273
+ <RichText source={view.text} />
274
+ </ListItem>
275
+ );
276
+ }
277
+ return <RichText source={block.body} />;
278
+ }
279
+
280
+ export function MarkdownPreview({ doc, editingIndex, readOnly, placeholder = "Write markdown…", onStartEdit, onEditMouseDown, onChangeBody, onBlurBlock, onEnterList, caret = "end", onAppend }: MarkdownPreviewProps) {
281
+ return (
282
+ <OverlayScroll className="h-full bg-card">
283
+ <div className="mx-auto flex w-full max-w-3xl flex-col px-8 py-6">
284
+ {doc.blocks.map((block, index) => {
285
+ const editing = editingIndex === index;
286
+ const locked = block.kind === "mermaid" || readOnly;
287
+ const view = block.kind === "text" ? readInlineEdit(block.body) : null;
288
+ const editor =
289
+ view?.kind === "heading" ? (
290
+ <BlockEditor value={view.text} className={headingClass(view.level)} caret={caret} onChange={(text) => onChangeBody(writeInlineEdit(block.body, text))} onBlur={onBlurBlock} />
291
+ ) : view?.kind === "list" ? (
292
+ <ListItem view={view}>
293
+ <BlockEditor value={view.text} caret={caret} onEnter={onEnterList} onChange={(text) => onChangeBody(writeInlineEdit(block.body, text))} onBlur={onBlurBlock} />
294
+ </ListItem>
295
+ ) : (
296
+ <BlockEditor value={block.body} mono={block.kind === "code"} caret={caret} onChange={onChangeBody} onBlur={onBlurBlock} />
297
+ );
298
+ const gap = spaceBefore(block, doc.blocks[index - 1]);
299
+ if (locked) {
300
+ return (
301
+ <div
302
+ // biome-ignore lint/suspicious/noArrayIndexKey: block position is the edit identity
303
+ key={`${index}:${block.kind}`}
304
+ data-md-block={block.kind}
305
+ className={cn("outline-none", gap)}
306
+ >
307
+ <BlockBody block={block} />
308
+ </div>
309
+ );
310
+ }
311
+ return (
312
+ <div
313
+ // biome-ignore lint/suspicious/noArrayIndexKey: block position is the edit identity
314
+ key={`${index}:${block.kind}`}
315
+ role="button"
316
+ data-md-block={block.kind}
317
+ tabIndex={0}
318
+ className={cn("cursor-text outline-none", gap)}
319
+ onMouseDown={(event) => onEditMouseDown(index, event)}
320
+ onClick={(event) => {
321
+ if (editing || interactiveTarget(event.target)) return;
322
+ const selection = window.getSelection();
323
+ if (selection && selection.toString().length > 0) return;
324
+ onStartEdit(index);
325
+ }}
326
+ onKeyDown={(event) => {
327
+ if (editing || event.key !== "Enter") return;
328
+ event.preventDefault();
329
+ onStartEdit(index);
330
+ }}
331
+ >
332
+ {editing ? editor : <BlockBody block={block} />}
333
+ </div>
334
+ );
335
+ })}
336
+ {readOnly ? (
337
+ doc.blocks.length === 0 ? <p className="m-0 text-sm text-placeholder">{placeholder}</p> : null
338
+ ) : (
339
+ <button type="button" className="mt-3 min-h-16 text-left text-sm text-placeholder" onClick={onAppend} aria-label="Add paragraph">
340
+ {doc.blocks.length === 0 ? placeholder : ""}
341
+ </button>
342
+ )}
343
+ </div>
344
+ </OverlayScroll>
345
+ );
346
+ }