@leafygreen-ui/combobox 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,293 @@
1
+ import { ReactElement, ReactNode } from 'react';
2
+ import { Either } from '@leafygreen-ui/lib';
3
+
4
+ /**
5
+ * Prop Enums & Types
6
+ */
7
+
8
+ export const ComboboxSize = {
9
+ default: 'default',
10
+ } as const;
11
+ export type ComboboxSize = typeof ComboboxSize[keyof typeof ComboboxSize];
12
+
13
+ export const TrunctationLocation = {
14
+ start: 'start',
15
+ middle: 'middle',
16
+ end: 'end',
17
+ none: 'none',
18
+ } as const;
19
+ export type TrunctationLocation = typeof TrunctationLocation[keyof typeof TrunctationLocation];
20
+
21
+ export const Overflow = {
22
+ expandY: 'expand-y',
23
+ expandX: 'expand-x',
24
+ scrollY: 'scroll-x',
25
+ } as const;
26
+ export type Overflow = typeof Overflow[keyof typeof Overflow];
27
+
28
+ export const State = {
29
+ error: 'error',
30
+ none: 'none',
31
+ } as const;
32
+ export type State = typeof State[keyof typeof State];
33
+
34
+ export const SearchState = {
35
+ unset: 'unset',
36
+ error: 'error',
37
+ loading: 'loading',
38
+ } as const;
39
+ export type SearchState = typeof SearchState[keyof typeof SearchState];
40
+
41
+ /**
42
+ * Generic Typing
43
+ */
44
+
45
+ export type SelectValueType<M extends boolean> = M extends true
46
+ ? Array<string>
47
+ : string | null;
48
+
49
+ export type onChangeType<M extends boolean> = M extends true
50
+ ? (value: SelectValueType<true>) => void
51
+ : (value: SelectValueType<false>) => void;
52
+
53
+ // Returns the correct empty state for multiselcect / single select
54
+ export function getNullSelection<M extends boolean>(
55
+ multiselect: M,
56
+ ): SelectValueType<M> {
57
+ if (multiselect) {
58
+ return ([] as Array<string>) as SelectValueType<M>;
59
+ } else {
60
+ return null as SelectValueType<M>;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Combobox Props
66
+ */
67
+
68
+ export interface ComboboxMultiselectProps<M extends boolean> {
69
+ /**
70
+ * Defines whether a user can select multiple options, or only a single option.
71
+ * When using TypeScript, `multiselect` affects the valid values of `initialValue`, `value`, and `onChange`
72
+ */
73
+ multiselect?: M;
74
+ /**
75
+ * The initial selection.
76
+ * Must be a string for a single-select, or an array of strings for multiselect.
77
+ * Changing the initialValue after initial render will not change the selection.
78
+ */
79
+ initialValue?: SelectValueType<M>;
80
+ /**
81
+ * A callback called when the selection changes.
82
+ * Callback recieves a single argument that is the new selection, either string, or string array
83
+ */
84
+ onChange?: onChangeType<M>;
85
+ /**
86
+ * The controlled value of the Combobox.
87
+ * Must be a string for a single-select, or an array of strings for multiselect.
88
+ * Changing value after initial render will affect the selection.
89
+ */
90
+ value?: SelectValueType<M>;
91
+ /**
92
+ * Defines the overflow behavior of a multiselect combobox.
93
+ *
94
+ * `expand-y`: Combobox has fixed width, and additional selections will cause the element to grow in the block direction.
95
+ *
96
+ * `expand-x`: Combobox has fixed height, and additional selections will cause the elemenet to grow in the inline direction.
97
+ *
98
+ * `scroll-x`: Combobox has fixed height and width, and additional selections will cause the element to be scrollable in the x (horizontal) direction.
99
+ */
100
+ overflow?: M extends true ? Overflow : undefined;
101
+ }
102
+
103
+ export interface BaseComboboxProps {
104
+ /**
105
+ * Defines the Combobox Options by passing children. Must be `ComboboxOption` or `ComboboxGroup`
106
+ */
107
+ children?: ReactNode;
108
+
109
+ /**
110
+ * An accessible label for the input, rendered in a <label> to the DOM
111
+ */
112
+ label?: string;
113
+
114
+ /**
115
+ * An accessible label for the input, used only for screen-readers
116
+ */
117
+ 'aria-label'?: string;
118
+
119
+ /**
120
+ * A description for the input
121
+ */
122
+ description?: string;
123
+
124
+ /**
125
+ * A placeholder for the input element. Uses the native `placeholder` attribute.
126
+ */
127
+ placeholder?: string;
128
+
129
+ /**
130
+ * Disables all interaction with the component
131
+ */
132
+ disabled?: boolean;
133
+
134
+ /**
135
+ * Defines the visual size of the component
136
+ */
137
+ size?: ComboboxSize;
138
+
139
+ /**
140
+ * Toggles Dark Mode
141
+ */
142
+ darkMode?: boolean;
143
+
144
+ /**
145
+ * The error state of the component. Defines whether the error message is displayed.
146
+ */
147
+ state?: State;
148
+
149
+ /**
150
+ * The message shown below the input when state is `error`
151
+ */
152
+ errorMessage?: string;
153
+
154
+ /**
155
+ * The state of search results. Toggles search messages within the menu.
156
+ */
157
+ searchState?: SearchState;
158
+
159
+ /**
160
+ * A message shown within the menu when there are no options passed in as children, or `filteredOptions` is an empty array
161
+ */
162
+ searchEmptyMessage?: string;
163
+
164
+ /**
165
+ * A message shown within the menu when searchState is `error`
166
+ */
167
+ searchErrorMessage?: string;
168
+
169
+ /**
170
+ * A message shown within the menu when searchState is `loading`
171
+ */
172
+ searchLoadingMessage?: string;
173
+
174
+ /**
175
+ * A callback called when the search input changes.
176
+ * Recieves a single argument that is the current input value.
177
+ * Use this callback to set `searchState` and/or `filteredOptions` appropriately
178
+ */
179
+ onFilter?: (value: string) => void;
180
+
181
+ /**
182
+ * Defines whether the Clear button appears to the right of the input.
183
+ */
184
+ clearable?: boolean;
185
+
186
+ /**
187
+ * A callback fired when the Clear button is pressed.
188
+ * Fired _after_ `onChange`, and _before_ `onFilter`
189
+ */
190
+ onClear?: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
191
+
192
+ /**
193
+ * An array used to define which options are displayed.
194
+ * Do not remove options from the JSX children, as this will affect the selected options
195
+ */
196
+ filteredOptions?: Array<string>;
197
+
198
+ /**
199
+ * Defines where the ellipses appear in a Chip when the length exceeds the `chipCharacterLimit`
200
+ */
201
+ chipTruncationLocation?: TrunctationLocation;
202
+
203
+ /**
204
+ * Defined the character limit of a multiselect Chip before they start truncating.
205
+ * Note: the three ellipses dots are included in the character limit.
206
+ */
207
+ chipCharacterLimit?: number;
208
+
209
+ /**
210
+ * Styling prop
211
+ */
212
+ className?: string;
213
+ }
214
+
215
+ export type ComboboxProps<M extends boolean> = Either<
216
+ BaseComboboxProps & ComboboxMultiselectProps<M>,
217
+ 'label' | 'aria-label'
218
+ >;
219
+
220
+ /**
221
+ * Combobox Option Props
222
+ */
223
+ interface BaseComboboxOptionProps {
224
+ /**
225
+ * The internal value of the option. Used as the identifier in Combobox `initialValue`, value and filteredOptions.
226
+ * When undefined, this is set to `_.kebabCase(displayName)`
227
+ */
228
+ value?: string;
229
+
230
+ /**
231
+ * The display value of the option. Used as the rendered string within the menu and chips.
232
+ * When undefined, this is set to `value`
233
+ */
234
+ displayName?: string;
235
+
236
+ /**
237
+ * The icon to display to the left of the option in the menu.
238
+ */
239
+ glyph?: ReactElement;
240
+
241
+ /**
242
+ * Styling Prop
243
+ */
244
+ className?: string;
245
+ }
246
+
247
+ export type ComboboxOptionProps = Either<
248
+ BaseComboboxOptionProps,
249
+ 'value' | 'displayName'
250
+ >;
251
+
252
+ export interface InternalComboboxOptionProps {
253
+ value: string;
254
+ displayName: string;
255
+ isSelected: boolean;
256
+ isFocused: boolean;
257
+ setSelected: () => void;
258
+ glyph?: ReactElement;
259
+ className?: string;
260
+ index: number;
261
+ }
262
+
263
+ /**
264
+ * Combobox Group Props
265
+ */
266
+
267
+ export interface ComboboxGroupProps {
268
+ /**
269
+ * Label for the group of options
270
+ */
271
+ label: string;
272
+
273
+ /**
274
+ * Options in the group. Must be one or more `ComboboxOption` components
275
+ */
276
+ children: React.ReactNode;
277
+
278
+ /**
279
+ * Styling prop
280
+ */
281
+ className?: string;
282
+ }
283
+
284
+ /**
285
+ * Combobox Chip
286
+ */
287
+
288
+ export interface ChipProps {
289
+ displayName: string;
290
+ isFocused: boolean;
291
+ onRemove: () => void;
292
+ onFocus: () => void;
293
+ }
@@ -0,0 +1,21 @@
1
+ import { createContext } from 'react';
2
+ import { ComboboxSize, TrunctationLocation } from './Combobox.types';
3
+
4
+ interface ComboboxData {
5
+ multiselect: boolean;
6
+ darkMode: boolean;
7
+ size: keyof typeof ComboboxSize;
8
+ withIcons: boolean;
9
+ disabled: boolean;
10
+ chipTruncationLocation?: TrunctationLocation;
11
+ chipCharacterLimit?: number;
12
+ inputValue?: string;
13
+ }
14
+
15
+ export const ComboboxContext = createContext<ComboboxData>({
16
+ multiselect: false,
17
+ darkMode: false,
18
+ size: 'default',
19
+ withIcons: false,
20
+ disabled: false,
21
+ });
@@ -0,0 +1,61 @@
1
+ import { css, cx } from '@leafygreen-ui/emotion';
2
+ import { useIdAllocator } from '@leafygreen-ui/hooks';
3
+ import { uiColors } from '@leafygreen-ui/palette';
4
+ import React, { useContext } from 'react';
5
+ import { ComboboxGroupProps } from './Combobox.types';
6
+ import { ComboboxContext } from './ComboboxContext';
7
+
8
+ const comboboxGroupStyle = (darkMode: boolean) => css`
9
+ --lg-combobox-group-label-color: ${darkMode
10
+ ? uiColors.gray.light1
11
+ : uiColors.gray.dark1};
12
+ --lg-combobox-group-border-color: ${darkMode
13
+ ? uiColors.gray.dark1
14
+ : uiColors.gray.light1};
15
+ padding-top: 8px;
16
+ border-bottom: 1px solid var(--lg-combobox-group-border-color);
17
+ `;
18
+
19
+ const comboboxGroupLabel = css`
20
+ cursor: default;
21
+ width: 100%;
22
+ padding: 0 12px 2px;
23
+ outline: none;
24
+ overflow-wrap: anywhere;
25
+ font-size: 12px;
26
+ line-height: 16px;
27
+ font-weight: bold;
28
+ text-transform: uppercase;
29
+ letter-spacing: 0.4px;
30
+ color: var(--lg-combobox-group-label-color);
31
+ `;
32
+
33
+ export function InternalComboboxGroup({
34
+ label,
35
+ className,
36
+ children,
37
+ }: ComboboxGroupProps): JSX.Element {
38
+ const { darkMode } = useContext(ComboboxContext);
39
+
40
+ const groupId = useIdAllocator({ prefix: 'combobox-group' });
41
+ const childCount = React.Children.count(children);
42
+
43
+ return childCount > 0 ? (
44
+ <div className={cx(comboboxGroupStyle(darkMode), className)}>
45
+ <div className={comboboxGroupLabel} id={groupId}>
46
+ {label}
47
+ </div>
48
+ <div role="group" aria-labelledby={groupId}>
49
+ {children}
50
+ </div>
51
+ </div>
52
+ ) : (
53
+ <></>
54
+ );
55
+ }
56
+
57
+ ComboboxGroup.displayName = 'ComboboxGroup';
58
+
59
+ export default function ComboboxGroup(_: ComboboxGroupProps): JSX.Element {
60
+ throw Error('`ComboboxGroup` must be a child of a `Combobox` instance');
61
+ }
@@ -0,0 +1,200 @@
1
+ import { css, cx } from '@leafygreen-ui/emotion';
2
+ import React, { useCallback, useContext, useMemo } from 'react';
3
+ import { uiColors } from '@leafygreen-ui/palette';
4
+ import { isComponentType } from '@leafygreen-ui/lib';
5
+ import { useForwardedRef, useIdAllocator } from '@leafygreen-ui/hooks';
6
+ import Checkbox from '@leafygreen-ui/checkbox';
7
+ import Icon, { isComponentGlyph } from '@leafygreen-ui/icon';
8
+ import {
9
+ ComboboxOptionProps,
10
+ InternalComboboxOptionProps,
11
+ } from './Combobox.types';
12
+ import { ComboboxContext } from './ComboboxContext';
13
+ import { wrapJSX } from './util';
14
+
15
+ /**
16
+ * Styles
17
+ */
18
+
19
+ const comboboxOptionStyle = () => css`
20
+ position: relative;
21
+ display: flex;
22
+ align-items: center;
23
+ justify-content: space-between;
24
+ list-style: none;
25
+ color: inherit;
26
+ cursor: pointer;
27
+ overflow: hidden;
28
+ font-size: var(--lg-combobox-item-font-size);
29
+ line-height: var(--lg-combobox-item-line-height);
30
+ padding: var(--lg-combobox-item-padding-y) var(--lg-combobox-item-padding-x);
31
+
32
+ &:before {
33
+ content: '';
34
+ position: absolute;
35
+ left: 0;
36
+ width: 3px;
37
+ height: var(--lg-combobox-item-wedge-height);
38
+ background-color: transparent;
39
+ border-radius: 0 2px 2px 0;
40
+ transform: scaleY(0.3);
41
+ transition: 150ms ease-in-out;
42
+ transition-property: transform, background-color;
43
+ }
44
+
45
+ &:hover {
46
+ outline: none;
47
+ background-color: var(--lg-combobox-item-hover-color);
48
+ }
49
+
50
+ &[aria-selected='true'] {
51
+ outline: none;
52
+ background-color: var(--lg-combobox-item-active-color);
53
+
54
+ &:before {
55
+ background-color: var(--lg-combobox-item-wedge-color);
56
+ transform: scaleY(1);
57
+ }
58
+ }
59
+ `;
60
+
61
+ const flexSpan = css`
62
+ display: inline-flex;
63
+ gap: 8px;
64
+ justify-content: start;
65
+ align-items: inherit;
66
+ `;
67
+
68
+ const displayNameStyle = (isSelected: boolean) => css`
69
+ font-weight: ${isSelected ? 'bold' : 'normal'};
70
+ `;
71
+ /**
72
+ * Component
73
+ */
74
+
75
+ const InternalComboboxOption = React.forwardRef<
76
+ HTMLLIElement,
77
+ InternalComboboxOptionProps
78
+ >(
79
+ (
80
+ {
81
+ displayName,
82
+ glyph,
83
+ isSelected,
84
+ isFocused,
85
+ setSelected,
86
+ className,
87
+ }: InternalComboboxOptionProps,
88
+ forwardedRef,
89
+ ) => {
90
+ const { multiselect, darkMode, withIcons, inputValue } = useContext(
91
+ ComboboxContext,
92
+ );
93
+ const optionTextId = useIdAllocator({ prefix: 'combobox-option-text' });
94
+ const optionRef = useForwardedRef(forwardedRef, null);
95
+
96
+ const handleOptionClick = useCallback(
97
+ (e: React.SyntheticEvent) => {
98
+ e.stopPropagation();
99
+ // If user clicked on the option, or the checkbox
100
+ // Ignore extra click events on the checkbox wrapper
101
+ if (
102
+ e.target === optionRef.current ||
103
+ (e.target as Element).tagName === 'INPUT'
104
+ ) {
105
+ setSelected();
106
+ }
107
+ },
108
+ [optionRef, setSelected],
109
+ );
110
+
111
+ const renderedIcon = useMemo(() => {
112
+ if (glyph) {
113
+ if (isComponentGlyph(glyph) || isComponentType(glyph, 'Icon')) {
114
+ return glyph;
115
+ }
116
+ console.error(
117
+ '`ComboboxOption` instance did not render icon because it is not a known glyph element.',
118
+ glyph,
119
+ );
120
+ }
121
+ }, [glyph]);
122
+
123
+ const renderedChildren = useMemo(() => {
124
+ // Multiselect
125
+ if (multiselect) {
126
+ const checkbox = (
127
+ <Checkbox
128
+ // Using empty label due to this bug: https://jira.mongodb.org/browse/PD-1681
129
+ label=""
130
+ aria-labelledby={optionTextId}
131
+ checked={isSelected}
132
+ tabIndex={-1}
133
+ animate={false}
134
+ />
135
+ );
136
+
137
+ return (
138
+ <>
139
+ <span className={flexSpan}>
140
+ {withIcons ? renderedIcon : checkbox}
141
+ <span id={optionTextId} className={displayNameStyle(isSelected)}>
142
+ {wrapJSX(displayName, inputValue, 'strong')}
143
+ </span>
144
+ </span>
145
+ {withIcons && checkbox}
146
+ </>
147
+ );
148
+ }
149
+
150
+ // Single select
151
+ return (
152
+ <>
153
+ <span className={flexSpan}>
154
+ {renderedIcon}
155
+ <span className={displayNameStyle(isSelected)}>
156
+ {wrapJSX(displayName, inputValue, 'strong')}
157
+ </span>
158
+ </span>
159
+ {isSelected && (
160
+ <Icon
161
+ glyph="Checkmark"
162
+ color={darkMode ? uiColors.blue.light1 : uiColors.blue.base}
163
+ />
164
+ )}
165
+ </>
166
+ );
167
+ }, [
168
+ multiselect,
169
+ renderedIcon,
170
+ isSelected,
171
+ displayName,
172
+ inputValue,
173
+ darkMode,
174
+ optionTextId,
175
+ withIcons,
176
+ ]);
177
+
178
+ return (
179
+ <li
180
+ ref={optionRef}
181
+ role="option"
182
+ aria-selected={isFocused}
183
+ aria-label={displayName}
184
+ tabIndex={-1}
185
+ className={cx(comboboxOptionStyle(), className)}
186
+ onClick={handleOptionClick}
187
+ onKeyPress={handleOptionClick}
188
+ >
189
+ {renderedChildren}
190
+ </li>
191
+ );
192
+ },
193
+ );
194
+ InternalComboboxOption.displayName = 'ComboboxOption';
195
+
196
+ export { InternalComboboxOption };
197
+ export default function ComboboxOption(_: ComboboxOptionProps): JSX.Element {
198
+ throw Error('`ComboboxOption` must be a child of a `Combobox` instance');
199
+ }
200
+ ComboboxOption.displayName = 'ComboboxOption';