Skip to content

Commit 715dde1

Browse files
committed
feat(plugin-slimsearch): improve default querySplitter, close #299
1 parent a11237c commit 715dde1

File tree

4 files changed

+39
-1
lines changed

4 files changed

+39
-1
lines changed

Diff for: plugins/search/plugin-slimsearch/src/client/helpers/search.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { useRouteLocale } from 'vuepress/client'
55

66
import { isFunction } from 'vuepress/shared'
77
import type { SearchResult, WorkerSearchOptions } from '../typings/index.js'
8+
import { defaultQuerySplitter } from '../utils/index.js'
89

910
declare const __VUEPRESS_DEV__: boolean
1011

@@ -33,7 +34,9 @@ export interface SearchOptions extends SearchLocaleOptions {
3334
locales?: Record<string, SearchLocaleOptions>
3435
}
3536

36-
const searchOptions: Ref<SearchOptions> = ref({})
37+
const searchOptions: Ref<SearchOptions> = ref({
38+
querySplitter: (query) => Promise.resolve(defaultQuerySplitter(query)),
39+
})
3740

3841
const slimsearchSymbol: InjectionKey<Ref<SearchOptions>> = Symbol(
3942
__VUEPRESS_DEV__ ? 'slimsearch' : '',

Diff for: plugins/search/plugin-slimsearch/src/client/utils/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ export * from './createSearchWorker.js'
22
export * from './getResultPath.js'
33
export * from './isFocusingTextControl.js'
44
export * from './isKeyMatched.js'
5+
export * from './querySplitter.js'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const CJK_REGEXP =
2+
/[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/
3+
4+
export const defaultQuerySplitter = (query: string): string[] =>
5+
query
6+
.split(/\s+/)
7+
.map((word) => {
8+
if (word.length > 3) {
9+
const chars = word.split('')
10+
11+
if (chars.every((char) => CJK_REGEXP.test(char))) return chars
12+
}
13+
14+
return word
15+
})
16+
.flat()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { expect, it } from 'vitest'
2+
import { defaultQuerySplitter } from '../src/client/utils/querySplitter.js'
3+
4+
it('defaultQuerySplitter', () => {
5+
const testCases: [string, string[]][] = [
6+
['你好世界', ['你', '好', '世', '界']],
7+
['你好 世界', ['你好', '世界']],
8+
['hello world', ['hello', 'world']],
9+
['hello 你好 world 世界', ['hello', '你好', 'world', '世界']],
10+
['hi hello 你好 世界', ['hi', 'hello', '你好', '世界']],
11+
['', ['']],
12+
]
13+
14+
for (const [query, expected] of testCases) {
15+
const result = defaultQuerySplitter(query)
16+
expect(result).toEqual(expected)
17+
}
18+
})

0 commit comments

Comments
 (0)