Skip to content
This repository has been archived by the owner on Jul 19, 2019. It is now read-only.

Add new optional prop isItemAutoHighlightMatch #337

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
29 changes: 20 additions & 9 deletions lib/Autocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ function getScrollOffset() {
}
}

const startsWithIgnoreCase = (haystack, needle) =>
haystack.toLowerCase().indexOf(needle.toLowerCase()) === 0

class Autocomplete extends React.Component {

static propTypes = {
Expand Down Expand Up @@ -137,6 +140,16 @@ class Autocomplete extends React.Component {
* menu.
*/
autoHighlight: PropTypes.bool,
/**
* Arguments: `itemValue: String, searchValue: String, item: Any`
*
* Invoked when attempting to use an item as auto highlighted value. The
* return value is used to determine whether the item should be actually
* highlighted or not.
* By default we check whether the item value starts with the search value
* case insensitively.
*/
isItemAutoHighlightMatch: PropTypes.func,
/**
* Whether or not to automatically select the highlighted item when the
* `<input>` loses focus.
Expand Down Expand Up @@ -186,6 +199,7 @@ class Autocomplete extends React.Component {
maxHeight: '50%', // TODO: don't cheat, let it flow to the bottom
},
autoHighlight: true,
isItemAutoHighlightMatch: startsWithIgnoreCase,
selectOnBlur: false,
onMenuVisibilityChange() {},
}
Expand Down Expand Up @@ -391,7 +405,7 @@ class Autocomplete extends React.Component {

maybeAutoCompleteText(state, props) {
const { highlightedIndex } = state
const { value, getItemValue } = props
const { value, getItemValue, isItemAutoHighlightMatch } = props
let index = highlightedIndex === null ? 0 : highlightedIndex
let items = this.getFilteredItems(props)
for (let i = 0; i < items.length ; i++) {
Expand All @@ -400,14 +414,11 @@ class Autocomplete extends React.Component {
index = (index + 1) % items.length
}
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)
if (itemValueDoesMatch) {
return { highlightedIndex: index }
}
if (value !== ''
&& matchedItem
&& isItemAutoHighlightMatch(getItemValue(matchedItem), value, matchedItem)
) {
return { highlightedIndex: index }
}
return { highlightedIndex: null }
}
Expand Down