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.

CSSValueInput ESC support, do not save if nothing has changed (#673)

Ivan Starkovd69b2622d7db
diff --git a/apps/designer/app/canvas/shared/styles.ts b/apps/designer/app/canvas/shared/styles.ts
index d39833eb6f..b71264a095 100644
--- a/apps/designer/app/canvas/shared/styles.ts
+++ b/apps/designer/app/canvas/shared/styles.ts
@@ -271,6 +271,10 @@ const usePreviewStyle = () => {
setCssVar(id, update.property, update.value);
}
+
+ if (update.operation === "delete") {
+ setCssVar(id, update.property, undefined);
+ }
}
cssEngine.render();
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 b7cf902dbf..0d7af630ff 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
@@ -12,6 +12,7 @@ export const TextControl = ({
currentStyle,
inheritedStyle,
setProperty,
+ deleteProperty,
styleConfig,
icon,
}: ControlProps & { icon?: JSX.Element }) => {
@@ -45,17 +46,30 @@ export const TextControl = ({
}))}
onChange={(styleValue) => {
setIntermediateValue(styleValue);
+
+ if (styleValue === undefined) {
+ deleteProperty(styleConfig.property, { isEphemeral: true });
+ return;
+ }
+
if (styleValue.type !== "intermediate") {
setValue(styleValue, { isEphemeral: true });
}
}}
onHighlight={(styleValue) => {
- setValue(styleValue, { isEphemeral: true });
+ if (styleValue !== undefined) {
+ setValue(styleValue, { isEphemeral: true });
+ } else {
+ deleteProperty(styleConfig.property, { isEphemeral: true });
+ }
}}
- onChangeComplete={({ value }) => {
+ onChangeComplete={({ value, reason }) => {
setValue(value);
setIntermediateValue(undefined);
}}
+ onAbort={() => {
+ deleteProperty(styleConfig.property, { isEphemeral: true });
+ }}
/>
</Box>
</Tooltip>
diff --git a/apps/designer/app/designer/features/style-panel/sections/layout/layout.tsx b/apps/designer/app/designer/features/style-panel/sections/layout/layout.tsx
index 80155a82d1..204d54dc08 100644
--- a/apps/designer/app/designer/features/style-panel/sections/layout/layout.tsx
+++ b/apps/designer/app/designer/features/style-panel/sections/layout/layout.tsx
@@ -170,6 +170,7 @@ export const LayoutSection = ({
currentStyle={display.currentStyle}
inheritedStyle={display.inheritedStyle}
setProperty={display.setProperty}
+ deleteProperty={display.deleteProperty}
// show only important values first and hide others with scroll
styleConfig={{
...display.styleConfig,
diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/input-popover.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/input-popover.tsx
index eea9bd96c8..ec81b89e43 100644
--- a/apps/designer/app/designer/features/style-panel/sections/spacing/input-popover.tsx
+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/input-popover.tsx
@@ -40,6 +40,13 @@ const Input = ({
value={value}
intermediateValue={intermediateValue}
onChange={(styleValue) => {
+ setIntermediateValue(styleValue);
+
+ if (styleValue === undefined) {
+ onChange({ operation: "delete", property }, { isEphemeral: true });
+ return;
+ }
+
setIntermediateValue(styleValue);
if (styleValue.type !== "intermediate") {
onChange(
@@ -49,6 +56,11 @@ const Input = ({
}
}}
onHighlight={(styleValue) => {
+ if (styleValue === undefined) {
+ onChange({ operation: "delete", property }, { isEphemeral: true });
+ return;
+ }
+
onChange(
{ operation: "set", property, value: styleValue },
{ isEphemeral: true }
@@ -63,6 +75,9 @@ const Input = ({
onClosePopover();
}
}}
+ onAbort={() => {
+ onChange({ operation: "delete", property }, { isEphemeral: true });
+ }}
/>
);
};
diff --git a/apps/designer/app/designer/features/style-panel/sections/spacing/spacing.tsx b/apps/designer/app/designer/features/style-panel/sections/spacing/spacing.tsx
index 33ba219aba..e451163989 100644
--- a/apps/designer/app/designer/features/style-panel/sections/spacing/spacing.tsx
+++ b/apps/designer/app/designer/features/style-panel/sections/spacing/spacing.tsx
@@ -96,7 +96,7 @@ export const SpacingSection = ({
if (update.operation === "set") {
setProperty(update.property)(update.value, options);
} else {
- deleteProperty(update.property);
+ deleteProperty(update.property, options);
}
};
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 565a6e86ab..fda54d9b02 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
@@ -42,6 +42,9 @@ export const WithKeywords = () => {
setIntermediateValue(undefined);
action("onChangeComplete")(value);
}}
+ onAbort={() => {
+ action("onAbort")();
+ }}
/>
);
};
@@ -82,6 +85,9 @@ export const WithIcons = () => {
setIntermediateValue(undefined);
action("onChangeComplete")(value);
}}
+ onAbort={() => {
+ action("onAbort")();
+ }}
/>
);
};
@@ -121,6 +127,9 @@ export const WithUnits = () => {
setIntermediateValue(undefined);
action("onChangeComplete")(value);
}}
+ onAbort={() => {
+ action("onAbort")();
+ }}
/>
<TextField
readOnly
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 76df2d2694..46098a0fab 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
@@ -16,7 +16,6 @@ import { ChevronDownIcon } from "@webstudio-is/icons";
import type {
KeywordValue,
StyleProperty,
- UnsetValue,
StyleValue,
Unit,
} from "@webstudio-is/css-data";
@@ -33,8 +32,6 @@ import { unstable_batchedUpdates as unstableBatchedUpdates } from "react-dom";
import { parseIntermediateOrInvalidValue } from "./parse-intermediate-or-invalid-value";
import { toValue } from "@webstudio-is/css-engine";
-const unsetValue: UnsetValue = { type: "unset", value: "" };
-
// We increment by 10 when shift is pressed, by 0.1 when alt/option is pressed and by 1 by default.
const calcNumberChange = (
value: number,
@@ -138,21 +135,31 @@ const useScrub = ({
return [scrubRef, inputRef];
};
+export const isNumericString = (input: string) =>
+ String(input).trim().length !== 0 && isNaN(Number(input)) === false;
+
const useHandleKeyDown =
({
ignoreEnter,
+ ignoreUpDownNumeric,
value,
onChange,
onChangeComplete,
onKeyDown,
}: {
ignoreEnter: boolean;
+ ignoreUpDownNumeric: boolean;
value: CssValueInputValue;
onChange: (value: CssValueInputValue) => void;
onChangeComplete: (value: CssValueInputValue) => void;
onKeyDown: KeyboardEventHandler<HTMLInputElement>;
}) =>
(event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.defaultPrevented) {
+ // Underlying select like `unitSelect` can already prevent an event like up/down buttons
+ return;
+ }
+
// Do not prevent downshift behaviour on item select
if (ignoreEnter === false) {
if (event.key === "Enter") {
@@ -161,13 +168,19 @@ const useHandleKeyDown =
}
if (
- value.type === "unit" &&
- (event.key === "ArrowUp" || event.key === "ArrowDown") &&
- event.currentTarget.value
+ ignoreUpDownNumeric === false &&
+ (value.type === "unit" ||
+ (value.type === "intermediate" && isNumericString(value.value))) &&
+ value.unit !== undefined &&
+ (event.key === "ArrowUp" || event.key === "ArrowDown")
) {
+ const inputValue =
+ value.type === "unit" ? value.value : Number(value.value.trim());
+
onChange({
- ...value,
- value: calcNumberChange(value.value, event),
+ type: "unit",
+ value: calcNumberChange(inputValue, event),
+ unit: value.unit,
});
// Prevent Downshift from opening menu on arrow up/down
return;
@@ -199,12 +212,18 @@ type CssValueInputProps = {
* Selected item in the dropdown
*/
keywords?: Array<KeywordValue>;
- onChange: (value: CssValueInputValue) => void;
+ onChange: (value: CssValueInputValue | undefined) => void;
onChangeComplete: (event: {
value: StyleValue;
reason: ChangeReason;
}) => void;
- onHighlight: (value: StyleValue) => void;
+ onHighlight: (value: StyleValue | undefined) => void;
+ onAbort: () => void;
+};
+
+const initialValue: IntermediateStyleValue = {
+ type: "intermediate",
+ value: "",
};
/**
@@ -243,11 +262,16 @@ export const CssValueInput = ({
property,
keywords = [],
onHighlight,
+ onAbort,
...props
}: CssValueInputProps & { icon?: JSX.Element }) => {
- const value = props.intermediateValue ?? props.value ?? unsetValue;
+ const value = props.intermediateValue ?? props.value ?? initialValue;
- const onChange = (input: string) => {
+ const onChange = (input: string | undefined) => {
+ if (input === undefined) {
+ props.onChange(undefined);
+ return;
+ }
// We don't know what's inside the input,
// preserve current unit value if exists
props.onChange({
@@ -292,18 +316,19 @@ export const CssValueInput = ({
? String(item.value)
: toValue(item),
onInputChange: (inputValue) => {
- onChange(inputValue ?? unsetValue.value);
+ onChange(inputValue);
},
onItemSelect: (value) => {
- onChangeComplete(value ?? unsetValue, "keyword-select");
+ onChangeComplete(value, "keyword-select");
},
onItemHighlight: (value) => {
if (value == null) {
- onHighlight(unsetValue);
+ onHighlight(undefined);
return;
}
+
if (value.type !== "intermediate") {
- onHighlight(value ?? unsetValue);
+ onHighlight(value);
}
},
});
@@ -351,13 +376,22 @@ export const CssValueInput = ({
return;
}
+ // Probably no changes have been made at this point
+ // In that case we will call onAbort instead of onChangeComplete
+ if (props.intermediateValue === undefined) {
+ onAbort();
+ return;
+ }
onChangeComplete(value, "blur");
};
const handleKeyDown = useHandleKeyDown({
// In case of the menu is really open and the selection is inside it
// we do not prevent the default downshift Enter key behavior
- ignoreEnter: isOpen && !menuProps.empty && highlightedIndex !== -1,
+ ignoreEnter:
+ isUnitsOpen || (isOpen && !menuProps.empty && highlightedIndex !== -1),
+ // Do not change the number value on the arrow up/down if any menu is opened
+ ignoreUpDownNumeric: isUnitsOpen || isOpen,
onChangeComplete: (value) => onChangeComplete(value, "enter"),
value,
onChange: props.onChange,
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.tsx
index d4608970c3..ff16b68c6a 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
@@ -48,7 +48,7 @@ export const useUnitSelect = ({
value,
units = defaultUnits,
...props
-}: UseUnitSelectType) => {
+}: UseUnitSelectType): [boolean, JSX.Element | null] => {
const [isOpen, setIsOpen] = useState(false);
const renderUnits = useMemo(
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.ts
index e07e2f333c..74b39503bd 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
@@ -29,8 +29,15 @@ export type SetProperty = (
property: StyleProperty
) => (style: string | StyleValue, options?: StyleUpdateOptions) => void;
+export type DeleteProperty = (
+ property: StyleProperty,
+ options?: StyleUpdateOptions
+) => void;
+
export type CreateBatchUpdate = () => {
- setProperty: SetProperty;
+ setProperty: (
+ property: StyleProperty
+ ) => (style: string | StyleValue) => void;
deleteProperty: (property: StyleProperty) => void;
publish: () => void;
};
@@ -50,52 +57,49 @@ export const useStyleData = ({
[selectedInstanceData?.cssRules, selectedBreakpoint]
);
- const getCurrentStyle = useCallback<() => Style>(
+ const [breakpointStyle, setBreakpointStyle] = useState(
+ () => cssRule?.style as Style
+ );
+
+ const currentStyle = useMemo<Style>(
() => ({
...selectedInstanceData?.browserStyle,
- ...cssRule?.style,
+ ...breakpointStyle,
}),
- [selectedInstanceData, cssRule]
+ [selectedInstanceData?.browserStyle, breakpointStyle]
);
- const [currentStyle, setCurrentStyle] = useState(() => getCurrentStyle());
-
useEffect(() => {
- const currentStyle = getCurrentStyle();
- setCurrentStyle(currentStyle);
- }, [getCurrentStyle]);
+ setBreakpointStyle({ ...cssRule?.style });
+ }, [cssRule?.style]);
const inheritedStyle = useMemo(() => {
- if (
- currentStyle === undefined ||
- selectedInstanceData === undefined ||
- rootInstance === undefined
- ) {
+ if (selectedInstanceData === undefined || rootInstance === undefined) {
return;
}
return getInheritedStyle(rootInstance, selectedInstanceData.id);
- }, [currentStyle, selectedInstanceData, rootInstance]);
-
- const publishUpdates = (
- type: "update" | "preview",
- updates: StyleUpdates["updates"]
- ) => {
- if (
- updates.length === 0 ||
- selectedInstanceData === undefined ||
- selectedBreakpoint === undefined
- ) {
- return;
- }
- publish({
- type: type === "update" ? "updateStyle" : "previewStyle",
- payload: {
- id: selectedInstanceData.id,
- updates,
- breakpoint: selectedBreakpoint,
- },
- });
- };
+ }, [selectedInstanceData, rootInstance]);
+
+ const publishUpdates = useCallback(
+ (type: "update" | "preview", updates: StyleUpdates["updates"]) => {
+ if (
+ updates.length === 0 ||
+ selectedInstanceData === undefined ||
+ selectedBreakpoint === undefined
+ ) {
+ return;
+ }
+ publish({
+ type: type === "update" ? "updateStyle" : "previewStyle",
+ payload: {
+ id: selectedInstanceData.id,
+ updates,
+ breakpoint: selectedBreakpoint,
+ },
+ });
+ },
+ [publish, selectedBreakpoint, selectedInstanceData]
+ );
// @deprecated should not be called
const toStyleValue = (property: StyleProperty, value: string) => {
@@ -106,58 +110,61 @@ export const useStyleData = ({
return parseCssValue(property, value);
};
- const setProperty: SetProperty = (property) => {
- return (inputOrStyle, options = { isEphemeral: false }) => {
- if (currentStyle === undefined) {
- return;
- }
+ const setProperty = useCallback<SetProperty>(
+ (property) => {
+ return (inputOrStyle, options = { isEphemeral: false }) => {
+ warnOnce(
+ typeof inputOrStyle === "string",
+ "setProperty should be called with a style object, string is deprecated"
+ );
- warnOnce(
- typeof inputOrStyle === "string",
- "setProperty should be called with a style object, string is deprecated"
- );
+ const nextValue =
+ typeof inputOrStyle === "string"
+ ? toStyleValue(property, inputOrStyle)
+ : inputOrStyle;
- const nextValue =
- typeof inputOrStyle === "string"
- ? toStyleValue(property, inputOrStyle)
- : inputOrStyle;
+ if (nextValue.type !== "invalid") {
+ const updates = [
+ { operation: "set" as const, property, value: nextValue },
+ ];
+ const type = options.isEphemeral ? "preview" : "update";
- if (nextValue.type !== "invalid") {
- const updates = [
- { operation: "set" as const, property, value: nextValue },
- ];
- const type = options.isEphemeral ? "preview" : "update";
+ publishUpdates(type, updates);
+ }
- publishUpdates(type, updates);
- }
+ if (options.isEphemeral === false) {
+ setBreakpointStyle((prevStyle) => ({
+ ...prevStyle,
+ [property]: nextValue,
+ }));
+ }
+ };
+ },
+ [publishUpdates]
+ );
+
+ const deleteProperty = useCallback(
+ (property: StyleProperty, options = { isEphemeral: false }) => {
+ const updates = [{ operation: "delete" as const, property }];
+ const type = options.isEphemeral ? "preview" : "update";
+ publishUpdates(type, updates);
if (options.isEphemeral === false) {
- setCurrentStyle({ ...currentStyle, [property]: nextValue });
+ setBreakpointStyle((prevStyle) => {
+ const nextStyle = { ...prevStyle };
+ delete nextStyle[property];
+ return nextStyle;
+ });
}
- };
- };
-
- const deleteProperty = (property: StyleProperty) => {
- if (currentStyle === undefined) {
- return;
- }
-
- const updates = [{ operation: "delete" as const, property }];
- publishUpdates("update", updates);
- const nextStyle = { ...currentStyle };
- delete nextStyle[property];
- setCurrentStyle(nextStyle);
- };
+ },
+ [publishUpdates]
+ );
- const createBatchUpdate = () => {
+ const createBatchUpdate = useCallback(() => {
let updates: StyleUpdates["updates"] = [];
const setProperty = (property: StyleProperty) => {
const setValue = (inputOrStyle: string | StyleValue) => {
- if (currentStyle === undefined) {
- return;
- }
-
warnOnce(
typeof inputOrStyle === "string",
"setProperty should be called with a style object, string is deprecated"
@@ -178,10 +185,6 @@ export const useStyleData = ({
};
const deleteProperty = (property: StyleProperty) => {
- if (currentStyle === undefined) {
- return;
- }
-
updates.push({ operation: "delete", property });
};
@@ -190,20 +193,22 @@ export const useStyleData = ({
return;
}
publishUpdates("update", updates);
- const nextStyle = updates.reduce(
- (currentStyle, update) => {
- if (update.operation === "delete") {
- delete currentStyle[update.property];
- }
- if (update.operation === "set") {
- currentStyle[update.property] = update.value;
- }
- return currentStyle;
- },
- { ...currentStyle }
- );
- updates = [];
- setCurrentStyle(nextStyle);
+ setBreakpointStyle((prevStyle) => {
+ const nextStyle = updates.reduce(
+ (reduceStyle, update) => {
+ if (update.operation === "delete") {
+ delete reduceStyle[update.property];
+ }
+ if (update.operation === "set") {
+ reduceStyle[update.property] = update.value;
+ }
+ return reduceStyle;
+ },
+ { ...prevStyle }
+ );
+ updates = [];
+ return nextStyle;
+ });
};
return {
@@ -211,7 +216,7 @@ export const useStyleData = ({
deleteProperty,
publish,
};
- };
+ }, [publishUpdates]);
return {
currentStyle,
diff --git a/apps/designer/app/designer/features/style-panel/style-panel.tsx b/apps/designer/app/designer/features/style-panel/style-panel.tsx
index 7a73c6c38f..885444d839 100644
--- a/apps/designer/app/designer/features/style-panel/style-panel.tsx
+++ b/apps/designer/app/designer/features/style-panel/style-panel.tsx
@@ -29,6 +29,7 @@ export const StylePanel = ({
selectedInstanceData,
publish,
});
+
const [breakpoint] = useSelectedBreakpoint();
const [canvasWidth] = useCanvasWidth();
const [search, setSearch] = useState("");
diff --git a/apps/designer/app/designer/features/style-panel/style-sections.tsx b/apps/designer/app/designer/features/style-panel/style-sections.tsx
index fb2dd7fd28..a9625c4e3c 100644
--- a/apps/designer/app/designer/features/style-panel/style-sections.tsx
+++ b/apps/designer/app/designer/features/style-panel/style-sections.tsx
@@ -2,8 +2,12 @@ import { Grid } from "@webstudio-is/design-system";
import { toValue } from "@webstudio-is/css-engine";
import type { StyleConfig } from "./shared/configs";
import type { Category } from "@webstudio-is/react-sdk";
-import type { Style, StyleProperty } from "@webstudio-is/css-data";
-import type { SetProperty, CreateBatchUpdate } from "./shared/use-style-data";
+import type { Style } from "@webstudio-is/css-data";
+import type {
+ SetProperty,
+ DeleteProperty,
+ CreateBatchUpdate,
+} from "./shared/use-style-data";
import type { InheritedStyle } from "./shared/get-inherited-style";
import * as controls from "./controls";
import {
@@ -23,6 +27,7 @@ import { PropertyName } from "./shared/property-name";
export type ControlProps = {
setProperty: SetProperty;
+ deleteProperty: DeleteProperty;
currentStyle: Style;
inheritedStyle: InheritedStyle;
styleConfig: StyleConfig;
@@ -31,7 +36,7 @@ export type ControlProps = {
export type RenderCategoryProps = {
setProperty: SetProperty;
- deleteProperty: (property: StyleProperty) => void;
+ deleteProperty: DeleteProperty;
createBatchUpdate: CreateBatchUpdate;
currentStyle: Style;
sectionStyle: {
@@ -45,7 +50,7 @@ export type RenderCategoryProps = {
export type RenderPropertyProps = {
setProperty: SetProperty;
- deleteProperty: (property: StyleProperty) => void;
+ deleteProperty: DeleteProperty;
currentStyle: Style;
inheritedStyle: InheritedStyle;
styleConfig: StyleConfig;
@@ -77,6 +82,7 @@ export const renderProperty = ({
currentStyle={currentStyle}
inheritedStyle={inheritedStyle}
setProperty={setProperty}
+ deleteProperty={deleteProperty}
styleConfig={styleConfig}
category={category}
/>
diff --git a/packages/design-system/src/components/combobox.tsx b/packages/design-system/src/components/combobox.tsx
index 12e7c35bc7..d180a4a661 100644
--- a/packages/design-system/src/components/combobox.tsx
+++ b/packages/design-system/src/components/combobox.tsx
@@ -136,7 +136,7 @@ type UseComboboxProps<Item> = UseDownshiftComboboxProps<Item> & {
value: Item | null; // This is to prevent: "downshift: A component has changed the uncontrolled prop "selectedItem" to be controlled."
selectedItem: Item | undefined;
onInputChange?: (value: string | undefined) => void;
- onItemSelect?: (value: Item | null) => void;
+ onItemSelect?: (value: Item) => void;
onItemHighlight?: (value: Item | null) => void;
stateReducer?: (
state: DownshiftState<Item>,
@@ -159,17 +159,39 @@ export const useCombobox = <Item,>({
match,
...rest
}: UseComboboxProps<Item>) => {
+ const [isOpen, setIsOpen] = useState(false);
+
const { filteredItems, filter, resetFilter } = useFilter<Item>({
items,
itemToString,
match,
});
+ if (isOpen && filteredItems.length === 0) {
+ setIsOpen(false);
+ }
+
const downshiftProps = useDownshiftCombobox({
...rest,
items: filteredItems,
defaultHighlightedIndex: -1,
selectedItem: selectedItem ?? null, // Prevent downshift warning about switching controlled mode
+ isOpen,
+
+ onIsOpenChange({ isOpen, inputValue }) {
+ const foundItems =
+ match !== undefined
+ ? match(inputValue ?? "", items, itemToString)
+ : defaultMatch(inputValue ?? "", items, itemToString);
+
+ // Don't set isOpen to true if there are no items to show
+ // because otherwise first ESC press will try to close it and only next ESC
+ // will reset the value. When list is empty, first ESC should reset the value.
+ const nextIsOpen = isOpen === true && foundItems.length !== 0;
+
+ setIsOpen(nextIsOpen);
+ },
+
stateReducer,
itemToString,
inputValue: value ? itemToString(value) : undefined,
@@ -179,8 +201,17 @@ export const useCombobox = <Item,>({
onInputChange?.(inputValue);
}
},
- onSelectedItemChange({ selectedItem }) {
- onItemSelect?.(selectedItem ?? null);
+ onSelectedItemChange({ selectedItem, type }) {
+ // Don't call onItemSelect when ESC is pressed
+ if (type === comboboxStateChangeTypes.InputKeyDownEscape) {
+ // Reset intermediate value when ESC is pressed
+ onInputChange?.(undefined);
+ return;
+ }
+
+ if (selectedItem != null) {
+ onItemSelect?.(selectedItem);
+ }
},
onHighlightedIndexChange({ highlightedIndex }) {
if (highlightedIndex !== undefined) {
@@ -189,8 +220,7 @@ export const useCombobox = <Item,>({
},
});
- const { isOpen, getItemProps, highlightedIndex, getMenuProps } =
- downshiftProps;
+ const { getItemProps, highlightedIndex, getMenuProps } = downshiftProps;
useEffect(() => {
if (isOpen === false) {
diff --git a/packages/design-system/src/components/text-field.tsx b/packages/design-system/src/components/text-field.tsx
index 49afde21ba..0350886335 100644
--- a/packages/design-system/src/components/text-field.tsx
+++ b/packages/design-system/src/components/text-field.tsx
@@ -270,6 +270,7 @@ export const TextField = React.forwardRef<HTMLDivElement, TextFieldProps>(
onBlur,
onClick,
type,
+ onKeyDown,
// prevent spreading it into the dom
suffix: suffixProp,
...textFieldProps
@@ -314,6 +315,7 @@ export const TextField = React.forwardRef<HTMLDivElement, TextFieldProps>(
withPrefix={Boolean(prefix)}
withSuffix={Boolean(suffix)}
onClickCapture={focusInnerInput}
+ onKeyDown={onKeyDown}
// Setting tabIndex to -1 to allow this element to be focused via JavaScript.
// This is used when we need to hide the caret but want to:
// 1. keep the visual focused state of the component