2019-10-09 02:54:00 +08:00
|
|
|
import React, { useState } from 'react';
|
|
|
|
import { cx } from 'emotion';
|
|
|
|
import { SegmentSelect } from './SegmentSelect';
|
|
|
|
import { SelectableValue } from '@grafana/data';
|
|
|
|
import { useExpandableLabel, SegmentProps } from '.';
|
|
|
|
|
|
|
|
export interface SegmentAsyncProps<T> extends SegmentProps<T> {
|
|
|
|
loadOptions: (query?: string) => Promise<Array<SelectableValue<T>>>;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function SegmentAsync<T>({
|
|
|
|
value,
|
|
|
|
onChange,
|
|
|
|
loadOptions,
|
|
|
|
Component,
|
|
|
|
className,
|
2019-10-15 21:08:56 +08:00
|
|
|
allowCustomValue,
|
2019-10-09 02:54:00 +08:00
|
|
|
}: React.PropsWithChildren<SegmentAsyncProps<T>>) {
|
|
|
|
const [selectPlaceholder, setSelectPlaceholder] = useState<string>('');
|
|
|
|
const [loadedOptions, setLoadedOptions] = useState<Array<SelectableValue<T>>>([]);
|
|
|
|
const [Label, width, expanded, setExpanded] = useExpandableLabel(false);
|
|
|
|
|
|
|
|
if (!expanded) {
|
|
|
|
return (
|
|
|
|
<Label
|
|
|
|
onClick={async () => {
|
|
|
|
setSelectPlaceholder('Loading options...');
|
|
|
|
const opts = await loadOptions();
|
|
|
|
setLoadedOptions(opts);
|
|
|
|
setSelectPlaceholder(opts.length ? '' : 'No options found');
|
|
|
|
}}
|
2019-12-04 20:55:23 +08:00
|
|
|
Component={Component || <a className={cx('gf-form-label', 'query-part', className)}>{value && value.label}</a>}
|
2019-10-09 02:54:00 +08:00
|
|
|
/>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<SegmentSelect
|
2019-12-04 20:55:23 +08:00
|
|
|
value={value}
|
2019-10-09 02:54:00 +08:00
|
|
|
options={loadedOptions}
|
2019-12-04 20:55:23 +08:00
|
|
|
width={width}
|
2019-10-09 02:54:00 +08:00
|
|
|
noOptionsMessage={selectPlaceholder}
|
2019-10-15 21:08:56 +08:00
|
|
|
allowCustomValue={allowCustomValue}
|
2019-10-09 02:54:00 +08:00
|
|
|
onClickOutside={() => {
|
|
|
|
setSelectPlaceholder('');
|
|
|
|
setLoadedOptions([]);
|
|
|
|
setExpanded(false);
|
|
|
|
}}
|
2019-12-04 20:55:23 +08:00
|
|
|
onChange={item => {
|
2019-10-09 02:54:00 +08:00
|
|
|
setSelectPlaceholder('');
|
|
|
|
setLoadedOptions([]);
|
|
|
|
setExpanded(false);
|
2019-12-04 20:55:23 +08:00
|
|
|
onChange(item);
|
2019-10-09 02:54:00 +08:00
|
|
|
}}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
}
|