Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ export {useSnackbarMessage} from './mui/SnackbarNotification/Context'
export {default as MuiInfiniteTable} from './mui/infinite-table'
export {default as MuiEditableTable} from './mui/editable-table/mui-table-editable'
export {default as MuiTable} from './mui/table/mui-table'
export {default as MuiCustomTablePagination} from './mui/table/CustomTablePagination'
export {default as MuiBulkEditTable} from './mui/BulkEditTable'
export {default as MuiSponsorOrderGrid} from './mui/SponsorOrderGrid'
export {TotalRow as MuiTotalRow, NotesRow as MuiNotesRow, FeeRow as MuiFeeRow, PaymentRow as MuiPaymentRow, RefundRow as MuiRefundRow, DiscountRow as MuiDiscountRow} from './mui/table/extra-rows'
export {default as MuiFormikAsyncSelect} from './mui/formik-inputs/mui-formik-async-select'
Expand Down
180 changes: 180 additions & 0 deletions src/components/mui/AsyncSelectInput.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* */

import React, { useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import T from "i18n-react/dist/i18n-react";
import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import CircularProgress from "@mui/material/CircularProgress";
import { ASYNC_SELECT_SAFETY_TIMEOUT, DEBOUNCE_WAIT_250 } from "../../utils/constants";

const defaultFormatOption = (item) => ({
value: item.id,
label: item.name
});

const optionShape = PropTypes.shape({
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
label: PropTypes.string,
raw: PropTypes.object
});

const AsyncSelectInput = ({
id,
value,
label,
placeholder,
disabled,
multiple,
queryFunction,
formatOption,
debounceWait,
minSearchLength,
onChange,
...rest
}) => {
const [options, setOptions] = useState([]);
const [loading, setLoading] = useState(false);
const debounceRef = useRef(null);
const mountedRef = useRef(false);
const requestIdRef = useRef(0);
// Backstops a queryFunction whose callback never fires (e.g. a non-404
// HTTP error swallowed upstream) so the spinner doesn't spin forever.
const safetyTimeoutRef = useRef(null);

// Filter.jsx passes `options` generically to every ValueInput type (meant
// for the sync `select` type); this type fetches its own, so it's stripped
// out here rather than spread onto the Autocomplete below.
const { options: _staleOptions, ...autocompleteProps } = rest;

Comment thread
santipalenque marked this conversation as resolved.
const fetchOptions = (searchTerm) => {
if (minSearchLength > 0 && (!searchTerm || searchTerm.length < minSearchLength)) {
setOptions([]);
return;
}
// Capture the ID for this request so the callback can discard stale ones.
requestIdRef.current += 1;
const thisRequestId = requestIdRef.current;
setLoading(true);

if (safetyTimeoutRef.current) clearTimeout(safetyTimeoutRef.current);
safetyTimeoutRef.current = setTimeout(() => {
if (mountedRef.current && thisRequestId === requestIdRef.current) {
setLoading(false);
}
}, ASYNC_SELECT_SAFETY_TIMEOUT);

queryFunction(searchTerm, (rawResults) => {
Comment thread
santipalenque marked this conversation as resolved.
if (!mountedRef.current || thisRequestId !== requestIdRef.current) return;
clearTimeout(safetyTimeoutRef.current);
// queryFunction implementations may invoke the callback with something
// other than an array (e.g. an Error on auth failure), so guard here
// rather than assume the shape.
const items = Array.isArray(rawResults) ? rawResults : [];
setOptions(items.map((item) => ({ ...formatOption(item), raw: item })));
setLoading(false);
});
};

useEffect(() => {
Comment thread
santipalenque marked this conversation as resolved.
mountedRef.current = true;
fetchOptions("");
return () => {
mountedRef.current = false;
if (debounceRef.current) clearTimeout(debounceRef.current);
if (safetyTimeoutRef.current) clearTimeout(safetyTimeoutRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Comment thread
santipalenque marked this conversation as resolved.

const handleInputChange = (event, newInputValue, reason) => {
if (reason !== "input") return;
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => fetchOptions(newInputValue), debounceWait);
};

const handleChange = (event, selected) => {
onChange({ target: { value: multiple ? selected || [] : selected || null } });
};

// Filter.jsx's single-value default is "" (not null); treat it as empty.
const normalizedValue = multiple ? value || [] : value || null;
const finalPlaceholder =
placeholder || T.translate("placeholders.async");

return (
<Autocomplete
id={id}
options={options}
value={normalizedValue}
onChange={handleChange}
onInputChange={handleInputChange}
loading={loading}
multiple={multiple}
disabled={disabled}
fullWidth
size="small"
getOptionLabel={(option) => option?.label || ""}
isOptionEqualToValue={(option, val) => option.value === val.value}
renderInput={(params) => (
<TextField
// eslint-disable-next-line react/jsx-props-no-spreading
{...params}
label={label}
placeholder={finalPlaceholder}
slotProps={{
input: {
...params.InputProps,
endAdornment: (
<>
{loading && <CircularProgress color="inherit" size={16} />}
{params.InputProps?.endAdornment}
</>
)
}
}}
/>
)}
// eslint-disable-next-line react/jsx-props-no-spreading
{...autocompleteProps}
/>
);
};

AsyncSelectInput.propTypes = {
id: PropTypes.string.isRequired,
value: PropTypes.oneOfType([optionShape, PropTypes.arrayOf(optionShape), PropTypes.string]),
label: PropTypes.string,
placeholder: PropTypes.string,
disabled: PropTypes.bool,
multiple: PropTypes.bool,
queryFunction: PropTypes.func.isRequired,
formatOption: PropTypes.func,
debounceWait: PropTypes.number,
minSearchLength: PropTypes.number,
onChange: PropTypes.func.isRequired
};

AsyncSelectInput.defaultProps = {
value: null,
label: "",
placeholder: "",
disabled: false,
multiple: false,
formatOption: defaultFormatOption,
debounceWait: DEBOUNCE_WAIT_250,
minSearchLength: 0
};

export default AsyncSelectInput;
Loading
Loading