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.

refactor: replace editor events with commands (#2508)

Bogdan Chadkin4ddac0e7ffdd
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index ac2d0932a9..cb9df8e19d 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -305,7 +305,6 @@ export const Builder = ({
<Main>
<Workspace
onTransitionEnd={onTransitionEnd}
- publish={publish}
initialBreakpoints={build.breakpoints}
>
<CanvasIframe
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
index 186864c92e..70702afe55 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
@@ -1,5 +1,4 @@
import { useStore } from "@nanostores/react";
-import type { Publish } from "~/shared/pubsub";
import { css } from "@webstudio-is/design-system";
import { PlacementIndicator } from "@webstudio-is/design-system";
import {
@@ -34,11 +33,7 @@ const containerStyle = css({
},
});
-type CanvasToolsProps = {
- publish: Publish;
-};
-
-export const CanvasTools = ({ publish }: CanvasToolsProps) => {
+export const CanvasTools = () => {
// @todo try to setup cross-frame atoms to avoid this
useSubscribeDragAndDropState();
@@ -80,7 +75,7 @@ export const CanvasTools = ({ publish }: CanvasToolsProps) => {
<HoveredInstanceOutline />
<CollaborativeInstanceOutline />
</div>
- <TextToolbar publish={publish} />
+ <TextToolbar />
</>
)}
</div>
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx
index 6d049a4d59..f7a5666614 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar.tsx
@@ -17,23 +17,8 @@ import {
selectedInstanceSelectorStore,
} from "~/shared/nano-states";
import { type TextToolbarState, textToolbarStore } from "~/shared/nano-states";
-import type { Publish } from "~/shared/pubsub";
import { scaleStore } from "~/builder/shared/nano-states";
-
-type Format =
- | "bold"
- | "italic"
- | "superscript"
- | "subscript"
- | "link"
- | "span"
- | "clear";
-
-declare module "~/shared/pubsub" {
- export interface PubsubMap {
- formatTextToolbar: Format;
- }
-}
+import { emitCommand } from "~/builder/shared/commands";
const getRectForRelativeRect = (
parent: DOMRect,
@@ -74,11 +59,10 @@ const $isWithinLink = computed(
type ToolbarProps = {
state: TextToolbarState;
- onToggle: (value: Format) => void;
scale: number;
};
-const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
+const Toolbar = ({ state, scale }: ToolbarProps) => {
const isWithinLink = useStore($isWithinLink);
const rootRef = useRef<HTMLDivElement | null>(null);
@@ -141,7 +125,7 @@ const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
<IconButton
aria-label="Clear styles"
disabled={isCleared}
- onClick={() => onToggle("clear")}
+ onClick={() => emitCommand("formatClear")}
>
<CrossSmallIcon />
</IconButton>
@@ -151,7 +135,7 @@ const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
<IconButton
aria-label="Bold"
variant={state.isBold ? "local" : "default"}
- onClick={() => onToggle("bold")}
+ onClick={() => emitCommand("formatBold")}
>
<BoldIcon />
</IconButton>
@@ -161,7 +145,7 @@ const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
<IconButton
aria-label="Italic"
variant={state.isItalic ? "local" : "default"}
- onClick={() => onToggle("italic")}
+ onClick={() => emitCommand("formatItalic")}
>
<TextItalicIcon />
</IconButton>
@@ -171,7 +155,7 @@ const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
<IconButton
aria-label="Superscript"
variant={state.isSuperscript ? "local" : "default"}
- onClick={() => onToggle("superscript")}
+ onClick={() => emitCommand("formatSuperscript")}
>
<SuperscriptIcon />
</IconButton>
@@ -181,7 +165,7 @@ const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
<IconButton
aria-label="Subscript"
variant={state.isSubscript ? "local" : "default"}
- onClick={() => onToggle("subscript")}
+ onClick={() => emitCommand("formatSubscript")}
>
<SubscriptIcon />
</IconButton>
@@ -192,7 +176,7 @@ const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
<IconButton
aria-label="Inline link"
variant={state.isLink ? "local" : "default"}
- onClick={() => onToggle("link")}
+ onClick={() => emitCommand("formatLink")}
>
<LinkIcon />
</IconButton>
@@ -203,7 +187,7 @@ const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
<IconButton
aria-label="Wrap with span"
variant={state.isSpan ? "local" : "default"}
- onClick={() => onToggle("span")}
+ onClick={() => emitCommand("formatSpan")}
>
<PaintBrushIcon />
</IconButton>
@@ -212,11 +196,7 @@ const Toolbar = ({ state, onToggle, scale }: ToolbarProps) => {
);
};
-type TextToolbarProps = {
- publish: Publish;
-};
-
-export const TextToolbar = ({ publish }: TextToolbarProps) => {
+export const TextToolbar = () => {
const textToolbar = useStore(textToolbarStore);
const scale = useStore(scaleStore);
const selectedInstanceSelector = useStore(selectedInstanceSelectorStore);
@@ -228,16 +208,5 @@ export const TextToolbar = ({ publish }: TextToolbarProps) => {
return null;
}
- return (
- <Toolbar
- state={textToolbar}
- scale={scale}
- onToggle={(value) =>
- publish({
- type: "formatTextToolbar",
- payload: value,
- })
- }
- />
- );
+ return <Toolbar state={textToolbar} scale={scale} />;
};
diff --git a/apps/builder/app/builder/features/workspace/workspace.tsx b/apps/builder/app/builder/features/workspace/workspace.tsx
index d18c97bbdd..b06937abde 100644
--- a/apps/builder/app/builder/features/workspace/workspace.tsx
+++ b/apps/builder/app/builder/features/workspace/workspace.tsx
@@ -5,7 +5,6 @@ import {
useCanvasWidth,
workspaceRectStore,
} from "~/builder/shared/nano-states";
-import type { Publish } from "~/shared/pubsub";
import {
selectedInstanceSelectorStore,
selectedStyleSourceSelectorStore,
@@ -142,14 +141,12 @@ const useOutlineStyle = (
type WorkspaceProps = {
children: JSX.Element;
onTransitionEnd: () => void;
- publish: Publish;
initialBreakpoints: [Breakpoint["id"], Breakpoint][];
};
export const Workspace = ({
children,
onTransitionEnd,
- publish,
initialBreakpoints,
}: WorkspaceProps) => {
const canvasStyle = useCanvasStyle(initialBreakpoints);
@@ -176,7 +173,7 @@ export const Workspace = ({
{children}
</div>
<div className={canvasContainerStyle()} style={outlineStyle}>
- <CanvasTools publish={publish} />
+ <CanvasTools />
</div>
<Toaster />
</div>
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index 221c8cf9cc..8cb4fdf434 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -69,7 +69,16 @@ const deleteSelectedInstance = () => {
export const { emitCommand, subscribeCommands } = createCommandsEmitter({
source: "builder",
- externalCommands: ["editInstanceText"],
+ externalCommands: [
+ "editInstanceText",
+ "formatBold",
+ "formatItalic",
+ "formatSuperscript",
+ "formatSubscript",
+ "formatLink",
+ "formatSpan",
+ "formatClear",
+ ],
commands: [
// ui
diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
index 9531287432..750b5ff265 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
@@ -1,28 +1,19 @@
-import { useRef } from "react";
+import { useEffect, useRef } from "react";
import { useStore } from "@nanostores/react";
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
-import type { ComponentStory, ComponentMeta } from "@storybook/react";
+import type { StoryFn, Meta } from "@storybook/react";
import { action } from "@storybook/addon-actions";
import { Box } from "@webstudio-is/design-system";
import { theme } from "@webstudio-is/design-system";
import type { Instance, Instances } from "@webstudio-is/sdk";
-import { publish } from "~/shared/pubsub";
import { textToolbarStore } from "~/shared/nano-states";
import { TextEditor } from "./text-editor";
+import { emitCommand, subscribeCommands } from "~/canvas/shared/commands";
export default {
component: TextEditor,
title: "Text Editor 2",
-} as ComponentMeta<typeof TextEditor>;
-
-type Format =
- | "bold"
- | "italic"
- | "superscript"
- | "subscript"
- | "link"
- | "span"
- | "clear";
+} satisfies Meta<typeof TextEditor>;
const createInstancePair = (
id: Instance["id"],
@@ -55,13 +46,11 @@ const instances: Instances = new Map([
createInstancePair("5", "Bold", [{ type: "text", value: " subtext" }]),
]);
-export const Basic: ComponentStory<typeof TextEditor> = ({ onChange }) => {
+export const Basic: StoryFn<typeof TextEditor> = ({ onChange }) => {
const state = useStore(textToolbarStore);
const ref = useRef<null | HTMLDivElement>(null);
- const setFormat = (type: Format) => {
- publish({ type: "formatTextToolbar", payload: type });
- };
+ useEffect(subscribeCommands, []);
return (
<div>
@@ -70,7 +59,7 @@ export const Basic: ComponentStory<typeof TextEditor> = ({ onChange }) => {
style={{ fontWeight: state?.isBold ? "bold" : "normal" }}
onClick={(event) => {
event.preventDefault();
- setFormat("bold");
+ emitCommand("formatBold");
}}
>
Bold
@@ -78,42 +67,42 @@ export const Basic: ComponentStory<typeof TextEditor> = ({ onChange }) => {
<button
disabled={state == null}
style={{ fontWeight: state?.isItalic ? "bold" : "normal" }}
- onClick={() => setFormat("italic")}
+ onClick={() => emitCommand("formatItalic")}
>
Italic
</button>
<button
disabled={state == null}
style={{ fontWeight: state?.isSuperscript ? "bold" : "normal" }}
- onClick={() => setFormat("superscript")}
+ onClick={() => emitCommand("formatSuperscript")}
>
Superscript
</button>
<button
disabled={state == null}
style={{ fontWeight: state?.isSubscript ? "bold" : "normal" }}
- onClick={() => setFormat("subscript")}
+ onClick={() => emitCommand("formatSubscript")}
>
Subscript
</button>
<button
disabled={state == null}
style={{ fontWeight: state?.isLink ? "bold" : "normal" }}
- onClick={() => setFormat("link")}
+ onClick={() => emitCommand("formatLink")}
>
Link
</button>
<button
disabled={state == null}
style={{ fontWeight: state?.isSpan ? "bold" : "normal" }}
- onClick={() => setFormat("span")}
+ onClick={() => emitCommand("formatSpan")}
>
Span
</button>
<button
disabled={state == null}
style={{ fontWeight: "normal" }}
- onClick={() => setFormat("clear")}
+ onClick={() => emitCommand("formatClear")}
>
Clear
</button>
diff --git a/apps/builder/app/canvas/features/text-editor/toolbar-connector.tsx b/apps/builder/app/canvas/features/text-editor/toolbar-connector.tsx
index 25d2fc90bf..9f4815015b 100644
--- a/apps/builder/app/canvas/features/text-editor/toolbar-connector.tsx
+++ b/apps/builder/app/canvas/features/text-editor/toolbar-connector.tsx
@@ -2,21 +2,32 @@ import { useCallback, useEffect, useRef, useState } from "react";
import {
type RangeSelection,
type TextNode,
+ type LexicalEditor,
$getSelection,
$isRangeSelection,
$isTextNode,
- FORMAT_TEXT_COMMAND,
SELECTION_CHANGE_COMMAND,
COMMAND_PRIORITY_LOW,
+ type TextFormatType,
+ createCommand,
+ COMMAND_PRIORITY_EDITOR,
} from "lexical";
import { $getNearestNodeOfType } from "@lexical/utils";
import { $patchStyleText } from "@lexical/selection";
-import { LinkNode, TOGGLE_LINK_COMMAND } from "@lexical/link";
+import { LinkNode } from "@lexical/link";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
-import { useSubscribe } from "~/shared/pubsub";
import { textToolbarStore } from "~/shared/nano-states";
import { subscribeScrollState } from "~/canvas/shared/scroll-state";
+let activeEditor: undefined | LexicalEditor;
+
+export const getActiveEditor = () => {
+ return activeEditor;
+};
+
+export const TOGGLE_SPAN_COMMAND = createCommand<void>();
+export const CLEAR_FORMAT_COMMAND = createCommand<void>();
+
const spanTriggerName = "--style-node-trigger";
export const $isSpanNode = (node: TextNode) => {
@@ -82,6 +93,18 @@ const $isSelectedLink = (selection: RangeSelection) => {
return $getNearestNodeOfType(selectedNode, LinkNode) != null;
};
+export const hasSelectionFormat = (formatType: TextFormatType | "link") => {
+ return activeEditor?.getEditorState().read(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ if (formatType === "link") {
+ return $isSelectedLink(selection);
+ }
+ return selection.hasFormat(formatType);
+ }
+ });
+};
+
const getSelectionClienRect = () => {
const nativeSelection = window.getSelection();
if (nativeSelection === null) {
@@ -199,79 +222,48 @@ const ToolbarConnectorPluginInternal = ({
});
}, [editor, updateToolbar]);
- // dispatch commands sent from toolbar
- useSubscribe("formatTextToolbar", (type) => {
- let isSuperscript = false;
- let isSubscript = false;
- editor.getEditorState().read(() => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- isSuperscript = selection.hasFormat("superscript");
- isSubscript = selection.hasFormat("subscript");
- }
- });
-
- if (type === "bold") {
- editor.dispatchCommand(FORMAT_TEXT_COMMAND, "bold");
- }
- if (type === "italic") {
- editor.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");
- }
- if (type === "superscript") {
- editor.dispatchCommand(FORMAT_TEXT_COMMAND, "superscript");
- // remove subscript if superscript is added
- if (isSubscript) {
- editor.dispatchCommand(FORMAT_TEXT_COMMAND, "subscript");
- }
- }
- if (type === "subscript") {
- editor.dispatchCommand(FORMAT_TEXT_COMMAND, "subscript");
- // remove superscript if subscript is added
- if (isSuperscript) {
- editor.dispatchCommand(FORMAT_TEXT_COMMAND, "superscript");
- }
- }
- if (type === "link") {
- const editorState = editor.getEditorState();
- let isLink = false;
- editorState.read(() => {
- const selection = $getSelection();
- isLink = $isRangeSelection(selection) && $isSelectedLink(selection);
- });
- if (isLink) {
- editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
- } else {
- editor.dispatchCommand(TOGGLE_LINK_COMMAND, "https://");
- }
- }
- if (type === "span") {
- editor.update(
- () => {
- $toggleSpan();
- },
- {
- onUpdate: () => {
- const editorState = editor.getEditorState();
- editorState.read(() => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- const spans = $getSpanNodes(selection);
- if (spans.length !== 0) {
- const [node] = spans;
- onSelectNode(node.getKey());
- }
- }
- });
+ useEffect(() => {
+ return editor.registerCommand(
+ TOGGLE_SPAN_COMMAND,
+ () => {
+ editor.update(
+ () => {
+ $toggleSpan();
},
- }
- );
- }
- if (type === "clear") {
- editor.update(() => {
- $clearText();
- });
- }
- });
+ {
+ onUpdate: () => {
+ const editorState = editor.getEditorState();
+ editorState.read(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ const spans = $getSpanNodes(selection);
+ if (spans.length !== 0) {
+ const [node] = spans;
+ onSelectNode(node.getKey());
+ }
+ }
+ });
+ },
+ }
+ );
+ return true;
+ },
+ COMMAND_PRIORITY_EDITOR
+ );
+ }, [editor, onSelectNode]);
+
+ useEffect(() => {
+ return editor.registerCommand(
+ CLEAR_FORMAT_COMMAND,
+ () => {
+ editor.update(() => {
+ $clearText();
+ });
+ return true;
+ },
+ COMMAND_PRIORITY_EDITOR
+ );
+ }, [editor]);
return null;
};
@@ -296,6 +288,8 @@ export const ToolbarConnectorPlugin = ({
}
setHasRootElement(true);
+
+ activeEditor = editor;
}, [editor]);
if (hasRootElement === false) {
diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.ts
index d86f291a26..f223eba320 100644
--- a/apps/builder/app/canvas/shared/commands.ts
+++ b/apps/builder/app/canvas/shared/commands.ts
@@ -1,3 +1,5 @@
+import { FORMAT_TEXT_COMMAND } from "lexical";
+import { TOGGLE_LINK_COMMAND } from "@lexical/link";
import { createCommandsEmitter } from "~/shared/commands-emitter";
import { getElementByInstanceSelector } from "~/shared/dom-utils";
import { findClosestEditableInstanceSelector } from "~/shared/instance-utils";
@@ -8,6 +10,12 @@ import {
selectedStyleSourceSelectorStore,
textEditingInstanceSelectorStore,
} from "~/shared/nano-states";
+import {
+ CLEAR_FORMAT_COMMAND,
+ TOGGLE_SPAN_COMMAND,
+ getActiveEditor,
+ hasSelectionFormat,
+} from "../features/text-editor/toolbar-connector";
export const { emitCommand, subscribeCommands } = createCommandsEmitter({
source: "canvas",
@@ -64,5 +72,67 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
selectedStyleSourceSelectorStore.set(undefined);
},
},
+
+ {
+ name: "formatBold",
+ handler: () => {
+ const editor = getActiveEditor();
+ editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "bold");
+ },
+ },
+ {
+ name: "formatItalic",
+ handler: () => {
+ const editor = getActiveEditor();
+ editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");
+ },
+ },
+ {
+ name: "formatSuperscript",
+ handler: () => {
+ const editor = getActiveEditor();
+ editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "superscript");
+ // remove subscript if superscript is added
+ if (hasSelectionFormat("subscript")) {
+ editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "subscript");
+ }
+ },
+ },
+ {
+ name: "formatSubscript",
+ handler: () => {
+ const editor = getActiveEditor();
+ editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "subscript");
+ // remove superscript if subscript is added
+ if (hasSelectionFormat("superscript")) {
+ editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "superscript");
+ }
+ },
+ },
+ {
+ name: "formatLink",
+ handler: () => {
+ const editor = getActiveEditor();
+ if (hasSelectionFormat("link")) {
+ editor?.dispatchCommand(TOGGLE_LINK_COMMAND, null);
+ } else {
+ editor?.dispatchCommand(TOGGLE_LINK_COMMAND, "https://");
+ }
+ },
+ },
+ {
+ name: "formatSpan",
+ handler: () => {
+ const editor = getActiveEditor();
+ editor?.dispatchCommand(TOGGLE_SPAN_COMMAND, undefined);
+ },
+ },
+ {
+ name: "formatClear",
+ handler: () => {
+ const editor = getActiveEditor();
+ editor?.dispatchCommand(CLEAR_FORMAT_COMMAND, undefined);
+ },
+ },
],
});