-
Notifications
You must be signed in to change notification settings - Fork 915
/
Copy pathdefault-handlers.js
53 lines (46 loc) · 1.43 KB
/
default-handlers.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
export function defaultGetNodeKey({ treeIndex }) {
return treeIndex;
}
// Cheap hack to get the text of a react object
function getReactElementText(parent) {
if (typeof parent === 'string') {
return parent;
}
if (
parent === null ||
typeof parent !== 'object' ||
!parent.props ||
!parent.props.children ||
(typeof parent.props.children !== 'string' &&
typeof parent.props.children !== 'object')
) {
return '';
}
if (typeof parent.props.children === 'string') {
return parent.props.children;
}
return parent.props.children
.map(child => getReactElementText(child))
.join('');
}
// Search for a query string inside a node property
function stringSearch(key, searchQuery, node, path, treeIndex) {
if (typeof node[key] === 'function') {
// Search within text after calling its function to generate the text
return (
String(node[key]({ node, path, treeIndex })).indexOf(searchQuery) > -1
);
}
if (typeof node[key] === 'object') {
// Search within text inside react elements
return getReactElementText(node[key]).indexOf(searchQuery) > -1;
}
// Search within string
return node[key] && String(node[key]).indexOf(searchQuery) > -1;
}
export function defaultSearchMethod({ node, path, treeIndex, searchQuery }) {
return (
stringSearch('title', searchQuery, node, path, treeIndex) ||
stringSearch('subtitle', searchQuery, node, path, treeIndex)
);
}