@grafana/ui
Version:
Grafana Components Library
95 lines (92 loc) • 2.79 kB
JavaScript
import { jsx } from 'react/jsx-runtime';
import { cx } from '@emotion/css';
import { isObject } from 'lodash';
import { useAsyncFn } from 'react-use';
import { t } from '@grafana/i18n';
import { useStyles2 } from '../../themes/ThemeContext.mjs';
import { InlineLabel } from '../Forms/InlineLabel.mjs';
import { SegmentSelect } from './SegmentSelect.mjs';
import { getSegmentStyles } from './styles.mjs';
import { useExpandableLabel } from './useExpandableLabel.mjs';
;
function SegmentAsync({
value,
onChange,
loadOptions,
reloadOptionsOnChange = false,
Component,
className,
allowCustomValue,
allowEmptyValue,
disabled,
placeholder,
inputMinWidth,
inputPlaceholder,
autofocus = false,
onExpandedChange,
noOptionMessageHandler = mapStateToNoOptionsMessage,
...rest
}) {
var _a;
const [state, fetchOptions] = useAsyncFn(loadOptions, [loadOptions]);
const [Label, labelWidth, expanded, setExpanded] = useExpandableLabel(autofocus, onExpandedChange);
const width = inputMinWidth ? Math.max(inputMinWidth, labelWidth) : labelWidth;
const styles = useStyles2(getSegmentStyles);
if (!expanded) {
const label = isObject(value) ? value.label : value;
const labelAsString = label != null ? String(label) : void 0;
return /* @__PURE__ */ jsx(
Label,
{
onClick: reloadOptionsOnChange ? void 0 : fetchOptions,
disabled,
Component: Component || /* @__PURE__ */ jsx(
InlineLabel,
{
className: cx(
styles.segment,
{
[styles.queryPlaceholder]: placeholder !== void 0 && !value,
[styles.disabled]: disabled
},
className
),
children: labelAsString || placeholder
}
)
}
);
}
return /* @__PURE__ */ jsx(
SegmentSelect,
{
...rest,
value: value && !isObject(value) ? { value } : value,
placeholder: inputPlaceholder,
options: (_a = state.value) != null ? _a : [],
loadOptions: reloadOptionsOnChange ? fetchOptions : void 0,
width,
noOptionsMessage: noOptionMessageHandler(state),
allowCustomValue,
allowEmptyValue,
onClickOutside: () => {
setExpanded(false);
},
onChange: (item) => {
setExpanded(false);
onChange(item);
}
}
);
}
function mapStateToNoOptionsMessage(state) {
if (state.loading) {
return t("grafana-ui.segment-async.loading", "Loading options...");
}
if (state.error) {
return t("grafana-ui.segment-async.error", "Failed to load options");
}
return t("grafana-ui.segment-async.no-options", "No options found");
}
export { SegmentAsync };
//# sourceMappingURL=SegmentAsync.mjs.map