docs/.vitepress/theme/workers/searchWorker.ts

29fae34075541b9056536846db51ac39afbc3e91
wotaku/docs/.vitepress/theme/workers/searchWorker.ts
taskylizard some hotpath improvementsa2386dba90 5 months ago

281 lines · 7181 bytes

  1import MiniSearch, {
  2  type Options,
  3  type SearchOptions,
  4  type SearchResult
  5} from 'minisearch'
  6
  7import type { PageLink } from '../../plugins/urlSearchPlugin'
  8
  9interface Result {
 10  title: string
 11  titles: string[]
 12  text?: string
 13}
 14
 15type SearchMode = 'exact' | 'fuzzy' | 'url'
 16
 17type PlainRecord = Record<string, unknown>
 18
 19interface SearchConfig {
 20  options?: PlainRecord
 21  searchOptions?: PlainRecord
 22  useDefaultBoostDocument?: boolean
 23}
 24
 25interface PageGroupCount {
 26  key: string
 27  count: number
 28}
 29
 30interface LoadIndexRequest {
 31  type: 'load-index'
 32  id: number
 33  localeIndex: string
 34  indexJson: unknown
 35  indexVersion: number
 36  config: SearchConfig
 37}
 38
 39interface TextSearchRequest {
 40  type: 'text-search'
 41  id: number
 42  query: string
 43  mode: SearchMode
 44  pageOrderEntries: [string, number][]
 45}
 46
 47interface UrlSearchRequest {
 48  type: 'url-search'
 49  id: number
 50  query: string
 51  pageOrderEntries: [string, number][]
 52}
 53
 54type SearchWorkerRequest =
 55  | LoadIndexRequest
 56  | TextSearchRequest
 57  | UrlSearchRequest
 58
 59type WorkerSearchResult = SearchResult & Result
 60
 61let searchIndex: MiniSearch<Result> | null = null
 62let searchIndexKey = ''
 63let urlLinks: PageLink[] = []
 64let urlLinkHrefsLower: string[] = []
 65let urlLinksPromise: Promise<void> | null = null
 66let pageOrder = new Map<string, number>()
 67let docOrder = new Map<string, number>()
 68
 69function defaultBoostDocument(
 70  _: string,
 71  term: string,
 72  storedFields: Record<string, string | string[]>
 73) {
 74  const titles = ((storedFields?.titles as string[] | undefined) ?? [])
 75    .filter((t) => Boolean(t))
 76    .map((t) => t.toLowerCase())
 77  const titleIndex = titles
 78    .map((t, i) => (t?.includes(term) ? i : -1))
 79    .find((i) => i >= 0) ?? -1
 80  if (titleIndex >= 0) return 10000 - titleIndex
 81  return 1
 82}
 83
 84function stableStringify(value: unknown): string {
 85  if (value === null || typeof value !== 'object') return JSON.stringify(value)
 86  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
 87  const object = value as Record<string, unknown>
 88  return `{${
 89    Object.keys(object).sort().map((key) =>
 90      `${JSON.stringify(key)}:${stableStringify(object[key])}`
 91    ).join(',')
 92  }}`
 93}
 94
 95function setPageOrder(entries: [string, number][]) {
 96  pageOrder = new Map(entries)
 97}
 98
 99function getPageKey(id: string) {
100  return id.split('#')[0].replace(/\/$/, '')
101}
102
103function getPageOrder(key: string) {
104  return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER
105}
106
107function getDocOrder(id: string) {
108  return docOrder.get(id) ?? Number.MAX_SAFE_INTEGER
109}
110
111function compareByPageAndDoc(a: { id: unknown }, b: { id: unknown }) {
112  const aId = String(a.id)
113  const bId = String(b.id)
114  const pageDiff = getPageOrder(getPageKey(aId)) - getPageOrder(getPageKey(bId))
115  if (pageDiff !== 0) return pageDiff
116  return getDocOrder(aId) - getDocOrder(bId)
117}
118
119function rebuildDocOrder(index: MiniSearch<Result>) {
120  const map = new Map<string, number>()
121  const ids = (index as any)._documentIds
122  if (ids instanceof Map) {
123    let i = 0
124    for (const originalId of ids.values()) {
125      map.set(String(originalId), i++)
126    }
127  } else if (ids && typeof ids === 'object') {
128    const keys = Object.keys(ids)
129      .map(Number)
130      .sort((a, b) => a - b)
131    let i = 0
132    for (const key of keys) {
133      map.set(String(ids[key]), i++)
134    }
135  }
136  docOrder = map
137}
138
139async function loadSearchIndex(
140  localeIndex: string,
141  indexVersion: number,
142  indexJson: unknown,
143  config: SearchConfig
144) {
145  const key = `${localeIndex}\n${indexVersion}\n${stableStringify(config)}`
146  if (searchIndex && searchIndexKey === key) return
147
148  const searchOptions = {
149    boost: { title: 10, titles: 4, text: 1 },
150    ...(config.searchOptions ?? {}),
151    ...(config.useDefaultBoostDocument
152      ? { boostDocument: defaultBoostDocument }
153      : {})
154  } as SearchOptions
155
156  searchIndex = MiniSearch.loadJSON<Result>(
157    indexJson as any,
158    {
159      fields: ['title', 'titles', 'text'],
160      storeFields: ['title', 'titles'],
161      searchOptions,
162      ...(config.options ?? {})
163    } as Options<Result>
164  )
165  searchIndexKey = key
166  rebuildDocOrder(searchIndex)
167}
168
169async function textSearch(message: TextSearchRequest) {
170  setPageOrder(message.pageOrderEntries)
171  if (!searchIndex) throw new Error('Search index has not been loaded')
172
173  const dynamicSearchOptions = {
174    fuzzy: message.mode === 'fuzzy' ? (0.3 as number | false) : false,
175    prefix: message.mode === 'fuzzy'
176      ? (term: string) => term.length > 3
177      : false,
178    maxFuzzy: message.mode === 'fuzzy' ? 1 : 0,
179    boost: { title: 10, titles: 4, text: 1 }
180  } as SearchOptions
181
182  const ranked = searchIndex.search(
183    message.query,
184    dynamicSearchOptions
185  ) as WorkerSearchResult[]
186
187  const top = ranked.slice(0, 50)
188  const seen = new Set(top.map((r) => r.id))
189  const titleHits = ranked.filter(
190    (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
191  )
192  const results = [...top, ...titleHits].sort(compareByPageAndDoc)
193  const terms = new Set<string>()
194  for (const result of results) {
195    for (const term in result.match) terms.add(term)
196  }
197
198  return {
199    results,
200    terms: [...terms]
201  }
202}
203
204async function ensureUrlLinks() {
205  if (urlLinks.length > 0) return
206  if (urlLinksPromise) {
207    await urlLinksPromise
208    return
209  }
210
211  urlLinksPromise = fetch('/url-search-index.json')
212    .then((r) => r.json())
213    .then((data: PageLink[]) => {
214      data.sort((a, b) => getPageOrder(a.pageId) - getPageOrder(b.pageId))
215      urlLinks = data
216      urlLinkHrefsLower = data.map((link) => link.href.toLowerCase())
217    })
218    .catch(() => {
219      urlLinks = []
220      urlLinkHrefsLower = []
221    })
222    .finally(() => {
223      urlLinksPromise = null
224    })
225  await urlLinksPromise
226}
227
228async function urlSearch(message: UrlSearchRequest) {
229  setPageOrder(message.pageOrderEntries)
230  await ensureUrlLinks()
231
232  const query = message.query.trim().toLowerCase()
233  if (!query) return { matches: [], pageGroups: [] }
234
235  const matches: PageLink[] = []
236  const pageGroups = new Map<string, PageGroupCount>()
237  for (let i = 0; i < urlLinks.length; i++) {
238    if (!urlLinkHrefsLower[i].includes(query)) continue
239
240    const link = urlLinks[i]
241
242    matches.push(link)
243    const existing = pageGroups.get(link.pageId)
244    if (existing) existing.count++
245    else pageGroups.set(link.pageId, { key: link.pageId, count: 1 })
246  }
247
248  return {
249    matches,
250    pageGroups: [...pageGroups.values()].sort(
251      (a, b) => getPageOrder(a.key) - getPageOrder(b.key)
252    )
253  }
254}
255
256self.onmessage = async (event: MessageEvent<SearchWorkerRequest>) => {
257  const message = event.data
258  try {
259    const payload = message.type === 'load-index'
260      ? await loadSearchIndex(
261        message.localeIndex,
262        message.indexVersion,
263        message.indexJson,
264        message.config
265      )
266      : message.type === 'text-search'
267      ? await textSearch(message)
268      : await urlSearch(message)
269    self.postMessage({
270      type: `${message.type}:success`,
271      id: message.id,
272      payload
273    })
274  } catch (error) {
275    self.postMessage({
276      type: `${message.type}:error`,
277      id: message.id,
278      error: error instanceof Error ? error.message : String(error)
279    })
280  }
281}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form