From 3f1f6a688db3fa0d6648da4d50510df8d08ebb87 Mon Sep 17 00:00:00 2001 From: David Davidson Date: Wed, 17 Apr 2019 10:42:29 -0700 Subject: [PATCH] Support configuring `autoHighlightValueMatches` fn --- README.md | 6 ++++++ lib/Autocomplete.js | 14 ++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e78523da..0c7c5034 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,12 @@ Default value: `true` Whether or not to automatically highlight the top match in the dropdown menu. +#### `autoHighlightValueMatches: Function` (optional) +Default value: `(itemValue, value) => (itemValue.toLowerCase().indexOf(value.toLowerCase()) === 0)` + +When `autoHighlight` is true, this is invoked to determine whether the top item +in the dropdown menu should be considered a match. + #### `inputProps: Object` (optional) Default value: `{}` diff --git a/lib/Autocomplete.js b/lib/Autocomplete.js index 1658c8bb..ee39c652 100644 --- a/lib/Autocomplete.js +++ b/lib/Autocomplete.js @@ -137,6 +137,11 @@ class Autocomplete extends React.Component { * menu. */ autoHighlight: PropTypes.bool, + /** + * Custom function to determine whether the top match in the dropdown should + * highlight + */ + autoHighlightValueMatches: PropTypes.func, /** * Whether or not to automatically select the highlighted item when the * `` loses focus. @@ -186,6 +191,9 @@ class Autocomplete extends React.Component { maxHeight: '50%', // TODO: don't cheat, let it flow to the bottom }, autoHighlight: true, + autoHighlightValueMatches: (itemValue, value) => (itemValue.toLowerCase().indexOf( + value.toLowerCase() + ) === 0), selectOnBlur: false, onMenuVisibilityChange() {}, } @@ -391,7 +399,7 @@ class Autocomplete extends React.Component { maybeAutoCompleteText(state, props) { const { highlightedIndex } = state - const { value, getItemValue } = props + const { value, getItemValue, autoHighlightValueMatches } = props let index = highlightedIndex === null ? 0 : highlightedIndex let items = this.getFilteredItems(props) for (let i = 0; i < items.length ; i++) { @@ -402,9 +410,7 @@ class Autocomplete extends React.Component { const matchedItem = items[index] && props.isItemSelectable(items[index]) ? items[index] : null if (value !== '' && matchedItem) { const itemValue = getItemValue(matchedItem) - const itemValueDoesMatch = (itemValue.toLowerCase().indexOf( - value.toLowerCase() - ) === 0) + const itemValueDoesMatch = autoHighlightValueMatches(itemValue, value) if (itemValueDoesMatch) { return { highlightedIndex: index } }