Skip to content

Commit

Permalink
Change selectbox into a controlled component
Browse files Browse the repository at this point in the history
  • Loading branch information
harishmohanraj committed Aug 19, 2024
1 parent d4c8aa9 commit 4e74747
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions app/src/client/components/buildPage/ModelSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import Select, { StylesConfig, SingleValue } from 'react-select';
import { PropertySchemaParser, SetUpdateFormStack } from './PropertySchemaParser';
import { SelectOption } from './PropertySchemaParser';
Expand All @@ -10,8 +11,28 @@ export const ModelSelector = ({
parser: PropertySchemaParser | null;
updateFormStack: SetUpdateFormStack;
}) => {
const selectOptions = parser?.getModelNames();
const selectOptions = useMemo(() => parser?.getModelNames() || [], [parser]);
const propertyName = parser?.getPropertyName();
const activeModel = parser?.getActiveModel();

const [selectedOption, setSelectedOption] = useState<SelectOption | null>(() => {
if (activeModel) {
return selectOptions.find((opt) => opt.value === activeModel) || null;
}
return selectOptions.length > 0 ? selectOptions[0] : null;
});

useEffect(() => {
if (activeModel) {
const option = selectOptions.find((opt) => opt.value === activeModel);
if (option && option.value !== selectedOption?.value) {
setSelectedOption(option);
}
} else if (selectOptions.length > 0 && !selectedOption) {
setSelectedOption(selectOptions[0]);
}
}, [activeModel, selectOptions]);

const propertyHeader = propertyName ? capitalizeFirstLetter(propertyName) : propertyName;
const customStyles: StylesConfig<SelectOption, false> = {
control: (baseStyles) => ({
Expand All @@ -20,13 +41,13 @@ export const ModelSelector = ({
}),
};

const handleChange = (selectedOption: SingleValue<SelectOption>) => {
if (selectedOption) {
updateFormStack(selectedOption.value);
const handleChange = (newValue: SingleValue<SelectOption>) => {
if (newValue) {
setSelectedOption(newValue);
updateFormStack(newValue.value);
}
};

const activeModel = parser?.getActiveModel();
const header = propertyHeader === 'Llm' ? 'Select LLM' : `Select ${propertyHeader}`;

return (
Expand All @@ -41,7 +62,7 @@ export const ModelSelector = ({
options={selectOptions}
onChange={handleChange}
className='pt-1 pb-1'
defaultValue={activeModel ? { value: activeModel, label: activeModel } : selectOptions[0]}
value={selectedOption}
isSearchable={true}
isClearable={false}
styles={customStyles}
Expand Down

0 comments on commit 4e74747

Please sign in to comment.