UNPKG

1.42 kBJavaScriptView Raw
1
2import get from 'lodash/get'
3
4export 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
18const matchTest = (query, domain) => {
19 const escapeRegExp = str => str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
20
21 // eslint-disable-next-line no-control-regex
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 // if the query only has ASCII chars, treat as English
31 const hasTrailingSpace = query.endsWith(' ')
32 const searchRegex = new RegExp(
33 words
34 .map((word, index) => {
35 if (words.length === index + 1 && !hasTrailingSpace) {
36 // The last word - ok with the word being "startswith"-like
37 return `(?=.*\\b${escapeRegExp(word)})`
38 } else {
39 // Not the last word - expect the whole word exactly
40 return `(?=.*\\b${escapeRegExp(word)}\\b)`
41 }
42 })
43 .join('') + '.+',
44 'gi'
45 )
46 return searchRegex.test(domain)
47 } else {
48 // if the query has non-ASCII chars, treat as other languages
49 return words.some(word => domain.toLowerCase().indexOf(word) > -1)
50 }
51}