devnonla-ui 0.18.1 → 0.19.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/package.json +2 -2
- package/src/chat/AgentChatbox.tsx +10 -3
- package/src/chat/AgentPanel.tsx +10 -3
- package/src/chat/index.ts +3 -1
- package/src/chat/message-ui/ChatInput.tsx +472 -98
- package/src/chat/message-ui/ChatSuggestions.tsx +105 -0
- package/src/chat/message-ui/ChatWelcome.tsx +6 -2
- package/src/chat/message-ui/commandChips.ts +127 -0
- package/src/css.d.ts +1 -0
- package/src/index.ts +0 -4
- package/src/markdown-editor/MarkdownViewer.tsx +7 -8
- package/src/markdown-editor/ReactCodeRunner.tsx +3 -3
- package/src/markdown-editor/ReactCodeSandbox.tsx +100 -30
- package/src/markdown-editor/reactSandboxFrame.css +14 -0
- package/src/markdown-editor/reactSandboxFrame.ts +26 -0
- package/src/styles.css +0 -1
- package/src/avatar/AgentAvatar.tsx +0 -332
- package/src/avatar/AgentBody.tsx +0 -458
- package/src/avatar/avatar.css +0 -600
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createContext, type ReactNode, useContext, useEffect, useId, useRef } from "react";
|
|
2
|
+
import { menuItemClass } from "../../dropdown/menuClasses";
|
|
3
|
+
import { cn } from "../../lib/cn";
|
|
4
|
+
/** A marker that opens a suggestion menu, e.g. `/`, `@`, or `#`. */
|
|
5
|
+
export type ChatTrigger = {
|
|
6
|
+
/** Text that opens the menu when it starts a word. No spaces. */
|
|
7
|
+
trigger: string;
|
|
8
|
+
/** Menu shown while the trigger is open. Use `useChatSuggest` inside for the live query. `null` or `false` disables this trigger. */
|
|
9
|
+
menu: ReactNode;
|
|
10
|
+
/** Chip background as hex, e.g. `#6366f1`. Defaults to amber `#c9841a`. */
|
|
11
|
+
color?: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type ChatToken = {
|
|
15
|
+
trigger: string;
|
|
16
|
+
query: string;
|
|
17
|
+
start: number;
|
|
18
|
+
end: number;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** What a custom menu can read while it is open. */
|
|
22
|
+
export type ChatSuggest = {
|
|
23
|
+
query: string;
|
|
24
|
+
trigger: string;
|
|
25
|
+
/**
|
|
26
|
+
* Replace the active token with a chip. `value` is stored and sent, e.g. `/plan` or `@file`.
|
|
27
|
+
* `label` is what the chip shows. Omit it to show `value`.
|
|
28
|
+
*/
|
|
29
|
+
insert: (value: string, label?: string) => void;
|
|
30
|
+
close: () => void;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
type SuggestOption = { value: string; label?: string };
|
|
34
|
+
|
|
35
|
+
type ChatSuggestContextValue = ChatSuggest & {
|
|
36
|
+
activeId: string | null;
|
|
37
|
+
register: (id: string, option: SuggestOption) => () => void;
|
|
38
|
+
highlight: (id: string) => void;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const ChatSuggestContext = createContext<ChatSuggestContextValue | null>(null);
|
|
42
|
+
|
|
43
|
+
export function useChatSuggest(): ChatSuggest {
|
|
44
|
+
const value = useContext(ChatSuggestContext);
|
|
45
|
+
if (!value) throw new Error("useChatSuggest must be used inside ChatInput triggers");
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Token at the caret when a word starts with one of `triggers`. Longest trigger wins. */
|
|
50
|
+
export function chatTokenAt(text: string, caret: number, triggers: readonly string[]): ChatToken | null {
|
|
51
|
+
if (caret < 0 || caret > text.length) return null;
|
|
52
|
+
let start = caret;
|
|
53
|
+
while (start > 0 && !/\s/.test(text[start - 1] ?? "")) start -= 1;
|
|
54
|
+
let end = caret;
|
|
55
|
+
while (end < text.length && !/\s/.test(text[end] ?? "")) end += 1;
|
|
56
|
+
if (start >= end) return null;
|
|
57
|
+
const word = text.slice(start, end);
|
|
58
|
+
let match: string | null = null;
|
|
59
|
+
for (const trigger of triggers) {
|
|
60
|
+
if (trigger && word.startsWith(trigger) && (match === null || trigger.length > match.length)) match = trigger;
|
|
61
|
+
}
|
|
62
|
+
if (match === null) return null;
|
|
63
|
+
return { trigger: match, query: word.slice(match.length), start, end };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function ChatSuggestProvider({ value, children }: { value: ChatSuggestContextValue; children: ReactNode }) {
|
|
67
|
+
return <ChatSuggestContext.Provider value={value}>{children}</ChatSuggestContext.Provider>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One row in a custom menu. Arrow keys and Enter use these rows.
|
|
72
|
+
* `value` is sent. `label` is shown in the chip; omit it to show `value`.
|
|
73
|
+
*/
|
|
74
|
+
export function ChatSuggestOption({ value, label, children }: { value: string; label?: string; children: ReactNode }) {
|
|
75
|
+
const suggest = useContext(ChatSuggestContext);
|
|
76
|
+
const id = useId();
|
|
77
|
+
const ref = useRef<HTMLButtonElement>(null);
|
|
78
|
+
if (!suggest) throw new Error("ChatSuggestOption must be used inside ChatInput triggers");
|
|
79
|
+
const { insert, activeId, register, highlight } = suggest;
|
|
80
|
+
const active = activeId === id;
|
|
81
|
+
|
|
82
|
+
useEffect(() => register(id, { value, label }), [id, register, value, label]);
|
|
83
|
+
|
|
84
|
+
useEffect(() => {
|
|
85
|
+
if (!active) return;
|
|
86
|
+
ref.current?.scrollIntoView({ block: "nearest" });
|
|
87
|
+
}, [active]);
|
|
88
|
+
|
|
89
|
+
return (
|
|
90
|
+
<button
|
|
91
|
+
ref={ref}
|
|
92
|
+
id={`chat-suggest-${id}`}
|
|
93
|
+
type="button"
|
|
94
|
+
role="option"
|
|
95
|
+
aria-selected={active}
|
|
96
|
+
data-highlighted={active ? "" : undefined}
|
|
97
|
+
onMouseEnter={() => highlight(id)}
|
|
98
|
+
onMouseDown={(e) => e.preventDefault()}
|
|
99
|
+
onClick={() => insert(value, label)}
|
|
100
|
+
className={cn(menuItemClass, "w-full cursor-pointer text-left")}
|
|
101
|
+
>
|
|
102
|
+
{children}
|
|
103
|
+
</button>
|
|
104
|
+
);
|
|
105
|
+
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { ReactNode } from "react";
|
|
2
|
-
import { AgentAvatar } from "../../avatar/AgentAvatar";
|
|
3
2
|
import { Button } from "../../button/Button";
|
|
4
3
|
import { cn } from "../../lib/cn";
|
|
5
4
|
|
|
@@ -17,7 +16,12 @@ export type ChatWelcomeProps = {
|
|
|
17
16
|
const DEFAULT_STARTERS = ["What can you help me with?", "Brainstorm a few ideas with me", "Walk me through how you work"] as const;
|
|
18
17
|
|
|
19
18
|
function DefaultAvatar({ name }: { name: string }) {
|
|
20
|
-
|
|
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
|
+
);
|
|
21
25
|
}
|
|
22
26
|
|
|
23
27
|
export function ChatWelcome({ name, description, avatar, starters = [...DEFAULT_STARTERS], onStarter, disabled, className }: ChatWelcomeProps) {
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
export type ComposerCaret = { index: number; offset: number };
|
|
2
|
+
|
|
3
|
+
export type ComposerPart =
|
|
4
|
+
| { type: "text"; id: string; value: string }
|
|
5
|
+
| { type: "command"; id: string; label: string; value: string; title?: string; color?: string };
|
|
6
|
+
|
|
7
|
+
export function emptyComposer(value = ""): { parts: ComposerPart[]; caret: ComposerCaret } {
|
|
8
|
+
return { parts: [{ type: "text", id: "t-0", value }], caret: { index: 0, offset: value.length } };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function isComposerEmpty(parts: readonly ComposerPart[]): boolean {
|
|
12
|
+
return parts.every((part) => part.type === "text" && part.value.length === 0);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function serializeComposer(parts: readonly ComposerPart[]): string {
|
|
16
|
+
return parts.map((part) => part.value).join("");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Keep a text run on both sides of every chip so the caret can sit inline. */
|
|
20
|
+
export function normalizeParts(parts: readonly ComposerPart[], caret: ComposerCaret | null): { parts: ComposerPart[]; caret: ComposerCaret | null } {
|
|
21
|
+
const acc: ComposerPart[] = [];
|
|
22
|
+
const caretOut: { current: ComposerCaret | null } = { current: null };
|
|
23
|
+
|
|
24
|
+
const pushText = (value: string, fromIndex: number, localCaret: number | null) => {
|
|
25
|
+
const prev = acc[acc.length - 1];
|
|
26
|
+
if (prev?.type === "text") {
|
|
27
|
+
const base = prev.value.length;
|
|
28
|
+
prev.value += value;
|
|
29
|
+
if (localCaret !== null && caret?.index === fromIndex) caretOut.current = { index: acc.length - 1, offset: base + localCaret };
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
acc.push({ type: "text", id: `t-${acc.length}`, value });
|
|
33
|
+
if (localCaret !== null && caret?.index === fromIndex) caretOut.current = { index: acc.length - 1, offset: localCaret };
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
parts.forEach((part, index) => {
|
|
37
|
+
if (part.type === "text") {
|
|
38
|
+
pushText(part.value, index, caret?.index === index ? caret.offset : null);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (acc.length === 0 || acc[acc.length - 1]?.type !== "text") pushText("", -1, null);
|
|
42
|
+
acc.push({ ...part });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
if (acc.length === 0 || acc[0]?.type !== "text") acc.unshift({ type: "text", id: "t-0", value: "" });
|
|
46
|
+
if (acc[acc.length - 1]?.type !== "text") acc.push({ type: "text", id: "t-end", value: "" });
|
|
47
|
+
|
|
48
|
+
const next = acc.map((part, index) => (part.type === "text" ? { ...part, id: `t-${index}` } : part));
|
|
49
|
+
const placed = caretOut.current;
|
|
50
|
+
if (!placed) return { parts: next, caret: null };
|
|
51
|
+
const at = next[placed.index];
|
|
52
|
+
if (!at || at.type !== "text") return { parts: next, caret: null };
|
|
53
|
+
return { parts: next, caret: { index: placed.index, offset: Math.min(Math.max(placed.offset, 0), at.value.length) } };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function insertTextAt(parts: readonly ComposerPart[], caret: ComposerCaret, text: string): { parts: ComposerPart[]; caret: ComposerCaret } {
|
|
57
|
+
const part = parts[caret.index];
|
|
58
|
+
if (!part || part.type !== "text") return { parts: [...parts], caret };
|
|
59
|
+
const value = part.value.slice(0, caret.offset) + text + part.value.slice(caret.offset);
|
|
60
|
+
const next = parts.map((item, index) => (index === caret.index && item.type === "text" ? { ...item, value } : item));
|
|
61
|
+
const normalized = normalizeParts(next, { index: caret.index, offset: caret.offset + text.length });
|
|
62
|
+
return { parts: normalized.parts, caret: normalized.caret ?? caret };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function insertCommandAt(
|
|
66
|
+
parts: readonly ComposerPart[],
|
|
67
|
+
caret: ComposerCaret,
|
|
68
|
+
tokenStart: number,
|
|
69
|
+
tokenEnd: number,
|
|
70
|
+
chip: { id: string; label: string; value: string; color?: string },
|
|
71
|
+
): { parts: ComposerPart[]; caret: ComposerCaret } {
|
|
72
|
+
const next: ComposerPart[] = [];
|
|
73
|
+
let caretIndex = caret.index;
|
|
74
|
+
let caretOffset = caret.offset;
|
|
75
|
+
parts.forEach((part, index) => {
|
|
76
|
+
if (part.type !== "text" || index !== caret.index) {
|
|
77
|
+
next.push(part);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const before = part.value.slice(0, tokenStart);
|
|
81
|
+
let after = part.value.slice(tokenEnd);
|
|
82
|
+
if (after === "" || !/^\s/.test(after)) after = ` ${after}`;
|
|
83
|
+
next.push({ type: "text", id: part.id, value: before });
|
|
84
|
+
next.push({ type: "command", ...chip });
|
|
85
|
+
caretIndex = next.length;
|
|
86
|
+
caretOffset = 1;
|
|
87
|
+
next.push({ type: "text", id: `${chip.id}-after`, value: after });
|
|
88
|
+
});
|
|
89
|
+
const normalized = normalizeParts(next, { index: caretIndex, offset: caretOffset });
|
|
90
|
+
return { parts: normalized.parts, caret: normalized.caret ?? { index: 0, offset: 0 } };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Insert a chip at the caret. Adds one space on each side when the text needs it. */
|
|
94
|
+
export function insertChipAt(parts: readonly ComposerPart[], caret: ComposerCaret, chip: { id: string; label: string; value: string; title?: string; color?: string }): { parts: ComposerPart[]; caret: ComposerCaret } {
|
|
95
|
+
const part = parts[caret.index];
|
|
96
|
+
if (!part || part.type !== "text") return { parts: [...parts], caret };
|
|
97
|
+
const head = part.value.slice(0, caret.offset);
|
|
98
|
+
const tail = part.value.slice(caret.offset);
|
|
99
|
+
const before = head.length > 0 && !/\s$/.test(head) ? `${head} ` : head;
|
|
100
|
+
const after = /^\s/.test(tail) ? tail : ` ${tail}`;
|
|
101
|
+
const next: ComposerPart[] = [
|
|
102
|
+
...parts.slice(0, caret.index),
|
|
103
|
+
{ ...part, value: before },
|
|
104
|
+
{ type: "command", ...chip },
|
|
105
|
+
{ type: "text", id: `${chip.id}-after`, value: after },
|
|
106
|
+
...parts.slice(caret.index + 1),
|
|
107
|
+
];
|
|
108
|
+
const normalized = normalizeParts(next, { index: caret.index + 2, offset: 1 });
|
|
109
|
+
return { parts: normalized.parts, caret: normalized.caret ?? caret };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function removeCommandPart(parts: readonly ComposerPart[], id: string): { parts: ComposerPart[]; caret: ComposerCaret } {
|
|
113
|
+
const index = parts.findIndex((part) => part.type === "command" && part.id === id);
|
|
114
|
+
if (index < 0) return { parts: [...parts], caret: { index: 0, offset: 0 } };
|
|
115
|
+
const left = parts[index - 1];
|
|
116
|
+
const next = parts.flatMap((part, partIndex) => {
|
|
117
|
+
if (partIndex === index) return [];
|
|
118
|
+
if (partIndex === index + 1 && part.type === "text" && left?.type === "text" && left.value.endsWith(" ") && part.value.startsWith(" ")) {
|
|
119
|
+
return [{ ...part, value: part.value.slice(1) }];
|
|
120
|
+
}
|
|
121
|
+
return [part];
|
|
122
|
+
});
|
|
123
|
+
const leftIndex = Math.max(0, index - 1);
|
|
124
|
+
const offset = left?.type === "text" ? left.value.length : 0;
|
|
125
|
+
const normalized = normalizeParts(next, { index: leftIndex, offset });
|
|
126
|
+
return { parts: normalized.parts, caret: normalized.caret ?? { index: 0, offset: 0 } };
|
|
127
|
+
}
|
package/src/css.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
declare module "*.css";
|
package/src/index.ts
CHANGED
|
@@ -15,10 +15,6 @@ 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, AgentAvatarEyeColor, AgentAvatarLook, AgentAvatarMotion, AgentAvatarProps } from "./avatar/AgentAvatar";
|
|
19
|
-
export { AGENT_AVATAR_PARTS, AgentAvatar } from "./avatar/AgentAvatar";
|
|
20
|
-
export type { AgentBodyConfig, AgentBodyLook, AgentBodyMotion, AgentBodyProps } from "./avatar/AgentBody";
|
|
21
|
-
export { AGENT_BODY_PARTS, AgentBody } from "./avatar/AgentBody";
|
|
22
18
|
export type { BlobShapeAppearance, BlobShapeProps, BlobShapeVariant } from "./blob-shape/BlobShape";
|
|
23
19
|
export { BlobShape } from "./blob-shape/BlobShape";
|
|
24
20
|
export type { CalendarProps } from "./calendar/Calendar";
|
|
@@ -225,13 +225,13 @@ function fenceComponent(components: MarkdownComponents | undefined, lang: string
|
|
|
225
225
|
|
|
226
226
|
type LiveReactOptions = {
|
|
227
227
|
trustedModules?: Record<string, unknown>;
|
|
228
|
-
|
|
228
|
+
sandbox?: boolean;
|
|
229
229
|
showHeader?: boolean;
|
|
230
230
|
showCode?: boolean;
|
|
231
231
|
components?: MarkdownComponents;
|
|
232
232
|
};
|
|
233
233
|
|
|
234
|
-
export function BlockBody({ block, streaming, trustedModules,
|
|
234
|
+
export function BlockBody({ block, streaming, trustedModules, sandbox, showHeader, showCode, components }: { block: MarkdownBlock; streaming?: boolean } & LiveReactOptions): ReactNode {
|
|
235
235
|
if (block.kind === "mermaid") {
|
|
236
236
|
const fence = readFence(block.body);
|
|
237
237
|
const code = fence?.code ?? block.body;
|
|
@@ -244,7 +244,7 @@ export function BlockBody({ block, streaming, trustedModules, sandboxSrc, showHe
|
|
|
244
244
|
const closed = fenceClosed(block.body);
|
|
245
245
|
// An unclosed fence is still being written, so it never runs.
|
|
246
246
|
if (fence.lang === "live-react" && closed) {
|
|
247
|
-
if (
|
|
247
|
+
if (sandbox) return <ReactCodeSandbox key={fence.code} code={fence.code} showHeader={showHeader} showCode={showCode} />;
|
|
248
248
|
if (trustedModules) return <ReactCode code={fence.code} trustedModules={trustedModules} showHeader={showHeader} showCode={showCode} />;
|
|
249
249
|
}
|
|
250
250
|
const Custom = fence.lang === "live-react" ? undefined : fenceComponent(components, fence.lang);
|
|
@@ -273,10 +273,9 @@ export type MarkdownViewerProps = {
|
|
|
273
273
|
className?: string;
|
|
274
274
|
/**
|
|
275
275
|
* Runs ```live-react fences in a sandboxed iframe. Use this for markdown written by
|
|
276
|
-
* users or agents.
|
|
277
|
-
* Wins over `trustedModules` when both are set.
|
|
276
|
+
* users or agents. Wins over `trustedModules` when both are set.
|
|
278
277
|
*/
|
|
279
|
-
|
|
278
|
+
sandbox?: boolean;
|
|
280
279
|
/**
|
|
281
280
|
* Runs ```live-react fences in this page, with its cookies, storage, and network.
|
|
282
281
|
* Only for markdown you wrote. `react` is provided. Other imports must be listed here.
|
|
@@ -296,7 +295,7 @@ export type MarkdownViewerProps = {
|
|
|
296
295
|
};
|
|
297
296
|
|
|
298
297
|
/** Read-only markdown. Same blocks as the editor preview, without editing. */
|
|
299
|
-
export function MarkdownViewer({ value = "", streaming = false,
|
|
298
|
+
export function MarkdownViewer({ value = "", streaming = false, sandbox = false, trustedModules, showHeader = true, showCode = true, placeholder, className, style, components }: MarkdownViewerProps) {
|
|
300
299
|
const doc = useMemo(() => parseMarkdownDoc(value), [value]);
|
|
301
300
|
if (doc.blocks.length === 0) {
|
|
302
301
|
return placeholder ? <p className={cn("m-0 text-sm text-quaternary-foreground", className)}>{placeholder}</p> : null;
|
|
@@ -310,7 +309,7 @@ export function MarkdownViewer({ value = "", streaming = false, sandboxSrc, trus
|
|
|
310
309
|
data-md-block={block.kind}
|
|
311
310
|
className={cn("outline-none", spaceBefore(block, doc.blocks[index - 1]))}
|
|
312
311
|
>
|
|
313
|
-
<BlockBody block={block} streaming={streaming} trustedModules={trustedModules}
|
|
312
|
+
<BlockBody block={block} streaming={streaming} trustedModules={trustedModules} sandbox={sandbox} showHeader={showHeader} showCode={showCode} components={components} />
|
|
314
313
|
</div>
|
|
315
314
|
))}
|
|
316
315
|
</div>
|
|
@@ -25,11 +25,11 @@ class Boundary extends Component<{ report: Report; children: ReactNode }, { erro
|
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
/**
|
|
28
|
-
* Runner side of the sandbox.
|
|
28
|
+
* Runner side of the sandbox. `ReactCodeSandbox` loads this from its own frame.
|
|
29
29
|
*
|
|
30
30
|
* `modules` is the only thing the markdown can import, and the host cannot change it.
|
|
31
|
-
*
|
|
32
|
-
*
|
|
31
|
+
* The frame document sets `Content-Security-Policy: connect-src 'none'`. Its scripts
|
|
32
|
+
* load cross-origin from an opaque origin, so those assets need `Access-Control-Allow-Origin`.
|
|
33
33
|
*/
|
|
34
34
|
export function mountReactCodeRunner(root: HTMLElement, modules: Record<string, unknown>): () => void {
|
|
35
35
|
root.classList.add("nonla-ui");
|
|
@@ -1,21 +1,11 @@
|
|
|
1
|
-
import { type ReactNode, useEffect,
|
|
1
|
+
import { type ReactNode, useEffect, useRef, useState } from "react";
|
|
2
2
|
import { Icon } from "../icon/Icon";
|
|
3
3
|
import { cn } from "../lib/cn";
|
|
4
4
|
import { getColorMode, type NonlaColorMode, subscribeColorMode } from "../theme";
|
|
5
5
|
import { ReactCodeFrame } from "./ReactCodeFrame";
|
|
6
6
|
import { type HostMessage, REACT_CODE_SOURCE, readRunnerMessage } from "./reactCodeProtocol";
|
|
7
7
|
|
|
8
|
-
|
|
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
|
-
}
|
|
8
|
+
const RUNNER_URL = new URL("./reactSandboxFrame.ts", import.meta.url).href;
|
|
19
9
|
|
|
20
10
|
/** The runner page must report `ready` within this time. */
|
|
21
11
|
const READY_TIMEOUT_MS = 20000;
|
|
@@ -24,11 +14,81 @@ const RENDER_TIMEOUT_MS = 15000;
|
|
|
24
14
|
const MIN_HEIGHT = 32;
|
|
25
15
|
const MAX_HEIGHT = 1200;
|
|
26
16
|
|
|
17
|
+
function escapeAttr(value: string): string {
|
|
18
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type ViteEnv = { DEV?: boolean; BASE_URL?: string };
|
|
22
|
+
|
|
23
|
+
function viteEnv(): ViteEnv {
|
|
24
|
+
return (import.meta as ImportMeta & { env?: ViteEnv }).env ?? {};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Local Vite needs a websocket. A deployed host does not get network from the frame. */
|
|
28
|
+
function connectSrc(origin: string): string {
|
|
29
|
+
const host = new URL(origin).hostname;
|
|
30
|
+
if (host !== "localhost" && host !== "127.0.0.1") return "'none'";
|
|
31
|
+
return `${origin} ${origin.replace(/^http/, "ws")}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Vite's React refresh check fails unless this runs before the runner module. Dev only. */
|
|
35
|
+
function reactRefreshPreamble(): string {
|
|
36
|
+
const env = viteEnv();
|
|
37
|
+
if (env.DEV !== true) return "";
|
|
38
|
+
const base = env.BASE_URL ?? "/";
|
|
39
|
+
return `<script type="module">
|
|
40
|
+
import { injectIntoGlobalHook } from ${JSON.stringify(`${base}@react-refresh`)};
|
|
41
|
+
injectIntoGlobalHook(window);
|
|
42
|
+
window.$RefreshReg$ = function () {};
|
|
43
|
+
window.$RefreshSig$ = function () { return function (type) { return type; }; };
|
|
44
|
+
</script>`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Document for the sandboxed frame. The runner and its styles load from this package. */
|
|
48
|
+
function sandboxDocument(mode: NonlaColorMode): string {
|
|
49
|
+
const origin = new URL(RUNNER_URL).origin;
|
|
50
|
+
const csp = [
|
|
51
|
+
"default-src 'none'",
|
|
52
|
+
`script-src 'unsafe-inline' 'unsafe-eval' ${origin}`,
|
|
53
|
+
`style-src 'unsafe-inline' ${origin}`,
|
|
54
|
+
`img-src data: blob: ${origin}`,
|
|
55
|
+
`font-src data: ${origin}`,
|
|
56
|
+
`connect-src ${connectSrc(origin)}`,
|
|
57
|
+
"form-action 'none'",
|
|
58
|
+
"base-uri 'none'",
|
|
59
|
+
"frame-src 'none'",
|
|
60
|
+
].join("; ");
|
|
61
|
+
return `<!doctype html>
|
|
62
|
+
<html lang="en">
|
|
63
|
+
<head>
|
|
64
|
+
<meta charset="UTF-8" />
|
|
65
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
66
|
+
<meta http-equiv="Content-Security-Policy" content="${escapeAttr(csp)}" />
|
|
67
|
+
<script>
|
|
68
|
+
document.documentElement.dataset.pendingMode=${JSON.stringify(mode)};
|
|
69
|
+
window.addEventListener("error", function (event) {
|
|
70
|
+
var message = event.message || "The sandbox did not start.";
|
|
71
|
+
parent.postMessage({ source: ${JSON.stringify(REACT_CODE_SOURCE)}, type: "error", message: String(message).slice(0, 300) }, "*");
|
|
72
|
+
});
|
|
73
|
+
</script>
|
|
74
|
+
<style>
|
|
75
|
+
html { color-scheme: dark; background: #141414; }
|
|
76
|
+
html:has(.nonla-ui.light) { color-scheme: light; background: #ffffff; }
|
|
77
|
+
.nonla-ui { min-height: 100%; }
|
|
78
|
+
</style>
|
|
79
|
+
</head>
|
|
80
|
+
<body>
|
|
81
|
+
<div id="root"></div>
|
|
82
|
+
${reactRefreshPreamble()}
|
|
83
|
+
<script type="module" src="${escapeAttr(RUNNER_URL)}"></script>
|
|
84
|
+
</body>
|
|
85
|
+
</html>`;
|
|
86
|
+
}
|
|
87
|
+
|
|
27
88
|
export type ReactCodeSandboxProps = {
|
|
89
|
+
/** Component source. Must `export default` a React component. */
|
|
28
90
|
code: string;
|
|
29
|
-
/**
|
|
30
|
-
src: string;
|
|
31
|
-
/** Header above the result. Default `true`. */
|
|
91
|
+
/** Header above the result. Default `false`. */
|
|
32
92
|
showHeader?: boolean;
|
|
33
93
|
/** Preview / Code switch in the header. Needs `showHeader`. Default `true`. */
|
|
34
94
|
showCode?: boolean;
|
|
@@ -43,29 +103,37 @@ export type ReactCodeSandboxProps = {
|
|
|
43
103
|
/**
|
|
44
104
|
* Runs untrusted `live-react` source in a sandboxed iframe.
|
|
45
105
|
*
|
|
106
|
+
* Pass `code`. The frame is built here and loads this package's runner.
|
|
107
|
+
* `react`, `devnonla-ui`, `devnonla-ui/chat`, `devnonla-ui/markdown`, and
|
|
108
|
+
* `react-hook-form` can be imported. Nothing else can.
|
|
109
|
+
*
|
|
46
110
|
* `sandbox="allow-scripts"` without `allow-same-origin` gives the frame an opaque origin,
|
|
47
111
|
* so it cannot read this page's cookies, storage, or DOM.
|
|
48
112
|
*/
|
|
49
|
-
export function ReactCodeSandbox({ code,
|
|
113
|
+
export function ReactCodeSandbox({ code, showHeader = false, showCode = true, title = "Sandbox", icon, className }: ReactCodeSandboxProps) {
|
|
50
114
|
const frameRef = useRef<HTMLIFrameElement>(null);
|
|
51
115
|
const [height, setHeight] = useState(MIN_HEIGHT);
|
|
52
116
|
const [error, setError] = useState<string | null>(null);
|
|
53
117
|
const [mode, setMode] = useState(getColorMode);
|
|
54
118
|
const [painted, setPainted] = useState(false);
|
|
55
|
-
|
|
119
|
+
const [srcDoc, setSrcDoc] = useState<string | null>(null);
|
|
120
|
+
// Mode is baked into the document once. A later theme change is a message, so the frame does not reload.
|
|
56
121
|
const modeOnLoad = useRef(getColorMode());
|
|
57
|
-
const frameSrc = useMemo(() => withColorMode(src, modeOnLoad.current), [src]);
|
|
58
122
|
|
|
59
123
|
useEffect(() => subscribeColorMode(() => setMode(getColorMode())), []);
|
|
60
124
|
|
|
125
|
+
useEffect(() => {
|
|
126
|
+
setSrcDoc(sandboxDocument(modeOnLoad.current));
|
|
127
|
+
}, []);
|
|
128
|
+
|
|
61
129
|
useEffect(() => {
|
|
62
130
|
setPainted(false);
|
|
63
131
|
setError(null);
|
|
64
|
-
}, [
|
|
132
|
+
}, [srcDoc, code]);
|
|
65
133
|
|
|
66
134
|
useEffect(() => {
|
|
67
135
|
const frame = frameRef.current;
|
|
68
|
-
if (!frame) return;
|
|
136
|
+
if (!frame || !srcDoc) return;
|
|
69
137
|
let alive = true;
|
|
70
138
|
// Once the runner has painted, a late timer must not replace the preview with an error.
|
|
71
139
|
let didRender = false;
|
|
@@ -131,7 +199,7 @@ export function ReactCodeSandbox({ code, src, showHeader = true, showCode = true
|
|
|
131
199
|
clearTimeout(readyTimer);
|
|
132
200
|
clearTimeout(renderTimer);
|
|
133
201
|
};
|
|
134
|
-
}, [code,
|
|
202
|
+
}, [code, srcDoc]);
|
|
135
203
|
|
|
136
204
|
return (
|
|
137
205
|
<ReactCodeFrame
|
|
@@ -142,15 +210,17 @@ export function ReactCodeSandbox({ code, src, showHeader = true, showCode = true
|
|
|
142
210
|
className={className}
|
|
143
211
|
>
|
|
144
212
|
{error ? <p className="m-0 text-sm text-destructive">{error}</p> : null}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
213
|
+
{srcDoc ? (
|
|
214
|
+
<iframe
|
|
215
|
+
ref={frameRef}
|
|
216
|
+
srcDoc={srcDoc}
|
|
217
|
+
title="React example"
|
|
218
|
+
sandbox="allow-scripts"
|
|
219
|
+
referrerPolicy="no-referrer"
|
|
220
|
+
className={cn("block w-full border-0 bg-background", (!painted || error) && "opacity-0")}
|
|
221
|
+
style={{ height, colorScheme: mode }}
|
|
222
|
+
/>
|
|
223
|
+
) : null}
|
|
154
224
|
</ReactCodeFrame>
|
|
155
225
|
);
|
|
156
226
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import "./reactSandboxFrame.css";
|
|
2
|
+
import * as rhf from "react-hook-form";
|
|
3
|
+
import * as chat from "../chat/index";
|
|
4
|
+
import * as ui from "../index";
|
|
5
|
+
import * as markdown from "./index";
|
|
6
|
+
import { mountReactCodeRunner } from "./ReactCodeRunner";
|
|
7
|
+
|
|
8
|
+
// Fixed allowlist. The host page only sends source text, so it cannot add modules.
|
|
9
|
+
const modules = {
|
|
10
|
+
"devnonla-ui": ui,
|
|
11
|
+
"devnonla-ui/markdown": markdown,
|
|
12
|
+
"devnonla-ui/chat": chat,
|
|
13
|
+
"@nonla-agents/ui": ui,
|
|
14
|
+
"@nonla-agents/ui/markdown": markdown,
|
|
15
|
+
"@nonla-agents/ui/chat": chat,
|
|
16
|
+
"react-hook-form": rhf,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const root = document.getElementById("root");
|
|
20
|
+
if (!root) throw new Error("Sandbox root element not found");
|
|
21
|
+
|
|
22
|
+
const stop = mountReactCodeRunner(root, modules);
|
|
23
|
+
|
|
24
|
+
type Hot = { dispose: (callback: () => void) => void };
|
|
25
|
+
const hot = (import.meta as ImportMeta & { hot?: Hot }).hot;
|
|
26
|
+
hot?.dispose(stop);
|