-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
field.js
77 lines (73 loc) · 2.81 KB
/
field.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import React from 'react';
import { flatten } from 'lodash';
import { escapeKuery } from './escape_kuery';
import { sortPrefixFirst } from './sort_prefix_first';
import { isFilterable } from '../../../../../../src/plugins/data/public';
import { FormattedMessage } from '@kbn/i18n/react';
const type = 'field';
function getDescription(fieldName) {
return (
<p>
<FormattedMessage
id="xpack.kueryAutocomplete.filterResultsDescription"
defaultMessage="Filter results that contain {fieldName}"
values={{ fieldName: <span className="kbnSuggestionItem__callout">{fieldName}</span> }}
/>
</p>
);
}
export function getSuggestionsProvider({ indexPatterns }) {
const allFields = flatten(
indexPatterns.map(indexPattern => {
return indexPattern.fields.filter(isFilterable);
})
);
return function getFieldSuggestions({ start, end, prefix, suffix, nestedPath = '' }) {
const search = `${prefix}${suffix}`.trim().toLowerCase();
const matchingFields = allFields.filter(field => {
return (
(!nestedPath ||
(nestedPath &&
field.subType &&
field.subType.nested &&
field.subType.nested.path.includes(nestedPath))) &&
field.name.toLowerCase().includes(search) &&
field.name !== search
);
});
const sortedFields = sortPrefixFirst(matchingFields.sort(keywordComparator), search, 'name');
const suggestions = sortedFields.map(field => {
const remainingPath =
field.subType && field.subType.nested
? field.subType.nested.path.slice(nestedPath ? nestedPath.length + 1 : 0)
: '';
const text =
field.subType && field.subType.nested && remainingPath.length > 0
? `${escapeKuery(remainingPath)}:{ ${escapeKuery(
field.name.slice(field.subType.nested.path.length + 1)
)} }`
: `${escapeKuery(field.name.slice(nestedPath ? nestedPath.length + 1 : 0))} `;
const description = getDescription(field.name);
const cursorIndex =
field.subType && field.subType.nested && remainingPath.length > 0
? text.length - 2
: text.length;
return { type, text, description, start, end, cursorIndex, field };
});
return suggestions;
};
}
function keywordComparator(first, second) {
const extensions = ['raw', 'keyword'];
if (extensions.map(ext => `${first.name}.${ext}`).includes(second.name)) {
return 1;
} else if (extensions.map(ext => `${second.name}.${ext}`).includes(first.name)) {
return -1;
}
return first.name.localeCompare(second.name);
}