Skip to content
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

Bugfix/prevent submit on enter in combobox #2861

Merged
merged 18 commits into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
be82931
Prevent "Enter" key in Combobox to...
it-vegard Apr 3, 2024
a28f0c9
Added test for Enter not submitting form
it-vegard Apr 17, 2024
c6de1dd
Added changeset
it-vegard Apr 17, 2024
d6c11ba
Add test for un-selecting a selected option using "enter" on a Chip n…
it-vegard Apr 17, 2024
9db454d
Do not prevent enter from submitting form if it should not perform an…
it-vegard Apr 17, 2024
98fbd97
Do not submit when the input field has a value
it-vegard Apr 17, 2024
dfeade2
Replace lots of sleep-calls with awaiting userEvents
it-vegard Apr 17, 2024
b0ab7b6
Create util function for looking up an option
it-vegard Apr 17, 2024
2c837e0
Fix bug where we couldn't un-select a custom option using "enter"
it-vegard Apr 17, 2024
1cee032
Merge branch 'main' into bugfix/prevent-submit-on-enter-in-combobox
it-vegard Apr 17, 2024
56e1240
Update test to account for the dropdown list closing when focus moves…
it-vegard Apr 17, 2024
570a264
Add possibility to slow down tests for debugging
it-vegard Apr 17, 2024
d8df132
Fix issue with onFocus -> onToggleSelected(false), where clicking the…
it-vegard Apr 17, 2024
7d5ec60
Fix test
it-vegard Apr 17, 2024
9401492
Closing the FilteredOptionsList when focusing a Chip caused too many …
it-vegard Apr 18, 2024
1b1477e
When no longer closing FilteredOptions on focusing a chip, we don't n…
it-vegard Apr 18, 2024
447bab0
Update .changeset/rotten-windows-cover.md
it-vegard Apr 18, 2024
9b1c8b7
Merge branch 'main' into bugfix/prevent-submit-on-enter-in-combobox
it-vegard Apr 18, 2024
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
5 changes: 5 additions & 0 deletions .changeset/rotten-windows-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@navikt/ds-react": patch
---

Preventing "enter" while Combobox is focused from submitting form
it-vegard marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,17 @@ export const FilteredOptionsProvider = ({
[filteredOptionsUtils.getAddNewOptionId(id)]: allowNewValues
? toComboboxOption(value)
: undefined,
...customOptions.reduce(
(acc, customOption) => ({
...acc,
[filteredOptionsUtils.getOptionId(id, customOption.label)]:
customOption,
}),
{},
),
},
),
[allowNewValues, id, options, value],
[allowNewValues, customOptions, id, options, value],
);

useClientLayoutEffect(() => {
Expand Down
4 changes: 4 additions & 0 deletions @navikt/core/react/src/form/combobox/Input/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
removeSelectedOption(lastSelectedOption);
}
}
} else if (e.key === "Enter" || e.key === "Accept") {
if (activeDecendantId || value) {
e.preventDefault();
}
} else if (e.key === "ArrowDown") {
// Check that cursor position is at the end of the input field,
// so we don't interfere with text editing
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from "react";
import { Chips } from "../../../chips";
import { useFilteredOptionsContext } from "../FilteredOptions/filteredOptionsContext";
import { useInputContext } from "../Input/inputContext";
import { ComboboxOption } from "../types";
import { useSelectedOptionsContext } from "./selectedOptionsContext";
Expand All @@ -13,13 +14,20 @@ interface SelectedOptionsProps {
const Option = ({ option }: { option: ComboboxOption }) => {
const { isMultiSelect, removeSelectedOption } = useSelectedOptionsContext();
const { focusInput } = useInputContext();
const { isListOpen, toggleIsListOpen } = useFilteredOptionsContext();

const onClick = (e) => {
e.stopPropagation();
removeSelectedOption(option);
focusInput();
};

const onFocus = () => {
it-vegard marked this conversation as resolved.
Show resolved Hide resolved
if (isListOpen) {
toggleIsListOpen(false);
}
};

if (!isMultiSelect) {
return (
<div className="navds-combobox__selected-options--no-bg">
Expand All @@ -28,7 +36,11 @@ const Option = ({ option }: { option: ComboboxOption }) => {
);
}

return <Chips.Removable onClick={onClick}>{option.label}</Chips.Removable>;
return (
<Chips.Removable onClick={onClick} onFocus={onFocus}>
{option.label}
</Chips.Removable>
);
};

const SelectedOptions: React.FC<SelectedOptionsProps> = ({
Expand Down
70 changes: 70 additions & 0 deletions @navikt/core/react/src/form/combobox/combobox.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,8 @@ export const RemoveSelectedMultiSelectTest: StoryObject = {
await sleep(250);
userEvent.click(appleSlett);
await sleep(250);
userEvent.click(canvas.getByRole("button", { name: "Alternativer" }));
await sleep(250);
const appleOption = canvas.getByRole("option", {
name: "apple",
selected: false,
Expand Down Expand Up @@ -624,3 +626,71 @@ export const TestHoverAndFocusSwitching: StoryObject = {
);
},
};

export const TestEnterNotSubmittingForm: StoryObj<{
onSubmit: ReturnType<typeof fn>;
}> = {
args: {
onSubmit: fn(),
},
render: ({ onSubmit }) => {
return (
<form action="https://www.aksel.nav.no" method="get" onSubmit={onSubmit}>
<UNSAFE_Combobox
options={options}
label="Hva er dine favorittfrukter?"
isMultiSelect
allowNewValues
/>
</form>
);
},
play: async ({ canvasElement, args }) => {
args.onSubmit.mockClear();
const canvas = within(canvasElement);
const waitTime = 0; // Change for debugging

await sleep(waitTime);

const getInput = () =>
canvas.getByRole("combobox", {
name: "Hva er dine favorittfrukter?",
});

const getOption = (name: string, selected: boolean) =>
canvas.getByRole("option", { name, selected });
await userEvent.click(getInput(), { delay: waitTime });

await userEvent.keyboard("{ArrowDown}", { delay: waitTime });
expect(getInput().getAttribute("aria-activedescendant")).toBe(
getOption("banana", false).getAttribute("id"),
);

await userEvent.keyboard("{Enter}", { delay: waitTime });
expect(args.onSubmit).not.toHaveBeenCalled();
expect(getOption("banana", true)).toBeVisible();

await userEvent.keyboard("{Shift>}{Tab}", { delay: waitTime });

await userEvent.keyboard("{Enter}", { delay: waitTime });
expect(args.onSubmit).not.toHaveBeenCalled();

await userEvent.keyboard("test"); // Type option that does not exist
await userEvent.keyboard("{Enter}", { delay: waitTime });
expect(args.onSubmit).not.toHaveBeenCalled();

await userEvent.keyboard("{ArrowDown}", { delay: waitTime }); // Select "test" custom option
expect(
canvas.getByRole("option", { name: "test", selected: true }),
).toBeVisible();
await userEvent.keyboard("{Enter}", { delay: waitTime }); // De-select "test"
expect(
canvas.queryByRole("option", { name: "test", selected: false }),
).toBeNull();
expect(args.onSubmit).not.toHaveBeenCalled();

await userEvent.keyboard("{Escape}", { delay: waitTime }); // Clear input field
await userEvent.keyboard("{Enter}", { delay: waitTime }); // Enter on empty Input with closed list
expect(args.onSubmit).toHaveBeenCalledOnce();
},
};
Loading