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: Transform Plus button to Minus in case of Alt button is pressed (#4490)

Ivan Starkov71e0be83634d
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index 284c844251..dd28d6a8a6 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState, type ReactNode } from "react";
+import { useEffect, useState, type ReactNode } from "react";
import { useStore } from "@nanostores/react";
import { TooltipProvider } from "@radix-ui/react-tooltip";
import { usePublish, $publisher } from "~/shared/pubsub";
@@ -32,10 +32,10 @@ import {
$authTokenPermissions,
$publisherHost,
$imageLoader,
- $textEditingInstanceSelector,
$isDesignMode,
$isContentMode,
$userPlanFeatures,
+ subscribeModifierKeys,
} from "~/shared/nano-states";
import { $settings, type Settings } from "./shared/client-settings";
import { builderUrl, getCanvasUrl } from "~/shared/router-utils";
@@ -56,7 +56,6 @@ import {
import { CloneProjectDialog } from "~/shared/clone-project";
import type { TokenPermissions } from "@webstudio-is/authorization-token";
import { useToastErrors } from "~/shared/error/toast-error";
-import { canvasApi } from "~/shared/canvas-api";
import { loadBuilderData, setBuilderData } from "~/shared/builder-data";
import { initBuilderApi } from "~/shared/builder-api";
import { updateWebstudioData } from "~/shared/instance-utils";
@@ -68,6 +67,7 @@ import {
initCopyPaste,
initCopyPasteForContentEditMode,
} from "~/shared/copy-paste/init-copy-paste";
+import { useInertHandlers } from "./shared/inert-handlers";
registerContainers();
@@ -320,10 +320,12 @@ export const Builder = ({
// @todo we need to forward the events from canvas to builder and avoid importing this
// in both places
initCopyPaste(abortController);
+ subscribeModifierKeys({ signal: abortController.signal });
}
if (isContentMode) {
initCopyPasteForContentEditMode(abortController);
+ subscribeModifierKeys({ signal: abortController.signal });
}
return () => {
@@ -344,57 +346,15 @@ export const Builder = ({
const canvasUrl = getCanvasUrl();
- /**
- * Prevents Lexical text editor from stealing focus during rendering.
- * Sets the inert attribute on the canvas body element and disables the text editor.
- *
- * This must be done synchronously to avoid the following issue:
- *
- * 1. Text editor is in edit state.
- * 2. User focuses on the builder (e.g., clicks any input).
- * 3. The text editor blur event triggers, causing a rerender on data change (data saved in onBlur).
- * 4. Text editor rerenders, stealing focus from the builder.
- * 5. Inert attribute is set asynchronously, but focus is already lost.
- *
- * Synchronous focusing and setInert prevent the text editor from focusing on render.
- * This cannot be handled inside the canvas because the text editor toolbar is in the builder and focus events in the canvas should be ignored.
- *
- * Use onPointerDown instead of onFocus because Radix focus lock triggers on text edit blur
- * before the focusin event when editing text inside a Radix dialog.
- */
- const handlePointerDown = useCallback((event: React.PointerEvent) => {
- // Ignore toolbar focus events. See the onFocus handler in text-toolbar.tsx
- if (false === event.defaultPrevented) {
- canvasApi.setInert();
- $textEditingInstanceSelector.set(undefined);
- }
- }, []);
-
- /**
- * Prevent Radix from stealing focus during editing in the style sources
- * For example, when the user select or create new style source item inside a dialog.
- */
- const handleKeyDown = useCallback((event: React.KeyboardEvent) => {
- if (event.target instanceof HTMLInputElement) {
- canvasApi.setInert();
- }
- }, []);
-
- /**
- * Prevent Radix from stealing focus during editing in the settings panel.
- * For example, when the user modifies the text content of an H1 element inside a dialog.
- */
- const handleInput = useCallback(() => {
- canvasApi.setInert();
- }, []);
+ const inertHandlers = useInertHandlers();
return (
<TooltipProvider>
<div
style={{ display: "contents" }}
- onPointerDown={handlePointerDown}
- onInput={handleInput}
- onKeyDown={handleKeyDown}
+ onPointerDown={inertHandlers.onPointerDown}
+ onInput={inertHandlers.onInput}
+ onKeyDown={inertHandlers.onKeyDown}
>
<ChromeWrapper
isPreviewMode={isPreviewMode}
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 6d83efd969..cf92fcd7c2 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
@@ -19,7 +19,7 @@ import { ResizeHandles } from "./resize-handles";
import { MediaBadge } from "./media-badge";
import { applyScale } from "./outline";
import { $scale } from "~/builder/shared/nano-states";
-import { BlockChildHoveredInstanceOutline } from "./outline/editable-block-instance-outline";
+import { BlockChildHoveredInstanceOutline } from "./outline/block-instance-outline";
const containerStyle = css({
position: "absolute",
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx
new file mode 100644
index 0000000000..cc70718256
--- /dev/null
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx
@@ -0,0 +1,504 @@
+import { useStore } from "@nanostores/react";
+import {
+ $blockChildOutline,
+ $hoveredInstanceOutline,
+ $hoveredInstanceSelector,
+ $instances,
+ $isContentMode,
+ $modifierKeys,
+ $registeredComponentMetas,
+ type BlockChildOutline,
+} from "~/shared/nano-states";
+import {
+ Box,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuPortal,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ Flex,
+ theme,
+ IconButton,
+ Tooltip,
+ Kbd,
+ Text,
+ iconButtonSize,
+ Grid,
+ DropdownMenuSeparator,
+ menuItemCss,
+} from "@webstudio-is/design-system";
+import { Outline } from "./outline";
+import { applyScale } from "./apply-scale";
+import { $scale } from "~/builder/shared/nano-states";
+import { PlusIcon, TrashIcon } from "@webstudio-is/icons";
+import { BoxIcon } from "@webstudio-is/icons/svg";
+import { useRef, useState } from "react";
+import { isFeatureEnabled } from "@webstudio-is/feature-flags";
+import type { DroppableTarget, InstanceSelector } from "~/shared/tree-utils";
+import type { Instance, Instances } from "@webstudio-is/sdk";
+import {
+ blockComponent,
+ blockTemplateComponent,
+} from "@webstudio-is/react-sdk";
+import {
+ deleteInstanceMutable,
+ extractWebstudioFragment,
+ findAvailableDataSources,
+ getWebstudioData,
+ insertInstanceChildrenMutable,
+ insertWebstudioFragmentCopy,
+ updateWebstudioData,
+} from "~/shared/instance-utils";
+import { shallowEqual } from "shallow-equal";
+import { MetaIcon } from "~/builder/shared/meta-icon";
+import { skipInertHandlersAttribute } from "~/builder/shared/inert-handlers";
+
+export const findBlockSelector = (
+ anchor: InstanceSelector,
+ instances: Instances
+) => {
+ if (anchor === undefined) {
+ return;
+ }
+
+ if (anchor.length === 0) {
+ return;
+ }
+
+ let blockInstanceSelector: InstanceSelector | undefined = undefined;
+
+ for (let i = 0; i < anchor.length; ++i) {
+ const instanceId = anchor[i];
+
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ return;
+ }
+
+ if (instance.component === blockComponent) {
+ blockInstanceSelector = anchor.slice(i);
+ break;
+ }
+ }
+
+ if (blockInstanceSelector === undefined) {
+ return;
+ }
+
+ return blockInstanceSelector;
+};
+
+const findTemplates = (anchor: InstanceSelector, instances: Instances) => {
+ const blockInstanceSelector = findBlockSelector(anchor, instances);
+ if (blockInstanceSelector === undefined) {
+ return;
+ }
+
+ const blockInstance = instances.get(blockInstanceSelector[0]);
+
+ if (blockInstance === undefined) {
+ return;
+ }
+
+ const templateInstanceId = blockInstance.children.find(
+ (child) =>
+ child.type === "id" &&
+ instances.get(child.value)?.component === blockTemplateComponent
+ )?.value;
+
+ if (templateInstanceId === undefined) {
+ return;
+ }
+
+ const templateInstance = instances.get(templateInstanceId);
+
+ if (templateInstance === undefined) {
+ return;
+ }
+
+ const result: [instance: Instance, instanceSelector: InstanceSelector][] =
+ templateInstance.children
+ .filter((child) => child.type === "id")
+ .map((child) => child.value)
+ .map((childId) => instances.get(childId))
+ .filter((child) => child !== undefined)
+ .map((child) => [
+ child,
+ [child.id, templateInstanceId, ...blockInstanceSelector],
+ ]);
+
+ return result;
+};
+
+const getInsertionIndex = (
+ anchor: InstanceSelector,
+ instances: Instances,
+ insertBefore: boolean = false
+) => {
+ const blockSelector = findBlockSelector(anchor, instances);
+ if (blockSelector === undefined) {
+ return;
+ }
+
+ const insertAtInitialPosition = shallowEqual(blockSelector, anchor);
+
+ const blockInstance = instances.get(blockSelector[0]);
+
+ if (blockInstance === undefined) {
+ return;
+ }
+
+ const index = blockInstance.children.findIndex((child) => {
+ if (child.type !== "id") {
+ return false;
+ }
+
+ if (insertAtInitialPosition) {
+ return instances.get(child.value)?.component === blockTemplateComponent;
+ }
+
+ return child.value === anchor[0];
+ });
+
+ if (index === -1) {
+ return;
+ }
+
+ // Independent of insertBefore, we always insert after the Templates instance
+ if (insertAtInitialPosition) {
+ return index + 1;
+ }
+
+ return insertBefore ? index : index + 1;
+};
+
+const TemplatesMenu = ({
+ onOpenChange,
+ open,
+ children,
+ anchor,
+}: {
+ children: React.ReactNode;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ anchor: InstanceSelector;
+}) => {
+ const instances = useStore($instances);
+ const metas = useStore($registeredComponentMetas);
+ const modifierKeys = useStore($modifierKeys);
+
+ const blockInstanceSelector = findBlockSelector(anchor, instances);
+
+ if (blockInstanceSelector === undefined) {
+ return;
+ }
+
+ const blockInstance = instances.get(blockInstanceSelector[0]);
+
+ if (blockInstance === undefined) {
+ return;
+ }
+
+ // 1 child is Templates instance
+ const hasChildren = blockInstance.children.length > 1;
+
+ const templates = findTemplates(anchor, instances);
+
+ const menuItems = templates?.map(([template, templateSelector]) => ({
+ id: template.id,
+ icon: <MetaIcon icon={metas.get(template.component)?.icon ?? BoxIcon} />,
+ title: template.label ?? template.component,
+ value: templateSelector,
+ }));
+
+ return (
+ <DropdownMenu onOpenChange={onOpenChange} open={open} modal>
+ {children}
+ <DropdownMenuPortal>
+ <DropdownMenuContent
+ align="start"
+ sideOffset={4}
+ collisionPadding={16}
+ side="bottom"
+ loop
+ >
+ <DropdownMenuRadioGroup
+ onValueChange={(value) => {
+ const insertBefore = modifierKeys.altKey;
+
+ const templateSelector = JSON.parse(value) as InstanceSelector;
+ const fragment = extractWebstudioFragment(
+ getWebstudioData(),
+ templateSelector[0]
+ );
+
+ const parentSelector = findBlockSelector(anchor, instances);
+
+ if (parentSelector === undefined) {
+ return;
+ }
+
+ const position = getInsertionIndex(
+ anchor,
+ instances,
+ insertBefore
+ );
+
+ if (position === undefined) {
+ return;
+ }
+
+ const target: DroppableTarget = {
+ parentSelector,
+ position,
+ };
+
+ updateWebstudioData((data) => {
+ const { newInstanceIds } = insertWebstudioFragmentCopy({
+ data,
+ fragment,
+ availableDataSources: findAvailableDataSources(
+ data.dataSources,
+ data.instances,
+ target.parentSelector
+ ),
+ });
+ const newRootInstanceId = newInstanceIds.get(
+ fragment.instances[0].id
+ );
+ if (newRootInstanceId === undefined) {
+ return;
+ }
+ const children: Instance["children"] = [
+ { type: "id", value: newRootInstanceId },
+ ];
+ insertInstanceChildrenMutable(data, children, target);
+ });
+ }}
+ >
+ {menuItems?.map(({ icon, title, id, value }) => (
+ <DropdownMenuRadioItem
+ key={id}
+ value={JSON.stringify(value)}
+ {...{ [skipInertHandlersAttribute]: true }}
+ data-yyy
+ >
+ <Flex
+ css={{ py: theme.spacing[4], px: theme.spacing[5] }}
+ gap={2}
+ data-xxx
+ >
+ {icon}
+ <Box>{title}</Box>
+ </Flex>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+
+ <div className={menuItemCss({ hint: true })}>
+ <Grid css={{ width: theme.spacing[25] }}>
+ <Flex gap={1} css={{ display: hasChildren ? "none" : undefined }}>
+ <Kbd value={["click"]} />
+ <Text>to add first</Text>
+ </Flex>
+
+ <Flex
+ gap={1}
+ css={{
+ order: modifierKeys.altKey ? 2 : 0,
+ display: hasChildren ? undefined : "none",
+ }}
+ >
+ <Kbd value={["click"]} />
+ <Text>to add after</Text>
+ </Flex>
+ <Flex
+ gap={1}
+ css={{ order: 1, display: hasChildren ? undefined : "none" }}
+ >
+ <Kbd value={["option", "click"]} /> <Text>to add before</Text>
+ </Flex>
+ </Grid>
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenu>
+ );
+};
+
+const distanceToButton = theme.spacing[4];
+
+/**
+ * The button's grace area must slightly overlap with the outline rectangle.
+ * This is because the outline rectangle has `pointer-events: none`, and some UI elements, like resize handles, are placed above it.
+ * The overlap ensures the grace area starts earlier to account for this.
+ */
+const graceAreaOverlap = theme.spacing[4];
+
+export const BlockChildHoveredInstanceOutline = () => {
+ const blockChildOutline = useStore($blockChildOutline);
+ const scale = useStore($scale);
+ const isContentMode = useStore($isContentMode);
+ const modifierKeys = useStore($modifierKeys);
+ const instances = useStore($instances);
+
+ const timeoutRef = useRef<undefined | ReturnType<typeof setTimeout>>(
+ undefined
+ );
+ const [buttonOutline, setButtonOutline] = useState<
+ undefined | BlockChildOutline
+ >(undefined);
+
+ const outline = blockChildOutline ?? buttonOutline;
+
+ const [isMenuOpen, setIsMenuOpen] = useState(false);
+
+ if (isFeatureEnabled("contentEditableMode") === false) {
+ return;
+ }
+
+ if (!isContentMode) {
+ return;
+ }
+
+ if (outline === undefined) {
+ return;
+ }
+
+ const blockInstanceSelector = findBlockSelector(outline.selector, instances);
+
+ if (blockInstanceSelector === undefined) {
+ return;
+ }
+
+ const blockInstance = instances.get(blockInstanceSelector[0]);
+
+ if (blockInstance === undefined) {
+ return;
+ }
+
+ const templates = findTemplates(outline.selector, instances);
+
+ if (templates === undefined) {
+ return;
+ }
+
+ if (templates.length === 0) {
+ return;
+ }
+
+ // 1 child is Templates instance
+ const hasChildren = blockInstance.children.length > 1;
+
+ const rect = applyScale(outline.rect, scale);
+
+ const isAddMode = isMenuOpen || !modifierKeys.altKey || !hasChildren;
+
+ const tooltipContent = (
+ <Grid>
+ <Flex gap={1} css={{ order: isAddMode ? 0 : 2 }}>
+ <Kbd value={["click"]} color="contrast" />
+ <Text color="subtle">to add block</Text>
+ </Flex>
+ <Flex
+ gap={1}
+ css={{ order: 1, display: !hasChildren ? "none" : undefined }}
+ >
+ <Kbd value={["option", "click"]} color="contrast" />{" "}
+ <Text color="subtle">to delete</Text>
+ </Flex>
+ </Grid>
+ );
+
+ return (
+ <Outline rect={rect}>
+ <div
+ style={{
+ width: 0,
+ display: "grid",
+
+ alignContent: "stretch",
+ justifyContent: "end",
+ }}
+ >
+ <Flex
+ css={{
+ // Define grace area for the button
+ width: `calc(${iconButtonSize} + ${distanceToButton} + ${graceAreaOverlap})`,
+ marginRight: `-${graceAreaOverlap}`,
+ pointerEvents: isMenuOpen ? "none" : "all",
+ clipPath: `polygon(0% 0%, 100% 0%, 100% 100%, calc(100% - ${graceAreaOverlap}) 100%, 0% ${iconButtonSize})`,
+ }}
+ onMouseEnter={() => {
+ clearTimeout(timeoutRef.current);
+
+ setButtonOutline(outline);
+ }}
+ onMouseLeave={() => {
+ if (isMenuOpen) {
+ return;
+ }
+
+ clearTimeout(timeoutRef.current);
+
+ timeoutRef.current = setTimeout(() => {
+ setButtonOutline(undefined);
+ }, 100);
+ }}
+ >
+ <TemplatesMenu
+ open={isMenuOpen}
+ onOpenChange={(open) => {
+ if (!isAddMode) {
+ return;
+ }
+
+ setIsMenuOpen(open);
+
+ if (!open) {
+ setButtonOutline(undefined);
+ }
+ }}
+ anchor={outline.selector}
+ >
+ <Tooltip
+ content={tooltipContent}
+ side="top"
+ disableHoverableContent
+ >
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant={isAddMode ? "local" : "overwritten"}
+ onClick={() => {
+ if (isAddMode) {
+ return;
+ }
+
+ updateWebstudioData((data) => {
+ deleteInstanceMutable(data, outline.selector);
+ });
+
+ setButtonOutline(undefined);
+ $blockChildOutline.set(undefined);
+ $hoveredInstanceSelector.set(undefined);
+ $hoveredInstanceOutline.set(undefined);
+ }}
+ css={{
+ borderStyle: "solid",
+ borderColor: isAddMode
+ ? `oklch(from ${theme.colors.backgroundPrimary} l c h / 0.7)`
+ : undefined,
+ }}
+ >
+ {isAddMode ? <PlusIcon /> : <TrashIcon />}
+ </IconButton>
+ </DropdownMenuTrigger>
+ </Tooltip>
+ </TemplatesMenu>
+ </Flex>
+ </div>
+ </Outline>
+ );
+};
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/editable-block-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/editable-block-instance-outline.tsx
deleted file mode 100644
index 1ec08464de..0000000000
--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/editable-block-instance-outline.tsx
+++ /dev/null
@@ -1,396 +0,0 @@
-import { useStore } from "@nanostores/react";
-import {
- $blockChildOutline,
- $instances,
- $isContentMode,
- $registeredComponentMetas,
- type BlockChildOutline,
-} from "~/shared/nano-states";
-import {
- Box,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuPortal,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
- DropdownMenuTrigger,
- Flex,
- theme,
- IconButton,
- Tooltip,
- toast,
- Kbd,
- Text,
- iconButtonSize,
-} from "@webstudio-is/design-system";
-import { BlockChildAddButtonOutline } from "./outline";
-import { applyScale } from "./apply-scale";
-import { $scale } from "~/builder/shared/nano-states";
-import { PlusIcon } from "@webstudio-is/icons";
-import { BoxIcon } from "@webstudio-is/icons/svg";
-import { useRef, useState } from "react";
-import { isFeatureEnabled } from "@webstudio-is/feature-flags";
-import type { DroppableTarget, InstanceSelector } from "~/shared/tree-utils";
-import type { Instance, Instances } from "@webstudio-is/sdk";
-import {
- blockComponent,
- blockTemplateComponent,
-} from "@webstudio-is/react-sdk";
-import {
- extractWebstudioFragment,
- findAvailableDataSources,
- getWebstudioData,
- insertInstanceChildrenMutable,
- insertWebstudioFragmentCopy,
- updateWebstudioData,
-} from "~/shared/instance-utils";
-import { shallowEqual } from "shallow-equal";
-import { MetaIcon } from "~/builder/shared/meta-icon";
-
-export const findBlockSelector = (
- anchor: InstanceSelector,
- instances: Instances
-) => {
- if (anchor === undefined) {
- return;
- }
-
- if (anchor.length === 0) {
- return;
- }
-
- let blockInstanceSelector: InstanceSelector | undefined = undefined;
-
- for (let i = 0; i < anchor.length; ++i) {
- const instanceId = anchor[i];
-
- const instance = instances.get(instanceId);
- if (instance === undefined) {
- return;
- }
-
- if (instance.component === blockComponent) {
- blockInstanceSelector = anchor.slice(i);
- break;
- }
- }
-
- if (blockInstanceSelector === undefined) {
- return;
- }
-
- return blockInstanceSelector;
-};
-
-const findTemplates = (anchor: InstanceSelector, instances: Instances) => {
- const blockInstanceSelector = findBlockSelector(anchor, instances);
- if (blockInstanceSelector === undefined) {
- toast.error("Editable block not found");
- return;
- }
-
- const blockInstance = instances.get(blockInstanceSelector[0]);
-
- if (blockInstance === undefined) {
- toast.error("Editable block instance not found");
- return;
- }
-
- const templateInstanceId = blockInstance.children.find(
- (child) =>
- child.type === "id" &&
- instances.get(child.value)?.component === blockTemplateComponent
- )?.value;
-
- if (templateInstanceId === undefined) {
- toast.error("Templates instance id not found");
- return;
- }
-
- const templateInstance = instances.get(templateInstanceId);
-
- if (templateInstance === undefined) {
- toast.error("Templates instance not found");
- return;
- }
-
- const result: [instance: Instance, instanceSelector: InstanceSelector][] =
- templateInstance.children
- .filter((child) => child.type === "id")
- .map((child) => child.value)
- .map((childId) => instances.get(childId))
- .filter((child) => child !== undefined)
- .map((child) => [
- child,
- [child.id, templateInstanceId, ...blockInstanceSelector],
- ]);
-
- return result;
-};
-
-const getInsertionIndex = (
- anchor: InstanceSelector,
- instances: Instances,
- insertBefore: boolean = false
-) => {
- const blockSelector = findBlockSelector(anchor, instances);
- if (blockSelector === undefined) {
- return;
- }
-
- const insertAtInitialPosition = shallowEqual(blockSelector, anchor);
-
- const blockInstance = instances.get(blockSelector[0]);
-
- if (blockInstance === undefined) {
- toast.error("Editable block instance not found");
- return;
- }
-
- const index = blockInstance.children.findIndex((child) => {
- if (child.type !== "id") {
- return false;
- }
-
- if (insertAtInitialPosition) {
- return instances.get(child.value)?.component === blockTemplateComponent;
- }
-
- return child.value === anchor[0];
- });
-
- if (index === -1) {
- return;
- }
-
- // Independent of insertBefore, we always insert after the Templates instance
- if (insertAtInitialPosition) {
- return index + 1;
- }
-
- return insertBefore ? index : index + 1;
-};
-
-const TemplatesMenu = ({
- onOpenChange,
- children,
- anchor,
-}: {
- children: React.ReactNode;
- onOpenChange: (open: boolean) => void;
- anchor: InstanceSelector;
-}) => {
- const instances = useStore($instances);
- const metas = useStore($registeredComponentMetas);
-
- const optionPointerDownTime = useRef(0);
- const isMenuOpenedWithOption = useRef(false);
-
- const handleOpen = (open: boolean) => {
- onOpenChange(open);
-
- isMenuOpenedWithOption.current =
- Date.now() - optionPointerDownTime.current < 100;
- };
-
- const templates = findTemplates(anchor, instances);
-
- const menuItems = templates?.map(([template, templateSelector]) => ({
- id: template.id,
- icon: <MetaIcon icon={metas.get(template.component)?.icon ?? BoxIcon} />,
- title: template.label ?? template.component,
- value: templateSelector,
- }));
-
- const tooltipContent = (
- <>
- <Flex gap={1}>
- <Kbd value={["click"]} color="contrast" />
- <Text color="subtle">to add after</Text>
- </Flex>
- <Flex gap={1}>
- <Kbd value={["option", "click"]} color="contrast" />{" "}
- <Text color="subtle">to add before</Text>
- </Flex>
- </>
- );
-
- return (
- <div
- style={{ display: "contents" }}
- onPointerDown={(event) => {
- if (event.altKey) {
- optionPointerDownTime.current = Date.now();
- }
- }}
- >
- <DropdownMenu onOpenChange={handleOpen} modal>
- <Tooltip content={tooltipContent} side="top" disableHoverableContent>
- <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
- </Tooltip>
-
- <DropdownMenuPortal>
- <DropdownMenuContent
- align="start"
- sideOffset={4}
- collisionPadding={16}
- side="bottom"
- loop
- >
- <DropdownMenuRadioGroup
- onValueChange={(value) => {
- const isOptionDownOnMenuItemClick =
- Date.now() - optionPointerDownTime.current < 100;
-
- const insertBefore =
- isMenuOpenedWithOption.current || isOptionDownOnMenuItemClick;
-
- const templateSelector = JSON.parse(value) as InstanceSelector;
- const fragment = extractWebstudioFragment(
- getWebstudioData(),
- templateSelector[0]
- );
-
- const parentSelector = findBlockSelector(anchor, instances);
-
- if (parentSelector === undefined) {
- return;
- }
-
- const position = getInsertionIndex(
- anchor,
- instances,
- insertBefore
- );
-
- if (position === undefined) {
- return;
- }
-
- const target: DroppableTarget = {
- parentSelector,
- position,
- };
-
- updateWebstudioData((data) => {
- const { newInstanceIds } = insertWebstudioFragmentCopy({
- data,
- fragment,
- availableDataSources: findAvailableDataSources(
- data.dataSources,
- data.instances,
- target.parentSelector
- ),
- });
- const newRootInstanceId = newInstanceIds.get(
- fragment.instances[0].id
- );
- if (newRootInstanceId === undefined) {
- return;
- }
- const children: Instance["children"] = [
- { type: "id", value: newRootInstanceId },
- ];
- insertInstanceChildrenMutable(data, children, target);
- });
- }}
- >
- {menuItems?.map(({ icon, title, id, value }) => (
- <DropdownMenuRadioItem key={id} value={JSON.stringify(value)}>
- <Flex
- css={{ py: theme.spacing[4], px: theme.spacing[5] }}
- gap={2}
- >
- {icon}
- <Box>{title}</Box>
- </Flex>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenu>
- </div>
- );
-};
-
-export const BlockChildHoveredInstanceOutline = () => {
- const blockChildOutline = useStore($blockChildOutline);
- const scale = useStore($scale);
- const isContentMode = useStore($isContentMode);
-
- const timeoutRef = useRef<undefined | ReturnType<typeof setTimeout>>(
- undefined
- );
- const [buttonOutline, setButtonOutline] = useState<
- undefined | BlockChildOutline
- >(undefined);
-
- const outline = blockChildOutline ?? buttonOutline;
-
- const [isMenuOpen, setIsMenuOpen] = useState(false);
-
- if (isFeatureEnabled("contentEditableMode") === false) {
- return;
- }
-
- if (!isContentMode) {
- return;
- }
-
- if (outline === undefined) {
- return;
- }
-
- const rect = applyScale(outline.rect, scale);
-
- return (
- <BlockChildAddButtonOutline rect={rect}>
- <Flex
- css={{
- width: "min-content",
- pointerEvents: isMenuOpen ? "none" : "all",
- clipPath: `polygon(0% 0%, 100% 0%, 100% 100%, 0% ${iconButtonSize})`,
- }}
- onMouseEnter={() => {
- clearTimeout(timeoutRef.current);
-
- setButtonOutline(outline);
- }}
- onMouseLeave={() => {
- if (isMenuOpen) {
- return;
- }
-
- clearTimeout(timeoutRef.current);
-
- timeoutRef.current = setTimeout(() => {
- setButtonOutline(undefined);
- }, 100);
- }}
- >
- <TemplatesMenu
- onOpenChange={(open) => {
- setIsMenuOpen(open);
-
- if (!open) {
- setButtonOutline(undefined);
- }
- }}
- anchor={outline.selector}
- >
- <IconButton
- variant={"local"}
- css={{
- mr: theme.spacing[4],
- borderStyle: "solid",
- borderColor: `oklch(from ${theme.colors.backgroundPrimary} l c h / 0.7)`,
- }}
- >
- <PlusIcon />
- </IconButton>
- </TemplatesMenu>
- </Flex>
- </BlockChildAddButtonOutline>
- );
-};
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/outline.tsx
index 37cc4e267e..9c74bef98c 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/outline.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/outline.tsx
@@ -72,37 +72,6 @@ type OutlineProps = {
variant?: "default" | "collaboration" | "slot";
};
-export const BlockChildAddButtonOutline = ({
- rect,
- children,
-}: {
- rect: Rect;
- children: ReactNode;
-}) => {
- const dynamicStyle = useDynamicStyle(rect);
-
- return (
- <>
- <div
- className={`${baseStyle()} ${baseOutlineStyle()}`}
- style={dynamicStyle}
- >
- <div
- style={{
- width: 0,
- display: "grid",
-
- alignContent: "stretch",
- justifyContent: "end",
- }}
- >
- {children}
- </div>
- </div>
- </>
- );
-};
-
export const Outline = ({ children, rect, variant }: OutlineProps) => {
const dynamicStyle = useDynamicStyle(rect);
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index 60179285a9..3b56b9424f 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -32,7 +32,7 @@ import {
import { selectInstance } from "~/shared/awareness";
import { openCommandPanel } from "../features/command-panel";
import { builderApi } from "~/shared/builder-api";
-import { findBlockSelector } from "../features/workspace/canvas-tools/outline/editable-block-instance-outline";
+import { findBlockSelector } from "../features/workspace/canvas-tools/outline/block-instance-outline";
import { blockTemplateComponent } from "@webstudio-is/react-sdk";
const makeBreakpointCommand = <CommandName extends string>(
diff --git a/apps/builder/app/builder/shared/inert-handlers.ts b/apps/builder/app/builder/shared/inert-handlers.ts
new file mode 100644
index 0000000000..b869f1a327
--- /dev/null
+++ b/apps/builder/app/builder/shared/inert-handlers.ts
@@ -0,0 +1,78 @@
+import { useCallback } from "react";
+import { canvasApi } from "~/shared/canvas-api";
+import { $textEditingInstanceSelector } from "~/shared/nano-states";
+
+export const skipInertHandlersAttribute = "data-ws-skip-inert-handlers";
+
+export const useInertHandlers = () => {
+ /**
+ * Prevents Lexical text editor from stealing focus during rendering.
+ * Sets the inert attribute on the canvas body element and disables the text editor.
+ *
+ * This must be done synchronously to avoid the following issue:
+ *
+ * 1. Text editor is in edit state.
+ * 2. User focuses on the builder (e.g., clicks any input).
+ * 3. The text editor blur event triggers, causing a rerender on data change (data saved in onBlur).
+ * 4. Text editor rerenders, stealing focus from the builder.
+ * 5. Inert attribute is set asynchronously, but focus is already lost.
+ *
+ * Synchronous focusing and setInert prevent the text editor from focusing on render.
+ * This cannot be handled inside the canvas because the text editor toolbar is in the builder and focus events in the canvas should be ignored.
+ *
+ * Use onPointerDown instead of onFocus because Radix focus lock triggers on text edit blur
+ * before the focusin event when editing text inside a Radix dialog.
+ */
+ const onPointerDown = useCallback((event: React.PointerEvent) => {
+ if (
+ event.target instanceof Element &&
+ event.target.closest(`[${skipInertHandlersAttribute}]`)
+ ) {
+ return;
+ }
+
+ // Ignore toolbar focus events. See the onFocus handler in text-toolbar.tsx
+ if (false === event.defaultPrevented) {
+ canvasApi.setInert();
+ $textEditingInstanceSelector.set(undefined);
+ }
+ }, []);
+
+ /**
+ * Prevent Radix from stealing focus during editing in the style sources
+ * For example, when the user select or create new style source item inside a dialog.
+ */
+ const onKeyDown = useCallback((event: React.KeyboardEvent) => {
+ if (
+ event.target instanceof Element &&
+ event.target.closest(`[${skipInertHandlersAttribute}]`)
+ ) {
+ return;
+ }
+
+ if (event.target instanceof HTMLInputElement) {
+ canvasApi.setInert();
+ }
+ }, []);
+
+ /**
+ * Prevent Radix from stealing focus during editing in the settings panel.
+ * For example, when the user modifies the text content of an H1 element inside a dialog.
+ */
+ const onInput = useCallback((event: React.FormEvent<HTMLDivElement>) => {
+ if (
+ event.target instanceof Element &&
+ event.target.closest(`[${skipInertHandlersAttribute}]`)
+ ) {
+ return;
+ }
+
+ canvasApi.setInert();
+ }, []);
+
+ return {
+ onInput,
+ onKeyDown,
+ onPointerDown,
+ };
+};
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index fd59d393c5..5a54d49030 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -47,6 +47,7 @@ import {
$isPreviewMode,
$isDesignMode,
$isContentMode,
+ subscribeModifierKeys,
} from "~/shared/nano-states";
import { useDragAndDrop } from "./shared/use-drag-drop";
import {
@@ -64,7 +65,6 @@ import type { ImageLoader } from "@webstudio-is/image";
import { subscribeCommands } from "~/canvas/shared/commands";
import { updateCollaborativeInstanceRect } from "./collaborative-instance";
import { $params } from "./stores";
-import { subscribeInspectorEdits } from "./inspector-edits";
import { initCanvasApi } from "~/shared/canvas-api";
import { subscribeFontLoadingDone } from "./shared/font-weight-support";
import { useDebounceEffect } from "~/shared/hook-utils/use-debounce-effect";
@@ -178,8 +178,8 @@ const DesignMode = () => {
updateCollaborativeInstanceRect(options);
subscribeInstanceSelection(options);
subscribeInstanceHovering(options);
- subscribeInspectorEdits(options);
subscribeFontLoadingDone(options);
+ subscribeModifierKeys(options);
return () => {
abortController.abort();
};
@@ -211,9 +211,9 @@ const ContentEditMode = () => {
manageContentEditModeStyles(options);
subscribeInstanceSelection(options);
subscribeInstanceHovering(options);
- subscribeInspectorEdits(options);
subscribeFontLoadingDone(options);
initCopyPasteForContentEditMode(options);
+ subscribeModifierKeys(options);
return () => {
abortController.abort();
};
diff --git a/apps/builder/app/canvas/features/build-mode/block.tsx b/apps/builder/app/canvas/features/build-mode/block.tsx
index f950e778a1..600f05bba0 100644
--- a/apps/builder/app/canvas/features/build-mode/block.tsx
+++ b/apps/builder/app/canvas/features/build-mode/block.tsx
@@ -28,21 +28,27 @@ export const Block = React.forwardRef<
React.isValidElement(child)
);
- if (isDesignMode) {
- if (instance === undefined) {
- return <div>Editable Block instance is undefined</div>;
- }
+ if (instance === undefined) {
+ return <div>Content Block instance is undefined</div>;
+ }
- const templateInstanceId = instance.children.find(
- (child) =>
- child.type === "id" &&
- instances.get(child.value)?.component === blockTemplateComponent
- )?.value;
+ const templateInstanceId = instance.children.find(
+ (child) =>
+ child.type === "id" &&
+ instances.get(child.value)?.component === blockTemplateComponent
+ )?.value;
- if (templateInstanceId === undefined) {
- return <div>Editable Block template instance not found</div>;
- }
+ if (templateInstanceId === undefined) {
+ return <div>Content Block template child is not found</div>;
+ }
+
+ const templateInstance = instances.get(templateInstanceId);
+ if (templateInstance === undefined) {
+ return <div>Content Block template instance is not found</div>;
+ }
+
+ if (isDesignMode) {
if (selectedInstanceSelector !== undefined) {
const selectedSelector = selectedInstanceSelector.join(",");
// If any template child is selected then render only template
@@ -64,6 +70,12 @@ export const Block = React.forwardRef<
}
const hasContent = childArray.length > 1;
+ const hasTemplates = templateInstance.children.length > 0;
+
+ if (!isDesignMode && !hasContent && !hasTemplates) {
+ return <></>;
+ }
+
const editableBlockStyle = hasContent ? { display: "contents" } : {};
return (
diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
index cf2ae47e89..b96ccf1a6b 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
@@ -848,19 +848,23 @@ const LinkSanitizePlugin = (): null => {
return null;
};
-const AnyKeyDownPlugin = ({ onKeyDown }: { onKeyDown: () => void }) => {
+const AnyKeyDownPlugin = ({
+ onKeyDown,
+}: {
+ onKeyDown: (event: KeyboardEvent) => void;
+}) => {
const [editor] = useLexicalComposerContext();
useEffect(() => {
return editor.registerCommand(
KEY_DOWN_COMMAND,
- () => {
+ (event) => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) {
return false;
}
- onKeyDown();
+ onKeyDown(event);
return false;
},
COMMAND_PRIORITY_NORMAL
@@ -1034,7 +1038,12 @@ export const TextEditor = ({
[handleChange, instances, rootInstanceSelector]
);
- const handleAnyKeydown = useCallback(() => {
+ const handleAnyKeydown = useCallback((event: KeyboardEvent) => {
+ // Skip alt as Block outline depends on Alt key press
+ if (event.key === "Alt") {
+ return;
+ }
+
$blockChildOutline.set(undefined);
$hoveredInstanceOutline.set(undefined);
$hoveredInstanceSelector.set(undefined);
diff --git a/apps/builder/app/canvas/inspector-edits.ts b/apps/builder/app/canvas/inspector-edits.ts
deleted file mode 100644
index feecc2ea8f..0000000000
--- a/apps/builder/app/canvas/inspector-edits.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { canvasApi } from "~/shared/canvas-api";
-import { $props } from "~/shared/nano-states";
-
-export const subscribeInspectorEdits = ({
- signal,
-}: {
- signal: AbortSignal;
-}) => {
- // Prevents Radix from stealing focus when the content inside a dialog changes.
- // (Radix focus scope uses a MutationObserver)
- const unsubscribeProps = $props.listen(canvasApi.setInert);
- signal.addEventListener("abort", unsubscribeProps);
-};
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index bd7640bfac..ff6c1b037b 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -138,65 +138,86 @@ const subscribeDesignModeHelperStyles = () => {
};
const subscribeContentEditModeHelperStyles = () => {
- helpersSheet.setAttribute("media", "all");
+ const renderHelperStyles = () => {
+ helpersSheet.clear();
+ helpersSheet.setAttribute("media", "all");
- for (const style of helperStylesContentEdit) {
- helpersSheet.addPlaintextRule(style);
- }
+ for (const style of helperStylesContentEdit) {
+ helpersSheet.addPlaintextRule(style);
+ }
- // Show text cursor on all editable elements (including links and buttons)
- // to indicate they are editable in the content editor mode
- //
- // @todo Consider setting cursor: pointer on non-editable elements by default
- // to better distinguish clickable vs editable elements, needs more investigation
- const rootInstanceId = $selectedPage.get()?.rootInstanceId;
- if (rootInstanceId !== undefined) {
- const editableInstanceSelectors: InstanceSelector[] = [];
- const instances = $instances.get();
-
- findAllEditableInstanceSelector(
- rootInstanceId,
- [],
- instances,
- $registeredComponentMetas.get(),
- editableInstanceSelectors
- );
+ // Show text cursor on all editable elements (including links and buttons)
+ // to indicate they are editable in the content editor mode
+ //
+ // @todo Consider setting cursor: pointer on non-editable elements by default
+ // to better distinguish clickable vs editable elements, needs more investigation
+ const rootInstanceId = $selectedPage.get()?.rootInstanceId;
+ if (rootInstanceId !== undefined) {
+ const editableInstanceSelectors: InstanceSelector[] = [];
+ const instances = $instances.get();
+
+ findAllEditableInstanceSelector(
+ rootInstanceId,
+ [],
+ instances,
+ $registeredComponentMetas.get(),
+ editableInstanceSelectors
+ );
- // Group IDs into chunks of 20 since :is() allows for more efficient grouping
- const chunkSize = 20;
- for (let i = 0; i < editableInstanceSelectors.length; i += chunkSize) {
- const chunk = editableInstanceSelectors
- .slice(i, i + chunkSize)
- .filter((selector) => {
- const instance = instances.get(selector[0]);
- if (instance === undefined) {
- return false;
- }
+ // Group IDs into chunks of 20 since :is() allows for more efficient grouping
+ const chunkSize = 20;
+ for (let i = 0; i < editableInstanceSelectors.length; i += chunkSize) {
+ const chunk = editableInstanceSelectors
+ .slice(i, i + chunkSize)
+ .filter((selector) => {
+ const instance = instances.get(selector[0]);
+ if (instance === undefined) {
+ return false;
+ }
+
+ const hasExpressionChildren = instance.children.some(
+ (child) => child.type === "expression"
+ );
+
+ if (hasExpressionChildren) {
+ return false;
+ }
+
+ return true;
+ });
- const hasExpressionChildren = instance.children.some(
- (child) => child.type === "expression"
- );
+ const selectors = chunk.map(
+ (selector) => `[${idAttribute}="${selector[0]}"]`
+ );
- if (hasExpressionChildren) {
- return false;
- }
+ helpersSheet.addPlaintextRule(
+ `:is(${selectors.join(", ")}), :is(${selectors.join(", ")}) a { cursor: text; }`
+ );
+ }
+ }
- return true;
- });
+ helpersSheet.render();
+ };
- const selectors = chunk.map(
- (selector) => `[${idAttribute}="${selector[0]}"]`
- );
+ renderHelperStyles();
- helpersSheet.addPlaintextRule(
- `:is(${selectors.join(", ")}), :is(${selectors.join(", ")}) a { cursor: text; }`
- );
- }
- }
+ const requestIdleCallbackFn =
+ globalThis.requestIdleCallback ?? requestAnimationFrame;
+ const cancelIdleCallbackFn =
+ globalThis.cancelIdleCallback ?? cancelAnimationFrame;
- helpersSheet.render();
+ let idleId: number;
+ const renderHelperStylesIdle = () => {
+ cancelIdleCallbackFn(idleId);
+ idleId = requestIdleCallbackFn(renderHelperStyles);
+ };
+
+ const unsubscribeInstances = $instances.listen(renderHelperStylesIdle);
+ const unsubscribeSelectedPage = $selectedPage.listen(renderHelperStylesIdle);
return () => {
+ unsubscribeInstances();
+ unsubscribeSelectedPage();
helpersSheet.clear();
helpersSheet.render();
};
diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.ts
index 6fee229467..7d48d7ec7c 100644
--- a/apps/builder/app/shared/nano-states/misc.ts
+++ b/apps/builder/app/shared/nano-states/misc.ts
@@ -415,6 +415,28 @@ export const setBuilderMode = (mode: BuilderMode | null) => {
export const $toastErrors = atom<string[]>([]);
+export const $modifierKeys = atom<{ altKey: boolean }>({ altKey: false });
+
+export const subscribeModifierKeys = (options: AddEventListenerOptions) => {
+ const handleKeyEvent = (event: MouseEvent | KeyboardEvent) => {
+ const altKey = event.altKey;
+ if ($modifierKeys.get().altKey !== altKey) {
+ $modifierKeys.set({ altKey });
+ }
+ };
+
+ const eventOptions: AddEventListenerOptions = {
+ ...options,
+ capture: true,
+
+ passive: true,
+ };
+
+ document.addEventListener("keydown", handleKeyEvent, eventOptions);
+ document.addEventListener("keyup", handleKeyEvent, eventOptions);
+ document.addEventListener("mousemove", handleKeyEvent, eventOptions);
+};
+
export type ItemDropTarget = {
itemSelector: InstanceSelector;
indexWithinChildren: number;
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index 8012693ce4..cf744a5ba8 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -45,6 +45,7 @@ import {
$textToolbar,
$registeredComponentMetas,
$registeredComponentPropsMetas,
+ $modifierKeys,
} from "~/shared/nano-states";
import { $ephemeralStyles } from "~/canvas/stores";
import { $awareness } from "../awareness";
@@ -139,6 +140,7 @@ const createObjectPool = () => {
),
new NanostoresSyncObject("hoveredInstanceOutline", $hoveredInstanceOutline),
new NanostoresSyncObject("blockChildOutline", $blockChildOutline),
+ new NanostoresSyncObject("modifierKeys", $modifierKeys),
new NanostoresSyncObject(
"collaborativeInstanceSelector",