Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Units menu in css value input (#1524)

Ivan Starkov5ba6c2556556
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.tsx
index 422c59578f..bd84f49385 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
@@ -34,7 +34,7 @@ import { toValue } from "@webstudio-is/css-engine";
import { useDebouncedCallback } from "use-debounce";
import type { StyleSource } from "../style-info";
import { toPascalCase } from "../keyword-utils";
-import { isValid } from "../parse-css-value";
+
import {
selectedInstanceBrowserStyleStore,
selectedInstanceUnitSizesStore,
@@ -364,15 +364,15 @@ export const CssValueInput = ({
const [isUnitsOpen, unitSelectElement] = useUnitSelect({
property,
- showUnitless:
- value.type === "unit" || value.type === "intermediate"
- ? isValid(property, `${value.value}`)
- : false,
- value:
- value.type === "unit" || value.type === "intermediate"
- ? value.unit
- : undefined,
- onChange: (unit) => {
+ value,
+ onChange: (unitOrKeyword) => {
+ if (unitOrKeyword.type === "keyword") {
+ onChangeComplete(unitOrKeyword, "unit-select");
+ return;
+ }
+
+ const unit = unitOrKeyword.value;
+
// value looks like a number and just edited (type === "intermediate")
// no additional conversions are necessary
if (
@@ -573,7 +573,7 @@ export const CssValueInput = ({
css={{ cursor: "default" }}
/>
</ComboboxAnchor>
- <ComboboxContent align="start" sideOffset={8} collisionPadding={10}>
+ <ComboboxContent align="start" sideOffset={2} collisionPadding={10}>
<ComboboxListbox {...menuProps}>
{isOpen &&
items.map((item, index) => (
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts
index f3d0c1272f..4c75168d2d 100644
--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts
@@ -1,12 +1,13 @@
import { describe, test, expect } from "@jest/globals";
import { parseIntermediateOrInvalidValue } from "./parse-intermediate-or-invalid-value";
+import { toKebabCase, toPascalCase } from "../keyword-utils";
const properties = ["width", "lineHeight", "backgroundPositionX"] as const;
const propertiesAndKeywords = [
- ["width", "auto"],
- ["lineHeight", "normal"],
- ["backgroundPositionX", "center"],
+ ["width", "auto" as string],
+ ["lineHeight", "normal" as string],
+ ["backgroundPositionX", "center" as string],
] as const;
describe("Parse intermediate or invalid value without math evaluation", () => {
@@ -86,6 +87,38 @@ describe("Parse intermediate or invalid value without math evaluation", () => {
});
}
});
+
+ test("accept keywords written as pascal case", () => {
+ const pascalCaseKeywords = propertiesAndKeywords.map(
+ ([property, keyword]) => [property, toPascalCase(keyword)] as const
+ );
+
+ for (const [propery, keyword] of pascalCaseKeywords) {
+ const result = parseIntermediateOrInvalidValue(propery, {
+ type: "intermediate",
+ value: keyword,
+ unit: "em",
+ });
+
+ expect(result).toEqual({
+ type: "keyword",
+ value: toKebabCase(keyword),
+ });
+ }
+ });
+
+ test("keyword with pascal case name", () => {
+ const result = parseIntermediateOrInvalidValue("boxSizing", {
+ type: "intermediate",
+ value: "Border Box",
+ unit: "em",
+ });
+
+ expect(result).toEqual({
+ type: "keyword",
+ value: "border-box",
+ });
+ });
});
describe("Parse intermediate or invalid value with math evaluation", () => {
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select-options.ts b/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select-options.ts
new file mode 100644
index 0000000000..1857e3bc44
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select-options.ts
@@ -0,0 +1,141 @@
+import type { CssValueInputValue } from "./css-value-input";
+import { isValid } from "../parse-css-value";
+import { toPascalCase } from "../keyword-utils";
+import { keywordValues, properties, units } from "@webstudio-is/css-data";
+import type { UnitOption } from "./unit-select";
+
+// To make sorting stable
+const preferedSorting = [
+ "number",
+ "px",
+ ...units.percentage,
+ "em",
+ "rem",
+ "dvw",
+ "dvh",
+ ...units.length,
+ ...units.angle,
+ ...units.decibel,
+ ...units.flex,
+ ...units.frequency,
+ ...units.resolution,
+ ...units.semitones,
+ ...units.time,
+];
+
+const visibleLengthUnits = ["px", "em", "rem", "dvw", "dvh"] as const;
+
+export const buildOptions = (
+ property: string,
+ value: CssValueInputValue,
+ nestedSelectButtonUnitless: string
+) => {
+ const unit =
+ value.type === "unit" || value.type === "intermediate"
+ ? value.unit
+ : undefined;
+
+ const options: UnitOption[] = [];
+ const { unitGroups } = properties[property as keyof typeof properties];
+
+ for (const unitGroup of unitGroups) {
+ if (unitGroup === "number") {
+ options.push({
+ id: "number",
+ type: "unit",
+ label: nestedSelectButtonUnitless,
+ });
+ continue;
+ }
+
+ const visibleUnits =
+ unitGroup === "length" ? visibleLengthUnits : units[unitGroup];
+ for (const unit of visibleUnits) {
+ options.push({
+ id: unit,
+ type: "unit",
+ label: unit.toLocaleUpperCase(),
+ });
+ }
+ }
+
+ // Special case for 0, which is often used as a unitless value
+ const showUnitless =
+ value.type === "unit" || value.type === "intermediate"
+ ? isValid(property, `${value.value}`)
+ : false;
+
+ if (
+ showUnitless &&
+ options.some((option) => option.id === "number") === false
+ ) {
+ options.push({
+ id: "number",
+ type: "unit",
+ label: nestedSelectButtonUnitless,
+ });
+ }
+
+ // Add a valid unit, such as ch or vw, to the list of options, even if it's not already visible
+ // This allows the currently selected unit to be displayed selected when the menu is opened
+ if (
+ unit !== undefined &&
+ options.some((option) => option.id === unit) === false
+ ) {
+ options.push({
+ id: unit,
+ type: "unit",
+ label:
+ unit === "number"
+ ? nestedSelectButtonUnitless
+ : unit.toLocaleUpperCase(),
+ });
+ }
+
+ const indexSortValue = (number: number) =>
+ number === -1 ? Number.POSITIVE_INFINITY : number;
+
+ // Use a stable sort for known dimensions, such as percentages after lengths
+ // This ensures that the order of options remains consistent between renders
+ options.sort(
+ (optionA, optionB) =>
+ indexSortValue(preferedSorting.indexOf(optionA.id)) -
+ indexSortValue(preferedSorting.indexOf(optionB.id))
+ );
+
+ // This value can't have units, skip select
+ // (show keywords menu instead)
+ if (options.length === 0) {
+ return [];
+ }
+
+ const propertyKeywordsSet = new Set(
+ keywordValues[property as keyof typeof keywordValues]
+ );
+
+ // Opinionated set of keywords to show
+ const webstudioKeywords = ["auto", "normal", "none"].filter((keyword) =>
+ propertyKeywordsSet.has(keyword as never)
+ );
+
+ for (const keyword of webstudioKeywords) {
+ options.push({
+ id: keyword,
+ label: toPascalCase(keyword),
+ type: "keyword",
+ });
+ }
+
+ if (
+ value.type === "keyword" &&
+ options.some((option) => option.id === value.value) === false
+ ) {
+ options.push({
+ id: value.value,
+ label: toPascalCase(value.value),
+ type: "keyword",
+ });
+ }
+
+ return options;
+};
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select.test.ts b/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select.test.ts
new file mode 100644
index 0000000000..55379e1e86
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select.test.ts
@@ -0,0 +1,132 @@
+import { buildOptions } from "./unit-select-options";
+import { describe, test, expect } from "@jest/globals";
+//@todo investigate Imports from "@webstudio-is/design-system" cause jest to fail
+export const nestedSelectButtonUnitless = " – ";
+
+describe("Unit menu options", () => {
+ test("Should show options", () => {
+ expect(
+ buildOptions(
+ "width",
+ { value: 10, type: "unit", unit: "px" },
+ nestedSelectButtonUnitless
+ )
+ ).toMatchInlineSnapshot(`
+ [
+ {
+ "id": "px",
+ "label": "PX",
+ "type": "unit",
+ },
+ {
+ "id": "%",
+ "label": "%",
+ "type": "unit",
+ },
+ {
+ "id": "em",
+ "label": "EM",
+ "type": "unit",
+ },
+ {
+ "id": "rem",
+ "label": "REM",
+ "type": "unit",
+ },
+ {
+ "id": "dvw",
+ "label": "DVW",
+ "type": "unit",
+ },
+ {
+ "id": "dvh",
+ "label": "DVH",
+ "type": "unit",
+ },
+ {
+ "id": "auto",
+ "label": "Auto",
+ "type": "keyword",
+ },
+ ]
+ `);
+ });
+
+ test("Should show options with unitless if value supports unitless", () => {
+ expect(
+ buildOptions(
+ "width",
+ { value: 0, type: "unit", unit: "px" },
+ nestedSelectButtonUnitless
+ ).some((option) => option.id === "number")
+ ).toBe(true);
+ });
+
+ test("Should show options with units if value is keyword", () => {
+ expect(
+ buildOptions(
+ "width",
+ { value: "auto", type: "keyword" },
+ nestedSelectButtonUnitless
+ )
+ ).toMatchInlineSnapshot(`
+ [
+ {
+ "id": "px",
+ "label": "PX",
+ "type": "unit",
+ },
+ {
+ "id": "%",
+ "label": "%",
+ "type": "unit",
+ },
+ {
+ "id": "em",
+ "label": "EM",
+ "type": "unit",
+ },
+ {
+ "id": "rem",
+ "label": "REM",
+ "type": "unit",
+ },
+ {
+ "id": "dvw",
+ "label": "DVW",
+ "type": "unit",
+ },
+ {
+ "id": "dvh",
+ "label": "DVH",
+ "type": "unit",
+ },
+ {
+ "id": "auto",
+ "label": "Auto",
+ "type": "keyword",
+ },
+ ]
+ `);
+ });
+
+ test("Should add unit to options even if it's not in a visibleLengthUnits", () => {
+ expect(
+ buildOptions(
+ "width",
+ { value: 10, type: "unit", unit: "ch" },
+ nestedSelectButtonUnitless
+ ).some((option) => option.id === "ch")
+ ).toBe(true);
+ });
+
+ test("Should add keyword to options", () => {
+ expect(
+ buildOptions(
+ "width",
+ { value: "inherit", type: "keyword" },
+ nestedSelectButtonUnitless
+ ).some((option) => option.id === "inherit")
+ ).toBe(true);
+ });
+});
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select.tsx b/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select.tsx
index e976662ec1..625296184e 100644
--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/unit-select.tsx
@@ -1,6 +1,5 @@
import { useState, useMemo } from "react";
-import type { Unit } from "@webstudio-is/css-data";
-import { properties, units } from "@webstudio-is/css-data";
+import { type Unit } from "@webstudio-is/css-data";
import * as SelectPrimitive from "@radix-ui/react-select";
import {
SelectScrollUpButton,
@@ -12,71 +11,67 @@ import {
nestedSelectButtonUnitless,
} from "@webstudio-is/design-system";
import { ChevronDownIcon, ChevronUpIcon } from "@webstudio-is/icons";
+import type { CssValueInputValue } from "./css-value-input";
+import { buildOptions } from "./unit-select-options";
-type UnitOption = {
- id: Unit;
- label: string;
-};
-
-const visibleLengthUnits = ["px", "em", "rem", "ch", "vw", "vh"] as const;
+export type UnitOption =
+ | {
+ id: Unit;
+ label: string;
+ type: "unit";
+ }
+ | { id: string; label: string; type: "keyword" };
type UseUnitSelectType = {
property: string;
- value?: Unit;
- showUnitless: boolean;
- onChange: (value: Unit) => void;
+ value: CssValueInputValue;
+ onChange: (
+ value: { type: "unit"; value: Unit } | { type: "keyword"; value: string }
+ ) => void;
onCloseAutoFocus: (event: Event) => void;
};
export const useUnitSelect = ({
property,
value,
- // edge-case, most css properties accept unitless value 0
- showUnitless,
onChange,
onCloseAutoFocus,
}: UseUnitSelectType): [boolean, JSX.Element | null] => {
const [isOpen, setIsOpen] = useState(false);
- 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: nestedSelectButtonUnitless });
- continue;
- }
- const visibleUnits =
- unitGroup === "length" ? visibleLengthUnits : units[unitGroup];
- for (const unit of visibleUnits) {
- options.push({ id: unit, label: unit.toLocaleUpperCase() });
- }
- }
-
- if (showUnitless && !options.some((o) => o.id === "number")) {
- options.push({ id: "number", label: nestedSelectButtonUnitless });
- }
+ const unit =
+ value.type === "unit" || value.type === "intermediate"
+ ? value.unit
+ : undefined;
- return options;
- }, [property, showUnitless]);
+ const options = useMemo(
+ () => buildOptions(property, value, nestedSelectButtonUnitless),
+ [property, value]
+ );
- if (
- options.length === 0 ||
- // hide unit select when value cannot have units
- (options.length === 1 && options[0].id === "number")
- ) {
+ if (options.length === 0) {
return [isOpen, null];
}
+ const unitOrKeyword: string | undefined =
+ unit ?? (value.type === "keyword" ? value.value : undefined);
+
const select = (
<UnitSelect
- value={value}
+ value={unitOrKeyword}
+ label={unit ?? nestedSelectButtonUnitless}
options={options}
open={isOpen}
onCloseAutoFocus={onCloseAutoFocus}
onOpenChange={setIsOpen}
- onChange={onChange}
- labelFallback={options[0].label}
+ onChange={(unitOption) => {
+ if (unitOption.type === "keyword") {
+ onChange({ type: "keyword", value: unitOption.id });
+ return;
+ }
+
+ onChange({ type: "unit", value: unitOption.id });
+ }}
/>
);
@@ -86,37 +81,39 @@ export const useUnitSelect = ({
type UnitSelectProps = {
options: Array<UnitOption>;
value?: string | undefined;
- onChange: (value: Unit) => void;
+ label?: string | undefined;
+ onChange: (value: UnitOption) => void;
onOpenChange: (open: boolean) => void;
onCloseAutoFocus: (event: Event) => void;
open: boolean;
- labelFallback: string;
};
const UnitSelect = ({
options,
value,
+ label,
onChange,
onOpenChange,
onCloseAutoFocus,
open,
- labelFallback,
}: UnitSelectProps) => {
- const matchedOption = options.find((item) => item.id === value);
return (
<SelectPrimitive.Root
value={value}
- onValueChange={onChange}
+ onValueChange={(value) => {
+ const optionValue = options.find((option) => option.id === value);
+ if (optionValue === undefined) {
+ return;
+ }
+ onChange(optionValue);
+ }}
onOpenChange={onOpenChange}
open={open}
>
<SelectPrimitive.SelectTrigger asChild>
<NestedSelectButton tabIndex={-1}>
<SelectPrimitive.Value>
- {matchedOption?.label ??
- (value === "number"
- ? nestedSelectButtonUnitless
- : value ?? labelFallback)}
+ {value === "number" ? nestedSelectButtonUnitless : label}
</SelectPrimitive.Value>
</NestedSelectButton>
</SelectPrimitive.SelectTrigger>
diff --git a/apps/builder/app/builder/features/style-panel/shared/parse-css-value.ts b/apps/builder/app/builder/features/style-panel/shared/parse-css-value.ts
index e1ef2f8d10..8fa5368d20 100644
--- a/apps/builder/app/builder/features/style-panel/shared/parse-css-value.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/parse-css-value.ts
@@ -114,10 +114,18 @@ export const parseCssValue = (
const values = keywordValues[
property as keyof typeof keywordValues
] as ReadonlyArray<string>;
- if (values?.includes(input)) {
+ const lettersRegex = /[^a-zA-Z]+/g;
+ const searchValues = values.map((value) =>
+ value.replace(lettersRegex, "").toLowerCase()
+ );
+ const keywordInput = input.replace(lettersRegex, "").toLowerCase();
+
+ const index = searchValues.indexOf(keywordInput);
+
+ if (index > -1) {
return {
type: "keyword",
- value: input,
+ value: values[index],
};
}
}