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

Added a select all feature #836

Open
wants to merge 1 commit 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
6 changes: 6 additions & 0 deletions src/components/Menu/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import cx from 'classnames';
import PropTypes from 'prop-types';
import React, { Children, HTMLProps, ReactNode, Ref } from 'react';

import { useTypeaheadContext } from '../../core/Context';

import { BaseMenuItem } from '../MenuItem';

import { preventInputBlur } from '../../utils';
Expand Down Expand Up @@ -37,6 +39,7 @@ export interface MenuProps extends HTMLProps<HTMLDivElement> {
emptyLabel?: ReactNode;
innerRef?: Ref<HTMLDivElement>;
maxHeight?: string;
multiple?: boolean;
}

/**
Expand All @@ -57,6 +60,8 @@ const Menu = ({
) : (
props.children
);

const { onSelectAllClick } = useTypeaheadContext();

return (
/* eslint-disable jsx-a11y/interactive-supports-focus */
Expand All @@ -76,6 +81,7 @@ const Menu = ({
maxHeight,
overflow: 'auto',
}}>
{props.multiple && <button type='button' className={cx('dropdown-item')} onClick={() => onSelectAllClick() }>Select All</button>}
{children}
</div>
/* eslint-enable jsx-a11y/interactive-supports-focus */
Expand Down
19 changes: 19 additions & 0 deletions src/components/Typeahead/Typeahead.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1636,4 +1636,23 @@ describe('<Typeahead> with custom menu', () => {
expect(items[1]).toHaveClass('active');
expect(items[1]).toHaveTextContent('Wisconsin');
});

describe('<Typehead> with multiselect', () => {
it('Should select all options when select all button is pressed', async () => {
const user = userEvent.setup();

const { container } = render(<MultiSelect selected={[]} defaultSelected={[]} />);
const input = getInput()
await user.type(input, 'Te');

await user.click(screen.getByRole('button'));

const tokens = getTokens(container);

expect(tokens).toHaveLength(2);

expect(screen.getByText('Tennessee')).toBeInTheDocument();
expect(screen.getByText('Texas')).toBeInTheDocument();
});
});
});
2 changes: 2 additions & 0 deletions src/components/Typeahead/Typeahead.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ class TypeaheadComponent extends React.Component<TypeaheadComponentProps> {
paginationText,
renderMenu,
renderMenuItemChildren,
multiple,
} = this.props;

return (renderMenu || defaultRenderMenu)(
Expand All @@ -288,6 +289,7 @@ class TypeaheadComponent extends React.Component<TypeaheadComponentProps> {
emptyLabel,
id,
maxHeight,
multiple,
newSelectionPrefix,
paginationText,
renderMenuItemChildren,
Expand Down
2 changes: 2 additions & 0 deletions src/core/Context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface TypeaheadContextType {
onAdd: OptionHandler;
onInitialItemChange: (option?: Option) => void;
onMenuItemClick: (option: Option, event: SelectEvent<HTMLElement>) => void;
onSelectAllClick: () => void;
setItem: (option: Option, position: number) => void;
}

Expand All @@ -28,6 +29,7 @@ export const defaultContext = {
onAdd: noop,
onInitialItemChange: noop,
onMenuItemClick: noop,
onSelectAllClick: noop,
setItem: noop,
};

Expand Down
41 changes: 36 additions & 5 deletions src/core/Typeahead.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ function triggerInputChange(input: HTMLInputElement, value: string) {
input.dispatchEvent(e);
}

let selectedOptions: Option[];

class Typeahead extends React.Component<Props, TypeaheadState> {
static propTypes = propTypes;
static defaultProps = defaultProps;
Expand Down Expand Up @@ -325,6 +327,7 @@ class Typeahead extends React.Component<Props, TypeaheadState> {
onInitialItemChange={this._handleInitialItemChange}
onKeyDown={this._handleKeyDown}
onMenuItemClick={this._handleMenuItemSelect}
onSelectAllClick={this._handleAddAll}
onRemove={this._handleSelectionRemove}
results={results}
setItem={this.setItem}
Expand Down Expand Up @@ -510,7 +513,6 @@ class Typeahead extends React.Component<Props, TypeaheadState> {
_handleSelectionAdd = (option: Option) => {
const { multiple, labelKey } = this.props;

let selected: Option[];
let selection = option;
let text: string;

Expand All @@ -523,26 +525,55 @@ class Typeahead extends React.Component<Props, TypeaheadState> {
if (multiple) {
// If multiple selections are allowed, add the new selection to the
// existing selections.
selected = this.state.selected.concat(selection);
selectedOptions = this.state.selected.concat(selection);
text = '';
} else {
// If only a single selection is allowed, replace the existing selection
// with the new one.
selected = [selection];
selectedOptions = [selection];
text = getOptionLabel(selection, labelKey);
}

this.setState(
(state, props) => ({
...hideMenu(state, props),
initialItem: selection,
selected,
selected: selectedOptions,
text,
}),
() => this._handleChange(selected)
() => this._handleChange(selectedOptions)
);
};

_handleAddAll = (results: Option[]) => {
const { multiple } = this.props

const updatedResults = results.map((result) => {

if (!isString(result) && result.customOption) {
return { ...result, id: uniqueId('new-id-') };
}
return result
})

if (multiple) {
// If multiple selections are allowed, add the all result to the
// existing selections.
selectedOptions = this.state.selected.concat(updatedResults);
}

this.setState(
(state, props) => ({
...hideMenu(state, props),
// initialItem: selection,
selected: selectedOptions,
text: '',
}),
() => this._handleChange(selectedOptions)
);
}


_handleSelectionRemove = (selection: Option) => {
const selected = this.state.selected.filter(
(option) => !isEqual(option, selection)
Expand Down
7 changes: 7 additions & 0 deletions src/core/TypeaheadManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const contextKeys = [
'onAdd',
'onInitialItemChange',
'onMenuItemClick',
'onSelectAllClick',
'setItem',
] as (keyof TypeaheadManagerProps)[];

Expand All @@ -66,6 +67,7 @@ const TypeaheadManager = (props: TypeaheadManagerProps) => {
onMenuToggle,
results,
selectHint,
onSelectAllClick
} = props;

const hintText = getHintText(props);
Expand Down Expand Up @@ -101,6 +103,10 @@ const TypeaheadManager = (props: TypeaheadManagerProps) => {
}
};

const handleSelectAll = () => {
onSelectAllClick(results)
}

const childProps = {
...pick(props, propKeys),
getInputProps: getInputProps({
Expand All @@ -114,6 +120,7 @@ const TypeaheadManager = (props: TypeaheadManagerProps) => {
...pick(props, contextKeys),
hintText,
isOnlyResult: getIsOnlyResult(props),
onSelectAllClick: handleSelectAll
};

return (
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ export interface TypeaheadManagerProps extends TypeaheadPropsAndState {
onHide: () => void;
onInitialItemChange: (option?: Option) => void;
onMenuItemClick: (option: Option, event: SelectEvent<HTMLElement>) => void;
onSelectAllClick: (result: Option[]) => void,
onRemove: OptionHandler;
placeholder?: string;
results: Option[];
Expand Down