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

feat(autocomplete): add autoHighlight prop #3829

Open
wants to merge 4 commits into
base: canary
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions .changeset/angry-pillows-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@nextui-org/autocomplete": minor
"@nextui-org/listbox": minor
---

add prop autoHighlight to enable/disable the automatic focus on autocomplete items (#2186)
53 changes: 53 additions & 0 deletions apps/docs/content/components/autocomplete/auto-highlight.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const data = `export const animals = [
{label: "Cat", value: "cat", description: "The second most popular pet in the world"},
{label: "Dog", value: "dog", description: "The most popular pet in the world"},
{label: "Elephant", value: "elephant", description: "The largest land animal"},
{label: "Lion", value: "lion", description: "The king of the jungle"},
{label: "Tiger", value: "tiger", description: "The largest cat species"},
{label: "Giraffe", value: "giraffe", description: "The tallest land animal"},
{
label: "Dolphin",
value: "dolphin",
description: "A widely distributed and diverse group of aquatic mammals",
},
{label: "Penguin", value: "penguin", description: "A group of aquatic flightless birds"},
{label: "Zebra", value: "zebra", description: "A several species of African equids"},
{
label: "Shark",
value: "shark",
description: "A group of elasmobranch fish characterized by a cartilaginous skeleton",
},
{
label: "Whale",
value: "whale",
description: "Diverse group of fully aquatic placental marine mammals",
},
{label: "Otter", value: "otter", description: "A carnivorous mammal in the subfamily Lutrinae"},
{label: "Crocodile", value: "crocodile", description: "A large semiaquatic reptile"},
];`;
wingkwong marked this conversation as resolved.
Show resolved Hide resolved

const App = `import {Autocomplete, AutocompleteItem} from "@nextui-org/react";
import {animals} from "./data";

export default function App() {
return (
<Autocomplete
autoHighlight
label="Favorite Animal"
placeholder="Search an animal"
className="max-w-xs"
defaultItems={animals}
>
{(item) => <AutocompleteItem key={item.value}>{item.label}</AutocompleteItem>}
</Autocomplete>
);
}`;

const react = {
"/App.jsx": App,
"/data.js": data,
};

export default {
...react,
};
2 changes: 2 additions & 0 deletions apps/docs/content/components/autocomplete/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import customSectionsStyle from "./custom-sections-style";
import customStyles from "./custom-styles";
import customEmptyContentMessage from "./custom-empty-content-message";
import readOnly from "./read-only";
import autoHighlight from "./auto-highlight";

export const autocompleteContent = {
usage,
Expand Down Expand Up @@ -56,4 +57,5 @@ export const autocompleteContent = {
customStyles,
customEmptyContentMessage,
readOnly,
autoHighlight,
};
8 changes: 7 additions & 1 deletion apps/docs/content/docs/components/autocomplete.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ the end of the label and the autocomplete will be required.

### Read Only

If you pass the `isReadOnly` property to the Autocomplete, the Listbox will open to display
If you pass the `isReadOnly` property to the Autocomplete, the Listbox will open to display
all available options, but users won't be able to select any of the listed options.

<CodeDemo title="Read Only" highlightedLines="8" files={autocompleteContent.readOnly} />
Expand Down Expand Up @@ -322,6 +322,12 @@ You can use the `AutocompleteSection` component to group autocomplete items.

<CodeDemo title="With Sections" files={autocompleteContent.sections} />

### Auto Highlight

If you pass the `autoHighlight` property to the Autocomplete, the Listbox will show the first list item automatically highlighted.

<CodeDemo title="Auto Highlight" files={autocompleteContent.autoHighlight} />
wingkwong marked this conversation as resolved.
Show resolved Hide resolved

wingkwong marked this conversation as resolved.
Show resolved Hide resolved
### Custom Sections Style

You can customize the sections style by using the `classNames` property of the `AutocompleteSection` component.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -861,3 +861,75 @@ describe("Autocomplete with React Hook Form", () => {
expect(onSubmit).toHaveBeenCalledTimes(1);
});
});

it("should auto-highlight the first non-disabled item when autoHighlight is true", async () => {
const {getByRole, getAllByRole} = render(
<Autocomplete
autoHighlight
aria-label="Favorite Animal"
items={itemsData}
label="Favorite Animal"
>
{(item) => <AutocompleteItem key={item.value}>{item.label}</AutocompleteItem>}
</Autocomplete>,
);

const input = getByRole("combobox");

await act(async () => {
await userEvent.click(input);
});

const options = getAllByRole("option");

expect(options[0]).toHaveAttribute("data-hover", "true");
});

it("should skip disabled items when auto-highlighting", async () => {
const {getByRole, getAllByRole} = render(
<Autocomplete
autoHighlight
aria-label="Favorite Animal"
disabledKeys={["cat", "dog"]}
items={itemsData}
label="Favorite Animal"
>
{(item) => <AutocompleteItem key={item.value}>{item.label}</AutocompleteItem>}
</Autocomplete>,
);

const input = getByRole("combobox");

await act(async () => {
await userEvent.click(input);
});

const options = getAllByRole("option");

expect(options[2]).toHaveAttribute("data-hover", "true");
});

it("should not auto-highlight when autoHighlight is false", async () => {
const {getByRole, getAllByRole} = render(
<Autocomplete
aria-label="Favorite Animal"
autoHighlight={false}
items={itemsData}
label="Favorite Animal"
>
{(item) => <AutocompleteItem key={item.value}>{item.label}</AutocompleteItem>}
</Autocomplete>,
);

const input = getByRole("combobox");

await act(async () => {
await userEvent.click(input);
});

const options = getAllByRole("option");

options.forEach((option) => {
expect(option).not.toHaveAttribute("data-hover", "true");
});
});
18 changes: 14 additions & 4 deletions packages/components/autocomplete/src/use-autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ interface Props<T> extends Omit<HTMLNextUIProps<"input">, keyof ComboBoxProps<T>
* Callback fired when the select menu is closed.
*/
onClose?: () => void;
/**
* Whether to automatically highlight the first item in the list as the user types.
* @default false
*/
autoHighlight?: boolean;
}

export type UseAutocompleteProps<T> = Props<T> &
Expand Down Expand Up @@ -165,6 +170,7 @@ export function useAutocomplete<T extends object>(originalProps: UseAutocomplete
onOpenChange,
onClose,
isReadOnly = false,
autoHighlight = false,
...otherProps
} = props;

Expand Down Expand Up @@ -319,12 +325,14 @@ export function useAutocomplete<T extends object>(originalProps: UseAutocomplete

// focus first non-disabled item
useEffect(() => {
let key = state.collection.getFirstKey();
if (autoHighlight) {
let key = state.collection.getFirstKey();

while (key && state.disabledKeys.has(key)) {
key = state.collection.getKeyAfter(key);
while (key && state.disabledKeys.has(key)) {
key = state.collection.getKeyAfter(key);
}
state.selectionManager.setFocusedKey(key);
}
state.selectionManager.setFocusedKey(key);
}, [state.collection, state.disabledKeys]);

useEffect(() => {
Expand Down Expand Up @@ -432,6 +440,7 @@ export function useAutocomplete<T extends object>(originalProps: UseAutocomplete
...mergeProps(slotsProps.listboxProps, listBoxProps, {
shouldHighlightOnFocus: true,
}),
autoHighlight,
} as ListboxProps);

const getPopoverProps = (props: DOMAttributes = {}) => {
Expand Down Expand Up @@ -515,6 +524,7 @@ export function useAutocomplete<T extends object>(originalProps: UseAutocomplete
disableAnimation,
allowsCustomValue,
selectorIcon,
autoHighlight,
getBaseProps,
getInputProps,
getListBoxProps,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ export default {
type: "boolean",
},
},
autoHighlight: {
control: {
type: "boolean",
},
},
validationBehavior: {
control: {
type: "select",
Expand Down Expand Up @@ -803,6 +808,21 @@ const WithReactHookFormTemplate = (args: AutocompleteProps) => {
);
};

const AutoHighlightTemplate = ({color, variant, ...args}: AutocompleteProps<Animal>) => (
<Autocomplete
autoHighlight
className="max-w-xs"
color={color}
defaultItems={animalsData}
label="Favorite Animal"
placeholder="Select an animal"
variant={variant}
{...args}
>
{(item) => <AutocompleteItem key={item.value}>{item.label}</AutocompleteItem>}
</Autocomplete>
);

export const Default = {
render: Template,
args: {
Expand Down Expand Up @@ -1061,3 +1081,10 @@ export const FullyControlled = {
...defaultProps,
},
};

export const WithAutoHighlight = {
render: AutoHighlightTemplate,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there's no need to create a new template for that. You can simply use Template one and just pass autoHighlight to args below.

args: {
...defaultProps,
},
};
2 changes: 2 additions & 0 deletions packages/components/listbox/src/listbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ function Listbox<T extends object>(props: Props<T>, ref: ForwardedRef<HTMLUListE
disableAnimation,
getEmptyContentProps,
getListProps,
autoHighlight,
} = useListbox<T>({...props, ref});

const content = (
Expand Down Expand Up @@ -51,6 +52,7 @@ function Listbox<T extends object>(props: Props<T>, ref: ForwardedRef<HTMLUListE
<ListboxItem
key={item.key}
{...itemProps}
autoHighlighted={autoHighlight && state.selectionManager.focusedKey === item.key}
classNames={mergeProps(itemClasses, item.props?.classNames)}
shouldHighlightOnFocus={shouldHighlightOnFocus}
/>
Expand Down
6 changes: 5 additions & 1 deletion packages/components/listbox/src/use-listbox-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {ListState} from "@react-stately/list";
interface Props<T extends object> extends ListboxItemBaseProps<T> {
item: Node<T>;
state: ListState<T>;
autoHighlighted?: boolean;
}

export type UseListboxItemProps<T extends object> = Props<T> &
Expand All @@ -46,6 +47,7 @@ export function useListboxItem<T extends object>(originalProps: UseListboxItemPr
onPress,
onClick,
shouldHighlightOnFocus,
autoHighlighted = false,
hideSelectedIcon = false,
isReadOnly = false,
...otherProps
Expand Down Expand Up @@ -111,7 +113,8 @@ export function useListboxItem<T extends object>(originalProps: UseListboxItemPr

const isHighlighted =
(shouldHighlightOnFocus && isFocused) ||
(isMobile ? isHovered || isPressed : isHovered || (isFocused && !isFocusVisible));
(isMobile ? isHovered || isPressed : isHovered || (isFocused && !isFocusVisible)) ||
autoHighlighted;

const getItemProps: PropGetter = (props = {}) => ({
ref: domRef,
Expand Down Expand Up @@ -178,6 +181,7 @@ export function useListboxItem<T extends object>(originalProps: UseListboxItemPr
selectedIcon,
hideSelectedIcon,
disableAnimation,
isHighlighted,
getItemProps,
getLabelProps,
getWrapperProps,
Expand Down
7 changes: 7 additions & 0 deletions packages/components/listbox/src/use-listbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ interface Props<T> extends Omit<HTMLNextUIProps<"ul">, "children"> {
* The menu items classNames.
*/
itemClasses?: ListboxItemProps["classNames"];
/**
* Whether to automatically highlight the first item in the list.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

first non-disabled item

* @default false
*/
autoHighlight?: boolean;
}

export type UseListboxProps<T = object> = Props<T> & AriaListBoxOptions<T> & ListboxVariantProps;
Expand All @@ -118,6 +123,7 @@ export function useListbox<T extends object>(props: UseListboxProps<T>) {
hideEmptyContent = false,
shouldHighlightOnFocus = false,
classNames,
autoHighlight = false,
...otherProps
} = props;

Expand Down Expand Up @@ -181,6 +187,7 @@ export function useListbox<T extends object>(props: UseListboxProps<T>) {
disableAnimation,
className,
itemClasses,
autoHighlight,
getBaseProps,
getListProps,
getEmptyContentProps,
Expand Down