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
Improve units in style panel (#735)
Bogdan Chadkin5fe9364cb154
diff --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 41bad17d6e..33ab97ccef 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@@ -358,9 +358,9 @@ export const CssValueInput = ({property,value:value.type === "unit" || value.type === "intermediate"- ? value+ ? value.unit: undefined,- onChange: (value) => onChangeComplete(value, "unit-select"),+ onChange: (unit) => onChangeComplete({ ...value, unit }, "unit-select"),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)event.preventDefault();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.tsindex 14235b36f1..e715e56971 100644--- 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.ts@@ -9,6 +9,8 @@ import { evaluateMath } from "./evaluate-math";import { units } from "@webstudio-is/css-data";import { toKebabCase } from "../keyword-utils";+const unitsList = Object.values(units).flat();+export const parseIntermediateOrInvalidValue = (property: StyleProperty,value: IntermediateStyleValue | InvalidValue@@ -38,7 +40,7 @@ export const parseIntermediateOrInvalidValue = (// 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 unitRegex = new RegExp(`(?:${unitsList.join("|")})`, "g");const matchedUnit = value.value.match(unitRegex)?.[0];const unitlessValue = value.value.replace(unitRegex, "");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 b8369ebe66..c816669509 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@@ -1,6 +1,6 @@import { useState, useMemo } from "react";-import type { Unit, UnitValue, StyleValue } from "@webstudio-is/css-data";-import { toValue } from "@webstudio-is/css-engine";+import type { Unit } from "@webstudio-is/css-data";+import { properties, units } from "@webstudio-is/css-data";import * as SelectPrimitive from "@radix-ui/react-select";import {SelectScrollUpButton,@@ -13,95 +13,62 @@ import {textStyles,} 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"],- ["%", "%"],- ["em", "EM"],- ["rem", "REM"],- ["ch", "CH"],- ["vw", "VW"],- ["vh", "VH"],- ["number", "—"],-]);--const renderUnitMap: Map<string, Unit> = new Map();-for (const [key, value] of unitRenderMap.entries()) {- renderUnitMap.set(value, key);-}+type UnitOption = {+ id: Unit;+ label: string;+};-const defaultUnits = Array.from(unitRenderMap.keys());+const visibleLengthUnits = ["px", "em", "rem", "ch", "vw", "vh"] as const;type UseUnitSelectType = {property: string;- value?: UnitValue | IntermediateStyleValue;- onChange: (value: StyleValue | IntermediateStyleValue) => void;- units?: Array<Unit>;+ value?: Unit;+ onChange: (value: Unit) => void;onCloseAutoFocus: (event: Event) => void;};export const useUnitSelect = ({property,- onChange,value,- units = defaultUnits,- ...props+ onChange,+ onCloseAutoFocus,}: UseUnitSelectType): [boolean, JSX.Element | null] => {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?.unit !== undefined ? unitRenderMap.get(value.unit) : undefined;+ const options = useMemo(() => {+ const options: UnitOption[] = [];+ const { unitGroups } = properties[property as keyof typeof properties];+ for (const unitGroup of unitGroups) {+ if (unitGroup === "number") {+ options.push({ id: "number", label: "—" });+ continue;+ }+ const visibleUnits =+ unitGroup === "length" ? visibleLengthUnits : units[unitGroup];+ for (const unit of visibleUnits) {+ options.push({ id: unit, label: unit.toLocaleUpperCase() });+ }+ }+ return options;+ }, [property]);if (- value === undefined ||- renderUnits === undefined ||- renderValue === undefined ||- renderUnits.length < 2+ options.length === 0 ||+ // hide unit select when value cannot have units+ (options.length === 1 && options[0].id === "number")) {return [isOpen, null];}const select = (<UnitSelect- {...props}- value={renderValue}- options={renderUnits}+ value={value ?? options[0].id}+ options={options}open={isOpen}+ onCloseAutoFocus={onCloseAutoFocus}onOpenChange={setIsOpen}- onChange={(option) => {- const unit = renderUnitMap.get(option);- if (unit === undefined) {- return;- }- onChange?.({- ...value,- unit,- });- }}+ onChange={onChange}/>);@@ -113,9 +80,9 @@ const StyledTrigger = styled(TextFieldIconButton, textStyles, {});type UnitSelectProps = {- options: Array<string>;+ options: Array<UnitOption>;value: string;- onChange: (value: string) => void;+ onChange: (value: Unit) => void;onOpenChange: (open: boolean) => void;onCloseAutoFocus: (event: Event) => void;open: boolean;@@ -129,6 +96,7 @@ const UnitSelect = ({onCloseAutoFocus,open,}: UnitSelectProps) => {+ const matchedOption = options.find((item) => item.id === value);return (<SelectPrimitive.Rootvalue={value}@@ -138,7 +106,10 @@ const UnitSelect = ({><SelectPrimitive.SelectTrigger asChild><StyledTrigger variant="unit">- <SelectPrimitive.Value>{value}</SelectPrimitive.Value>+ <SelectPrimitive.Value>+ {/* fallback to uppercased value for not listed units */}+ {matchedOption?.label ?? value.toLocaleUpperCase()}+ </SelectPrimitive.Value></StyledTrigger></SelectPrimitive.SelectTrigger><SelectPrimitive.Portal>@@ -161,9 +132,9 @@ const UnitSelect = ({<ChevronUpIcon /></SelectScrollUpButton><SelectViewport>- {options.map((option) => (- <SelectItem key={option} value={option} textValue={option}>- {option}+ {options.map(({ id, label }) => (+ <SelectItem key={id} value={id}>+ {label}</SelectItem>))}</SelectViewport>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 4cda81d8f4..32d1150c06 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,7 +1,12 @@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 type {+ StyleProperty,+ StyleValue,+ Unit,+ UnitGroup,+} from "@webstudio-is/css-data";+import { units, properties, keywordValues } from "@webstudio-is/css-data";import warnOnce from "warn-once";const cssTryParseValue = (input: string) => {@@ -58,77 +63,57 @@ export const parseCssValue = (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;+ const first = ast.children.first;+ const unitGroups = properties[property as keyof typeof properties]+ .unitGroups as ReadonlyArray<UnitGroup>;- if (parsedUnit !== undefined) {+ if (first?.type === "Number") {+ if (unitGroups.includes("number")) {return {type: "unit",- unit: parsedUnit as Unit,- value: Number(singleChild.value),+ unit: "number",+ value: Number(first.value),};}+ return invalidValue;}- if (singleChild?.type === "Percentage") {- return {- type: "unit",- unit: "%",- value: Number(singleChild.value),- };+ if (first?.type === "Dimension") {+ const unit = first.unit as typeof units[keyof typeof units][number];+ for (const unitGroup of unitGroups) {+ const possibleUnits = units[unitGroup] as ReadonlyArray<typeof unit>;+ if (possibleUnits.includes(unit)) {+ return {+ type: "unit",+ unit: unit as Unit,+ value: Number(first.value),+ };+ }+ }+ return invalidValue;}- }-- 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?.length === 1) {- const singleMatch = match[0];- if (singleMatch.syntax?.type === "Keyword") {+ if (first?.type === "Percentage") {+ if (unitGroups.includes("percentage")) {+ return {+ type: "unit",+ unit: "%",+ value: Number(first.value),+ };+ }+ return invalidValue;+ }+ if (first?.type === "Identifier") {+ const values = keywordValues[+ property as keyof typeof keywordValues+ ] as ReadonlyArray<string>;+ if (values?.includes(input)) {return {type: "keyword",value: input,- } as const;- }-- if (singleMatch.syntax?.type === "Type") {- if ("match" in singleMatch && singleMatch.match.length === 1) {- const singleMatchMatch = singleMatch.match[0];-- if (singleMatchMatch.syntax?.type === "Keyword") {- return {- type: "keyword",- value: input,- } as const;- }- }+ };}+ return invalidValue;}}diff --git a/packages/css-data/bin/mdn-data.ts b/packages/css-data/bin/mdn-data.tsindex 636ee207fe..3cb530b754 100755--- a/packages/css-data/bin/mdn-data.ts+++ b/packages/css-data/bin/mdn-data.ts@@ -1,7 +1,6 @@import { parse, definitionSyntax, type DSNode } from "css-tree";import properties from "mdn-data/css/properties.json";import syntaxes from "mdn-data/css/syntaxes.json";-import unitsList from "mdn-data/css/units.json";import data from "css-tree/dist/data";import { popularityIndex } from "../src/popularity-index";import camelCase from "camelcase";@@ -289,8 +288,6 @@ const keywordValues = (() => {return result;})();+writeToFile("units.ts", "units", units);writeToFile("properties.ts", "properties", propertiesData);-// @todo % is somehow not in the units list-// https://github.com/mdn/data/issues/553-writeToFile("units.ts", "units", [...Object.keys(unitsList), "%"]);writeToFile("keyword-values.ts", "keywordValues", keywordValues);diff --git a/packages/css-data/src/__generated__/units.ts b/packages/css-data/src/__generated__/units.tsindex a0d157738e..11186094a6 100644--- a/packages/css-data/src/__generated__/units.ts+++ b/packages/css-data/src/__generated__/units.ts@@ -1,34 +1,63 @@// This file was generated by pnpm mdn-data-export const units = [- "cap",- "ch",- "cm",- "deg",- "dpcm",- "dpi",- "dppx",- "em",- "ex",- "fr",- "grad",- "Hz",- "ic",- "in",- "kHz",- "mm",- "ms",- "pc",- "pt",- "px",- "Q",- "rad",- "rem",- "s",- "turn",- "vh",- "vmax",- "vmin",- "vw",- "x",- "%",-] as const;+export const units = {+ number: [],+ percentage: ["%"],+ angle: ["deg", "grad", "rad", "turn"],+ decibel: ["db"],+ flex: ["fr"],+ frequency: ["hz", "khz"],+ length: [+ "cm",+ "mm",+ "q",+ "in",+ "pt",+ "pc",+ "px",+ "em",+ "rem",+ "ex",+ "rex",+ "cap",+ "rcap",+ "ch",+ "rch",+ "ic",+ "ric",+ "lh",+ "rlh",+ "vw",+ "svw",+ "lvw",+ "dvw",+ "vh",+ "svh",+ "lvh",+ "dvh",+ "vi",+ "svi",+ "lvi",+ "dvi",+ "vb",+ "svb",+ "lvb",+ "dvb",+ "vmin",+ "svmin",+ "lvmin",+ "dvmin",+ "vmax",+ "svmax",+ "lvmax",+ "dvmax",+ "cqw",+ "cqh",+ "cqi",+ "cqb",+ "cqmin",+ "cqmax",+ ],+ resolution: ["dpi", "dpcm", "dppx", "x"],+ semitones: ["st"],+ time: ["s", "ms"],+} as const;diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.tsindex 03b3298e2b..27517bcb33 100644--- a/packages/css-data/src/schema.ts+++ b/packages/css-data/src/schema.ts@@ -17,7 +17,16 @@ type CustomProperty = `--${string}`;export type AppliesTo = Properties[StyleProperty]["appliesTo"];-const Unit = z.union([z.enum(units), z.literal("number")]);+export type UnitGroup = keyof typeof units;++type UnitEnum = typeof units[UnitGroup][number];++const Unit = z.union([+ // expected tuple with at least single element+ // so cast to tuple with single union element to get correct inference+ z.enum(Object.values(units).flat() as [UnitEnum]),+ z.literal("number"),+]);export type Unit = z.infer<typeof Unit>;diff --git a/packages/react-sdk/src/css/get-browser-style.ts b/packages/react-sdk/src/css/get-browser-style.tsindex f1e49a92da..a803ab9d41 100644--- a/packages/react-sdk/src/css/get-browser-style.ts+++ b/packages/react-sdk/src/css/get-browser-style.ts@@ -2,19 +2,20 @@ import { detectFont } from "detect-font";import type { Style, StyleValue, Unit } from "@webstudio-is/css-data";import { properties, units } from "@webstudio-is/css-data";-const unitRegex = new RegExp(`${units.join("|")}`);+const unitsList = Object.values(units).flat();+const unitRegex = new RegExp(`${unitsList.join("|")}`);// @todo use a parserconst parseValue = (property: keyof typeof properties,value: string): StyleValue => {- const number = parseFloat(value);+ const number = Number.parseFloat(value);const parsedUnit = unitRegex.exec(value);if (value === "rgba(0, 0, 0, 0)") {value = "transparent";}- if (isNaN(number) || parsedUnit === null) {+ if (Number.isNaN(number)) {return {type: "keyword",value,@@ -25,6 +26,14 @@ const parseValue = (return properties[property].initial;}+ if (parsedUnit === null) {+ return {+ type: "unit",+ unit: "number",+ value: number,+ };+ }+return {type: "unit",unit: parsedUnit[0] as Unit,