Commit 7dcde1e400
Unsigned
Layout: unified · split
docs/.vitepress/theme/components/Search.vue +283 −141
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | <script lang="ts" setup> |
| 2 | import MiniSearch, { type SearchResult } from 'minisearch' | |
| 2 | import type { SearchResult } from 'minisearch' | |
| 3 | 3 | import { dataSymbol, type DefaultTheme, inBrowser, useRouter } from 'vitepress' |
| 4 | 4 | import { |
| 5 | 5 | computed, |
| @@ -80,7 +80,14 @@ const el = shallowRef<HTMLElement>() | ||
| 80 | 80 | const resultsEl = shallowRef<HTMLElement>() |
| 81 | 81 | |
| 82 | 82 | /* Search */ |
| 83 | interface Result { | |
| 84 | title: string | |
| 85 | titles: string[] | |
| 86 | text?: string | |
| 87 | } | |
| 88 | ||
| 83 | 89 | const searchIndexData = shallowRef(localSearchIndex) |
| 90 | const searchIndexVersion = ref(0) | |
| 84 | 91 | |
| 85 | 92 | // @ts-ignore |
| 86 | 93 | if (import.meta.hot) { |
| @@ -88,16 +95,11 @@ if (import.meta.hot) { | ||
| 88 | 95 | import.meta.hot.accept('@localSearchIndex', (m) => { |
| 89 | 96 | if (m) { |
| 90 | 97 | searchIndexData.value = m.default |
| 98 | searchIndexVersion.value++ | |
| 91 | 99 | } |
| 92 | 100 | }) |
| 93 | 101 | } |
| 94 | 102 | |
| 95 | interface Result { | |
| 96 | title: string | |
| 97 | titles: string[] | |
| 98 | text?: string | |
| 99 | } | |
| 100 | ||
| 101 | 103 | const vitePressData = useData() |
| 102 | 104 | const { activate } = useFocusTrap(el, { |
| 103 | 105 | immediate: true, |
| @@ -110,24 +112,6 @@ const { activate } = useFocusTrap(el, { | ||
| 110 | 112 | } |
| 111 | 113 | }) |
| 112 | 114 | const { localeIndex, theme } = vitePressData |
| 113 | const searchIndex = computedAsync(async () => | |
| 114 | markRaw( | |
| 115 | MiniSearch.loadJSON<Result>( | |
| 116 | (await searchIndexData.value[localeIndex.value]?.())?.default, | |
| 117 | { | |
| 118 | fields: ['title', 'titles', 'text'], | |
| 119 | storeFields: ['title', 'titles'], | |
| 120 | searchOptions: { | |
| 121 | boost: { title: 10, titles: 4, text: 1 }, | |
| 122 | ...(theme.value.search?.provider === 'local' && | |
| 123 | theme.value.search.options?.miniSearch?.searchOptions) | |
| 124 | }, | |
| 125 | ...(theme.value.search?.provider === 'local' && | |
| 126 | theme.value.search.options?.miniSearch?.options) | |
| 127 | } | |
| 128 | ) | |
| 129 | ) | |
| 130 | ) | |
| 131 | 115 | |
| 132 | 116 | const disableQueryPersistence = computed(() => { |
| 133 | 117 | return ( |
| @@ -287,37 +271,13 @@ function cycleSearchMode() { | ||
| 287 | 271 | const matchExact = computed(() => searchMode.value === 'exact') |
| 288 | 272 | const urlSearchMode = computed(() => searchMode.value === 'url') |
| 289 | 273 | |
| 290 | const allLinks = shallowRef<PageLink[]>([]) | |
| 291 | let allLinksFetchPromise: Promise<void> | null = null | |
| 292 | ||
| 293 | async function ensureAllLinks() { | |
| 294 | if (allLinks.value.length > 0) return | |
| 295 | if (allLinksFetchPromise) { | |
| 296 | await allLinksFetchPromise | |
| 297 | return | |
| 298 | } | |
| 299 | allLinksFetchPromise = fetch('/url-search-index.json') | |
| 300 | .then((r) => r.json()) | |
| 301 | .then((data: PageLink[]) => { | |
| 302 | data.sort((a, b) => { | |
| 303 | const pa = pageMeta.get(a.pageId)?.order ?? Number.MAX_SAFE_INTEGER | |
| 304 | const pb = pageMeta.get(b.pageId)?.order ?? Number.MAX_SAFE_INTEGER | |
| 305 | return pa - pb | |
| 306 | }) | |
| 307 | allLinks.value = data | |
| 308 | }) | |
| 309 | .catch(() => { | |
| 310 | allLinks.value = [] | |
| 311 | }) | |
| 312 | .finally(() => { | |
| 313 | allLinksFetchPromise = null | |
| 314 | }) | |
| 315 | await allLinksFetchPromise | |
| 274 | interface PageGroupCount { | |
| 275 | key: string | |
| 276 | count: number | |
| 316 | 277 | } |
| 317 | 278 | |
| 318 | watch(urlSearchMode, (active) => { | |
| 319 | if (active) ensureAllLinks() | |
| 320 | }, { immediate: true }) | |
| 279 | const urlMatches = shallowRef<PageLink[]>([]) | |
| 280 | const urlPageGroupCounts = shallowRef<PageGroupCount[]>([]) | |
| 321 | 281 | |
| 322 | 282 | interface UrlResult { |
| 323 | 283 | href: string |
| @@ -333,34 +293,21 @@ const URL_PAGE_SIZE = 25 | ||
| 333 | 293 | // 1-indexed current page within the URL results. |
| 334 | 294 | const urlPage = ref(1) |
| 335 | 295 | |
| 336 | // Full match set — cheap string filtering only (no regex, no object churn). | |
| 296 | // Full URL match set returned by the search worker. | |
| 337 | 297 | // Used for accurate page-group counts in the ribbon and for pagination. |
| 338 | const urlMatches = computed((): PageLink[] => { | |
| 339 | if (!urlSearchMode.value || !filterText.value.trim()) return [] | |
| 340 | const query = urlFilterDebounced.value.trim().toLowerCase() | |
| 341 | if (!query) return [] | |
| 342 | const out: PageLink[] = [] | |
| 343 | for (const link of allLinks.value) { | |
| 344 | if (link.href.toLowerCase().includes(query)) out.push(link) | |
| 345 | } | |
| 346 | return out | |
| 347 | }) | |
| 348 | 298 | |
| 349 | 299 | // URL mode page ribbon — mirrors the normal pageGroups/filteredResults logic |
| 350 | 300 | const urlActivePageFilter = ref<string | null>(null) |
| 351 | 301 | |
| 352 | const urlPageGroups = computed(() => { | |
| 353 | const map = new Map<string, { key: string; label: string; count: number }>() | |
| 354 | for (const r of urlMatches.value) { | |
| 355 | const key = r.pageId | |
| 356 | const existing = map.get(key) | |
| 357 | if (existing) existing.count++ | |
| 358 | else map.set(key, { key, label: getPageLabel(key), count: 1 }) | |
| 359 | } | |
| 360 | return [...map.values()].sort((a, b) => | |
| 361 | getPageOrder(a.key) - getPageOrder(b.key) | |
| 362 | ) | |
| 363 | }) | |
| 302 | const urlPageGroups = computed(() => | |
| 303 | urlPageGroupCounts.value | |
| 304 | .map((group) => ({ | |
| 305 | key: group.key, | |
| 306 | label: getPageLabel(group.key), | |
| 307 | count: group.count | |
| 308 | })) | |
| 309 | .sort((a, b) => getPageOrder(a.key) - getPageOrder(b.key)) | |
| 310 | ) | |
| 364 | 311 | |
| 365 | 312 | // Full match set honoring the active ribbon page filter (uncapped). |
| 366 | 313 | const urlFilteredMatches = computed((): PageLink[] => { |
| @@ -540,36 +487,209 @@ const pageMeta = (() => { | ||
| 540 | 487 | return map |
| 541 | 488 | })() |
| 542 | 489 | |
| 490 | type SearchMode = 'exact' | 'fuzzy' | 'url' | |
| 491 | ||
| 492 | interface TextSearchWorkerPayload { | |
| 493 | results: (SearchResult & Result)[] | |
| 494 | terms: string[] | |
| 495 | } | |
| 496 | ||
| 497 | interface UrlSearchWorkerPayload { | |
| 498 | matches: PageLink[] | |
| 499 | pageGroups: PageGroupCount[] | |
| 500 | } | |
| 501 | ||
| 502 | interface LoadIndexWorkerRequest { | |
| 503 | type: 'load-index' | |
| 504 | localeIndex: string | |
| 505 | indexJson: unknown | |
| 506 | indexVersion: number | |
| 507 | config: ReturnType<typeof getMiniSearchWorkerConfig> | |
| 508 | } | |
| 509 | ||
| 510 | interface TextSearchWorkerRequest { | |
| 511 | type: 'text-search' | |
| 512 | query: string | |
| 513 | mode: SearchMode | |
| 514 | pageOrderEntries: [string, number][] | |
| 515 | } | |
| 516 | ||
| 517 | interface UrlSearchWorkerRequest { | |
| 518 | type: 'url-search' | |
| 519 | query: string | |
| 520 | pageOrderEntries: [string, number][] | |
| 521 | } | |
| 522 | ||
| 523 | type SearchWorkerRequest = | |
| 524 | | LoadIndexWorkerRequest | |
| 525 | | TextSearchWorkerRequest | |
| 526 | | UrlSearchWorkerRequest | |
| 527 | ||
| 543 | 528 | const activePageFilter = ref<string | null>(null) |
| 529 | const searchWorkerReady = ref(false) | |
| 530 | const searchWorkerConfigKey = computed(() => | |
| 531 | JSON.stringify(getMiniSearchWorkerConfig()) | |
| 532 | ) | |
| 533 | let searchWorker: Worker | undefined | |
| 534 | let searchWorkerRequestId = 0 | |
| 535 | let loadedWorkerIndexKey = '' | |
| 536 | const searchWorkerRequests = new Map< | |
| 537 | number, | |
| 538 | { | |
| 539 | resolve: (value: unknown) => void | |
| 540 | reject: (reason?: unknown) => void | |
| 541 | } | |
| 542 | >() | |
| 543 | ||
| 544 | function getPageOrderEntries(): [string, number][] { | |
| 545 | return [...pageMeta.entries()].map(([key, meta]) => [key, meta.order]) | |
| 546 | } | |
| 547 | ||
| 548 | function stripNonCloneable(value: unknown): unknown { | |
| 549 | if (typeof value === 'function' || typeof value === 'symbol') return undefined | |
| 550 | if (!value || typeof value !== 'object') return value | |
| 551 | if (Array.isArray(value)) { | |
| 552 | return value | |
| 553 | .map((item) => stripNonCloneable(item)) | |
| 554 | .filter((item) => item !== undefined) | |
| 555 | } | |
| 556 | ||
| 557 | const out: Record<string, unknown> = {} | |
| 558 | for (const [key, nestedValue] of Object.entries(value)) { | |
| 559 | const cloneable = stripNonCloneable(nestedValue) | |
| 560 | if (cloneable !== undefined) out[key] = cloneable | |
| 561 | } | |
| 562 | return out | |
| 563 | } | |
| 564 | ||
| 565 | function getMiniSearchWorkerConfig() { | |
| 566 | const miniSearch = theme.value.search?.provider === 'local' | |
| 567 | ? theme.value.search.options?.miniSearch | |
| 568 | : undefined | |
| 569 | const rawSearchOptions = miniSearch?.searchOptions as | |
| 570 | | Record<string, unknown> | |
| 571 | | undefined | |
| 572 | ||
| 573 | return { | |
| 574 | options: stripNonCloneable(miniSearch?.options) as | |
| 575 | | Record<string, unknown> | |
| 576 | | undefined, | |
| 577 | searchOptions: stripNonCloneable(rawSearchOptions) as | |
| 578 | | Record<string, unknown> | |
| 579 | | undefined, | |
| 580 | useDefaultBoostDocument: | |
| 581 | typeof rawSearchOptions?.boostDocument === 'function' | |
| 582 | } | |
| 583 | } | |
| 584 | ||
| 585 | function ensureSearchWorker() { | |
| 586 | if (!inBrowser || searchWorker) return searchWorker | |
| 587 | ||
| 588 | try { | |
| 589 | searchWorker = new Worker( | |
| 590 | new URL('../workers/searchWorker.ts', import.meta.url), | |
| 591 | { | |
| 592 | type: 'module' | |
| 593 | } | |
| 594 | ) | |
| 595 | } catch (error) { | |
| 596 | console.error('[search] failed to start search worker', error) | |
| 597 | return | |
| 598 | } | |
| 544 | 599 | |
| 545 | const docOrder = computed(() => { | |
| 546 | const map = new Map<string, number>() | |
| 547 | const index = searchIndex.value as any | |
| 548 | if (!index) return map | |
| 549 | // _documentIds maps internalDocId -> original id, in insertion order. | |
| 550 | const ids = index._documentIds | |
| 551 | if (ids instanceof Map) { | |
| 552 | let i = 0 | |
| 553 | for (const originalId of ids.values()) { | |
| 554 | map.set(String(originalId), i++) | |
| 600 | searchWorker.onmessage = (event: MessageEvent) => { | |
| 601 | const data = event.data as { | |
| 602 | id: number | |
| 603 | type: string | |
| 604 | payload?: unknown | |
| 605 | error?: string | |
| 555 | 606 | } |
| 556 | } else if (ids && typeof ids === 'object') { | |
| 557 | // Some versions store it as a plain object keyed by numeric doc id. | |
| 558 | const keys = Object.keys(ids) | |
| 559 | .map(Number) | |
| 560 | .sort((a, b) => a - b) | |
| 561 | let i = 0 | |
| 562 | for (const k of keys) { | |
| 563 | map.set(String(ids[k]), i++) | |
| 607 | const request = searchWorkerRequests.get(data.id) | |
| 608 | if (!request) return | |
| 609 | ||
| 610 | searchWorkerRequests.delete(data.id) | |
| 611 | if (data.type.endsWith(':error')) { | |
| 612 | request.reject(new Error(data.error ?? 'Search worker failed')) | |
| 613 | } else { | |
| 614 | request.resolve(data.payload) | |
| 564 | 615 | } |
| 565 | 616 | } |
| 566 | return map | |
| 567 | }) | |
| 617 | searchWorker.onerror = (event) => { | |
| 618 | console.error('[search] search worker error', event) | |
| 619 | } | |
| 620 | searchWorkerReady.value = true | |
| 621 | return searchWorker | |
| 622 | } | |
| 623 | ||
| 624 | function postSearchWorker<T>(message: SearchWorkerRequest) { | |
| 625 | const worker = ensureSearchWorker() | |
| 626 | if (!worker) return Promise.reject(new Error('Search worker is unavailable')) | |
| 568 | 627 | |
| 569 | function getDocOrder(id: string) { | |
| 570 | return docOrder.value.get(id) ?? Number.MAX_SAFE_INTEGER | |
| 628 | const id = ++searchWorkerRequestId | |
| 629 | return new Promise<T>((resolve, reject) => { | |
| 630 | searchWorkerRequests.set(id, { | |
| 631 | resolve: (value) => resolve(value as T), | |
| 632 | reject | |
| 633 | }) | |
| 634 | worker.postMessage({ ...message, id }) | |
| 635 | }) | |
| 571 | 636 | } |
| 572 | 637 | |
| 638 | onMounted(() => { | |
| 639 | ensureSearchWorker() | |
| 640 | }) | |
| 641 | ||
| 642 | onBeforeUnmount(() => { | |
| 643 | searchWorker?.terminate() | |
| 644 | searchWorker = undefined | |
| 645 | loadedWorkerIndexKey = '' | |
| 646 | searchWorkerReady.value = false | |
| 647 | for (const request of searchWorkerRequests.values()) { | |
| 648 | request.reject(new Error('Search worker was terminated')) | |
| 649 | } | |
| 650 | searchWorkerRequests.clear() | |
| 651 | }) | |
| 652 | ||
| 653 | watch( | |
| 654 | () => | |
| 655 | [ | |
| 656 | searchWorkerReady.value, | |
| 657 | urlSearchMode.value, | |
| 658 | urlFilterDebounced.value | |
| 659 | ] as const, | |
| 660 | async ([ready, active, query], _old, onCleanup) => { | |
| 661 | let canceled = false | |
| 662 | onCleanup(() => { | |
| 663 | canceled = true | |
| 664 | }) | |
| 665 | ||
| 666 | if (!active || !query.trim()) { | |
| 667 | urlMatches.value = [] | |
| 668 | urlPageGroupCounts.value = [] | |
| 669 | return | |
| 670 | } | |
| 671 | if (!ready) return | |
| 672 | ||
| 673 | try { | |
| 674 | const payload = await postSearchWorker<UrlSearchWorkerPayload>({ | |
| 675 | type: 'url-search', | |
| 676 | query, | |
| 677 | pageOrderEntries: getPageOrderEntries() | |
| 678 | }) | |
| 679 | if (canceled) return | |
| 680 | urlMatches.value = payload.matches | |
| 681 | urlPageGroupCounts.value = payload.pageGroups | |
| 682 | } catch (error) { | |
| 683 | if (!canceled) { | |
| 684 | console.error('[search] URL search worker request failed', error) | |
| 685 | urlMatches.value = [] | |
| 686 | urlPageGroupCounts.value = [] | |
| 687 | } | |
| 688 | } | |
| 689 | }, | |
| 690 | { immediate: true } | |
| 691 | ) | |
| 692 | ||
| 573 | 693 | function getPageKey(id: string) { |
| 574 | 694 | return id.split('#')[0].replace(/\/$/, '') |
| 575 | 695 | } |
| @@ -893,18 +1013,34 @@ function buildDocExcerpt( | ||
| 893 | 1013 | watchDebounced( |
| 894 | 1014 | () => |
| 895 | 1015 | [ |
| 896 | searchIndex.value, | |
| 1016 | searchWorkerReady.value, | |
| 1017 | localeIndex.value, | |
| 1018 | searchIndexVersion.value, | |
| 1019 | searchWorkerConfigKey.value, | |
| 897 | 1020 | filterText.value, |
| 898 | 1021 | showDetailedList.value, |
| 899 | 1022 | searchMode.value |
| 900 | 1023 | ] as const, |
| 901 | 1024 | async ( |
| 902 | [index, filterTextValue, showDetailedListValue, mode], | |
| 1025 | [ | |
| 1026 | ready, | |
| 1027 | localeIndexValue, | |
| 1028 | indexVersion, | |
| 1029 | configKey, | |
| 1030 | filterTextValue, | |
| 1031 | showDetailedListValue, | |
| 1032 | mode | |
| 1033 | ], | |
| 903 | 1034 | old, |
| 904 | 1035 | onCleanup |
| 905 | 1036 | ) => { |
| 906 | if (old?.[0] !== index) { | |
| 907 | // in case of hmr | |
| 1037 | if ( | |
| 1038 | old?.[1] !== localeIndexValue || | |
| 1039 | old?.[2] !== indexVersion || | |
| 1040 | old?.[3] !== configKey | |
| 1041 | ) { | |
| 1042 | // Locale/config changes rebuild the worker index, so cached excerpts may no | |
| 1043 | // longer match the active result set. | |
| 908 | 1044 | cache.clear() |
| 909 | 1045 | } |
| 910 | 1046 | |
| @@ -913,35 +1049,55 @@ watchDebounced( | ||
| 913 | 1049 | canceled = true |
| 914 | 1050 | }) |
| 915 | 1051 | |
| 916 | if (!index) return | |
| 1052 | if (!ready) return | |
| 917 | 1053 | |
| 918 | 1054 | // In URL search mode, skip normal text search |
| 919 | 1055 | if (mode === 'url') { |
| 920 | 1056 | results.value = [] |
| 1057 | currentTerms.value = new Set() | |
| 921 | 1058 | enableNoResults.value = true |
| 922 | 1059 | return |
| 923 | 1060 | } |
| 924 | 1061 | |
| 925 | // Dynamic search options based on matchExact toggle | |
| 926 | const dynamicSearchOptions = { | |
| 927 | fuzzy: mode === 'fuzzy' ? (0.3 as number | false) : false, | |
| 928 | prefix: mode === 'fuzzy' ? (term: string) => term.length > 3 : false, | |
| 929 | maxFuzzy: mode === 'fuzzy' ? 1 : 0, | |
| 930 | boost: { title: 10, titles: 4, text: 1 } | |
| 931 | } | |
| 1062 | let workerPayload: TextSearchWorkerPayload | |
| 1063 | try { | |
| 1064 | const workerIndexKey = | |
| 1065 | `${localeIndexValue}\n${indexVersion}\n${configKey}` | |
| 1066 | if (loadedWorkerIndexKey !== workerIndexKey) { | |
| 1067 | const indexJson = (await searchIndexData.value[localeIndexValue]?.()) | |
| 1068 | ?.default | |
| 1069 | if (canceled) return | |
| 1070 | await postSearchWorker<void>({ | |
| 1071 | type: 'load-index', | |
| 1072 | localeIndex: localeIndexValue, | |
| 1073 | indexJson, | |
| 1074 | indexVersion, | |
| 1075 | config: getMiniSearchWorkerConfig() | |
| 1076 | }) | |
| 1077 | if (canceled) return | |
| 1078 | loadedWorkerIndexKey = workerIndexKey | |
| 1079 | } | |
| 932 | 1080 | |
| 933 | // Search | |
| 934 | const ranked = index.search( | |
| 935 | filterTextValue, | |
| 936 | dynamicSearchOptions | |
| 937 | ) as (SearchResult & Result)[] | |
| 1081 | workerPayload = await postSearchWorker<TextSearchWorkerPayload>({ | |
| 1082 | type: 'text-search', | |
| 1083 | query: filterTextValue, | |
| 1084 | mode, | |
| 1085 | pageOrderEntries: getPageOrderEntries() | |
| 1086 | }) | |
| 1087 | } catch (error) { | |
| 1088 | if (!canceled) { | |
| 1089 | console.error('[search] text search worker request failed', error) | |
| 1090 | results.value = [] | |
| 1091 | currentTerms.value = new Set() | |
| 1092 | enableNoResults.value = true | |
| 1093 | } | |
| 1094 | return | |
| 1095 | } | |
| 1096 | if (canceled) return | |
| 938 | 1097 | |
| 939 | const top = ranked.slice(0, 50) | |
| 940 | const seen = new Set(top.map((r) => r.id)) | |
| 941 | const titleHits = ranked.filter( | |
| 942 | (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0 | |
| 943 | ) | |
| 944 | const _result = [...top, ...titleHits] as (SearchResult & Result)[] | |
| 1098 | const _result = workerPayload.results | |
| 1099 | const terms = new Set(workerPayload.terms) | |
| 1100 | currentTerms.value = terms | |
| 945 | 1101 | enableNoResults.value = true |
| 946 | 1102 | |
| 947 | 1103 | if (!_result.length) { |
| @@ -949,26 +1105,12 @@ watchDebounced( | ||
| 949 | 1105 | return |
| 950 | 1106 | } |
| 951 | 1107 | |
| 952 | // Collect highlight terms up front (cheap — no rendering needed). | |
| 953 | const terms = new Set<string>() | |
| 954 | for (const r of _result) { | |
| 955 | for (const term in r.match) terms.add(term) | |
| 956 | } | |
| 957 | currentTerms.value = terms | |
| 958 | ||
| 959 | 1108 | const toRows = (list: (SearchResult & Result)[]) => |
| 960 | list | |
| 961 | .map((r) => { | |
| 962 | const [id, anchor] = r.id.split('#') | |
| 963 | const map = cache.get(`${id}\n${filterTextValue}`) | |
| 964 | return { ...r, text: map?.get(anchor) ?? '' } | |
| 965 | }) | |
| 966 | .sort((a, b) => { | |
| 967 | const pageDiff = getPageOrder(getPageKey(a.id)) - | |
| 968 | getPageOrder(getPageKey(b.id)) | |
| 969 | if (pageDiff !== 0) return pageDiff | |
| 970 | return getDocOrder(a.id) - getDocOrder(b.id) | |
| 971 | }) | |
| 1109 | list.map((r) => { | |
| 1110 | const [id, anchor] = r.id.split('#') | |
| 1111 | const map = cache.get(`${id}\n${filterTextValue}`) | |
| 1112 | return { ...r, text: map?.get(anchor) ?? '' } | |
| 1113 | }) | |
| 972 | 1114 | |
| 973 | 1115 | const highlight = () => |
| 974 | 1116 | new Promise<void>((resolve) => { |
docs/.vitepress/theme/workers/searchWorker.ts added +276
| @@ -0,0 +1,276 @@ | ||
| 1 | import MiniSearch, { | |
| 2 | type Options, | |
| 3 | type SearchOptions, | |
| 4 | type SearchResult | |
| 5 | } from 'minisearch' | |
| 6 | ||
| 7 | import type { PageLink } from '../../plugins/urlSearchPlugin' | |
| 8 | ||
| 9 | interface Result { | |
| 10 | title: string | |
| 11 | titles: string[] | |
| 12 | text?: string | |
| 13 | } | |
| 14 | ||
| 15 | type SearchMode = 'exact' | 'fuzzy' | 'url' | |
| 16 | ||
| 17 | type PlainRecord = Record<string, unknown> | |
| 18 | ||
| 19 | interface SearchConfig { | |
| 20 | options?: PlainRecord | |
| 21 | searchOptions?: PlainRecord | |
| 22 | useDefaultBoostDocument?: boolean | |
| 23 | } | |
| 24 | ||
| 25 | interface PageGroupCount { | |
| 26 | key: string | |
| 27 | count: number | |
| 28 | } | |
| 29 | ||
| 30 | interface LoadIndexRequest { | |
| 31 | type: 'load-index' | |
| 32 | id: number | |
| 33 | localeIndex: string | |
| 34 | indexJson: unknown | |
| 35 | indexVersion: number | |
| 36 | config: SearchConfig | |
| 37 | } | |
| 38 | ||
| 39 | interface TextSearchRequest { | |
| 40 | type: 'text-search' | |
| 41 | id: number | |
| 42 | query: string | |
| 43 | mode: SearchMode | |
| 44 | pageOrderEntries: [string, number][] | |
| 45 | } | |
| 46 | ||
| 47 | interface UrlSearchRequest { | |
| 48 | type: 'url-search' | |
| 49 | id: number | |
| 50 | query: string | |
| 51 | pageOrderEntries: [string, number][] | |
| 52 | } | |
| 53 | ||
| 54 | type SearchWorkerRequest = | |
| 55 | | LoadIndexRequest | |
| 56 | | TextSearchRequest | |
| 57 | | UrlSearchRequest | |
| 58 | ||
| 59 | type WorkerSearchResult = SearchResult & Result | |
| 60 | ||
| 61 | let searchIndex: MiniSearch<Result> | null = null | |
| 62 | let searchIndexKey = '' | |
| 63 | let urlLinks: PageLink[] = [] | |
| 64 | let urlLinksPromise: Promise<void> | null = null | |
| 65 | let pageOrder = new Map<string, number>() | |
| 66 | let docOrder = new Map<string, number>() | |
| 67 | ||
| 68 | function defaultBoostDocument( | |
| 69 | _: string, | |
| 70 | term: string, | |
| 71 | storedFields: Record<string, string | string[]> | |
| 72 | ) { | |
| 73 | const titles = ((storedFields?.titles as string[] | undefined) ?? []) | |
| 74 | .filter((t) => Boolean(t)) | |
| 75 | .map((t) => t.toLowerCase()) | |
| 76 | const titleIndex = titles | |
| 77 | .map((t, i) => (t?.includes(term) ? i : -1)) | |
| 78 | .find((i) => i >= 0) ?? -1 | |
| 79 | if (titleIndex >= 0) return 10000 - titleIndex | |
| 80 | return 1 | |
| 81 | } | |
| 82 | ||
| 83 | function stableStringify(value: unknown): string { | |
| 84 | if (value === null || typeof value !== 'object') return JSON.stringify(value) | |
| 85 | if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]` | |
| 86 | const object = value as Record<string, unknown> | |
| 87 | return `{${ | |
| 88 | Object.keys(object).sort().map((key) => | |
| 89 | `${JSON.stringify(key)}:${stableStringify(object[key])}` | |
| 90 | ).join(',') | |
| 91 | }}` | |
| 92 | } | |
| 93 | ||
| 94 | function setPageOrder(entries: [string, number][]) { | |
| 95 | pageOrder = new Map(entries) | |
| 96 | } | |
| 97 | ||
| 98 | function getPageKey(id: string) { | |
| 99 | return id.split('#')[0].replace(/\/$/, '') | |
| 100 | } | |
| 101 | ||
| 102 | function getPageOrder(key: string) { | |
| 103 | return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER | |
| 104 | } | |
| 105 | ||
| 106 | function getDocOrder(id: string) { | |
| 107 | return docOrder.get(id) ?? Number.MAX_SAFE_INTEGER | |
| 108 | } | |
| 109 | ||
| 110 | function compareByPageAndDoc(a: { id: unknown }, b: { id: unknown }) { | |
| 111 | const aId = String(a.id) | |
| 112 | const bId = String(b.id) | |
| 113 | const pageDiff = getPageOrder(getPageKey(aId)) - getPageOrder(getPageKey(bId)) | |
| 114 | if (pageDiff !== 0) return pageDiff | |
| 115 | return getDocOrder(aId) - getDocOrder(bId) | |
| 116 | } | |
| 117 | ||
| 118 | function rebuildDocOrder(index: MiniSearch<Result>) { | |
| 119 | const map = new Map<string, number>() | |
| 120 | const ids = (index as any)._documentIds | |
| 121 | if (ids instanceof Map) { | |
| 122 | let i = 0 | |
| 123 | for (const originalId of ids.values()) { | |
| 124 | map.set(String(originalId), i++) | |
| 125 | } | |
| 126 | } else if (ids && typeof ids === 'object') { | |
| 127 | const keys = Object.keys(ids) | |
| 128 | .map(Number) | |
| 129 | .sort((a, b) => a - b) | |
| 130 | let i = 0 | |
| 131 | for (const key of keys) { | |
| 132 | map.set(String(ids[key]), i++) | |
| 133 | } | |
| 134 | } | |
| 135 | docOrder = map | |
| 136 | } | |
| 137 | ||
| 138 | async function loadSearchIndex( | |
| 139 | localeIndex: string, | |
| 140 | indexVersion: number, | |
| 141 | indexJson: unknown, | |
| 142 | config: SearchConfig | |
| 143 | ) { | |
| 144 | const key = `${localeIndex}\n${indexVersion}\n${stableStringify(config)}` | |
| 145 | if (searchIndex && searchIndexKey === key) return | |
| 146 | ||
| 147 | const searchOptions = { | |
| 148 | boost: { title: 10, titles: 4, text: 1 }, | |
| 149 | ...(config.searchOptions ?? {}), | |
| 150 | ...(config.useDefaultBoostDocument | |
| 151 | ? { boostDocument: defaultBoostDocument } | |
| 152 | : {}) | |
| 153 | } as SearchOptions | |
| 154 | ||
| 155 | searchIndex = MiniSearch.loadJSON<Result>( | |
| 156 | indexJson as any, | |
| 157 | { | |
| 158 | fields: ['title', 'titles', 'text'], | |
| 159 | storeFields: ['title', 'titles'], | |
| 160 | searchOptions, | |
| 161 | ...(config.options ?? {}) | |
| 162 | } as Options<Result> | |
| 163 | ) | |
| 164 | searchIndexKey = key | |
| 165 | rebuildDocOrder(searchIndex) | |
| 166 | } | |
| 167 | ||
| 168 | async function textSearch(message: TextSearchRequest) { | |
| 169 | setPageOrder(message.pageOrderEntries) | |
| 170 | if (!searchIndex) throw new Error('Search index has not been loaded') | |
| 171 | ||
| 172 | const dynamicSearchOptions = { | |
| 173 | fuzzy: message.mode === 'fuzzy' ? (0.3 as number | false) : false, | |
| 174 | prefix: message.mode === 'fuzzy' | |
| 175 | ? (term: string) => term.length > 3 | |
| 176 | : false, | |
| 177 | maxFuzzy: message.mode === 'fuzzy' ? 1 : 0, | |
| 178 | boost: { title: 10, titles: 4, text: 1 } | |
| 179 | } as SearchOptions | |
| 180 | ||
| 181 | const ranked = searchIndex.search( | |
| 182 | message.query, | |
| 183 | dynamicSearchOptions | |
| 184 | ) as WorkerSearchResult[] | |
| 185 | ||
| 186 | const top = ranked.slice(0, 50) | |
| 187 | const seen = new Set(top.map((r) => r.id)) | |
| 188 | const titleHits = ranked.filter( | |
| 189 | (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0 | |
| 190 | ) | |
| 191 | const results = [...top, ...titleHits].sort(compareByPageAndDoc) | |
| 192 | const terms = new Set<string>() | |
| 193 | for (const result of results) { | |
| 194 | for (const term in result.match) terms.add(term) | |
| 195 | } | |
| 196 | ||
| 197 | return { | |
| 198 | results, | |
| 199 | terms: [...terms] | |
| 200 | } | |
| 201 | } | |
| 202 | ||
| 203 | async function ensureUrlLinks() { | |
| 204 | if (urlLinks.length > 0) return | |
| 205 | if (urlLinksPromise) { | |
| 206 | await urlLinksPromise | |
| 207 | return | |
| 208 | } | |
| 209 | ||
| 210 | urlLinksPromise = fetch('/url-search-index.json') | |
| 211 | .then((r) => r.json()) | |
| 212 | .then((data: PageLink[]) => { | |
| 213 | data.sort((a, b) => getPageOrder(a.pageId) - getPageOrder(b.pageId)) | |
| 214 | urlLinks = data | |
| 215 | }) | |
| 216 | .catch(() => { | |
| 217 | urlLinks = [] | |
| 218 | }) | |
| 219 | .finally(() => { | |
| 220 | urlLinksPromise = null | |
| 221 | }) | |
| 222 | await urlLinksPromise | |
| 223 | } | |
| 224 | ||
| 225 | async function urlSearch(message: UrlSearchRequest) { | |
| 226 | setPageOrder(message.pageOrderEntries) | |
| 227 | await ensureUrlLinks() | |
| 228 | ||
| 229 | const query = message.query.trim().toLowerCase() | |
| 230 | if (!query) return { matches: [], pageGroups: [] } | |
| 231 | ||
| 232 | const matches: PageLink[] = [] | |
| 233 | const pageGroups = new Map<string, PageGroupCount>() | |
| 234 | for (const link of urlLinks) { | |
| 235 | if (!link.href.toLowerCase().includes(query)) continue | |
| 236 | ||
| 237 | matches.push(link) | |
| 238 | const existing = pageGroups.get(link.pageId) | |
| 239 | if (existing) existing.count++ | |
| 240 | else pageGroups.set(link.pageId, { key: link.pageId, count: 1 }) | |
| 241 | } | |
| 242 | ||
| 243 | return { | |
| 244 | matches, | |
| 245 | pageGroups: [...pageGroups.values()].sort( | |
| 246 | (a, b) => getPageOrder(a.key) - getPageOrder(b.key) | |
| 247 | ) | |
| 248 | } | |
| 249 | } | |
| 250 | ||
| 251 | self.onmessage = async (event: MessageEvent<SearchWorkerRequest>) => { | |
| 252 | const message = event.data | |
| 253 | try { | |
| 254 | const payload = message.type === 'load-index' | |
| 255 | ? await loadSearchIndex( | |
| 256 | message.localeIndex, | |
| 257 | message.indexVersion, | |
| 258 | message.indexJson, | |
| 259 | message.config | |
| 260 | ) | |
| 261 | : message.type === 'text-search' | |
| 262 | ? await textSearch(message) | |
| 263 | : await urlSearch(message) | |
| 264 | self.postMessage({ | |
| 265 | type: `${message.type}:success`, | |
| 266 | id: message.id, | |
| 267 | payload | |
| 268 | }) | |
| 269 | } catch (error) { | |
| 270 | self.postMessage({ | |
| 271 | type: `${message.type}:error`, | |
| 272 | id: message.id, | |
| 273 | error: error instanceof Error ? error.message : String(error) | |
| 274 | }) | |
| 275 | } | |
| 276 | } | |