fix(custom-widgets): stabilize authoring flows
This commit is contained in:
22 files changed
+454
-203
No files matched your search
@@ -60,7 +60,8 @@ export function buildCustomWidgetAiPrompt(
|
||||
if (currentConfig) {
|
||||
sections.push(`Current widget:\n\n\`\`\`json\n${JSON.stringify(redactValue(currentConfig), null, 2)}\n\`\`\``);
|
||||
}
|
||||
return sections.join("\n\n").slice(0, 8_000);
|
||||
const prompt = sections.join("\n\n");
|
||||
return embeddedSkill ? prompt : prompt.slice(0, 8_000);
|
||||
}
|
||||
|
||||
export function buildCustomWidgetFixPrompt(input: {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ComponentType, ErrorInfo, ReactNode } from "react";
|
||||
import { Component, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Alert, Badge, Box, Group, Popover, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle, IconNetwork } from "@tabler/icons-react";
|
||||
import { Alert, Box, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import { renderSafeJsx } from "../jsx/interpreter";
|
||||
import { CustomJsxInputsProvider } from "../jsx/runtime-components";
|
||||
@@ -23,8 +23,6 @@ const permissions = new Set(["view", "modify", "full"]);
|
||||
|
||||
export interface CustomJsxRendererMessages {
|
||||
noTemplate: string;
|
||||
interactive: string;
|
||||
networkCapabilities: string;
|
||||
templateWarnings(count: number): string;
|
||||
}
|
||||
|
||||
@@ -33,7 +31,6 @@ export interface CustomJsxRendererProps {
|
||||
data: unknown;
|
||||
status?: Record<string, unknown>;
|
||||
options?: Record<string, unknown>;
|
||||
requestCapabilities: unknown;
|
||||
components: Readonly<Record<string, ComponentType<never>>>;
|
||||
createBindings(data: unknown): Readonly<Record<string, unknown>>;
|
||||
messages: CustomJsxRendererMessages;
|
||||
@@ -107,7 +104,6 @@ export function CustomJsxRenderer({
|
||||
data,
|
||||
status = EMPTY_RECORD,
|
||||
options = EMPTY_RECORD,
|
||||
requestCapabilities: rawCapabilities,
|
||||
components,
|
||||
createBindings,
|
||||
messages,
|
||||
@@ -150,7 +146,7 @@ export function CustomJsxRenderer({
|
||||
() => ({ ...createBindings(data), status, options, inputs }),
|
||||
[createBindings, data, inputs, options, status],
|
||||
);
|
||||
const capabilities = useMemo(() => parseRequestCapabilities(rawCapabilities), [rawCapabilities]);
|
||||
const boundaryKey = useMemo(() => createBoundaryKey(template, bindings), [bindings, template]);
|
||||
const rendered = useMemo(() => {
|
||||
try {
|
||||
return { ...renderSafeJsx({ template, components, bindings }), error: null };
|
||||
@@ -182,47 +178,6 @@ export function CustomJsxRenderer({
|
||||
);
|
||||
return (
|
||||
<Stack gap={0} h="100%">
|
||||
{capabilities.length > 0 && (
|
||||
<Group justify="flex-end" mb={4}>
|
||||
<Popover width={320} position="bottom-end" withinPortal={false} shadow="md">
|
||||
<Popover.Target>
|
||||
<Badge
|
||||
component="button"
|
||||
type="button"
|
||||
size="sm"
|
||||
color="gray"
|
||||
variant="light"
|
||||
leftSection={<IconNetwork size={12} />}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
{messages.interactive}
|
||||
</Badge>
|
||||
</Popover.Target>
|
||||
<Popover.Dropdown>
|
||||
<Stack gap={6}>
|
||||
<Text size="sm" fw={600}>
|
||||
{messages.networkCapabilities}
|
||||
</Text>
|
||||
{capabilities.map((capability) => (
|
||||
<Group key={capability.id} justify="space-between" gap="xs" wrap="nowrap">
|
||||
<Text size="xs" ff="monospace" truncate>
|
||||
{capability.id}
|
||||
</Text>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<Badge size="xs" color={methodColors[capability.method] ?? "gray"} variant="light">
|
||||
{capability.method}
|
||||
</Badge>
|
||||
<Badge size="xs" color="gray" variant="outline">
|
||||
{capability.minimumBoardPermission}
|
||||
</Badge>
|
||||
</Group>
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
</Group>
|
||||
)}
|
||||
<Box h="100%" style={{ contain: "layout paint style", isolation: "isolate", overflow: "auto", minHeight: 0 }}>
|
||||
{rendered.error ? (
|
||||
<ErrorAlert error={rendered.error} />
|
||||
@@ -233,7 +188,7 @@ export function CustomJsxRenderer({
|
||||
registerInput={registerInput}
|
||||
setInputValue={setInputValue}
|
||||
>
|
||||
<RendererErrorBoundary key={template} onError={handleError}>
|
||||
<RendererErrorBoundary key={boundaryKey} onError={handleError}>
|
||||
{rendered.node}
|
||||
</RendererErrorBoundary>
|
||||
</CustomJsxInputsProvider>
|
||||
@@ -254,3 +209,10 @@ export function CustomJsxRenderer({
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function createBoundaryKey(template: string, bindings: Readonly<Record<string, unknown>>) {
|
||||
let hash = 0;
|
||||
const value = `${template}\0${JSON.stringify(bindings)}`;
|
||||
for (let index = 0; index < value.length; index += 1) hash = (hash * 31 + value.charCodeAt(index)) | 0;
|
||||
return `${template.length}:${hash}`;
|
||||
}
|
||||
@@ -18,7 +18,7 @@ describe("buildCustomWidgetAiPrompt", () => {
|
||||
expect(prompt).toContain("Use this embedded Homarr Custom Widget skill while authoring:");
|
||||
expect(prompt).toContain("# Homarr Custom Widget");
|
||||
expect(prompt).toContain("installed Mantine components can differ by Homarr release.");
|
||||
expect(prompt.length).toBeLessThanOrEqual(8_000);
|
||||
expect(prompt.endsWith(CUSTOM_WIDGET_SKILL_MD)).toBe(true);
|
||||
});
|
||||
|
||||
test("is concise and describes the one-widget v2 contract", () => {
|
||||
|
||||
@@ -110,8 +110,6 @@ describe("Custom Widget runtime ports", () => {
|
||||
const setItem = vi.spyOn(Storage.prototype, "setItem");
|
||||
const rendererMessages = {
|
||||
noTemplate: "No template",
|
||||
interactive: "Interactive",
|
||||
networkCapabilities: "Network capabilities",
|
||||
templateWarnings: (count: number) => `${count} warnings`,
|
||||
};
|
||||
const components = createCustomJsxComponents({
|
||||
@@ -122,7 +120,6 @@ describe("Custom Widget runtime ports", () => {
|
||||
<CustomJsxRenderer
|
||||
template={'<Stack><TextInput bind="search" defaultValue="containers"/><Text>{inputs.search}</Text></Stack>'}
|
||||
data={{}}
|
||||
requestCapabilities={[]}
|
||||
components={components}
|
||||
createBindings={() => ({})}
|
||||
messages={rendererMessages}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { Alert, Stack, Text, UnstyledButton } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
@@ -8,12 +7,12 @@ import classes from "./code-editor.module.css";
|
||||
|
||||
export function EditorDiagnostics({
|
||||
diagnostics,
|
||||
editorView,
|
||||
messages,
|
||||
onSelect,
|
||||
}: {
|
||||
diagnostics: EditorDiagnostic[];
|
||||
editorView: EditorView | null;
|
||||
messages: CustomWidgetEditorMessages;
|
||||
onSelect(diagnostic: EditorDiagnostic): void;
|
||||
}) {
|
||||
if (diagnostics.length === 0) return null;
|
||||
return (
|
||||
@@ -24,12 +23,7 @@ export function EditorDiagnostics({
|
||||
type="button"
|
||||
w="100%"
|
||||
className={classes.diagnosticButton}
|
||||
onClick={() => {
|
||||
if (!editorView || diagnostic.index === undefined) return;
|
||||
const anchor = Math.min(diagnostic.index, editorView.state.doc.length);
|
||||
editorView.dispatch({ selection: { anchor }, scrollIntoView: true });
|
||||
editorView.focus();
|
||||
}}
|
||||
onClick={() => onSelect(diagnostic)}
|
||||
>
|
||||
<Alert
|
||||
color={diagnostic.severity === "error" ? "red" : "yellow"}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { redo, undo } from "@codemirror/commands";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { Button, Group, Text } from "@mantine/core";
|
||||
import {
|
||||
IconArrowBackUp,
|
||||
@@ -17,24 +15,28 @@ import classes from "./code-editor.module.css";
|
||||
|
||||
interface CodeEditorToolbarProps {
|
||||
props: CustomWidgetCodeEditorProps;
|
||||
editorView: EditorView | null;
|
||||
editorCreated: boolean;
|
||||
historyDepth: { undo: number; redo: number };
|
||||
formattedValue: string;
|
||||
copied: boolean;
|
||||
referenceOpened: boolean;
|
||||
onReferenceToggle(): void;
|
||||
onCopy(): void;
|
||||
onUndo(): void;
|
||||
onRedo(): void;
|
||||
}
|
||||
|
||||
export function CodeEditorToolbar({
|
||||
props,
|
||||
editorView,
|
||||
editorCreated,
|
||||
historyDepth,
|
||||
formattedValue,
|
||||
copied,
|
||||
referenceOpened,
|
||||
onReferenceToggle,
|
||||
onCopy,
|
||||
onUndo,
|
||||
onRedo,
|
||||
}: CodeEditorToolbarProps) {
|
||||
const starter = props.starter;
|
||||
return (
|
||||
@@ -53,8 +55,8 @@ export function CodeEditorToolbar({
|
||||
size="compact-xs"
|
||||
variant="subtle"
|
||||
leftSection={<IconArrowBackUp size={14} />}
|
||||
onClick={() => editorView && undo(editorView)}
|
||||
disabled={!editorView || historyDepth.undo === 0}
|
||||
onClick={onUndo}
|
||||
disabled={!editorCreated || historyDepth.undo === 0}
|
||||
>
|
||||
{props.messages.undo}
|
||||
</Button>
|
||||
@@ -63,8 +65,8 @@ export function CodeEditorToolbar({
|
||||
size="compact-xs"
|
||||
variant="subtle"
|
||||
leftSection={<IconArrowForwardUp size={14} />}
|
||||
onClick={() => editorView && redo(editorView)}
|
||||
disabled={!editorView || historyDepth.redo === 0}
|
||||
onClick={onRedo}
|
||||
disabled={!editorCreated || historyDepth.redo === 0}
|
||||
>
|
||||
{props.messages.redo}
|
||||
</Button>
|
||||
|
||||
@@ -1,21 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { autocompletion } from "@codemirror/autocomplete";
|
||||
import { redoDepth, undoDepth } from "@codemirror/commands";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { json } from "@codemirror/lang-json";
|
||||
import { linter } from "@codemirror/lint";
|
||||
import { redo, redoDepth, undo, undoDepth } from "@codemirror/commands";
|
||||
import type { EditorView as EditorViewType } from "@codemirror/view";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { ComponentType } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { ReactCodeMirrorProps } from "@uiw/react-codemirror";
|
||||
import { lazy, Suspense, useCallback, useEffect, useId, useMemo, useState } from "react";
|
||||
import { Badge, Collapse, Group, Input, Loader, Tabs, Text, useComputedColorScheme } from "@mantine/core";
|
||||
import { IconCheck } from "@tabler/icons-react";
|
||||
|
||||
import { createCustomJsxCompletionSource, customJsxComponentHover } from "./code-language";
|
||||
import { EditorDiagnostics } from "./code-editor-diagnostics";
|
||||
import { CodeEditorToolbar } from "./code-editor-toolbar";
|
||||
import type { EditorDiagnostic } from "./analyzer";
|
||||
import type {
|
||||
CustomWidgetCodeEditorProps,
|
||||
CustomWidgetEditorMessages,
|
||||
@@ -30,53 +24,24 @@ export type {
|
||||
} from "./code-editor-types";
|
||||
|
||||
const EMPTY_DIAGNOSTICS: NonNullable<CustomWidgetCodeEditorProps["diagnostics"]> = [];
|
||||
const LazyCodeMirror = lazy(() => import("./direct-code-mirror"));
|
||||
const editorViews = new Map<string, EditorViewType>();
|
||||
|
||||
export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
|
||||
const editorInstanceId = useId();
|
||||
const diagnostics = props.diagnostics ?? EMPTY_DIAGNOSTICS;
|
||||
const [CodeMirror, setCodeMirror] = useState<ComponentType<ReactCodeMirrorProps> | null>(null);
|
||||
const [editorReady, setEditorReady] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [referenceOpened, setReferenceOpened] = useState(false);
|
||||
const [cursor, setCursor] = useState({ line: 1, column: 1 });
|
||||
const [editorView, setEditorView] = useState<EditorViewType | null>(null);
|
||||
const [editorCreated, setEditorCreated] = useState(false);
|
||||
const [historyDepth, setHistoryDepth] = useState({ undo: 0, redo: 0 });
|
||||
const colorScheme = useComputedColorScheme("light");
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void import("@uiw/react-codemirror").then((module) => {
|
||||
if (!cancelled) setCodeMirror(() => module.default);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
setEditorReady(true);
|
||||
}, []);
|
||||
const extensions = useMemo(() => {
|
||||
const diagnosticsExtension = linter((view) =>
|
||||
diagnostics.map((diagnostic) => {
|
||||
const from = Math.min(diagnostic.index ?? 0, view.state.doc.length);
|
||||
return {
|
||||
from,
|
||||
to: Math.min(from + 1, view.state.doc.length),
|
||||
severity: diagnostic.severity,
|
||||
message: props.messages.diagnostic(diagnostic),
|
||||
};
|
||||
}),
|
||||
);
|
||||
const accessibilityExtension = EditorView.contentAttributes.of({ id: props.id, "aria-label": props.label });
|
||||
const editable = props.readOnly
|
||||
? [EditorView.editable.of(false), EditorView.contentAttributes.of({ tabindex: "0" })]
|
||||
: [];
|
||||
return props.language === "jsx"
|
||||
? [
|
||||
javascript({ jsx: true }),
|
||||
autocompletion({ override: [createCustomJsxCompletionSource(props.completions ?? [])] }),
|
||||
customJsxComponentHover,
|
||||
diagnosticsExtension,
|
||||
accessibilityExtension,
|
||||
...editable,
|
||||
]
|
||||
: [json(), diagnosticsExtension, accessibilityExtension, ...editable];
|
||||
}, [diagnostics, props.completions, props.id, props.label, props.language, props.messages, props.readOnly]);
|
||||
useEffect(() => {
|
||||
const editorView = editorViews.get(editorInstanceId);
|
||||
if (!editorView || !props.revealText) return;
|
||||
const from = editorView.state.doc.toString().indexOf(props.revealText);
|
||||
if (from < 0) return;
|
||||
@@ -85,12 +50,27 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
|
||||
effects: EditorView.scrollIntoView(from, { y: "center" }),
|
||||
});
|
||||
editorView.focus();
|
||||
}, [editorView, props.revealKey, props.revealText]);
|
||||
const handleCreateEditor = useCallback((view: EditorViewType) => {
|
||||
// @uiw invokes this while constructing CodeMirror. Deferring the parent update avoids
|
||||
// re-entering React's renderer during initialisation in Next.js and Docusaurus.
|
||||
window.setTimeout(() => setEditorView(view), 0);
|
||||
}, []);
|
||||
}, [editorCreated, editorInstanceId, props.revealKey, props.revealText]);
|
||||
const handleCreateEditor = useCallback(
|
||||
(view: EditorViewType) => {
|
||||
editorViews.set(editorInstanceId, view);
|
||||
window.setTimeout(() => setEditorCreated(true), 0);
|
||||
},
|
||||
[editorInstanceId],
|
||||
);
|
||||
const handleDestroyEditor = useCallback(() => {
|
||||
editorViews.delete(editorInstanceId);
|
||||
}, [editorInstanceId]);
|
||||
const selectDiagnostic = useCallback(
|
||||
(diagnostic: EditorDiagnostic) => {
|
||||
const editorView = editorViews.get(editorInstanceId);
|
||||
if (!editorView || diagnostic.index === undefined) return;
|
||||
const anchor = Math.min(diagnostic.index, editorView.state.doc.length);
|
||||
editorView.dispatch({ selection: { anchor }, scrollIntoView: true });
|
||||
editorView.focus();
|
||||
},
|
||||
[editorInstanceId],
|
||||
);
|
||||
const formattedValue = useMemo(() => formatCode(props.value, props.language), [props.language, props.value]);
|
||||
const errorCount = diagnostics.filter(({ severity }) => severity === "error").length;
|
||||
const warningCount = diagnostics.length - errorCount;
|
||||
@@ -115,13 +95,21 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
|
||||
<div className={classes.root}>
|
||||
<CodeEditorToolbar
|
||||
props={props}
|
||||
editorView={editorView}
|
||||
editorCreated={editorCreated}
|
||||
historyDepth={historyDepth}
|
||||
formattedValue={formattedValue}
|
||||
copied={copied}
|
||||
referenceOpened={referenceOpened}
|
||||
onReferenceToggle={() => setReferenceOpened((value) => !value)}
|
||||
onCopy={() => void copy()}
|
||||
onUndo={() => {
|
||||
const editorView = editorViews.get(editorInstanceId);
|
||||
if (editorView) undo(editorView);
|
||||
}}
|
||||
onRedo={() => {
|
||||
const editorView = editorViews.get(editorInstanceId);
|
||||
if (editorView) redo(editorView);
|
||||
}}
|
||||
/>
|
||||
{props.reference && (
|
||||
<Collapse expanded={referenceOpened}>
|
||||
@@ -129,36 +117,32 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
|
||||
</Collapse>
|
||||
)}
|
||||
<div className={classes.viewport}>
|
||||
{CodeMirror ? (
|
||||
<CodeMirror
|
||||
id={`${props.id}-root`}
|
||||
value={props.value}
|
||||
onChange={props.readOnly ? () => undefined : props.onChange}
|
||||
placeholder={props.placeholder}
|
||||
extensions={extensions}
|
||||
theme={colorScheme}
|
||||
height={props.height ?? (props.language === "jsx" ? "320px" : "220px")}
|
||||
basicSetup={{
|
||||
autocompletion: props.language !== "jsx" && !props.readOnly,
|
||||
bracketMatching: true,
|
||||
closeBrackets: !props.readOnly,
|
||||
foldGutter: true,
|
||||
history: !props.readOnly,
|
||||
highlightActiveLine: !props.readOnly,
|
||||
highlightActiveLineGutter: !props.readOnly,
|
||||
indentOnInput: !props.readOnly,
|
||||
lineNumbers: true,
|
||||
}}
|
||||
onCreateEditor={handleCreateEditor}
|
||||
onUpdate={(update) => {
|
||||
if (!editorView) return;
|
||||
if (!update.selectionSet && !update.docChanged) return;
|
||||
const head = update.state.selection.main.head;
|
||||
const line = update.state.doc.lineAt(head);
|
||||
setCursor({ line: line.number, column: head - line.from + 1 });
|
||||
setHistoryDepth({ undo: undoDepth(update.state), redo: redoDepth(update.state) });
|
||||
}}
|
||||
/>
|
||||
{editorReady ? (
|
||||
<Suspense fallback={<EditorLoader />}>
|
||||
<LazyCodeMirror
|
||||
id={`${props.id}-root`}
|
||||
value={props.value}
|
||||
language={props.language}
|
||||
diagnostics={diagnostics}
|
||||
completions={props.completions ?? []}
|
||||
label={props.label}
|
||||
placeholder={props.placeholder}
|
||||
theme={colorScheme}
|
||||
height={props.height ?? (props.language === "jsx" ? "320px" : "220px")}
|
||||
readOnly={props.readOnly ?? false}
|
||||
diagnosticMessage={props.messages.diagnostic}
|
||||
onChange={props.readOnly ? () => undefined : props.onChange}
|
||||
onCreateEditor={handleCreateEditor}
|
||||
onDestroyEditor={handleDestroyEditor}
|
||||
onUpdate={(update) => {
|
||||
if (!update.selectionSet && !update.docChanged) return;
|
||||
const head = update.state.selection.main.head;
|
||||
const line = update.state.doc.lineAt(head);
|
||||
setCursor({ line: line.number, column: head - line.from + 1 });
|
||||
setHistoryDepth({ undo: undoDepth(update.state), redo: redoDepth(update.state) });
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<EditorLoader />
|
||||
)}
|
||||
@@ -190,7 +174,7 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
|
||||
</Text>
|
||||
</Group>
|
||||
</div>
|
||||
<EditorDiagnostics diagnostics={diagnostics} editorView={editorView} messages={props.messages} />
|
||||
<EditorDiagnostics diagnostics={diagnostics} messages={props.messages} onSelect={selectDiagnostic} />
|
||||
</Input.Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"use client";
|
||||
|
||||
import { autocompletion } from "@codemirror/autocomplete";
|
||||
import { indentWithTab } from "@codemirror/commands";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { json } from "@codemirror/lang-json";
|
||||
import { linter } from "@codemirror/lint";
|
||||
import { EditorState, StateEffect } from "@codemirror/state";
|
||||
import { oneDark } from "@codemirror/theme-one-dark";
|
||||
import { EditorView, keymap, placeholder as codeMirrorPlaceholder } from "@codemirror/view";
|
||||
import type { ViewUpdate } from "@codemirror/view";
|
||||
import { basicSetup } from "codemirror";
|
||||
import { useCallback, useEffect, useId, useState } from "react";
|
||||
import type { Completion } from "@codemirror/autocomplete";
|
||||
|
||||
import { createCustomJsxCompletionSource, customJsxComponentHover } from "./code-language";
|
||||
import type { EditorDiagnostic } from "./analyzer";
|
||||
|
||||
interface DirectCodeMirrorProps {
|
||||
value: string;
|
||||
language: "jsx" | "json";
|
||||
diagnostics: EditorDiagnostic[];
|
||||
completions: Completion[];
|
||||
id: string;
|
||||
label: string;
|
||||
placeholder?: string;
|
||||
height: string;
|
||||
theme: "light" | "dark";
|
||||
readOnly: boolean;
|
||||
diagnosticMessage(diagnostic: EditorDiagnostic): string;
|
||||
onChange(value: string): void;
|
||||
onCreateEditor(view: EditorView): void;
|
||||
onDestroyEditor(): void;
|
||||
onUpdate(update: ViewUpdate): void;
|
||||
}
|
||||
|
||||
interface EditorCallbacks {
|
||||
onChange(value: string): void;
|
||||
onUpdate(update: ViewUpdate): void;
|
||||
}
|
||||
|
||||
const editorViews = new Map<string, EditorView>();
|
||||
const editorCallbacks = new Map<string, EditorCallbacks>();
|
||||
const editorContainers = new Map<string, HTMLDivElement>();
|
||||
|
||||
export default function DirectCodeMirror(props: DirectCodeMirrorProps) {
|
||||
const instanceId = useId();
|
||||
const [initialProps] = useState(props);
|
||||
const [containerReady, setContainerReady] = useState(false);
|
||||
const setContainer = useCallback(
|
||||
(container: HTMLDivElement | null) => {
|
||||
if (!container) {
|
||||
editorContainers.delete(instanceId);
|
||||
return;
|
||||
}
|
||||
editorContainers.set(instanceId, container);
|
||||
setContainerReady(true);
|
||||
},
|
||||
[instanceId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
editorCallbacks.set(instanceId, { onChange: props.onChange, onUpdate: props.onUpdate });
|
||||
}, [instanceId, props.onChange, props.onUpdate]);
|
||||
|
||||
useEffect(() => {
|
||||
const parent = editorContainers.get(instanceId);
|
||||
if (!parent) return;
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({ doc: initialProps.value, extensions: createExtensions(instanceId, initialProps) }),
|
||||
});
|
||||
editorViews.set(instanceId, view);
|
||||
initialProps.onCreateEditor(view);
|
||||
return () => {
|
||||
editorViews.delete(instanceId);
|
||||
editorCallbacks.delete(instanceId);
|
||||
initialProps.onDestroyEditor();
|
||||
view.destroy();
|
||||
};
|
||||
}, [containerReady, initialProps, instanceId]);
|
||||
|
||||
useEffect(() => {
|
||||
const view = editorViews.get(instanceId);
|
||||
if (!view || view.state.doc.toString() === props.value) return;
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: props.value } });
|
||||
}, [instanceId, props.value]);
|
||||
|
||||
useEffect(() => {
|
||||
const view = editorViews.get(instanceId);
|
||||
if (!view) return;
|
||||
view.dispatch({ effects: StateEffect.reconfigure.of(createExtensions(instanceId, props)) });
|
||||
}, [instanceId, props]);
|
||||
|
||||
return <div ref={setContainer} />;
|
||||
}
|
||||
|
||||
function createExtensions(instanceId: string, props: DirectCodeMirrorProps) {
|
||||
const language =
|
||||
props.language === "jsx"
|
||||
? [
|
||||
javascript({ jsx: true }),
|
||||
autocompletion({ override: [createCustomJsxCompletionSource(props.completions)] }),
|
||||
customJsxComponentHover,
|
||||
]
|
||||
: [json()];
|
||||
return [
|
||||
basicSetup,
|
||||
...language,
|
||||
linter((view) =>
|
||||
props.diagnostics.map((diagnostic) => {
|
||||
const from = Math.min(diagnostic.index ?? 0, view.state.doc.length);
|
||||
return {
|
||||
from,
|
||||
to: Math.min(from + 1, view.state.doc.length),
|
||||
severity: diagnostic.severity,
|
||||
message: props.diagnosticMessage(diagnostic),
|
||||
};
|
||||
}),
|
||||
),
|
||||
EditorView.contentAttributes.of({ id: props.id, "aria-label": props.label }),
|
||||
EditorView.editable.of(!props.readOnly),
|
||||
EditorState.readOnly.of(props.readOnly),
|
||||
keymap.of(props.readOnly ? [] : [indentWithTab]),
|
||||
props.placeholder ? codeMirrorPlaceholder(props.placeholder) : [],
|
||||
EditorView.theme({ "&": { height: props.height }, ".cm-scroller": { overflow: "auto" } }),
|
||||
props.theme === "dark" ? oneDark : [],
|
||||
EditorView.updateListener.of((update) => {
|
||||
const callbacks = editorCallbacks.get(instanceId);
|
||||
if (!callbacks) return;
|
||||
if (update.docChanged) callbacks.onChange(update.state.doc.toString());
|
||||
callbacks.onUpdate(update);
|
||||
}),
|
||||
];
|
||||
}
|
||||
Reference in new issue
Block a user