devnonla-ui 0.9.0 → 0.10.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.
@@ -62,6 +62,8 @@ function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (v
62
62
  * Preview renders the document. Click a heading, list item, or paragraph to edit that text in place.
63
63
  * Mermaid fences render as diagrams and stay view only.
64
64
  * Edit is the full-file text buffer. Diff compares `original` and `value` like Monaco.
65
+ * `readOnly` locks editing and hides the mode switcher.
66
+ * A finished document with no editor chrome uses `MarkdownViewer`.
65
67
  */
66
68
  export function MarkdownEditor({
67
69
  value: valueProp,
@@ -229,46 +231,52 @@ export function MarkdownEditor({
229
231
 
230
232
  const doc = live?.doc ?? parseMarkdownDoc(valueRef.current);
231
233
  const model = useMemo(() => (mode === "diff" && original !== undefined ? diffMarkdown(original, value) : null), [mode, original, value]);
234
+ const showModes = !readOnly;
235
+ const showHeader = Boolean(title) || showModes || model !== null;
232
236
 
233
237
  return (
234
238
  <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"}>
235
- <div className="flex h-10 shrink-0 items-center justify-between gap-3 border-b border-border px-2">
236
- <div className="min-w-0 truncate px-1 text-sm font-medium">{title}</div>
237
- <div className="flex shrink-0 items-center gap-2">
238
- {model ? (
239
- <span className="font-mono text-xs">
240
- {model.added === 0 && model.removed === 0 ? (
241
- <span className="text-muted-foreground">No changes</span>
242
- ) : (
243
- <>
244
- <span className="text-success">+{model.added}</span> <span className="text-destructive">−{model.removed}</span>
245
- </>
246
- )}
247
- </span>
248
- ) : null}
249
- {mode === "diff" && original !== undefined ? (
250
- <Segmented
251
- size="small"
252
- value={layout}
253
- onChange={setLayout}
254
- options={[
255
- { label: "Inline", value: "inline" },
256
- { label: "Split", value: "side-by-side" },
257
- ]}
258
- />
259
- ) : null}
260
- <Segmented
261
- size="small"
262
- value={mode}
263
- onChange={changeMode}
264
- options={[
265
- { label: "Preview", value: "preview", icon: <SolarIcon name="eye-linear" size={14} /> },
266
- { label: "Edit", value: "edit", icon: <SolarIcon name="pen-linear" size={14} /> },
267
- { label: "Diff", value: "diff", icon: <SolarIcon name="transfer-horizontal-linear" size={14} />, disabled: original === undefined },
268
- ]}
269
- />
239
+ {showHeader ? (
240
+ <div className="flex h-10 shrink-0 items-center justify-between gap-3 border-b border-border px-2">
241
+ <div className="min-w-0 truncate px-1 text-sm font-medium">{title}</div>
242
+ <div className="flex shrink-0 items-center gap-2">
243
+ {model ? (
244
+ <span className="font-mono text-xs">
245
+ {model.added === 0 && model.removed === 0 ? (
246
+ <span className="text-muted-foreground">No changes</span>
247
+ ) : (
248
+ <>
249
+ <span className="text-success">+{model.added}</span> <span className="text-destructive">−{model.removed}</span>
250
+ </>
251
+ )}
252
+ </span>
253
+ ) : null}
254
+ {mode === "diff" && original !== undefined ? (
255
+ <Segmented
256
+ size="small"
257
+ value={layout}
258
+ onChange={setLayout}
259
+ options={[
260
+ { label: "Inline", value: "inline" },
261
+ { label: "Split", value: "side-by-side" },
262
+ ]}
263
+ />
264
+ ) : null}
265
+ {showModes ? (
266
+ <Segmented
267
+ size="small"
268
+ value={mode}
269
+ onChange={changeMode}
270
+ options={[
271
+ { label: "Preview", value: "preview", icon: <SolarIcon name="eye-linear" size={14} /> },
272
+ { label: "Edit", value: "edit", icon: <SolarIcon name="pen-linear" size={14} /> },
273
+ { label: "Diff", value: "diff", icon: <SolarIcon name="transfer-horizontal-linear" size={14} />, disabled: original === undefined },
274
+ ]}
275
+ />
276
+ ) : null}
277
+ </div>
270
278
  </div>
271
- </div>
279
+ ) : null}
272
280
  <div className="min-h-0 flex-1">
273
281
  {mode === "edit" ? <MarkdownSource value={value} onChange={emit} readOnly={readOnly} placeholder={placeholder} /> : null}
274
282
  {mode === "preview" ? (
@@ -1,83 +1,8 @@
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";
1
+ import { type MouseEvent, useLayoutEffect, useRef } from "react";
8
2
  import { cn } from "../lib/cn";
9
3
  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-[1.75rem] [&_h1]:leading-tight [&_h1]:font-semibold",
15
- "[&_h2]:my-0 [&_h2]:text-[1.35rem] [&_h2]:leading-tight [&_h2]:font-semibold",
16
- "[&_h3]:my-0 [&_h3]:text-[1.15rem] [&_h3]:leading-snug [&_h3]:font-semibold",
17
- "[&_:is(h4,h5,h6)]:my-0 [&_:is(h4,h5,h6)]:text-base [&_:is(h4,h5,h6)]:font-semibold",
18
- "[&_p]:my-0",
19
- "[&_ul]:my-1 [&_ul]:list-disc [&_ul]:pl-6",
20
- "[&_ol]:my-1 [&_ol]:list-decimal [&_ol]:pl-6",
21
- "[&_ul.contains-task-list]:list-none",
22
- "[&_li]:my-0.5",
23
- "[&_li.task-list-item]:relative",
24
- "[&_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",
25
- "[&_blockquote]:my-1 [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground",
26
- "[&_a]:text-link [&_a]:underline-offset-[3px] hover:[&_a]:underline",
27
- "[&_hr]:my-2 [&_hr]:border-border",
28
- "[&_strong]:font-semibold",
29
- "[&_img]:my-1 [&_img]:max-w-full [&_img]:rounded-lg",
30
- );
31
-
32
- const previewComponents: Components = {
33
- code({ className, children }) {
34
- const match = /language-(\w+)/.exec(className || "");
35
- const lang = match?.[1] ?? "";
36
- const codeText = String(children).replace(/\n$/, "");
37
- const isBlock = codeText.includes("\n") || !!match;
38
- if (!isBlock) {
39
- return <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-[0.9em]">{children}</code>;
40
- }
41
- if (lang.toLowerCase() === "mermaid") return <MermaidView code={codeText} />;
42
- return <CodeBlock code={codeText} language={lang || undefined} className="my-2" />;
43
- },
44
- table({ children }) {
45
- return <ChatMarkdownTable>{children}</ChatMarkdownTable>;
46
- },
47
- a({ href, children, ...props }) {
48
- return (
49
- <a href={href} target="_blank" rel="noopener noreferrer" {...props}>
50
- {children}
51
- </a>
52
- );
53
- },
54
- input({ type, checked }) {
55
- if (type !== "checkbox") return <input type={type} checked={checked} readOnly />;
56
- return (
57
- <span className="nonla-md-task-check pointer-events-none inline-flex h-7 items-center">
58
- <Checkbox
59
- checked={Boolean(checked)}
60
- tabIndex={-1}
61
- className="data-[state=checked]:border-white data-[state=checked]:bg-white data-[state=checked]:text-(--nonla-bg) data-[state=indeterminate]:border-white data-[state=indeterminate]:bg-white data-[state=indeterminate]:text-(--nonla-bg)"
62
- />
63
- </span>
64
- );
65
- },
66
- };
67
-
68
- function MermaidView({ code }: { code: string }) {
69
- if (!code.trim()) {
70
- return <div className="rounded-xl border border-dashed border-border px-4 py-6 text-center text-xs text-muted-foreground">Empty diagram</div>;
71
- }
72
- return <MermaidBlock className="my-0">{code}</MermaidBlock>;
73
- }
74
-
75
- function headingClass(level: number): string {
76
- if (level === 1) return "text-[1.75rem] font-semibold leading-tight";
77
- if (level === 2) return "text-[1.35rem] font-semibold leading-tight";
78
- if (level === 3) return "text-[1.15rem] font-semibold leading-snug";
79
- return "text-base font-semibold leading-snug";
80
- }
4
+ import { type MarkdownDoc, readInlineEdit, writeInlineEdit } from "./blocks";
5
+ import { BlockBody, headingClass, ListItem, spaceBefore } from "./MarkdownViewer";
81
6
 
82
7
  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
8
  const ref = useRef<HTMLTextAreaElement>(null);
@@ -160,116 +85,6 @@ export type MarkdownPreviewProps = {
160
85
  onAppend: () => void;
161
86
  };
162
87
 
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
224
- checked={view.checked}
225
- tabIndex={-1}
226
- className="data-[state=checked]:border-white data-[state=checked]:bg-white data-[state=checked]:text-(--nonla-bg) data-[state=indeterminate]:border-white data-[state=indeterminate]:bg-white data-[state=indeterminate]:text-(--nonla-bg)"
227
- />
228
- </span>
229
- ) : view.ordered ? (
230
- <span className="w-6 shrink-0 text-right text-[15px] leading-7 tabular-nums">{ordinal}.</span>
231
- ) : (
232
- <span className="flex h-7 w-5 shrink-0 items-center justify-center" aria-hidden>
233
- <span className="size-1.5 rounded-full bg-current" />
234
- </span>
235
- )}
236
- <div className="min-w-0 flex-1">{children}</div>
237
- </div>
238
- );
239
- }
240
-
241
- function isListBlock(block: MarkdownBlock): boolean {
242
- return block.kind === "text" && readInlineEdit(block.body).kind === "list";
243
- }
244
-
245
- function spaceBefore(block: MarkdownBlock, prev?: MarkdownBlock): string {
246
- if (!prev) return "";
247
- if (isListBlock(block) && isListBlock(prev)) return "mt-0.5";
248
- if (block.kind === "text" && readInlineEdit(block.body).kind === "heading") return "mt-6";
249
- return "mt-3";
250
- }
251
-
252
- function BlockBody({ block }: { block: MarkdownBlock }): ReactNode {
253
- if (block.kind === "mermaid") {
254
- const fence = readFence(block.body);
255
- return <MermaidView code={fence?.code ?? block.body} />;
256
- }
257
- if (block.kind === "code") {
258
- const fence = readFence(block.body);
259
- if (!fence) return <CodeBlock code={block.body} className="my-0" />;
260
- return <CodeBlock code={fence.code} language={fence.lang || undefined} className="my-0" />;
261
- }
262
- const view = readInlineEdit(block.body);
263
- if (view.kind === "list") {
264
- return (
265
- <ListItem view={view}>
266
- <RichText source={view.text} />
267
- </ListItem>
268
- );
269
- }
270
- return <RichText source={block.body} />;
271
- }
272
-
273
88
  export function MarkdownPreview({ doc, editingIndex, readOnly, placeholder = "Write markdown…", onStartEdit, onEditMouseDown, onChangeBody, onBlurBlock, onEnterList, caret = "end", onAppend }: MarkdownPreviewProps) {
274
89
  return (
275
90
  <OverlayScroll className="h-full bg-card">
@@ -288,23 +103,36 @@ export function MarkdownPreview({ doc, editingIndex, readOnly, placeholder = "Wr
288
103
  ) : (
289
104
  <BlockEditor value={block.body} mono={block.kind === "code"} caret={caret} onChange={onChangeBody} onBlur={onBlurBlock} />
290
105
  );
106
+ const gap = spaceBefore(block, doc.blocks[index - 1]);
107
+ if (locked) {
108
+ return (
109
+ <div
110
+ // biome-ignore lint/suspicious/noArrayIndexKey: block position is the edit identity
111
+ key={`${index}:${block.kind}`}
112
+ data-md-block={block.kind}
113
+ className={cn("outline-none", gap)}
114
+ >
115
+ <BlockBody block={block} />
116
+ </div>
117
+ );
118
+ }
291
119
  return (
292
120
  <div
293
121
  // biome-ignore lint/suspicious/noArrayIndexKey: block position is the edit identity
294
122
  key={`${index}:${block.kind}`}
295
123
  role="button"
296
124
  data-md-block={block.kind}
297
- tabIndex={locked ? undefined : 0}
298
- className={cn("outline-none", !locked && "cursor-text", spaceBefore(block, doc.blocks[index - 1]))}
125
+ tabIndex={0}
126
+ className={cn("cursor-text outline-none", gap)}
299
127
  onMouseDown={(event) => onEditMouseDown(index, event)}
300
128
  onClick={(event) => {
301
- if (locked || editing || interactiveTarget(event.target)) return;
129
+ if (editing || interactiveTarget(event.target)) return;
302
130
  const selection = window.getSelection();
303
131
  if (selection && selection.toString().length > 0) return;
304
132
  onStartEdit(index);
305
133
  }}
306
134
  onKeyDown={(event) => {
307
- if (locked || editing || event.key !== "Enter") return;
135
+ if (editing || event.key !== "Enter") return;
308
136
  event.preventDefault();
309
137
  onStartEdit(index);
310
138
  }}
@@ -1,5 +1,5 @@
1
1
  import { type ReactNode, useCallback, useRef } from "react";
2
- import { ButtonCopy } from "../../button/ButtonCopy";
2
+ import { ButtonCopy } from "../button/ButtonCopy";
3
3
 
4
4
  function escapeCell(text: string): string {
5
5
  return text.replace(/\|/g, "\\|").replace(/\n+/g, "").trim();
@@ -20,7 +20,7 @@ function tableToMarkdown(table: HTMLTableElement): string {
20
20
  return [`| ${header.join(" | ")} |`, `| ${separator.join(" | ")} |`, ...body.map((row) => `| ${row.join(" | ")} |`)].join("\n");
21
21
  }
22
22
 
23
- export function ChatMarkdownTable({ children }: { children: ReactNode }) {
23
+ export function MarkdownTable({ children }: { children: ReactNode }) {
24
24
  const tableRef = useRef<HTMLTableElement>(null);
25
25
 
26
26
  const getText = useCallback(() => {
@@ -0,0 +1,235 @@
1
+ import { type ReactNode, useMemo } from "react";
2
+ import ReactMarkdown, { type Components } from "react-markdown";
3
+ import remarkGfm from "remark-gfm";
4
+ import { Checkbox } from "../checkbox/Checkbox";
5
+ import { CodeBlock } from "../codeblock/CodeBlock";
6
+ import { cn } from "../lib/cn";
7
+ import { type InlineEdit, type MarkdownBlock, parseMarkdownDoc, readFence, readInlineEdit } from "./blocks";
8
+ import { MarkdownTable } from "./MarkdownTable";
9
+ import { MermaidBlock } from "./MermaidBlock";
10
+
11
+ const documentClass = cn(
12
+ "min-w-0 wrap-anywhere text-[15px] leading-7 text-foreground",
13
+ "[&_h1]:my-0 [&_h1]:text-[32px] [&_h1]:leading-tight [&_h1]:font-bold [&_h1]:tracking-tight",
14
+ "[&_h2]:my-0 [&_h2]:text-[24px] [&_h2]:leading-tight [&_h2]:font-bold [&_h2]:tracking-tight",
15
+ "[&_h3]:my-0 [&_h3]:text-[20px] [&_h3]:leading-snug [&_h3]:font-semibold",
16
+ "[&_h4]:my-0 [&_h4]:text-[18px] [&_h4]:leading-snug [&_h4]:font-semibold",
17
+ "[&_h5]:my-0 [&_h5]:text-[16px] [&_h5]:leading-snug [&_h5]:font-semibold",
18
+ "[&_h6]:my-0 [&_h6]:text-[15px] [&_h6]:leading-snug [&_h6]:font-semibold",
19
+ "[&_p]:my-0",
20
+ "[&_ul]:my-1 [&_ul]:list-disc [&_ul]:pl-6",
21
+ "[&_ol]:my-1 [&_ol]:list-decimal [&_ol]:pl-6",
22
+ "[&_ul.contains-task-list]:list-none",
23
+ "[&_li]:my-0.5",
24
+ "[&_li.task-list-item]:relative",
25
+ "[&_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",
26
+ "[&_blockquote]:my-1 [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground",
27
+ "[&_a]:text-link [&_a]:underline-offset-[3px] hover:[&_a]:underline",
28
+ "[&_hr]:my-2 [&_hr]:border-border",
29
+ "[&_strong]:font-semibold",
30
+ "[&_img]:my-1 [&_img]:max-w-full [&_img]:rounded-lg",
31
+ );
32
+
33
+ const previewComponents: Components = {
34
+ code({ className, children }) {
35
+ const match = /language-(\w+)/.exec(className || "");
36
+ const lang = match?.[1] ?? "";
37
+ const codeText = String(children).replace(/\n$/, "");
38
+ const isBlock = codeText.includes("\n") || !!match;
39
+ if (!isBlock) {
40
+ return <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-[0.9em]">{children}</code>;
41
+ }
42
+ if (lang.toLowerCase() === "mermaid") return <MermaidView code={codeText} />;
43
+ return <CodeBlock code={codeText} language={lang || undefined} className="my-2" />;
44
+ },
45
+ table({ children }) {
46
+ return <MarkdownTable>{children}</MarkdownTable>;
47
+ },
48
+ a({ href, children, ...props }) {
49
+ return (
50
+ <a href={href} target="_blank" rel="noopener noreferrer" {...props}>
51
+ {children}
52
+ </a>
53
+ );
54
+ },
55
+ input({ type, checked }) {
56
+ if (type !== "checkbox") return <input type={type} checked={checked} readOnly />;
57
+ return (
58
+ <span className="nonla-md-task-check pointer-events-none inline-flex h-7 items-center">
59
+ <Checkbox checked={Boolean(checked)} tabIndex={-1} />
60
+ </span>
61
+ );
62
+ },
63
+ };
64
+
65
+ function MermaidView({ code }: { code: string }) {
66
+ if (!code.trim()) {
67
+ return <div className="rounded-xl border border-dashed border-border px-4 py-6 text-center text-xs text-muted-foreground">Empty diagram</div>;
68
+ }
69
+ return <MermaidBlock className="my-0">{code}</MermaidBlock>;
70
+ }
71
+
72
+ export function headingClass(level: number): string {
73
+ if (level === 1) return "text-[32px] font-bold leading-tight tracking-tight";
74
+ if (level === 2) return "text-[24px] font-bold leading-tight tracking-tight";
75
+ if (level === 3) return "text-[20px] font-semibold leading-snug";
76
+ if (level === 4) return "text-[18px] font-semibold leading-snug";
77
+ if (level === 5) return "text-[16px] font-semibold leading-snug";
78
+ return "text-[15px] font-semibold leading-snug";
79
+ }
80
+
81
+ type MdNode = {
82
+ type: string;
83
+ value?: string;
84
+ children?: MdNode[];
85
+ };
86
+
87
+ /** A single Enter stays a visible line after the block editor closes. */
88
+ function remarkKeepLineBreaks() {
89
+ return (tree: MdNode) => {
90
+ breakParagraphLines(tree);
91
+ };
92
+ }
93
+
94
+ function breakParagraphLines(node: MdNode) {
95
+ if (!node.children) return;
96
+ if (node.type === "paragraph" || node.type === "heading") {
97
+ splitInlineBreaks(node);
98
+ return;
99
+ }
100
+ for (const child of node.children) breakParagraphLines(child);
101
+ }
102
+
103
+ function splitInlineBreaks(node: MdNode) {
104
+ if (!node.children) return;
105
+ node.children = node.children.flatMap((child) => {
106
+ if (child.type === "inlineCode" || child.type === "code") return [child];
107
+ splitInlineBreaks(child);
108
+ return splitSoftBreaks(child);
109
+ });
110
+ }
111
+
112
+ function splitSoftBreaks(node: MdNode): MdNode[] {
113
+ if (node.type !== "text" || !node.value?.includes("\n")) return [node];
114
+ const parts = node.value.split("\n");
115
+ const out: MdNode[] = [];
116
+ for (let index = 0; index < parts.length; index++) {
117
+ if (index > 0) out.push({ type: "break" });
118
+ const part = parts[index] ?? "";
119
+ if (part.length > 0) out.push({ type: "text", value: part });
120
+ }
121
+ return out;
122
+ }
123
+
124
+ function RichText({ source }: { source: string }) {
125
+ return (
126
+ <div className={documentClass}>
127
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkKeepLineBreaks]} components={previewComponents}>
128
+ {source}
129
+ </ReactMarkdown>
130
+ </div>
131
+ );
132
+ }
133
+
134
+ export function ListItem({ view, children }: { view: Extract<InlineEdit, { kind: "list" }>; children: ReactNode }) {
135
+ const level = Math.floor(view.indent.length / 2);
136
+ const ordinal = Number(/^(\d+)/.exec(view.marker)?.[1] ?? "1");
137
+ return (
138
+ <div className="flex items-start gap-1.5" style={level > 0 ? { marginLeft: `${level * 1.25}rem` } : undefined}>
139
+ {view.task ? (
140
+ <span className="pointer-events-none inline-flex h-7 w-5 shrink-0 items-center justify-center">
141
+ <Checkbox checked={view.checked} tabIndex={-1} />
142
+ </span>
143
+ ) : view.ordered ? (
144
+ <span className="w-6 shrink-0 text-right text-[15px] leading-7 tabular-nums">{ordinal}.</span>
145
+ ) : (
146
+ <span className="flex h-7 w-5 shrink-0 items-center justify-center" aria-hidden>
147
+ <span className="size-1.5 rounded-full bg-current" />
148
+ </span>
149
+ )}
150
+ <div className="min-w-0 flex-1">{children}</div>
151
+ </div>
152
+ );
153
+ }
154
+
155
+ function isListBlock(block: MarkdownBlock): boolean {
156
+ return block.kind === "text" && readInlineEdit(block.body).kind === "list";
157
+ }
158
+
159
+ function headingGap(level: number): string {
160
+ if (level <= 2) return "mt-6";
161
+ if (level === 3) return "mt-5";
162
+ if (level === 4) return "mt-4";
163
+ return "mt-3";
164
+ }
165
+
166
+ export function spaceBefore(block: MarkdownBlock, prev?: MarkdownBlock): string {
167
+ if (!prev) return "";
168
+ if (isListBlock(block) && isListBlock(prev)) return "mt-0.5";
169
+ if (block.kind === "text") {
170
+ const view = readInlineEdit(block.body);
171
+ if (view.kind === "heading") return headingGap(view.level);
172
+ }
173
+ if (prev.kind === "text" && readInlineEdit(prev.body).kind === "heading") return "mt-2";
174
+ return "mt-3";
175
+ }
176
+
177
+ function fenceClosed(body: string): boolean {
178
+ const lines = body.split("\n");
179
+ if (lines.length < 2) return false;
180
+ const last = (lines[lines.length - 1] ?? "").trim();
181
+ return /^(?:`{3,}|~{3,})$/.test(last);
182
+ }
183
+
184
+ export function BlockBody({ block, streaming }: { block: MarkdownBlock; streaming?: boolean }): ReactNode {
185
+ if (block.kind === "mermaid") {
186
+ const fence = readFence(block.body);
187
+ const code = fence?.code ?? block.body;
188
+ if (streaming && !fenceClosed(block.body)) return <CodeBlock code={code} language="mermaid" className="my-0" />;
189
+ return <MermaidView code={code} />;
190
+ }
191
+ if (block.kind === "code") {
192
+ const fence = readFence(block.body);
193
+ if (!fence) return <CodeBlock code={block.body} className="my-0" />;
194
+ return <CodeBlock code={fence.code} language={fence.lang || undefined} className="my-0" />;
195
+ }
196
+ const view = readInlineEdit(block.body);
197
+ if (view.kind === "list") {
198
+ return (
199
+ <ListItem view={view}>
200
+ <RichText source={view.text} />
201
+ </ListItem>
202
+ );
203
+ }
204
+ return <RichText source={block.body} />;
205
+ }
206
+
207
+ export type MarkdownViewerProps = {
208
+ value?: string;
209
+ /** An open mermaid fence stays a code block until the stream closes it. */
210
+ streaming?: boolean;
211
+ placeholder?: string;
212
+ className?: string;
213
+ };
214
+
215
+ /** Read-only markdown. Same blocks as the editor preview, without editing. */
216
+ export function MarkdownViewer({ value = "", streaming = false, placeholder, className }: MarkdownViewerProps) {
217
+ const doc = useMemo(() => parseMarkdownDoc(value), [value]);
218
+ if (doc.blocks.length === 0) {
219
+ return placeholder ? <p className={cn("m-0 text-sm text-placeholder", className)}>{placeholder}</p> : null;
220
+ }
221
+ return (
222
+ <div className={cn("nonla-markdown-viewer flex min-w-0 flex-col text-foreground", className)}>
223
+ {doc.blocks.map((block, index) => (
224
+ <div
225
+ // biome-ignore lint/suspicious/noArrayIndexKey: block position is the document identity
226
+ key={`${index}:${block.kind}`}
227
+ data-md-block={block.kind}
228
+ className={cn("outline-none", spaceBefore(block, doc.blocks[index - 1]))}
229
+ >
230
+ <BlockBody block={block} streaming={streaming} />
231
+ </div>
232
+ ))}
233
+ </div>
234
+ );
235
+ }
@@ -1,9 +1,9 @@
1
1
  import { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
2
- import { Button } from "../../button/Button";
3
- import { CodeBlock } from "../../codeblock/CodeBlock";
4
- import { SolarIcon } from "../../icon/SolarIcon";
5
- import { cn } from "../../lib/cn";
6
- import { getColorMode, subscribeColorMode } from "../../theme";
2
+ import { Button } from "../button/Button";
3
+ import { CodeBlock } from "../codeblock/CodeBlock";
4
+ import { SolarIcon } from "../icon/SolarIcon";
5
+ import { cn } from "../lib/cn";
6
+ import { getColorMode, subscribeColorMode } from "../theme";
7
7
  import { sanitizeMermaid } from "./sanitizeMermaid";
8
8
 
9
9
  /** Official Mermaid palettes: `default` is light, `dark` is dark. */
@@ -198,7 +198,7 @@ export function MermaidBlock({ children, className }: MermaidBlockProps) {
198
198
 
199
199
  <dialog
200
200
  ref={dialogRef}
201
- className="m-0 p-0 w-screen h-screen max-w-none max-h-none backdrop:bg-black/40 open:flex open:flex-col bg-card"
201
+ className="inset-2.5 m-0 h-auto w-auto max-h-none max-w-none overflow-hidden rounded-xl border border-foreground/25 bg-card p-0 shadow-xl backdrop:bg-black/40 open:flex open:flex-col"
202
202
  onClose={resetView}
203
203
  onKeyDown={(e) => {
204
204
  if (e.key !== "Escape") return;
@@ -207,14 +207,14 @@ export function MermaidBlock({ children, className }: MermaidBlockProps) {
207
207
  closeFullscreen();
208
208
  }}
209
209
  >
210
- <div className="fixed top-5 right-5 z-50 flex items-center gap-1.5">
210
+ <div className="absolute top-5 right-5 z-50 flex items-center gap-1.5">
211
211
  <Button size="small" icon={<SolarIcon name="download-linear" size={12} />} title="Download SVG" aria-label="Download SVG" onClick={downloadSvg} disabled={!svgContent} />
212
212
  <Button size="small" icon={<SolarIcon name="minimize-linear" size={12} />} title="Exit fullscreen" onClick={closeFullscreen}>
213
213
  Exit
214
214
  </Button>
215
215
  </div>
216
216
 
217
- <div className="fixed bottom-5 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 px-3 py-1.5 rounded-full border border-border text-xs text-muted-foreground shadow-md select-none bg-card">
217
+ <div className="absolute bottom-5 left-1/2 z-50 flex -translate-x-1/2 items-center gap-2 rounded-full border border-border bg-card px-3 py-1.5 text-xs text-muted-foreground shadow-md select-none">
218
218
  <span>{Math.round(zoom * 100)}%</span>
219
219
  {!isDefaultView ? (
220
220
  <Button type="text" size="small" onClick={resetView}>