devnonla-ui 0.10.0 → 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.
package/README.md CHANGED
@@ -205,6 +205,32 @@ import { MarkdownEditor, MarkdownViewer } from "devnonla-ui";
205
205
  <MarkdownEditor value={text} original={previous} onChange={setText} />
206
206
  ```
207
207
 
208
+ ## Live React in markdown
209
+
210
+ A `live-react` fence exports a default component and renders it above its source. It is off unless you opt in.
211
+
212
+ - **Markdown from users or agents:** pass `sandboxSrc`. The fence runs in an iframe with `sandbox="allow-scripts"` and no `allow-same-origin`, so it cannot reach the page's cookies, storage, or DOM. `sandboxSrc` is a page you host on its own origin that calls `mountReactCodeRunner`; its `modules` are the only imports markdown gets.
213
+ - **Markdown you wrote:** pass `trustedModules`. The fence runs in your page with full access. Never use it for content someone else can write.
214
+
215
+ ```tsx
216
+ // sandbox page
217
+ import * as ui from "devnonla-ui";
218
+ import { mountReactCodeRunner } from "devnonla-ui";
219
+
220
+ mountReactCodeRunner(document.getElementById("root")!, { "devnonla-ui": ui });
221
+
222
+ // app
223
+ <MarkdownViewer value={article} sandboxSrc="https://sandbox.example.com/runner.html" />
224
+ ```
225
+
226
+ Outside markdown, use the pieces directly. `ReactCodeSandbox` takes `code` and `src` and renders the same framed result with a Code tab. `ReactCode` is the in-page version for source you wrote. `ReactCodeFrame` is the header and tab box, if you want to wrap your own result.
227
+
228
+ ```tsx
229
+ <ReactCodeSandbox code={source} src="https://sandbox.example.com/runner.html" />
230
+ ```
231
+
232
+ Serve the runner page with `Content-Security-Policy: connect-src 'none'` and `Access-Control-Allow-Origin: *` on its assets, since a sandboxed frame loads them cross-origin.
233
+
208
234
  # Typography
209
235
 
210
236
  `Text`, `Title`, `Paragraph`, and `Link` share one decoration set: `type` (`secondary` | `success` | `warning` | `danger`), `disabled`, `mark`, `code`, `keyboard`, `underline`, `delete`, `strong`, and `italic`. `Title` `level` is 1–5. `Typography` groups the same pieces.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devnonla-ui",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "description": "NonlaUI — React controls for Nonla Agents",
6
6
  "author": "devlangla <devlangla0x01@gmail.com>",
@@ -55,6 +55,7 @@
55
55
  "react-day-picker": "^10.0.1",
56
56
  "react-markdown": "^10.1.0",
57
57
  "remark-gfm": "^4.0.1",
58
+ "sucrase": "^3.35.1",
58
59
  "tailwind-merge": "^3.5.0"
59
60
  },
60
61
  "devDependencies": {
@@ -0,0 +1,205 @@
1
+ import { createContext, type ReactNode, useContext, useId } from "react";
2
+ import { cn } from "../lib/cn";
3
+
4
+ /** `still` holds the pose. `idle` looks around. Defaults to `still`. */
5
+ export type AgentAvatarMotion = "still" | "idle";
6
+
7
+ /** Fixed facing. The head turns that way and the eyes follow. */
8
+ export type AgentAvatarLook = "forward" | "left" | "right" | "up" | "down" | "up-left" | "up-right" | "down-left" | "down-right";
9
+
10
+ export const AGENT_AVATAR_PARTS = {
11
+ shape: ["circle", "square", "triangle", "diamond", "hex", "gem", "pill", "arch", "cloud", "blob", "drop", "shield"],
12
+ color: ["#6E56F0", "#1C1C1C", "#F0B429", "#3DCFC0", "#F47820", "#3B82F6", "#F2549B", "#A56B3C"],
13
+ } as const;
14
+
15
+ type Part<K extends keyof typeof AGENT_AVATAR_PARTS> = (typeof AGENT_AVATAR_PARTS)[K][number];
16
+
17
+ /** A character is one shape plus the two eyes. */
18
+ export type AgentAvatarConfig = {
19
+ shape: Part<"shape">;
20
+ color: string;
21
+ };
22
+
23
+ export type AgentAvatarProps = {
24
+ /** Shape and color. Omitted parts use circle and `#6E56F0`. */
25
+ config?: Partial<AgentAvatarConfig>;
26
+ /** Square size in px. Defaults to 64. */
27
+ size?: number;
28
+ motion?: AgentAvatarMotion;
29
+ /** Which way the face is turned. Defaults to straight ahead. */
30
+ look?: AgentAvatarLook;
31
+ className?: string;
32
+ /** Accessible name. Defaults to "Agent". */
33
+ label?: string;
34
+ };
35
+
36
+ function hash(seed: string) {
37
+ let h = 2166136261;
38
+ for (let i = 0; i < seed.length; i++) {
39
+ h ^= seed.charCodeAt(i);
40
+ h = Math.imul(h, 16777619);
41
+ }
42
+ return h >>> 0;
43
+ }
44
+
45
+ const DEFAULT_CONFIG: AgentAvatarConfig = {
46
+ shape: AGENT_AVATAR_PARTS.shape[0],
47
+ color: AGENT_AVATAR_PARTS.color[0],
48
+ };
49
+
50
+ function resolveConfig(config?: Partial<AgentAvatarConfig>): AgentAvatarConfig {
51
+ return {
52
+ shape: config?.shape ?? DEFAULT_CONFIG.shape,
53
+ color: config?.color ?? DEFAULT_CONFIG.color,
54
+ };
55
+ }
56
+
57
+ function stagger(seed: string) {
58
+ return (hash(seed) % 8) * 0.2;
59
+ }
60
+
61
+ const EYE = "#111";
62
+ const EYE_ON_DARK = "#fff";
63
+
64
+ function eyeInk(color: string) {
65
+ const hex = color.replace("#", "");
66
+ if (hex.length < 6) return EYE;
67
+ const r = Number.parseInt(hex.slice(0, 2), 16);
68
+ const g = Number.parseInt(hex.slice(2, 4), 16);
69
+ const b = Number.parseInt(hex.slice(4, 6), 16);
70
+ const luma = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
71
+ return luma < 0.28 ? EYE_ON_DARK : EYE;
72
+ }
73
+
74
+ /** Head shift, then how much further the eyes travel, in viewBox units. */
75
+ const LOOK: Record<AgentAvatarLook, { head: [number, number]; eyes: [number, number] }> = {
76
+ forward: { head: [0, 0], eyes: [0, 0] },
77
+ left: { head: [-3.2, 0.6], eyes: [-6.4, 0.4] },
78
+ right: { head: [3.2, 0.6], eyes: [6.4, 0.4] },
79
+ up: { head: [0, -2.6], eyes: [0, -4.4] },
80
+ down: { head: [0, 2.8], eyes: [0, 4.6] },
81
+ "up-left": { head: [-2.3, -1.9], eyes: [-4.5, -3.1] },
82
+ "up-right": { head: [2.3, -1.9], eyes: [4.5, -3.1] },
83
+ "down-left": { head: [-2.3, 2], eyes: [-4.5, 3.3] },
84
+ "down-right": { head: [2.3, 2], eyes: [4.5, 3.3] },
85
+ };
86
+
87
+ function mixHex(color: string, toward: "#fff" | "#000", amount: number) {
88
+ const hex = color.replace("#", "");
89
+ const channel = (start: number) => Number.parseInt(hex.slice(start, start + 2), 16);
90
+ const target = toward === "#fff" ? 255 : 0;
91
+ const mix = (value: number) => Math.round(value + (target - value) * amount)
92
+ .toString(16)
93
+ .padStart(2, "0");
94
+ return `#${mix(channel(0))}${mix(channel(2))}${mix(channel(4))}`;
95
+ }
96
+
97
+ const PaintContext = createContext("#111");
98
+ const ShadowContext = createContext<string | undefined>(undefined);
99
+ const InkContext = createContext(EYE);
100
+
101
+ function Eyes({ cx, cy, w = 5.2, h = 12 }: { cx: number; cy: number; w?: number; h?: number }) {
102
+ const gap = w * 1.5;
103
+ const top = cy - h / 2;
104
+ const fill = useContext(InkContext);
105
+ return (
106
+ <g className="nonla-avatar-gaze">
107
+ <g className="nonla-avatar-eyes">
108
+ <rect x={cx - gap / 2 - w} y={top} width={w} height={h} rx={w / 2} fill={fill} />
109
+ <rect x={cx + gap / 2} y={top} width={w} height={h} rx={w / 2} fill={fill} />
110
+ </g>
111
+ </g>
112
+ );
113
+ }
114
+
115
+ function Shape({ shape, color }: AgentAvatarConfig) {
116
+ const paint = useContext(PaintContext);
117
+ const shadow = useContext(ShadowContext);
118
+ const soft = { fill: paint, stroke: paint, strokeLinejoin: "round" as const };
119
+ const face = (mark: ReactNode, eyes: ReactNode, shiftY = 0) => (
120
+ <g transform={shiftY ? `translate(0 ${shiftY})` : undefined}>
121
+ <g filter={shadow}>{mark}</g>
122
+ {eyes}
123
+ </g>
124
+ );
125
+ const body: Record<AgentAvatarConfig["shape"], ReactNode> = {
126
+ circle: face(<circle cx="32" cy="32" r="22" fill={paint} />, <Eyes cx={32} cy={30} />),
127
+ square: face(<rect x="9" y="9" width="46" height="46" rx="16" fill={paint} />, <Eyes cx={32} cy={30} />),
128
+ triangle: face(<path d="M32 16 L50 50 H14 Z" strokeWidth="14" {...soft} />, <Eyes cx={32} cy={38} />, -1),
129
+ diamond: face(<path d="M32 10 L54 32 L32 54 L10 32 Z" strokeWidth="16" {...soft} />, <Eyes cx={32} cy={30} />),
130
+ hex: face(<path d="M32 12 L49 22 L49 42 L32 52 L15 42 L15 22 Z" strokeWidth="8" {...soft} />, <Eyes cx={32} cy={30} />),
131
+ gem: face(<path d="M22 12 H42 L52 22 V42 L42 52 H22 L12 42 V22 Z" strokeWidth="8" {...soft} />, <Eyes cx={32} cy={30} />),
132
+ pill: face(<rect x="6" y="18" width="52" height="28" rx="14" fill={paint} />, <Eyes cx={32} cy={30} />),
133
+ arch: face(<path d="M14 50V32C14 18 50 18 50 32V50C50 56 14 56 14 50Z" fill={paint} />, <Eyes cx={32} cy={36} />, -6),
134
+ cloud: face(
135
+ <g fill={paint}>
136
+ <circle cx="20" cy="38" r="12" />
137
+ <circle cx="44" cy="38" r="12" />
138
+ <circle cx="32" cy="28" r="14" />
139
+ <rect x="16" y="34" width="32" height="14" />
140
+ </g>,
141
+ <Eyes cx={32} cy={36} />,
142
+ ),
143
+ blob: face(<ellipse cx="32" cy="34" rx="24" ry="18" fill={paint} />, <Eyes cx={32} cy={32} />, -2),
144
+ drop: face(
145
+ <path d="M27 23C19 30 15 37 15 46C15 55 22.5 60 32 60C41.5 60 49 55 49 46C49 37 45 30 37 23Q32 16 27 23Z" strokeWidth="5" {...soft} />,
146
+ <Eyes cx={32} cy={42} />,
147
+ -8,
148
+ ),
149
+ shield: face(
150
+ <path d="M18 18H46C52 18 54 24 54 32V36C54 48 46 56 32 58C18 56 10 48 10 36V32C10 24 12 18 18 18Z" fill={paint} />,
151
+ <Eyes cx={32} cy={34} />,
152
+ -6,
153
+ ),
154
+ };
155
+ return <InkContext.Provider value={eyeInk(color)}>{body[shape]}</InkContext.Provider>;
156
+ }
157
+
158
+ export function AgentAvatar({ config, size = 64, motion = "still", look = "forward", className, label = "Agent" }: AgentAvatarProps) {
159
+ const resolved = resolveConfig(config);
160
+ const delay = stagger(`${resolved.shape}${resolved.color}`);
161
+ const facing = LOOK[look];
162
+ const [hx, hy] = facing.head;
163
+ const [ex, ey] = facing.eyes;
164
+ const uid = useId().replace(/:/g, "");
165
+ const light = `nonla-av-${uid}`;
166
+ const shadow = `nonla-av-s-${uid}`;
167
+
168
+ return (
169
+ <span
170
+ role="img"
171
+ aria-label={label}
172
+ data-motion={motion}
173
+ data-look={look}
174
+ className={cn("nonla-avatar", className)}
175
+ style={{
176
+ width: size,
177
+ height: size,
178
+ ["--nonla-avatar-delay" as string]: `${delay}s`,
179
+ ["--nonla-avatar-hx" as string]: `${(hx / 64) * 100}%`,
180
+ ["--nonla-avatar-hy" as string]: `${(hy / 64) * 100}%`,
181
+ ["--nonla-avatar-ex" as string]: `${(ex / 64) * 100}%`,
182
+ ["--nonla-avatar-ey" as string]: `${(ey / 64) * 100}%`,
183
+ }}
184
+ >
185
+ <span className="nonla-avatar-bob" aria-hidden>
186
+ <svg viewBox="0 0 64 64" width="100%" height="100%">
187
+ <defs>
188
+ <linearGradient id={light} gradientUnits="userSpaceOnUse" x1="32" y1="4" x2="32" y2="60">
189
+ <stop offset="0" stopColor={mixHex(resolved.color, "#fff", 0.16)} />
190
+ <stop offset="1" stopColor={resolved.color} />
191
+ </linearGradient>
192
+ <filter id={shadow} x="-20%" y="-20%" width="140%" height="150%">
193
+ <feDropShadow dx="0" dy="0.8" stdDeviation="0.6" floodColor="#000" floodOpacity="0.18" />
194
+ </filter>
195
+ </defs>
196
+ <PaintContext.Provider value={`url(#${light})`}>
197
+ <ShadowContext.Provider value={`url(#${shadow})`}>
198
+ <Shape {...resolved} />
199
+ </ShadowContext.Provider>
200
+ </PaintContext.Provider>
201
+ </svg>
202
+ </span>
203
+ </span>
204
+ );
205
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ReactNode } from "react";
2
+ import { AgentAvatar } from "../../avatar/AgentAvatar";
2
3
  import { Button } from "../../button/Button";
3
4
  import { cn } from "../../lib/cn";
4
5
 
@@ -16,12 +17,7 @@ export type ChatWelcomeProps = {
16
17
  const DEFAULT_STARTERS = ["What can you help me with?", "Brainstorm a few ideas with me", "Walk me through how you work"] as const;
17
18
 
18
19
  function DefaultAvatar({ name }: { name: string }) {
19
- const initial = (name.trim()[0] ?? "?").toUpperCase();
20
- return (
21
- <div className="flex size-16 items-center justify-center rounded-full bg-brand/20 text-xl font-semibold text-brand-700" aria-hidden>
22
- {initial}
23
- </div>
24
- );
20
+ return <AgentAvatar size={72} label={name} />;
25
21
  }
26
22
 
27
23
  export function ChatWelcome({ name, description, avatar, starters = [...DEFAULT_STARTERS], onStarter, disabled, className }: ChatWelcomeProps) {
@@ -29,23 +25,7 @@ export function ChatWelcome({ name, description, avatar, starters = [...DEFAULT_
29
25
 
30
26
  return (
31
27
  <div className={cn("nonla-chat-welcome flex flex-col items-center justify-center min-h-full w-full px-6 py-10 text-center", className)}>
32
- <div className="relative mb-5">
33
- <div
34
- aria-hidden
35
- className="pointer-events-none absolute left-1/2 top-1/2 size-28 -translate-x-1/2 -translate-y-1/2 rounded-full"
36
- style={{
37
- background: "radial-gradient(circle, color-mix(in oklab, var(--brand) 28%, transparent) 0%, transparent 70%)",
38
- }}
39
- />
40
- <div
41
- className="relative rounded-full p-0.5"
42
- style={{
43
- background: "linear-gradient(145deg, color-mix(in oklab, var(--brand-600) 55%, transparent), transparent 60%)",
44
- }}
45
- >
46
- <div className="rounded-full bg-popover p-0.5">{avatar ?? <DefaultAvatar name={name} />}</div>
47
- </div>
48
- </div>
28
+ <div className="mb-5">{avatar ?? <DefaultAvatar name={name} />}</div>
49
29
 
50
30
  <h2 className="m-0 text-[22px] font-semibold tracking-tight text-foreground leading-snug">Hi, I&apos;m {name}</h2>
51
31
 
package/src/index.ts CHANGED
@@ -15,6 +15,8 @@ export type InputRef = HTMLInputElement;
15
15
 
16
16
  export type { AlertProps, AlertType } from "./alert/Alert";
17
17
  export { Alert } from "./alert/Alert";
18
+ export type { AgentAvatarConfig, AgentAvatarLook, AgentAvatarMotion, AgentAvatarProps } from "./avatar/AgentAvatar";
19
+ export { AGENT_AVATAR_PARTS, AgentAvatar } from "./avatar/AgentAvatar";
18
20
  export type { CalendarProps } from "./calendar/Calendar";
19
21
  export { Calendar } from "./calendar/Calendar";
20
22
  export type { CardFooterProps, CardItemProps, CardProps } from "./card/Card";
@@ -165,6 +167,13 @@ export type { MarkdownViewerProps } from "./markdown-editor/MarkdownViewer";
165
167
  export { MarkdownViewer } from "./markdown-editor/MarkdownViewer";
166
168
  export type { MermaidBlockProps } from "./markdown-editor/MermaidBlock";
167
169
  export { MermaidBlock } from "./markdown-editor/MermaidBlock";
170
+ export type { ReactCodeProps } from "./markdown-editor/ReactCode";
171
+ export { ReactCode } from "./markdown-editor/ReactCode";
172
+ export type { ReactCodeFrameProps } from "./markdown-editor/ReactCodeFrame";
173
+ export { ReactCodeFrame } from "./markdown-editor/ReactCodeFrame";
174
+ export { mountReactCodeRunner } from "./markdown-editor/ReactCodeRunner";
175
+ export type { ReactCodeSandboxProps } from "./markdown-editor/ReactCodeSandbox";
176
+ export { ReactCodeSandbox } from "./markdown-editor/ReactCodeSandbox";
168
177
  export type { MenuItemProps, MenuRootProps, MenuTriggerProps } from "./menu/Menu";
169
178
  export { Menu, MenuAction, MenuDivider, MenuItem, MenuTrigger } from "./menu/Menu";
170
179
  export type { MessageConfig, MessageType } from "./message/message";
@@ -35,7 +35,7 @@ export function MarkdownTable({ children }: { children: ReactNode }) {
35
35
  <div className="overflow-x-auto">
36
36
  <table
37
37
  ref={tableRef}
38
- className="w-max min-w-full wrap-normal border-separate border-spacing-0 text-[14px] [&_th]:bg-(--nonla-table-head) [&_th]:text-foreground [&_th]:font-semibold [&_th]:px-2.5 [&_th]:py-1.5 [&_th]:text-left [&_th]:align-top [&_th]:border-r [&_th]:border-b [&_th]:border-border [&_th:last-child]:border-r-0 [&_td]:px-2.5 [&_td]:py-1.5 [&_td]:align-top [&_td]:text-foreground [&_td]:bg-card [&_td]:border-r [&_td]:border-b [&_td]:border-border [&_td:last-child]:border-r-0 [&_tbody_tr:last-child_td]:border-b-0"
38
+ className="w-max min-w-full border-separate border-spacing-0 text-[14px] [&_th]:max-w-[360px] [&_td]:max-w-[360px] [&_th]:whitespace-normal [&_td]:whitespace-normal [&_th]:wrap-normal [&_td]:wrap-normal [&_th]:bg-(--nonla-table-head) [&_th]:text-foreground [&_th]:font-semibold [&_th]:px-2.5 [&_th]:py-1.5 [&_th]:text-left [&_th]:align-top [&_th]:border-r [&_th]:border-b [&_th]:border-border [&_th:last-child]:border-r-0 [&_td]:px-2.5 [&_td]:py-1.5 [&_td]:align-top [&_td]:text-foreground [&_td]:bg-card [&_td]:border-r [&_td]:border-b [&_td]:border-border [&_td:last-child]:border-r-0 [&_tbody_tr:last-child_td]:border-b-0"
39
39
  >
40
40
  {children}
41
41
  </table>
@@ -7,6 +7,8 @@ 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 { ReactCode } from "./ReactCode";
11
+ import { ReactCodeSandbox } from "./ReactCodeSandbox";
10
12
 
11
13
  const documentClass = cn(
12
14
  "min-w-0 wrap-anywhere text-[15px] leading-7 text-foreground",
@@ -181,7 +183,14 @@ function fenceClosed(body: string): boolean {
181
183
  return /^(?:`{3,}|~{3,})$/.test(last);
182
184
  }
183
185
 
184
- export function BlockBody({ block, streaming }: { block: MarkdownBlock; streaming?: boolean }): ReactNode {
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 {
185
194
  if (block.kind === "mermaid") {
186
195
  const fence = readFence(block.body);
187
196
  const code = fence?.code ?? block.body;
@@ -191,6 +200,11 @@ export function BlockBody({ block, streaming }: { block: MarkdownBlock; streamin
191
200
  if (block.kind === "code") {
192
201
  const fence = readFence(block.body);
193
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
+ }
194
208
  return <CodeBlock code={fence.code} language={fence.lang || undefined} className="my-0" />;
195
209
  }
196
210
  const view = readInlineEdit(block.body);
@@ -210,10 +224,25 @@ export type MarkdownViewerProps = {
210
224
  streaming?: boolean;
211
225
  placeholder?: string;
212
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;
213
242
  };
214
243
 
215
244
  /** Read-only markdown. Same blocks as the editor preview, without editing. */
216
- export function MarkdownViewer({ value = "", streaming = false, placeholder, className }: MarkdownViewerProps) {
245
+ export function MarkdownViewer({ value = "", streaming = false, sandboxSrc, trustedModules, showHeader = true, showCode = true, placeholder, className }: MarkdownViewerProps) {
217
246
  const doc = useMemo(() => parseMarkdownDoc(value), [value]);
218
247
  if (doc.blocks.length === 0) {
219
248
  return placeholder ? <p className={cn("m-0 text-sm text-placeholder", className)}>{placeholder}</p> : null;
@@ -227,7 +256,7 @@ export function MarkdownViewer({ value = "", streaming = false, placeholder, cla
227
256
  data-md-block={block.kind}
228
257
  className={cn("outline-none", spaceBefore(block, doc.blocks[index - 1]))}
229
258
  >
230
- <BlockBody block={block} streaming={streaming} />
259
+ <BlockBody block={block} streaming={streaming} trustedModules={trustedModules} sandboxSrc={sandboxSrc} showHeader={showHeader} showCode={showCode} />
231
260
  </div>
232
261
  ))}
233
262
  </div>
@@ -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
+ }
@@ -0,0 +1,31 @@
1
+ import type { ReactNode } from "react";
2
+ import * as React from "react";
3
+ import { transform } from "sucrase";
4
+
5
+ export type LiveComponent = () => ReactNode;
6
+
7
+ /**
8
+ * Compiles TSX source to a component. This runs the source as code in the current
9
+ * page, so it must only see trusted input or run inside the sandbox runner.
10
+ */
11
+ export function compileReactCode(code: string, modules: Record<string, unknown>): LiveComponent {
12
+ const js = transform(code, {
13
+ transforms: ["typescript", "jsx", "imports"],
14
+ jsxRuntime: "classic",
15
+ production: true,
16
+ }).code;
17
+ const requireModule = (id: string) => {
18
+ if (id === "react") return React;
19
+ if (Object.hasOwn(modules, id)) return modules[id];
20
+ throw new Error(`Unknown module "${id}".`);
21
+ };
22
+ const exports: { default?: LiveComponent } = {};
23
+ const run = new Function("require", "exports", "React", `${js}\nreturn exports.default;`) as (
24
+ require: (id: string) => unknown,
25
+ exports: { default?: LiveComponent },
26
+ React: typeof import("react"),
27
+ ) => LiveComponent | undefined;
28
+ const Demo = run(requireModule, exports, React);
29
+ if (typeof Demo !== "function") throw new Error("React block must export default a component.");
30
+ return Demo;
31
+ }
package/src/styles.css CHANGED
@@ -1148,3 +1148,111 @@
1148
1148
  color: #b31d28;
1149
1149
  background-color: #ffeef0;
1150
1150
  }
1151
+
1152
+ /* ── Agent avatars — a quiet shift, not a bounce ──────────────────────── */
1153
+ .nonla-avatar {
1154
+ display: inline-flex;
1155
+ flex-shrink: 0;
1156
+ line-height: 0;
1157
+ vertical-align: middle;
1158
+ }
1159
+
1160
+ .nonla-avatar-bob {
1161
+ display: block;
1162
+ width: 100%;
1163
+ height: 100%;
1164
+ transform: translate(var(--nonla-avatar-hx, 0), var(--nonla-avatar-hy, 0));
1165
+ }
1166
+
1167
+ .nonla-avatar-gaze {
1168
+ transform-box: view-box;
1169
+ transform: translate(var(--nonla-avatar-ex, 0), var(--nonla-avatar-ey, 0));
1170
+ }
1171
+
1172
+ .nonla-avatar-eyes {
1173
+ transform-box: fill-box;
1174
+ transform-origin: center;
1175
+ }
1176
+
1177
+ .nonla-avatar[data-motion="idle"] .nonla-avatar-bob {
1178
+ animation: nonla-avatar-wander 8.4s ease-in-out infinite;
1179
+ animation-delay: var(--nonla-avatar-delay, 0s);
1180
+ }
1181
+
1182
+ .nonla-avatar[data-motion="idle"] .nonla-avatar-gaze {
1183
+ animation: nonla-avatar-glance 8.4s ease-in-out infinite;
1184
+ animation-delay: var(--nonla-avatar-delay, 0s);
1185
+ }
1186
+
1187
+ .nonla-avatar[data-motion="idle"] .nonla-avatar-eyes {
1188
+ animation: nonla-avatar-blink 6.4s ease-in-out infinite;
1189
+ animation-delay: var(--nonla-avatar-delay, 0s);
1190
+ }
1191
+
1192
+ @keyframes nonla-avatar-wander {
1193
+ 0%,
1194
+ 14%,
1195
+ 100% {
1196
+ transform: translate(var(--nonla-avatar-hx, 0), var(--nonla-avatar-hy, 0));
1197
+ }
1198
+ 22%,
1199
+ 34% {
1200
+ transform: translate(-5%, 1%);
1201
+ }
1202
+ 42%,
1203
+ 54% {
1204
+ transform: translate(0, -4%);
1205
+ }
1206
+ 62%,
1207
+ 74% {
1208
+ transform: translate(5%, 1%);
1209
+ }
1210
+ 82%,
1211
+ 94% {
1212
+ transform: translate(0, 4.4%);
1213
+ }
1214
+ }
1215
+
1216
+ @keyframes nonla-avatar-glance {
1217
+ 0%,
1218
+ 14%,
1219
+ 100% {
1220
+ transform: translate(var(--nonla-avatar-ex, 0), var(--nonla-avatar-ey, 0));
1221
+ }
1222
+ 22%,
1223
+ 34% {
1224
+ transform: translate(-10%, 0.6%);
1225
+ }
1226
+ 42%,
1227
+ 54% {
1228
+ transform: translate(0, -6.9%);
1229
+ }
1230
+ 62%,
1231
+ 74% {
1232
+ transform: translate(10%, 0.6%);
1233
+ }
1234
+ 82%,
1235
+ 94% {
1236
+ transform: translate(0, 7.2%);
1237
+ }
1238
+ }
1239
+
1240
+ @keyframes nonla-avatar-blink {
1241
+ 0%,
1242
+ 46%,
1243
+ 52%,
1244
+ 100% {
1245
+ transform: scaleY(1);
1246
+ }
1247
+ 49% {
1248
+ transform: scaleY(0.15);
1249
+ }
1250
+ }
1251
+
1252
+ @media (prefers-reduced-motion: reduce) {
1253
+ .nonla-avatar[data-motion] .nonla-avatar-bob,
1254
+ .nonla-avatar[data-motion] .nonla-avatar-gaze,
1255
+ .nonla-avatar[data-motion] .nonla-avatar-eyes {
1256
+ animation: none;
1257
+ }
1258
+ }