Skip to content

feat: Backspace to reset the value in CSS Value Input #4878

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 15, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,15 @@ export const PropertyInfo = ({
description,
styles,
onReset,
resetType = "reset",
}: {
title: string;
code?: string;
link?: string;
description: ReactNode;
styles: ComputedStyleDecl[];
onReset: () => void;
resetType?: "reset" | "delete";
}) => {
const breakpoints = useStore($breakpoints);
const instances = useStore($instances);
Expand Down Expand Up @@ -203,9 +205,7 @@ export const PropertyInfo = ({
css={{ gridTemplateColumns: "1fr max-content 1fr" }}
onClick={onReset}
>
{styles[0].property.startsWith("--")
? "Delete variable"
: "Reset value"}
{resetType === "delete" ? "Delete property" : "Reset value"}
</Button>
)}
</Flex>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,31 +178,34 @@ export const AddStylesInput = forwardRef<
setItem({ property: "", label: "" });
};

const handleKeys = (event: KeyboardEvent) => {
// Dropdown might handle enter or escape.
if (event.defaultPrevented) {
return;
}
const handleEnter = (event: KeyboardEvent) => {
if (event.key === "Enter") {
clear();
onSubmit(item.property);
return;
}
// When user hits backspace and there is nothing in the input - we hide the input
const abortByBackspace =
event.key === "Backspace" && combobox.inputValue === "";
};

if (event.key === "Escape" || abortByBackspace) {
const handleEscape = (event: KeyboardEvent) => {
if (event.key === "Escape") {
clear();
onClose();
event.preventDefault();
}
};

const handleKeyDown = composeEventHandlers(inputProps.onKeyDown, handleKeys, {
// Pass prevented events to the combobox (e.g., the Escape key doesn't work otherwise, as it's blocked by Radix)
checkForDefaultPrevented: false,
});
const handleDelete = (event: KeyboardEvent) => {
// When user hits backspace and there is nothing in the input - we hide the input
if (event.key === "Backspace" && combobox.inputValue === "") {
clear();
onClose();
}
};

const handleKeyDown = composeEventHandlers([
inputProps.onKeyDown,
handleEnter,
handleEscape,
handleDelete,
]);

return (
<ComboboxRoot open={combobox.isOpen}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ const AdvancedPropertyLabel = ({
setIsOpen(false);
onReset?.();
}}
resetType="delete"
/>
}
>
Expand All @@ -178,13 +179,15 @@ const AdvancedPropertyValue = ({
autoFocus,
property,
onChangeComplete,
onReset,
inputRef: inputRefProp,
}: {
autoFocus?: boolean;
property: StyleProperty;
onChangeComplete: ComponentProps<
typeof CssValueInputContainer
>["onChangeComplete"];
onReset: ComponentProps<typeof CssValueInputContainer>["onReset"];
inputRef?: RefObject<HTMLInputElement>;
}) => {
const styleDecl = useComputedStyleDecl(property);
Expand Down Expand Up @@ -245,6 +248,7 @@ const AdvancedPropertyValue = ({
}}
deleteProperty={deleteProperty}
onChangeComplete={onChangeComplete}
onReset={onReset}
/>
);
};
Expand Down Expand Up @@ -340,6 +344,7 @@ const AdvancedProperty = memo(
autoFocus={autoFocus}
property={property}
onChangeComplete={onChangeComplete}
onReset={onReset}
inputRef={valueInputRef}
/>
</Box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ type CssValueInputContainerProps = {
| "onChangeComplete"
> & {
onChangeComplete?: ComponentProps<typeof CssValueInput>["onChangeComplete"];
onReset?: ComponentProps<typeof CssValueInput>["onReset"];
};

export const CssValueInputContainer = ({
property,
setValue,
deleteProperty,
onChangeComplete,
onReset,
...props
}: CssValueInputContainerProps) => {
const [intermediateValue, setIntermediateValue] = useState<
Expand Down Expand Up @@ -63,6 +65,7 @@ export const CssValueInputContainer = ({
}}
onReset={() => {
deleteProperty(property);
onReset?.();
}}
/>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,9 @@ type CssValueInputProps = Pick<
onChange: (value: CssValueInputValue | undefined) => void;
onChangeComplete: (event: ChangeCompleteEvent) => void;
onHighlight: (value: StyleValue | undefined) => void;
// Does not reset intermediate changes.
onAbort: () => void;
// Resets the value to default even if it has intermediate changes.
onReset: () => void;
icon?: ReactNode;
showSuffix?: boolean;
Expand Down Expand Up @@ -798,7 +800,7 @@ export const CssValueInput = ({
}
};

const handleMetaEnter = (event: KeyboardEvent<HTMLInputElement>) => {
const handleEnter = (event: KeyboardEvent<HTMLInputElement>) => {
if (
isUnitsOpen ||
(isOpen && !menuProps.empty && highlightedIndex !== -1)
Expand All @@ -813,6 +815,14 @@ export const CssValueInput = ({
}
};

const handleDelete = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Backspace" && inputProps.value === "") {
event.preventDefault();
closeMenu();
onReset();
}
};

const { abort, ...autoScrollProps } = useMemo(() => {
return getAutoScrollProps();
}, []);
Expand Down Expand Up @@ -860,11 +870,11 @@ export const CssValueInput = ({
}, [inputRef]);

const inputPropsHandleKeyDown = composeEventHandlers(
composeEventHandlers(handleUpDownNumeric, inputProps.onKeyDown, {
[handleUpDownNumeric, inputProps.onKeyDown, handleEnter, handleDelete],
{
// Pass prevented events to the combobox (e.g., the Escape key doesn't work otherwise, as it's blocked by Radix)
checkForDefaultPrevented: false,
}),
handleMetaEnter
}
);

const suffixRef = useRef<HTMLDivElement | null>(null);
Expand Down
46 changes: 46 additions & 0 deletions apps/builder/app/shared/event-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, test, expect, vi } from "vitest";
import { composeEventHandlers } from "./event-utils";

describe("composeEventHandlers", () => {
test("executes handlers in sequence", () => {
const handler1 = vi.fn();
const handler2 = vi.fn();
const event = {};

const composed = composeEventHandlers([handler1, handler2]);
composed(event);

expect(handler1).toHaveBeenCalledWith(event);
expect(handler2).toHaveBeenCalledWith(event);
});

test("stops execution if event.defaultPrevented is true", () => {
const handler1 = vi.fn((event) => {
event.defaultPrevented = true;
});
const handler2 = vi.fn();
const event = {};

const composed = composeEventHandlers([handler1, handler2]);
composed(event);

expect(handler1).toHaveBeenCalled();
expect(handler2).not.toHaveBeenCalled();
});

test("continues execution when checkForDefaultPrevented is false", () => {
const handler1 = vi.fn((event) => {
event.defaultPrevented = true;
});
const handler2 = vi.fn();
const event = {};

const composed = composeEventHandlers([handler1, handler2], {
checkForDefaultPrevented: false,
});
composed(event);

expect(handler1).toHaveBeenCalled();
expect(handler2).toHaveBeenCalled();
});
});
50 changes: 14 additions & 36 deletions apps/builder/app/shared/event-utils.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,20 @@
/*
https://github.com/radix-ui/primitives/blob/main/packages/core/primitive/src/primitive.tsx

MIT License

Copyright (c) 2022 WorkOS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

export const composeEventHandlers = <E>(
originalEventHandler?: (event: E) => void,
ourEventHandler?: (event: E) => void,
* Inspired by
* https://github.com/radix-ui/primitives/blob/main/packages/core/primitive/src/primitive.tsx
*/
export const composeEventHandlers = <CustomEvent>(
handlers: Array<(event: CustomEvent) => void>,
{ checkForDefaultPrevented = true } = {}
) => {
return function handleEvent(event: E) {
originalEventHandler?.(event);

if (
checkForDefaultPrevented === false ||
!(event as unknown as Event).defaultPrevented
) {
return ourEventHandler?.(event);
return function handleEvent(event: CustomEvent) {
for (const handler of handlers) {
handler?.(event);
if (
checkForDefaultPrevented &&
(event as unknown as Event).defaultPrevented
) {
break;
}
}
};
};
Loading