1 |
|
2 | import get from 'lodash/get'
|
3 |
|
4 | export default (query, page, additionalStr = null) => {
|
5 | let domain = get(page, 'title', '')
|
6 |
|
7 | if (get(page, 'frontmatter.tags')) {
|
8 | domain += ` ${page.frontmatter.tags.join(' ')}`
|
9 | }
|
10 |
|
11 | if (additionalStr) {
|
12 | domain += ` ${additionalStr}`
|
13 | }
|
14 |
|
15 | return matchTest(query, domain)
|
16 | }
|
17 |
|
18 | const matchTest = (query, domain) => {
|
19 | const escapeRegExp = str => str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
|
20 |
|
21 |
|
22 | const nonASCIIRegExp = new RegExp('[^\x00-\x7F]')
|
23 |
|
24 | const words = query
|
25 | .split(/\s+/g)
|
26 | .map(str => str.trim())
|
27 | .filter(str => !!str)
|
28 |
|
29 | if (!nonASCIIRegExp.test(query)) {
|
30 |
|
31 | const hasTrailingSpace = query.endsWith(' ')
|
32 | const searchRegex = new RegExp(
|
33 | words
|
34 | .map((word, index) => {
|
35 | if (words.length === index + 1 && !hasTrailingSpace) {
|
36 |
|
37 | return `(?=.*\\b${escapeRegExp(word)})`
|
38 | } else {
|
39 |
|
40 | return `(?=.*\\b${escapeRegExp(word)}\\b)`
|
41 | }
|
42 | })
|
43 | .join('') + '.+',
|
44 | 'gi'
|
45 | )
|
46 | return searchRegex.test(domain)
|
47 | } else {
|
48 |
|
49 | return words.some(word => domain.toLowerCase().indexOf(word) > -1)
|
50 | }
|
51 | }
|