devnonla-ui 0.11.0 → 0.13.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.
@@ -7,29 +7,39 @@ import { cn } from "../lib/cn";
7
7
  import { type InlineEdit, type MarkdownBlock, parseMarkdownDoc, readFence, readInlineEdit } from "./blocks";
8
8
  import { MarkdownTable } from "./MarkdownTable";
9
9
  import { MermaidBlock } from "./MermaidBlock";
10
+ import { headingClass, type MarkdownVariant, markdownVariantStyle } from "./markdownScale";
10
11
  import { ReactCode } from "./ReactCode";
11
12
  import { ReactCodeSandbox } from "./ReactCodeSandbox";
12
13
 
14
+ export type { MarkdownVariant };
15
+ export { headingClass, markdownVariantStyle };
16
+
17
+ /** Task checks use the body ink, so a checked box sits with the text instead of the brand fill. */
18
+ const taskCheckClass =
19
+ "data-[state=checked]:border-(--md-ink)! data-[state=checked]:bg-(--md-ink)! data-[state=checked]:text-background! data-[state=indeterminate]:border-(--md-ink)! data-[state=indeterminate]:bg-(--md-ink)! data-[state=indeterminate]:text-background!";
20
+
13
21
  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",
22
+ "min-w-0 wrap-anywhere text-(length:--md-body-size,16px) leading-(--md-body-leading,24px) text-(--md-ink)",
23
+ "[&_:is(h1,h2,h3,h4,h5,h6)]:text-(--md-heading)",
24
+ "[&_:is(h1,h2)]:mt-(--md-h2-mt,24px) [&_h1]:mb-(--md-h1-mb,12px) [&_h2]:mb-(--md-h2-mb,1px) [&_:is(h1,h2)]:pt-(--md-h2-py,3px) [&_:is(h1,h2)]:pb-(--md-h2-py,3px) [&_:is(h1,h2)]:text-(length:--md-h2-size,30px) [&_:is(h1,h2)]:leading-(--md-h2-leading,40px) [&_:is(h1,h2)]:font-(--md-h2-weight,600) [&_:is(h1,h2)]:tracking-normal",
25
+ "[&_h3]:mt-(--md-h3-mt,22px) [&_h3]:mb-(--md-h3-mb,1px) [&_h3]:text-(length:--md-h3-size,24px) [&_h3]:leading-(--md-h3-leading,32px) [&_h3]:font-(--md-h3-weight,700)",
26
+ "[&_h4]:mt-(--md-h4-mt,16px) [&_h4]:mb-(--md-h4-mb,1px) [&_h4]:text-(length:--md-h4-size,20px) [&_h4]:leading-(--md-h4-leading,26px) [&_h4]:font-(--md-h4-weight,700)",
27
+ "[&_h5]:mt-(--md-h5-mt,0px) [&_h5]:mb-(--md-h5-mb,0px) [&_h5]:text-(length:--md-h5-size,16px) [&_h5]:leading-(--md-h5-leading,1.375) [&_h5]:font-(--md-h5-weight,700)",
28
+ "[&_h6]:mt-(--md-h6-mt,0px) [&_h6]:mb-(--md-h6-mb,0px) [&_h6]:text-(length:--md-h6-size,14px) [&_h6]:leading-(--md-h6-leading,1.375) [&_h6]:font-(--md-h6-weight,700)",
29
+ "[&_p]:my-(--md-p-my,1px) [&_p]:py-(--md-p-py,4px) [&_p]:leading-(--md-p-leading,1.5)",
30
+ "[&_ul]:my-(--md-list-my,8px) [&_ul]:list-disc [&_ul]:pl-(--md-ul-pl,4px)",
31
+ "[&_ol]:my-(--md-list-my,8px) [&_ol]:list-decimal [&_ol]:pl-(--md-ol-pl,4px)",
32
+ "[&_li>ul]:mt-1 [&_li>ol]:mt-1 [&_li>ol]:pl-(--md-nest,1.25rem)",
33
+ "[&_th_ul]:my-0 [&_td_ul]:my-0 [&_th_ol]:my-0 [&_td_ol]:my-0 [&_th_li]:mt-0 [&_td_li]:mt-0 [&_th_li>ul]:mt-0.5 [&_td_li>ul]:mt-0.5 [&_th_li>ol]:mt-0.5 [&_td_li>ol]:mt-0.5 [&_th_li>p]:my-0 [&_td_li>p]:my-0",
24
34
  "[&_ul.contains-task-list]:list-none",
25
- "[&_li]:my-0.5",
35
+ "[&_li]:mt-(--md-li-mt,4px) [&_li]:leading-[1.5]",
26
36
  "[&_li.task-list-item]:relative",
27
37
  "[&_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",
38
+ "[&_blockquote]:my-(--md-quote-my,4px) [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground",
29
39
  "[&_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",
40
+ "[&_hr]:my-(--md-rule-my,8px) [&_hr]:border-border",
41
+ "[&_strong]:font-(--md-strong-weight,600)",
42
+ "[&_img]:my-(--md-img-my,4px) [&_img]:max-w-full [&_img]:rounded-lg",
33
43
  );
34
44
 
35
45
  const previewComponents: Components = {
@@ -39,10 +49,10 @@ const previewComponents: Components = {
39
49
  const codeText = String(children).replace(/\n$/, "");
40
50
  const isBlock = codeText.includes("\n") || !!match;
41
51
  if (!isBlock) {
42
- return <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-[0.9em]">{children}</code>;
52
+ return <code className="nonla-inline-code">{children}</code>;
43
53
  }
44
54
  if (lang.toLowerCase() === "mermaid") return <MermaidView code={codeText} />;
45
- return <CodeBlock code={codeText} language={lang || undefined} className="my-2" />;
55
+ return <CodeBlock code={codeText} language={lang || undefined} className="my-(--md-code-my,8px)" />;
46
56
  },
47
57
  table({ children }) {
48
58
  return <MarkdownTable>{children}</MarkdownTable>;
@@ -57,8 +67,8 @@ const previewComponents: Components = {
57
67
  input({ type, checked }) {
58
68
  if (type !== "checkbox") return <input type={type} checked={checked} readOnly />;
59
69
  return (
60
- <span className="nonla-md-task-check pointer-events-none inline-flex h-7 items-center">
61
- <Checkbox checked={Boolean(checked)} tabIndex={-1} />
70
+ <span className="nonla-md-task-check pointer-events-none inline-flex h-(--md-body-leading,24px) items-center">
71
+ <Checkbox checked={Boolean(checked)} tabIndex={-1} className={taskCheckClass} />
62
72
  </span>
63
73
  );
64
74
  },
@@ -71,15 +81,6 @@ function MermaidView({ code }: { code: string }) {
71
81
  return <MermaidBlock className="my-0">{code}</MermaidBlock>;
72
82
  }
73
83
 
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
84
  type MdNode = {
84
85
  type: string;
85
86
  value?: string;
@@ -136,20 +137,23 @@ function RichText({ source }: { source: string }) {
136
137
  export function ListItem({ view, children }: { view: Extract<InlineEdit, { kind: "list" }>; children: ReactNode }) {
137
138
  const level = Math.floor(view.indent.length / 2);
138
139
  const ordinal = Number(/^(\d+)/.exec(view.marker)?.[1] ?? "1");
140
+ const marker = "w-6 shrink-0 pt-0.5 text-(length:--md-body-size,16px) leading-(--md-p-leading,1.5)";
139
141
  return (
140
- <div className="flex items-start gap-1.5" style={level > 0 ? { marginLeft: `${level * 1.25}rem` } : undefined}>
142
+ <div className="flex items-start gap-1.5 pl-(--md-item-pl,4px)" style={level > 0 ? { marginLeft: `calc(${level} * var(--md-nest, 1.25rem))` } : undefined}>
141
143
  {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 className={cn(marker, "pointer-events-none inline-flex justify-center")}>
145
+ <span className="mt-[calc((1lh-1rem)/2)] inline-flex">
146
+ <Checkbox checked={view.checked} tabIndex={-1} className={taskCheckClass} />
147
+ </span>
144
148
  </span>
145
149
  ) : view.ordered ? (
146
- <span className="w-6 shrink-0 text-right text-[15px] leading-7 tabular-nums">{ordinal}.</span>
150
+ <span className={cn(marker, "text-right tabular-nums")}>{ordinal}.</span>
147
151
  ) : (
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" />
152
+ <span className={cn(marker, "flex justify-center")} aria-hidden>
153
+ <span className="mt-[calc((1lh-0.375rem)/2)] size-1.5 rounded-full bg-current" />
150
154
  </span>
151
155
  )}
152
- <div className="min-w-0 flex-1">{children}</div>
156
+ <div className="min-w-0 flex-1 [&_p]:my-0! [&_p]:py-0.5!">{children}</div>
153
157
  </div>
154
158
  );
155
159
  }
@@ -158,22 +162,14 @@ function isListBlock(block: MarkdownBlock): boolean {
158
162
  return block.kind === "text" && readInlineEdit(block.body).kind === "list";
159
163
  }
160
164
 
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 {
165
+ export function spaceBefore(block: MarkdownBlock, prev?: MarkdownBlock, variant: MarkdownVariant = "docs"): string {
166
+ const chat = variant === "chat";
169
167
  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";
168
+ if (isListBlock(block) && isListBlock(prev)) return chat ? "mt-px" : "mt-0.5";
169
+ if (prev.kind === "text" && readInlineEdit(prev.body).kind === "heading") return "[&_p]:mt-0! [&_p]:pt-0.5!";
170
+ if (isListBlock(block) && prev.kind === "text") return chat ? "mt-0.5" : "mt-1";
171
+ if (block.kind === "text" && prev.kind === "text") return "";
172
+ return chat ? "mt-2" : "mt-3";
177
173
  }
178
174
 
179
175
  function fenceClosed(body: string): boolean {
@@ -235,26 +231,28 @@ export type MarkdownViewerProps = {
235
231
  * Only for markdown you wrote. `react` is provided. Other imports must be listed here.
236
232
  */
237
233
  trustedModules?: Record<string, unknown>;
238
- /** Header on `live-react` results (`Sandbox` or `Live`). `false` shows the result inline. Default `true`. */
234
+ /** Frame around `live-react` results. `false` shows the result inline. Default `true`. */
239
235
  showHeader?: boolean;
240
- /** Code tab in the header of `live-react` results. Needs `showHeader`. Default `true`. */
236
+ /** Switch that opens the source of a `live-react` preview. Needs `showHeader`. Default `true`. */
241
237
  showCode?: boolean;
238
+ /** `docs` is the article scale. `chat` tightens size and spacing for a thread. Default `docs`. */
239
+ variant?: MarkdownVariant;
242
240
  };
243
241
 
244
242
  /** 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) {
243
+ export function MarkdownViewer({ value = "", streaming = false, sandboxSrc, trustedModules, showHeader = true, showCode = true, placeholder, className, variant = "docs" }: MarkdownViewerProps) {
246
244
  const doc = useMemo(() => parseMarkdownDoc(value), [value]);
247
245
  if (doc.blocks.length === 0) {
248
246
  return placeholder ? <p className={cn("m-0 text-sm text-placeholder", className)}>{placeholder}</p> : null;
249
247
  }
250
248
  return (
251
- <div className={cn("nonla-markdown-viewer flex min-w-0 flex-col text-foreground", className)}>
249
+ <div data-variant={variant} className={cn("nonla-markdown-viewer flex min-w-0 flex-col text-(--md-ink)", variant === "chat" && "[&>[data-md-block]:first-child_:is(h1,h2,h3,h4,h5,h6)]:mt-0", className)} style={markdownVariantStyle(variant)}>
252
250
  {doc.blocks.map((block, index) => (
253
251
  <div
254
252
  // biome-ignore lint/suspicious/noArrayIndexKey: block position is the document identity
255
253
  key={`${index}:${block.kind}`}
256
254
  data-md-block={block.kind}
257
- className={cn("outline-none", spaceBefore(block, doc.blocks[index - 1]))}
255
+ className={cn("outline-none", spaceBefore(block, doc.blocks[index - 1], variant))}
258
256
  >
259
257
  <BlockBody block={block} streaming={streaming} trustedModules={trustedModules} sandboxSrc={sandboxSrc} showHeader={showHeader} showCode={showCode} />
260
258
  </div>
@@ -189,7 +189,7 @@ export function MermaidBlock({ children, className }: MermaidBlockProps) {
189
189
 
190
190
  return (
191
191
  <>
192
- <div className={cn("my-3 last:mb-0 group relative rounded-xl border border-border overflow-hidden bg-card", className)}>
192
+ <div className={cn("my-3 last:mb-0 group relative overflow-hidden rounded-xl bg-card", className)}>
193
193
  <div className="absolute top-2 right-2 z-10 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
194
194
  <Button size="small" icon={<SolarIcon name="maximize-linear" size={12} />} title="Fullscreen" aria-label="Fullscreen" onClick={openFullscreen} />
195
195
  </div>
@@ -1,5 +1,4 @@
1
1
  import { Component, type ReactNode, useMemo } from "react";
2
- import { SolarIcon } from "../icon/SolarIcon";
3
2
  import { ReactCodeFrame } from "./ReactCodeFrame";
4
3
  import { compileReactCode, type LiveComponent } from "./reactCompile";
5
4
 
@@ -8,13 +7,13 @@ export type ReactCodeProps = {
8
7
  code: string;
9
8
  /** Modules `import` can resolve. `react` is always available. */
10
9
  trustedModules: Record<string, unknown>;
11
- /** Header above the result. Default `true`. */
10
+ /** Bordered frame around the preview. `false` shows the result inline. Default `true`. */
12
11
  showHeader?: boolean;
13
- /** Code tab in the header. Needs `showHeader`. Default `true`. */
12
+ /** Switch that opens the source. Needs `showHeader`. Default `true`. */
14
13
  showCode?: boolean;
15
- /** Header text. Default `Live`. */
14
+ /** Label above the preview. Omit for no label bar. */
16
15
  title?: ReactNode;
17
- /** Header icon. `null` hides it. */
16
+ /** Icon before the title. */
18
17
  icon?: ReactNode;
19
18
  /** Classes for the outer box. */
20
19
  className?: string;
@@ -58,11 +57,11 @@ class RenderBoundary extends Component<{ children: ReactNode }, { error: string
58
57
  *
59
58
  * Only for source you wrote. Markdown from users or agents must use `ReactCodeSandbox`.
60
59
  */
61
- export function ReactCode({ code, trustedModules, showHeader = true, showCode = true, title = "Live", icon, className }: ReactCodeProps) {
60
+ export function ReactCode({ code, trustedModules, showHeader = true, showCode = true, title, icon, className }: ReactCodeProps) {
62
61
  return (
63
62
  <ReactCodeFrame
64
63
  title={title}
65
- icon={icon === undefined ? <SolarIcon name="play-circle-linear" size={16} className="text-warn" /> : icon}
64
+ icon={icon}
66
65
  showHeader={showHeader}
67
66
  code={showCode ? code : undefined}
68
67
  className={className}
@@ -1,7 +1,9 @@
1
1
  import { type ReactNode, useState } from "react";
2
2
  import { CodeBlock } from "../codeblock/CodeBlock";
3
+ import { SolarIcon } from "../icon/SolarIcon";
3
4
  import { cn } from "../lib/cn";
4
5
  import { Segmented } from "../segmented/Segmented";
6
+ import { Tooltip } from "../tooltip/Tooltip";
5
7
 
6
8
  type Tab = "preview" | "code";
7
9
 
@@ -11,36 +13,60 @@ const TABS = [
11
13
  ] satisfies { label: string; value: Tab }[];
12
14
 
13
15
  export type ReactCodeFrameProps = {
14
- /** Header text, such as `Sandbox`. */
15
- title: ReactNode;
16
- /** Icon before the title. `null` hides it. */
16
+ /** Label above the preview. Omit for no label bar. */
17
+ title?: ReactNode;
18
+ /** Icon before the title. */
17
19
  icon?: ReactNode;
18
- /** `false` drops the header and the border, so the result sits inline with the text around it. */
20
+ /** `false` drops the frame, so the result sits inline with the text around it. */
19
21
  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. */
22
+ /** Source for the Code view. Omit to show the result only. The switch lives in the frame, so no frame means no code. */
21
23
  code?: string;
22
24
  className?: string;
23
25
  /** The rendered result. */
24
26
  children: ReactNode;
25
27
  };
26
28
 
27
- /** Header, result, and an optional Code tab around a rendered `live-react` block. */
29
+ /** Preview, and a way to open the source. A title bar keeps that switch beside the label. */
28
30
  export function ReactCodeFrame({ title, icon, showHeader = true, code, className, children }: ReactCodeFrameProps) {
29
31
  const [tab, setTab] = useState<Tab>("preview");
32
+ const [open, setOpen] = useState(false);
30
33
  if (!showHeader) return <div className={cn("mb-2 w-full min-w-0", className)}>{children}</div>;
31
34
  const hasCode = code !== undefined;
35
+ const hasLabel = (title != null && title !== false) || icon != null;
36
+ const showingCode = hasLabel ? tab === "code" : open;
37
+ const codeLabel = open ? "Hide code" : "Show code";
32
38
  return (
33
39
  <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>
40
+ {hasLabel ? (
41
+ <div className="flex h-10 items-center justify-between gap-2 border-b border-border pr-2 pl-3 text-xs font-medium">
42
+ <div className="flex min-w-0 items-center gap-2">
43
+ {icon}
44
+ {title != null && title !== false ? <span className="truncate">{title}</span> : null}
45
+ </div>
46
+ {hasCode ? <Segmented<Tab> size="small" options={TABS} value={tab} onChange={setTab} /> : null}
38
47
  </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}
48
+ ) : null}
49
+ {/* Stays mounted on the Code view, so an iframe keeps its state. */}
50
+ <div className={cn("min-w-0 px-6 py-8", showingCode && "hidden")}>{children}</div>
51
+ {hasCode && !hasLabel ? (
52
+ <div className="flex h-10 items-center justify-end border-t border-border pr-1.5">
53
+ <Tooltip title={codeLabel}>
54
+ <button
55
+ type="button"
56
+ aria-expanded={open}
57
+ aria-label={codeLabel}
58
+ className={cn(
59
+ "inline-flex size-7 cursor-pointer items-center justify-center rounded-md transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
60
+ open ? "bg-muted text-foreground" : "text-muted-foreground",
61
+ )}
62
+ onClick={() => setOpen((value) => !value)}
63
+ >
64
+ <SolarIcon name="code-square-linear" size={16} />
65
+ </button>
66
+ </Tooltip>
67
+ </div>
68
+ ) : null}
69
+ {hasCode && showingCode ? <CodeBlock code={code} language="tsx" className="my-0 rounded-none border-0" /> : null}
44
70
  </div>
45
71
  );
46
72
  }
@@ -35,12 +35,14 @@ export function mountReactCodeRunner(root: HTMLElement, modules: Record<string,
35
35
  const reactRoot = createRoot(root);
36
36
  const report: Report = (message) => window.parent.postMessage({ source: REACT_CODE_SOURCE, ...message }, "*");
37
37
 
38
+ let waitingForRun = true;
38
39
  const onMessage = (event: MessageEvent) => {
39
40
  if (event.source !== window.parent) return;
40
41
  const msg = readHostMessage(event.data);
41
42
  if (!msg) return;
42
43
  applyColorMode(msg.mode);
43
44
  if (msg.type === "mode") return;
45
+ waitingForRun = false;
44
46
  try {
45
47
  const Demo = compileReactCode(msg.code, modules);
46
48
  flushSync(() =>
@@ -64,8 +66,15 @@ export function mountReactCodeRunner(root: HTMLElement, modules: Record<string,
64
66
 
65
67
  window.addEventListener("message", onMessage);
66
68
  report({ type: "ready" });
69
+ // Host effect may miss the first ping (React Strict Mode remounts the listener).
70
+ const readyBeat = window.setInterval(() => {
71
+ if (waitingForRun) report({ type: "ready" });
72
+ else window.clearInterval(readyBeat);
73
+ }, 250);
67
74
 
68
75
  return () => {
76
+ waitingForRun = false;
77
+ window.clearInterval(readyBeat);
69
78
  window.removeEventListener("message", onMessage);
70
79
  observer.disconnect();
71
80
  reactRoot.unmount();
@@ -1,23 +1,36 @@
1
- import { type ReactNode, useEffect, useRef, useState } from "react";
1
+ import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
2
2
  import { SolarIcon } from "../icon/SolarIcon";
3
- import { getColorMode, subscribeColorMode } from "../theme";
3
+ import { cn } from "../lib/cn";
4
+ import { getColorMode, type NonlaColorMode, subscribeColorMode } from "../theme";
4
5
  import { ReactCodeFrame } from "./ReactCodeFrame";
5
6
  import { type HostMessage, REACT_CODE_SOURCE, readRunnerMessage } from "./reactCodeProtocol";
6
7
 
8
+ /** Keep `mode` on the runner URL without dropping a query the caller already set. */
9
+ function withColorMode(src: string, mode: NonlaColorMode): string {
10
+ const hashAt = src.indexOf("#");
11
+ const hash = hashAt >= 0 ? src.slice(hashAt) : "";
12
+ const beforeHash = hashAt >= 0 ? src.slice(0, hashAt) : src;
13
+ const queryAt = beforeHash.indexOf("?");
14
+ const path = queryAt >= 0 ? beforeHash.slice(0, queryAt) : beforeHash;
15
+ const params = new URLSearchParams(queryAt >= 0 ? beforeHash.slice(queryAt + 1) : "");
16
+ params.set("mode", mode);
17
+ return `${path}?${params.toString()}${hash}`;
18
+ }
19
+
7
20
  /** The runner page must report `ready` within this time. */
8
- const READY_TIMEOUT_MS = 4000;
21
+ const READY_TIMEOUT_MS = 20000;
9
22
  /** After the code is sent, the runner must report `rendered` within this time. */
10
- const RENDER_TIMEOUT_MS = 5000;
23
+ const RENDER_TIMEOUT_MS = 15000;
11
24
  const MIN_HEIGHT = 32;
12
25
  const MAX_HEIGHT = 1200;
13
26
 
14
27
  export type ReactCodeSandboxProps = {
15
28
  code: string;
16
- /** URL of a page that calls `mountReactCodeRunner`. Serve it from its own origin. */
29
+ /** URL of a page that calls `mountReactCodeRunner`. Serve it from its own origin. Loaded with `?mode=light|dark` so the runner can paint before its script. */
17
30
  src: string;
18
31
  /** Header above the result. Default `true`. */
19
32
  showHeader?: boolean;
20
- /** Code tab in the header. Needs `showHeader`. Default `true`. */
33
+ /** Preview / Code switch in the header. Needs `showHeader`. Default `true`. */
21
34
  showCode?: boolean;
22
35
  /** Header text. Default `Sandbox`. */
23
36
  title?: ReactNode;
@@ -31,41 +44,73 @@ export type ReactCodeSandboxProps = {
31
44
  * Runs untrusted `live-react` source in a sandboxed iframe.
32
45
  *
33
46
  * `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.
47
+ * so it cannot read this page's cookies, storage, or DOM.
35
48
  */
36
49
  export function ReactCodeSandbox({ code, src, showHeader = true, showCode = true, title = "Sandbox", icon, className }: ReactCodeSandboxProps) {
37
50
  const frameRef = useRef<HTMLIFrameElement>(null);
38
51
  const [height, setHeight] = useState(MIN_HEIGHT);
39
52
  const [error, setError] = useState<string | null>(null);
53
+ const [mode, setMode] = useState(getColorMode);
54
+ const [painted, setPainted] = useState(false);
55
+ // Mode stays out of the URL after first load. A later theme change is a message, so the frame does not reload.
56
+ const modeOnLoad = useRef(getColorMode());
57
+ const frameSrc = useMemo(() => withColorMode(src, modeOnLoad.current), [src]);
58
+
59
+ useEffect(() => subscribeColorMode(() => setMode(getColorMode())), []);
60
+
61
+ useEffect(() => {
62
+ setPainted(false);
63
+ setError(null);
64
+ }, [frameSrc, code]);
40
65
 
41
66
  useEffect(() => {
42
67
  const frame = frameRef.current;
43
68
  if (!frame) return;
44
- let readyTimer: ReturnType<typeof setTimeout> | undefined = setTimeout(() => setError("The sandbox did not start."), READY_TIMEOUT_MS);
69
+ let alive = true;
70
+ // Once the runner has painted, a late timer must not replace the preview with an error.
71
+ let didRender = false;
45
72
  let renderTimer: ReturnType<typeof setTimeout> | undefined;
73
+ const readyTimer = setTimeout(() => {
74
+ if (alive && !didRender) setError("The sandbox did not start.");
75
+ }, READY_TIMEOUT_MS);
76
+
77
+ const postRun = () => {
78
+ const run: HostMessage = { source: REACT_CODE_SOURCE, type: "run", code, mode: getColorMode() };
79
+ frame.contentWindow?.postMessage(run, "*");
80
+ };
81
+
82
+ const expectRender = () => {
83
+ clearTimeout(renderTimer);
84
+ renderTimer = setTimeout(() => {
85
+ if (alive && !didRender) setError("The code took too long to run.");
86
+ }, RENDER_TIMEOUT_MS);
87
+ };
46
88
 
47
89
  const onMessage = (event: MessageEvent) => {
48
90
  // Only the frame we created. Its origin is opaque, so compare the window, not the origin.
49
91
  if (event.source !== frame.contentWindow) return;
50
92
  const msg = readRunnerMessage(event.data);
51
93
  if (!msg) return;
52
- if (msg.type === "ready" && readyTimer) {
94
+ if (msg.type === "ready") {
53
95
  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);
96
+ // A runner that restarts after paint (HMR) still needs the code, but must not restart the failure clock.
97
+ if (didRender) {
98
+ postRun();
99
+ return;
100
+ }
101
+ setError(null);
102
+ postRun();
103
+ expectRender();
58
104
  } else if (msg.type === "rendered") {
105
+ didRender = true;
59
106
  clearTimeout(renderTimer);
60
- renderTimer = undefined;
107
+ setError(null);
108
+ setPainted(true);
61
109
  } else if (msg.type === "resize") {
62
110
  setHeight(Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(msg.height))));
63
111
  } else if (msg.type === "error") {
64
- // The real error wins over a timeout that has not fired yet.
65
112
  clearTimeout(readyTimer);
66
113
  clearTimeout(renderTimer);
67
- readyTimer = undefined;
68
- renderTimer = undefined;
69
114
  setError(msg.message);
70
115
  }
71
116
  };
@@ -77,7 +122,10 @@ export function ReactCodeSandbox({ code, src, showHeader = true, showCode = true
77
122
  });
78
123
 
79
124
  window.addEventListener("message", onMessage);
125
+ // Strict Mode remounts this listener after the frame already posted `ready`.
126
+ postRun();
80
127
  return () => {
128
+ alive = false;
81
129
  unsubscribeMode();
82
130
  window.removeEventListener("message", onMessage);
83
131
  clearTimeout(readyTimer);
@@ -93,19 +141,16 @@ export function ReactCodeSandbox({ code, src, showHeader = true, showCode = true
93
141
  code={showCode ? code : undefined}
94
142
  className={className}
95
143
  >
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
- )}
144
+ {error ? <p className="m-0 text-sm text-destructive">{error}</p> : null}
145
+ <iframe
146
+ ref={frameRef}
147
+ src={frameSrc}
148
+ title="React example"
149
+ sandbox="allow-scripts"
150
+ referrerPolicy="no-referrer"
151
+ className={cn("block w-full border-0 bg-background", (!painted || error) && "opacity-0")}
152
+ style={{ height, colorScheme: mode }}
153
+ />
109
154
  </ReactCodeFrame>
110
155
  );
111
156
  }