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
wip cssvalue input with select and combobox
Oleg Isonene3a40b4b0e9b
diff --git a/apps/designer/.storybook/preview.tsx b/apps/designer/.storybook/preview.tsxindex 5bc24f57f5..d4d4c2037d 100644--- a/apps/designer/.storybook/preview.tsx+++ b/apps/designer/.storybook/preview.tsx@@ -15,7 +15,7 @@ export const parameters = {const globalStyles = globalCss({body: {backgroundColor: "$background",- color: "$text",+ color: "$hiContrast",fontFamily: "$sans",},});diff --git a/apps/designer/app/dashboard/components/card.tsx b/apps/designer/app/dashboard/components/card.tsxindex 5e4a9f1c58..7dbf9d19c4 100644--- a/apps/designer/app/dashboard/components/card.tsx+++ b/apps/designer/app/dashboard/components/card.tsx@@ -40,7 +40,6 @@ export const SelectProjectCard = ({Select a project</Heading><Select- size={2}name="project"options={options}onChange={setSelectedProject}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 5b1002f417..7600895f23 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,7 +1,7 @@import { CssValueInput } from "~/designer/features/style-panel/shared/css-value-input/css-value-input";import { getFinalValue } from "../../shared/get-final-value";import { ControlProps } from "../../style-sections";-import { StyleValue } from "@webstudio-is/react-sdk";+import { toValue } from "@webstudio-is/react-sdk";export const TextControl = ({currentStyle,@@ -17,33 +17,19 @@ export const TextControl = ({const setValue = setProperty(styleConfig.property);- const handleChange = (- styleValue: StyleValue | undefined,- isEphemeral: boolean- ) => {- if (styleValue === undefined) {- setValue("");- return;- }- const { value, type } = styleValue;- const newValue =- type === "unit" ? `${value}${styleValue.unit}` : `${value}`;- setValue(newValue, { isEphemeral });- };-return (<CssValueInputproperty={styleConfig.property}value={value}- items={styleConfig.items.map((item) => ({+ keywords={styleConfig.items.map((item) => ({type: "keyword",value: item.name,}))}- onChange={(value) => {- handleChange(value, true);+ onChange={(styleValue) => {+ setValue(toValue(styleValue), { isEphemeral: true });}}- onChangeComplete={(value) => {- handleChange(value, false);+ onChangeComplete={(styleValue) => {+ setValue(toValue(styleValue));}}/>);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 55653f427f..2c6a3d40fc 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@@ -2,6 +2,7 @@ import React from "react";import { Flex, TextField } from "@webstudio-is/design-system";import { StyleValue } from "@webstudio-is/react-sdk";import { CssValueInput } from "./css-value-input";+import { action } from "@storybook/addon-actions";export default {component: CssValueInput,@@ -17,26 +18,26 @@ export const WithKeywords = () => {<CssValueInputproperty="width"value={value}- items={[+ keywords={[{ type: "keyword", value: "auto" },{ type: "keyword", value: "min-content" },{ type: "keyword", value: "max-content" },{ type: "keyword", value: "fit-content" },]}onChange={(value) => {- console.log("onChange", value);setValue(value);}}onChangeComplete={(newValue) => {// on blur, select, enter etc.setValue(newValue);+ action("onChangeComplete")(newValue);}}/>);};export const WithIcons = () => {- const [value, setValue] = React.useState<StyleValue | undefined>({+ const [value, setValue] = React.useState<StyleValue>({type: "keyword",value: "space-around",});@@ -45,7 +46,7 @@ export const WithIcons = () => {<CssValueInputproperty="alignItems"value={value}- items={[+ keywords={[{ type: "keyword", value: "normal" },{ type: "keyword", value: "start" },{ type: "keyword", value: "end" },@@ -55,21 +56,19 @@ export const WithIcons = () => {{ type: "keyword", value: "space-between" },]}onChange={(newValue) => {- // every time we change the input with units- if (newValue?.type === "unit") {- setValue(newValue);- }+ setValue(newValue);}}onChangeComplete={(newValue) => {// on blur, select, enter etc.setValue(newValue);+ action("onChangeComplete")(newValue);}}/>);};export const WithUnits = () => {- const [value, setValue] = React.useState<StyleValue | undefined>({+ const [value, setValue] = React.useState<StyleValue>({type: "unit",value: 100,unit: "px",@@ -80,21 +79,19 @@ export const WithUnits = () => {<CssValueInputproperty="rowGap"value={value}- items={[+ keywords={[{ type: "keyword", value: "auto" },{ type: "keyword", value: "min-content" },{ type: "keyword", value: "max-content" },{ type: "keyword", value: "fit-content" },]}onChange={(newValue) => {- // every time we change the input with units- if (newValue === undefined || newValue?.type === "unit") {- setValue(newValue);- }+ setValue(newValue);}}onChangeComplete={(newValue) => {// on blur, select, enter etc.setValue(newValue);+ action("onChangeComplete")(newValue);}}/><TextFielddiff --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 8e1c890c76..74c67ceeae 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@@ -2,60 +2,108 @@ import {Box,TextField,useCombobox,- comboboxStateChangeTypes,ComboboxPopper,ComboboxPopperContent,ComboboxPopperAnchor,ComboboxListbox,ComboboxListboxItem,IconButton,+ Select,} from "@webstudio-is/design-system";import { ChevronDownIcon } from "@webstudio-is/icons";import {- KeywordValue,- StyleProperty,+ type KeywordValue,+ type StyleProperty,+ type Unit,+ type UnitValue,+ type UnsetValue,StyleValue,- Unit,- units,+ units as unsortedUnits,} from "@webstudio-is/react-sdk";-import { useCallback, useEffect, useState } from "react";-import { parseCssValue } from "../parse-css-value";--const sortedUnits = units- .slice(0)- .sort((v) =>- ["%", "px", "rem", "em", "ch", "vh", "vw", "hv", "vmin", "vmax"].includes(v)- ? -1- : 1+import { useEffect, useRef } from "react";++// @todo sorting doesn't work+export const defaultUnits: Array<Unit> = [...unsortedUnits].sort((unit) =>+ ["px", "%", "em", "rem", "ch", "vw", "vh", "vmin", "vmax"].includes(unit)+ ? -1+ : 1+);++const defaultKeywords: [] = [];++const defaultValue: UnsetValue = { type: "unset", value: "" };++type UnitSelectType = {+ value: UnitValue;+ onChange: (value: StyleValue) => void;+ units?: Array<Unit>;+};++const UnitSelect = ({+ onChange,+ value,+ units = defaultUnits,+ ...props+}: UnitSelectType) => {+ return (+ <Select+ {...props}+ value={value.unit}+ options={units}+ suffix={null}+ ghost+ onChange={(unit) => {+ onChange?.({+ ...value,+ unit,+ } as UnitValue);+ }}+ />);+};type CssValueInputProps = {property: StyleProperty;- value: StyleValue;- items?: Array<KeywordValue>;+ value?: StyleValue;+ keywords?: Array<KeywordValue>;+ units?: Array<Unit>;onChange: (value: StyleValue) => void;onChangeComplete: (value: StyleValue) => void;};+/**+ * Common:+ * - Free text editing+ * - Filterable keywords list (click on chevron or arrow down)+ * - When text is a number - unit mode+ * - Enter or blur submits the value+ * - After submission, when value is an invalid CSS value - invalid mode+ *+ * Unit mode:+ * - Unit selection on unit button click+ * - When selecting unit arrow keys are used to navigate unit items+ * - When selecting unit Enter key or click is used to select item+ * - When selecting unit Escape key is used to close list+ * - Key up and down on focused input increment/decrement the value+ * - Typing a unit in unit mode will change the selected unit+ * - During typing the unit until unit is matched, input is in invalid mode+ * - Math expression: "2px + 3em" (like CSS calc())+ *+ * Keywords mode:+ * - Filter by typing+ * - Arrow keys are used to navigate keyword items+ * - Enter key or click is used to select item when list is open+ * - Escape key is used to close list+ */+export const CssValueInput = ({property,- value,- items: itemsProp = [],+ value = defaultValue,+ keywords = defaultKeywords,+ units,onChange,onChangeComplete,}: CssValueInputProps) => {- const isInvalid = false;- const onItemSelect = () => {};-- const stateReducer = useCallback((state, action) => {- switch (action.type) {- case comboboxStateChangeTypes.InputChange: {- }- }-- return action.changes;- }, []);-const {items,getInputProps,@@ -64,28 +112,54 @@ export const CssValueInput = ({getMenuProps,getItemProps,isOpen,- } = useCombobox({- items: itemsProp,+ } = useCombobox<StyleValue>({+ items: value.type === "keyword" ? keywords : defaultKeywords,value,- itemToString: (item) => item?.value ?? "",- onItemSelect,- stateReducer,+ // @todo if we String() the value, it leads to an infinite loop+ itemToString: (item) => (item?.value as string) ?? "",+ onItemSelect: (value) => {+ onChangeComplete(value ?? defaultValue);+ },});const inputProps = getInputProps();+ // Used to decouple onChange effect from value ref change+ const valueRef = useRef<StyleValue>(value);- console.log({ value, inputProps });+ useEffect(() => {+ valueRef.current = value;+ }, [value]);useEffect(() => {- if (inputProps.value === value.value) return;- // @todo parseCssValue was done in setValue in useStyleData, now we need to move it to controls, otherwise we are going to do it twice with this one.- const nextValue = parseCssValue(- property,- inputProps.value,- "unit" in value ? value.unit : undefined- );- onChange?.(nextValue);- }, [inputProps.value, value]);+ const input = inputProps.value;++ if (input === valueRef.current.value) return;++ // We want to switch to unit mode if entire input is a number.+ if (/^\d+$/.test(input)) {+ onChange?.({+ type: "unit",+ // Use previously known unit or fallback to px.+ unit: valueRef.current.type === "unit" ? valueRef.current.unit : "px",+ value: Number(input),+ });+ return;+ }++ onChange?.({+ type: "keyword",+ value: input,+ });+ }, [inputProps.value, onChange]);++ const suffix =+ value.type === "keyword" ? (+ <IconButton {...getToggleButtonProps()}>+ <ChevronDownIcon />+ </IconButton>+ ) : value.type === "unit" ? (+ <UnitSelect value={value} onChange={onChange} units={units} />+ ) : null;return (<ComboboxPopper>@@ -94,12 +168,8 @@ export const CssValueInput = ({<TextField{...inputProps}name={property}- state={isInvalid ? "invalid" : undefined}- suffix={- <IconButton {...getToggleButtonProps()}>- <ChevronDownIcon />- </IconButton>- }+ state={value.type === "invalid" ? "invalid" : undefined}+ suffix={suffix}/></ComboboxPopperAnchor><ComboboxPopperContent align="start" sideOffset={5}>diff --git a/packages/design-system/src/components/combobox.stories.tsx b/packages/design-system/src/components/combobox.stories.tsxindex 622ddea45a..82d174a428 100644--- a/packages/design-system/src/components/combobox.stories.tsx+++ b/packages/design-system/src/components/combobox.stories.tsx@@ -1,4 +1,4 @@-import { ComponentStory } from "@storybook/react";+import type { ComponentStory } from "@storybook/react";import { MagnifyingGlassIcon } from "@webstudio-is/icons";import { useCombobox as useDownshiftCombobox } from "downshift";import React, { useCallback } from "react";diff --git a/packages/design-system/src/components/combobox.tsx b/packages/design-system/src/components/combobox.tsxindex bc76713be7..95f40cbc4e 100644--- a/packages/design-system/src/components/combobox.tsx+++ b/packages/design-system/src/components/combobox.tsx@@ -30,8 +30,18 @@ const Listbox = styled("ul", panelStyles, {// @todo need some non-hardcoded valuemaxHeight: 400,minWidth: 230,- '&[data-state="closed"], &[data-empty="true"]': {- display: "none",+ variants: {+ state: {+ open: {},+ closed: {+ display: "none",+ },+ },+ isEmpty: {+ true: {+ display: "none",+ },+ },},});@@ -74,34 +84,43 @@ export const ComboboxPopperContent = PopperContent;export const ComboboxPopperAnchor = PopperAnchor;+const defaultMatch = <Item,>(+ search: string,+ items: Array<Item>,+ itemToString: (item: Item | null) => string+) =>+ matchSorter(items, search, {+ keys: [(item) => itemToString(item)],+ });+const useFilter = <Item,>({items,itemToString,+ match = defaultMatch,}: {items: Array<Item>;itemToString: (item: Item | null) => string;+ match?: typeof defaultMatch;}) => {const [filteredItems, setFilteredItems] = useState<Array<Item>>(items);const cachedItems = useRef(items);- useEffect(() => {- cachedItems.current = items;- }, [items]);-const filter = useCallback((search?: string) => {- const foundItems: Array<Item> = matchSorter(items, search ?? "", {- keys: [(item) => itemToString(item)],- });+ const foundItems = match(search ?? "", items, itemToString);setFilteredItems(foundItems);},- [itemToString, items]+ [itemToString, items, match]);const resetFilter = useCallback(() => {setFilteredItems(cachedItems.current);}, []);+ useEffect(() => {+ cachedItems.current = items;+ }, [items]);+return {filteredItems,filter,@@ -119,6 +138,7 @@ type UseComboboxProps<Item> = {state: DownshiftState<Item>,changes: UseComboboxStateChangeOptions<Item>) => Partial<UseComboboxStateChangeOptions<Item>>;+ match?: typeof defaultMatch;};export const comboboxStateChangeTypes = useDownshiftCombobox.stateChangeTypes;@@ -130,10 +150,12 @@ export const useCombobox = <Item,>({onItemSelect,onItemHighlight,stateReducer = (state, { changes }) => changes,+ match,}: UseComboboxProps<Item>) => {const { filteredItems, filter, resetFilter } = useFilter<Item>({items,itemToString,+ match,});const downshiftProps = useDownshiftCombobox({@@ -177,12 +199,12 @@ export const useCombobox = <Item,>({);const enhancedGetMenuProps = useCallback(- (options) => {- return getMenuProps({- ...options,- "data-state": isOpen ? "open" : "closed",- ...{ "data-empty": filteredItems.length === 0 },- });+ (options?: Parameters<typeof getMenuProps>[0]) => {+ return {+ ...getMenuProps(options),+ state: isOpen ? "open" : "closed",+ isEmpty: filteredItems.length === 0,+ };},[getMenuProps, isOpen, filteredItems.length]);@@ -195,7 +217,7 @@ export const useCombobox = <Item,>({};};-type ComboboxProps<Item> = useComboboxProps<Item> & {+type ComboboxProps<Item> = UseComboboxProps<Item> & {name: string;label?: string;placeholder?: string;diff --git a/packages/design-system/src/components/select.tsx b/packages/design-system/src/components/select.tsxindex 56a1192ba1..41623396a9 100644--- a/packages/design-system/src/components/select.tsx+++ b/packages/design-system/src/components/select.tsx@@ -18,6 +18,9 @@ const StyledTrigger = styled(SelectPrimitive.SelectTrigger, {backgroundColor: "$loContrast",color: "$hiContrast",boxShadow: "inset 0 0 0 1px $colors$slate7",+ height: 28, // @todo waiting for the sizing scale+ px: "$2",+ fontSize: "$1","&:hover": {backgroundColor: "$slateA3",},@@ -27,10 +30,6 @@ const StyledTrigger = styled(SelectPrimitive.SelectTrigger, {},variants: {- size: {- 1: { padding: "0 $1 0 $2", fontSize: "$1", height: "$5" },- 2: { padding: "0 $2 0 $3", height: "$6", fontSize: "$3" },- },ghost: {true: {backgroundColor: "transparent",@@ -42,9 +41,14 @@ const StyledTrigger = styled(SelectPrimitive.SelectTrigger, {width: "100%",},},+ withSuffix: {+ true: {+ paddingRight: "$1",+ },+ },},defaultVariants: {- size: 1,+ withSuffix: true,},});@@ -96,7 +100,7 @@ const scrollButtonStyles = {alignItems: "center",justifyContent: "center",height: 25,- color: "$text",+ color: "$hiContrast",cursor: "default",};@@ -133,18 +137,25 @@ type SelectItemProps = SelectPrimitive.SelectItemProps & {};const SelectItem = React.forwardRef(SelectItemBase);+const defaultSuffix = (+ <StyledIcon>+ <ChevronDownIcon />+ </StyledIcon>+);+export type SelectOption = string;-export type SelectProps<T = SelectOption> = Omit<+export type SelectProps<Option = SelectOption> = Omit<React.ComponentProps<typeof StyledTrigger>,"onChange" | "value" | "defaultValue"> & {- options: T[];- defaultValue?: T;- value?: T;- onChange?: (option: T) => void;+ options: Option[];+ defaultValue?: Option;+ value?: Option;+ onChange?: (option: Option) => void;placeholder?: string;- getLabel?: (option: T) => string | undefined;+ getLabel?: (option: Option) => string | undefined;+ suffix?: JSX.Element | null;};const SelectBase = (@@ -156,6 +167,7 @@ const SelectBase = (onChange = noop,getLabel = (option) => option,name,+ suffix = defaultSuffix,...props}: SelectProps,forwardedRef: Ref<HTMLButtonElement>@@ -167,13 +179,11 @@ const SelectBase = (defaultValue={defaultValue}onValueChange={onChange}>- <StyledTrigger ref={forwardedRef} {...props}>+ <StyledTrigger ref={forwardedRef} withSuffix={Boolean(suffix)} {...props}><SelectPrimitive.Value>{value ? getLabel(value) : placeholder}</SelectPrimitive.Value>- <StyledIcon>- <ChevronDownIcon />- </StyledIcon>+ {suffix}</StyledTrigger><SelectPrimitive.Portal><StyledContent>diff --git a/packages/react-sdk/src/css/schema.ts b/packages/react-sdk/src/css/schema.tsindex 4cd2443d10..865e5c021f 100644--- a/packages/react-sdk/src/css/schema.ts+++ b/packages/react-sdk/src/css/schema.ts@@ -3,13 +3,13 @@ import { units } from "./units";export const UnitSchema = z.union([z.enum(units), z.literal("number")]);-const UnitValueSchema = z.object({+export const UnitValueSchema = z.object({type: z.literal("unit"),unit: UnitSchema,value: z.number(),});-const KeywordValueSchema = z.object({+export const KeywordValueSchema = z.object({type: z.literal("keyword"),// @todo use exact typevalue: z.string(),@@ -17,15 +17,21 @@ const KeywordValueSchema = z.object({// We want to be able to render the invalid value// and show it is invalid visually, without saving it to the db-const InvalidValueSchema = z.object({+export const InvalidValueSchema = z.object({type: z.literal("invalid"),value: z.string(),});+export const UnsetValueSchema = z.object({+ type: z.literal("unset"),+ value: z.literal(""),+});+export const StyleValueSchema = z.union([UnitValueSchema,KeywordValueSchema,InvalidValueSchema,+ UnsetValueSchema,]);export const StyleSchema = z.record(z.string(), StyleValueSchema);diff --git a/packages/react-sdk/src/css/types.ts b/packages/react-sdk/src/css/types.tsindex b777676c49..d7850f134d 100644--- a/packages/react-sdk/src/css/types.ts+++ b/packages/react-sdk/src/css/types.ts@@ -3,8 +3,12 @@ import { properties } from "./properties";import {BreakpointSchema,CssRuleSchema,+ InvalidValueSchema,+ KeywordValueSchema,StyleValueSchema,UnitSchema,+ UnitValueSchema,+ UnsetValueSchema,} from "./schema";type Properties = typeof properties;@@ -22,5 +26,9 @@ export type CssRule = z.infer<typeof CssRuleSchema>;export type Unit = z.infer<typeof UnitSchema>;export type StyleValue = z.infer<typeof StyleValueSchema>;+export type UnitValue = z.infer<typeof UnitValueSchema>;+export type KeywordValue = z.infer<typeof KeywordValueSchema>;+export type InvalidValue = z.infer<typeof InvalidValueSchema>;+export type UnsetValue = z.infer<typeof UnsetValueSchema>;export type Breakpoint = z.infer<typeof BreakpointSchema>;