import React, { ElementType, ReactNode, useState, useEffect, useCallback, useRef, Fragment, LegacyRef, CSSProperties, } from 'react'; import Downshift, { ControllerStateAndHelpers, GetRootPropsOptions, GetToggleButtonPropsOptions, } from 'downshift'; import styled from '@emotion/styled'; import { css } from '@emotion/react'; import AnimatedBorder from 'components/AnimatedBorder'; import ErrorMessage from 'components/ErrorMessage'; import { tick2 as Tick } from 'components/Icon/icons'; import DropDownIcon from 'components/Icon/icons/arrows/dropdown'; import List from 'components/List'; import noop from 'utils/noop'; import { mineShaft, nobel } from 'styles/colors'; import { getThemeFont } from 'styles/fonts'; import { DROPDOWN, GROUND } from 'styles/zIndex'; import Portal from 'components/Portal'; const Wrapper = styled.div>` position: relative; display: block; ${({ theme: { rtl } }) => rtl && css` direction: rtl; `} ${({ error }) => error && `padding-bottom: 24px;`}; `; const Container = styled.div` width: 100%; `; const Button = styled.button` display: flex; align-items: flex-end; width: 100%; padding: 10px; border: none; background: transparent; color: ${mineShaft['900']}; outline: none; ${({ disabled }) => disabled && `cursor: not-allowed;`}; `; const CustomIcon = styled.span` flex: 0 0 auto; align-self: center; ${({ theme: { rtl } }) => css` margin-${rtl ? 'left' : 'right'}:0.5em; `} line-height: 1.6; `; const Content = styled.span` flex: 1 1 auto; font-family: ${getThemeFont}; line-height: 1.6; ${({ theme: { rtl } }) => css` text-align: ${rtl ? 'right' : 'left'}; `} `; const Caret = styled.span` ${({ theme: { rtl } }) => css` margin-${rtl ? 'left' : 'right'}:-5px ; `} color: ${nobel.main}; `; const StyledList = styled(List)` position: absolute; top: calc(100% + 1px); left: 0; ${({ theme: { rtl }, listZIndex = DROPDOWN }) => css` text-align: ${rtl ? 'right' : 'left'}; z-index: ${listZIndex}; `} li[disabled] { opacity: 0.5; cursor: not-allowed; } `; const StyledErrorMessage = styled(ErrorMessage)` position: absolute; z-index: ${GROUND + 1}; right: 0; left: 0; `; const CheckMarkSpan = styled.span` margin: 6px 12px 0 12px; ${({ theme: { rtl } }) => css` float: ${rtl ? 'left' : 'right'}; `} `; export type Item = { /** @deprecated */ id?: string | number; // For backward compatibiliy /** Element shown next to label */ icon?: ReactNode; /** Value of the option */ value: string; /** Label of the option for users */ label: string; /** Rest Props */ [rest: string]: any; }; interface Props { /** Id of the component */ id?: string; /** Name of the component */ name?: string; /** Label of the component */ label?: string; /** Error message of the component */ error?: string | null; /** The currently selected item */ selectedItem?: Item | null; /** Select items */ items?: Item[]; /** @deprecated Please use `items` */ itemList?: Item[]; /** For backward compatible only, append `data-required` to the select if it is `true` */ required?: boolean; /** Disable the select if it is `true` */ disabled?: boolean; /** * Callback function, to be executed when user selected an item and it has changed * * @param {any} selectedItem * @param {object} stateAndHelpers */ onChange?: ( // eslint-disable-next-line no-unused-vars selectedItem: Item | null, // eslint-disable-next-line no-unused-vars stateAndHelpers: ControllerStateAndHelpers ) => void; /** * Callback function, to be executed when user trigger to open select dropdown * * @param {SyntheticEvent} event https://reactjs.org/docs/events.html */ onFocus?: (_e?: React.ChangeEvent) => void; /** * Callback function, to be executed when user leave the select dropdown * * @param {SyntheticEvent} event https://reactjs.org/docs/events.html */ onBlur?: (_e?: React.ChangeEvent) => void; /** * absolute: render items with absolute css (default) * portal: render items in a React Portal, breaking out of the DOM tree */ renderStrategy?: 'absolute' | 'portal'; /** * Prevents list from extending out of the viewport */ preventOverflowViewport?: boolean; /** * Override the default zIndex */ listZIndex?: number; /** Rest Props */ [rest: string]: any; } // eslint-disable react/prop-types const Select = ({ id, name, label, error = null, selectedItem = null, items = [], itemList = [], required = false, disabled = false, onChange = noop, onFocus: superOnFocus = noop, onBlur: superOnBlur = noop, renderStrategy = 'absolute', preventOverflowViewport = false, listZIndex, ...rest }: Props) => { const [focused, setFocused] = useState(false); const [listStyles, setListStyles] = useState({ width: '100%', }); const buttonRef = useRef(); const listRef = useRef(); const resizeObserverRef = useRef(); const mutationObserverRef = useRef(); const cancelAnimationFrameRef = useRef(); const updateListStyles = useCallback(() => { const btn = buttonRef.current; if (renderStrategy === 'portal' && btn) { const { left, bottom, width } = btn.getBoundingClientRect(); setListStyles({ top: bottom + window.scrollY + 1, left, width, ...(preventOverflowViewport && { overflow: 'auto', maxHeight: Math.max(window.innerHeight - bottom - 44, 0), }), }); } }, [renderStrategy, preventOverflowViewport]); const queueUpdateListStyles = useCallback(() => { if (cancelAnimationFrameRef.current !== undefined) { window.cancelAnimationFrame(cancelAnimationFrameRef.current); } cancelAnimationFrameRef.current = window.requestAnimationFrame( updateListStyles ); }, [updateListStyles]); useEffect(() => { if (itemList.length) { // eslint-disable-next-line no-console console.warn( '[Select] prop `itemList` deprecated. Please check documentation for better' + ' alternative.' ); } }, []); useEffect(() => { const cleanup = () => { /* eslint-disable no-unused-expressions */ const cancel = cancelAnimationFrameRef.current; cancel && window.cancelAnimationFrame(cancel); resizeObserverRef.current?.disconnect(); mutationObserverRef.current?.disconnect(); /* eslint-enable no-unused-expressions */ window.removeEventListener('scroll', queueUpdateListStyles); }; switch (renderStrategy) { case 'portal': { if (typeof window.ResizeObserver === 'function') { resizeObserverRef.current = new ResizeObserver(queueUpdateListStyles); resizeObserverRef.current.observe(document.body); } if (typeof window.MutationObserver === 'function') { mutationObserverRef.current = new MutationObserver( queueUpdateListStyles ); mutationObserverRef.current.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['height'], }); } window.addEventListener('scroll', queueUpdateListStyles, true); break; } case 'absolute': { setListStyles({ width: '100%' }); cleanup(); break; } default: } return cleanup; }, [renderStrategy, queueUpdateListStyles]); const onFocus = useCallback( (e?: React.ChangeEvent) => { setFocused(true); superOnFocus(e); }, [setFocused, superOnFocus] ); const onBlur = useCallback( (e?: React.ChangeEvent) => { setFocused(false); superOnBlur(e); }, [setFocused, superOnBlur] ); const ListWrapper = renderStrategy === 'portal' ? Portal : Fragment; return ( (item ? item.value : '')} > {({ isOpen, getMenuProps, getInputProps, getToggleButtonProps, getItemProps, getRootProps, closeMenu, }) => { const onKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Escape') { (e.nativeEvent as any).preventDownshiftDefault = true; closeMenu(); } }; return ( {isOpen && ( , })} style={listStyles} hoverable size="small" items={items.length ? items : itemList} render={({ data, Item: ItemComponent, getProps, }: { data: Item; Item: ElementType; getProps: () => any; }) => ( ), })} > {data.icon} {data.label || data.value} )} listZIndex={listZIndex} /> )} ); }} ); }; export default Select; export type SelectProps = Props;