Skip to content

Commit

Permalink
Use match-sorter for more flexible autocomplete (#2671)
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop authored Mar 8, 2023
1 parent 57ba533 commit 1fb2727
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"just-index": "^4.1.2",
"just-map-values": "^3.2.0",
"just-omit": "^2.2.0",
"match-sorter": "^6.3.1",
"minimist": "^1.2.7",
"ms": "^2.1.2",
"natural-compare": "^1.2.2",
Expand Down
17 changes: 8 additions & 9 deletions src/components/Chat/Input/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React from 'react';
import PropTypes from 'prop-types';
import { translate } from '@u-wave/react-translate';
import AutoComplete, { Completion } from 'react-abstract-autocomplete';
import { matchSorter } from 'match-sorter';
import SuggestionsList from './SuggestionsList';
import EmojiSuggestion from './EmojiSuggestion';
import GroupSuggestion from './GroupSuggestion';
Expand Down Expand Up @@ -34,10 +35,8 @@ const renderSuggestions = (children) => (

// User suggestions:
const getUserCompletions = (value, { trigger, completions }) => {
const compare = value.substr(trigger.length).toLowerCase();
return completions.filter((user) => (
user.username.substr(0, compare.length).toLowerCase() === compare
));
const compare = value.substr(trigger.length);
return matchSorter(completions, compare, { keys: ['username'] });
};
const getUserText = (user, { trigger }) => `${trigger}${user.username} `;
const renderUser = (props) => <UserSuggestion {...props} />;
Expand All @@ -48,12 +47,12 @@ const renderGroup = (props) => <GroupSuggestion {...props} />;
// Emoji suggestions:
const getEmojiCompletions = (value, { trigger, completions }) => {
const compare = value.substr(trigger.length).toLowerCase();
const results = completions.filter((emoji) => (
emoji.shortcode.substr(0, compare.length).toLowerCase() === compare
));
const results = matchSorter(completions, compare, {
keys: ['shortcode'],
baseSort: (a, b) => a.rankedValue.length - b.rankedValue.length,
});

const uniqueResults = uniqBy(results, (emoji) => emoji.image);
return uniqueResults.sort((a, b) => a.shortcode.length - b.shortcode.length);
return uniqBy(results, (emoji) => emoji.image);
};
const getEmojiText = (value) => `:${value.shortcode}: `;
const renderEmoji = (props) => <EmojiSuggestion {...props} />;
Expand Down

0 comments on commit 1fb2727

Please sign in to comment.