Skip to content

Commit

Permalink
Prevent form submission when pressing enter in typeahead input, and r…
Browse files Browse the repository at this point in the history
…emove 3-character limit for showing options (#1266)
  • Loading branch information
dmfalke authored Nov 9, 2024
1 parent a3e4b4d commit cd82232
Showing 1 changed file with 8 additions and 39 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import React, { useMemo, useState, useCallback } from 'react';
import React, { useMemo, useCallback } from 'react';
import Select from 'react-select';
import { TypeAheadEnumParam } from '../../../Utils/WdkModel';
import { Props } from '../../../Views/Question/Params/Utils';
import { ValueType, InputActionMeta } from 'react-select/src/types';
import { ValueType } from 'react-select/src/types';
import { isMultiPick } from '../../../Views/Question/Params/EnumParamUtils';
import { safeHtml } from '../../../Utils/ComponentUtils';

Expand Down Expand Up @@ -33,24 +32,13 @@ export const TypeAheadEnumParamComponent = (props: TypeAheadParamProps) => {
[props.parameter.vocabulary]
);

const [searchTerm, setSearchTerm] = useState('');

const selection = useMemo(() => {
return props.selectedValues.map((value) => ({
value,
label: vocabularyByValue[value][1],
}));
}, [props.selectedValues, isMultiPick(props.parameter)]);

const onInputChange = useCallback(
(inputValue: string, { action }: InputActionMeta) => {
if (action === 'input-change') {
setSearchTerm(inputValue);
}
},
[]
);

const onChange = useCallback(
(newSelection: ValueType<Option, any>) => {
const newSelectionArray =
Expand All @@ -61,44 +49,25 @@ export const TypeAheadEnumParamComponent = (props: TypeAheadParamProps) => {
: [newSelection as Option];

props.onChange(newSelectionArray.map(({ value }) => value));
setSearchTerm('');
},
[props.onChange]
);

const filterOption = useCallback(
(option: Option, inputValue: string) =>
(inputValue.length >= 3 || option.label.length < 3) &&
option.label.toLowerCase().includes(inputValue.toLowerCase()),
[]
);

const noOptionsMessage = useCallback(
({ inputValue }: { inputValue: string }) =>
inputValue.length === 0
? 'Please input at least 3 characters'
: inputValue.length === 1
? 'Please input at least 2 more characters'
: inputValue.length === 2
? 'Please input at least 1 more character'
: 'No matches found',
[]
);

return (
<Select<Option, any>
isMulti={isMultiPick(props.parameter)}
isSearchable
options={options}
filterOption={filterOption}
noOptionsMessage={noOptionsMessage}
value={selection}
onChange={onChange}
inputValue={searchTerm}
onInputChange={onInputChange}
formatOptionLabel={(option) => safeHtml(option.label)}
formatOptionLabel={formatOptionLabel}
form="DO_NOT_SUBMIT_ON_ENTER"
/>
);
};

export default TypeAheadEnumParamComponent;

function formatOptionLabel(option: Option) {
return safeHtml(option.label);
}

0 comments on commit cd82232

Please sign in to comment.