UNPKG

glass-app-manager

Version:

Informatica's Glass Framework CLI for bootstrapping

111 lines (90 loc) 2.85 kB
// @flow import * as React from "react"; import SimpleDropdown from "./SimpleDropdown"; import MultiDropdown from "./MultiDropdown"; type OptionDefinition = { text: string, value: any, }; type Options = Array<OptionDefinition>; type DropdownProps = { /** * Set true to enable checkboxes. */ checkbox?: boolean, /** * Set true to enable multiple selection. */ multiple?: boolean, /** * Callback to execute when the user selects something. */ onChange: () => void, /** * Options to use. */ options: Options, /** * Custom placeholder string to show when no items are selected. */ placeholder?: string, /** * Set true to enable searching. */ search?: boolean, /** * Some value */ value?: string, }; function Dropdown(props: DropdownProps) { const { multiple, options, value } = props; const initialSelected = multiple ? options.filter(item => Array.isArray(value) && value.indexOf(item.value) !== -1) : options.filter(item => item.value === value); const initialState = multiple ? initialSelected : initialSelected[0]; const [selectedItems, setSelectedItem] = React.useState(initialState); const [inputValue, setInputValue] = React.useState(""); const [userInput, setUserInput] = React.useState(false); const [visibleOptions, setVisibleOptions] = React.useState(options); const handleChange = props.onChange ? props.onChange : () => {}; const handleOpen = props.onOpen ? props.onOpen : () => {}; const handleClose = props.onClose ? props.onClose : () => {}; const itemToString = item => (item ? item.text : ""); React.useEffect(() => { if (initialState) { multiple ? setInputValue("") : setInputValue(initialState.text); setSelectedItem(initialState); } else { setInputValue(""); multiple ? setSelectedItem([]) : setSelectedItem(""); } setVisibleOptions(options); setUserInput(false); }, [multiple, options, setInputValue]); return React.createElement(multiple ? MultiDropdown : SimpleDropdown, { initialSelectedItem: selectedItems, inputValue, itemToString, onChange: handleChange, onOpen: handleOpen, onClose: handleClose, selectedItems, setInputValue, setSelectedItem, setUserInput, setVisibleOptions, userInput, visibleOptions, ...props, }); } Dropdown.defaultProps = { options: [ { text: "No Objects Available", value: 0, }, ], }; export default Dropdown;