UNPKG

1.84 kBJavaScriptView Raw
1import isEqual from 'fast-deep-equal';
2import getOptionProperty from './getOptionProperty';
3import { isFunction, isString } from './nodash';
4import stripDiacritics from './stripDiacritics';
5import warn from './warn';
6
7function isMatch(input, string, props) {
8 var searchStr = input;
9 var str = string;
10
11 if (!props.caseSensitive) {
12 searchStr = searchStr.toLowerCase();
13 str = str.toLowerCase();
14 }
15
16 if (props.ignoreDiacritics) {
17 searchStr = stripDiacritics(searchStr);
18 str = stripDiacritics(str);
19 }
20
21 return str.indexOf(searchStr) !== -1;
22}
23/**
24 * Default algorithm for filtering results.
25 */
26
27
28export default function defaultFilterBy(option, props) {
29 var filterBy = props.filterBy,
30 labelKey = props.labelKey,
31 multiple = props.multiple,
32 selected = props.selected,
33 text = props.text; // Don't show selected options in the menu for the multi-select case.
34
35 if (multiple && selected.some(function (o) {
36 return isEqual(o, option);
37 })) {
38 return false;
39 }
40
41 if (isFunction(labelKey)) {
42 return isMatch(text, labelKey(option), props);
43 }
44
45 var fields = filterBy.slice();
46
47 if (isString(labelKey)) {
48 // Add the `labelKey` field to the list of fields if it isn't already there.
49 if (fields.indexOf(labelKey) === -1) {
50 fields.unshift(labelKey);
51 }
52 }
53
54 if (isString(option)) {
55 warn(fields.length <= 1, 'You cannot filter by properties when `option` is a string.');
56 return isMatch(text, option, props);
57 }
58
59 return fields.some(function (field) {
60 var value = getOptionProperty(option, field);
61
62 if (!isString(value)) {
63 warn(false, 'Fields passed to `filterBy` should have string values. Value will ' + 'be converted to a string; results may be unexpected.');
64 value = String(value);
65 }
66
67 return isMatch(text, value, props);
68 });
69}
\No newline at end of file