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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
refactor: add commands emitter (#2389)
Bogdan Chadkin743d2f184258
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 6f7b9ef07a..3d29600adf 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -2,7 +2,7 @@ import { useCallback, useEffect } from "react";import { useStore } from "@nanostores/react";import { useUnmount } from "react-use";import { TooltipProvider } from "@radix-ui/react-tooltip";-import { type Publish, usePublish } from "~/shared/pubsub";+import { type Publish, usePublish, $publisher } from "~/shared/pubsub";import type { Asset } from "@webstudio-is/sdk";import type { Build } from "@webstudio-is/project-build";import type { Project } from "@webstudio-is/project";@@ -45,6 +45,7 @@ import { useCopyPaste } from "~/shared/copy-paste";import { BlockingAlerts } from "./features/blocking-alerts";import { useSyncPageUrl } from "~/shared/pages";import { useMount } from "~/shared/hook-utils/use-mount";+import { subscribeCommands } from "~/builder/shared/commands";registerContainers();@@ -253,6 +254,8 @@ export const Builder = ({stylesStore.set(new Map(build.styles));});+ useEffect(subscribeCommands, []);+useUnmount(() => {pagesStore.set(undefined);});@@ -260,6 +263,10 @@ export const Builder = ({useSyncPageUrl();const [publish, publishRef] = usePublish();+ useEffect(() => {+ $publisher.set({ publish });+ }, [publish]);+useBuilderStore(publish);useSyncServer({buildId: build.id,diff --git a/apps/builder/app/builder/features/topbar/menu/menu.tsx b/apps/builder/app/builder/features/topbar/menu/menu.tsxindex 77a3457554..2f761d4f66 100644--- a/apps/builder/app/builder/features/topbar/menu/menu.tsx+++ b/apps/builder/app/builder/features/topbar/menu/menu.tsx@@ -29,8 +29,9 @@ import {} from "~/shared/theme";import { useClientSettings } from "~/builder/shared/client-settings";import { dashboardPath } from "~/shared/router-utils";-import { $isPreviewMode, $authPermit } from "~/shared/nano-states";+import { $authPermit } from "~/shared/nano-states";import { deleteSelectedInstance } from "~/shared/instance-utils";+import { emitCommand } from "~/builder/shared/commands";import { MenuButton } from "./menu-button";const ThemeMenuItem = () => {@@ -98,7 +99,6 @@ export const Menu = ({ publish }: MenuProps) => {const navigate = useNavigate();const [, setIsShareOpen] = useIsShareDialogOpen();const [, setIsPublishOpen] = useIsPublishDialogOpen();- const isPreviewMode = useStore($isPreviewMode);const authPermit = useStore($authPermit);const isPublishEnabled = authPermit === "own" || authPermit === "admin";@@ -184,11 +184,7 @@ export const Menu = ({ publish }: MenuProps) => {<DropdownMenuSeparator /><ThemeMenuItem /><ViewMenuItem />- <DropdownMenuItem- onSelect={() => {- $isPreviewMode.set(isPreviewMode === false);- }}- >+ <DropdownMenuItem onSelect={() => emitCommand("togglePreview")}>Preview<DropdownMenuItemRightSlot><ShortcutHint value={["cmd", "shift", "p"]} />diff --git a/apps/builder/app/builder/features/topbar/preview.tsx b/apps/builder/app/builder/features/topbar/preview.tsxindex c95a7816af..6ae3575eae 100644--- a/apps/builder/app/builder/features/topbar/preview.tsx+++ b/apps/builder/app/builder/features/topbar/preview.tsx@@ -2,6 +2,7 @@ import { useStore } from "@nanostores/react";import { PlayIcon } from "@webstudio-is/icons";import { ToolbarToggleItem } from "@webstudio-is/design-system";import { $isPreviewMode } from "~/shared/nano-states";+import { emitCommand } from "~/builder/shared/commands";export const PreviewButton = () => {const isPreviewMode = useStore($isPreviewMode);@@ -12,7 +13,7 @@ export const PreviewButton = () => {aria-label="Toggle Preview"variant="preview"data-state={isPreviewMode ? "on" : "off"}- onClick={() => $isPreviewMode.set(isPreviewMode === false)}+ onClick={() => emitCommand("togglePreview")}tabIndex={0}><PlayIcon />diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsnew file mode 100644index 0000000000..c7da351c09--- /dev/null+++ b/apps/builder/app/builder/shared/commands.ts@@ -0,0 +1,15 @@+import { createCommandsEmitter } from "~/shared/commands-emitter";+import { $isPreviewMode } from "~/shared/nano-states";++export const { emitCommand, subscribeCommands } = createCommandsEmitter({+ source: "builder",+ commands: [+ {+ name: "togglePreview",+ defaultHotkeys: ["meta+shift+p", "ctrl+shift+p"],+ handler: () => {+ $isPreviewMode.set($isPreviewMode.get() === false);+ },+ },+ ],+});diff --git a/apps/builder/app/canvas/canvas-shortcuts.ts b/apps/builder/app/canvas/canvas-shortcuts.tsindex 97dc187665..87856ae74e 100644--- a/apps/builder/app/canvas/canvas-shortcuts.ts+++ b/apps/builder/app/canvas/canvas-shortcuts.ts@@ -1,7 +1,6 @@import { useHotkeys } from "react-hotkeys-hook";import { shortcuts, instanceTreeShortcuts, options } from "~/shared/shortcuts";import { publish, useSubscribe } from "~/shared/pubsub";-import { $isPreviewMode } from "~/shared/nano-states";import { enterEditingMode, escapeSelection } from "~/shared/instance-utils";declare module "~/shared/pubsub" {@@ -11,10 +10,6 @@ declare module "~/shared/pubsub" {}}-const togglePreviewMode = () => {- $isPreviewMode.set(!$isPreviewMode.get());-};-const publishOpenBreakpointsMenu = () => {publish({ type: "openBreakpointsMenu" });};@@ -25,7 +20,6 @@ const publishCancelCurrentDrag = () => {export const useCanvasShortcuts = () => {const shortcutHandlerMap = {- preview: togglePreviewMode,breakpointsMenu: publishOpenBreakpointsMenu,esc: publishCancelCurrentDrag,enter: enterEditingMode,@@ -34,8 +28,6 @@ export const useCanvasShortcuts = () => {unknown>;- useHotkeys(shortcuts.preview, shortcutHandlerMap.preview, options, []);-useHotkeys(shortcuts.breakpointsMenu,shortcutHandlerMap.breakpointsMenu,diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 4506d347aa..38e0cb4fab 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -20,7 +20,7 @@ import * as radixComponents from "@webstudio-is/sdk-components-react-radix";import * as radixComponentMetas from "@webstudio-is/sdk-components-react-radix/metas";import * as radixComponentPropsMetas from "@webstudio-is/sdk-components-react-radix/props";import { hooks as radixComponentHooks } from "@webstudio-is/sdk-components-react-radix/hooks";-import { publish } from "~/shared/pubsub";+import { $publisher, publish } from "~/shared/pubsub";import {handshakenStore,registerContainers,@@ -56,6 +56,7 @@ import { useMount } from "~/shared/hook-utils/use-mount";import { useSelectedInstance } from "./instance-selected-react";import { subscribeInterceptedEvents } from "./interceptor";import type { ImageLoader } from "@webstudio-is/image";+import { subscribeCommands } from "~/canvas/shared/commands";registerContainers();@@ -197,6 +198,12 @@ export const Canvas = ({useEffect(subscribeComponentHooks, []);+ useEffect(subscribeCommands, []);++ useEffect(() => {+ $publisher.set({ publish });+ }, []);+// e.g. toggling preview is still needed in both modesuseCanvasShortcuts();useSharedShortcuts({ source: "canvas" });diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.tsnew file mode 100644index 0000000000..467651fc18--- /dev/null+++ b/apps/builder/app/canvas/shared/commands.ts@@ -0,0 +1,6 @@+import { createCommandsEmitter } from "~/shared/commands-emitter";++export const { emitCommand, subscribeCommands } = createCommandsEmitter({+ source: "canvas",+ commands: [],+});diff --git a/apps/builder/app/shared/commands-emitter.ts b/apps/builder/app/shared/commands-emitter.tsnew file mode 100644index 0000000000..2db760654a--- /dev/null+++ b/apps/builder/app/shared/commands-emitter.ts@@ -0,0 +1,111 @@+import { isHotkeyPressed } from "react-hotkeys-hook";+import { atom, onMount } from "nanostores";+import { $publisher, subscribe } from "~/shared/pubsub";++type CommandMeta<CommandName extends string> = {+ // @todo category, description+ name: CommandName;+ // default because hotkeys can be customized from ui+ defaultHotkeys?: string[];+};++type CommandHandler = () => void;++/**+ * Command can be registered by builder, canvas or plugin+ */+type Command<CommandName extends string> = CommandMeta<CommandName> & {+ /**+ * Command handler accepting source where was triggered+ * which is builder, canvas or plugin name+ */+ handler: CommandHandler;+};++/*+ * expose command metas to synchronize between builder, canvas and plugins+ */+export const $commandMetas = atom(new Map<string, CommandMeta<string>>());++export const createCommandsEmitter = <CommandName extends string>({+ source,+ commands,+}: {+ source: string;+ // type only input to describe available commands from builder or other plugins+ externalCommands?: CommandName[];+ commands: Command<CommandName>[];+}) => {+ const commandMetas = new Map($commandMetas.get());+ const commandHandlers = new Map<string, CommandHandler>();+ for (const { handler, ...meta } of commands) {+ commandMetas.set(meta.name, meta);+ commandHandlers.set(meta.name, handler);+ }++ if (commands.length > 0) {+ onMount($commandMetas, () => {+ // listener from sync-stores is called after onMount callback+ // schedule store.set to the next tick+ // so store.listen is executed after store.set below+ Promise.resolve().then(() => {+ // @todo use patches to avoid race when both builder and canvas send commands+ $commandMetas.set(commandMetas);+ });+ });+ }++ const emitCommand = (name: CommandName) => {+ const { publish } = $publisher.get();+ publish({+ type: "command",+ payload: {+ source,+ name,+ },+ });+ };++ /**+ * subscribe to keydown in every app and emit command globally+ * actual handlers are executed in app where defined+ */+ const subscribeCommands = () => {+ const unsubscribePubsub = subscribe("command", ({ name }) => {+ commandHandlers.get(name)?.();+ });+ const handleKeyDown = (event: KeyboardEvent) => {+ const commandMetas = $commandMetas.get();+ let emitted = false;+ for (const commandMeta of commandMetas.values()) {+ if (commandMeta.defaultHotkeys === undefined) {+ continue;+ }+ if (+ commandMeta.defaultHotkeys.some((hotkey) =>+ isHotkeyPressed(hotkey.split("+"))+ ) === false+ ) {+ continue;+ }+ emitted = true;+ emitCommand(commandMeta.name as CommandName);+ }+ // command can redefine browser hotkeys+ // always prevent to avoid unexpected behavior+ if (emitted) {+ event.preventDefault();+ }+ };+ document.addEventListener("keydown", handleKeyDown);+ return () => {+ unsubscribePubsub();+ document.removeEventListener("keydown", handleKeyDown);+ };+ };++ return {+ emitCommand,+ subscribeCommands,+ };+};diff --git a/apps/builder/app/shared/pubsub/create.ts b/apps/builder/app/shared/pubsub/create.tsindex ebb51b8410..1cf0c4eac9 100644--- a/apps/builder/app/shared/pubsub/create.ts+++ b/apps/builder/app/shared/pubsub/create.ts@@ -4,8 +4,8 @@ import { batchUpdate } from "./raf-queue";export const createPubsub = <PublishMap>() => {type Action<Type extends keyof PublishMap> =- undefined extends PublishMap[Type]- ? { type: Type; payload?: PublishMap[Type] }+ PublishMap[Type] extends undefined+ ? { type: Type; payload?: undefined }: { type: Type; payload: PublishMap[Type] };// eslint-disable-next-line @typescript-eslint/no-explicit-anydiff --git a/apps/builder/app/shared/pubsub/index.ts b/apps/builder/app/shared/pubsub/index.tsindex 14096deea7..fc37e9e049 100644--- a/apps/builder/app/shared/pubsub/index.ts+++ b/apps/builder/app/shared/pubsub/index.ts@@ -1,10 +1,20 @@+import { atom } from "nanostores";import { createPubsub } from "./create";-// this interface is meant to be augmented by the user-// eslint-disable-next-line @typescript-eslint/no-empty-interface-export interface PubsubMap {}+export interface PubsubMap {+ command: {+ source: string;+ name: string;+ };+}export const { publish, usePublish, useSubscribe, subscribe } =createPubsub<PubsubMap>();export type Publish = typeof publish;export type UsePublish = typeof usePublish;++export const $publisher = atom<{+ publish: Publish;+}>({+ publish: () => {},+});diff --git a/apps/builder/app/shared/shortcuts/shortcuts.ts b/apps/builder/app/shared/shortcuts/shortcuts.tsindex e93a7379f9..8cfec7c4ee 100644--- a/apps/builder/app/shared/shortcuts/shortcuts.ts+++ b/apps/builder/app/shared/shortcuts/shortcuts.ts@@ -10,7 +10,6 @@ import { onCopy, onPaste } from "../copy-paste/plugin-instance";export const shortcuts = {esc: "esc",- preview: "meta+shift+p, ctrl+shift+p",breakpointsMenu: "meta+b, ctrl+b",} as const;diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex 7705a39fb4..edc7ae4123 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -30,6 +30,7 @@ import {synchronizedComponentsMetaStores,dataSourceVariablesStore,} from "~/shared/nano-states";+import { $commandMetas } from "~/shared/commands-emitter";enableMapSet();@@ -72,6 +73,7 @@ export const registerContainers = () => {store.register("dataSources", dataSourcesStore);store.register("assets", assetsStore);// synchronize whole states+ clientStores.set("commandMetas", $commandMetas);clientStores.set("project", projectStore);clientStores.set("dataSourceVariables", dataSourceVariablesStore);clientStores.set("selectedPageId", selectedPageIdStore);@@ -241,7 +243,7 @@ const handshakeAndSyncStores = (if (destinationReady) {return publish(action);}- actions.push(action);+ actions.push({ payload: undefined, ...action });};const unsubscribe = sync(publishAction);