/* eslint-disable react/sort-comp */ import React, { Component } from 'react'; import styled from '@emotion/styled'; import { css, withTheme } from '@emotion/react'; import { ControllerStateAndHelpers } from 'downshift'; import noop from 'utils/noop'; import DropdownButton from './components/DropdownButton'; import DropdownList from './components/DropdownList'; import ExpandButton from './components/ExpandButton'; import MultiDownshift from './components/MutliDownshift'; import { Item } from './types'; const validIndex = /(\d+)_(-?\d+)/; let setHighlightedIndex; let toggleMenu; let closeMenu; let selectHighlightedItem; const Container = styled.div<{ block: boolean }>` position: relative; display: inline-block; ${({ theme: { rtl } }) => rtl && css` direction: rtl; `} ${({ block }) => block && css` display: block; `}; `; interface Props { /** Fit the width to its parent width when it is `true`. */ block: boolean; /** Pop menu items */ items: Item[]; /** The currently selected item */ selectedItems: Item[] | null; /** Callback function, to be executed when user selected an item and it has changed */ onChange: (_selectedItem: Item, _selectedItems: Item[]) => void; /** Callback function, to be executed when user selected an item, return clicked item and current selected items */ onSelect: (_selectedItem: Item, _selectedItems: Item[]) => void; /** Callback function, to be executed when user clicked outside of pop menu, return clicked item and current selected items */ onOuterClick: (_: ControllerStateAndHelpers) => void; /** Callback function, to be executed when user toggled the pop menu */ onToggle: (_isOpen: boolean) => void; /** Label of the component, will be shown before user selected option */ defaultLabel: string; /** Label of the component */ customLabel: string; /** Open direction of pop menu */ direction: 'left' | 'right' | 'auto'; /** Variant of component, `default` is the component with standard select button; * `compact` is the component with icon-only button */ variant: 'default' | 'compact'; /** Custom icon for the Dropdown button, if not supplied default icon will be used: * (`v`) icon on `default` variant and (**⋮**) icon on `compact` variant */ // eslint-disable-next-line no-undef icon: JSX.Element; /** A boolean which, if true, disables the Dropdown */ disabled: boolean; /** A boolean which, if ture, show Reset Button */ showResetButton: boolean; /** A string which, will be shown in Reset Button if showResetButton is true */ resetButtonLabel: string; /** injected by with theme, used to handle key down for auto direction and rtl */ theme: { rtl: boolean; }; } interface State { depthLevel: number; highlightedIndexes: string[]; listCounts: number[]; selectedItems: Item[]; } /* eslint-disable react/destructuring-assignment */ class MultiDropdown extends Component { static defaultProps = { block: false, selectedItems: null, onChange: noop, onOuterClick: noop, onToggle: noop, onSelect: noop, defaultLabel: undefined, customLabel: undefined, direction: 'auto' as const, variant: 'default' as const, icon: undefined, disabled: false, showResetButton: false, resetButtonLabel: 'Reset', theme: { rtl: false, }, }; static getDerivedStateFromProps(props, state) { // if prop selectedItems is not passed, the component is uncontrolled and state selectedItems handled by MultiDropdown const uncontrolled = !props.selectedItems; const isPropStateItemsMatch = props.selectedItems && props.selectedItems.reduce( (prevBool, curr) => prevBool && state.selectedItems.some(item => item.label === curr.label), true ); if (uncontrolled || isPropStateItemsMatch) return null; return { selectedItems: props.selectedItems || [], }; } state = { depthLevel: 0, highlightedIndexes: [], listCounts: [this.props.items.length], selectedItems: this.props.selectedItems || [], } as State; componentDidUpdate(prevProps: Props) { if (this.props.selectedItems !== prevProps.selectedItems) { // eslint-disable-next-line react/no-did-update-set-state this.setState({ selectedItems: this.props.selectedItems || [] }); } } // sync highlighted indexes in state and Downshift setHighlightedIndexes = (index: string, depthLevel: number) => { setHighlightedIndex(index); // method in Downshift this.handleHighlightedIndexes(index, depthLevel); }; handleDepthLevel = (level: number) => { const { depthLevel } = this.state; if (depthLevel === level) return; this.setState({ depthLevel: level }); }; handleHighlightedIndexes = (index: string, depthLevel: number) => { const { highlightedIndexes } = this.state; const expectedCount = depthLevel + 1; if ( highlightedIndexes[depthLevel] === index && highlightedIndexes.length === expectedCount ) return; const updatedArray = [...highlightedIndexes].slice(0, expectedCount); updatedArray[depthLevel] = index; this.setState({ highlightedIndexes: updatedArray }); }; handleListCounts = (count, depthLevel) => { const { listCounts } = this.state; const expectedCount = depthLevel + 1; if (listCounts[depthLevel] === count && listCounts.length === expectedCount) return; const updatedArray = [...listCounts].slice(0, expectedCount); updatedArray[depthLevel] = count; this.setState({ listCounts: updatedArray }); }; // override method defined in Downshift to support sub-options moveHighlightedIndex = (moveAmount = 1) => { const { highlightedIndexes, depthLevel, listCounts } = this.state; // get highlightedIndex in state const baseId = highlightedIndexes[depthLevel] || '0_-1'; // get current list count const count = listCounts[depthLevel]; const lastIndex = count - 1; // new index const subIndex = validIndex.exec(baseId)?.[2] ?? '0'; let updatedSubIndex = parseInt(subIndex, 10) + moveAmount; if (updatedSubIndex < 0) { updatedSubIndex = lastIndex; } else if (updatedSubIndex > lastIndex) { updatedSubIndex = 0; } // set updated highlightedIndexes const updatedIndex = `${depthLevel}_${updatedSubIndex}`; this.setHighlightedIndexes(updatedIndex, depthLevel); }; triggerSubOptions = (open = true) => { const { highlightedIndexes, depthLevel, listCounts } = this.state; const updatedDepthLevel = open ? depthLevel + 1 : depthLevel - 1; if (updatedDepthLevel < 0) return; // get highlightedIndex in state const baseId = highlightedIndexes[depthLevel]; if (baseId === null) return; // prevent update if listCounts length === updatedDepthLevel if (listCounts.length === updatedDepthLevel) return; // new index const updatedIndex = open ? `${updatedDepthLevel}_0` : highlightedIndexes[updatedDepthLevel]; // set updated highlightedIndexes and updated depthLevel this.handleDepthLevel(updatedDepthLevel); this.setHighlightedIndexes(updatedIndex, updatedDepthLevel); }; selectHighlightedItem = () => { const { depthLevel, listCounts } = this.state; const subOptionsAvailable = listCounts.length - 1 > depthLevel; if (!subOptionsAvailable) { selectHighlightedItem(); } }; handleKeyDown = (e, isOpen = false) => { const moveAmount = e.shiftKey ? 5 : 1; let arrowRightToOpenSubOptions = true; const { theme: { rtl }, } = this.props; switch (this.props.direction) { case 'right': arrowRightToOpenSubOptions = true; break; case 'left': arrowRightToOpenSubOptions = false; break; default: arrowRightToOpenSubOptions = !rtl; } switch (e.key) { case 'ArrowDown': // eslint-disable-next-line no-param-reassign e.nativeEvent.preventDownshiftDefault = true; this.moveHighlightedIndex(moveAmount); break; case 'ArrowUp': // eslint-disable-next-line no-param-reassign e.nativeEvent.preventDownshiftDefault = true; this.moveHighlightedIndex(-moveAmount); break; case 'ArrowRight': this.triggerSubOptions(arrowRightToOpenSubOptions); break; case 'ArrowLeft': this.triggerSubOptions(!arrowRightToOpenSubOptions); break; case 'Escape': e.nativeEvent.preventDownshiftDefault = true; closeMenu(); break; case ' ': if (!isOpen) { toggleMenu(); } else { // do not select if item is disabled: const { depthLevel, highlightedIndexes } = this.state; const getItemIndex = depth => highlightedIndexes[depth].split('_')[1]; let depth = 0; let item = this.props.items[getItemIndex(depth)]; while (depth < depthLevel) { depth += 1; item = item.options[getItemIndex(depth)]; } if (!item.disabled) this.selectHighlightedItem(); // TODO: maybe skip disabled items when navigating with arrow keys } break; default: break; } }; handleChange = (selectedItem, selectedItems) => { this.setState({ highlightedIndexes: [] }); this.props.onChange(selectedItem, selectedItems); }; handleOuterClick = stateAndHelpers => { this.setState({ highlightedIndexes: [] }); this.props.onOuterClick(stateAndHelpers); }; handleSelect = (selectedItem, selectedItems) => { this.props.onSelect(selectedItem, selectedItems); }; handleRemoveItem = item => { this.setState(({ selectedItems }) => { const newSelectedItems = selectedItems.filter( i => i.label !== item.label ); this.handleSelect(item, newSelectedItems); this.handleChange(item, newSelectedItems); return { selectedItems: newSelectedItems, }; }); }; handleAddSelectedItem = item => { this.setState(({ selectedItems }) => { const newSelectedItems = [...selectedItems, item]; this.handleSelect(item, newSelectedItems); this.handleChange(item, newSelectedItems); return { selectedItems: newSelectedItems, }; }); }; handleReset = () => { this.handleChange({}, []); this.setState({ selectedItems: [] }); }; getLabel = selectedItems => { const { customLabel, defaultLabel } = this.props; if (defaultLabel && selectedItems.length === 0) { return `${defaultLabel}`; } if (customLabel) { return customLabel; } return `${ selectedItems.length === 0 ? 'All' : `${selectedItems.length} selected` }`; }; render() { const { block, items, defaultLabel, customLabel, onChange, onOuterClick, direction, variant, icon, disabled, onToggle, showResetButton, resetButtonLabel, ...remainProps } = this.props; const { selectedItems } = this.state; const { highlightedIndexes } = this.state; return ( {({ getInputProps, getItemProps, getToggleButtonProps, getRootProps, isOpen, highlightedIndex, resetSelectedItems, selectHighlightedItem: dsSelectHighlightedItem, setHighlightedIndex: dsSetHighlightedIndex, toggleMenu: dsToggleMenu, closeMenu: dsCloseMenu, }) => { selectHighlightedItem = dsSelectHighlightedItem; setHighlightedIndex = dsSetHighlightedIndex; toggleMenu = dsToggleMenu; closeMenu = dsCloseMenu; return ( {variant === 'compact' && ( this.handleKeyDown(e), }) as any)} /> )} {variant !== 'compact' && ( this.handleKeyDown(e, isOpen), }) as any)} /> )} {isOpen && ( )} ); }} ); } } export default withTheme(MultiDropdown);