|
- import { Autocomplete, TextField } from '@mui/material';
- import { useEffect, useState } from 'react';
-
- export default function Combo({
- valueName,
- disabled,
- form,
- dataList = [],
- filterOptions,
- getOptionLabel,
- isOptionEqualToValue,
- onInputChange,
- onChange,
- ...props
- }) {
- const formValue = form.values[valueName] ?? null;
-
- const [inputValue, setInputValue] = useState("");
-
- // optional: keep input text in sync when form value changes (e.g. after reload/reset)
- useEffect(() => {
- if (!formValue) return;
- try {
- const label = getOptionLabel ? getOptionLabel(formValue) : "";
- if (typeof label === "string") setInputValue(label);
- } catch {
- // ignore label errors
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [formValue]);
-
- const defaultIsEqual = (option, value) => option?.id != null && value?.id != null
- ? option.id === value.id
- : option === value;
-
- return (
- <Autocomplete
- {...props}
- disablePortal
- fullWidth
- id={valueName}
- disabled={disabled}
- // consider removing disableClearable if you allow empty
- disableClearable
- options={Array.isArray(dataList) ? dataList : []}
- value={formValue}
- inputValue={inputValue}
- filterOptions={filterOptions}
- getOptionLabel={(opt) => {
- if (!opt) return "";
- const v = getOptionLabel ? getOptionLabel(opt) : String(opt);
- return typeof v === "string" ? v : "";
- }}
- isOptionEqualToValue={(option, value) => {
- return isOptionEqualToValue
- ? isOptionEqualToValue(option, value)
- : defaultIsEqual(option, value);
- }}
- onInputChange={(event, newValue) => {
- if (onInputChange) onInputChange(event, newValue, setInputValue);
- else setInputValue(newValue);
- }}
- onChange={(event, newValue) => {
- if (onChange) onChange(event, newValue);
- else form.setFieldValue(valueName, newValue);
- }}
- sx={{
- '& .MuiInputBase-root': { alignItems: 'center' },
- '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
- '& .MuiOutlinedInput-root': { height: 40 },
- "& .MuiInputBase-input.Mui-disabled": {
- WebkitTextFillColor: "#000000",
- background: "#f8f8f8",
- },
- }}
- renderInput={(params) => (
- <TextField
- {...params}
- sx={{
- "& .MuiInputBase-input.Mui-disabled": {
- WebkitTextFillColor: "#000000",
- background: "#f8f8f8",
- },
- }}
- />
- )}
- />
- );
- }
|