@etsoo/materialui
Version:
TypeScript Material-UI Implementation
68 lines (67 loc) • 3.04 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import React from "react";
import { InputField } from "./InputField";
import { DataTypes } from "@etsoo/shared";
import { useAppContext } from "./app/ReactApp";
import Autocomplete from "@mui/material/Autocomplete";
export function ComboBoxPro(props) {
// Global app
const app = useAppContext();
// Labels
const { noOptions, loading: loadingLabel, open: openDefault } = app?.getLabels("noOptions", "loading", "open") ?? {};
// Destruct
const { noOptionsText = noOptions, loadingText = loadingLabel, openText = openDefault, options, openOnFocus = true, label, inputProps, name, value, idValue, onChange, onValueChange, ...rest } = props;
const [open, setOpen] = React.useState(false);
const [localOptions, setOptions] = React.useState([]);
const [localValue, setValue] = React.useState(null);
const [loading, setLoading] = React.useState(false);
React.useEffect(() => {
if (value === undefined)
return;
setValue(value);
}, [value]);
React.useEffect(() => {
if (idValue == null)
return;
const option = localOptions.find((option) => option.id === idValue);
if (option) {
setValue(option);
if (onValueChange)
onValueChange(option);
}
else
setValue(null);
}, [localOptions, idValue]);
React.useEffect(() => {
if (typeof options === "function") {
setLoading(true);
options().then((result) => {
setLoading(false);
if (result != null)
setOptions(result);
});
}
else {
setOptions(options);
}
}, [options]);
return (_jsx(Autocomplete, { id: name, value: localValue == null ? "" : localValue, open: open, freeSolo: true, clearOnBlur: false, onOpen: () => {
setOpen(true);
}, onClose: () => {
setOpen(false);
}, options: localOptions, loading: loading, openOnFocus: openOnFocus, renderInput: (params) => (_jsx(InputField, { ...inputProps, ...params, label: label, name: name, onBlur: (event) => {
if (onChange) {
const value = event.target.value;
if (!localValue && localValue != value)
onChange(event, value, "blur", undefined);
}
} })), getOptionLabel: (item) => typeof item === "object" ? DataTypes.getListItemLabel(item) : item, isOptionEqualToValue: (option, value) => option.id === value.id, noOptionsText: noOptionsText, loadingText: loadingText, openText: openText, onChange: (event, value, reason, details) => {
setValue(value);
if (onChange)
onChange(event, value, reason, details);
if (onValueChange) {
if (typeof value === "object")
onValueChange(value == null ? null : value);
}
}, ...rest }));
}