Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: Prevent editing Code Text component as text (#3246)

Oleg Isonenc478e65029ea
diff --git a/apps/builder/app/builder/features/project-settings/section-general.tsx b/apps/builder/app/builder/features/project-settings/section-general.tsx
index 641ea4ff1d..f489cdb84f 100644
--- a/apps/builder/app/builder/features/project-settings/section-general.tsx
+++ b/apps/builder/app/builder/features/project-settings/section-general.tsx
@@ -19,7 +19,7 @@ import type { ProjectMeta, CompilerSettings } from "@webstudio-is/sdk";
import { useState } from "react";
import { serverSyncStore } from "~/shared/sync";
import { sectionSpacing } from "./utils";
-import { HtmlEditor } from "~/builder/shared/html-editor";
+import { CodeEditor } from "~/builder/shared/code-editor";
const imgStyle = css({
width: 72,
@@ -112,7 +112,7 @@ export const SectionGeneral = () => {
Custom code and scripts will be added at the end of the <head>
tag to every page across the published project.
</Text>
- <HtmlEditor value={meta.code ?? ""} onChange={handleSave("code")} />
+ <CodeEditor value={meta.code ?? ""} onChange={handleSave("code")} />
</Grid>
<Separator />
diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
index 06744ddb1e..6609acf382 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
@@ -1,5 +1,5 @@
import { useStore } from "@nanostores/react";
-import { HtmlEditor } from "~/builder/shared/html-editor";
+import { CodeEditor } from "~/builder/shared/code-editor";
import {
BindingControl,
BindingPopover,
@@ -84,18 +84,21 @@ export const CodeControl = ({
deletable,
onChange,
onDelete,
-}: ControlProps<"code">) => {
+}: ControlProps<"code"> | ControlProps<"codetext">) => {
const [error, setError] = useState<Error>();
const metaOverride = {
...meta,
control: "text" as const,
};
+ const lang = meta.control === "code" ? "html" : undefined;
const localValue = useLocalValue(String(computedValue ?? ""), (value) => {
- const error = validateHtml(value);
- setError(error);
+ if (lang === "html") {
+ const error = validateHtml(value);
+ setError(error);
- if (error) {
- return;
+ if (error) {
+ return;
+ }
}
if (prop?.type === "expression") {
@@ -142,10 +145,11 @@ export const CodeControl = ({
onDelete={onDelete}
>
<BindingControl>
- <HtmlEditor
+ <CodeEditor
+ lang={lang}
title={
<Flex gap="1" align="center">
- <Text variant="labelsTitleCase">HTML Code Editor</Text>
+ <Text variant="labelsTitleCase">Code Editor</Text>
{errorInfo}
</Flex>
}
diff --git a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
index 45b24f2df5..940f51989f 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/combined.tsx
@@ -45,6 +45,10 @@ export const renderControl = ({
return <CodeControl key={key} meta={meta} prop={prop} {...rest} />;
}
+ if (meta.control === "codetext") {
+ return <CodeControl key={key} meta={meta} prop={prop} {...rest} />;
+ }
+
if (meta.control === "color") {
return (
<TextControl
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index 186b31fec8..f9da97217e 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -61,7 +61,7 @@ import {
EditorDialog,
EditorDialogButton,
EditorDialogControl,
-} from "~/builder/shared/code-editor";
+} from "~/builder/shared/code-editor-base";
import { ResourceForm } from "./resource-panel";
import { generateCurl } from "./curl";
diff --git a/apps/builder/app/builder/shared/code-editor-base.tsx b/apps/builder/app/builder/shared/code-editor-base.tsx
new file mode 100644
index 0000000000..23a4e1d5d2
--- /dev/null
+++ b/apps/builder/app/builder/shared/code-editor-base.tsx
@@ -0,0 +1,386 @@
+import {
+ useEffect,
+ useRef,
+ type ReactNode,
+ useState,
+ forwardRef,
+ type ComponentProps,
+} from "react";
+import {
+ Annotation,
+ EditorState,
+ StateEffect,
+ type Extension,
+} from "@codemirror/state";
+import {
+ EditorView,
+ drawSelection,
+ dropCursor,
+ keymap,
+} from "@codemirror/view";
+import {
+ defaultKeymap,
+ history,
+ historyKeymap,
+ indentWithTab,
+} from "@codemirror/commands";
+import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
+import { tags } from "@lezer/highlight";
+import {
+ theme,
+ textVariants,
+ css,
+ SmallIconButton,
+ Dialog,
+ DialogTrigger,
+ DialogContent,
+ Grid,
+ DialogTitle,
+ Button,
+ DialogClose,
+ Flex,
+} from "@webstudio-is/design-system";
+import { CrossIcon, MaximizeIcon, MinimizeIcon } from "@webstudio-is/icons";
+
+const ExternalChange = Annotation.define<boolean>();
+
+const minHeightVar = "--ws-code-editor-min-height";
+const maxHeightVar = "--ws-code-editor-max-height";
+
+export const getMinMaxHeightVars = ({
+ minHeight,
+ maxHeight,
+}: {
+ minHeight: string;
+ maxHeight: string;
+}) => ({
+ [minHeightVar]: minHeight,
+ [maxHeightVar]: maxHeight,
+});
+
+const editorContentStyle = css({
+ ...textVariants.mono,
+ // fit editor into parent if stretched
+ display: "flex",
+ minHeight: 0,
+ boxSizing: "border-box",
+ color: theme.colors.foregroundMain,
+ borderRadius: theme.borderRadius[4],
+ border: `1px solid ${theme.colors.borderMain}`,
+ background: theme.colors.backgroundControls,
+ paddingTop: 6,
+ paddingBottom: 4,
+ paddingRight: theme.spacing[2],
+ paddingLeft: theme.spacing[3],
+ "&:focus-within": {
+ borderColor: theme.colors.borderFocus,
+ outline: `1px solid ${theme.colors.borderFocus}`,
+ },
+ '&[data-invalid="true"]': {
+ borderColor: theme.colors.borderDestructiveMain,
+ outlineColor: theme.colors.borderDestructiveMain,
+ },
+ "& .cm-focused": {
+ outline: "none",
+ },
+ // fix scrolls appear on mount
+ "& .cm-scroller": {
+ overflowX: "hidden",
+ },
+ "& .cm-content": {
+ padding: 0,
+ // makes sure you can click to focus when editor content is smaller than the container
+ minHeight: "100%",
+ },
+ "& .cm-line": {
+ padding: 0,
+ },
+ "& .cm-editor": {
+ width: "100%",
+ // avoid modifying height in .cm-content
+ // because it breaks scroll events and makes scrolling laggy
+ minHeight: `var(${minHeightVar}, auto)`,
+ maxHeight: `var(${maxHeightVar}, none)`,
+ },
+});
+
+// https://thememirror.net/clouds
+const highlightStyle = HighlightStyle.define([
+ {
+ tag: tags.comment,
+ color: "#BCC8BA",
+ },
+ {
+ tag: [tags.string, tags.special(tags.brace), tags.regexp],
+ color: "#5D90CD",
+ },
+ {
+ tag: [tags.number, tags.bool, tags.null],
+ color: "#46A609",
+ },
+ {
+ tag: tags.keyword,
+ color: "#AF956F",
+ },
+ {
+ tag: [tags.definitionKeyword, tags.modifier],
+ color: "#C52727",
+ },
+ {
+ tag: [tags.angleBracket, tags.tagName, tags.attributeName],
+ color: "#606060",
+ },
+ {
+ tag: tags.self,
+ color: "#000",
+ },
+]);
+
+type EditorContentProps = {
+ extensions?: Extension[];
+ readOnly?: boolean;
+ autoFocus?: boolean;
+ invalid?: boolean;
+ value: string;
+ onChange: (newValue: string) => void;
+ onBlur?: (event: FocusEvent) => void;
+};
+
+export const EditorContent = ({
+ extensions = [],
+ readOnly = false,
+ autoFocus = false,
+ invalid = false,
+ value,
+ onChange,
+ onBlur,
+}: EditorContentProps) => {
+ const editorRef = useRef<null | HTMLDivElement>(null);
+ const viewRef = useRef<undefined | EditorView>();
+
+ const onChangeRef = useRef(onChange);
+ onChangeRef.current = onChange;
+ const onBlurRef = useRef(onBlur);
+ onBlurRef.current = onBlur;
+
+ // setup editor
+
+ useEffect(() => {
+ if (editorRef.current === null) {
+ return;
+ }
+ const view = new EditorView({
+ doc: "",
+ parent: editorRef.current,
+ });
+ if (autoFocus) {
+ view.focus();
+ }
+ viewRef.current = view;
+ return () => {
+ view.destroy();
+ };
+ }, [autoFocus]);
+
+ // update extensions whenever variables data is changed
+
+ useEffect(() => {
+ const view = viewRef.current;
+ if (view === undefined) {
+ return;
+ }
+ view.dispatch({
+ effects: StateEffect.reconfigure.of([
+ ...extensions,
+ history(),
+ drawSelection(),
+ dropCursor(),
+ syntaxHighlighting(highlightStyle, { fallback: true }),
+ keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
+ EditorView.lineWrapping,
+ EditorView.editable.of(readOnly === false),
+ EditorState.readOnly.of(readOnly === true),
+ // https://github.com/uiwjs/react-codemirror/blob/5d7a37245ce70e61f215b77dc42a7eaf295c46e7/core/src/useCodeMirror.ts#L57-L70
+ EditorView.updateListener.of((update) => {
+ if (
+ // prevent invoking callback when focus or selection is changed
+ update.docChanged &&
+ // prevent invoking callback when the change came from react value
+ update.transactions.some((trx) =>
+ trx.annotation(ExternalChange)
+ ) === false
+ ) {
+ onChangeRef.current(update.state.doc.toString());
+ }
+ }),
+ EditorView.domEventHandlers({
+ blur(event) {
+ onBlurRef.current?.(event);
+ },
+ cut(event) {
+ // prevent catching cut by global copy paste
+ // with target outside of contenteditable
+ event.stopPropagation();
+ },
+ }),
+ ]),
+ });
+ }, [readOnly, extensions]);
+
+ // update editor with react value
+ // https://github.com/uiwjs/react-codemirror/blob/5d7a37245ce70e61f215b77dc42a7eaf295c46e7/core/src/useCodeMirror.ts#L158-L169
+ useEffect(() => {
+ const view = viewRef.current;
+ if (view === undefined) {
+ return;
+ }
+ // prevent updating when editor has the same state
+ // and can be the source of new value
+ if (value === view.state.doc.toString()) {
+ return;
+ }
+ view.dispatch({
+ changes: { from: 0, to: view.state.doc.length, insert: value },
+ annotations: [ExternalChange.of(true)],
+ });
+ }, [value]);
+
+ return (
+ <div
+ className={editorContentStyle()}
+ data-invalid={invalid}
+ ref={editorRef}
+ />
+ );
+};
+
+const editorDialogControlStyle = css({
+ position: "relative",
+ "&:hover": {
+ "--ws-code-editor-maximize-icon-visibility": "visible",
+ },
+});
+
+export const EditorDialogControl = ({ children }: { children: ReactNode }) => {
+ return <div className={editorDialogControlStyle()}>{children}</div>;
+};
+
+export const EditorDialogButton = forwardRef<
+ HTMLButtonElement,
+ Partial<ComponentProps<typeof SmallIconButton>>
+>((props, ref) => {
+ return (
+ <SmallIconButton
+ {...props}
+ ref={ref}
+ icon={<MaximizeIcon />}
+ css={{
+ position: "absolute",
+ top: 6,
+ right: 4,
+ visibility: `var(--ws-code-editor-maximize-icon-visibility, hidden)`,
+ }}
+ />
+ );
+});
+EditorDialogButton.displayName = "EditorDialogButton";
+
+export const EditorDialog = ({
+ open,
+ onOpenChange,
+ title,
+ content,
+ children,
+}: {
+ open?: boolean;
+ onOpenChange?: (newOpen: boolean) => void;
+ title?: ReactNode;
+ content: ReactNode;
+ children: ReactNode;
+}) => {
+ const [isMaximized, setIsMaximized] = useState(false);
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange} modal={false}>
+ <DialogTrigger asChild>{children}</DialogTrigger>
+ <DialogContent
+ resize="auto"
+ width={640}
+ height={480}
+ minHeight={240}
+ isMaximized={isMaximized}
+ onInteractOutside={(event) => {
+ event.preventDefault();
+ }}
+ >
+ <Grid
+ align="stretch"
+ css={{
+ padding: theme.spacing[7],
+ height: "100%",
+ overflow: "hidden",
+ boxSizing: "content-box",
+ }}
+ >
+ {content}
+ </Grid>
+ {/* Title is at the end intentionally,
+ * to make the close button last in the tab order
+ */}
+ <DialogTitle
+ draggable
+ suffix={
+ <Flex
+ gap="1"
+ onMouseDown={(event) => {
+ // Prevent dragging dialog
+ event.preventDefault();
+ }}
+ >
+ <Button
+ color="ghost"
+ prefix={isMaximized ? <MinimizeIcon /> : <MaximizeIcon />}
+ aria-label="Expand"
+ onClick={() => setIsMaximized(isMaximized ? false : true)}
+ />
+ <DialogClose asChild>
+ <Button
+ color="ghost"
+ prefix={<CrossIcon />}
+ aria-label="Close"
+ />
+ </DialogClose>
+ </Flex>
+ }
+ >
+ {title}
+ </DialogTitle>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export const CodeEditorBase = ({
+ title,
+ open,
+ onOpenChange,
+ ...editorContentProps
+}: EditorContentProps & {
+ title?: ReactNode;
+ open?: boolean;
+ onOpenChange?: (newOpen: boolean) => void;
+}) => {
+ const content = <EditorContent {...editorContentProps} />;
+ return (
+ <EditorDialogControl>
+ {content}
+ <EditorDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={title}
+ content={content}
+ >
+ <EditorDialogButton />
+ </EditorDialog>
+ </EditorDialogControl>
+ );
+};
diff --git a/apps/builder/app/builder/shared/code-editor.stories.tsx b/apps/builder/app/builder/shared/code-editor.stories.tsx
new file mode 100644
index 0000000000..715c83dc8f
--- /dev/null
+++ b/apps/builder/app/builder/shared/code-editor.stories.tsx
@@ -0,0 +1,27 @@
+import { useState } from "react";
+import type { Meta } from "@storybook/react";
+import { CodeEditor as CodeEditorComponent } from "./code-editor";
+
+export default {
+ title: "Builder/Code Editor",
+ component: CodeEditorComponent,
+} satisfies Meta;
+
+const initialHtml = `
+<div>
+ <a href="#">Click me</a>
+</div>
+<script>
+ runMyJavascript()
+</script>
+`.trim();
+
+export const BaseEditor = () => {
+ const [value, setValue] = useState(initialHtml);
+ return <CodeEditorComponent value={value} onChange={setValue} />;
+};
+
+export const HtmlEditor = () => {
+ const [value, setValue] = useState(initialHtml);
+ return <CodeEditorComponent value={value} onChange={setValue} lang="html" />;
+};
diff --git a/apps/builder/app/builder/shared/code-editor.tsx b/apps/builder/app/builder/shared/code-editor.tsx
index 4ee00226fa..d50749d9f5 100644
--- a/apps/builder/app/builder/shared/code-editor.tsx
+++ b/apps/builder/app/builder/shared/code-editor.tsx
@@ -1,386 +1,122 @@
+import { forwardRef, useMemo, type ComponentProps, useEffect } from "react";
import {
- useEffect,
- useRef,
- type ReactNode,
- useState,
- forwardRef,
- type ComponentProps,
-} from "react";
-import {
- Annotation,
- EditorState,
- StateEffect,
- type Extension,
-} from "@codemirror/state";
-import {
- EditorView,
- drawSelection,
- dropCursor,
keymap,
+ tooltips,
+ highlightSpecialChars,
+ highlightActiveLine,
} from "@codemirror/view";
+import { bracketMatching, indentOnInput } from "@codemirror/language";
import {
- defaultKeymap,
- history,
- historyKeymap,
- indentWithTab,
-} from "@codemirror/commands";
-import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
-import { tags } from "@lezer/highlight";
-import {
- theme,
- textVariants,
- css,
- SmallIconButton,
- Dialog,
- DialogTrigger,
- DialogContent,
- Grid,
- DialogTitle,
- Button,
- DialogClose,
- Flex,
-} from "@webstudio-is/design-system";
-import { CrossIcon, MaximizeIcon, MinimizeIcon } from "@webstudio-is/icons";
-
-const ExternalChange = Annotation.define<boolean>();
-
-const minHeightVar = "--ws-code-editor-min-height";
-const maxHeightVar = "--ws-code-editor-max-height";
-
-export const getMinMaxHeightVars = ({
- minHeight,
- maxHeight,
-}: {
- minHeight: string;
- maxHeight: string;
-}) => ({
- [minHeightVar]: minHeight,
- [maxHeightVar]: maxHeight,
-});
-
-const editorContentStyle = css({
- ...textVariants.mono,
- // fit editor into parent if stretched
- display: "flex",
- minHeight: 0,
- boxSizing: "border-box",
- color: theme.colors.foregroundMain,
- borderRadius: theme.borderRadius[4],
- border: `1px solid ${theme.colors.borderMain}`,
- background: theme.colors.backgroundControls,
- paddingTop: 6,
- paddingBottom: 4,
- paddingRight: theme.spacing[2],
- paddingLeft: theme.spacing[3],
- "&:focus-within": {
- borderColor: theme.colors.borderFocus,
- outline: `1px solid ${theme.colors.borderFocus}`,
- },
- '&[data-invalid="true"]': {
- borderColor: theme.colors.borderDestructiveMain,
- outlineColor: theme.colors.borderDestructiveMain,
- },
- "& .cm-focused": {
- outline: "none",
- },
- // fix scrolls appear on mount
- "& .cm-scroller": {
- overflowX: "hidden",
- },
- "& .cm-content": {
- padding: 0,
- // makes sure you can click to focus when editor content is smaller than the container
- minHeight: "100%",
- },
- "& .cm-line": {
- padding: 0,
- },
- "& .cm-editor": {
- width: "100%",
- // avoid modifying height in .cm-content
- // because it breaks scroll events and makes scrolling laggy
- minHeight: `var(${minHeightVar}, auto)`,
- maxHeight: `var(${maxHeightVar}, none)`,
+ autocompletion,
+ closeBrackets,
+ closeBracketsKeymap,
+ completionKeymap,
+} from "@codemirror/autocomplete";
+import { html } from "@codemirror/lang-html";
+import { theme, textVariants, css } from "@webstudio-is/design-system";
+import { CodeEditorBase, getMinMaxHeightVars } from "./code-editor-base";
+
+const autocompletionStyle = css({
+ "&.cm-tooltip.cm-tooltip-autocomplete": {
+ ...textVariants.mono,
+ border: "none",
+ backgroundColor: "transparent",
+ // override none set on body by radix popover
+ pointerEvents: "auto",
+ "& ul": {
+ minWidth: 160,
+ maxWidth: 260,
+ width: "max-content",
+ boxSizing: "border-box",
+ borderRadius: theme.borderRadius[6],
+ backgroundColor: theme.colors.backgroundMenu,
+ border: `1px solid ${theme.colors.borderMain}`,
+ boxShadow: `${theme.shadows.menuDropShadow}, inset 0 0 0 1px ${theme.colors.borderMenuInner}`,
+ padding: theme.spacing[3],
+ "& li": {
+ ...textVariants.labelsTitleCase,
+ textTransform: "none",
+ position: "relative",
+ display: "flex",
+ alignItems: "center",
+ color: theme.colors.foregroundMain,
+ padding: theme.spacing[3],
+ borderRadius: theme.borderRadius[3],
+ "&[aria-selected], &:hover": {
+ color: theme.colors.foregroundMain,
+ backgroundColor: theme.colors.backgroundItemMenuItemHover,
+ },
+ "& .cm-completionLabel": {
+ flexGrow: 1,
+ },
+ "& .cm-completionDetail": {
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ fontStyle: "normal",
+ color: theme.colors.hint,
+ },
+ },
+ },
},
});
-// https://thememirror.net/clouds
-const highlightStyle = HighlightStyle.define([
- {
- tag: tags.comment,
- color: "#BCC8BA",
- },
- {
- tag: [tags.string, tags.special(tags.brace), tags.regexp],
- color: "#5D90CD",
- },
- {
- tag: [tags.number, tags.bool, tags.null],
- color: "#46A609",
- },
- {
- tag: tags.keyword,
- color: "#AF956F",
- },
- {
- tag: [tags.definitionKeyword, tags.modifier],
- color: "#C52727",
- },
- {
- tag: [tags.angleBracket, tags.tagName, tags.attributeName],
- color: "#606060",
- },
- {
- tag: tags.self,
- color: "#000",
- },
-]);
-
-type EditorContentProps = {
- extensions: Extension[];
- readOnly?: boolean;
- autoFocus?: boolean;
- invalid?: boolean;
- value: string;
- onChange: (newValue: string) => void;
- onBlur?: (event: FocusEvent) => void;
-};
-
-export const BaseCodeEditor = ({
- extensions,
- readOnly = false,
- autoFocus = false,
- invalid = false,
- value,
- onChange,
- onBlur,
-}: EditorContentProps) => {
- const editorRef = useRef<null | HTMLDivElement>(null);
- const viewRef = useRef<undefined | EditorView>();
-
- const onChangeRef = useRef(onChange);
- onChangeRef.current = onChange;
- const onBlurRef = useRef(onBlur);
- onBlurRef.current = onBlur;
+const wrapperStyle = css({
+ position: "relative",
+ // 1 line is 16px
+ // set min 10 lines and max 20 lines
+ ...getMinMaxHeightVars({ minHeight: "160px", maxHeight: "320px" }),
+});
- // setup editor
+const getHtmlExtensions = () => [
+ highlightActiveLine(),
+ highlightSpecialChars(),
+ indentOnInput(),
+ html({}),
+ bracketMatching(),
+ closeBrackets(),
+ // render autocomplete in body
+ // to prevent popover scroll overflow
+ tooltips({ parent: document.body }),
+ autocompletion({
+ icons: false,
+ tooltipClass: () => autocompletionStyle.toString(),
+ closeOnBlur: false,
+ }),
+ keymap.of([...closeBracketsKeymap, ...completionKeymap]),
+];
+
+export const CodeEditor = forwardRef<
+ HTMLDivElement,
+ Omit<ComponentProps<typeof CodeEditorBase>, "extensions"> & { lang?: "html" }
+>(({ lang, ...props }, ref) => {
+ const extensions = useMemo(
+ () => (lang === "html" ? getHtmlExtensions() : []),
+ [lang]
+ );
+ // prevent clicking on autocomplete options propagating to body
+ // and closing dialogs and popovers
useEffect(() => {
- if (editorRef.current === null) {
- return;
- }
- const view = new EditorView({
- doc: "",
- parent: editorRef.current,
- });
- if (autoFocus) {
- view.focus();
- }
- viewRef.current = view;
+ const handlePointerDown = (event: PointerEvent) => {
+ if (
+ event.target instanceof HTMLElement &&
+ event.target.closest(".cm-tooltip-autocomplete")
+ ) {
+ event.stopPropagation();
+ }
+ };
+ const options = { capture: true };
+ document.addEventListener("pointerdown", handlePointerDown, options);
return () => {
- view.destroy();
+ document.removeEventListener("pointerdown", handlePointerDown, options);
};
- }, [autoFocus]);
-
- // update extensions whenever variables data is changed
-
- useEffect(() => {
- const view = viewRef.current;
- if (view === undefined) {
- return;
- }
- view.dispatch({
- effects: StateEffect.reconfigure.of([
- ...extensions,
- history(),
- drawSelection(),
- dropCursor(),
- syntaxHighlighting(highlightStyle, { fallback: true }),
- keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
- EditorView.lineWrapping,
- EditorView.editable.of(readOnly === false),
- EditorState.readOnly.of(readOnly === true),
- // https://github.com/uiwjs/react-codemirror/blob/5d7a37245ce70e61f215b77dc42a7eaf295c46e7/core/src/useCodeMirror.ts#L57-L70
- EditorView.updateListener.of((update) => {
- if (
- // prevent invoking callback when focus or selection is changed
- update.docChanged &&
- // prevent invoking callback when the change came from react value
- update.transactions.some((trx) =>
- trx.annotation(ExternalChange)
- ) === false
- ) {
- onChangeRef.current(update.state.doc.toString());
- }
- }),
- EditorView.domEventHandlers({
- blur(event) {
- onBlurRef.current?.(event);
- },
- cut(event) {
- // prevent catching cut by global copy paste
- // with target outside of contenteditable
- event.stopPropagation();
- },
- }),
- ]),
- });
- }, [readOnly, extensions]);
-
- // update editor with react value
- // https://github.com/uiwjs/react-codemirror/blob/5d7a37245ce70e61f215b77dc42a7eaf295c46e7/core/src/useCodeMirror.ts#L158-L169
- useEffect(() => {
- const view = viewRef.current;
- if (view === undefined) {
- return;
- }
- // prevent updating when editor has the same state
- // and can be the source of new value
- if (value === view.state.doc.toString()) {
- return;
- }
- view.dispatch({
- changes: { from: 0, to: view.state.doc.length, insert: value },
- annotations: [ExternalChange.of(true)],
- });
- }, [value]);
+ }, []);
return (
- <div
- className={editorContentStyle()}
- data-invalid={invalid}
- ref={editorRef}
- />
- );
-};
-
-const editorDialogControlStyle = css({
- position: "relative",
- "&:hover": {
- "--ws-code-editor-maximize-icon-visibility": "visible",
- },
-});
-
-export const EditorDialogControl = ({ children }: { children: ReactNode }) => {
- return <div className={editorDialogControlStyle()}>{children}</div>;
-};
-
-export const EditorDialogButton = forwardRef<
- HTMLButtonElement,
- Partial<ComponentProps<typeof SmallIconButton>>
->((props, ref) => {
- return (
- <SmallIconButton
- {...props}
- ref={ref}
- icon={<MaximizeIcon />}
- css={{
- position: "absolute",
- top: 6,
- right: 4,
- visibility: `var(--ws-code-editor-maximize-icon-visibility, hidden)`,
- }}
- />
+ <div className={wrapperStyle()} ref={ref}>
+ <CodeEditorBase {...props} extensions={extensions} />
+ </div>
);
});
-EditorDialogButton.displayName = "EditorDialogButton";
-export const EditorDialog = ({
- open,
- onOpenChange,
- title,
- content,
- children,
-}: {
- open?: boolean;
- onOpenChange?: (newOpen: boolean) => void;
- title?: ReactNode;
- content: ReactNode;
- children: ReactNode;
-}) => {
- const [isMaximized, setIsMaximized] = useState(false);
- return (
- <Dialog open={open} onOpenChange={onOpenChange} modal={false}>
- <DialogTrigger asChild>{children}</DialogTrigger>
- <DialogContent
- resize="auto"
- width={640}
- height={480}
- minHeight={240}
- isMaximized={isMaximized}
- onInteractOutside={(event) => {
- event.preventDefault();
- }}
- >
- <Grid
- align="stretch"
- css={{
- padding: theme.spacing[7],
- height: "100%",
- overflow: "hidden",
- boxSizing: "content-box",
- }}
- >
- {content}
- </Grid>
- {/* Title is at the end intentionally,
- * to make the close button last in the tab order
- */}
- <DialogTitle
- draggable
- suffix={
- <Flex
- gap="1"
- onMouseDown={(event) => {
- // Prevent dragging dialog
- event.preventDefault();
- }}
- >
- <Button
- color="ghost"
- prefix={isMaximized ? <MinimizeIcon /> : <MaximizeIcon />}
- aria-label="Expand"
- onClick={() => setIsMaximized(isMaximized ? false : true)}
- />
- <DialogClose asChild>
- <Button
- color="ghost"
- prefix={<CrossIcon />}
- aria-label="Close"
- />
- </DialogClose>
- </Flex>
- }
- >
- {title}
- </DialogTitle>
- </DialogContent>
- </Dialog>
- );
-};
-
-export const CodeEditor = ({
- title,
- open,
- onOpenChange,
- ...editorContentProps
-}: EditorContentProps & {
- title?: ReactNode;
- open?: boolean;
- onOpenChange?: (newOpen: boolean) => void;
-}) => {
- const content = <BaseCodeEditor {...editorContentProps} />;
- return (
- <EditorDialogControl>
- {content}
- <EditorDialog
- open={open}
- onOpenChange={onOpenChange}
- title={title}
- content={content}
- >
- <EditorDialogButton />
- </EditorDialog>
- </EditorDialogControl>
- );
-};
+CodeEditor.displayName = "CodeEditor";
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index 2b115cb262..f39866433e 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -31,7 +31,7 @@ import {
decodeDataSourceVariable,
transpileExpression,
} from "@webstudio-is/sdk";
-import { BaseCodeEditor, CodeEditor, EditorDialog } from "./code-editor";
+import { CodeEditorBase, EditorDialog } from "./code-editor-base";
export const formatValue = (value: unknown) => {
if (Array.isArray(value)) {
@@ -402,7 +402,7 @@ export const ExpressionEditor = ({
return (
<div className={wrapperStyle.toString()}>
- <CodeEditor
+ <CodeEditorBase
extensions={extensions}
invalid={color === "error"}
readOnly={readOnly}
@@ -440,7 +440,7 @@ export const ExpressionEditor = ({
const ValuePreviewEditor = ({ value }: { value: unknown }) => {
const extensions = useMemo(() => [javascript({})], []);
return (
- <BaseCodeEditor
+ <CodeEditorBase
readOnly={true}
extensions={extensions}
value={JSON.stringify(value, null, 2)}
diff --git a/apps/builder/app/builder/shared/html-editor.stories.tsx b/apps/builder/app/builder/shared/html-editor.stories.tsx
deleted file mode 100644
index 4401f13093..0000000000
--- a/apps/builder/app/builder/shared/html-editor.stories.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { useState } from "react";
-import type { Meta, StoryObj } from "@storybook/react";
-import { HtmlEditor as HtmlEditorComponent } from "./html-editor";
-
-export default {
- title: "Builder/Html Editor",
- component: HtmlEditorComponent,
-} satisfies Meta;
-
-const initialHtml = `
-<div>
- <a href="#">Click me</a>
-</div>
-<script>
- runMyJavascript()
-</script>
-`.trim();
-
-const HtmlStory = () => {
- const [value, setValue] = useState(initialHtml);
- return <HtmlEditorComponent value={value} onChange={setValue} />;
-};
-
-export const HtmlEditor: StoryObj = {
- render: () => <HtmlStory />,
-};
diff --git a/apps/builder/app/builder/shared/html-editor.tsx b/apps/builder/app/builder/shared/html-editor.tsx
deleted file mode 100644
index 30f72626b6..0000000000
--- a/apps/builder/app/builder/shared/html-editor.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { forwardRef, useMemo, type ComponentProps, useEffect } from "react";
-import {
- keymap,
- tooltips,
- highlightSpecialChars,
- highlightActiveLine,
-} from "@codemirror/view";
-import { bracketMatching, indentOnInput } from "@codemirror/language";
-import {
- autocompletion,
- closeBrackets,
- closeBracketsKeymap,
- completionKeymap,
-} from "@codemirror/autocomplete";
-import { html } from "@codemirror/lang-html";
-import { theme, textVariants, css } from "@webstudio-is/design-system";
-import { CodeEditor, getMinMaxHeightVars } from "./code-editor";
-
-const autocompletionStyle = css({
- "&.cm-tooltip.cm-tooltip-autocomplete": {
- ...textVariants.mono,
- border: "none",
- backgroundColor: "transparent",
- // override none set on body by radix popover
- pointerEvents: "auto",
- "& ul": {
- minWidth: 160,
- maxWidth: 260,
- width: "max-content",
- boxSizing: "border-box",
- borderRadius: theme.borderRadius[6],
- backgroundColor: theme.colors.backgroundMenu,
- border: `1px solid ${theme.colors.borderMain}`,
- boxShadow: `${theme.shadows.menuDropShadow}, inset 0 0 0 1px ${theme.colors.borderMenuInner}`,
- padding: theme.spacing[3],
- "& li": {
- ...textVariants.labelsTitleCase,
- textTransform: "none",
- position: "relative",
- display: "flex",
- alignItems: "center",
- color: theme.colors.foregroundMain,
- padding: theme.spacing[3],
- borderRadius: theme.borderRadius[3],
- "&[aria-selected], &:hover": {
- color: theme.colors.foregroundMain,
- backgroundColor: theme.colors.backgroundItemMenuItemHover,
- },
- "& .cm-completionLabel": {
- flexGrow: 1,
- },
- "& .cm-completionDetail": {
- overflow: "hidden",
- textOverflow: "ellipsis",
- fontStyle: "normal",
- color: theme.colors.hint,
- },
- },
- },
- },
-});
-
-const wrapperStyle = css({
- position: "relative",
- // 1 line is 16px
- // set min 10 lines and max 20 lines
- ...getMinMaxHeightVars({ minHeight: "160px", maxHeight: "320px" }),
-});
-
-export const HtmlEditor = forwardRef<
- HTMLDivElement,
- Omit<ComponentProps<typeof CodeEditor>, "extensions">
->((props, ref) => {
- const extensions = useMemo(
- () => [
- highlightActiveLine(),
- highlightSpecialChars(),
- indentOnInput(),
- html({}),
- bracketMatching(),
- closeBrackets(),
- // render autocomplete in body
- // to prevent popover scroll overflow
- tooltips({ parent: document.body }),
- autocompletion({
- icons: false,
- tooltipClass: () => autocompletionStyle.toString(),
- closeOnBlur: false,
- }),
- keymap.of([...closeBracketsKeymap, ...completionKeymap]),
- ],
- []
- );
-
- // prevent clicking on autocomplete options propagating to body
- // and closing dialogs and popovers
- useEffect(() => {
- const handlePointerDown = (event: PointerEvent) => {
- if (
- event.target instanceof HTMLElement &&
- event.target.closest(".cm-tooltip-autocomplete")
- ) {
- event.stopPropagation();
- }
- };
- const options = { capture: true };
- document.addEventListener("pointerdown", handlePointerDown, options);
- return () => {
- document.removeEventListener("pointerdown", handlePointerDown, options);
- };
- }, []);
-
- return (
- <div className={wrapperStyle()} ref={ref}>
- <CodeEditor {...props} extensions={extensions} />
- </div>
- );
-});
-
-HtmlEditor.displayName = "HtmlEditor";
diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.test.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.test.ts
index 485161e0ea..7441fe01c2 100644
--- a/apps/builder/app/shared/copy-paste/plugin-markdown.test.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.test.ts
@@ -571,12 +571,7 @@ baz",
"dataSources": [],
"instances": [
{
- "children": [
- {
- "type": "text",
- "value": "foo",
- },
- ],
+ "children": [],
"component": "CodeText",
"id": "123",
"type": "instance",
@@ -593,7 +588,15 @@ baz",
"type": "instance",
},
],
- "props": [],
+ "props": [
+ {
+ "id": "123",
+ "instanceId": "123",
+ "name": "code",
+ "type": "string",
+ "value": "foo",
+ },
+ ],
"resources": [],
"styleSourceSelections": [
{
@@ -638,18 +641,20 @@ baz",
"dataSources": [],
"instances": [
{
- "children": [
- {
- "type": "text",
- "value": "foo",
- },
- ],
+ "children": [],
"component": "CodeText",
"id": "123",
"type": "instance",
},
],
"props": [
+ {
+ "id": "123",
+ "instanceId": "123",
+ "name": "code",
+ "type": "string",
+ "value": "foo",
+ },
{
"id": "123",
"instanceId": "123",
diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.ts
index 997ba2607b..0444ac568f 100644
--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts
@@ -113,8 +113,11 @@ const toInstanceData = (
});
}
if (child.type === "inlineCode") {
- instance.children.push({
- type: "text",
+ props.push({
+ id: generateId(),
+ type: "string",
+ name: "code",
+ instanceId,
value: child.value,
});
const styleSourceId = generateId();
@@ -128,8 +131,11 @@ const toInstanceData = (
});
}
if (child.type === "code") {
- instance.children.push({
- type: "text",
+ props.push({
+ id: generateId(),
+ type: "string",
+ name: "code",
+ instanceId,
value: child.value,
});
if (child.lang) {
diff --git a/packages/react-sdk/src/prop-meta.ts b/packages/react-sdk/src/prop-meta.ts
index 95d2645a3d..48e2a87d5f 100644
--- a/packages/react-sdk/src/prop-meta.ts
+++ b/packages/react-sdk/src/prop-meta.ts
@@ -47,11 +47,10 @@ const Code = z.object({
control: z.literal("code"),
type: z.literal("string"),
defaultValue: z.string().optional(),
- /**
- * The number of rows in <textarea>. If set to 0 an <input> will be used instead.
- * In line with Storybook team's plan: https://github.com/storybookjs/storybook/issues/21100
- */
- rows: z.number().optional(),
+});
+
+const CodeText = Code.extend({
+ control: z.literal("codetext"),
});
const Color = z.object({
@@ -169,6 +168,7 @@ export const PropMeta = z.union([
Range,
Text,
Code,
+ CodeText,
Color,
Boolean,
Radio,
diff --git a/packages/sdk-components-react/src/__generated__/code-text.props.ts b/packages/sdk-components-react/src/__generated__/code-text.props.ts
index 659b4ec6e0..8b50cecea3 100644
--- a/packages/sdk-components-react/src/__generated__/code-text.props.ts
+++ b/packages/sdk-components-react/src/__generated__/code-text.props.ts
@@ -399,6 +399,7 @@ export const props: Record<string, PropMeta> = {
},
autoSave: { required: false, control: "text", type: "string" },
className: { required: false, control: "text", type: "string" },
+ code: { required: false, control: "text", type: "string" },
color: {
required: false,
control: "color",
diff --git a/packages/sdk-components-react/src/code-text.tsx b/packages/sdk-components-react/src/code-text.tsx
index 001058e94f..d396877713 100644
--- a/packages/sdk-components-react/src/code-text.tsx
+++ b/packages/sdk-components-react/src/code-text.tsx
@@ -1,14 +1,35 @@
-import { type ElementRef, type ComponentProps, forwardRef } from "react";
+import {
+ type ElementRef,
+ type ComponentProps,
+ forwardRef,
+ type ForwardedRef,
+} from "react";
export const defaultTag = "code";
+const Placeholder = ({
+ innerRef,
+ ...rest
+}: {
+ innerRef: ForwardedRef<HTMLElement>;
+}) => {
+ return (
+ <code {...rest} style={{ padding: 20 }} ref={innerRef}>
+ {`Open the "Settings" panel to edit the code.`}
+ </code>
+ );
+};
+
export const CodeText = forwardRef<
ElementRef<typeof defaultTag>,
- ComponentProps<typeof defaultTag>
->(({ children, ...props }, ref) => {
+ ComponentProps<typeof defaultTag> & { code?: string }
+>(({ code, ...props }, ref) => {
+ if (code === undefined || String(code).trim().length === 0) {
+ return <Placeholder innerRef={ref} {...props} />;
+ }
return (
<code {...props} ref={ref}>
- {children ?? "Code you can edit"}
+ {code}
</code>
);
});
diff --git a/packages/sdk-components-react/src/code-text.ws.ts b/packages/sdk-components-react/src/code-text.ws.ts
index ded86616d2..a85ac21fe3 100644
--- a/packages/sdk-components-react/src/code-text.ws.ts
+++ b/packages/sdk-components-react/src/code-text.ws.ts
@@ -37,7 +37,7 @@ const presetStyle = {
export const meta: WsComponentMeta = {
category: "general",
- type: "container",
+ type: "embed",
label: "Code Text",
description:
"Use this component when you want to display code as text on the page.",
@@ -49,6 +49,13 @@ export const meta: WsComponentMeta = {
};
export const propsMeta: WsComponentPropsMeta = {
- props,
- initialProps: ["id", "className", "lang"],
+ props: {
+ ...props,
+ code: {
+ required: true,
+ control: "codetext",
+ type: "string",
+ },
+ },
+ initialProps: ["id", "className", "lang", "code"],
};
diff --git a/packages/sdk-components-react/src/html-embed.tsx b/packages/sdk-components-react/src/html-embed.tsx
index 6bc7df5b5c..dc0028cc4c 100644
--- a/packages/sdk-components-react/src/html-embed.tsx
+++ b/packages/sdk-components-react/src/html-embed.tsx
@@ -115,8 +115,8 @@ type ChildProps = {
const Placeholder = (props: ChildProps) => {
const { code, innerRef, ...rest } = props;
return (
- <div ref={innerRef} {...rest} style={{ padding: "20px" }}>
- {'Open the "Settings" panel to insert HTML code'}
+ <div ref={innerRef} {...rest} style={{ padding: 20 }}>
+ {'Open the "Settings" panel to insert HTML code.'}
</div>
);
};