Skip to content

Improve sort order of Select component filtered results #1652

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 12, 2024
Merged
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
63 changes: 56 additions & 7 deletions src/components/Select.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import React, { useMemo } from 'react';
import React, { useMemo, useState } from 'react';
import ReactSelect from 'react-select';
import cn from 'classnames';

import * as css from './Select.module.css';

const toOption = (value) => ({ value, label: value });

export const Select = ({
title,
options,
Expand All @@ -17,8 +15,12 @@ export const Select = ({
variant,
instanceId
}) => {
const [input, setInput] = useState('');
const opts = useMemo(() => options.map(toOption), [options]);
const handleOnChange = (o, action) => onChange(o ? o.value : o);
const filteredOpts = useMemo(
() => (input === '' ? opts : filterAndSortRank(opts, input)),
[opts, input]
);

return (
<section className={cn(css.root, className, { [css[variant]]: variant })}>
Expand All @@ -36,10 +38,12 @@ export const Select = ({
placeholder={placeholder}
className={css.select}
classNamePrefix="rs"
options={opts}
defaultValue={selected ? toOption(selected) : selected}
onChange={handleOnChange}
options={filteredOpts}
defaultValue={selected ? toOption(selected) : ''}
onChange={(o) => onChange(o ? o.value : null)}
instanceId={instanceId}
onInputChange={setInput}
filterOption={() => true}
/>

<div className={css.itemSpacer}></div>
Expand All @@ -48,4 +52,49 @@ export const Select = ({
</section>
);
};

export default Select;

const toOption = (value) => ({ value, label: value });

// trim, lowercase and strip accents
const normalize = (value) =>
value
.trim()
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '');

const rank = (value, input) => {
// exact match: highest priority
if (value === input) return 0;

// complete word match: higher priority based on word position
const words = value.split(' ');
for (let i = 0; i < words.length; i++) {
if (words[i] === input) return i + 1;
}

// partial match: lower priority based on character position
const index = value.indexOf(input);
return index === -1 ? Number.MAX_SAFE_INTEGER : 1000 + index;
};

const filterAndSortRank = (options, input) => {
// It doesn't seem possible to only sort the filtered options in react-select, but we can re-implement the filtering to do so.
// https://github.com/JedWatson/react-select/discussions/4426

const normalizedInput = normalize(input);

return options
.filter((o) => normalize(o.value).includes(normalizedInput))
.sort((optA, optB) => {
const rankDelta =
rank(normalize(optA.value), normalizedInput) -
rank(normalize(optB.value), normalizedInput);

if (rankDelta !== 0) return rankDelta;

return optA.value.localeCompare(optB.value);
});
};
Loading