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.

wip value input with unit/keyword mode switch logic

Oleg Isonen374b173f4906
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.tsx
index fb5bb954b2..5b1002f417 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
@@ -35,7 +35,7 @@ export const TextControl = ({
<CssValueInput
property={styleConfig.property}
value={value}
- allowedValues={styleConfig.items.map((item) => ({
+ items={styleConfig.items.map((item) => ({
type: "keyword",
value: item.name,
}))}
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.tsx
index 1582a36476..55653f427f 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,14 +1,14 @@
import React from "react";
import { Flex, TextField } from "@webstudio-is/design-system";
import { StyleValue } from "@webstudio-is/react-sdk";
-import { CssValueInput } from "./css-property";
+import { CssValueInput } from "./css-value-input";
export default {
component: CssValueInput,
};
export const WithKeywords = () => {
- const [value, setValue] = React.useState<StyleValue | undefined>({
+ const [value, setValue] = React.useState<StyleValue>({
type: "keyword",
value: "auto",
});
@@ -17,16 +17,15 @@ export const WithKeywords = () => {
<CssValueInput
property="width"
value={value}
- allowedValues={[
+ items={[
{ type: "keyword", value: "auto" },
{ type: "keyword", value: "min-content" },
{ type: "keyword", value: "max-content" },
{ type: "keyword", value: "fit-content" },
]}
onChange={(value) => {
- // every time we change the input
- // eslint-disable-next-line no-console
- console.log(value);
+ console.log("onChange", value);
+ setValue(value);
}}
onChangeComplete={(newValue) => {
// on blur, select, enter etc.
@@ -46,7 +45,7 @@ export const WithIcons = () => {
<CssValueInput
property="alignItems"
value={value}
- allowedValues={[
+ items={[
{ type: "keyword", value: "normal" },
{ type: "keyword", value: "start" },
{ type: "keyword", value: "end" },
@@ -81,7 +80,7 @@ export const WithUnits = () => {
<CssValueInput
property="rowGap"
value={value}
- allowedValues={[
+ items={[
{ type: "keyword", value: "auto" },
{ type: "keyword", value: "min-content" },
{ type: "keyword", value: "max-content" },
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.tsx
index b2f6169ccf..8e1c890c76 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
@@ -1,16 +1,14 @@
import {
- Button,
- Combobox,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuPortal,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
- DropdownMenuTrigger,
- Flex,
- IconButton,
- numericScrubControl,
+ Box,
TextField,
+ useCombobox,
+ comboboxStateChangeTypes,
+ ComboboxPopper,
+ ComboboxPopperContent,
+ ComboboxPopperAnchor,
+ ComboboxListbox,
+ ComboboxListboxItem,
+ IconButton,
} from "@webstudio-is/design-system";
import { ChevronDownIcon } from "@webstudio-is/icons";
import {
@@ -20,9 +18,8 @@ import {
Unit,
units,
} from "@webstudio-is/react-sdk";
-import { useCombobox } from "downshift";
-import { KeyboardEvent, PointerEvent, useCallback, useRef } from "react";
-import { PropertyIcon } from "../../shared/property-name";
+import { useCallback, useEffect, useState } from "react";
+import { parseCssValue } from "../parse-css-value";
const sortedUnits = units
.slice(0)
@@ -34,213 +31,91 @@ const sortedUnits = units
type CssValueInputProps = {
property: StyleProperty;
- value?: StyleValue;
- allowedValues?: Array<KeywordValue>;
- onChange?: (value?: StyleValue) => void;
- onChangeComplete?: (value?: StyleValue) => void;
+ value: StyleValue;
+ items?: Array<KeywordValue>;
+ onChange: (value: StyleValue) => void;
+ onChangeComplete: (value: StyleValue) => void;
};
export const CssValueInput = ({
property,
value,
- allowedValues = [],
+ items: itemsProp = [],
onChange,
onChangeComplete,
}: CssValueInputProps) => {
- const inputRef = useRef<HTMLInputElement | null>(null);
-
- const handleArrowUpDown = (event: KeyboardEvent<HTMLInputElement>) => {
- // @todo: There is a bug when type === "keyword" and the user presses arrow up/dow then it's going to be displayed NaN as a value
- if (value?.type === "unit") {
- let numberValue = parseFloat(event.currentTarget.value);
- const direction = event.code === "ArrowUp" ? 1 : -1;
- let currentDelta = 1;
- if (event.shiftKey) currentDelta = 10;
- if (event.altKey) currentDelta = 0.1;
- numberValue = numberValue + currentDelta * direction;
- const roundedValue =
- numberValue % 1
- ? Number(
- numberValue.toPrecision(
- Math.abs(numberValue).toString().indexOf(".") + 2
- )
- )
- : numberValue;
- event.currentTarget.value = String(roundedValue);
- onChange?.({
- type: "unit",
- value: roundedValue,
- unit: value?.unit ?? "px",
- });
- }
- };
+ const isInvalid = false;
+ const onItemSelect = () => {};
- const unitStateReducer = useCallback((state, actionAndChanges) => {
- const { type, changes } = actionAndChanges;
- switch (type) {
- // on item selection.
- case useCombobox.stateChangeTypes.ItemClick:
- case useCombobox.stateChangeTypes.InputKeyDownEnter:
- case useCombobox.stateChangeTypes.InputBlur:
- case useCombobox.stateChangeTypes.ControlledPropUpdatedSelectedItem: {
- if (changes.selectedItem?.type !== "unit") {
- return {
- ...changes,
- // if we had an item selected.
- ...(changes.selectedItem && {
- // we will set the input value to be empty since we display it using prefix
- inputValue: "",
- }),
- };
- }
- return changes;
- }
- case useCombobox.stateChangeTypes.InputChange: {
- // When we erased the value, we want to reset the selectedItem
- if (changes.inputValue === "") {
- return {
- ...changes,
- selectedItem: null,
- };
- }
- // If we type a number, we want to set the selectedItem to of type: "unit"
- if (!isNaN(parseFloat(changes.inputValue))) {
- return {
- ...changes,
- selectedItem: {
- type: "unit",
- value: parseFloat(changes.inputValue),
- unit: "px",
- } as StyleValue,
- };
- }
- return changes;
+ const stateReducer = useCallback((state, action) => {
+ switch (action.type) {
+ case comboboxStateChangeTypes.InputChange: {
}
- default:
- return changes; // otherwise business as usual.
}
+
+ return action.changes;
}, []);
+ const {
+ items,
+ getInputProps,
+ getComboboxProps,
+ getToggleButtonProps,
+ getMenuProps,
+ getItemProps,
+ isOpen,
+ } = useCombobox({
+ items: itemsProp,
+ value,
+ itemToString: (item) => item?.value ?? "",
+ onItemSelect,
+ stateReducer,
+ });
+
+ const inputProps = getInputProps();
+
+ console.log({ value, inputProps });
+
+ 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]);
+
return (
- <Combobox
- name={property}
- value={value}
- items={allowedValues}
- stateReducer={value?.type === "unit" ? unitStateReducer : undefined}
- itemToString={(item) => (item ? String(item.value) : "")}
- onItemSelect={(item) => {
- onChangeComplete?.(item);
- }}
- onItemHighlight={(item) => {
- onChange?.(item);
- }}
- renderTextField={({ inputProps, toggleProps }) => {
- return (
+ <ComboboxPopper>
+ <Box {...getComboboxProps()}>
+ <ComboboxPopperAnchor>
<TextField
{...inputProps}
- inputRef={inputRef}
- onFocus={() => {
- inputRef.current?.select();
- }}
- onKeyDown={(event) => {
- if (
- value?.type === "unit" &&
- ["ArrowUp", "ArrowDown"].includes(event.code)
- ) {
- handleArrowUpDown(event);
- return;
- }
- // Skip Backspace behavior
- if (
- value?.type === "unit" &&
- ["Backspace"].includes(event.code)
- ) {
- return;
- }
- inputProps.onKeyDown?.(event); // Call original event handler
- }}
- prefix={
- <Flex css={{ alignItems: "center" }}>
- <PropertyIcon
- property={property}
- label={property}
- {...(value?.type === "unit" && {
- onPointerEnter: (event: PointerEvent<HTMLElement>) => {
- Object(event.currentTarget)[Symbol.for("scrub")] ??=
- numericScrubControl(event.currentTarget, {
- initialValue: value.value,
- onValueInput: (event) => {
- onChange?.({
- ...value,
- value: event.value,
- });
- },
- onValueChange: (event) => {
- onChangeComplete?.({
- ...value,
- value: event.value,
- });
- },
- });
- },
- })}
- />
- {value?.type !== "unit" && inputProps.prefix}
- </Flex>
- }
+ name={property}
+ state={isInvalid ? "invalid" : undefined}
suffix={
- value?.type === "invalid" ? null : value?.type === "keyword" ? (
- <IconButton {...toggleProps}>
- <ChevronDownIcon />
- </IconButton>
- ) : (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- {/* @ts-expect-error Type comes from the SDK :shrug: */}
- <Button variant="ghost" size="1" css={{ px: 0 }}>
- {value?.unit}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuPortal>
- <DropdownMenuContent
- sideOffset={14}
- collisionPadding={16}
- side="bottom"
- css={{
- minWidth: 124,
- maxHeight: 190,
- }}
- >
- <DropdownMenuRadioGroup
- value={String(value?.unit)}
- onValueChange={(unit) => {
- onChangeComplete?.(
- value
- ? {
- type: "unit",
- value: value.value,
- unit: unit as Unit,
- }
- : undefined
- );
- }}
- >
- {sortedUnits.map((unit) => {
- return (
- <DropdownMenuRadioItem key={unit} value={unit}>
- {unit}
- </DropdownMenuRadioItem>
- );
- })}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenuPortal>
- </DropdownMenu>
- )
+ <IconButton {...getToggleButtonProps()}>
+ <ChevronDownIcon />
+ </IconButton>
}
/>
- );
- }}
- />
+ </ComboboxPopperAnchor>
+ <ComboboxPopperContent align="start" sideOffset={5}>
+ <ComboboxListbox {...getMenuProps()}>
+ {isOpen &&
+ items.map((item, index) => (
+ <ComboboxListboxItem
+ {...getItemProps({ item, index })}
+ key={index}
+ >
+ {item.value}
+ </ComboboxListboxItem>
+ ))}
+ </ComboboxListbox>
+ </ComboboxPopperContent>
+ </Box>
+ </ComboboxPopper>
);
};
diff --git a/packages/design-system/src/components/combobox.tsx b/packages/design-system/src/components/combobox.tsx
index e2916240f4..bc76713be7 100644
--- a/packages/design-system/src/components/combobox.tsx
+++ b/packages/design-system/src/components/combobox.tsx
@@ -1,4 +1,4 @@
-import {
+import React, {
useState,
forwardRef,
useCallback,
@@ -30,6 +30,9 @@ const Listbox = styled("ul", panelStyles, {
// @todo need some non-hardcoded value
maxHeight: 400,
minWidth: 230,
+ '&[data-state="closed"], &[data-empty="true"]': {
+ display: "none",
+ },
});
const ListboxItem = styled("li", itemCss, {
@@ -106,7 +109,7 @@ const useFilter = <Item,>({
};
};
-type useComboboxProps<Item> = {
+type UseComboboxProps<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."
@@ -118,6 +121,8 @@ type useComboboxProps<Item> = {
) => Partial<UseComboboxStateChangeOptions<Item>>;
};
+export const comboboxStateChangeTypes = useDownshiftCombobox.stateChangeTypes;
+
export const useCombobox = <Item,>({
items,
value,
@@ -125,7 +130,7 @@ export const useCombobox = <Item,>({
onItemSelect,
onItemHighlight,
stateReducer = (state, { changes }) => changes,
-}: useComboboxProps<Item>) => {
+}: UseComboboxProps<Item>) => {
const { filteredItems, filter, resetFilter } = useFilter<Item>({
items,
itemToString,
@@ -149,7 +154,7 @@ export const useCombobox = <Item,>({
},
});
- const { isOpen, getItemProps, highlightedIndex, selectedItem } =
+ const { isOpen, getItemProps, highlightedIndex, selectedItem, getMenuProps } =
downshiftProps;
useEffect(() => {
@@ -171,10 +176,22 @@ export const useCombobox = <Item,>({
[getItemProps, highlightedIndex, itemToString, selectedItem]
);
+ const enhancedGetMenuProps = useCallback(
+ (options) => {
+ return getMenuProps({
+ ...options,
+ "data-state": isOpen ? "open" : "closed",
+ ...{ "data-empty": filteredItems.length === 0 },
+ });
+ },
+ [getMenuProps, isOpen, filteredItems.length]
+ );
+
return {
...downshiftProps,
items: filteredItems,
getItemProps: enhancedGetItemProps,
+ getMenuProps: enhancedGetMenuProps,
};
};