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: ComboBox component #315

Merged
merged 18 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
40 changes: 40 additions & 0 deletions packages/ui/src/components/ComboBox/ComboBox.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { Meta, StoryObj } from '@storybook/react';
import { useState } from 'react';
import { ComboBox, type ComboBoxProps } from './ComboBox';

const meta: Meta<typeof ComboBox> = {
title: 'Form/ComboBox',
component: ComboBox,
argTypes: {
debounce: {
control: 'number',
defaultValue: 300,
},
},
parameters: {
layout: 'centered',
},
};

export default meta;
type Story = StoryObj<typeof ComboBox>;

function ComboBoxStory(args: Pick<ComboBoxProps, 'debounce'>) {
const [value, setValue] = useState<string>('');

return (
<ComboBox
{...args}
suggestions={['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry']}
placeholder="Type a fruit name"
value={value}
onChange={(value) => setValue(value || '')}
>
<ComboBox.Content />
</ComboBox>
);
}

export const Usage: Story = {
render: ComboBoxStory,
};
250 changes: 250 additions & 0 deletions packages/ui/src/components/ComboBox/ComboBox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
import React, {
useMemo,
useState,
useRef,
memo,
type ReactElement,
type FocusEvent,
type KeyboardEvent,
type MouseEvent,
} from 'react';
import { createComponent, withNamespace } from '../../utils/component';
import { Flex } from '../Box';
import { Input, type InputFieldProps } from '../Input';
import { Popover } from '../Popover';
import { Text } from '../Text';

export interface ComboBoxProps<T = string> {
arthurgeron marked this conversation as resolved.
Show resolved Hide resolved
suggestions: T[];
placeholder?: string;
debounce?: number;
onChange: (value: string | null) => void;
value: T | null;
onClick?: (e: MouseEvent<HTMLInputElement, globalThis.MouseEvent>) => void;
onBlur?: (e: FocusEvent<HTMLInputElement>) => void;
onFocus?: (e: FocusEvent<HTMLInputElement, Element>) => void;
onKeyDown?: (e: KeyboardEvent<HTMLInputElement>) => void;
inputFieldProps?: InputFieldProps;
suggestionFilter?: (suggestion: T) => boolean;
itemNameSelector?: (suggestion: T) => string;
onItemSelected?: (suggestion: T) => void;
children: ReactElement<ComboBoxContentProps<T>>;
/**
* @description If true, input can only be a value from the ComboBox list
*/
strict?: boolean;
}

export interface ComboBoxItemProps<T = string>
extends Pick<ComboBoxProps<T>, 'itemNameSelector'> {
className?: string;
suggestion: T | null;
onItemSelected: (suggestion: T) => void;
}

export interface ComboBoxContentProps<T = string>
extends Pick<ComboBoxProps<T>, 'itemNameSelector' | 'suggestions'> {
suggestion: T | null;
onItemSelected: (suggestion: T) => void;
className?: string;
}

function ComboBoxRoot<T = string>({
suggestions,
placeholder,
strict,
debounce = 300,
suggestionFilter,
itemNameSelector,
onChange,
onBlur: _onBlur,
onClick: _onClick,
onFocus: _onFocus,
onKeyDown: _onKeyDown,
value,
onItemSelected,
inputFieldProps,
children,
}: ComboBoxProps<T>) {
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
const [itemSelected, setItemSelected] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const [filteredSuggestions, setFilteredSuggestions] =
useState<Array<T>>(suggestions);
const debounceTimeout = useRef<NodeJS.Timeout>();
arthurgeron marked this conversation as resolved.
Show resolved Hide resolved

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setItemSelected(false);
const input = event.target.value;
clearTimeout(debounceTimeout.current);
debounceTimeout.current = setTimeout(() => {
clearTimeout(debounceTimeout.current);
debounceTimeout.current = undefined;
const filter =
suggestionFilter ??
((_suggestion) =>
typeof _suggestion === 'string'
? _suggestion.toLowerCase().includes(input.toLowerCase())
: false);
const newFilteredSuggestions = suggestions.filter(filter);
onChange(input);
setFilteredSuggestions(
!newFilteredSuggestions?.length && !input
? suggestions
: newFilteredSuggestions,
);
}, debounce);
};

const handleSuggestionClick = (suggestion: T) => {
inputRef.current?.focus();
const value = itemNameSelector?.(suggestion) ?? (suggestion as string);
if (inputRef.current) {
inputRef.current.value = value;
}
setIsPopoverOpen(false);
if (strict) {
setItemSelected(true);
}
if (onItemSelected) {
onItemSelected(suggestion);
return;
}
onChange(value);
};

const onFocus = (e: FocusEvent<HTMLInputElement, Element>) => {
_onFocus?.(e);
setIsPopoverOpen(true);
};

const onClick = (e: MouseEvent<HTMLInputElement, globalThis.MouseEvent>) => {
_onClick?.(e);
setIsPopoverOpen(true);
};

const onBlur = (e: FocusEvent<HTMLInputElement, Element>) => {
_onBlur?.(e);
if (strict && !itemSelected) {
onChange(null);
}
};

const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
arthurgeron marked this conversation as resolved.
Show resolved Hide resolved
_onKeyDown?.(event);
switch (event.key) {
case 'Enter': {
const selectedValue = strict ? suggestionFilter?.[0] : value;
selectedValue && handleSuggestionClick(selectedValue);
setIsPopoverOpen(false);
break;
}
case 'Escape':
setIsPopoverOpen(false);
break;
default:
break;
}
};

const childWithProps = useMemo(() => {
arthurgeron marked this conversation as resolved.
Show resolved Hide resolved
return React.cloneElement(children, {
suggestions: filteredSuggestions,
itemNameSelector,
onItemSelected: handleSuggestionClick,
});
}, [children]);

return (
<Popover open={isPopoverOpen}>
<Input>
<Input.Field
ref={inputRef}
{...inputFieldProps}
onChange={handleInputChange}
placeholder={placeholder}
onFocus={onFocus}
onClick={onClick}
onBlur={onBlur}
onKeyDown={onKeyDown}
/>
</Input>
<Popover.Trigger>
<div />
arthurgeron marked this conversation as resolved.
Show resolved Hide resolved
</Popover.Trigger>
<Popover.Content
// Goes against accessibility rules but otherwise we'd be constantly losing focus on the input
onOpenAutoFocus={(e) => e.preventDefault()}
>
{childWithProps}
</Popover.Content>
</Popover>
);
}

function ComboBoxItemBase<T = string>({
onItemSelected,
suggestion,
itemNameSelector,
className,
}: ComboBoxItemProps<T>) {
if (!suggestion) return null;

const onClick = () => {
onItemSelected(suggestion);
};

const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Enter') {
onItemSelected(suggestion);
}
};

return (
<div className={className} onClick={onClick} onKeyDown={onKeyDown}>
<Text>{itemNameSelector?.(suggestion) ?? (suggestion as string)}</Text>
</div>
);
}

export const ComboBoxItem = memo(
createComponent({
id: 'ComboBoxItem',
baseElement: ComboBoxItemBase,
arthurgeron marked this conversation as resolved.
Show resolved Hide resolved
}),
) as typeof ComboBoxItemBase;

function ComboBoxContentBase<T = string>({
suggestions,
itemNameSelector,
onItemSelected,
className,
}: ComboBoxContentProps<T>) {
return (
<Flex className={className} direction="column" gap="2">
{suggestions.map((suggestion: T) => (
<ComboBoxItem
key={itemNameSelector?.(suggestion) ?? (suggestion as string)}
suggestion={suggestion}
itemNameSelector={itemNameSelector}
onItemSelected={onItemSelected}
/>
))}
</Flex>
);
}

export const ComboBoxContent = createComponent<
ComboBoxContentProps,
typeof ComboBoxContentBase
>({
id: 'ComboBoxContent',
baseElement: ComboBoxContentBase,
});

export const ComboBox = withNamespace(ComboBoxRoot, {
Item: ComboBoxItem,
Content: ComboBoxContent as unknown as React.ComponentType<
Pick<ComboBoxContentProps, 'className'>
>,
});
11 changes: 11 additions & 0 deletions packages/ui/src/components/ComboBox/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export {
ComboBox,
ComboBoxItem,
ComboBoxContent,
} from './ComboBox';

export type {
ComboBoxProps,
ComboBoxItemProps,
ComboBoxContentProps,
} from './ComboBox';
1 change: 1 addition & 0 deletions packages/ui/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export * from './components/Alert';
export * from './components/AlertDialog';
export * from './components/AspectRatio';
export * from './components/Asset';
export * from './components/ComboBox';
export * from './components/Avatar';
export * from './components/Badge';
export * from './components/Box';
Expand Down
Loading