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.

Attempt to hover/select without element (#2014)

Ivan Starkov4f10bc26f841
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 51bc689969..fcd8529021 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -52,6 +52,7 @@ import { subscribeInstanceSelection } from "./instance-selection";
import { subscribeInstanceHovering } from "./instance-hovering";
import { useHashLinkSync } from "~/shared/pages";
import { useMount } from "~/shared/hook-utils/use-mount";
+import { useSelectedInstance } from "./instance-selected-react";
registerContainers();
@@ -160,6 +161,7 @@ const DesignMode = ({ params }: { params: Params }) => {
// in both places
useCopyPaste();
+ useSelectedInstance();
useEffect(subscribeInstanceSelection, []);
useEffect(subscribeInstanceHovering, []);
diff --git a/apps/builder/app/canvas/features/webstudio-component/selected-instance-connector.ts b/apps/builder/app/canvas/features/webstudio-component/selected-instance-connector.ts
deleted file mode 100644
index faf54000e5..0000000000
--- a/apps/builder/app/canvas/features/webstudio-component/selected-instance-connector.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { useEffect } from "react";
-import { useStore } from "@nanostores/react";
-import type { Instance, StyleDecl } from "@webstudio-is/project-build";
-import { idAttribute } from "@webstudio-is/react-sdk";
-import { subscribe } from "~/shared/pubsub";
-import { subscribeWindowResize } from "~/shared/dom-hooks";
-import {
- isResizingCanvasStore,
- instancesStore,
- selectedInstanceBrowserStyleStore,
- selectedInstanceIntanceToTagStore,
- selectedInstanceUnitSizesStore,
- selectedInstanceRenderStateStore,
-} from "~/shared/nano-states";
-import htmlTags, { type htmlTags as HtmlTags } from "html-tags";
-import { getAllElementsBoundingBox } from "~/shared/dom-utils";
-import { subscribeScrollState } from "~/canvas/shared/scroll-state";
-import { selectedInstanceOutlineStore } from "~/shared/nano-states";
-import type { UnitSizes } from "~/builder/features/style-panel/shared/css-value-input/convert-units";
-import { setDataCollapsed } from "~/canvas/collapsed";
-import { type InstanceSelector } from "~/shared/tree-utils";
-import { getIsVisuallyHidden } from "./visually-hidden";
-import { getBrowserStyle } from "./get-browser-style";
-
-const isHtmlTag = (tag: string): tag is HtmlTags =>
- htmlTags.includes(tag as HtmlTags);
-
-const setOutline = (instanceId: Instance["id"], element: HTMLElement) => {
- selectedInstanceOutlineStore.set({
- instanceId,
- rect: getAllElementsBoundingBox(element),
- });
-};
-
-const hideOutline = () => {
- selectedInstanceOutlineStore.set(undefined);
-};
-
-const calculateUnitSizes = (element: HTMLElement): UnitSizes => {
- // Based on this https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions/8876069#8876069
- // this is crossbrowser way to get viewport sizes vw vh in px
- const vw =
- Math.max(document.documentElement.clientWidth, window.innerWidth) / 100;
- const vh =
- Math.max(document.documentElement.clientHeight, window.innerHeight) / 100;
-
- // em in px is equal to current computed style for font size
- const em = Number.parseFloat(getComputedStyle(element).fontSize);
-
- // rem in px is equal to root computed style for font size
- const rem = Number.parseFloat(
- getComputedStyle(document.documentElement).fontSize
- );
-
- // we create a node with 1ch width, measure it in px and remove it
- const node = document.createElement("div");
- node.style.width = "1ch";
- node.style.position = "absolute";
- element.appendChild(node);
- const ch = Number.parseFloat(getComputedStyle(node).width);
- element.removeChild(node);
-
- return {
- ch, // 1ch in pixels
- vw, // 1vw in pixels
- vh, // 1vh in pixels
- em, // 1em in pixels
- rem, // 1rem in pixels
- px: 1, // always 1, simplifies conversions and types, i.e valueTo = valueFrom * unitSizes[from] / unitSizes[to]
- };
-};
-
-export const SelectedInstanceConnector = ({
- instanceElementRef,
- instance,
- instanceStyles,
- instanceProps,
- instanceSelector,
-}: {
- instanceElementRef: { current: null | HTMLElement };
- instance: Instance;
- instanceStyles: StyleDecl[];
- instanceProps: unknown;
- instanceSelector: InstanceSelector;
-}) => {
- const instances = useStore(instancesStore);
-
- useEffect(() => {
- // Synchronously execute setDataCollapsed to calculate right outline
- // This fixes an issue, when new element outline was calulated before collapsed elements calculations
- setDataCollapsed(instance.id, true);
-
- const element = instanceElementRef.current;
- if (element === null) {
- return;
- }
-
- if (getIsVisuallyHidden(element)) {
- return;
- }
-
- const showOutline = () => {
- if (isResizingCanvasStore.get()) {
- return;
- }
- setOutline(instance.id, element);
- };
- // effect close to rendered element also catches dnd remounts
- // so actual state is always provided here
- showOutline();
-
- const resizeObserver = new ResizeObserver(() => {
- // Having hover etc, element can have no size because of that
- setDataCollapsed(instance.id, true);
- // contentRect has wrong x/y values for absolutely positioned element.
- // getBoundingClientRect is used instead.
- showOutline();
- });
- resizeObserver.observe(element);
-
- // detect movement of the element within same parent
- // React prevent remount when key stays the same
- const mutationObserver = new window.MutationObserver(() => {
- showOutline();
- });
- const parent = element?.parentElement;
- if (parent) {
- mutationObserver.observe(parent, { childList: true });
- }
-
- // hide rect when preview style is send
- // new rect will be send when new styles
- // will be written to instance css rules
- const unsubscribePreviewStyle = subscribe("previewStyle", () => {
- hideOutline();
- });
-
- const unsubscribeIsResizingCanvas = isResizingCanvasStore.subscribe(
- (isResizing) => {
- if (isResizing && selectedInstanceOutlineStore.get()) {
- return hideOutline();
- }
- showOutline();
- }
- );
-
- const unsubscribeScrollState = subscribeScrollState({
- onScrollStart() {
- hideOutline();
- },
- onScrollEnd() {
- showOutline();
- },
- });
-
- const unsubscribeWindowResize = subscribeWindowResize({
- onResizeStart() {
- hideOutline();
- },
- onResizeEnd() {
- showOutline();
- },
- });
-
- // trigger style recomputing every time instance styles are changed
- selectedInstanceBrowserStyleStore.set(getBrowserStyle(element));
-
- // Map self and ancestor instance ids to tag names
- const instanceToTag = new Map<Instance["id"], HtmlTags>();
- for (
- let ancestorOrSelf: HTMLElement | null = element;
- ancestorOrSelf !== null;
- ancestorOrSelf = ancestorOrSelf.parentElement
- ) {
- const tagName = ancestorOrSelf.tagName.toLowerCase();
- const instanceId = ancestorOrSelf.getAttribute(idAttribute);
-
- if (isHtmlTag(tagName) && instanceId !== null) {
- instanceToTag.set(instanceId, tagName);
- }
- }
-
- selectedInstanceIntanceToTagStore.set(instanceToTag);
-
- const unitSizes = calculateUnitSizes(element);
- selectedInstanceUnitSizesStore.set(unitSizes);
-
- selectedInstanceRenderStateStore.set("mounted");
-
- return () => {
- hideOutline();
- resizeObserver.disconnect();
- mutationObserver.disconnect();
- unsubscribePreviewStyle();
- unsubscribeScrollState();
- unsubscribeWindowResize();
- unsubscribeIsResizingCanvas();
-
- // see webstudio-component.tsx for where it's set to "notMounted"
- selectedInstanceRenderStateStore.set("pending");
- };
- }, [
- instanceElementRef,
- instance,
- instanceSelector,
- instanceStyles,
- // instance props may change dom element
- instanceProps,
- // update on all changes in the tree in case ResizeObserver does ont work
- instances,
- ]);
-
- return null;
-};
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index fc2ccc0f9c..e00d10a258 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -32,12 +32,10 @@ import {
type InstanceSelector,
areInstanceSelectorsEqual,
} from "~/shared/tree-utils";
-import { SelectedInstanceConnector } from "./selected-instance-connector";
import { handleLinkClick } from "./link";
import { mergeRefs } from "@react-aria/utils";
import { composeEventHandlers } from "@radix-ui/primitive";
import { setDataCollapsed } from "~/canvas/collapsed";
-import { useIsVisuallyHidden } from "./visually-hidden";
const TextEditor = lazy(() => import("../text-editor"));
@@ -160,7 +158,6 @@ export const WebstudioComponentDev = forwardRef<
useCssRules({ instanceId: instance.id, instanceStyles });
const instances = useStore(instancesStore);
- const selectedInstanceSelector = useStore(selectedInstanceSelectorStore);
const textEditingInstanceSelector = useStore(
textEditingInstanceSelectorStore
);
@@ -168,24 +165,10 @@ export const WebstudioComponentDev = forwardRef<
const instanceProps = useInstanceProps(instance.id);
const { [showAttribute]: show = true, ...userProps } = instanceProps;
- const isSelected = areInstanceSelectorsEqual(
- selectedInstanceSelector,
- instanceSelector
- );
const isPreviewMode = useStore(isPreviewModeStore);
useCollapsedOnNewElement(instanceId);
- // Scroll the selected instance into view when selected from navigator.
- useEffect(() => {
- if (isSelected) {
- instanceElementRef.current?.scrollIntoView({
- behavior: "smooth",
- block: "nearest",
- });
- }
- }, [isSelected]);
-
// this assumes presence of `useStore(selectedInstanceSelectorStore)` above
// we rely on root re-rendering after selected instance changes
useEffect(() => {
@@ -200,11 +183,6 @@ export const WebstudioComponentDev = forwardRef<
}
});
- const isScreenReaderDescendant = useIsVisuallyHidden(instanceElementRef);
- if (isScreenReaderDescendant) {
- return <></>;
- }
-
const readonlyProps =
isPreviewMode === false &&
(instance.component === "Input" || instance.component === "Textarea")
@@ -273,15 +251,6 @@ export const WebstudioComponentDev = forwardRef<
const instanceElement = (
<>
- {isSelected && (
- <SelectedInstanceConnector
- instanceElementRef={instanceElementRef}
- instance={instance}
- instanceSelector={instanceSelector}
- instanceStyles={instanceStyles}
- instanceProps={instanceProps}
- />
- )}
<Component
{...restProps}
{...props}
diff --git a/apps/builder/app/canvas/instance-hovering.ts b/apps/builder/app/canvas/instance-hovering.ts
index 67f90d63ed..929a3dbe17 100644
--- a/apps/builder/app/canvas/instance-hovering.ts
+++ b/apps/builder/app/canvas/instance-hovering.ts
@@ -6,10 +6,11 @@ import {
import { hoveredInstanceOutlineStore } from "~/shared/nano-states";
import {
getAllElementsBoundingBox,
- getElementByInstanceSelector,
+ getElementsByInstanceSelector,
getInstanceSelectorFromElement,
} from "~/shared/dom-utils";
import { subscribeScrollState } from "./shared/scroll-state";
+import type { InstanceSelector } from "~/shared/tree-utils";
type TimeoutId = undefined | ReturnType<typeof setTimeout>;
@@ -44,27 +45,41 @@ export const subscribeInstanceHovering = () => {
hoveredInstanceSelectorStore.set(undefined);
hoveredInstanceOutlineStore.set(undefined);
}, 100);
+
+ // Fixes the bug, that new hover occures during timeout
+ const unsubscribe = hoveredInstanceSelectorStore.listen(() => {
+ clearTimeout(mouseOutTimeoutId);
+ unsubscribe();
+ });
};
const eventOptions = { passive: true };
window.addEventListener("mouseover", handleMouseOver, eventOptions);
window.addEventListener("mouseout", handleMouseOut, eventOptions);
- // debounce is used to avoid laggy hover because of iframe message delay
- const updateHoveredRect = (element: Element) => {
- const instanceId = element.getAttribute(idAttribute) ?? undefined;
- if (instanceId === undefined) {
+ const updateHoveredRect = (
+ elements: Element[],
+ instanceSelector: Readonly<InstanceSelector>
+ ) => {
+ if (elements.length === 0) {
return;
}
+
+ if (instanceSelector.length === 0) {
+ return;
+ }
+
+ const [instanceId] = instanceSelector;
const instances = instancesStore.get();
const instance = instances.get(instanceId);
if (instance === undefined) {
return;
}
+
if (!isScrolling) {
hoveredInstanceOutlineStore.set({
instanceId: instance.id,
- rect: getAllElementsBoundingBox(element),
+ rect: getAllElementsBoundingBox(elements),
});
}
};
@@ -79,7 +94,13 @@ export const subscribeInstanceHovering = () => {
onScrollEnd() {
isScrolling = false;
if (hoveredElement !== undefined) {
- updateHoveredRect(hoveredElement);
+ const instanceSelector = getInstanceSelectorFromElement(hoveredElement);
+
+ if (instanceSelector === undefined) {
+ return;
+ }
+
+ updateHoveredRect([hoveredElement], instanceSelector);
}
},
});
@@ -88,10 +109,8 @@ export const subscribeInstanceHovering = () => {
const unsubscribeHoveredInstanceId = hoveredInstanceSelectorStore.subscribe(
(instanceSelector) => {
if (instanceSelector) {
- const element = getElementByInstanceSelector(instanceSelector);
- if (element !== undefined) {
- updateHoveredRect(element);
- }
+ const elements = getElementsByInstanceSelector(instanceSelector);
+ updateHoveredRect(elements, instanceSelector);
} else {
hoveredInstanceOutlineStore.set(undefined);
}
diff --git a/apps/builder/app/canvas/instance-selected-react.ts b/apps/builder/app/canvas/instance-selected-react.ts
new file mode 100644
index 0000000000..1b0b2769ad
--- /dev/null
+++ b/apps/builder/app/canvas/instance-selected-react.ts
@@ -0,0 +1,38 @@
+import { useCallback, useEffect, useState } from "react";
+import { useStore } from "@nanostores/react";
+import { selectedInstanceSelectorStore } from "~/shared/nano-states";
+import { subscribeSelectedInstance } from "./instance-selected";
+
+/**
+ * Debounce task execution until useEffect
+ */
+const useDebounceEffect = () => {
+ const [updateCallback, setUpdateCallback] = useState(() => () => {
+ /* empty */
+ });
+
+ useEffect(() => {
+ // Because of how our styles works we need to update after React render to be sure that
+ // all styles are applied
+ updateCallback();
+ }, [updateCallback]);
+
+ return useCallback((task: () => void) => {
+ setUpdateCallback(() => task);
+ }, []);
+};
+
+export const useSelectedInstance = () => {
+ const selectedInstanceSelector = useStore(selectedInstanceSelectorStore);
+ const execTaskInEffect = useDebounceEffect();
+
+ useEffect(() => {
+ if (selectedInstanceSelector === undefined) {
+ return;
+ }
+ return subscribeSelectedInstance(
+ selectedInstanceSelector,
+ execTaskInEffect
+ );
+ }, [selectedInstanceSelector, execTaskInEffect]);
+};
diff --git a/apps/builder/app/canvas/instance-selected.ts b/apps/builder/app/canvas/instance-selected.ts
new file mode 100644
index 0000000000..106cdda1db
--- /dev/null
+++ b/apps/builder/app/canvas/instance-selected.ts
@@ -0,0 +1,275 @@
+import type { Instance } from "@webstudio-is/project-build";
+import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";
+import { subscribeWindowResize } from "~/shared/dom-hooks";
+import {
+ isResizingCanvasStore,
+ selectedInstanceBrowserStyleStore,
+ selectedInstanceIntanceToTagStore,
+ selectedInstanceUnitSizesStore,
+ selectedInstanceRenderStateStore,
+ stylesIndexStore,
+ instancesStore,
+ propsStore,
+ dataSourceValuesStore,
+} from "~/shared/nano-states";
+import htmlTags, { type htmlTags as HtmlTags } from "html-tags";
+import {
+ getAllElementsBoundingBox,
+ getElementsByInstanceSelector,
+} from "~/shared/dom-utils";
+import { subscribeScrollState } from "~/canvas/shared/scroll-state";
+import { selectedInstanceOutlineStore } from "~/shared/nano-states";
+import type { UnitSizes } from "~/builder/features/style-panel/shared/css-value-input/convert-units";
+import { setDataCollapsed } from "~/canvas/collapsed";
+import { getBrowserStyle } from "./features/webstudio-component/get-browser-style";
+import type { InstanceSelector } from "~/shared/tree-utils";
+
+const isHtmlTag = (tag: string): tag is HtmlTags =>
+ htmlTags.includes(tag as HtmlTags);
+
+const setOutline = (instanceId: Instance["id"], elements: HTMLElement[]) => {
+ selectedInstanceOutlineStore.set({
+ instanceId,
+ rect: getAllElementsBoundingBox(elements),
+ });
+};
+
+const hideOutline = () => {
+ selectedInstanceOutlineStore.set(undefined);
+};
+
+const calculateUnitSizes = (element: HTMLElement): UnitSizes => {
+ // Based on this https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions/8876069#8876069
+ // this is crossbrowser way to get viewport sizes vw vh in px
+ const vw =
+ Math.max(document.documentElement.clientWidth, window.innerWidth) / 100;
+ const vh =
+ Math.max(document.documentElement.clientHeight, window.innerHeight) / 100;
+
+ // em in px is equal to current computed style for font size
+ const em = Number.parseFloat(getComputedStyle(element).fontSize);
+
+ // rem in px is equal to root computed style for font size
+ const rem = Number.parseFloat(
+ getComputedStyle(document.documentElement).fontSize
+ );
+
+ // we create a node with 1ch width, measure it in px and remove it
+ const node = document.createElement("div");
+ node.style.width = "1ch";
+ node.style.position = "absolute";
+ element.appendChild(node);
+ const ch = Number.parseFloat(getComputedStyle(node).width);
+ element.removeChild(node);
+
+ return {
+ ch, // 1ch in pixels
+ vw, // 1vw in pixels
+ vh, // 1vh in pixels
+ em, // 1em in pixels
+ rem, // 1rem in pixels
+ px: 1, // always 1, simplifies conversions and types, i.e valueTo = valueFrom * unitSizes[from] / unitSizes[to]
+ };
+};
+
+export const subscribeSelectedInstance = (
+ selectedInstanceSelector: InstanceSelector,
+ queueTask: (task: () => void) => void
+) => {
+ if (selectedInstanceSelector.length === 0) {
+ return;
+ }
+
+ const instanceId = selectedInstanceSelector[0];
+ // setDataCollapsed
+
+ let elements = getElementsByInstanceSelector(selectedInstanceSelector);
+
+ if (elements.length === 0) {
+ return;
+ }
+
+ elements[0].scrollIntoView({
+ behavior: "smooth",
+ block: "nearest",
+ });
+
+ const updateElements = () => {
+ elements = getElementsByInstanceSelector(selectedInstanceSelector);
+ };
+
+ const updateDataCollapsed = () => {
+ if (elements.length === 0) {
+ return;
+ }
+
+ for (const element of elements) {
+ const selectorId = element.getAttribute(selectorIdAttribute);
+ if (selectorId === null) {
+ continue;
+ }
+
+ const instanceSelector = selectorId.split(",");
+ if (instanceSelector.length === 0) {
+ continue;
+ }
+
+ setDataCollapsed(instanceSelector[0], false);
+ }
+
+ // Synchronously execute setDataCollapsed to calculate right outline
+ // This fixes an issue, when new element outline was calulated before collapsed elements calculations
+ setDataCollapsed(instanceId, true);
+ };
+
+ updateDataCollapsed();
+
+ const showOutline = () => {
+ if (isResizingCanvasStore.get()) {
+ return;
+ }
+ setOutline(instanceId, elements);
+ };
+ // effect close to rendered element also catches dnd remounts
+ // so actual state is always provided here
+ showOutline();
+
+ const updateStores = () => {
+ if (elements.length === 0) {
+ return;
+ }
+
+ const element = elements[0];
+ // trigger style recomputing every time instance styles are changed
+ selectedInstanceBrowserStyleStore.set(getBrowserStyle(element));
+
+ // Map self and ancestor instance ids to tag names
+ const instanceToTag = new Map<Instance["id"], HtmlTags>();
+ for (
+ let ancestorOrSelf: HTMLElement | null = element;
+ ancestorOrSelf !== null;
+ ancestorOrSelf = ancestorOrSelf.parentElement
+ ) {
+ const tagName = ancestorOrSelf.tagName.toLowerCase();
+ const instanceId = ancestorOrSelf.getAttribute(idAttribute);
+
+ if (isHtmlTag(tagName) && instanceId !== null) {
+ instanceToTag.set(instanceId, tagName);
+ }
+ }
+
+ selectedInstanceIntanceToTagStore.set(instanceToTag);
+
+ const unitSizes = calculateUnitSizes(element);
+ selectedInstanceUnitSizesStore.set(unitSizes);
+ };
+
+ let updateStoreTimeouHandle: undefined | ReturnType<typeof setTimeout>;
+
+ const updateStoresDebounced = () => {
+ clearTimeout(updateStoreTimeouHandle);
+ updateStoreTimeouHandle = setTimeout(updateStores, 100);
+ };
+
+ const update = () => {
+ queueTask(() => {
+ updateElements();
+ // Having hover etc, element can have no size because of that
+ // Newly created element can have 0 size
+ updateDataCollapsed();
+ // contentRect has wrong x/y values for absolutely positioned element.
+ // getBoundingClientRect is used instead.
+ showOutline();
+
+ // Cause serious performance issues, use debounced version
+ // The result of stores is not needed immediately
+ updateStoresDebounced();
+
+ // Having that elements can be changed (i.e. div => address tag change, observe again)
+ updateObservers();
+ });
+ };
+
+ // Lightweight update
+ const updateOutline = () => {
+ queueTask(() => {
+ showOutline();
+ });
+ };
+
+ const resizeObserver = new ResizeObserver(update);
+
+ // detect movement of the element within same parent
+ // React prevent remount when key stays the same
+ const mutationObserver = new MutationObserver(update);
+
+ const updateObservers = () => {
+ for (const element of elements) {
+ resizeObserver.observe(element);
+ const parent = element?.parentElement;
+ if (parent) {
+ mutationObserver.observe(parent, { childList: true });
+ }
+ }
+ };
+
+ const bodyStyleMutationObserver = new MutationObserver(updateOutline);
+ // previewStyle variables
+ bodyStyleMutationObserver.observe(document.body, {
+ attributes: true,
+ attributeFilter: ["style", "class"],
+ });
+
+ updateObservers();
+
+ const unsubscribeStylesIndexStore = stylesIndexStore.subscribe(update);
+ const unsubscribeInstancesStore = instancesStore.subscribe(update);
+ const unsubscribePropsStore = propsStore.subscribe(update);
+ const unsubscribeDataSourceValuesStore =
+ dataSourceValuesStore.subscribe(update);
+
+ const unsubscribeIsResizingCanvas = isResizingCanvasStore.subscribe(
+ (isResizing) => {
+ if (isResizing && selectedInstanceOutlineStore.get()) {
+ return hideOutline();
+ }
+ showOutline();
+ }
+ );
+
+ const unsubscribeScrollState = subscribeScrollState({
+ onScrollStart() {
+ hideOutline();
+ },
+ onScrollEnd() {
+ showOutline();
+ },
+ });
+
+ const unsubscribeWindowResize = subscribeWindowResize({
+ onResizeStart() {
+ hideOutline();
+ },
+ onResizeEnd() {
+ showOutline();
+ },
+ });
+
+ selectedInstanceRenderStateStore.set("mounted");
+
+ return () => {
+ clearTimeout(updateStoreTimeouHandle);
+ hideOutline();
+ selectedInstanceRenderStateStore.set("pending");
+ resizeObserver.disconnect();
+ mutationObserver.disconnect();
+ bodyStyleMutationObserver.disconnect();
+ unsubscribeIsResizingCanvas();
+ unsubscribeScrollState();
+ unsubscribeWindowResize();
+ unsubscribeStylesIndexStore();
+ unsubscribeInstancesStore();
+ unsubscribePropsStore();
+ unsubscribeDataSourceValuesStore();
+ };
+};
diff --git a/apps/builder/app/shared/dom-utils.ts b/apps/builder/app/shared/dom-utils.ts
index 9331132d82..9b6c90b2a3 100644
--- a/apps/builder/app/shared/dom-utils.ts
+++ b/apps/builder/app/shared/dom-utils.ts
@@ -1,6 +1,7 @@
import type { Instance } from "@webstudio-is/project-build";
import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";
import type { InstanceSelector } from "./tree-utils";
+import { getIsVisuallyHidden } from "./visually-hidden";
export const getInstanceIdFromElement = (
element: Element
@@ -33,6 +34,42 @@ export const getElementByInstanceSelector = (
);
};
+/**
+ * Get root visible elements, even if instance
+ **/
+export const getElementsByInstanceSelector = (
+ instanceSelector: InstanceSelector | Readonly<InstanceSelector>
+) => {
+ const descendantsOrSelf = [
+ ...document.querySelectorAll<HTMLElement>(
+ `[${selectorIdAttribute}$="${instanceSelector.join(",")}"]`
+ ),
+ ].filter((element) => getIsVisuallyHidden(element) === false);
+
+ const visibleIdSelectors = descendantsOrSelf.map(
+ (element) => element.getAttribute(selectorIdAttribute) ?? ""
+ );
+
+ // Find root selectors (i.e. selectors that are not descendants of other selectors)
+ let rootSelectors = [...visibleIdSelectors];
+ const isDescendant = (testSelector: string, selector: string) =>
+ testSelector.endsWith(`,${selector}`);
+
+ for (const selector of visibleIdSelectors) {
+ rootSelectors = rootSelectors.filter(
+ (rootSelector) => isDescendant(rootSelector, selector) === false
+ );
+ }
+
+ const rootSelectorSet = new Set(rootSelectors);
+
+ const rootElements = descendantsOrSelf.filter((element) =>
+ rootSelectorSet.has(element.getAttribute(selectorIdAttribute) ?? "")
+ );
+
+ return rootElements;
+};
+
type Rect = {
top: number;
right: number;
@@ -49,21 +86,27 @@ const sumRects = (first: Rect, second: Rect) => {
};
};
-export const getAllElementsBoundingBox = (element: Element): DOMRect => {
- const rect = element.getBoundingClientRect();
- if (element.children.length === 0) {
- return rect;
- }
- // possible display: contents
- if (rect.width !== 0 || rect.height !== 0) {
- return rect;
+export const getAllElementsBoundingBox = (elements: Element[]): DOMRect => {
+ const rects: Rect[] = [];
+
+ if (elements.length === 0) {
+ return DOMRect.fromRect({ width: 0, height: 0, x: 0, y: 0 });
}
- const rects: Rect[] = [];
+ for (const element of elements) {
+ const rect = element.getBoundingClientRect();
- for (const child of element.children) {
- const childRect = getAllElementsBoundingBox(child);
// possible display: contents
+ if (rect.width !== 0 || rect.height !== 0) {
+ rects.push(rect);
+ continue;
+ }
+
+ if (element.children.length === 0) {
+ continue;
+ }
+
+ const childRect = getAllElementsBoundingBox([...element.children]);
if (childRect.width !== 0 || childRect.height !== 0) {
const { top, right, bottom, left } = childRect;
rects.push({ top, right, bottom, left });
@@ -71,10 +114,12 @@ export const getAllElementsBoundingBox = (element: Element): DOMRect => {
}
if (rects.length === 0) {
- return rect;
+ // To preserve position even if width/height is 0
+ return elements[0].getBoundingClientRect();
}
const { top, right, bottom, left } = rects.reduce(sumRects);
+
return DOMRect.fromRect({
x: left,
y: top,
diff --git a/apps/builder/app/canvas/features/webstudio-component/visually-hidden.ts b/apps/builder/app/shared/visually-hidden.ts
similarity index 78%
rename from apps/builder/app/canvas/features/webstudio-component/visually-hidden.ts
rename to apps/builder/app/shared/visually-hidden.ts
index 161469cb68..b465445c52 100644
--- a/apps/builder/app/canvas/features/webstudio-component/visually-hidden.ts
+++ b/apps/builder/app/shared/visually-hidden.ts
@@ -1,5 +1,13 @@
-import { useState, type RefObject, useEffect } from "react";
-
+/**
+ * Radix's VisuallyHiddenPrimitive.Root https://github.com/radix-ui/primitives/blob/main/packages/react/visually-hidden/src/VisuallyHidden.tsx
+ * component makes content from hidden elements accessible to screen readers.
+ * react-aria VisuallyHidden https://github.com/adobe/react-spectrum/blob/e4bc3269fa41aa096700445c6bfa9c8620545e6a/packages/%40react-aria/visually-hidden/src/VisuallyHidden.tsx#L32-L43
+ * The problem we're addressing is that the Radix and similar frameworks reuse the same Content children
+ * for VisuallyHiddenPrimitive.Root within the Tooltip and similar components.
+ * Using the same Content children, however, leads to duplicated React elements, breaking our 'isSelected' logic.
+ * To prevent this, we check if an instance is a descendant of VisuallyHiddenPrimitive.Root, and if so,
+ * we avoid rendering it.
+ */
export const getIsVisuallyHidden = (currentElement: HTMLElement) => {
for (
let element: HTMLElement | null = currentElement;
@@ -18,25 +26,3 @@ export const getIsVisuallyHidden = (currentElement: HTMLElement) => {
}
return false;
};
-
-/**
- * Radix's VisuallyHiddenPrimitive.Root https://github.com/radix-ui/primitives/blob/main/packages/react/visually-hidden/src/VisuallyHidden.tsx
- * component makes content from hidden elements accessible to screen readers.
- * react-aria VisuallyHidden https://github.com/adobe/react-spectrum/blob/e4bc3269fa41aa096700445c6bfa9c8620545e6a/packages/%40react-aria/visually-hidden/src/VisuallyHidden.tsx#L32-L43
- * The problem we're addressing is that the Radix and similar frameworks reuse the same Content children
- * for VisuallyHiddenPrimitive.Root within the Tooltip and similar components.
- * Using the same Content children, however, leads to duplicated React elements, breaking our 'isSelected' logic.
- * To prevent this, we check if an instance is a descendant of VisuallyHiddenPrimitive.Root, and if so,
- * we avoid rendering it.
- */
-export const useIsVisuallyHidden = (ref: RefObject<HTMLElement>) => {
- const [isVisuallyHidden, setIsVisuallyHidden] = useState(false);
-
- useEffect(() => {
- if (ref.current !== null && getIsVisuallyHidden(ref.current)) {
- setIsVisuallyHidden(true);
- }
- }, [ref]);
-
- return isVisuallyHidden;
-};
diff --git a/packages/sdk-components-react-radix/src/collapsible.tsx b/packages/sdk-components-react-radix/src/collapsible.tsx
index 35eaa86a72..40ebb81f58 100644
--- a/packages/sdk-components-react-radix/src/collapsible.tsx
+++ b/packages/sdk-components-react-radix/src/collapsible.tsx
@@ -9,23 +9,11 @@ import {
Children,
} from "react";
import { Root, Trigger, Content } from "@radix-ui/react-collapsible";
-import {
- type WebstudioAttributes,
- splitPropsWithWebstudioAttributes,
-} from "@webstudio-is/react-sdk";
export const Collapsible: ForwardRefExoticComponent<
Omit<ComponentPropsWithRef<typeof Root>, "defaultOpen" | "asChild">
> = Root;
-/**
- * CollapsibleTrigger is HTML-less components.
- * To make them work in our system, we wrap their attributes with a div that has a display: contents property.
- *
- * These divs function like fragments, with all web studio-related attributes attached to them.
- */
-const displayContentsStyle = { display: "contents" };
-
/**
* We're not exposing the 'asChild' property for the Trigger.
* Instead, we're enforcing 'asChild=true' for the Trigger and making it style-less.
@@ -33,18 +21,14 @@ const displayContentsStyle = { display: "contents" };
* which would prevent us from displaying styles properly in the builder.
*/
export const CollapsibleTrigger = forwardRef<
- HTMLDivElement,
- WebstudioAttributes & { children: ReactNode }
+ HTMLButtonElement,
+ { children: ReactNode }
>(({ children, ...props }, ref) => {
const firstChild = Children.toArray(children)[0];
- const [webstudioAttributes, restProps] =
- splitPropsWithWebstudioAttributes(props);
return (
- <div ref={ref} style={displayContentsStyle} {...webstudioAttributes}>
- <Trigger asChild={true} {...restProps}>
- {firstChild ?? <button>Add button</button>}
- </Trigger>
- </div>
+ <Trigger asChild={true} ref={ref} {...props}>
+ {firstChild ?? <button>Add button</button>}
+ </Trigger>
);
});
diff --git a/packages/sdk-components-react-radix/src/dialog.tsx b/packages/sdk-components-react-radix/src/dialog.tsx
index aeec442f12..efacd854e3 100644
--- a/packages/sdk-components-react-radix/src/dialog.tsx
+++ b/packages/sdk-components-react-radix/src/dialog.tsx
@@ -2,10 +2,6 @@
// We can't use .displayName until this is merged https://github.com/styleguidist/react-docgen-typescript/pull/449
import * as DialogPrimitive from "@radix-ui/react-dialog";
-import {
- splitPropsWithWebstudioAttributes,
- type WebstudioAttributes,
-} from "@webstudio-is/react-sdk";
import {
forwardRef,
@@ -23,32 +19,15 @@ type BuilderDialogProps = {
isOpen: "initial" | "open" | "closed";
};
-/**
- * Dialog and DialogTrigger are HTML-less components.
- * To make them work in our system, we wrap their attributes with a div that has a display: contents property.
- *
- * These divs function like fragments, with all web studio-related attributes attached to them.
- */
-const DisplayContentsStyle = { display: "contents" };
-
export const Dialog = forwardRef<
ElementRef<"div">,
- WebstudioAttributes &
- ComponentPropsWithoutRef<typeof DialogPrimitive.Root> &
- BuilderDialogProps
+ ComponentPropsWithoutRef<typeof DialogPrimitive.Root> & BuilderDialogProps
>(({ open: openProp, isOpen, ...props }, ref) => {
- const [webstudioAttributes, restProps] =
- splitPropsWithWebstudioAttributes(props);
-
const open =
openProp ??
(isOpen === "open" ? true : isOpen === "closed" ? false : undefined);
- return (
- <div ref={ref} style={DisplayContentsStyle} {...webstudioAttributes}>
- <DialogPrimitive.Root open={open} {...restProps} />
- </div>
- );
+ return <DialogPrimitive.Root open={open} {...props} />;
});
/**
@@ -59,18 +38,14 @@ export const Dialog = forwardRef<
*/
export const DialogTrigger = forwardRef<
ElementRef<"div">,
- WebstudioAttributes & { children: ReactNode }
+ { children: ReactNode }
>(({ children, ...props }, ref) => {
const firstChild = Children.toArray(children)[0];
- const [webstudioAttributes, restProps] =
- splitPropsWithWebstudioAttributes(props);
return (
- <div ref={ref} style={DisplayContentsStyle} {...webstudioAttributes}>
- <DialogPrimitive.Trigger asChild={true} {...restProps}>
- {firstChild ?? <button>Add button or link</button>}
- </DialogPrimitive.Trigger>
- </div>
+ <DialogPrimitive.Trigger asChild={true} {...props}>
+ {firstChild ?? <button>Add button or link</button>}
+ </DialogPrimitive.Trigger>
);
});
diff --git a/packages/sdk-components-react-radix/src/popover.tsx b/packages/sdk-components-react-radix/src/popover.tsx
index bc424ab4be..0fe82a430c 100644
--- a/packages/sdk-components-react-radix/src/popover.tsx
+++ b/packages/sdk-components-react-radix/src/popover.tsx
@@ -2,10 +2,6 @@
// We can't use .displayName until this is merged https://github.com/styleguidist/react-docgen-typescript/pull/449
import * as PopoverPrimitive from "@radix-ui/react-popover";
-import {
- splitPropsWithWebstudioAttributes,
- type WebstudioAttributes,
-} from "@webstudio-is/react-sdk";
import {
forwardRef,
@@ -23,32 +19,15 @@ type BuilderPopoverProps = {
isOpen: "initial" | "open" | "closed";
};
-/**
- * Popover and PopoverTrigger are HTML-less components.
- * To make them work in our system, we wrap their attributes with a div that has a display: contents property.
- *
- * These divs function like fragments, with all web studio-related attributes attached to them.
- */
-const DisplayContentsStyle = { display: "contents" };
-
export const Popover = forwardRef<
ElementRef<"div">,
- WebstudioAttributes &
- ComponentPropsWithoutRef<typeof PopoverPrimitive.Root> &
- BuilderPopoverProps
+ ComponentPropsWithoutRef<typeof PopoverPrimitive.Root> & BuilderPopoverProps
>(({ open: openProp, isOpen, ...props }, ref) => {
- const [webstudioAttributes, restProps] =
- splitPropsWithWebstudioAttributes(props);
-
const open =
openProp ??
(isOpen === "open" ? true : isOpen === "closed" ? false : undefined);
- return (
- <div ref={ref} style={DisplayContentsStyle} {...webstudioAttributes}>
- <PopoverPrimitive.Root open={open} {...restProps} />
- </div>
- );
+ return <PopoverPrimitive.Root open={open} {...props} />;
});
/**
@@ -58,19 +37,15 @@ export const Popover = forwardRef<
* which would prevent us from displaying styles properly in the builder.
*/
export const PopoverTrigger = forwardRef<
- ElementRef<"div">,
- WebstudioAttributes & { children: ReactNode }
+ ElementRef<"button">,
+ { children: ReactNode }
>(({ children, ...props }, ref) => {
const firstChild = Children.toArray(children)[0];
- const [webstudioAttributes, restProps] =
- splitPropsWithWebstudioAttributes(props);
return (
- <div ref={ref} style={DisplayContentsStyle} {...webstudioAttributes}>
- <PopoverPrimitive.Trigger asChild={true} {...restProps}>
- {firstChild ?? <button>Add button or link</button>}
- </PopoverPrimitive.Trigger>
- </div>
+ <PopoverPrimitive.Trigger asChild={true} ref={ref} {...props}>
+ {firstChild ?? <button>Add button or link</button>}
+ </PopoverPrimitive.Trigger>
);
});
diff --git a/packages/sdk-components-react-radix/src/tooltip.tsx b/packages/sdk-components-react-radix/src/tooltip.tsx
index 70c2c62cc9..3921a9890b 100644
--- a/packages/sdk-components-react-radix/src/tooltip.tsx
+++ b/packages/sdk-components-react-radix/src/tooltip.tsx
@@ -2,10 +2,6 @@
// We can't use .displayName until this is merged https://github.com/styleguidist/react-docgen-typescript/pull/449
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
-import {
- splitPropsWithWebstudioAttributes,
- type WebstudioAttributes,
-} from "@webstudio-is/react-sdk";
import {
forwardRef,
@@ -23,33 +19,18 @@ type BuilderTooltipProps = {
isOpen: "initial" | "open" | "closed";
};
-/**
- * Tooltip and TooltipTrigger are HTML-less components.
- * To make them work in our system, we wrap their attributes with a div that has a display: contents property.
- *
- * These divs function like fragments, with all web studio-related attributes attached to them.
- */
-const DisplayContentsStyle = { display: "contents" };
-
export const Tooltip = forwardRef<
ElementRef<"div">,
- WebstudioAttributes &
- ComponentPropsWithoutRef<typeof TooltipPrimitive.Root> &
- BuilderTooltipProps
+ ComponentPropsWithoutRef<typeof TooltipPrimitive.Root> & BuilderTooltipProps
>(({ open: openProp, isOpen, ...props }, ref) => {
- const [webstudioAttributes, restProps] =
- splitPropsWithWebstudioAttributes(props);
-
const open =
openProp ??
(isOpen === "open" ? true : isOpen === "closed" ? false : undefined);
return (
- <div ref={ref} style={DisplayContentsStyle} {...webstudioAttributes}>
- <TooltipPrimitive.Provider>
- <TooltipPrimitive.Root open={open} {...restProps} />
- </TooltipPrimitive.Provider>
- </div>
+ <TooltipPrimitive.Provider>
+ <TooltipPrimitive.Root open={open} {...props} />
+ </TooltipPrimitive.Provider>
);
});
@@ -60,19 +41,15 @@ export const Tooltip = forwardRef<
* which would prevent us from displaying styles properly in the builder.
*/
export const TooltipTrigger = forwardRef<
- ElementRef<"div">,
- WebstudioAttributes & { children: ReactNode }
+ ElementRef<"button">,
+ { children: ReactNode }
>(({ children, ...props }, ref) => {
const firstChild = Children.toArray(children)[0];
- const [webstudioAttributes, restProps] =
- splitPropsWithWebstudioAttributes(props);
return (
- <div ref={ref} style={DisplayContentsStyle} {...webstudioAttributes}>
- <TooltipPrimitive.Trigger asChild={true} {...restProps}>
- {firstChild ?? <button>Add button or link</button>}
- </TooltipPrimitive.Trigger>
- </div>
+ <TooltipPrimitive.Trigger asChild={true} ref={ref} {...props}>
+ {firstChild ?? <button>Add button or link</button>}
+ </TooltipPrimitive.Trigger>
);
});