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
fix: Various Scrub bugs and issues (#4722)
Ivan Starkov8d5b69844a9f
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsxindex 1a34223326..02658c70b9 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx@@ -212,8 +212,12 @@ const useScrub = ({// Returning focus that we've moved abovescrubRef.current?.removeAttribute("tabindex");- inputRef.current?.focus();- inputRef.current?.select();++ // Otherwise selectionchange event can be triggered after 300-1000ms after focus+ requestAnimationFrame(() => {+ inputRef.current?.focus();+ inputRef.current?.select();+ });},shouldHandleEvent,});@@ -817,6 +821,44 @@ export const CssValueInput = ({return () => abort("unmount");}, [abort]);+ useEffect(() => {+ if (inputRef.current === null) {+ return;+ }++ const abortController = new AbortController();++ const options = {+ signal: abortController.signal,+ };++ let focusTime = 0;+ inputRef.current.addEventListener(+ "selectionchange",+ () => {+ if (Date.now() - focusTime < 150) {+ inputRef.current?.select();+ }+ },+ options+ );+ inputRef.current.addEventListener(+ "focus",+ () => {+ if (inputRef.current === null) {+ return;+ }++ focusTime = Date.now();+ },+ options+ );++ return () => {+ abortController.abort();+ };+ }, [inputRef]);+const inputPropsHandleKeyDown = composeEventHandlers(composeEventHandlers(handleUpDownNumeric, inputProps.onKeyDown, {// Pass prevented events to the combobox (e.g., the Escape key doesn't work otherwise, as it's blocked by Radix)@@ -863,7 +905,6 @@ export const CssValueInput = ({// We are setting the value on focus because we might have removed the var() from the value,// but once focused, we need to show the full valueevent.target.value = itemToString(value);- event.target.select();}}}autoFocus={autoFocus}diff --git a/apps/builder/app/shared/copy-paste/init-copy-paste.ts b/apps/builder/app/shared/copy-paste/init-copy-paste.tsindex dadaab8984..4d084212d3 100644--- a/apps/builder/app/shared/copy-paste/init-copy-paste.ts+++ b/apps/builder/app/shared/copy-paste/init-copy-paste.ts@@ -92,13 +92,14 @@ const initPlugins = ({plugins: Array<Plugin>;signal: AbortSignal;}) => {- const handleCopy = async (event: ClipboardEvent) => {+ const handleCopy = (event: ClipboardEvent) => {if (validateClipboardEvent(event) === false) {return;}for (const { mimeType = defaultMimeType, onCopy } of plugins) {- const data = await onCopy?.();+ const data = onCopy?.();+if (data) {// must prevent default, otherwise setData() will not workevent.preventDefault();diff --git a/packages/design-system/src/components/input-field.tsx b/packages/design-system/src/components/input-field.tsxindex d12236db55..b783a431d5 100644--- a/packages/design-system/src/components/input-field.tsx+++ b/packages/design-system/src/components/input-field.tsx@@ -89,6 +89,7 @@ const containerStyle = css({},"&:focus-within": {borderColor: theme.colors.borderFocus,+ outline: "none",},"&:has([data-input-field-input][data-color=error])": {borderColor: theme.colors.borderDestructiveMain,@@ -99,6 +100,7 @@ const containerStyle = css({"&:has([data-input-field-input]:is(:disabled, [aria-disabled=true]))": {backgroundColor: theme.colors.backgroundInputDisabled,},+variants: {variant: {chromeless: {diff --git a/packages/design-system/src/components/primitives/numeric-gesture-control.ts b/packages/design-system/src/components/primitives/numeric-gesture-control.tsindex 3dd7fc264e..22bfdf4a59 100644--- a/packages/design-system/src/components/primitives/numeric-gesture-control.ts+++ b/packages/design-system/src/components/primitives/numeric-gesture-control.ts@@ -15,6 +15,33 @@*/import { clamp } from "@react-aria/utils";+import { css } from "../../stitches.config";++const scrubUI = css({+ "*": {+ userSelect: "none!important",+ touchAction: "none!important",+ },+});++const cursorUI = css({+ variants: {+ direction: {+ horizontal: {+ cursor: "ew-resize!important",+ "*": {+ cursor: "ew-resize!important",+ },+ },+ vertical: {+ cursor: "ns-resize!important",+ "*": {+ cursor: "ns-resize!important",+ },+ },+ },+ },+});export type NumericScrubDirection = "horizontal" | "vertical";@@ -53,7 +80,6 @@ type NumericScrubState = {value: number;cursor?: SVGElement;direction: NumericScrubDirection;- timerId?: ReturnType<typeof window.setTimeout>;status: "idle" | "scrubbing";};@@ -82,6 +108,41 @@ const preventContextMenu = () => {};};+const scrubTimeout = 150;++const addScrubUi = () => {+ const className = scrubUI();+ const timerId = setTimeout(() => {+ // Fixes Safari hovers during scrubbing+ window.document.documentElement.setAttribute("inert", "true");+ }, scrubTimeout);++ window.document.documentElement.classList.add(className);++ return () => {+ clearTimeout(timerId);+ window.document.documentElement.classList.remove(className);+ window.document.documentElement.removeAttribute("inert");+ };+};++const addCursorUI = (direction: NumericScrubDirection) => {+ const cursorClassNames = cursorUI({ direction }).toString().split(" ");++ const timerId = setTimeout(() => {+ for (const cursorClassName of cursorClassNames) {+ window.document.documentElement.classList.add(cursorClassName);+ }+ }, scrubTimeout);++ return () => {+ for (const cursorClassName of cursorClassNames) {+ window.document.documentElement.classList.remove(cursorClassName);+ }+ clearTimeout(timerId);+ };+};+export const numericScrubControl = (targetNode: HTMLElement | SVGElement,options: NumericScrubOptions@@ -97,35 +158,46 @@ export const numericScrubControl = (onStatusChange,shouldHandleEvent,} = options;- const eventNames = ["pointerup", "pointerdown"] as const;++ const cleanupTasks: Array<() => void> = [];+ const disposeOnCleanup = (fn: () => () => void) => cleanupTasks.push(fn());+const state: NumericScrubState = {// We will read value lazyly in a moment it will be used to avoid having outdated valuevalue: -1,cursor: undefined,direction,- timerId: undefined,status: "idle",};- let exitPointerLock: (() => void) | undefined = undefined;- let restoreUserSelect: (() => void) | undefined = undefined;- let restoreContextMenu: (() => void) | undefined = undefined;+ // The appearance of the custom cursor is delayed, so we need to track the mouse position+ // for its initial placement.+ const mouseState = {+ x: 0,+ y: 0,+ };const cleanup = () => {- targetNode.removeEventListener("pointermove", handleEvent);+ for (const task of [...cleanupTasks.reverse()]) {+ task();+ }if (state.status === "scrubbing") {state.status = "idle";onStatusChange?.("idle");}+ };++ let disposeCursorUI: () => void | undefined;- clearTimeout(state.timerId);- exitPointerLock?.();- exitPointerLock = undefined;- restoreUserSelect?.();- restoreUserSelect = undefined;- restoreContextMenu?.();- restoreContextMenu = undefined;+ // Called on ESC key press or in cases of third-party pointer lock exit.+ const handlePointerLockChange = () => {+ if (document.pointerLockElement !== targetNode) {+ cleanup();+ return;+ }++ disposeCursorUI?.();};// Cannot define `event:` as PointerEvent,@@ -142,9 +214,10 @@ export const numericScrubControl = (switch (type) {case "pointerup": {- const shouldComponentUpdate =- Boolean(state.cursor) && state.status === "scrubbing";+ const shouldComponentUpdate = state.status === "scrubbing";+cleanup();+if (shouldComponentUpdate) {onValueChange?.({type: "scrubend",@@ -153,6 +226,7 @@ export const numericScrubControl = (preventDefault: () => event.preventDefault(),});}+break;}case "pointerdown": {@@ -167,22 +241,64 @@ export const numericScrubControl = (break;}+ mouseState.x = event.clientX;+ mouseState.y = event.clientY;+onStart?.();state.value = getInitialValue();- state.timerId = setTimeout(async () => {- exitPointerLock?.();- exitPointerLock = await requestPointerLock(state, event, targetNode);- }, 150);- targetNode.addEventListener("pointermove", handleEvent);+ disposeOnCleanup(() =>+ requestPointerLock(state, mouseState, event, targetNode)+ );+ disposeOnCleanup(() => addScrubUi());++ disposeCursorUI = addCursorUI(options.direction ?? "horizontal");+ disposeOnCleanup(() => disposeCursorUI);++ disposeOnCleanup(() => {+ const abortController = new AbortController();+ const eventOptions = {+ signal: abortController.signal,+ };++ targetNode.addEventListener("pointermove", handleEvent, eventOptions);++ document.addEventListener(+ "pointerlockchange",+ handlePointerLockChange,+ eventOptions+ );++ targetNode.addEventListener(+ "click",+ (event) => {+ // Prevent the click event from firing during scrubbing+ // Resolves issues with margin scrubbing and opening inputs after scrubbing+ // Fixes unintended click events triggered during canvas resizing+ if (state.status === "scrubbing") {+ event.preventDefault();+ event.stopImmediatePropagation();+ }+ },+ eventOptions+ );++ return () => {+ abortController.abort();+ };+ });+// Pointer event will stop firing on touch after ~300ms because browser starts scrolling the page.- restoreUserSelect = setRootStyle(targetNode, "user-select", "none");+ // restoreUserSelect = setRootStyle(targetNode, "user-select", "none");// In chrome mobile touch simulation, you will get the context menu because tapping and holding// results in a right click.- restoreContextMenu = preventContextMenu();+ disposeOnCleanup(preventContextMenu);break;}case "pointermove": {+ mouseState.x = event.clientX;+ mouseState.y = event.clientY;+const nextValue = getValue(state, movement, options);if (nextValue === state.value) {break;@@ -229,124 +345,150 @@ export const numericScrubControl = (}break;}+ case "pointercancel": {+ cleanup();+ break;+ }+ case "lostpointercapture": {+ if (document.pointerLockElement === null) {+ cleanup();+ }+ break;+ }}};+ const abortController = new AbortController();+ const eventOptions = { signal: abortController.signal };++ const eventNames = [+ "pointerup",+ "pointerdown",+ "pontercancel",+ "lostpointercapture",+ ] as const;eventNames.forEach((eventName) =>- targetNode.addEventListener(eventName, handleEvent)+ targetNode.addEventListener(eventName, handleEvent, eventOptions)+ );++ // Prevents dragging of the input content+ // Dragging breaks the setPointerCapture+ targetNode.addEventListener(+ "dragstart",+ (event) => {+ event.preventDefault();+ },+ eventOptions);return () => {- eventNames.forEach((eventName) =>- targetNode.removeEventListener(eventName, handleEvent)- );+ abortController.abort();cleanup();};};-// If the same property was set while its already in a temporal state, something is wrong with-// the logic on call-site and we need to inform the developer.-const rootStyleTracker = new Map<string, boolean>();--const setRootStyle = (- targetNode: HTMLElement | SVGElement,- property: string,- value: string-) => {- if (rootStyleTracker.has(property)) {- throw new Error(- "setRootStyle is called while the property is already in a temporal state."- );+const requestPointerLockSafe = async (targetNode: HTMLElement | SVGElement) => {+ try {+ return await targetNode.requestPointerLock({+ unadjustedMovement: true,+ });+ } catch {+ // Some platforms may not support unadjusted movement.+ return await targetNode.requestPointerLock();}- const root = targetNode.ownerDocument.documentElement;- const originalValue = root.style.getPropertyValue(property);- root.style.setProperty(property, value);- rootStyleTracker.set(property, true);- return () => {- rootStyleTracker.delete(property);- if (originalValue) {- root.style.setProperty(property, originalValue);- return;- }- root.style.removeProperty(property);- };};-const requestPointerLock = async (+const requestPointerLock = (state: NumericScrubState,+ mouseState: { x: number; y: number },event: PointerEvent,targetNode: HTMLElement | SVGElement) => {- // After ~0.3 seconds starts touch events as page scrolling.- const restoreTouchAction = setRootStyle(targetNode, "touch-action", "none");- // The pointer lock api nukes the cursor on requestng a pointer lock,- // creating and managing the visual que of the cursor is thus left to the author- // we create and append an svg that serves as the visual que of where the cursor currently is- // taking into account horizontal/vertical orientation of the cursor itself, and update its position on move.- // we only use pointerLock api on chromium based browsers, because they feature an unobtrusive ux when activating it- // other browsers show a warning banner, making the use of it in this scenario subpar: in which case we fallback to using non-pointerLock means:- // albeit without an infinite cursor ux.- if (shouldUsePointerLock) {- // based on https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock is async- try {- // unadjustedMovement is a chromium only feature, fixes random movementX|Y jumps on windows- await targetNode.requestPointerLock({ unadjustedMovement: true });- } catch {- // Some platforms may not support unadjusted movement.- await targetNode.requestPointerLock();- }+ const cleanupTasks: Array<() => void> = [];+ const disposeOnCleanup = (fn: () => () => void) => cleanupTasks.push(fn());- const cursorNode = (targetNode.ownerDocument.querySelector(- "#numeric-guesture-control-cursor"- ) ||- new Range().createContextualFragment(`- <svg id="numeric-guesture-control-cursor" version="1.1" xmlns="http://www.w3.org/2000/svg" width="46" height="15">- <g transform="translate(2 3)">- <path d="M 15 4.5L 15 2L 11.5 5.5L 15 9L 15 6.5L 31 6.5L 31 9L 34.5 5.5L 31 2L 31 4.5Z" fill="#111" fill-rule="evenodd" stroke="#FFF" stroke-width="2"></path>- <path d="M 15 4.5L 15 2L 11.5 5.5L 15 9L 15 6.5L 31 6.5L 31 9L 34.5 5.5L 31 2L 31 4.5Z" fill="#111" fill-rule="evenodd"></path>- </g>- </svg>`).firstElementChild) as SVGElement;- cursorNode.style.filter = `drop-shadow(${- state.direction === "horizontal" ? "0 1px" : "1px 0"- } 1.1px rgba(0,0,0,.4))`;- cursorNode.style.position = "fixed";- cursorNode.style.zIndex = Number.MAX_SAFE_INTEGER.toString();- cursorNode.style.left = `${event.clientX}px`;- cursorNode.style.top = `${event.clientY}px`;- cursorNode.style.transform = `translate(-50%, -50%) ${- state.direction === "horizontal" ? "rotate(0deg)" : "rotate(90deg)"- }`;- state.cursor = cursorNode;- if (state.cursor) {- targetNode.ownerDocument.documentElement.appendChild(state.cursor);- }+ const { pointerId } = event;++ // Fixes an issue where setPointerCapture disrupts the input cursor if the input has a selection.+ // To reproduce: click into the input and observe that everything is selected.+ // Then click again and notice the cursor is not placed correctly.+ window.getSelection()?.removeAllRanges();++ disposeOnCleanup(() => {+ targetNode.setPointerCapture(pointerId);return () => {- if (state.cursor) {- state.cursor.remove();- state.cursor = undefined;- }- restoreTouchAction();- targetNode.ownerDocument.exitPointerLock();+ targetNode.releasePointerCapture(pointerId);};- }+ });++ const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);+ // Safari supports pointer lock well, but the issue lies with the pointer lock banner.+ // It shifts the entire page down, which creates a poor user experience.+ if (!isSafari) {+ disposeOnCleanup(() => {+ const timerId = window.setTimeout(() => {+ requestPointerLockSafe(targetNode)+ .then(() => {+ const cursorNode =+ (targetNode.ownerDocument.querySelector(+ "#numeric-guesture-control-cursor"+ ) as SVGElement) ||+ (new DOMParser().parseFromString(+ `+ <svg id="numeric-guesture-control-cursor" version="1.1" xmlns="http://www.w3.org/2000/svg" width="46" height="15">+ <g transform="translate(2 3)">+ <path d="M 15 4.5L 15 2L 11.5 5.5L 15 9L 15 6.5L 31 6.5L 31 9L 34.5 5.5L 31 2L 31 4.5Z" fill="#111" fill-rule="evenodd" stroke="#FFF" stroke-width="2"></path>+ <path d="M 15 4.5L 15 2L 11.5 5.5L 15 9L 15 6.5L 31 6.5L 31 9L 34.5 5.5L 31 2L 31 4.5Z" fill="#111" fill-rule="evenodd"></path>+ </g>+ </svg>`,+ "application/xml"+ ).documentElement as Element as SVGElement);++ cursorNode.style.filter = `drop-shadow(${+ state.direction === "horizontal" ? "0 1px" : "1px 0"+ } 1.1px rgba(0,0,0,.4))`;+ cursorNode.style.position = "fixed";+ cursorNode.style.zIndex = Number.MAX_SAFE_INTEGER.toString();++ cursorNode.style.left = `${mouseState.x}px`;+ cursorNode.style.top = `${mouseState.y}px`;++ cursorNode.style.transform = `translate(-50%, -50%) ${+ state.direction === "horizontal"+ ? "rotate(0deg)"+ : "rotate(90deg)"+ }`;+ state.cursor = cursorNode;+ if (state.cursor) {+ targetNode.ownerDocument.documentElement.appendChild(+ state.cursor+ );+ }+ })+ .catch((error) => {+ console.error("requestPointerLock", error);+ });+ }, scrubTimeout);- const { pointerId } = event;- const restoreCursor = setRootStyle(- targetNode,- "cursor",- state.direction === "horizontal" ? "ew-resize" : "ns-resize"- );- targetNode.setPointerCapture(pointerId);+ return () => {+ if (state.cursor) {+ state.cursor.remove();+ state.cursor = undefined;+ }++ targetNode.ownerDocument.exitPointerLock();+ clearTimeout(timerId);+ };+ });+ }return () => {- restoreCursor();- restoreTouchAction();- targetNode.releasePointerCapture(pointerId);+ for (const task of [...cleanupTasks.reverse()]) {+ task();+ }};};-const shouldUsePointerLock = "chrome" in globalThis;-// When the value is outside of the range make it come back to the range from the other side// | | . -> | . |// . | | -> | . |