devnonla-ui 0.9.1 → 0.11.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.
@@ -0,0 +1,264 @@
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
+ import { ReactCode } from "./ReactCode";
11
+ import { ReactCodeSandbox } from "./ReactCodeSandbox";
12
+
13
+ const documentClass = cn(
14
+ "min-w-0 wrap-anywhere text-[15px] leading-7 text-foreground",
15
+ "[&_h1]:my-0 [&_h1]:text-[32px] [&_h1]:leading-tight [&_h1]:font-bold [&_h1]:tracking-tight",
16
+ "[&_h2]:my-0 [&_h2]:text-[24px] [&_h2]:leading-tight [&_h2]:font-bold [&_h2]:tracking-tight",
17
+ "[&_h3]:my-0 [&_h3]:text-[20px] [&_h3]:leading-snug [&_h3]:font-semibold",
18
+ "[&_h4]:my-0 [&_h4]:text-[18px] [&_h4]:leading-snug [&_h4]:font-semibold",
19
+ "[&_h5]:my-0 [&_h5]:text-[16px] [&_h5]:leading-snug [&_h5]:font-semibold",
20
+ "[&_h6]:my-0 [&_h6]:text-[15px] [&_h6]:leading-snug [&_h6]:font-semibold",
21
+ "[&_p]:my-0",
22
+ "[&_ul]:my-1 [&_ul]:list-disc [&_ul]:pl-6",
23
+ "[&_ol]:my-1 [&_ol]:list-decimal [&_ol]:pl-6",
24
+ "[&_ul.contains-task-list]:list-none",
25
+ "[&_li]:my-0.5",
26
+ "[&_li.task-list-item]:relative",
27
+ "[&_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",
28
+ "[&_blockquote]:my-1 [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground",
29
+ "[&_a]:text-link [&_a]:underline-offset-[3px] hover:[&_a]:underline",
30
+ "[&_hr]:my-2 [&_hr]:border-border",
31
+ "[&_strong]:font-semibold",
32
+ "[&_img]:my-1 [&_img]:max-w-full [&_img]:rounded-lg",
33
+ );
34
+
35
+ const previewComponents: Components = {
36
+ code({ className, children }) {
37
+ const match = /language-(\w+)/.exec(className || "");
38
+ const lang = match?.[1] ?? "";
39
+ const codeText = String(children).replace(/\n$/, "");
40
+ const isBlock = codeText.includes("\n") || !!match;
41
+ if (!isBlock) {
42
+ return <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-[0.9em]">{children}</code>;
43
+ }
44
+ if (lang.toLowerCase() === "mermaid") return <MermaidView code={codeText} />;
45
+ return <CodeBlock code={codeText} language={lang || undefined} className="my-2" />;
46
+ },
47
+ table({ children }) {
48
+ return <MarkdownTable>{children}</MarkdownTable>;
49
+ },
50
+ a({ href, children, ...props }) {
51
+ return (
52
+ <a href={href} target="_blank" rel="noopener noreferrer" {...props}>
53
+ {children}
54
+ </a>
55
+ );
56
+ },
57
+ input({ type, checked }) {
58
+ if (type !== "checkbox") return <input type={type} checked={checked} readOnly />;
59
+ return (
60
+ <span className="nonla-md-task-check pointer-events-none inline-flex h-7 items-center">
61
+ <Checkbox checked={Boolean(checked)} tabIndex={-1} />
62
+ </span>
63
+ );
64
+ },
65
+ };
66
+
67
+ function MermaidView({ code }: { code: string }) {
68
+ if (!code.trim()) {
69
+ return <div className="rounded-xl border border-dashed border-border px-4 py-6 text-center text-xs text-muted-foreground">Empty diagram</div>;
70
+ }
71
+ return <MermaidBlock className="my-0">{code}</MermaidBlock>;
72
+ }
73
+
74
+ export function headingClass(level: number): string {
75
+ if (level === 1) return "text-[32px] font-bold leading-tight tracking-tight";
76
+ if (level === 2) return "text-[24px] font-bold leading-tight tracking-tight";
77
+ if (level === 3) return "text-[20px] font-semibold leading-snug";
78
+ if (level === 4) return "text-[18px] font-semibold leading-snug";
79
+ if (level === 5) return "text-[16px] font-semibold leading-snug";
80
+ return "text-[15px] font-semibold leading-snug";
81
+ }
82
+
83
+ type MdNode = {
84
+ type: string;
85
+ value?: string;
86
+ children?: MdNode[];
87
+ };
88
+
89
+ /** A single Enter stays a visible line after the block editor closes. */
90
+ function remarkKeepLineBreaks() {
91
+ return (tree: MdNode) => {
92
+ breakParagraphLines(tree);
93
+ };
94
+ }
95
+
96
+ function breakParagraphLines(node: MdNode) {
97
+ if (!node.children) return;
98
+ if (node.type === "paragraph" || node.type === "heading") {
99
+ splitInlineBreaks(node);
100
+ return;
101
+ }
102
+ for (const child of node.children) breakParagraphLines(child);
103
+ }
104
+
105
+ function splitInlineBreaks(node: MdNode) {
106
+ if (!node.children) return;
107
+ node.children = node.children.flatMap((child) => {
108
+ if (child.type === "inlineCode" || child.type === "code") return [child];
109
+ splitInlineBreaks(child);
110
+ return splitSoftBreaks(child);
111
+ });
112
+ }
113
+
114
+ function splitSoftBreaks(node: MdNode): MdNode[] {
115
+ if (node.type !== "text" || !node.value?.includes("\n")) return [node];
116
+ const parts = node.value.split("\n");
117
+ const out: MdNode[] = [];
118
+ for (let index = 0; index < parts.length; index++) {
119
+ if (index > 0) out.push({ type: "break" });
120
+ const part = parts[index] ?? "";
121
+ if (part.length > 0) out.push({ type: "text", value: part });
122
+ }
123
+ return out;
124
+ }
125
+
126
+ function RichText({ source }: { source: string }) {
127
+ return (
128
+ <div className={documentClass}>
129
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkKeepLineBreaks]} components={previewComponents}>
130
+ {source}
131
+ </ReactMarkdown>
132
+ </div>
133
+ );
134
+ }
135
+
136
+ export function ListItem({ view, children }: { view: Extract<InlineEdit, { kind: "list" }>; children: ReactNode }) {
137
+ const level = Math.floor(view.indent.length / 2);
138
+ const ordinal = Number(/^(\d+)/.exec(view.marker)?.[1] ?? "1");
139
+ return (
140
+ <div className="flex items-start gap-1.5" style={level > 0 ? { marginLeft: `${level * 1.25}rem` } : undefined}>
141
+ {view.task ? (
142
+ <span className="pointer-events-none inline-flex h-7 w-5 shrink-0 items-center justify-center">
143
+ <Checkbox checked={view.checked} tabIndex={-1} />
144
+ </span>
145
+ ) : view.ordered ? (
146
+ <span className="w-6 shrink-0 text-right text-[15px] leading-7 tabular-nums">{ordinal}.</span>
147
+ ) : (
148
+ <span className="flex h-7 w-5 shrink-0 items-center justify-center" aria-hidden>
149
+ <span className="size-1.5 rounded-full bg-current" />
150
+ </span>
151
+ )}
152
+ <div className="min-w-0 flex-1">{children}</div>
153
+ </div>
154
+ );
155
+ }
156
+
157
+ function isListBlock(block: MarkdownBlock): boolean {
158
+ return block.kind === "text" && readInlineEdit(block.body).kind === "list";
159
+ }
160
+
161
+ function headingGap(level: number): string {
162
+ if (level <= 2) return "mt-6";
163
+ if (level === 3) return "mt-5";
164
+ if (level === 4) return "mt-4";
165
+ return "mt-3";
166
+ }
167
+
168
+ export function spaceBefore(block: MarkdownBlock, prev?: MarkdownBlock): string {
169
+ if (!prev) return "";
170
+ if (isListBlock(block) && isListBlock(prev)) return "mt-0.5";
171
+ if (block.kind === "text") {
172
+ const view = readInlineEdit(block.body);
173
+ if (view.kind === "heading") return headingGap(view.level);
174
+ }
175
+ if (prev.kind === "text" && readInlineEdit(prev.body).kind === "heading") return "mt-2";
176
+ return "mt-3";
177
+ }
178
+
179
+ function fenceClosed(body: string): boolean {
180
+ const lines = body.split("\n");
181
+ if (lines.length < 2) return false;
182
+ const last = (lines[lines.length - 1] ?? "").trim();
183
+ return /^(?:`{3,}|~{3,})$/.test(last);
184
+ }
185
+
186
+ type LiveReactOptions = {
187
+ trustedModules?: Record<string, unknown>;
188
+ sandboxSrc?: string;
189
+ showHeader?: boolean;
190
+ showCode?: boolean;
191
+ };
192
+
193
+ export function BlockBody({ block, streaming, trustedModules, sandboxSrc, showHeader, showCode }: { block: MarkdownBlock; streaming?: boolean } & LiveReactOptions): ReactNode {
194
+ if (block.kind === "mermaid") {
195
+ const fence = readFence(block.body);
196
+ const code = fence?.code ?? block.body;
197
+ if (streaming && !fenceClosed(block.body)) return <CodeBlock code={code} language="mermaid" className="my-0" />;
198
+ return <MermaidView code={code} />;
199
+ }
200
+ if (block.kind === "code") {
201
+ const fence = readFence(block.body);
202
+ if (!fence) return <CodeBlock code={block.body} className="my-0" />;
203
+ // An unclosed fence is still being written, so it never runs.
204
+ if (fence.lang === "live-react" && fenceClosed(block.body)) {
205
+ if (sandboxSrc) return <ReactCodeSandbox key={fence.code} code={fence.code} src={sandboxSrc} showHeader={showHeader} showCode={showCode} />;
206
+ if (trustedModules) return <ReactCode code={fence.code} trustedModules={trustedModules} showHeader={showHeader} showCode={showCode} />;
207
+ }
208
+ return <CodeBlock code={fence.code} language={fence.lang || undefined} className="my-0" />;
209
+ }
210
+ const view = readInlineEdit(block.body);
211
+ if (view.kind === "list") {
212
+ return (
213
+ <ListItem view={view}>
214
+ <RichText source={view.text} />
215
+ </ListItem>
216
+ );
217
+ }
218
+ return <RichText source={block.body} />;
219
+ }
220
+
221
+ export type MarkdownViewerProps = {
222
+ value?: string;
223
+ /** An open mermaid fence stays a code block until the stream closes it. */
224
+ streaming?: boolean;
225
+ placeholder?: string;
226
+ className?: string;
227
+ /**
228
+ * Runs ```live-react fences in a sandboxed iframe. Use this for markdown written by
229
+ * users or agents. Points at a page that calls `mountReactCodeRunner`, on its own origin.
230
+ * Wins over `trustedModules` when both are set.
231
+ */
232
+ sandboxSrc?: string;
233
+ /**
234
+ * Runs ```live-react fences in this page, with its cookies, storage, and network.
235
+ * Only for markdown you wrote. `react` is provided. Other imports must be listed here.
236
+ */
237
+ trustedModules?: Record<string, unknown>;
238
+ /** Header on `live-react` results (`Sandbox` or `Live`). `false` shows the result inline. Default `true`. */
239
+ showHeader?: boolean;
240
+ /** Code tab in the header of `live-react` results. Needs `showHeader`. Default `true`. */
241
+ showCode?: boolean;
242
+ };
243
+
244
+ /** Read-only markdown. Same blocks as the editor preview, without editing. */
245
+ export function MarkdownViewer({ value = "", streaming = false, sandboxSrc, trustedModules, showHeader = true, showCode = true, placeholder, className }: MarkdownViewerProps) {
246
+ const doc = useMemo(() => parseMarkdownDoc(value), [value]);
247
+ if (doc.blocks.length === 0) {
248
+ return placeholder ? <p className={cn("m-0 text-sm text-placeholder", className)}>{placeholder}</p> : null;
249
+ }
250
+ return (
251
+ <div className={cn("nonla-markdown-viewer flex min-w-0 flex-col text-foreground", className)}>
252
+ {doc.blocks.map((block, index) => (
253
+ <div
254
+ // biome-ignore lint/suspicious/noArrayIndexKey: block position is the document identity
255
+ key={`${index}:${block.kind}`}
256
+ data-md-block={block.kind}
257
+ className={cn("outline-none", spaceBefore(block, doc.blocks[index - 1]))}
258
+ >
259
+ <BlockBody block={block} streaming={streaming} trustedModules={trustedModules} sandboxSrc={sandboxSrc} showHeader={showHeader} showCode={showCode} />
260
+ </div>
261
+ ))}
262
+ </div>
263
+ );
264
+ }
@@ -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}>
@@ -0,0 +1,75 @@
1
+ import { Component, type ReactNode, useMemo } from "react";
2
+ import { SolarIcon } from "../icon/SolarIcon";
3
+ import { ReactCodeFrame } from "./ReactCodeFrame";
4
+ import { compileReactCode, type LiveComponent } from "./reactCompile";
5
+
6
+ export type ReactCodeProps = {
7
+ /** Component source. Must `export default` a React component. */
8
+ code: string;
9
+ /** Modules `import` can resolve. `react` is always available. */
10
+ trustedModules: Record<string, unknown>;
11
+ /** Header above the result. Default `true`. */
12
+ showHeader?: boolean;
13
+ /** Code tab in the header. Needs `showHeader`. Default `true`. */
14
+ showCode?: boolean;
15
+ /** Header text. Default `Live`. */
16
+ title?: ReactNode;
17
+ /** Header icon. `null` hides it. */
18
+ icon?: ReactNode;
19
+ /** Classes for the outer box. */
20
+ className?: string;
21
+ };
22
+
23
+ type Compiled = { Demo: LiveComponent } | { error: string };
24
+
25
+ function Live({ code, trustedModules }: Pick<ReactCodeProps, "code" | "trustedModules">) {
26
+ const compiled = useMemo<Compiled>(() => {
27
+ try {
28
+ return { Demo: compileReactCode(code, trustedModules) };
29
+ } catch (error) {
30
+ return { error: error instanceof Error ? error.message : "Could not run this React block." };
31
+ }
32
+ }, [code, trustedModules]);
33
+
34
+ if ("error" in compiled) return <p className="m-0 text-sm text-destructive">{compiled.error}</p>;
35
+ const { Demo } = compiled;
36
+ return (
37
+ <div className="flex w-full flex-wrap items-center justify-center gap-6">
38
+ <Demo />
39
+ </div>
40
+ );
41
+ }
42
+
43
+ class RenderBoundary extends Component<{ children: ReactNode }, { error: string | null }> {
44
+ state = { error: null as string | null };
45
+
46
+ static getDerivedStateFromError(error: Error) {
47
+ return { error: error.message };
48
+ }
49
+
50
+ render() {
51
+ if (this.state.error) return <p className="m-0 text-sm text-destructive">{this.state.error}</p>;
52
+ return this.props.children;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Runs a `live-react` fence in this page, with this page's cookies, storage, and network.
58
+ *
59
+ * Only for source you wrote. Markdown from users or agents must use `ReactCodeSandbox`.
60
+ */
61
+ export function ReactCode({ code, trustedModules, showHeader = true, showCode = true, title = "Live", icon, className }: ReactCodeProps) {
62
+ return (
63
+ <ReactCodeFrame
64
+ title={title}
65
+ icon={icon === undefined ? <SolarIcon name="play-circle-linear" size={16} className="text-warn" /> : icon}
66
+ showHeader={showHeader}
67
+ code={showCode ? code : undefined}
68
+ className={className}
69
+ >
70
+ <RenderBoundary key={code}>
71
+ <Live code={code} trustedModules={trustedModules} />
72
+ </RenderBoundary>
73
+ </ReactCodeFrame>
74
+ );
75
+ }
@@ -0,0 +1,46 @@
1
+ import { type ReactNode, useState } from "react";
2
+ import { CodeBlock } from "../codeblock/CodeBlock";
3
+ import { cn } from "../lib/cn";
4
+ import { Segmented } from "../segmented/Segmented";
5
+
6
+ type Tab = "preview" | "code";
7
+
8
+ const TABS = [
9
+ { label: "Preview", value: "preview" },
10
+ { label: "Code", value: "code" },
11
+ ] satisfies { label: string; value: Tab }[];
12
+
13
+ export type ReactCodeFrameProps = {
14
+ /** Header text, such as `Sandbox`. */
15
+ title: ReactNode;
16
+ /** Icon before the title. `null` hides it. */
17
+ icon?: ReactNode;
18
+ /** `false` drops the header and the border, so the result sits inline with the text around it. */
19
+ showHeader?: boolean;
20
+ /** Source for the Code tab. Omit to show the result only. The tab lives in the header, so no header means no tab. */
21
+ code?: string;
22
+ className?: string;
23
+ /** The rendered result. */
24
+ children: ReactNode;
25
+ };
26
+
27
+ /** Header, result, and an optional Code tab around a rendered `live-react` block. */
28
+ export function ReactCodeFrame({ title, icon, showHeader = true, code, className, children }: ReactCodeFrameProps) {
29
+ const [tab, setTab] = useState<Tab>("preview");
30
+ if (!showHeader) return <div className={cn("mb-2 w-full min-w-0", className)}>{children}</div>;
31
+ const hasCode = code !== undefined;
32
+ return (
33
+ <div className={cn("mb-2 flex w-full min-w-0 flex-col overflow-clip rounded-xl border border-border text-foreground", className)}>
34
+ <div className="flex h-10 items-center justify-between gap-2 border-b border-border pr-2 pl-3 text-xs font-medium">
35
+ <div className="flex min-w-0 items-center gap-2">
36
+ {icon}
37
+ <span className="truncate">{title}</span>
38
+ </div>
39
+ {hasCode ? <Segmented<Tab> size="small" options={TABS} value={tab} onChange={setTab} /> : null}
40
+ </div>
41
+ {/* Stays mounted on the Code tab, so an iframe keeps its state. */}
42
+ <div className={cn("min-w-0 px-3 py-3", hasCode && tab === "code" && "hidden")}>{children}</div>
43
+ {hasCode && tab === "code" ? <CodeBlock code={code} language="tsx" className="my-0 rounded-none border-0" /> : null}
44
+ </div>
45
+ );
46
+ }
@@ -0,0 +1,73 @@
1
+ import { Component, type ReactNode } from "react";
2
+ import { flushSync } from "react-dom";
3
+ import { createRoot } from "react-dom/client";
4
+ import { applyColorMode } from "../theme";
5
+ import { REACT_CODE_SOURCE, type RunnerPayload, readHostMessage } from "./reactCodeProtocol";
6
+ import { compileReactCode } from "./reactCompile";
7
+
8
+ type Report = (message: RunnerPayload) => void;
9
+
10
+ class Boundary extends Component<{ report: Report; children: ReactNode }, { error: string | null }> {
11
+ state = { error: null as string | null };
12
+
13
+ static getDerivedStateFromError(error: Error) {
14
+ return { error: error.message };
15
+ }
16
+
17
+ componentDidCatch(error: Error) {
18
+ this.props.report({ type: "error", message: error.message });
19
+ }
20
+
21
+ render() {
22
+ if (this.state.error) return <p style={{ margin: 0, color: "crimson", fontSize: 14 }}>{this.state.error}</p>;
23
+ return this.props.children;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Runner side of the sandbox. Call this once from the page `ReactCodeSandbox` loads.
29
+ *
30
+ * `modules` is the only thing the markdown can import, and the host cannot change it.
31
+ * Serve the page with `Content-Security-Policy: connect-src 'none'`, and with
32
+ * `Access-Control-Allow-Origin: *` on its assets, since a sandboxed frame loads them cross-origin.
33
+ */
34
+ export function mountReactCodeRunner(root: HTMLElement, modules: Record<string, unknown>): () => void {
35
+ const reactRoot = createRoot(root);
36
+ const report: Report = (message) => window.parent.postMessage({ source: REACT_CODE_SOURCE, ...message }, "*");
37
+
38
+ const onMessage = (event: MessageEvent) => {
39
+ if (event.source !== window.parent) return;
40
+ const msg = readHostMessage(event.data);
41
+ if (!msg) return;
42
+ applyColorMode(msg.mode);
43
+ if (msg.type === "mode") return;
44
+ try {
45
+ const Demo = compileReactCode(msg.code, modules);
46
+ flushSync(() =>
47
+ reactRoot.render(
48
+ <Boundary report={report}>
49
+ <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "center", gap: 24 }}>
50
+ <Demo />
51
+ </div>
52
+ </Boundary>,
53
+ ),
54
+ );
55
+ report({ type: "rendered" });
56
+ } catch (error) {
57
+ report({ type: "error", message: error instanceof Error ? error.message : "Could not run this React block." });
58
+ }
59
+ };
60
+
61
+ const sendHeight = () => report({ type: "resize", height: root.getBoundingClientRect().height });
62
+ const observer = new ResizeObserver(sendHeight);
63
+ observer.observe(root);
64
+
65
+ window.addEventListener("message", onMessage);
66
+ report({ type: "ready" });
67
+
68
+ return () => {
69
+ window.removeEventListener("message", onMessage);
70
+ observer.disconnect();
71
+ reactRoot.unmount();
72
+ };
73
+ }
@@ -0,0 +1,111 @@
1
+ import { type ReactNode, useEffect, useRef, useState } from "react";
2
+ import { SolarIcon } from "../icon/SolarIcon";
3
+ import { getColorMode, subscribeColorMode } from "../theme";
4
+ import { ReactCodeFrame } from "./ReactCodeFrame";
5
+ import { type HostMessage, REACT_CODE_SOURCE, readRunnerMessage } from "./reactCodeProtocol";
6
+
7
+ /** The runner page must report `ready` within this time. */
8
+ const READY_TIMEOUT_MS = 4000;
9
+ /** After the code is sent, the runner must report `rendered` within this time. */
10
+ const RENDER_TIMEOUT_MS = 5000;
11
+ const MIN_HEIGHT = 32;
12
+ const MAX_HEIGHT = 1200;
13
+
14
+ export type ReactCodeSandboxProps = {
15
+ code: string;
16
+ /** URL of a page that calls `mountReactCodeRunner`. Serve it from its own origin. */
17
+ src: string;
18
+ /** Header above the result. Default `true`. */
19
+ showHeader?: boolean;
20
+ /** Code tab in the header. Needs `showHeader`. Default `true`. */
21
+ showCode?: boolean;
22
+ /** Header text. Default `Sandbox`. */
23
+ title?: ReactNode;
24
+ /** Header icon. `null` hides it. */
25
+ icon?: ReactNode;
26
+ /** Classes for the outer box. */
27
+ className?: string;
28
+ };
29
+
30
+ /**
31
+ * Runs untrusted `live-react` source in a sandboxed iframe.
32
+ *
33
+ * `sandbox="allow-scripts"` without `allow-same-origin` gives the frame an opaque origin,
34
+ * so it cannot read this page's cookies, storage, or DOM. Hang or error removes the frame.
35
+ */
36
+ export function ReactCodeSandbox({ code, src, showHeader = true, showCode = true, title = "Sandbox", icon, className }: ReactCodeSandboxProps) {
37
+ const frameRef = useRef<HTMLIFrameElement>(null);
38
+ const [height, setHeight] = useState(MIN_HEIGHT);
39
+ const [error, setError] = useState<string | null>(null);
40
+
41
+ useEffect(() => {
42
+ const frame = frameRef.current;
43
+ if (!frame) return;
44
+ let readyTimer: ReturnType<typeof setTimeout> | undefined = setTimeout(() => setError("The sandbox did not start."), READY_TIMEOUT_MS);
45
+ let renderTimer: ReturnType<typeof setTimeout> | undefined;
46
+
47
+ const onMessage = (event: MessageEvent) => {
48
+ // Only the frame we created. Its origin is opaque, so compare the window, not the origin.
49
+ if (event.source !== frame.contentWindow) return;
50
+ const msg = readRunnerMessage(event.data);
51
+ if (!msg) return;
52
+ if (msg.type === "ready" && readyTimer) {
53
+ clearTimeout(readyTimer);
54
+ readyTimer = undefined;
55
+ const run: HostMessage = { source: REACT_CODE_SOURCE, type: "run", code, mode: getColorMode() };
56
+ frame.contentWindow?.postMessage(run, "*");
57
+ renderTimer = setTimeout(() => setError("The code took too long to run."), RENDER_TIMEOUT_MS);
58
+ } else if (msg.type === "rendered") {
59
+ clearTimeout(renderTimer);
60
+ renderTimer = undefined;
61
+ } else if (msg.type === "resize") {
62
+ setHeight(Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(msg.height))));
63
+ } else if (msg.type === "error") {
64
+ // The real error wins over a timeout that has not fired yet.
65
+ clearTimeout(readyTimer);
66
+ clearTimeout(renderTimer);
67
+ readyTimer = undefined;
68
+ renderTimer = undefined;
69
+ setError(msg.message);
70
+ }
71
+ };
72
+
73
+ // The frame has its own document, so it follows the page's light or dark mode through us.
74
+ const unsubscribeMode = subscribeColorMode(() => {
75
+ const mode: HostMessage = { source: REACT_CODE_SOURCE, type: "mode", mode: getColorMode() };
76
+ frame.contentWindow?.postMessage(mode, "*");
77
+ });
78
+
79
+ window.addEventListener("message", onMessage);
80
+ return () => {
81
+ unsubscribeMode();
82
+ window.removeEventListener("message", onMessage);
83
+ clearTimeout(readyTimer);
84
+ clearTimeout(renderTimer);
85
+ };
86
+ }, [code, src]);
87
+
88
+ return (
89
+ <ReactCodeFrame
90
+ title={title}
91
+ icon={icon === undefined ? <SolarIcon name="shield-check-linear" size={16} className="text-success" /> : icon}
92
+ showHeader={showHeader}
93
+ code={showCode ? code : undefined}
94
+ className={className}
95
+ >
96
+ {error ? (
97
+ <p className="m-0 text-sm text-destructive">{error}</p>
98
+ ) : (
99
+ <iframe
100
+ ref={frameRef}
101
+ src={src}
102
+ title="React example"
103
+ sandbox="allow-scripts"
104
+ referrerPolicy="no-referrer"
105
+ className="block w-full border-0 bg-transparent"
106
+ style={{ height }}
107
+ />
108
+ )}
109
+ </ReactCodeFrame>
110
+ );
111
+ }
@@ -0,0 +1,47 @@
1
+ import type { NonlaColorMode } from "../theme";
2
+
3
+ /** Message tag shared by the sandbox host (`ReactCodeSandbox`) and the runner page. */
4
+ export const REACT_CODE_SOURCE = "nonla-react-code";
5
+
6
+ export type HostMessage =
7
+ | { source: typeof REACT_CODE_SOURCE; type: "run"; code: string; mode: NonlaColorMode }
8
+ | { source: typeof REACT_CODE_SOURCE; type: "mode"; mode: NonlaColorMode };
9
+
10
+ export type RunnerMessage =
11
+ | { source: typeof REACT_CODE_SOURCE; type: "ready" }
12
+ | { source: typeof REACT_CODE_SOURCE; type: "rendered" }
13
+ | { source: typeof REACT_CODE_SOURCE; type: "resize"; height: number }
14
+ | { source: typeof REACT_CODE_SOURCE; type: "error"; message: string };
15
+
16
+ /** A runner message without the shared tag. */
17
+ export type RunnerPayload = RunnerMessage extends infer M ? (M extends RunnerMessage ? Omit<M, "source"> : never) : never;
18
+
19
+ /** Anything from the iframe is untrusted, so check the shape before using it. */
20
+ export function readRunnerMessage(data: unknown): RunnerMessage | null {
21
+ if (typeof data !== "object" || data === null) return null;
22
+ const msg = data as Record<string, unknown>;
23
+ if (msg.source !== REACT_CODE_SOURCE) return null;
24
+ if (msg.type === "ready" || msg.type === "rendered") return { source: REACT_CODE_SOURCE, type: msg.type };
25
+ if (msg.type === "resize" && typeof msg.height === "number" && Number.isFinite(msg.height)) {
26
+ return { source: REACT_CODE_SOURCE, type: "resize", height: msg.height };
27
+ }
28
+ if (msg.type === "error" && typeof msg.message === "string") {
29
+ return { source: REACT_CODE_SOURCE, type: "error", message: msg.message.slice(0, 300) };
30
+ }
31
+ return null;
32
+ }
33
+
34
+ function readMode(value: unknown): NonlaColorMode | null {
35
+ return value === "light" || value === "dark" ? value : null;
36
+ }
37
+
38
+ export function readHostMessage(data: unknown): HostMessage | null {
39
+ if (typeof data !== "object" || data === null) return null;
40
+ const msg = data as Record<string, unknown>;
41
+ if (msg.source !== REACT_CODE_SOURCE) return null;
42
+ const mode = readMode(msg.mode);
43
+ if (!mode) return null;
44
+ if (msg.type === "mode") return { source: REACT_CODE_SOURCE, type: "mode", mode };
45
+ if (msg.type === "run" && typeof msg.code === "string") return { source: REACT_CODE_SOURCE, type: "run", code: msg.code, mode };
46
+ return null;
47
+ }