demarches-normaliennes/app/javascript/components/ComboDepartementsSearch.tsx

43 lines
1 KiB
TypeScript
Raw Normal View History

import React from 'react';
2021-02-16 13:17:36 +01:00
import { matchSorter } from 'match-sorter';
2020-10-07 17:42:21 +02:00
import ComboSearch, { ComboSearchProps } from './ComboSearch';
2020-10-07 17:42:21 +02:00
type DepartementResult = { code: string; nom: string };
2020-10-07 17:42:21 +02:00
const extraTerms = [{ code: '99', nom: 'Etranger' }];
function expandResultsWithForeignDepartement(term: string, result: unknown) {
const results = result as DepartementResult[];
return [
2020-10-07 17:42:21 +02:00
...results,
...matchSorter(extraTerms, term, {
keys: ['nom', 'code']
})
];
}
2020-10-07 17:42:21 +02:00
type ComboDepartementsSearchProps = Omit<
ComboSearchProps<DepartementResult> & {
addForeignDepartement: boolean;
},
'transformResult' | 'transformResults'
>;
export function ComboDepartementsSearch({
addForeignDepartement = true,
...props
}: ComboDepartementsSearchProps) {
return (
<ComboSearch
{...props}
scope="departements"
minimumInputLength={1}
transformResult={({ code, nom }) => [code, `${code} - ${nom}`]}
transformResults={
addForeignDepartement ? expandResultsWithForeignDepartement : undefined
}
/>
);
}