-
Notifications
You must be signed in to change notification settings - Fork 65
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
fix(component): performance improvements for Dropdown/Select components #475
Merged
Merged
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
36e01f6
refactor: performance improvements
jorgemoya d0fc14a
fix: add groups
jorgemoya 3a13384
fix: add actions
jorgemoya 87ac777
fix: add filtering
jorgemoya 2ddfdf4
fix: add popper
jorgemoya 3b9f8a1
fix: select handling
jorgemoya 4faba33
fix: add dropdown
jorgemoya d4b4a82
fix: popper in dropdowns
jorgemoya 85c9e29
fix: dropdown types
jorgemoya 2a9efc9
fix: merge List
jorgemoya 5c59b65
fix: remove unsued components
jorgemoya d5ee51c
fix: error logs
jorgemoya cbf87cd
fix: add groups to multiselect
jorgemoya 2c5fae0
fix: fix unit tests
jorgemoya 287557b
fix: some ts fixes
jorgemoya bb817a5
fix: add positionFixed
jorgemoya 5870bf0
fix: ts errors
jorgemoya d13eae4
fix: add more doc stuff
jorgemoya 2bad280
fix: add disabled prop
jorgemoya a87a804
fix: improvements and fixes
jorgemoya 22f57ab
fix: add missing docs
jorgemoya 18dd9f2
fix: some ts changes
jorgemoya 72208b0
fix: more ts stuff
jorgemoya ba68a2d
fix: more ts changes
jorgemoya 1af7867
fix: more ts fixes
jorgemoya 20e7656
fix: pr feedback
jorgemoya a43e3b5
fix: button
jorgemoya 4672aab
chore: bump dependencies
jorgemoya 67772cb
chore: bump downshift
jorgemoya File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
327 changes: 74 additions & 253 deletions
327
packages/big-design/src/components/Dropdown/Dropdown.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,298 +1,119 @@ | ||
import { useSelect, UseSelectState } from 'downshift'; | ||
import React, { cloneElement, Fragment, isValidElement, memo, useCallback, useMemo, useRef } from 'react'; | ||
import { Manager, Popper, Reference } from 'react-popper'; | ||
import React, { cloneElement, isValidElement, memo, useCallback, useMemo, useRef } from 'react'; | ||
import { usePopper } from 'react-popper'; | ||
|
||
import { useUniqueId } from '../../hooks'; | ||
import { Flex } from '../Flex'; | ||
import { FlexItem } from '../Flex/Item'; | ||
import { Box } from '../Box'; | ||
import { List } from '../List'; | ||
import { ListGroupHeader } from '../List/GroupHeader'; | ||
import { ListGroupSeparator } from '../List/GroupSeparator'; | ||
import { ListItem } from '../List/Item'; | ||
import { Tooltip } from '../Tooltip'; | ||
|
||
import { StyledBox, StyledLink } from './styled'; | ||
import { StyledBox } from './styled'; | ||
import { DropdownItem, DropdownItemGroup, DropdownLinkItem, DropdownProps } from './types'; | ||
|
||
export const Dropdown = memo( | ||
({ | ||
autoWidth = false, | ||
className, | ||
disabled = false, | ||
maxHeight = 250, | ||
maxHeight, | ||
id, | ||
items, | ||
placement = 'bottom-start' as 'bottom-start', | ||
placement = 'bottom-start' as const, | ||
positionFixed = false, | ||
toggle, | ||
style, | ||
...rest | ||
...props | ||
}: DropdownProps) => { | ||
// We only need the items to pass down to Downshift, not groups | ||
const onlyItems = useMemo(() => flattenItems(items), [items]); | ||
const dropdownUniqueId = useUniqueId('dropdown'); | ||
|
||
// We need to keep track of key since we need to use it between groups. | ||
const itemKey = useRef(0); | ||
const flattenItems = useCallback((items: DropdownProps['items']) => { | ||
const isGroups = ( | ||
items: Array<DropdownItemGroup | DropdownItem | DropdownLinkItem>, | ||
): items is Array<DropdownItemGroup> => items.every((items) => 'items' in items && !('content' in items)); | ||
|
||
const dropdownUniqueId = useUniqueId('dropdown'); | ||
return isGroups(items) ? items.map((group) => group.items).reduce((acum, curr) => acum.concat(curr), []) : items; | ||
}, []); | ||
|
||
// We only need the items to pass down to Downshift, not groups | ||
const flattenedItems = useMemo(() => flattenItems(items), [flattenItems, items]); | ||
|
||
const handleOnSelectedItemChange = useCallback( | ||
({ selectedItem }: Partial<UseSelectState<DropdownItem | DropdownLinkItem | null>>) => { | ||
if (!selectedItem) { | ||
return; | ||
} | ||
|
||
if (selectedItem.type !== 'link' && typeof selectedItem.onItemClick === 'function') { | ||
// Links don't trigger an onItemClick | ||
if (selectedItem && selectedItem.type !== 'link' && typeof selectedItem.onItemClick === 'function') { | ||
// Call onItemClick with selected item | ||
selectedItem.onItemClick(selectedItem); | ||
} | ||
}, | ||
[], | ||
); | ||
|
||
const { getItemProps, getMenuProps, getToggleButtonProps, highlightedIndex, isOpen } = useSelect< | ||
DropdownItem | DropdownLinkItem | null | ||
>({ | ||
const { getItemProps, getMenuProps, getToggleButtonProps, highlightedIndex, isOpen } = useSelect({ | ||
circularNavigation: true, | ||
defaultHighlightedIndex: 0, | ||
id: dropdownUniqueId, | ||
itemToString: (item) => (item ? item.content : ''), | ||
items: onlyItems, | ||
items: flattenedItems, | ||
menuId: id, | ||
onSelectedItemChange: handleOnSelectedItemChange, | ||
selectedItem: null, | ||
selectedItem: null, // We never set a selected item | ||
toggleButtonId: toggle.props.id, | ||
}); | ||
|
||
// Popper | ||
const referenceRef = useRef(null); | ||
const popperRef = useRef(null); | ||
|
||
const { attributes, styles, update } = usePopper(referenceRef.current, popperRef.current, { | ||
modifiers: [ | ||
{ | ||
name: 'eventListeners', | ||
options: { | ||
scroll: isOpen, | ||
resize: isOpen, | ||
}, | ||
}, | ||
{ | ||
name: 'offset', | ||
options: { | ||
offset: [0, 4], | ||
}, | ||
}, | ||
], | ||
placement, | ||
strategy: positionFixed ? 'fixed' : 'absolute', | ||
}); | ||
|
||
const renderToggle = useMemo(() => { | ||
return ( | ||
<Reference> | ||
{({ ref }) => | ||
isValidElement(toggle) && | ||
cloneElement<React.HTMLAttributes<any> & React.RefAttributes<any>>(toggle as any, { | ||
...getToggleButtonProps({ | ||
disabled, | ||
ref, | ||
}), | ||
'aria-expanded': isOpen, | ||
}) | ||
} | ||
</Reference> | ||
isValidElement(toggle) && | ||
cloneElement(toggle, { | ||
...getToggleButtonProps({ | ||
'aria-expanded': isOpen, // Because of memoization, we need to manually set this option | ||
disabled, | ||
ref: referenceRef, | ||
}), | ||
}) | ||
); | ||
}, [disabled, getToggleButtonProps, isOpen, toggle]); | ||
|
||
const renderItem = useCallback( | ||
(item: DropdownItem) => { | ||
const { actionType, content, disabled: itemDisabled, hash, onItemClick, type, ...itemProps } = item; | ||
const key = itemKey.current; | ||
const isHighlighted = highlightedIndex === key; | ||
|
||
itemKey.current += 1; | ||
|
||
return ( | ||
<ListItem | ||
{...itemProps} | ||
{...getItemProps({ | ||
disabled: itemDisabled, | ||
index: key, | ||
item, | ||
})} | ||
actionType={actionType} | ||
isAction={true} | ||
isHighlighted={isHighlighted} | ||
key={`${content}-${key}`} | ||
> | ||
{getContent(item, isHighlighted)} | ||
</ListItem> | ||
); | ||
}, | ||
[getItemProps, highlightedIndex], | ||
); | ||
|
||
const renderLinkItem = useCallback( | ||
(item: DropdownLinkItem) => { | ||
const { actionType, content, disabled: itemDisabled, url, target, type, ...itemProps } = item; | ||
const key = itemKey.current; | ||
const isHighlighted = highlightedIndex === key; | ||
|
||
itemKey.current += 1; | ||
|
||
return ( | ||
<ListItem | ||
{...itemProps} | ||
{...getItemProps({ | ||
disabled: itemDisabled, | ||
index: key, | ||
item, | ||
})} | ||
actionType={actionType} | ||
isAction={true} | ||
isHighlighted={isHighlighted} | ||
key={`${content}-${key}`} | ||
> | ||
{getContent(item, isHighlighted)} | ||
</ListItem> | ||
); | ||
}, | ||
[getItemProps, highlightedIndex], | ||
); | ||
|
||
const renderItems = useCallback( | ||
(dropdownItems: Array<DropdownItem | DropdownLinkItem>) => { | ||
return ( | ||
Array.isArray(dropdownItems) && | ||
dropdownItems.map((item) => (item.type === 'link' ? renderLinkItem(item) : renderItem(item))) | ||
); | ||
}, | ||
[renderItem, renderLinkItem], | ||
); | ||
|
||
const renderGroup = useCallback( | ||
(group: DropdownItemGroup) => { | ||
return ( | ||
<> | ||
{group.separated && <ListGroupSeparator />} | ||
{group.label && <ListGroupHeader>{group.label}</ListGroupHeader>} | ||
{renderItems(group.items)} | ||
</> | ||
); | ||
}, | ||
[renderItems], | ||
); | ||
|
||
const renderChildren = useMemo(() => { | ||
// Reset the key every time we rerender children | ||
itemKey.current = 0; | ||
|
||
if (Array.isArray(items) && items.every(isGroup)) { | ||
return (items as DropdownItemGroup[]).map((group, index) => ( | ||
<Fragment key={index}>{renderGroup(group)}</Fragment> | ||
)); | ||
} | ||
|
||
if (Array.isArray(items) && items.every(isItem)) { | ||
return renderItems(items as Array<DropdownItem | DropdownLinkItem>); | ||
} | ||
}, [items, renderGroup, renderItems]); | ||
|
||
const renderList = useMemo( | ||
() => ( | ||
<Popper | ||
modifiers={[{ name: 'eventListeners' }, { name: 'offset', options: { offset: [0, 4] } }]} | ||
strategy="absolute" | ||
placement={placement} | ||
> | ||
{({ placement: popperPlacement, ref, style: popperStyle, update }) => ( | ||
<List | ||
{...rest} | ||
{...getMenuProps({ | ||
onKeyDown: (event) => { | ||
if (event.key === 'Enter') { | ||
const element = event.currentTarget.children[highlightedIndex]; | ||
const link = element.querySelector('a'); | ||
|
||
// We want to click the link if it is selected | ||
if (link) { | ||
link.click(); | ||
} | ||
} | ||
}, | ||
ref, | ||
})} | ||
data-placement={popperPlacement} | ||
isOpen={isOpen} | ||
maxHeight={maxHeight} | ||
style={popperStyle} | ||
update={update} | ||
> | ||
{isOpen && renderChildren} | ||
</List> | ||
)} | ||
</Popper> | ||
), | ||
[getMenuProps, highlightedIndex, isOpen, maxHeight, placement, renderChildren, rest], | ||
); | ||
|
||
return ( | ||
<Manager> | ||
<StyledBox> | ||
{renderToggle} | ||
{renderList} | ||
</StyledBox> | ||
</Manager> | ||
<StyledBox> | ||
{renderToggle} | ||
<Box ref={popperRef} style={styles.popper} {...attributes.poppper} zIndex="popover"> | ||
<List | ||
{...props} | ||
autoWidth={autoWidth} | ||
getItemProps={getItemProps} | ||
getMenuProps={getMenuProps} | ||
highlightedIndex={highlightedIndex} | ||
isDropdown={true} | ||
isOpen={isOpen} | ||
items={items} | ||
maxHeight={maxHeight} | ||
update={update} | ||
/> | ||
</Box> | ||
</StyledBox> | ||
); | ||
}, | ||
); | ||
|
||
const flattenItems = ( | ||
items: Array<DropdownItem | DropdownLinkItem> | DropdownItemGroup[], | ||
): Array<DropdownItem | DropdownLinkItem> => { | ||
return items.every(isGroup) | ||
? (items as DropdownItemGroup[]) | ||
.map((group: DropdownItemGroup) => group.items) | ||
.reduce((acum, curr) => acum.concat(curr), []) | ||
: (items as DropdownItem[]); | ||
}; | ||
|
||
const isGroup = (item: DropdownItem | DropdownLinkItem | DropdownItemGroup) => { | ||
return 'items' in item && !('content' in item); | ||
}; | ||
|
||
const isItem = (item: DropdownItem | DropdownLinkItem | DropdownItemGroup) => { | ||
return 'content' in item && !('items' in item); | ||
}; | ||
|
||
const renderIcon = (item: DropdownItem | DropdownLinkItem, isHighlighted: boolean) => { | ||
return ( | ||
isValidElement(item.icon) && | ||
cloneElement(item.icon, { | ||
color: iconColor(item, isHighlighted), | ||
size: 'large', | ||
}) | ||
); | ||
}; | ||
|
||
const getContent = (item: DropdownItem | DropdownLinkItem, isHighlighted: boolean) => { | ||
const { disabled: itemDisabled, icon, tooltip } = item; | ||
|
||
const baseContent = ( | ||
<Flex alignItems="center" flexDirection="row"> | ||
{icon && <FlexItem paddingRight="xSmall">{renderIcon(item, isHighlighted)}</FlexItem>} | ||
{item.content} | ||
</Flex> | ||
); | ||
|
||
const content = item.type === 'link' && !itemDisabled ? wrapInLink(item, baseContent) : baseContent; | ||
|
||
return itemDisabled && tooltip ? wrapInTooltip(tooltip, content) : content; | ||
}; | ||
|
||
const iconColor = (item: DropdownItem | DropdownLinkItem, isHighlighted: boolean) => { | ||
if (item.disabled) { | ||
return 'secondary40'; | ||
} | ||
|
||
if (!isHighlighted) { | ||
return 'secondary60'; | ||
} | ||
|
||
return item.actionType === 'destructive' ? 'danger50' : 'primary'; | ||
}; | ||
|
||
const wrapInLink = (item: DropdownLinkItem, content: React.ReactChild) => { | ||
return ( | ||
<StyledLink href={item.url} tabIndex={-1} target={item.target}> | ||
{content} | ||
</StyledLink> | ||
); | ||
}; | ||
|
||
const wrapInTooltip = (tooltip: DropdownItem['tooltip'], tooltipTrigger: React.ReactChild) => { | ||
return ( | ||
<Tooltip | ||
placement="left" | ||
trigger={tooltipTrigger} | ||
modifiers={[{ name: 'preventOverflow' }, { name: 'offset', options: { offset: [0, 20] } }]} | ||
inline={false} | ||
> | ||
{tooltip} | ||
</Tooltip> | ||
); | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nice