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

Add generic option type #768

Open
wants to merge 6 commits into
base: main
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
19 changes: 9 additions & 10 deletions src/behaviors/async.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { optionType } from '../propTypes';
import { getDisplayName, isFunction, warn } from '../utils';

import { TypeaheadComponentProps } from '../components/Typeahead';
import type { Option } from '../types';
import type { OptionType } from '../types';

const propTypes = {
/**
Expand Down Expand Up @@ -57,7 +57,7 @@ const propTypes = {
useCache: PropTypes.bool,
};

export interface UseAsyncProps extends TypeaheadComponentProps {
export interface UseAsyncProps<Option extends OptionType> extends TypeaheadComponentProps<Option> {
delay?: number;
isLoading: boolean;
onSearch: (query: string) => void;
Expand All @@ -66,7 +66,7 @@ export interface UseAsyncProps extends TypeaheadComponentProps {
useCache?: boolean;
}

type Cache = Record<string, Option[]>;
type Cache<Option extends OptionType> = Record<string, Option[]>;

interface DebouncedFunction extends Function {
cancel(): void;
Expand All @@ -80,7 +80,7 @@ interface DebouncedFunction extends Function {
* - Optional query caching
* - Search prompt and empty results behaviors
*/
export function useAsync(props: UseAsyncProps) {
export function useAsync<Option extends OptionType>(props: UseAsyncProps<Option>) {
const {
allowNew,
delay = 200,
Expand All @@ -96,7 +96,7 @@ export function useAsync(props: UseAsyncProps) {
...otherProps
} = props;

const cacheRef = useRef<Cache>({});
const cacheRef = useRef<Cache<Option>>({});
const handleSearchDebouncedRef = useRef<DebouncedFunction | null>(null);
const queryRef = useRef<string>(props.defaultInputValue || '');

Expand Down Expand Up @@ -179,16 +179,15 @@ export function useAsync(props: UseAsyncProps) {
}

/* istanbul ignore next */
export function withAsync<T extends UseAsyncProps = UseAsyncProps>(
export function withAsync<Option extends OptionType, T extends UseAsyncProps<Option> = UseAsyncProps<Option>>(
Component: ComponentType<T>
) {
warn(
false,
'Warning: `withAsync` is deprecated and will be removed in the next ' +
false,
'Warning: `withAsync` is deprecated and will be removed in the next ' +
'major version. Use `useAsync` instead.'
);

const AsyncTypeahead = forwardRef<Typeahead, T>((props, ref) => (
const AsyncTypeahead = forwardRef<Typeahead<Option>, T>((props, ref) => (
<Component {...props} {...useAsync(props)} ref={ref} />
));

Expand Down
12 changes: 6 additions & 6 deletions src/behaviors/item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,26 @@ import {
} from '../utils';

import { optionType } from '../propTypes';
import { Option } from '../types';
import { OptionType } from '../types';

const propTypes = {
option: optionType.isRequired,
position: PropTypes.number,
};

export interface UseItemProps<T> extends HTMLProps<T> {
export interface UseItemProps<T, Option extends OptionType> extends HTMLProps<T> {
onClick?: MouseEventHandler<T>;
option: Option;
position: number;
}

export function useItem<T extends HTMLElement>({
export function useItem<T extends HTMLElement, Option extends OptionType>({
label,
onClick,
option,
position,
...props
}: UseItemProps<T>) {
}: UseItemProps<T, Option>) {
const {
activeIndex,
id,
Expand All @@ -47,7 +47,7 @@ export function useItem<T extends HTMLElement>({
onInitialItemChange,
onMenuItemClick,
setItem,
} = useTypeaheadContext();
} = useTypeaheadContext<Option>();

const itemRef = useRef<T>(null);

Expand Down Expand Up @@ -101,7 +101,7 @@ export function useItem<T extends HTMLElement>({
}

/* istanbul ignore next */
export function withItem<T extends UseItemProps<HTMLElement>>(
export function withItem<Option extends OptionType, T extends UseItemProps<HTMLElement, Option>>(
Component: ComponentType<T>
) {
warn(
Expand Down
12 changes: 6 additions & 6 deletions src/behaviors/token.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import { useRootClose } from 'react-overlays';
import { getDisplayName, isFunction, warn } from '../utils';

import { optionType } from '../propTypes';
import { Option, OptionHandler } from '../types';
import { OptionType, OptionHandler } from '../types';

export interface UseTokenProps<T> extends Omit<HTMLProps<T>, 'onBlur'> {
export interface UseTokenProps<T, Option extends OptionType> extends Omit<HTMLProps<T>, 'onBlur'> {
// `onBlur` is typed more generically because it's passed to `useRootClose`,
// which passes a generic event to the callback.
onBlur?: (event: Event) => void;
onClick?: MouseEventHandler<T>;
onFocus?: FocusEventHandler<T>;
onRemove?: OptionHandler;
onRemove?: OptionHandler<Option>;
option: Option;
}

Expand All @@ -34,14 +34,14 @@ const propTypes = {
option: optionType.isRequired,
};

export function useToken<T extends HTMLElement>({
export function useToken<T extends HTMLElement, Option extends OptionType>({
onBlur,
onClick,
onFocus,
onRemove,
option,
...props
}: UseTokenProps<T>) {
}: UseTokenProps<T, Option>) {
const [active, setActive] = useState<boolean>(false);
const [rootElement, attachRef] = useState<T | null>(null);

Expand Down Expand Up @@ -89,7 +89,7 @@ export function useToken<T extends HTMLElement>({
}

/* istanbul ignore next */
export function withToken<T extends UseTokenProps<HTMLElement>>(
export function withToken<Option extends OptionType, T extends UseTokenProps<HTMLElement, Option>>(
Component: ComponentType<T>
) {
warn(
Expand Down
5 changes: 3 additions & 2 deletions src/components/AsyncTypeahead/AsyncTypeahead.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
render,
userEvent,
} from '../../tests/helpers';
import {TestOption} from "../../tests/data";

const TestComponent = (props) => {
const [isLoading, setIsLoading] = useState(false);
Expand All @@ -37,7 +38,7 @@ const TestComponent = (props) => {
);
};

describe('<AsyncTypeahead>', () => {
describe('<AsyncTyThere isnt peahead>', () => {
it('displays a search prompt', async () => {
const promptText = 'Prompt text';
render(<TestComponent promptText={promptText} />);
Expand Down Expand Up @@ -270,7 +271,7 @@ describe('<AsyncTypeahead>', () => {
});

it('exposes the typeahead instance and public methods', () => {
const ref = createRef<Typeahead>();
const ref = createRef<Typeahead<TestOption>>();

render(
<AsyncTypeahead
Expand Down
8 changes: 5 additions & 3 deletions src/components/AsyncTypeahead/AsyncTypeahead.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import React, { forwardRef } from 'react';
import React, { forwardRef, ReactElement, Ref } from 'react';
import { useAsync, UseAsyncProps } from '../../behaviors/async';
import TypeaheadComponent from '../Typeahead';
import Typeahead from '../../core/Typeahead';
import { OptionType } from "../../types";

const AsyncTypeahead = forwardRef<Typeahead, UseAsyncProps>((props, ref) => (
// Generics are handled with `as` casting
const AsyncTypeahead = forwardRef<Typeahead<OptionType>, UseAsyncProps<OptionType>>((props, ref) => (
<TypeaheadComponent {...useAsync(props)} ref={ref} />
));
)) as <Option extends OptionType>(p: UseAsyncProps<Option> & { ref?: Ref<Typeahead<Option>> }) => ReactElement;

export default AsyncTypeahead;
18 changes: 10 additions & 8 deletions src/components/MenuItem/MenuItem.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,35 @@ import { Story, Meta } from '@storybook/react';

import MenuItem, { MenuItemProps } from './MenuItem';
import {
createTypeaheadContext,
defaultContext,
TypeaheadContext,
TypeaheadContextType,
} from '../../core/Context';
import {OptionType} from "../../types";

export default {
title: 'Components/MenuItem/MenuItem',
component: MenuItem,
} as Meta;

interface Args {
context: Partial<TypeaheadContextType>;
props: MenuItemProps;
interface Args<Option extends OptionType> {
context: Partial<TypeaheadContextType<Option>>;
props: MenuItemProps<Option>;
}

const value = {
...defaultContext,
id: 'test-id',
};

const Template: Story<Args> = ({ context, props }) => (
<TypeaheadContext.Provider value={{ ...value, ...context }}>
const Template = <Option extends OptionType>(): Story<Args<Option>> => ({ context, props }) => {
const TypeaheadContext = createTypeaheadContext<Option>()
return <TypeaheadContext.Provider value={{...value, ...context}}>
<MenuItem {...props} />
</TypeaheadContext.Provider>
);
};

export const Default = Template.bind({});
export const Default = Template().bind({});
Default.args = {
props: {
children: 'This is a menu item',
Expand Down
5 changes: 3 additions & 2 deletions src/components/MenuItem/MenuItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import cx from 'classnames';
import React, { forwardRef, HTMLAttributes, MouseEvent } from 'react';

import { useItem, UseItemProps } from '../../behaviors/item';
import {OptionType} from "../../types";

export interface BaseMenuItemProps extends HTMLAttributes<HTMLAnchorElement> {
active?: boolean;
Expand All @@ -27,8 +28,8 @@ export const BaseMenuItem = forwardRef<HTMLAnchorElement, BaseMenuItemProps>(
}
);

export type MenuItemProps = UseItemProps<HTMLAnchorElement>;
export type MenuItemProps<Option extends OptionType> = UseItemProps<HTMLAnchorElement, Option>;

export default function MenuItem(props: MenuItemProps) {
export default function MenuItem<Option extends OptionType>(props: MenuItemProps<Option>) {
return <BaseMenuItem {...useItem(props)} />;
}
3 changes: 2 additions & 1 deletion src/components/Token/Token.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import { Story, Meta } from '@storybook/react';

import Token, { TokenProps } from './Token';
import { noop } from '../../utils';
import {TestOption} from "../../tests/data";

export default {
title: 'Components/Token',
component: Token,
} as Meta;

const Template: Story<TokenProps<HTMLElement>> = (args) => <Token {...args} />;
const Template: Story<TokenProps<HTMLElement, TestOption>> = (args) => <Token {...args} />;

export const Interactive = Template.bind({});
Interactive.args = {
Expand Down
7 changes: 4 additions & 3 deletions src/components/Token/Token.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ClearButton from '../ClearButton';

import { useToken, UseTokenProps } from '../../behaviors/token';
import { isFunction } from '../../utils';
import {OptionType} from "../../types";

type HTMLElementProps = Omit<HTMLProps<HTMLDivElement>, 'onBlur' | 'ref'>;

Expand Down Expand Up @@ -68,7 +69,7 @@ const StaticToken = ({
return <div className={classnames}>{children}</div>;
};

export interface TokenProps<T> extends UseTokenProps<T> {
export interface TokenProps<T, Option extends OptionType> extends UseTokenProps<T, Option> {
disabled?: boolean;
readOnly?: boolean;
}
Expand All @@ -77,12 +78,12 @@ export interface TokenProps<T> extends UseTokenProps<T> {
* Individual token component, generally displayed within the
* `TypeaheadInputMulti` component, but can also be rendered on its own.
*/
const Token = ({
const Token = <Option extends OptionType>({
children,
option,
readOnly,
...props
}: TokenProps<HTMLElement>) => {
}: TokenProps<HTMLElement, Option>) => {
const { ref, ...tokenProps } = useToken({ ...props, option });
const child = <div className="rbt-token-label">{children}</div>;

Expand Down
13 changes: 7 additions & 6 deletions src/components/Typeahead/Typeahead.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import Hint from '../Hint';
import Menu from '../Menu';
import MenuItem from '../MenuItem';

import options, { Option } from '../../tests/data';
import options, { TestOption } from '../../tests/data';
import { noop } from '../../tests/helpers';
import {OptionType} from "../../types";

export default {
title: 'Components/Typeahead',
Expand Down Expand Up @@ -53,7 +54,7 @@ const defaultProps = {
positionFixed: true,
};

const Template: Story<TypeaheadComponentProps> = (args) => (
const Template: Story<TypeaheadComponentProps<TestOption>> = (args) => (
<Typeahead {...args} />
);

Expand Down Expand Up @@ -122,7 +123,7 @@ CustomMenu.args = {
renderMenu: (results, menuProps) => (
<Menu {...menuProps}>
{/* Use `slice` to avoid mutating the original array */}
{(results as Option[])
{results
.slice()
.reverse()
.map((r, index) => (
Expand All @@ -134,7 +135,7 @@ CustomMenu.args = {
),
};

export const InputGrouping = (args: TypeaheadComponentProps) => (
export const InputGrouping = <Option extends OptionType>(args: TypeaheadComponentProps<Option>) => (
<div
className={cx('input-group', {
'input-group-sm': args.size === 'sm',
Expand All @@ -149,7 +150,7 @@ InputGrouping.args = {
...defaultProps,
};

export const Controlled = (args: TypeaheadComponentProps) => {
export const Controlled = <Option extends OptionType = TestOption>(args: TypeaheadComponentProps<Option>) => {
const [selected, setSelected] = useState(args.selected || []);

return <Typeahead {...args} onChange={setSelected} selected={selected} />;
Expand All @@ -158,7 +159,7 @@ Controlled.args = {
...defaultProps,
};

export const InputValidation = (args: TypeaheadComponentProps) => {
export const InputValidation = <Option extends OptionType = TestOption>(args: TypeaheadComponentProps<Option>) => {
let feedback;
if (args.isValid) {
feedback = 'Looks good!';
Expand Down
Loading