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
Track selected rect close to element (#627)
Bogdan Chadkin122bd8adb534
diff --git a/apps/designer/app/canvas/canvas.tsx b/apps/designer/app/canvas/canvas.tsxindex 6c622f52a0..b22a7b3ae4 100644--- a/apps/designer/app/canvas/canvas.tsx+++ b/apps/designer/app/canvas/canvas.tsx@@ -19,7 +19,6 @@ import {usePopulateRootInstance,usePublishRootInstance,usePublishSelectedInstanceData,- usePublishSelectedInstanceDataRect,usePublishTextEditingInstanceId,useReparentInstance,useSetHoveredInstance,@@ -150,7 +149,6 @@ const DesignMode = ({ treeId, buildId }: DesignModeProps) => {usePublishHoveredInstanceData();useSync({ buildId, treeId });useUpdateSelectedInstance();- usePublishSelectedInstanceDataRect();useUnselectInstance();usePublishScrollState();useSubscribeScrollState();diff --git a/apps/designer/app/canvas/features/wrapper-component/selected-instance-connector.ts b/apps/designer/app/canvas/features/wrapper-component/selected-instance-connector.tsnew file mode 100644index 0000000000..828778a248--- /dev/null+++ b/apps/designer/app/canvas/features/wrapper-component/selected-instance-connector.ts@@ -0,0 +1,92 @@+import { useCallback, useEffect } from "react";+import type { Instance } from "@webstudio-is/react-sdk";+import { useUserProps } from "@webstudio-is/react-sdk";+import { publish, subscribeAll } from "~/shared/pubsub";+import { useScrollState } from "~/shared/dom-hooks";++const publishSelectedRect = (element: HTMLElement) => {+ publish({+ type: "selectedInstanceRect",+ payload: element.getBoundingClientRect(),+ });+};++export const SelectedInstanceConnector = ({+ instanceElementRef,+ instanceProps,+}: {+ instanceElementRef: { current: undefined | HTMLElement };+ instance: Instance;+ instanceProps: ReturnType<typeof useUserProps>;+}) => {+ useEffect(() => {+ const element = instanceElementRef.current;+ if (element === undefined) {+ return;+ }++ // effect close to rendered element also catches dnd remounts+ // so actual state is always provided here+ publishSelectedRect(element);++ // ResizeObserver does not work for inline elements+ const canObserve = getComputedStyle(element).display !== "inline";++ const resizeObserver = new ResizeObserver(() => {+ // contentRect has wrong x/y values for absolutely positioned element.+ // getBoundingClientRect is used instead.+ publishSelectedRect(element);+ });+ resizeObserver.observe(element);++ // detect movement of the element within same parent+ // React prevent remount when key stays the same+ const mutationObserver = new window.MutationObserver(() => {+ publishSelectedRect(element);+ });+ const parent = element?.parentElement;+ if (parent) {+ mutationObserver.observe(parent, { childList: true });+ }++ let unsubscribeTreeChange: undefined | (() => void);+ if (canObserve === false) {+ // recompute inline elements on tree changes+ unsubscribeTreeChange = subscribeAll((type) => {+ if (+ type === "updateProps" ||+ type === "deleteProp" ||+ type === "insertInstance" ||+ type === "deleteInstance" ||+ type === "reparentInstance" ||+ type === "updateStyle" ||+ type.startsWith("previewStyle:")+ ) {+ publishSelectedRect(element);+ }+ });+ }++ return () => {+ resizeObserver.disconnect();+ mutationObserver.disconnect();+ unsubscribeTreeChange?.();+ };++ // instance props may change dom element+ }, [instanceElementRef, instanceProps]);++ const onScrollEnd = useCallback(() => {+ const element = instanceElementRef.current;+ if (element === undefined) {+ return;+ }+ publishSelectedRect(element);+ }, [instanceElementRef]);++ useScrollState({+ onScrollEnd,+ });++ return null;+};diff --git a/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx b/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsxindex 4d4497f5ea..2e545f8615 100644--- a/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx+++ b/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx@@ -1,4 +1,5 @@-import { MouseEvent, FormEvent } from "react";+import type { MouseEvent, FormEvent } from "react";+import { useRef } from "react";import { Suspense, lazy, useCallback } from "react";import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";import {@@ -10,9 +11,13 @@ import {idAttribute,} from "@webstudio-is/react-sdk";import { useTextEditingInstanceId } from "~/shared/nano-states";-import { useSelectedElement } from "~/canvas/shared/nano-states";+import {+ useSelectedElement,+ useSelectedInstance,+} from "~/canvas/shared/nano-states";import { useCssRules } from "~/canvas/shared/styles";import { publish } from "~/shared/pubsub";+import { SelectedInstanceConnector } from "./selected-instance-connector";const TextEditor = lazy(() => import("../text-editor"));@@ -21,16 +26,15 @@ const ContentEditable = ({elementRef,...props}: {- // eslint-disable-next-line- Component: any;- elementRef: (element: null | HTMLElement) => void;+ Component: ReturnType<typeof getComponent>;+ elementRef: (element: undefined | HTMLElement) => void;}) => {const [editor] = useLexicalComposerContext();const ref = useCallback((rootElement: null | HTMLElement) => {editor.setRootElement(rootElement);- elementRef(rootElement);+ elementRef(rootElement ?? undefined);},[editor, elementRef]);@@ -48,20 +52,23 @@ export const WrapperComponentDev = ({instance,children,onChangeChildren,- ...rest}: WrapperComponentDevProps) => {useCssRules(instance);const [editingInstanceId, setTextEditingInstanceId] =useTextEditingInstanceId();+ const [selectedInstance] = useSelectedInstance();const [, setSelectedElement] = useSelectedElement();+ const instanceElementRef = useRef<HTMLElement>();+const refCallback = useCallback(- (element) => {+ (element: undefined | HTMLElement) => {// When entering text editing we unmount the instance element, so we need to update the reference, otherwise we have a detached element referenced and bounding box will be wrong.- if (element !== null) {+ if (element !== undefined) {setSelectedElement(element);}+ instanceElementRef.current = element;},[setSelectedElement]);@@ -74,10 +81,8 @@ export const WrapperComponentDev = ({const props = {...userProps,- ...rest,...readonlyProps,tabIndex: 0,- // @todo stop using id to free it up to the user// we should replace id, data-component and data-id with "data-ws"=instance.id and grab the rest always over the id// for this we need to also make search by id fastid: instance.id,@@ -98,7 +103,20 @@ export const WrapperComponentDev = ({};const instanceElement = (- <Component {...props}>{renderWrapperComponentChildren(children)}</Component>+ <>+ {selectedInstance?.id === instance.id && (+ <SelectedInstanceConnector+ instanceElementRef={instanceElementRef}+ instance={instance}+ instanceProps={userProps}+ />+ )}+ {/* Component includes many types and it's hard to provide right ref type with useRef */}+ {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}+ <Component {...props} ref={instanceElementRef as any}>+ {renderWrapperComponentChildren(children)}+ </Component>+ </>);if (editingInstanceId !== instance.id) {diff --git a/apps/designer/app/canvas/shared/instance.ts b/apps/designer/app/canvas/shared/instance.tsindex 04f05c9840..f5e124714e 100644--- a/apps/designer/app/canvas/shared/instance.ts+++ b/apps/designer/app/canvas/shared/instance.ts@@ -28,7 +28,6 @@ import {useRootInstance,useTextEditingInstanceId,} from "~/shared/nano-states";-import { useMeasureInstance } from "~/canvas/shared/use-measure-instance";import {findInstanceByElement,getInstanceElementById,@@ -250,24 +249,6 @@ export const usePublishRootInstance = () => {}, [rootInstance]);};-const publishRect = (rect: DOMRect) => {- publish({- type: "selectedInstanceRect",- payload: rect,- });-};--export const usePublishSelectedInstanceDataRect = () => {- const [element] = useSelectedElement();- const rect = useMeasureInstance(element);-- useEffect(() => {- if (rect) {- publishRect(rect);- }- }, [rect]);-};-export const useSetHoveredInstance = () => {const [rootInstance] = useRootInstance();const [, setHoveredInstance] = useHoveredInstance();diff --git a/apps/designer/app/canvas/shared/use-measure-instance.ts b/apps/designer/app/canvas/shared/use-measure-instance.tsdeleted file mode 100644index 3f0bc3ee70..0000000000--- a/apps/designer/app/canvas/shared/use-measure-instance.ts+++ /dev/null@@ -1,47 +0,0 @@-import { useCallback, useEffect, useMemo } from "react";-import { useMeasure, useRectState } from "~/shared/dom-hooks";-import { type PubsubMap, useSubscribeAll } from "~/shared/pubsub";--const useSubscribeTreeChange = (onChange: () => void, isEnabled: boolean) => {- const callback = useMemo(() => {- if (isEnabled === false) {- return () => null;- }- return (type: keyof PubsubMap) => {- if (- type === "updateProps" ||- type === "deleteProp" ||- type === "insertInstance" ||- type === "deleteInstance" ||- type === "reparentInstance" ||- type === "updateStyle" ||- type.startsWith("previewStyle:")- ) {- onChange();- }- };- }, [onChange, isEnabled]);-- useSubscribeAll(callback);-};--// A version of useMeasure capable of measuring inlined elements, but works only within canvas.-export const useMeasureInstance = (element: HTMLElement | undefined) => {- const { canObserve, rect: baseRect } = useMeasure(element);-- const [rect, setRect] = useRectState();-- const handleChange = useCallback(() => {- setRect(element && element.getBoundingClientRect());- }, [element, setRect]);-- useSubscribeTreeChange(handleChange, canObserve === false);-- useEffect(() => {- if (canObserve === false) {- handleChange();- }- }, [handleChange, canObserve]);-- return canObserve ? baseRect : rect;-};diff --git a/apps/designer/app/canvas/shared/use-track-hovered-element.ts b/apps/designer/app/canvas/shared/use-track-hovered-element.tsindex fe47faf493..7559e1baa7 100644--- a/apps/designer/app/canvas/shared/use-track-hovered-element.ts+++ b/apps/designer/app/canvas/shared/use-track-hovered-element.ts@@ -1,5 +1,4 @@import { useEffect, useState } from "react";-import { useSelectedElement } from "./nano-states";import { useRootInstance } from "~/shared/nano-states";// @todo: importing normally doesn't work in Jest for some reason@@ -14,7 +13,6 @@ export const useTrackHoveredElement = (onChange: (element: HTMLElement | undefined) => void) => {const [rootInstance] = useRootInstance();- const [selectedElement] = useSelectedElement();const [hoveredElement, setHoveredElement] = useState<HTMLElement>();useDebounce(@@ -45,5 +43,5 @@ export const useTrackHoveredElement = (window.removeEventListener("mouseover", handleMouseOver);window.removeEventListener("mouseout", handleMouseOut);};- }, [rootInstance, selectedElement, onChange]);+ }, [rootInstance, onChange]);};diff --git a/apps/designer/app/shared/dom-hooks/index.ts b/apps/designer/app/shared/dom-hooks/index.tsindex 0a86bfe9fd..0e0923f601 100644--- a/apps/designer/app/shared/dom-hooks/index.ts+++ b/apps/designer/app/shared/dom-hooks/index.ts@@ -1,3 +1,2 @@export * from "./use-window-resize";-export * from "./use-measure";export * from "./use-scroll-state";diff --git a/apps/designer/app/shared/dom-hooks/use-measure.ts b/apps/designer/app/shared/dom-hooks/use-measure.tsdeleted file mode 100644index 2f8e46865e..0000000000--- a/apps/designer/app/shared/dom-hooks/use-measure.ts+++ /dev/null@@ -1,75 +0,0 @@-// This hook is based on https://github.com/streamich/react-use/blob/master/src/useMeasure.ts-// The problem is that contentRect has wrong x/y values for absolutely positioned element.-// We have to use getBoundingClientRect instead.-// @todo optimize for the case when many consumers need to measure the same element--import { useCallback, useEffect, useState } from "react";-import { useScrollState } from "./use-scroll-state";--export const useRectState = () => {- const [rect, setRectBase] = useState<DOMRect>();- const setRect = useCallback(- (nextRect: DOMRect | undefined) =>- setRectBase((currentRect) => {- if (- currentRect === undefined ||- nextRect === undefined ||- currentRect.x !== nextRect.x ||- currentRect.y !== nextRect.y ||- currentRect.width !== nextRect.width ||- currentRect.height !== nextRect.height- ) {- return nextRect;- }- return currentRect;- }),- []- );- return [rect, setRect] as const;-};--export const useMeasure = (- element: HTMLElement | undefined-): { canObserve: boolean; rect: DOMRect | undefined } => {- const [rect, setRect] = useRectState();- const [isInline, setIsInline] = useState(false);-- const handleChange = useCallback(() => {- setRect(element && element.getBoundingClientRect());- setIsInline(- element ? window.getComputedStyle(element).display === "inline" : false- );- }, [element, setRect]);-- useScrollState({- onScrollEnd: handleChange,- });-- // Detect movement of the element without remounting.- useEffect(() => {- // No need to worry about parent changing while element stays the same.- // React cannot do that. It can only move within the same parent.- const parent = element?.parentElement;- if (parent) {- const observer = new window.MutationObserver(handleChange);- observer.observe(parent, { childList: true });- return () => observer.disconnect();- }- }, [element, handleChange]);-- useEffect(() => {- if (element) {- const observer = new window.ResizeObserver(handleChange);- observer.observe(element);- return () => observer.disconnect();- }- }, [element, handleChange]);-- useEffect(handleChange, [handleChange]);-- return {- // ResizeObserver does not work for inline elements- canObserve: isInline === false,- rect,- };-};diff --git a/apps/designer/app/shared/pubsub/index.ts b/apps/designer/app/shared/pubsub/index.tsindex dc5d39878a..bab035aff5 100644--- a/apps/designer/app/shared/pubsub/index.ts+++ b/apps/designer/app/shared/pubsub/index.ts@@ -4,7 +4,12 @@ import { createPubsub } from "@webstudio-is/react-sdk";// eslint-disable-next-line @typescript-eslint/no-empty-interfaceexport interface PubsubMap {}-export const { publish, usePublish, useSubscribe, useSubscribeAll } =- createPubsub<PubsubMap>();+export const {+ publish,+ usePublish,+ useSubscribe,+ useSubscribeAll,+ subscribeAll,+} = createPubsub<PubsubMap>();export type Publish = typeof publish;export type UsePublish = typeof usePublish;diff --git a/packages/react-sdk/src/pubsub/create.ts b/packages/react-sdk/src/pubsub/create.tsindex 1c615bfd7d..212ddbcee1 100644--- a/packages/react-sdk/src/pubsub/create.ts+++ b/packages/react-sdk/src/pubsub/create.ts@@ -82,5 +82,17 @@ export const createPubsub = <PublishMap>() => {};}, [onAction]);},++ subscribeAll(+ onAction: <Type extends keyof PublishMap>(+ type: Type,+ payload: PublishMap[Type]+ ) => void+ ) {+ emitter.on("*", onAction);+ return () => {+ emitter.off("*", onAction);+ };+ },};};