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
Make CSSValueInput controllable, (#551)
Ivan Starkovffae4bd4030b
diff --git a/@types/css-tree.d.ts b/@types/css-tree.d.tsnew file mode 100644index 0000000000..da19694c77--- /dev/null+++ b/@types/css-tree.d.ts@@ -0,0 +1,35 @@+declare module "css-tree" {+ export function parse(+ text: string,+ options?: import("@types/css-tree").ParseOptions+ ): import("@types/css-tree").CssNode;++ type Match =+ | {+ syntax: { type: "Property"; name: string };+ match: Match[];+ }+ | {+ syntax: { type: "Keyword"; name: string };+ token: string;+ }+ | { syntax: null };++ type MatchProperty =+ | {+ matched: null;+ error: { message: string };+ }+ // eslint-disable-next-line @typescript-eslint/ban-types+ | {+ matched: Match;+ error: null;+ };++ export declare const lexer: {+ matchProperty: (+ property: string,+ ast: import("@types/css-tree").CssNode+ ) => MatchProperty;+ };+}diff --git a/apps/designer/app/canvas/shared/styles.ts b/apps/designer/app/canvas/shared/styles.tsindex 2a3defe690..e89913f49b 100644--- a/apps/designer/app/canvas/shared/styles.ts+++ b/apps/designer/app/canvas/shared/styles.ts@@ -244,16 +244,26 @@ const useDeleteToken = () => {const usePreviewStyle = () => {useSubscribe("previewStyle", ({ id, updates, breakpoint }) => {- if (getRule(id, breakpoint.id) === undefined) {- const rule = addRule(id, { breakpoint: breakpoint.id, style: {} });- for (const update of updates) {- rule.styleMap.set(update.property, update.value);- }- cssEngine.render();+ let rule = getRule(id, breakpoint.id);++ if (rule === undefined) {+ rule = addRule(id, { breakpoint: breakpoint.id, style: {} });}+for (const update of updates) {+ // This is possible on newly created instances, properties are not yet defined in the style.+ if (rule.styleMap.has(update.property) === false) {+ const dynamicStyle = toVarStyleWithFallback(id, {+ [update.property]: update.value,+ });++ rule.styleMap.set(update.property, dynamicStyle[update.property]);+ }+setCssVar(id, update.property, update.value);}++ cssEngine.render();});};diff --git a/apps/designer/app/designer/features/style-panel/controls/index.ts b/apps/designer/app/designer/features/style-panel/controls/index.tsindex 03f708c803..8d0e75c464 100644--- a/apps/designer/app/designer/features/style-panel/controls/index.ts+++ b/apps/designer/app/designer/features/style-panel/controls/index.ts@@ -5,4 +5,3 @@ export * from "./menu/menu-control";export * from "./font-family/font-family-control";export * from "./font-weight/font-weight-control";export * from "./image/image-control";-export * from "./toggle/toggle-control";diff --git a/apps/designer/app/designer/features/style-panel/controls/text/text-control.tsx b/apps/designer/app/designer/features/style-panel/controls/text/text-control.tsxindex a762cfcf1e..7ef8947721 100644--- a/apps/designer/app/designer/features/style-panel/controls/text/text-control.tsx+++ b/apps/designer/app/designer/features/style-panel/controls/text/text-control.tsx@@ -1,8 +1,10 @@-import { CssValueInput } from "../../shared/css-value-input";+import {+ CssValueInput,+ type IntermediateStyleValue,+} from "../../shared/css-value-input";import { getFinalValue } from "../../shared/get-final-value";import { ControlProps } from "../../style-sections";import type { StyleValue } from "@webstudio-is/css-data";-import { toValue } from "@webstudio-is/css-engine";import { useState } from "react";import { Box, Tooltip } from "@webstudio-is/design-system";@@ -21,7 +23,10 @@ export const TextControl = ({const setValue = setProperty(styleConfig.property);- const [currentValue, setCurrentValue] = useState<StyleValue>();+ const [currentValue, setCurrentValue] = useState<+ StyleValue | IntermediateStyleValue+ >();+return (<Tooltipcontent={styleConfig.label}@@ -39,22 +44,16 @@ export const TextControl = ({}))}onChange={(styleValue) => {setCurrentValue(styleValue);- setValue(toValue(styleValue), { isEphemeral: true });- }}- onItemHighlight={(styleValue) => {- const nextValue = styleValue ?? currentValue ?? value;- if (nextValue) {- setValue(toValue(nextValue), {- isEphemeral: true,- });+ if (styleValue.type !== "intermediate") {+ setValue(styleValue, { isEphemeral: true });}}}+ onPreview={(styleValue) => {+ setValue(styleValue, { isEphemeral: true });+ }}onChangeComplete={(styleValue) => {- const prevValue = toValue(value);- const nextValue = toValue(styleValue);- if (prevValue === nextValue) return;+ setValue(styleValue);setCurrentValue(undefined);- setValue(toValue(styleValue));}}/></Box>diff --git a/apps/designer/app/designer/features/style-panel/sections/flex-child/flex-child.tsx b/apps/designer/app/designer/features/style-panel/sections/flex-child/flex-child.tsxindex ed5abc76bf..ab423faca0 100644--- a/apps/designer/app/designer/features/style-panel/sections/flex-child/flex-child.tsx+++ b/apps/designer/app/designer/features/style-panel/sections/flex-child/flex-child.tsx@@ -1,6 +1,6 @@import { Flex, Grid } from "@webstudio-is/design-system";import type { RenderCategoryProps } from "../../style-sections";-import { ToggleGroupControl } from "../../controls";+import { ToggleGroupControl } from "../../controls/toggle/toggle-control";import { PropertyName } from "../../shared/property-name";import { TextControl } from "../../controls";import {diff --git a/apps/designer/app/designer/features/style-panel/shared/configs.ts b/apps/designer/app/designer/features/style-panel/shared/configs.tsindex 0f16df299e..43d679b8bf 100644--- a/apps/designer/app/designer/features/style-panel/shared/configs.ts+++ b/apps/designer/app/designer/features/style-panel/shared/configs.ts@@ -33,6 +33,7 @@ import {ColumnGapIcon,} from "@webstudio-is/icons";import { keywordValues, properties } from "@webstudio-is/css-data";+import type * as Controls from "../controls";type BaseStyleConfig = {label: string;@@ -40,15 +41,7 @@ type BaseStyleConfig = {appliesTo: AppliesTo;};-// @todo make it use actual list of controls-export type Control =- | "TextControl"- | "ColorControl"- | "MenuControl"- | "SelectControl"- | "FontFamilyControl"- | "ImageControl"- | "FontWeightControl";+export type Control = keyof typeof Controls;export type StyleConfig = BaseStyleConfig & {control: Control;diff --git a/apps/designer/app/designer/features/style-panel/shared/css-value-input/css-value-input.stories.tsx b/apps/designer/app/designer/features/style-panel/shared/css-value-input/css-value-input.stories.tsxindex a73ce2c5f4..7d31fb0676 100644--- a/apps/designer/app/designer/features/style-panel/shared/css-value-input/css-value-input.stories.tsx+++ b/apps/designer/app/designer/features/style-panel/shared/css-value-input/css-value-input.stories.tsx@@ -1,7 +1,7 @@import React from "react";import { Flex, TextField } from "@webstudio-is/design-system";import type { StyleValue } from "@webstudio-is/css-data";-import { CssValueInput } from "./css-value-input";+import { CssValueInput, type IntermediateStyleValue } from "./css-value-input";import { action } from "@storybook/addon-actions";export default {@@ -9,10 +9,12 @@ export default {};export const WithKeywords = () => {- const [value, setValue] = React.useState<StyleValue>({- type: "keyword",- value: "auto",- });+ const [value, setValue] = React.useState<StyleValue | IntermediateStyleValue>(+ {+ type: "keyword",+ value: "auto",+ }+ );return (<CssValueInput@@ -27,23 +29,25 @@ export const WithKeywords = () => {onChange={(value) => {setValue(value);}}+ onPreview={(value) => {+ action("onPreview")(value);+ }}onChangeComplete={(newValue) => {// on blur, select, enter etc.setValue(newValue);action("onChangeComplete")(newValue);}}- onItemHighlight={(value) => {- action("onItemHighlight")(value);- }}/>);};export const WithIcons = () => {- const [value, setValue] = React.useState<StyleValue>({- type: "keyword",- value: "space-around",- });+ const [value, setValue] = React.useState<StyleValue | IntermediateStyleValue>(+ {+ type: "keyword",+ value: "space-around",+ }+ );return (<CssValueInput@@ -61,24 +65,26 @@ export const WithIcons = () => {onChange={(newValue) => {setValue(newValue);}}+ onPreview={(value) => {+ action("onPreview")(value);+ }}onChangeComplete={(newValue) => {// on blur, select, enter etc.setValue(newValue);action("onChangeComplete")(newValue);}}- onItemHighlight={(value) => {- action("onItemHighlight")(value);- }}/>);};export const WithUnits = () => {- const [value, setValue] = React.useState<StyleValue>({- type: "unit",- value: 100,- unit: "px",- });+ const [value, setValue] = React.useState<StyleValue | IntermediateStyleValue>(+ {+ type: "unit",+ value: 100,+ unit: "px",+ }+ );return (<Flex css={{ gap: "$spacing$9" }}>@@ -94,14 +100,14 @@ export const WithUnits = () => {onChange={(newValue) => {setValue(newValue);}}+ onPreview={(value) => {+ action("onPreview")(value);+ }}onChangeComplete={(newValue) => {// on blur, select, enter etc.setValue(newValue);action("onChangeComplete")(newValue);}}- onItemHighlight={(value) => {- action("onItemHighlight")(value);- }}/><TextFieldreadOnlydiff --git a/apps/designer/app/designer/features/style-panel/shared/css-value-input/css-value-input.tsx b/apps/designer/app/designer/features/style-panel/shared/css-value-input/css-value-input.tsxindex 924aea89bb..a45c245848 100644--- a/apps/designer/app/designer/features/style-panel/shared/css-value-input/css-value-input.tsx+++ b/apps/designer/app/designer/features/style-panel/shared/css-value-input/css-value-input.tsx@@ -18,6 +18,7 @@ import type {StyleProperty,UnsetValue,StyleValue,+ Unit,} from "@webstudio-is/css-data";import {type KeyboardEventHandler,@@ -29,7 +30,8 @@ import {} from "react";import { useIsFromCurrentBreakpoint } from "../use-is-from-current-breakpoint";import { useUnitSelect } from "./unit-select";-import { isValid, isNumericString } from "../parse-css-value";+import { unstable_batchedUpdates } from "react-dom";+import { parseIntermediateOrInvalidValue } from "./parse-intermediate-or-invalid-value";const unsetValue: UnsetValue = { type: "unset", value: "" };@@ -43,56 +45,14 @@ const calcNumberChange = (return Number((value + delta * multiplier).toFixed(1));};-const useHandleOnChange = (- property: StyleProperty,- value: StyleValue,- input: string,- onChange: (value: StyleValue) => void-) => {- // Used to decouple onChange effect from value ref change- const valueRef = useRef<StyleValue>(value);-- useEffect(() => {- if (input === "" || input === String(valueRef.current.value)) {- return;- }-- // We want to switch to unit mode if entire input is a number.- if (isNumericString(input)) {- if (value.type === "unit" && String(Number(input)) !== input) return;- onChange?.({- type: "unit",- // Use previously known unit or fallback to the most common unit: px, if supported- unit:- valueRef.current.type === "unit"- ? valueRef.current.unit- : isValid(property, input + "px")- ? "px"- : "number",- value: Number(input),- });- return;- }-- onChange?.({- type: "keyword",- value: input,- });- }, [property, input, value.type, onChange]);-- useEffect(() => {- valueRef.current = value;- }, [value]);-};-const useScrub = ({value,onChange,onChangeComplete,shouldHandleEvent,}: {- value: StyleValue;- onChange: (value: StyleValue) => void;+ value: CssValueInputValue;+ onChange: (value: CssValueInputValue) => void;onChangeComplete: (value: StyleValue) => void;shouldHandleEvent?: (node: EventTarget) => boolean;}): [@@ -103,12 +63,14 @@ const useScrub = ({const scrubRef = useRef<HTMLDivElement | null>(null);const inputRef = useRef<HTMLInputElement | null>(null);const [isInputActive, setIsInputActive] = useState(false);+const onChangeRef = useRef(onChange);const onChangeCompleteRef = useRef(onChangeComplete);const valueRef = useRef(value);onChangeCompleteRef.current = onChangeComplete;onChangeRef.current = onChange;+valueRef.current = value;const type = valueRef.current.type;@@ -132,16 +94,26 @@ const useScrub = ({const scrub = numericScrubControl(scrubRefCurrent, {initialValue: value,onValueInput(event) {- inputRefCurrent.value = String(event.value);setIsInputActive(true);inputRefCurrent.blur();- },- onValueChange(event) {- onChangeCompleteRef.current({++ onChangeRef.current({type,unit,value: event.value,});+ },+ onValueChange(event) {+ // Will work without but depends on order of setState updates+ // at text-control, now fixed in both places (order of updates is right, and batched here)+ unstable_batchedUpdates(() => {+ onChangeCompleteRef.current({+ type,+ unit,+ value: event.value,+ });+ });+setIsInputActive(false);inputRefCurrent.focus();inputRefCurrent.select();@@ -157,24 +129,26 @@ const useScrub = ({const useHandleKeyDown =({+ ignoreEnter,value,onChange,onChangeComplete,onKeyDown,- closeMenu,}: {- value: StyleValue;- onChange: (value: StyleValue) => void;- onChangeComplete: (value: StyleValue) => void;+ ignoreEnter: boolean;+ value: CssValueInputValue;+ onChange: (value: CssValueInputValue) => void;+ onChangeComplete: (value: CssValueInputValue) => void;onKeyDown: KeyboardEventHandler<HTMLInputElement>;- closeMenu: () => void;}) =>(event: KeyboardEvent<HTMLInputElement>) => {- onKeyDown(event);- if (event.key === "Enter") {- closeMenu();- onChangeComplete(value);+ // Do not prevent downshift behaviour on item select+ if (ignoreEnter === false) {+ if (event.key === "Enter") {+ onChangeComplete(value);+ }}+if (value.type === "unit" &&(event.key === "ArrowUp" || event.key === "ArrowDown") &&@@ -184,16 +158,28 @@ const useHandleKeyDown =...value,value: calcNumberChange(value.value, event),});+ // Prevent Downshift from opening menu on arrow up/down+ return;}++ onKeyDown(event);};+export type IntermediateStyleValue = {+ type: "intermediate";+ value: string;+ unit?: Unit;+};++type CssValueInputValue = StyleValue | IntermediateStyleValue;+type CssValueInputProps = {property: StyleProperty;- value?: StyleValue;+ value?: CssValueInputValue;keywords?: Array<KeywordValue>;- onChange: (value: StyleValue) => void;+ onChange: (value: CssValueInputValue) => void;onChangeComplete: (value: StyleValue) => void;- onItemHighlight?: (value: StyleValue | null) => void;+ onPreview: (value: StyleValue) => void;};/**@@ -227,16 +213,33 @@ type CssValueInputProps = {* - Typing number + unit (e.g. "12px") in unit mode will change the selected unit on blur/enter* - Evaluated math expression: "2px + 3em" (like CSS calc())*/-export const CssValueInput = ({icon,property,value = unsetValue,keywords = [],- onChange,- onChangeComplete,- onItemHighlight,+ onPreview,+ ...props}: CssValueInputProps & { icon?: JSX.Element }) => {+ const onChange = (input: string) => {+ // We don't know what's inside the input,+ // preserve current unit value if exists+ props.onChange({+ type: "intermediate",+ value: input,+ unit: "unit" in value ? value.unit : undefined,+ });+ };++ const onChangeComplete = (value: CssValueInputValue) => {+ if (value.type !== "intermediate" && value.type !== "invalid") {+ props.onChangeComplete(value);+ return;+ }++ props.onChangeComplete(parseIntermediateOrInvalidValue(property, value));+ };+const {items,getInputProps,@@ -245,24 +248,35 @@ export const CssValueInput = ({getMenuProps,getItemProps,isOpen,- closeMenu,- } = useCombobox<StyleValue>({+ } = useCombobox<CssValueInputValue>({items: keywords,value,itemToString: (item) => (item === null ? "" : String(item.value)),+ onInputChange: (inputValue) => {+ onChange(inputValue ?? unsetValue.value);+ },onItemSelect: (value) => {onChangeComplete(value ?? unsetValue);},- onItemHighlight,+ onItemHighlight: (value) => {+ if (value == null) {+ onPreview(unsetValue);+ return;+ }+ if (value.type !== "intermediate") {+ onPreview(value ?? unsetValue);+ }+ },});const inputProps = getInputProps();- useHandleOnChange(property, value, inputProps.value, onChange);-const [isUnitsOpen, unitSelectElement] = useUnitSelect({property,- value: value.type === "unit" ? value : undefined,+ value:+ value.type === "unit" || value.type === "intermediate"+ ? value+ : undefined,onChange: onChangeComplete,onCloseAutoFocus(event) {// We don't want to focus the unit trigger when closing the select (no matter if unit was selected, clicked outside or esc was pressed)@@ -277,24 +291,26 @@ export const CssValueInput = ({}, []);const [scrubRef, inputRef, isInputActive] = useScrub({value,- onChange,+ onChange: props.onChange,onChangeComplete,shouldHandleEvent,});const handleOnBlur: KeyboardEventHandler = (event) => {- // When units select is open, onBlur is triggered,though we don't want a change event in this case.- if (isUnitsOpen) return;+ // When select is open, onBlur is triggered,though we don't want a change event in this case.+ if (isUnitsOpen || isOpen) return;+onChangeComplete(value);inputProps.onBlur(event);};const handleKeyDown = useHandleKeyDown({- value,- onChange,+ // In case of menu is really open do not prevent default downshift Enter key behaviour+ ignoreEnter: isOpen && !getMenuProps().empty,onChangeComplete,+ value,+ onChange: props.onChange,onKeyDown: inputProps.onKeyDown,- closeMenu,});const isCurrentBreakpoint = useIsFromCurrentBreakpoint(property);@@ -316,7 +332,7 @@ export const CssValueInput = ({</TextFieldIconButton>);const hasItems = items.length !== 0;- const isUnitValue = value.type === "unit";+ const isUnitValue = "unit" in value;const isKeywordValue = value.type === "keyword" && hasItems;const suffixRef = useRef<HTMLDivElement | null>(null);const suffix = (diff --git a/apps/designer/app/designer/features/style-panel/shared/css-value-input/evaluate-math.test.ts b/apps/designer/app/designer/features/style-panel/shared/css-value-input/evaluate-math.test.tsnew file mode 100644index 0000000000..6652044c12--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/shared/css-value-input/evaluate-math.test.ts@@ -0,0 +1,28 @@+import { evaluateMath } from "./evaluate-math";++describe("Evaluate math", () => {+ test("should evaluate simple math", () => {+ expect(evaluateMath("1 + 1")).toEqual(2);+ expect(evaluateMath("4 + 2 * 3")).toEqual(10);+ expect(evaluateMath("4 / 2 * 3 - 1")).toEqual(5);+ });++ test("should evaluate simple floating math", () => {+ expect(evaluateMath("1.0 + 1.1")).toEqual(2.1);+ expect(evaluateMath("4 + 2.5 * 3.4")).toEqual(12.5);+ expect(evaluateMath("4.5 / 2 * 3.3 - 1")).toEqual(6.425);+ });++ test("return undefined if math is wrong", () => {+ expect(evaluateMath("1 ++ 1")).toEqual(undefined);+ expect(evaluateMath("++1")).toEqual(undefined);+ expect(evaluateMath("1 * 2 *")).toEqual(undefined);+ });++ test("return undefined if any symbols excepts numbers or spaces in input", () => {+ expect(evaluateMath("1 + 1 p")).toEqual(undefined);+ expect(evaluateMath("e")).toEqual(undefined);+ expect(evaluateMath("{1+2}")).toEqual(undefined);+ expect(evaluateMath("alert('hello')")).toEqual(undefined);+ });+});diff --git a/apps/designer/app/designer/features/style-panel/shared/css-value-input/evaluate-math.ts b/apps/designer/app/designer/features/style-panel/shared/css-value-input/evaluate-math.tsnew file mode 100644index 0000000000..4f82f582da--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/shared/css-value-input/evaluate-math.ts@@ -0,0 +1,14 @@+export const evaluateMath = (expression: string) => {+ if (/^[\d\s.+*/-]+$/.test(expression) === false) {+ return;+ }+ try {+ // Eval is safe here because of the regex above+ const result = eval(`(${expression})`);+ if (typeof result === "number") {+ return result;+ }+ } catch {+ return;+ }+};diff --git a/apps/designer/app/designer/features/style-panel/shared/css-value-input/index.ts b/apps/designer/app/designer/features/style-panel/shared/css-value-input/index.tsindex e6f31e7e27..977f5f1563 100644--- a/apps/designer/app/designer/features/style-panel/shared/css-value-input/index.ts+++ b/apps/designer/app/designer/features/style-panel/shared/css-value-input/index.ts@@ -1 +1 @@-export { CssValueInput } from "./css-value-input";+export { CssValueInput, type IntermediateStyleValue } from "./css-value-input";diff --git a/apps/designer/app/designer/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts b/apps/designer/app/designer/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.tsnew file mode 100644index 0000000000..3d917c046a--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts@@ -0,0 +1,64 @@+import type {+ StyleProperty,+ StyleValue,+ InvalidValue,+} from "@webstudio-is/css-data";+import type { IntermediateStyleValue } from "./css-value-input";++import { parseCssValue } from "../parse-css-value";++import { evaluateMath } from "./evaluate-math";+import { units } from "@webstudio-is/css-data";++export const parseIntermediateOrInvalidValue = (+ property: StyleProperty,+ value: IntermediateStyleValue | InvalidValue+): StyleValue => {+ // Try value with existing or fallback unit+ const unit = "unit" in value ? value.unit ?? "px" : "px";+ let styleInput = parseCssValue(property, `${value.value}${unit}`);++ if (styleInput.type !== "invalid") {+ return styleInput;+ }++ // Probably value is already valid, use it+ styleInput = parseCssValue(property, value.value);++ if (styleInput.type !== "invalid") {+ return styleInput;+ }++ // Try evaluate something like 10px + 4 or 13 + 4em++ // Try to extract/remove anything similar to unit value+ const unitRegex = new RegExp(`(?:${units.join("|")})`, "g");+ const matchedUnit = value.value.match(unitRegex)?.[0];+ const unitlessValue = value.value.replace(unitRegex, "");++ // Try to evaluate math expression if possible+ const mathResult = evaluateMath(unitlessValue);++ if (mathResult != null) {+ const unit = matchedUnit ?? ("unit" in value ? value.unit ?? "px" : "px");+ styleInput = parseCssValue(property, `${String(mathResult)}${unit}`);++ if (styleInput.type !== "invalid") {+ return styleInput;+ }++ // If math expression is valid, use it as a value+ styleInput = parseCssValue(property, String(mathResult));++ if (styleInput.type !== "invalid") {+ return styleInput;+ }+ }++ // If we are here it means that value can be Valid but our parseCssValue can't handle it+ // or value is invalid+ return {+ type: "invalid",+ value: value.value,+ };+};diff --git a/apps/designer/app/designer/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts b/apps/designer/app/designer/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.tsnew file mode 100644index 0000000000..68aa005f2a--- /dev/null+++ b/apps/designer/app/designer/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts@@ -0,0 +1,210 @@+import { parseIntermediateOrInvalidValue } from "./parse-intermediate-or-invalid-value";++const properties = ["width", "lineHeight", "backgroundPositionX"] as const;++const propertiesAndKeywords = [+ ["width", "auto"],+ ["lineHeight", "normal"],+ ["backgroundPositionX", "center"],+] as const;++describe("Parse intermediate or invalid value without math evaluation", () => {+ test("not lost unit value", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: "10",+ unit: "em",+ });++ expect(result).toEqual({+ type: "unit",+ value: 10,+ unit: "em",+ });+ }+ });++ test("fallback to px", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: "10",+ });++ expect(result).toEqual({+ type: "unit",+ value: 10,+ unit: "px",+ });+ }+ });++ test("switch on new unit if previous not known", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: "10rem",+ });++ expect(result).toEqual({+ type: "unit",+ value: 10,+ unit: "rem",+ });+ }+ });++ test("switch on new unit if previous present", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: "10rem",+ unit: "em",+ });++ expect(result).toEqual({+ type: "unit",+ value: 10,+ unit: "rem",+ });+ }+ });++ test("accept keywords", () => {+ for (const [propery, keyword] of propertiesAndKeywords) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: keyword,+ unit: "em",+ });++ expect(result).toEqual({+ type: "keyword",+ value: keyword,+ });+ }+ });+});++describe("Parse intermediate or invalid value with math evaluation", () => {+ test("not lost unit value", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: "10+10",+ unit: "em",+ });++ expect(result).toEqual({+ type: "unit",+ value: 20,+ unit: "em",+ });+ }+ });++ test("fallback to px", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: "10 + 10",+ });++ expect(result).toEqual({+ type: "unit",+ value: 20,+ unit: "px",+ });+ }+ });++ test("switch on new unit if previous not known", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: "10rem + 15px",+ });++ expect(result).toEqual({+ type: "unit",+ value: 25,+ unit: "rem",+ });+ }+ });++ test("switch on new unit if previous present", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "intermediate",+ value: "10rem + 15",+ unit: "em",+ });++ expect(result).toEqual({+ type: "unit",+ value: 25,+ unit: "rem",+ });+ }+ });+});++describe("Parse invalid", () => {+ test("fallback to px", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "invalid",+ value: "10",+ });++ expect(result).toEqual({+ type: "unit",+ value: 10,+ unit: "px",+ });+ }+ });++ test("switch on new unit if previous not known", () => {+ for (const propery of properties) {+ const result = parseIntermediateOrInvalidValue(propery, {+ type: "invalid",+ value: "10rem + 15px",+ });++ expect(result).toEqual({+ type: "unit",+ value: 25,+ unit: "rem",+ });+ }+ });+});++describe("Returns invalid if can't parse", () => {+ test("do not accept unknown units", () => {+ const result = parseIntermediateOrInvalidValue("width", {+ type: "intermediate",+ value: "10ee",+ });++ expect(result).toEqual({+ type: "invalid",+ value: "10ee",+ });+ });++ test("do not accept wrong keywords", () => {+ const result = parseIntermediateOrInvalidValue("lineHeight", {+ type: "intermediate",+ value: "auto",+ });++ expect(result).toEqual({+ type: "invalid",+ value: "auto",+ });+ });+});diff --git a/apps/designer/app/designer/features/style-panel/shared/css-value-input/unit-select.tsx b/apps/designer/app/designer/features/style-panel/shared/css-value-input/unit-select.tsxindex 227f7c51d3..7e9bc56036 100644--- a/apps/designer/app/designer/features/style-panel/shared/css-value-input/unit-select.tsx+++ b/apps/designer/app/designer/features/style-panel/shared/css-value-input/unit-select.tsx@@ -14,6 +14,7 @@ import {} from "@webstudio-is/design-system";import { ChevronDownIcon, ChevronUpIcon } from "@webstudio-is/icons";import { isValid } from "../parse-css-value";+import type { IntermediateStyleValue } from "../css-value-input";const unitRenderMap: Map<Unit, string> = new Map([["px", "PX"],@@ -35,8 +36,8 @@ const defaultUnits = Array.from(unitRenderMap.keys());type UseUnitSelectType = {property: string;- value?: UnitValue;- onChange: (value: StyleValue) => void;+ value?: UnitValue | IntermediateStyleValue;+ onChange: (value: StyleValue | IntermediateStyleValue) => void;units?: Array<Unit>;onCloseAutoFocus: (event: Event) => void;};@@ -49,18 +50,31 @@ export const useUnitSelect = ({...props}: UseUnitSelectType) => {const [isOpen, setIsOpen] = useState(false);+const renderUnits = useMemo(() =>value &&units.filter((unit) => {+ if (value.type === "intermediate") {+ if (value.unit !== undefined) {+ // check that property is valid for any positive number like 1 during editing+ return isValid(+ property,+ toValue({ type: "unit", unit, value: 1 })+ );+ }+ return false;+ }+return isValid(property, toValue({ ...value, unit }));}).map((unit) => unitRenderMap.get(unit) ?? unit),[units, property, value]);- const renderValue = value && unitRenderMap.get(value.unit);+ const renderValue =+ value?.unit !== undefined ? unitRenderMap.get(value.unit) : undefined;if (value === undefined ||diff --git a/apps/designer/app/designer/features/style-panel/shared/get-final-value.ts b/apps/designer/app/designer/features/style-panel/shared/get-final-value.tsindex e429616d50..c8d4b5ebce 100644--- a/apps/designer/app/designer/features/style-panel/shared/get-final-value.ts+++ b/apps/designer/app/designer/features/style-panel/shared/get-final-value.ts@@ -1,7 +1,10 @@import type { Style, StyleValue, StyleProperty } from "@webstudio-is/css-data";import { toValue } from "@webstudio-is/css-engine";import type { InheritedStyle } from "./get-inherited-style";-import { isValid, isNumericString } from "./parse-css-value";+import { isValid } from "./parse-css-value";++export const isNumericString = (input: string) =>+ String(input).trim().length !== 0 && isNaN(Number(input)) === false;// @todo expose which instance we inherited the value fromexport const getFinalValue = ({diff --git a/apps/designer/app/designer/features/style-panel/shared/parse-css-value.test.ts b/apps/designer/app/designer/features/style-panel/shared/parse-css-value.test.tsindex 8a188daf0d..827894492f 100644--- a/apps/designer/app/designer/features/style-panel/shared/parse-css-value.test.ts+++ b/apps/designer/app/designer/features/style-panel/shared/parse-css-value.test.ts@@ -20,35 +20,12 @@ describe("Parse CSS value", () => {});});- test("with default unit", () => {- expect(parseCssValue("width", "10", "px")).toEqual({- type: "unit",- unit: "px",- value: 10,- });- });-- test("with unit and default unit", () => {- expect(parseCssValue("width", "10px", "rem")).toEqual({- type: "unit",- unit: "px",- value: 10,- });- });-test("empty input", () => {expect(parseCssValue("width", "")).toEqual({type: "invalid",value: "",});});-- test("empty input with default unit", () => {- expect(parseCssValue("width", "", "px")).toEqual({- type: "invalid",- value: "",- });- });});describe("keyword value", () => {@@ -61,59 +38,23 @@ describe("Parse CSS value", () => {test("keyword with unit", () => {expect(parseCssValue("width", "autopx")).toEqual({- type: "keyword",+ type: "invalid",value: "autopx",});});- test("incomplete", () => {- // This will return invalid unit when `CSSStyleValue.parse` is available- expect(parseCssValue("width", "10p")).toEqual({- type: "unit",- unit: "number",- value: 10,- });- });- });-- describe("math expression", () => {- test("addition with unit", () => {- expect(parseCssValue("width", "10+1px")).toEqual({- type: "unit",- unit: "px",- value: 11,- });- });-- test("addition without unit", () => {- expect(parseCssValue("width", "10+1", "px")).toEqual({- type: "unit",- unit: "px",- value: 11,- });- });-- test("subtraction with unit", () => {- expect(parseCssValue("width", "10-1px")).toEqual({- type: "unit",- unit: "px",- value: 9,- });- });-- test("multiplication with unit", () => {- expect(parseCssValue("width", "2*2px")).toEqual({- type: "unit",- unit: "px",- value: 4,+ test("invalid", () => {+ // This will return px as a fallback unit, as number is not valid for width.+ expect(parseCssValue("width", "10")).toEqual({+ type: "invalid",+ value: "10",});- });- test("division with unit", () => {- expect(parseCssValue("width", "4/2px")).toEqual({+ // This will return number unit, as number is valid for aspectRatio.+ expect(parseCssValue("aspectRatio", "10")).toEqual({type: "unit",- unit: "px",- value: 2,+ unit: "number",+ value: 10,});});});diff --git a/apps/designer/app/designer/features/style-panel/shared/parse-css-value.ts b/apps/designer/app/designer/features/style-panel/shared/parse-css-value.tsindex 44a1e5dfc4..5a91dc50bf 100644--- a/apps/designer/app/designer/features/style-panel/shared/parse-css-value.ts+++ b/apps/designer/app/designer/features/style-panel/shared/parse-css-value.ts@@ -1,103 +1,131 @@+import * as csstree from "css-tree";import hyphenate from "hyphenate-style-name";import type { StyleProperty, StyleValue, Unit } from "@webstudio-is/css-data";import { units } from "@webstudio-is/css-data";+import warnOnce from "warn-once";-const unitRegex = new RegExp(`${[...units, "number"].join("|")}`);--export const isNumericString = (input: string) =>- String(input).trim().length !== 0 && isNaN(Number(input)) === false;--export const isValid = (property: string, value: string): boolean => {- // Only browsers with houdini api will provide validation for now- // @todo add a polyfill maybe- if (- typeof CSSStyleValue === "undefined" ||- typeof CSSStyleValue.parse === "undefined"- ) {- return true;- }-- try {- CSSStyleValue.parse(hyphenate(property), value);- } catch (error) {- return false;- }- return true;-};--// If expression is a math expression, evaluates it.-// Otherwise returns undefined.-const evaluateMath = (expression: string) => {- if (/^[\d\s.+*/-]+$/.test(expression) === false) {- return undefined;- }+const cssTryParseValue = (input: string) => {try {- // Eval is safe here because of the regex above- const result = eval(`(${expression})`);- if (typeof result === "number") {- return result;- }- } catch (err) {+ const ast = csstree.parse(input, { context: "value" });+ return ast;+ } catch {return undefined;}};-// - 2+2px-// - 2*2-const evaluate = (input: string, parsedUnit: [Unit] | null) => {- const result = evaluateMath(- parsedUnit === null ? input : input.replace(parsedUnit[0], "")- );+export const isValid = (property: string, value: string): boolean => {+ const ast = cssTryParseValue(value);- if (result !== undefined) {- return result;+ if (ast == null) {+ return false;}- const number = parseFloat(input);- return isNaN(number) ? undefined : number;+ const matchResult = csstree.lexer.matchProperty(hyphenate(property), ast);++ return matchResult.matched != null;};-// Helper to let user input:-// - 10-// - 10p-// - 10px > px as unit-// - empty string-// - a keywordexport const parseCssValue = (property: StyleProperty,- input: string,- defaultUnit?: Unit+ input: string): StyleValue => {const invalidValue = {type: "invalid",value: input,} as const;+if (input.length === 0) {return invalidValue;}- const parsedUnit = unitRegex.exec(input) as [Unit] | null;- const number = evaluate(input, parsedUnit);+ if (!isValid(property, input)) {+ return invalidValue;+ }++ const ast = cssTryParseValue(input);- // If we get a unit but there is no number - we assume its an accidental- // unit match and its a keyword value.- if (number === undefined) {- if (isValid(property, input)) {+ if (ast == null) {+ warnOnce(+ true,+ `Can't parse css property "${property}" with value "${input}"`+ );+ return invalidValue;+ }++ if (+ ast != null &&+ ast.type === "Value" &&+ ast.children.first === ast.children.last+ ) {+ // Try extract units from 1st children+ const singleChild = ast.children.filter(+ (child) =>+ child.type === "Number" ||+ child.type === "Dimension" ||+ child.type === "Percentage"+ ).first;++ if (singleChild?.type === "Number") {+ return {+ type: "unit",+ unit: "number",+ value: Number(singleChild.value),+ };+ }++ if (singleChild?.type === "Dimension") {+ const parsedUnit =+ singleChild.unit != null && units.includes(singleChild.unit as never)+ ? (singleChild.unit as never)+ : undefined;++ if (parsedUnit !== undefined) {+ return {+ type: "unit",+ unit: parsedUnit as Unit,+ value: Number(singleChild.value),+ };+ }+ }++ if (singleChild?.type === "Percentage") {+ return {+ type: "unit",+ unit: "%",+ value: Number(singleChild.value),+ };+ }+ }++ const matchResult = csstree.lexer.matchProperty(hyphenate(property), ast);++ if (+ matchResult.matched != null &&+ matchResult.matched.syntax != null &&+ matchResult.matched.syntax.type === "Property"+ ) {+ const match =+ "match" in matchResult.matched ? matchResult.matched.match : undefined;++ if (+ match != null &&+ match.length === 1 &&+ match[0].syntax?.type === "Keyword"+ ) {return {type: "keyword",value: input,} as const;}- return invalidValue;}- // If user didn't enter a unit, use the previous known unit otherwise fallback to px.- const fallbackUnit: Unit = defaultUnit ?? "number";- const [unit] = parsedUnit || [fallbackUnit];+ warnOnce(+ true,+ `Property "${property}" with value "${input}" is valid but can't be parsed.`+ );return {- type: "unit",- unit: isValid(property, number + unit.replace("number", "")) ? unit : "px",- value: number,+ type: "invalid",+ value: input,};};diff --git a/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts b/apps/designer/app/designer/features/style-panel/shared/use-style-data.tsindex 942716ed3c..3e6741ef68 100644--- a/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts+++ b/apps/designer/app/designer/features/style-panel/shared/use-style-data.ts@@ -1,12 +1,14 @@import { useState, useMemo, useEffect, useCallback } from "react";+import warnOnce from "warn-once";import type { SelectedInstanceData, StyleUpdates } from "@webstudio-is/project";-import type { Style, StyleProperty } from "@webstudio-is/css-data";+import type { Style, StyleProperty, StyleValue } from "@webstudio-is/css-data";import { type Publish } from "~/shared/pubsub";import { useSelectedBreakpoint } from "~/designer/shared/nano-states";-import { parseCssValue } from "./parse-css-value";import { getInheritedStyle } from "./get-inherited-style";import { getCssRuleForBreakpoint } from "./get-css-rule-for-breakpoint";import { useRootInstance } from "~/shared/nano-states";+// @todo: must be removed, now it's only for compatibility with existing code+import { parseCssValue } from "./parse-css-value";declare module "~/shared/pubsub" {export interface PubsubMap {@@ -22,9 +24,10 @@ type UseStyleData = {type StyleUpdateOptions = { isEphemeral: boolean };+// @todo: style must have StyleValue type alwaysexport type SetProperty = (property: StyleProperty-) => (value: string, options?: StyleUpdateOptions) => void;+) => (style: string | StyleValue, options?: StyleUpdateOptions) => void;export type CreateBatchUpdate = () => {setProperty: SetProperty;@@ -93,23 +96,36 @@ export const useStyleData = ({});};+ // @deprecated should not be calledconst toStyleValue = (property: StyleProperty, value: string) => {- if (currentStyle === undefined) return;if (property === "fontFamily") {return { type: "fontFamily" as const, value: [value] };}- return parseCssValue(property, value, "number");++ return parseCssValue(property, value);};const setProperty: SetProperty = (property) => {- return (input, options = { isEphemeral: false }) => {- const nextValue = toStyleValue(property, input);- if (nextValue === undefined) return;+ return (inputOrStyle, options = { isEphemeral: false }) => {+ if (currentStyle === undefined) return;++ warnOnce(+ typeof inputOrStyle === "string",+ "setProperty should be called with a style object, string is deprecated"+ );++ const nextValue =+ typeof inputOrStyle === "string"+ ? toStyleValue(property, inputOrStyle)+ : inputOrStyle;+if (nextValue.type !== "invalid") {const updates = [{ property, value: nextValue }];const type = options.isEphemeral ? "preview" : "update";+publishUpdates(type, updates);}+if (options.isEphemeral === false) {setCurrentStyle({ ...currentStyle, [property]: nextValue });}@@ -120,11 +136,23 @@ export const useStyleData = ({let updates: StyleUpdates["updates"] = [];const setProperty = (property: StyleProperty) => {- const setValue = (input: string) => {- const value = toStyleValue(property, input);- if (value === undefined || value.type === "invalid") {+ const setValue = (inputOrStyle: string | StyleValue) => {+ if (currentStyle === undefined) return;++ warnOnce(+ typeof inputOrStyle === "string",+ "setProperty should be called with a style object, string is deprecated"+ );++ const value =+ typeof inputOrStyle === "string"+ ? toStyleValue(property, inputOrStyle)+ : inputOrStyle;++ if (value.type === "invalid") {return;}+updates.push({ property, value });};return setValue;diff --git a/apps/designer/package.json b/apps/designer/package.jsonindex 7093343eac..41dc24f064 100644--- a/apps/designer/package.json+++ b/apps/designer/package.json@@ -35,6 +35,7 @@"@webstudio-is/react-sdk": "*","bson-objectid": "^2.0.2","camelcase": "^6.3.0",+ "css-tree": "^2.3.0","debug": "^4.3.4","detect-font": "^0.1.5","downshift": "^6.1.7",@@ -84,7 +85,7 @@"@storybook/testing-library": "^0.0.13","@testing-library/react": "^12.1.5","@testing-library/react-hooks": "^8.0.1",- "@types/css-tree": "^1.0.7",+ "@types/css-tree": "^2.0.0","@types/hoist-non-react-statics": "^3.3.1","@types/hyphenate-style-name": "^1.0.0","@types/jest": "^29.2.3",@@ -100,13 +101,13 @@"@types/sharp": "^0.30.4","@types/w3c-css-typed-object-model-level-1": "^20180410.0.4","@webstudio-is/eslint-config-custom": "*",+ "@webstudio-is/jest-config": "*","@webstudio-is/tsconfig": "*","babel-loader": "^8.2.5",- "css-tree": "^2.0.4",+ "css-tree": "^2.3.0","dotenv": "^16.0.0","esbuild-jest": "^0.5.0","esbuild-node-externals": "^1.4.1",- "@webstudio-is/jest-config": "*","prettier": "^2.6.2","react-test-renderer": "^17.0.2","relative-deps": "^1.0.7",diff --git a/packages/css-data/package.json b/packages/css-data/package.jsonindex e12bffbe39..e912c9d1da 100644--- a/packages/css-data/package.json+++ b/packages/css-data/package.json@@ -10,18 +10,18 @@"checks": "yarn typecheck && yarn lint","dev": "build-package --watch","build": "build-package",- "build:mdn-data": "tsx ./bin/mdn-data.ts ./src/__generated__",+ "build:mdn-data": "tsx ./bin/mdn-data.ts ./src/__generated__ && prettier --write \"./src/__generated__/**/*.ts\"","lint": "eslint ./src --ext .ts,.tsx --max-warnings 0","publish-to-npm": "bash ../../bin/publish-to-npm.sh"},"dependencies": {},"devDependencies": {+ "@types/css-tree": "^2.0.0","@webstudio-is/scripts": "*",+ "camelcase": "^6.3.0",+ "css-tree": "^2.3.0","mdn-data": "2.0.23","typescript": "4.7.4",- "@types/css-tree": "^1.0.7",- "css-tree": "^2.1.0",- "camelcase": "^6.3.0","zod": "^3.19.1"},"peerDependencies": {diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.tsindex bf1ccd49f2..6eb6f9c90d 100644--- a/packages/css-engine/src/core/rules.ts+++ b/packages/css-engine/src/core/rules.ts@@ -12,6 +12,9 @@ class StylePropertyMap {this.#isDirty = true;this.onChange?.();}+ has(property: StyleProperty) {+ return this.#styleMap.has(property);+ }clear() {this.#styleMap.clear();this.#isDirty = true;@@ -90,7 +93,7 @@ export class MediaRule {export class PlaintextRule {cssText;- styleMap = new Map();+ styleMap = new StylePropertyMap();constructor(cssText: string) {this.cssText = cssText;}diff --git a/packages/design-system/src/components/combobox.tsx b/packages/design-system/src/components/combobox.tsxindex 65a476725b..42748163dd 100644--- a/packages/design-system/src/components/combobox.tsx+++ b/packages/design-system/src/components/combobox.tsx@@ -134,6 +134,7 @@ type UseComboboxProps<Item> = UseDownshiftComboboxProps<Item> & {items: Array<Item>;itemToString: (item: Item | null) => string;value: Item | null; // This is to prevent: "downshift: A component has changed the uncontrolled prop "selectedItem" to be controlled."+ onInputChange?: (value: string | undefined) => void;onItemSelect?: (value: Item | null) => void;onItemHighlight?: (value: Item | null) => void;stateReducer?: (@@ -149,6 +150,7 @@ export const useCombobox = <Item,>({items,value,itemToString,+ onInputChange,onItemSelect,onItemHighlight,stateReducer = (state, { changes }) => changes,@@ -168,15 +170,18 @@ export const useCombobox = <Item,>({selectedItem: value, // Prevent downshift warning about switching controlled modestateReducer,itemToString,- onInputValueChange({ inputValue }) {- filter(inputValue);+ onInputValueChange({ inputValue, type }) {+ if (type === comboboxStateChangeTypes.InputChange) {+ filter(inputValue);+ onInputChange?.(inputValue);+ }},onSelectedItemChange({ selectedItem }) {onItemSelect?.(selectedItem ?? null);},onHighlightedIndexChange({ highlightedIndex }) {if (highlightedIndex !== undefined) {- onItemHighlight?.(items[highlightedIndex] ?? null);+ onItemHighlight?.(filteredItems[highlightedIndex] ?? null);}},});diff --git a/packages/design-system/src/components/primitives/numeric-gesture-control.ts b/packages/design-system/src/components/primitives/numeric-gesture-control.tsindex d97e0d3977..b310541346 100644--- a/packages/design-system/src/components/primitives/numeric-gesture-control.ts+++ b/packages/design-system/src/components/primitives/numeric-gesture-control.ts@@ -64,17 +64,24 @@ export const numericScrubControl = (direction: direction,timerId: undefined,};++ let exitPointerLock: (() => void) | undefined = undefined;+const handleEvent = (event: PointerEvent) => {const { type, clientX, clientY, movementY, movementX } = event;const offset = direction === "horizontal" ? clientX : clientY;const movement = direction === "horizontal" ? movementX : -movementY;+switch (type) {case "pointerup": {const shouldComponentUpdate = Boolean(state.cursor);state.offset = 0;targetNode.removeEventListener("pointermove", handleEvent);clearTimeout(state.timerId);- exitPointerLock(state, event, targetNode);++ exitPointerLock?.();+ exitPointerLock = undefined;+if (shouldComponentUpdate)onValueChange?.({target: targetNode,@@ -88,10 +95,12 @@ export const numericScrubControl = (// light touches don't register corresponding pointerupif (event.pressure === 0 || event.button !== 0) break;state.offset = offset;- state.timerId = setTimeout(- () => requestPointerLock(state, event, targetNode),- 150- );+ state.timerId = setTimeout(() => {+ exitPointerLock?.();++ exitPointerLock = requestPointerLock(state, event, targetNode);+ }, 150);+targetNode.addEventListener("pointermove", handleEvent);break;}@@ -125,11 +134,18 @@ export const numericScrubControl = (eventNames.forEach((eventName) =>targetNode.addEventListener(eventName, handleEvent));+return {disconnectedCallback: () => {eventNames.forEach((eventName) =>targetNode.removeEventListener(eventName, handleEvent));++ clearTimeout(state.timerId);+ targetNode.removeEventListener("pointermove", handleEvent);++ exitPointerLock?.();+ exitPointerLock = undefined;},};};@@ -169,30 +185,26 @@ const requestPointerLock = (if (state.cursor) {targetNode.ownerDocument.documentElement.append(state.cursor);}+ return () => {+ if (state.cursor) {+ state.cursor.remove();+ state.cursor = undefined;+ }++ targetNode.ownerDocument.exitPointerLock();+ };} else {+ const { pointerId } = event;targetNode.ownerDocument.documentElement.style.setProperty("cursor",state.direction === "horizontal" ? "ew-resize" : "ns-resize");- targetNode.setPointerCapture(event.pointerId);- }-};+ targetNode.setPointerCapture(pointerId);-const exitPointerLock = (- state: NumericScrubState,- event: PointerEvent,- targetNode: HTMLElement-) => {- if (shouldUsePointerLock) {- if (state.cursor) {- state.cursor.remove();- state.cursor = undefined;- }- targetNode.onpointermove = null;- targetNode.ownerDocument.exitPointerLock();- } else {- targetNode.ownerDocument.documentElement.style.removeProperty("cursor");- targetNode.releasePointerCapture(event.pointerId);+ return () => {+ targetNode.ownerDocument.documentElement.style.removeProperty("cursor");+ targetNode.releasePointerCapture(pointerId);+ };}};diff --git a/yarn.lock b/yarn.lockindex c0863b660e..8e84ae014d 100644--- a/yarn.lock+++ b/yarn.lock@@ -5208,10 +5208,10 @@resolved "https://registry.yarnpkg.com/@types/cookie/-/cookie-0.4.1.tgz#bfd02c1f2224567676c1545199f87c3a861d878d"integrity sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==-"@types/css-tree@^1.0.7":- version "1.0.7"- resolved "https://registry.yarnpkg.com/@types/css-tree/-/css-tree-1.0.7.tgz#4483b824a7923d9a7819408a33144014b0c5124c"- integrity sha512-Pz+DfVODpQTAV6PwPBK6kzyy7+f6EyPbr1+mYkc1YolJfl2NAJ4wbg0TC/AJPBsqn9jWfyiO19A/sgpvFLfqnw==+"@types/css-tree@^2.0.0":+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/@types/css-tree/-/css-tree-2.0.0.tgz#b5f940aae863899a5a628114d8bc526863937e0a"+ integrity sha512-mY2sXRLBnUPMYw6mkOT+6dABeaNxAEKZz6scE9kQPNJx8fKe1fOsm8Honl7+xFYe6TKX8WNk2+7oMp2vBArJ9Q=="@types/debug@^4.0.0":version "4.1.7"@@ -8234,14 +8234,6 @@ css-tree@^1.1.2:mdn-data "2.0.14"source-map "^0.6.1"-css-tree@^2.0.4, css-tree@^2.1.0:- version "2.1.0"- resolved "https://registry.yarnpkg.com/css-tree/-/css-tree-2.1.0.tgz#170e27ccf94e7c5facb183765c25898be843d1d2"- integrity sha512-PcysZRzToBbrpoUrZ9qfblRIRf8zbEAkU0AIpQFtgkFK0vSbzOmBCvdSAx2Zg7Xx5wiYJKUKk0NMP7kxevie/A==- dependencies:- mdn-data "2.0.27"- source-map-js "^1.0.1"-css-tree@^2.2.1, css-tree@~2.2.0:version "2.2.1"resolved "https://registry.yarnpkg.com/css-tree/-/css-tree-2.2.1.tgz#36115d382d60afd271e377f9c5f67d02bd48c032"@@ -8250,6 +8242,14 @@ css-tree@^2.2.1, css-tree@~2.2.0:mdn-data "2.0.28"source-map-js "^1.0.1"+css-tree@^2.3.0:+ version "2.3.0"+ resolved "https://registry.yarnpkg.com/css-tree/-/css-tree-2.3.0.tgz#a0122cbc85305576df92ac528fb079c8217a15b2"+ integrity sha512-1rg0LiK2MFi4R3/lVvnRokEWTZb30ljSAe5x+0HHkZ+OqZaAeiP8g8Eh91VmkyCtQn9vMgQRiaTDYgLBt+2Qyw==+ dependencies:+ mdn-data "2.0.30"+ source-map-js "^1.0.1"+css-what@^6.0.1, css-what@^6.1.0:version "6.1.0"resolved "https://registry.yarnpkg.com/css-what/-/css-what-6.1.0.tgz#fb5effcf76f1ddea2c81bdfaa4de44e79bac70f4"@@ -12754,16 +12754,16 @@ [email protected]:resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.0.23.tgz#dfb6c41e50a0edb808cf340973ab29321b70808e"integrity sha512-IonVb7pfla2U4zW8rc7XGrtgq11BvYeCxWN8HS+KFBnLDE7XDK9AAMVhRuG6fj9BBsjc69Fqsp6WEActEdNTDQ==- version "2.0.27"- resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.0.27.tgz#1710baa7b0db8176d3b3d565ccb7915fc69525ab"- integrity sha512-kwqO0I0jtWr25KcfLm9pia8vLZ8qoAKhWZuZMbneJq3jjBD3gl5nZs8l8Tu3ZBlBAHVQtDur9rdDGyvtfVraHQ==-version "2.0.28"resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.0.28.tgz#5ec48e7bef120654539069e1ae4ddc81ca490eba"integrity sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==+ version "2.0.30"+ resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.0.30.tgz#ce4df6f80af6cfbe218ecd5c552ba13c4dfa08cc"+ integrity sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==+mdurl@^1.0.0:version "1.0.1"resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e"@@ -14921,9 +14921,9 @@ react-refresh@^0.11.0:integrity sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==react-remove-scroll-bar@^2.3.3:- version "2.3.3"- resolved "https://registry.yarnpkg.com/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.3.tgz#e291f71b1bb30f5f67f023765b7435f4b2b2cd94"- integrity sha512-i9GMNWwpz8XpUpQ6QlevUtFjHGqnPG4Hxs+wlIJntu/xcsZVEpJcIV71K3ZkqNy2q3GfgvkD7y6t/Sv8ofYSbw==+ version "2.3.4"+ resolved "https://registry.yarnpkg.com/react-remove-scroll-bar/-/react-remove-scroll-bar-2.3.4.tgz#53e272d7a5cb8242990c7f144c44d8bd8ab5afd9"+ integrity sha512-63C4YQBUt0m6ALadE9XV56hV8BgJWDmmTPY758iIJjfQKt2nYwoUrPk0LXRXcB/yIj82T1/Ixfdpdk68LwIB0A==dependencies:react-style-singleton "^2.2.1"tslib "^2.0.0"