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.

feat: add html editor (#2717)

Bogdan Chadkina22f9fe90092
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 c25023e4c8..6716f54185 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
@@ -1,8 +1,15 @@
-import type { ControlProps } from "../shared";
-import { TextControl } from "./text";
+import { Box, theme } from "@webstudio-is/design-system";
+import {
+ useLocalValue,
+ type ControlProps,
+ getLabel,
+ VerticalLayout,
+ Label,
+} from "../shared";
+import { VariablesButton } from "../variables";
+import { HtmlEditor } from "~/builder/shared/html-editor";
export const CodeControl = ({
- instanceId,
meta,
prop,
propName,
@@ -11,31 +18,46 @@ export const CodeControl = ({
onChange,
onDelete,
}: ControlProps<"code", "string">) => {
+ const metaOverride = {
+ ...meta,
+ control: "text" as const,
+ };
+ const localValue = useLocalValue(prop?.value ?? "", (value) => {
+ // sanitize html before saving
+ // this is basically what browser does when innerHTML is set
+ // but isolated within temporary element
+ // so the result is correct markup
+ const div = document.createElement("div");
+ div.innerHTML = value;
+ onChange({ type: "string", value: div.innerHTML });
+ });
+ const label = getLabel(metaOverride, propName);
+
return (
- <TextControl
- instanceId={instanceId}
- meta={{
- ...meta,
- control: "text",
- }}
- prop={prop}
- propName={propName}
- readOnly={readOnly}
+ <VerticalLayout
+ label={
+ <Box css={{ position: "relative" }}>
+ <Label description={metaOverride.description} readOnly={readOnly}>
+ {label}
+ </Label>
+ <VariablesButton
+ propId={prop?.id}
+ propName={propName}
+ propMeta={metaOverride}
+ />
+ </Box>
+ }
deletable={deletable}
- onChange={(value) => {
- if (value.type === "string") {
- // sanitize html before saving
- // this is basically what browser does when innerHTML is set
- // but isolated within temporary element
- // so the result is correct markup
- const div = document.createElement("div");
- div.innerHTML = value.value;
- onChange({ type: "string", value: div.innerHTML });
- } else {
- onChange(value);
- }
- }}
onDelete={onDelete}
- />
+ >
+ <Box css={{ py: theme.spacing[2] }}>
+ <HtmlEditor
+ readOnly={readOnly}
+ value={localValue.value}
+ onChange={localValue.set}
+ onBlur={localValue.save}
+ />
+ </Box>
+ </VerticalLayout>
);
};
diff --git a/apps/builder/app/builder/shared/code-editor.tsx b/apps/builder/app/builder/shared/code-editor.tsx
new file mode 100644
index 0000000000..8fdcbc0700
--- /dev/null
+++ b/apps/builder/app/builder/shared/code-editor.tsx
@@ -0,0 +1,134 @@
+import { useEffect, useRef } from "react";
+import {
+ Annotation,
+ EditorState,
+ StateEffect,
+ type Extension,
+} from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { theme, textVariants, css } from "@webstudio-is/design-system";
+
+const ExternalChange = Annotation.define<boolean>();
+
+const rootStyle = css({
+ ...textVariants.mono,
+ 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}`,
+ },
+ "& .cm-focused": {
+ outline: "none",
+ },
+ "& .cm-content": {
+ padding: 0,
+ },
+ "& .cm-line": {
+ padding: 0,
+ },
+});
+
+export const CodeEditor = ({
+ extensions,
+ readOnly = false,
+ autoFocus = false,
+ value,
+ onChange,
+ onBlur,
+}: {
+ extensions: Extension[];
+ readOnly?: boolean;
+ autoFocus?: boolean;
+ value: string;
+ onChange: (newValue: string) => void;
+ onBlur?: () => void;
+}) => {
+ 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,
+ 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: () => {
+ onBlurRef.current?.();
+ },
+ }),
+ ]),
+ });
+ }, [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={rootStyle.toString()} ref={editorRef}></div>;
+};
diff --git a/apps/builder/app/builder/shared/expression-editor.stories.tsx b/apps/builder/app/builder/shared/expression-editor.stories.tsx
index 918fb08ff7..523591573c 100644
--- a/apps/builder/app/builder/shared/expression-editor.stories.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.stories.tsx
@@ -3,7 +3,7 @@ import { ExpressionEditor as ExpressionEditorComponent } from "./expression-edit
import { useState } from "react";
export default {
- title: "Builder/ExpressionEditor",
+ title: "Builder/Expression Editor",
component: ExpressionEditorComponent,
} satisfies Meta;
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index 5dd121c22d..62a1bfbc5b 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -1,6 +1,6 @@
-import { useEffect, useRef } from "react";
+import { useMemo } from "react";
import { matchSorter } from "match-sorter";
-import { Annotation, EditorState, Facet, StateEffect } from "@codemirror/state";
+import { Facet } from "@codemirror/state";
import {
type DecorationSet,
type ViewUpdate,
@@ -31,6 +31,7 @@ import {
} from "@codemirror/autocomplete";
import { completionPath, javascript } from "@codemirror/lang-javascript";
import { theme, textVariants, css } from "@webstudio-is/design-system";
+import { CodeEditor } from "./code-editor";
export const formatValue = (value: unknown) => {
if (Array.isArray(value)) {
@@ -70,8 +71,6 @@ export const formatValuePreview = (value: unknown) => {
return typeof value;
};
-const ExternalChange = Annotation.define<boolean>();
-
type Scope = Record<string, unknown>;
type Aliases = Map<string, string>;
@@ -168,32 +167,6 @@ const variables = ViewPlugin.fromClass(
}
);
-const rootStyle = css({
- ...textVariants.mono,
- 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}`,
- },
- "& .cm-focused": {
- outline: "none",
- },
- "& .cm-content": {
- padding: 0,
- },
- "& .cm-line": {
- padding: 0,
- },
-});
-
const autocompletionStyle = css({
"&.cm-tooltip.cm-tooltip-autocomplete": {
...textVariants.mono,
@@ -262,114 +235,51 @@ export const ExpressionEditor = ({
onChange: (newValue: string) => void;
onBlur?: () => void;
}) => {
- 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([
- history(),
- drawSelection(),
- dropCursor(),
- bracketMatching(),
- closeBrackets(),
- EditorView.lineWrapping,
- syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
- javascript({}),
- VariablesData.of({ scope, aliases }),
- // render autocomplete in body
- // to prevent popover scroll overflow
- tooltips({ parent: document.body }),
- autocompletion({
- override: [scopeCompletionSource],
- icons: false,
- tooltipClass: () => autocompletionStyle.toString(),
- }),
- variables,
- keymap.of([
- ...closeBracketsKeymap,
- ...defaultKeymap,
- ...historyKeymap,
- ...completionKeymap,
- // use tab to trigger completion
- {
- key: "Tab",
- preventDefault: true,
- stopPropagation: true,
- run: startCompletion,
- },
- ]),
- 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: () => {
- onBlurRef.current?.();
- },
- }),
+ const extensions = useMemo(
+ () => [
+ history(),
+ drawSelection(),
+ dropCursor(),
+ bracketMatching(),
+ closeBrackets(),
+ EditorView.lineWrapping,
+ syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
+ javascript({}),
+ VariablesData.of({ scope, aliases }),
+ // render autocomplete in body
+ // to prevent popover scroll overflow
+ tooltips({ parent: document.body }),
+ autocompletion({
+ override: [scopeCompletionSource],
+ icons: false,
+ tooltipClass: () => autocompletionStyle.toString(),
+ }),
+ variables,
+ keymap.of([
+ ...closeBracketsKeymap,
+ ...defaultKeymap,
+ ...historyKeymap,
+ ...completionKeymap,
+ // use tab to trigger completion
+ {
+ key: "Tab",
+ preventDefault: true,
+ stopPropagation: true,
+ run: startCompletion,
+ },
]),
- });
- }, [scope, aliases, readOnly]);
-
- // 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]);
+ ],
+ [scope, aliases]
+ );
- return <div className={rootStyle.toString()} ref={editorRef}></div>;
+ return (
+ <CodeEditor
+ extensions={extensions}
+ readOnly={readOnly}
+ autoFocus={autoFocus}
+ value={value}
+ onChange={onChange}
+ onBlur={onBlur}
+ />
+ );
};
diff --git a/apps/builder/app/builder/shared/html-editor.stories.tsx b/apps/builder/app/builder/shared/html-editor.stories.tsx
new file mode 100644
index 0000000000..4401f13093
--- /dev/null
+++ b/apps/builder/app/builder/shared/html-editor.stories.tsx
@@ -0,0 +1,26 @@
+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
new file mode 100644
index 0000000000..367ff414aa
--- /dev/null
+++ b/apps/builder/app/builder/shared/html-editor.tsx
@@ -0,0 +1,131 @@
+import { useMemo } from "react";
+import {
+ keymap,
+ drawSelection,
+ dropCursor,
+ EditorView,
+ tooltips,
+ highlightSpecialChars,
+ highlightActiveLine,
+} from "@codemirror/view";
+import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
+import {
+ bracketMatching,
+ defaultHighlightStyle,
+ indentOnInput,
+ syntaxHighlighting,
+} 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 } from "./code-editor";
+
+const autocompletionStyle = css({
+ "&.cm-tooltip.cm-tooltip-autocomplete": {
+ ...textVariants.mono,
+ border: "none",
+ backgroundColor: "transparent",
+ "& 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]": {
+ 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({
+ "& .cm-content": {
+ // 1 line is 16px
+ // set min 10 lines and max 20 lines
+ minHeight: 160,
+ maxHeight: 320,
+ },
+});
+
+export const HtmlEditor = ({
+ readOnly = false,
+ value,
+ onChange,
+ onBlur,
+}: {
+ readOnly?: boolean;
+ value: string;
+ onChange: (newValue: string) => void;
+ onBlur?: () => void;
+}) => {
+ const extensions = useMemo(
+ () => [
+ highlightActiveLine(),
+ highlightSpecialChars(),
+ history(),
+ drawSelection(),
+ dropCursor(),
+ indentOnInput(),
+ EditorView.lineWrapping,
+ syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
+ html({}),
+ bracketMatching(),
+ closeBrackets(),
+ // render autocomplete in body
+ // to prevent popover scroll overflow
+ tooltips({ parent: document.body }),
+ autocompletion({
+ icons: false,
+ tooltipClass: () => autocompletionStyle.toString(),
+ }),
+ keymap.of([
+ ...closeBracketsKeymap,
+ ...defaultKeymap,
+ ...historyKeymap,
+ ...completionKeymap,
+ ]),
+ ],
+ []
+ );
+
+ return (
+ <div className={wrapperStyle.toString()}>
+ <CodeEditor
+ extensions={extensions}
+ readOnly={readOnly}
+ value={value}
+ onChange={onChange}
+ onBlur={onBlur}
+ />
+ </div>
+ );
+};
diff --git a/apps/builder/package.json b/apps/builder/package.json
index f20d45f7fb..8bdcc0ff0f 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -22,6 +22,7 @@
"dependencies": {
"@codemirror/autocomplete": "^6.11.1",
"@codemirror/commands": "^6.3.2",
+ "@codemirror/lang-html": "^6.4.7",
"@codemirror/lang-javascript": "^6.2.1",
"@codemirror/language": "^6.9.3",
"@codemirror/state": "^6.3.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c1c4d92b23..593a3e6236 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -67,6 +67,9 @@ importers:
'@codemirror/commands':
specifier: ^6.3.2
version: 6.3.2
+ '@codemirror/lang-html':
+ specifier: ^6.4.7
+ version: 6.4.7
'@codemirror/lang-javascript':
specifier: ^6.2.1
version: 6.2.1
@@ -3317,6 +3320,32 @@ packages:
'@lezer/common': 1.1.2
dev: false
+ /@codemirror/[email protected](@codemirror/[email protected]):
+ resolution: {integrity: sha512-/UNWDNV5Viwi/1lpr/dIXJNWiwDxpw13I4pTUAsNxZdg6E0mI2kTQb0P2iHczg1Tu+H4EBgJR+hYhKiHKko7qg==}
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.3
+ '@lezer/common': 1.1.2
+ '@lezer/css': 1.1.4
+ transitivePeerDependencies:
+ - '@codemirror/view'
+ dev: false
+
+ /@codemirror/[email protected]:
+ resolution: {integrity: sha512-y9hWSSO41XlcL4uYwWyk0lEgTHcelWWfRuqmvcAmxfCs0HNWZdriWo/EU43S63SxEZpc1Hd50Itw7ktfQvfkUg==}
+ dependencies:
+ '@codemirror/autocomplete': 6.11.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])
+ '@codemirror/lang-css': 6.2.1(@codemirror/[email protected])
+ '@codemirror/lang-javascript': 6.2.1
+ '@codemirror/language': 6.9.3
+ '@codemirror/state': 6.3.3
+ '@codemirror/view': 6.22.3
+ '@lezer/common': 1.1.2
+ '@lezer/css': 1.1.4
+ '@lezer/html': 1.3.7
+ dev: false
+
/@codemirror/[email protected]:
resolution: {integrity: sha512-jlFOXTejVyiQCW3EQwvKH0m99bUYIw40oPmFjSX2VS78yzfe0HELZ+NEo9Yfo1MkGRpGlj3Gnu4rdxV1EnAs5A==}
dependencies:
@@ -4847,12 +4876,27 @@ packages:
resolution: {integrity: sha512-V+GqBsga5+cQJMfM0GdnHmg4DgWvLzgMWjbldBg0+jC3k9Gu6nJNZDLJxXEBT1Xj8KhRN4jmbC5CY7SIL++sVw==}
dev: false
+ resolution: {integrity: sha512-CuUwjidrU7FOBokqASRJc72SmJ9g1PsHXDOWMoKg4md6+2u/Zxzwx5YsYrAFxRDsLrjLlsIyEF1rZHK3gFEJbw==}
+ dependencies:
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
resolution: {integrity: sha512-WrS5Mw51sGrpqjlh3d4/fOwpEV2Hd3YOkp9DBt4k8XZQcoTHZFB7sx030A6OcahF4J1nDQAa3jXlTVVYH50IFA==}
dependencies:
'@lezer/common': 1.1.2
dev: false
+ resolution: {integrity: sha512-Wo+rZ5UjLP0VqUTyXjzgmTYRW5bvTJUFn4Uw0K3HCQjX2/+f+zRo9GLN5BCAojwHQISPvaQk8BWSv2SSKx/UcQ==}
+ dependencies:
+ '@lezer/common': 1.1.2
+ '@lezer/highlight': 1.2.0
+ '@lezer/lr': 1.3.14
+ dev: false
+
resolution: {integrity: sha512-XJu3fZjHVVjJcRS7kHdwBO50irXc4H8rQwgm6SmT3Y8IHWk7WzpaLsaR2vdr/jSk/J4pQhXc1WLul7jVdxC+0Q==}
dependencies: