// Copyright 2017-2020 @polkadot/react-components authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { BareProps } from './types';
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import SUIButton from 'semantic-ui-react/dist/commonjs/elements/Button/Button';
import SUIDropdown, { DropdownProps } from 'semantic-ui-react/dist/commonjs/modules/Dropdown/Dropdown';
import { isUndefined } from '@polkadot/util';
import { classes } from './util';
import Labelled from './Labelled';
interface Props extends BareProps {
allowAdd?: boolean;
defaultValue?: any;
dropdownClassName?: string;
help?: React.ReactNode;
isButton?: boolean;
isDisabled?: boolean;
isError?: boolean;
isMultiple?: boolean;
label?: React.ReactNode;
labelExtra?: React.ReactNode;
onAdd?: (value: any) => void;
onBlur?: () => void;
onChange?: (value: any) => void;
onClose?: () => void;
onSearch?: (filteredOptions: any[], query: string) => Option[];
options: Option[];
placeholder?: string;
renderLabel?: (item: any) => any;
searchInput?: { autoFocus: boolean };
transform?: (value: any) => any;
value?: any;
withEllipsis?: boolean;
withLabel?: boolean;
}
function Dropdown ({ allowAdd = false, className, defaultValue, dropdownClassName, help, isButton, isDisabled, isError, isMultiple, label, labelExtra, onAdd, onBlur, onChange, onClose, onSearch, options, placeholder, renderLabel, searchInput, style, transform, withEllipsis, withLabel, value }: Props ): React.ReactElement> {
const lastUpdate = useRef('');
const [stored, setStored] = useState();
const _setStored = (value: any): void => {
const json = JSON.stringify({ v: value });
if (lastUpdate.current !== json) {
lastUpdate.current = json;
setStored(value);
onChange && onChange(
transform
? transform(value)
: value
);
}
};
useEffect((): void => {
_setStored(isUndefined(value) ? defaultValue : value);
}, [defaultValue, value]);
const _onAdd = (_: React.SyntheticEvent, { value }: DropdownProps): void =>
onAdd && onAdd(value);
const _onChange = (_: React.SyntheticEvent | null, { value }: DropdownProps): void =>
_setStored(value);
const dropdown = (
);
return isButton
? (
{dropdown}
)
: (
{dropdown}
);
}
export default styled(Dropdown)`
.ui--Dropdown-item {
position: relative;
white-space: nowrap;
.ui--Dropdown-icon,
.ui--Dropdown-name {
display: inline-block;
}
.ui--Dropdown-icon {
height: 32px;
left: 0;
position: absolute;
top: -9px;
width: 32px;
}
.ui--Dropdown-name {
margin-left: 3rem;
}
}
.ui.selection.dropdown {
> .text > .ui--Dropdown-item {
.ui--Dropdown-icon {
left: -2.6rem;
top: -1.15rem;
opacity: 1;
}
.ui--Dropdown-name {
margin-left: 0;
}
}
}
`;