-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDropdown.tsx
475 lines (436 loc) · 13.4 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import React, {
Children,
cloneElement,
forwardRef,
isValidElement,
useCallback,
useEffect,
useMemo,
useRef,
useState
} from 'react'
import { mergeRefs } from 'react-merge-refs'
import {
flip,
FloatingFocusManager,
FloatingNode,
FloatingPortal,
FloatingTree,
offset,
safePolygon,
shift,
useClick,
useDismiss,
useFloating,
useFloatingNodeId,
useFloatingParentNodeId,
useFloatingTree,
useHover, // useTypeahead,
useInteractions,
useListNavigation
} from '@floating-ui/react-dom-interactions'
import searchLine from '@iconify/icons-ri/search-line'
import { Icon } from '@iconify/react'
import cx from 'classnames'
import { debounce } from 'lodash'
import { useTheme } from 'styled-components'
import { fuzzySearch, MIcon } from '@mexit/core'
import { FilterMenuDiv } from '../../Style/Filter'
import { SidebarListFilter } from '../../Style/SidebarList.style'
import { IconDisplay } from '../IconDisplay'
import { Input } from './../../Style/Form'
import { MenuClassName, MenuFilterInputClassName, MenuItemClassName, RootMenuClassName } from './Dropdown.classes'
import {
ItemLabel,
MenuItemCount,
MenuItemWrapper,
MenuWrapper,
MultiSelectIcon,
RootMenuWrapper
} from './Dropdown.style'
export const MenuItem = forwardRef<
HTMLButtonElement,
{
label: string
icon: MIcon
tabIndex?: number
role?: string
className?: string
count?: number
fontSize?: 'small' | 'regular'
multiSelect?: boolean
isActive?: boolean
selected?: boolean
disabled?: boolean
color?: string
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void
}
>(({ label, disabled, count, color, fontSize, icon, multiSelect, selected, ...props }, ref) => {
return (
<MenuItemWrapper {...props} ref={ref} role="menuitem" disabled={disabled}>
<FilterMenuDiv>
{multiSelect && (
<MultiSelectIcon selected={selected}>
{selected ? <Icon icon="ri:checkbox-fill" /> : <Icon icon="ri:checkbox-blank-line" />}
</MultiSelectIcon>
)}
<IconDisplay icon={icon} color={color} />
<ItemLabel fontSize={fontSize}>{label}</ItemLabel>
</FilterMenuDiv>
{count && <MenuItemCount>{count}</MenuItemCount>}
</MenuItemWrapper>
)
})
MenuItem.displayName = 'MenuItem'
interface Props {
className?: string
label?: string
/**
* Is the menu nested
*/
nested?: boolean
/**
* MenuItems or Menus
*/
children?: React.ReactNode
/**
* Additional values to render in the menu trigger
*/
values?: React.ReactNode
/**
* Whether to show search input?
*/
allowSearch?: boolean
/**
* Placeholder for search input
*/
searchPlaceholder?: string
/**
* Does it allow multiple selections?
*/
multiSelect?: boolean
noHover?: boolean
noBackground?: boolean
onMouseEnter?: (e: any) => void
onMouseLeave?: (e: any) => void
/**
* Show Button with Border
*/
border?: boolean
noPadding?: boolean
handleKeyDown?: (e: KeyboardEvent) => void
/**
* Creatable?
*/
onCreate?: (value: string) => void
/**
* Which element to render the portal in
*/
root?: HTMLElement | null
/**
* Menu Type
*/
type?: 'default' | 'modal'
}
export const MenuComponent = forwardRef<any, Props & React.HTMLProps<HTMLButtonElement>>(
(
{
children,
label,
values,
border = false,
noHover,
multiSelect,
allowSearch,
onCreate,
onMouseEnter,
type,
noPadding,
onMouseLeave,
handleKeyDown,
searchPlaceholder,
className,
root,
...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 theme = useTheme()
const listItemsRef = useRef<Array<HTMLButtonElement | 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({
padding: 25
})
],
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,
event: 'mousedown',
ignoreMouse: nested
}),
useDismiss(context, {
escapeKey: true,
bubbles: false
}),
useListNavigation(context, {
listRef: listItemsRef,
activeIndex,
nested,
loop: true,
onNavigate: setActiveIndex
})
])
// Add scroll to active item
// Required for scrollable menu and when overflow
useEffect(() => {
const activeEl = listItemsRef.current[activeIndex]
if (activeEl) {
activeEl.scrollIntoView({ block: 'nearest' })
}
}, [activeIndex])
useEffect(() => {
if (!open) {
allowSearch && resetSearch()
} else {
if (inputRef.current) {
listItemsRef.current.push(inputRef.current as any)
inputRef.current.focus()
}
}
}, [open, inputRef, allowSearch])
const keyDownHandler = (event: React.KeyboardEvent<HTMLInputElement>) => {
// mog('keyDownHandler', { code: event.code })
if (event.code === 'Enter' && !!onCreate) {
event.preventDefault()
event.stopPropagation()
const inpVal = event.currentTarget.value
onCreate(inpVal)
setOpen(false)
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(e) {
if (handleKeyDown) handleKeyDown(e)
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
} else return null
}).filter((child) => child !== null)
setFilteredChildren(newChildren)
}
if (search === '') {
setFilteredChildren(children)
}
}
}, [search, allowSearch, children])
const mergedReferenceRef = useMemo(() => mergeRefs([ref, reference]), [reference, ref])
return (
<FloatingNode id={nodeId}>
<RootMenuWrapper
noHover={noHover}
border={border}
$noPadding={noPadding}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
{...getReferenceProps({
...props,
ref: mergedReferenceRef,
onClick(event) {
event.stopPropagation()
event.preventDefault()
;(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 root={root}>
{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
type={type}
{...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} color={theme.tokens.text.default} />
<Input
placeholder={searchPlaceholder ?? 'Filter items'}
className={MenuFilterInputClassName}
onChange={debounce((e) => onSearchChange(e), 250)}
onKeyDown={keyDownHandler}
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(e) {
e.stopPropagation()
child.props.onClick?.(e)
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'