-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDropdown.tsx
372 lines (346 loc) · 11.5 KB
/
Dropdown.tsx
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import React, {
Children,
cloneElement,
forwardRef,
isValidElement,
useCallback,
useEffect,
useMemo,
useRef,
useState
} from 'react'
import { fuzzySearch } from '@utils/lib/fuzzySearch'
import { debounce } from 'lodash'
import {
useFloating,
offset,
flip,
shift,
useListNavigation,
useHover,
// useTypeahead,
useInteractions,
useRole,
useClick,
useDismiss,
autoUpdate,
safePolygon,
FloatingPortal,
useFloatingTree,
useFloatingNodeId,
useFloatingParentNodeId,
FloatingNode,
FloatingTree,
FloatingFocusManager
} from '@floating-ui/react-dom-interactions'
import cx from 'classnames'
import { mergeRefs } from 'react-merge-refs'
import {
MenuItemCount,
ItemLabel,
MenuItemWrapper,
MenuWrapper,
MultiSelectIcon,
RootMenuWrapper
} from './Dropdown.style'
import { SidebarListFilter } from '@components/mex/Sidebar/SidebarList.style'
import { Icon } from '@iconify/react'
import { Input } from '@style/Form'
import searchLine from '@iconify/icons-ri/search-line'
import { mog } from '@workduck-io/mex-utils'
import { MIcon } from '../../types/Types'
import IconDisplay from '@ui/components/IconPicker/IconDisplay'
import { GenericFlex } from '@ui/components/Filters/Filter.style'
import { MenuClassName, MenuItemClassName, RootMenuClassName } from './Dropdown.classes'
export const MenuItem = forwardRef<
HTMLButtonElement,
{
label: string
icon: MIcon
count?: number
multiSelect?: boolean
selected?: boolean
disabled?: boolean
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void
}
>(({ label, disabled, count, icon, multiSelect, selected, ...props }, ref) => {
// mog('MenuItem', { label, disabled, count, icon, multiSelect, selected, props })
return (
<MenuItemWrapper {...props} ref={ref} role="menuitem" disabled={disabled}>
<GenericFlex>
{multiSelect && (
<MultiSelectIcon selected={selected}>
{selected ? <Icon icon="ri:checkbox-fill" /> : <Icon icon="ri:checkbox-blank-line" />}
</MultiSelectIcon>
)}
<IconDisplay icon={icon} />
<ItemLabel>{label}</ItemLabel>
</GenericFlex>
{count && <MenuItemCount>{count}</MenuItemCount>}
</MenuItemWrapper>
)
})
MenuItem.displayName = 'MenuItem'
interface Props {
className?: string
label?: string
nested?: boolean
children?: React.ReactNode
values?: React.ReactNode
allowSearch?: boolean
searchPlaceholder?: string
multiSelect?: boolean
}
export const MenuComponent = forwardRef<any, Props & React.HTMLProps<HTMLButtonElement>>(
({ children, label, values, multiSelect, allowSearch, searchPlaceholder, className, ...props }, ref) => {
const [open, setOpen] = useState(false)
const [activeIndex, setActiveIndex] = useState<number | null>(null)
const [allowHover, setAllowHover] = useState(false)
const [search, setSearch] = useState('')
const [filteredChildren, setFilteredChildren] = useState<React.ReactNode>(children)
const inputRef = React.useRef<HTMLInputElement>(null)
const listItemsRef = useRef<Array<HTMLButtonElement | null>>([])
// const listContentRef = useRef(
// Children.map(filteredChildren, (child) => (isValidElement(child) ? child.props.label : null)) as Array<
// string | null
// >
// )
const onSearchChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
setSearch(e.target.value)
}
const tree = useFloatingTree()
const nodeId = useFloatingNodeId()
const parentId = useFloatingParentNodeId()
const nested = parentId != null
const { x, y, reference, floating, strategy, refs, context } = useFloating<HTMLButtonElement>({
open,
onOpenChange: setOpen,
middleware: [offset({ mainAxis: 4, alignmentAxis: nested ? -5 : 0 }), flip(), shift()],
placement: nested ? 'right-start' : 'bottom-start',
nodeId,
whileElementsMounted: autoUpdate
})
const resetSearch = useCallback(() => {
mog('resetSearch')
setSearch('')
setFilteredChildren(children)
}, [children])
const { getReferenceProps, getFloatingProps, getItemProps } = useInteractions([
useHover(context, {
handleClose: safePolygon({ restMs: 25 }),
enabled: nested && allowHover,
delay: { open: 75 }
}),
useClick(context, {
toggle: !nested && !multiSelect,
pointerDown: true,
ignoreMouse: nested
}),
useRole(context, { role: 'menu' }),
useDismiss(context, {
escapeKey: true,
}),
useListNavigation(context, {
listRef: listItemsRef,
activeIndex,
nested,
onNavigate: setActiveIndex
})
// Typeahead disabled as it conflicts with search input
// useTypeahead(context, {
// listRef: listContentRef,
// onMatch: open ? setActiveIndex : undefined,
// activeIndex
// })
])
useEffect(() => {
if (!open) {
allowSearch && resetSearch()
} else {
if (inputRef.current) {
inputRef.current.focus()
}
}
}, [open, inputRef, allowSearch, resetSearch])
// Event emitter allows you to communicate across tree components.
// This effect closes all menus when an item gets clicked anywhere
// in the tree.
useEffect(() => {
function onTreeClick() {
if (!multiSelect) {
setOpen(false)
resetSearch()
}
if (parentId === null) {
refs.reference.current?.focus()
}
}
tree?.events.on('click', onTreeClick)
return () => {
tree?.events.off('click', onTreeClick)
}
}, [parentId, tree, refs])
// Determine if "hover" logic can run based on the modality of input. This
// prevents unwanted focus synchronization as menus open and close with
// keyboard navigation and the cursor is resting on the menu.
useEffect(() => {
function onPointerMove() {
setAllowHover(true)
}
function onKeyDown() {
setAllowHover(false)
}
window.addEventListener('pointermove', onPointerMove, {
once: true,
capture: true
})
window.addEventListener('keydown', onKeyDown, true)
return () => {
window.removeEventListener('pointermove', onPointerMove, {
capture: true
})
window.removeEventListener('keydown', onKeyDown, true)
}
}, [allowHover])
// Search through the children labels and filter out any that don't match
useEffect(() => {
if (allowSearch) {
if (search && search !== '') {
const childs = Children.map(children, (child) => (isValidElement(child) ? child.props.label : null)) as Array<
string | null
>
// mog('Search', { search, childs })
const filtered = fuzzySearch(childs, search, (item) => item)
// mog('Search', { search, filtered })
const newChildren = Children.map(children, (child) => {
if (isValidElement(child) && filtered.includes(child.props.label)) {
return child
}
})
setFilteredChildren(newChildren)
}
if (search === '') {
setFilteredChildren(children)
}
}
}, [search, allowSearch, children])
const mergedReferenceRef = useMemo(() => mergeRefs([ref, reference]), [reference, ref])
return (
<FloatingNode id={nodeId}>
<RootMenuWrapper
{...getReferenceProps({
...props,
ref: mergedReferenceRef,
onClick(event) {
event.stopPropagation()
;(event.currentTarget as HTMLButtonElement).focus()
},
...(nested
? {
className: cx(MenuItemClassName, { open }),
role: 'menuitem',
onKeyDown(event) {
// Prevent more than one menu from being open.
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
setOpen(false)
resetSearch()
}
}
}
: {
className: cx(className ? className : '', RootMenuClassName, { open })
})
})}
>
{label} {values && values}
{nested && <Icon style={{ marginLeft: 10 }} icon="ri:arrow-right-s-line" />}
</RootMenuWrapper>
<FloatingPortal>
{open && (
<FloatingFocusManager
context={context}
modal={!nested}
returnFocus={!nested}
// Touch-based screen readers will be able to navigate back to the
// reference and click it to dismiss the menu without clicking an item.
// This acts as a touch-based `Esc` key. A visually-hidden dismiss button
// is an alternative.
order={['reference', 'content']}
>
<MenuWrapper
{...getFloatingProps({
className: MenuClassName,
ref: floating,
style: {
position: strategy,
top: y ?? 0,
left: x ?? 0
},
onKeyDown(event) {
if (event.key === 'Tab') {
setOpen(false)
resetSearch()
}
}
})}
>
{allowSearch && children && (
<SidebarListFilter noMargin>
<Icon icon={searchLine} />
<Input
placeholder={searchPlaceholder ?? 'Filter items'}
onChange={debounce((e) => onSearchChange(e), 250)}
ref={inputRef}
/>
</SidebarListFilter>
)}
{Children.map(
filteredChildren,
(child, index) =>
isValidElement(child) &&
cloneElement(
child,
getItemProps({
tabIndex: -1,
role: 'menuitem',
className: MenuItemClassName,
ref(node: HTMLButtonElement) {
listItemsRef.current[index] = node
},
onClick() {
child.props.onClick?.()
tree?.events.emit('click')
},
// By default `focusItemOnHover` uses `mousemove` to sync focus,
// but when a menu closes we want this to sync it on `enter`
// even if the cursor didn't move. NB: Safari does not sync in
// this case.
onPointerEnter() {
if (allowHover) {
setActiveIndex(index)
}
}
})
)
)}
</MenuWrapper>
</FloatingFocusManager>
)}
</FloatingPortal>
</FloatingNode>
)
}
)
MenuComponent.displayName = 'Menu Component'
export const Menu: React.FC<Props> = forwardRef((props, ref) => {
const parentId = useFloatingParentNodeId()
if (parentId == null) {
return (
<FloatingTree>
<MenuComponent {...props} ref={ref} />
</FloatingTree>
)
}
return <MenuComponent {...props} ref={ref} />
})
Menu.displayName = 'Menu'