-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathSelect.tsx
More file actions
259 lines (244 loc) · 7.26 KB
/
Copy pathSelect.tsx
File metadata and controls
259 lines (244 loc) · 7.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import {
Select as AriaSelect,
Autocomplete,
SelectValue,
Button,
Label,
Text,
Popover,
Virtualizer,
ListLayout,
ListBoxSection,
Collection,
Header,
useFilter
} from 'react-aria-components';
import type {
SelectProps as AriaSelectProps,
AutocompleteProps
} from 'react-aria-components';
import { useState, useMemo, useRef, useCallback, type Key } from 'react';
import { flushSync } from 'react-dom';
import * as s from 'superstruct';
import { Plural } from '@lingui/react/macro';
import './react-aria/components/Select.css';
import { SearchField } from './react-aria/components/SearchField';
import {
DropdownListBox as SelectListBox,
DropdownItem as SelectItem
} from './react-aria/components/ListBox';
import {
type Item,
type Section,
SingleSelectProps,
MultipleSelectProps
} from './react-aria/props';
import { TagGroup } from './react-aria/components/TagGroup';
type SelectionMode = 'single' | 'multiple';
type SelectProps<M extends SelectionMode = 'single'> = AriaSelectProps<
Item,
M
> & {
items?: Item[];
sections?: Section[];
value: M extends 'single' ? string | null : string[];
label?: string;
description?: string;
triggerId?: string;
labelId?: string;
ariaLabelledbyPrefix?: string;
alwaysShowKey?: string;
};
type AutocompleteFilter = NonNullable<AutocompleteProps<Item>['filter']>;
function Select<M extends SelectionMode = 'single'>({
items,
sections,
label,
description,
triggerId,
labelId,
ariaLabelledbyPrefix,
alwaysShowKey,
...props
}: SelectProps<M>) {
const { contains } = useFilter({ sensitivity: 'base', numeric: true });
const filter = useCallback<AutocompleteFilter>(
(textValue, inputValue, node) => {
if (alwaysShowKey && node.value?.value == alwaysShowKey) {
return true;
}
return contains(textValue, inputValue);
},
[contains, alwaysShowKey]
);
if (!items && !sections) {
throw new Error('Select must be provided with either items or sections');
}
if (!props['aria-label'] && labelId && ariaLabelledbyPrefix) {
props['aria-labelledby'] = `${ariaLabelledbyPrefix} ${labelId}`;
}
return (
<AriaSelect {...props}>
{label ? (
<Label className="fr-label">
{label}
{description ? (
<Text slot="description" className="fr-hint-text">
{description}
</Text>
) : null}
</Label>
) : null}
{props.selectionMode == 'single' ? (
<Button id={triggerId} className="fr-select">
<SelectValue />
</Button>
) : (
<MultipleSelectValue triggerId={triggerId} />
)}
<Popover
className="react-aria-Popover select-popover"
style={{ display: 'flex', flexDirection: 'column' }}
>
<Autocomplete<Item> filter={filter}>
<SearchField autoFocus style={{ margin: 4 }} />
<Virtualizer layout={ListLayout}>
<SelectListBox items={sections ? undefined : items}>
{sections ? (
<Collection items={sections}>
{(section) => (
<ListBoxSection id={section.label}>
<Header className="dropdown-section-header">
{section.label}
</Header>
<Collection items={section.items}>
{(item) => (
<SelectItem id={item.value}>{item.label}</SelectItem>
)}
</Collection>
</ListBoxSection>
)}
</Collection>
) : (
(item) => <SelectItem id={item.value}>{item.label}</SelectItem>
)}
</SelectListBox>
</Virtualizer>
</Autocomplete>
</Popover>
</AriaSelect>
);
}
function MultipleSelectValue({ triggerId }: { triggerId?: string }) {
const selectButtonRef = useRef<HTMLButtonElement>(null);
return (
<SelectValue<Item>>
{({ selectedItems, state, defaultChildren }) => (
<>
<Button id={triggerId} className="fr-select" ref={selectButtonRef}>
<span className="react-aria-SelectValue" data-placeholder>
<Plural
value={selectedItems.length}
_0={defaultChildren}
one="1 choix sélectionné"
other="# choix sélectionnés"
/>
</span>
</Button>
<TagGroup
items={selectedItems.filter((item) => item != null)}
onRemove={(value) => {
if (Array.isArray(state.value)) {
state.setValue(state.value.filter((k) => k !== value));
}
}}
fallbackFocusRef={selectButtonRef}
aria-label="Sélection"
/>
</>
)}
</SelectValue>
);
}
export function SingleSelect(maybeProps: SelectProps<'single'>) {
const {
value: initialValue,
className,
...props
} = useMemo(() => s.create(maybeProps, SingleSelectProps), [maybeProps]);
const [value, setValue] = useState<string | null>(() => initialValue);
const changeDispatchRef = useRef<HTMLInputElement>(null);
const dispatchChange = () => {
changeDispatchRef.current?.dispatchEvent(
new Event('change', { bubbles: true })
);
};
const onChange = (key: Key | null) => {
flushSync(() => {
setValue(key ? String(key) : null);
});
dispatchChange();
};
return (
<>
<Select
className={`fr-ds-select_single react-aria-Select ${className ?? ''}`}
selectionMode="single"
value={value}
onChange={onChange}
{...props}
/>
<input ref={changeDispatchRef} type="hidden" />
</>
);
}
export function MultipleSelect(maybeProps: SelectProps<'multiple'>) {
const {
value: initialValue,
className,
name,
...props
} = useMemo(() => s.create(maybeProps, MultipleSelectProps), [maybeProps]);
const [value, setValue] = useState<string[]>(() => initialValue);
const changeDispatchRef = useRef<HTMLInputElement>(null);
const dispatchChange = () => {
changeDispatchRef.current?.dispatchEvent(
new Event('change', { bubbles: true })
);
};
const onChange = (keys: Key[]) => {
flushSync(() => {
setValue(keys.map(String));
});
dispatchChange();
};
// `name` is destructured out above so the `{...props}` spread no longer carries
// it into <Select>. Otherwise react-aria's hidden <select multiple> picks up the
// name and the browser submits its selected options in DOM (collection) order —
// losing the user's selection order. The explicit hidden inputs below carry the
// form value in selection order instead.
return (
<>
<Select
className={`fr-ds-select_multiple react-aria-Select ${className ?? ''}`}
selectionMode="multiple"
value={value}
onChange={onChange}
{...props}
/>
{value.length === 0 ? (
<input ref={changeDispatchRef} type="hidden" name={name} value="" />
) : (
value.map((v, i) => (
<input
key={v}
ref={i === 0 ? changeDispatchRef : undefined}
type="hidden"
name={name}
value={v}
/>
))
)}
</>
);
}