docs/.vitepress/theme/components/search/utils.ts
168 lines · 5033 bytes
1import type { SearchResult } from 'minisearch'
2import type { SearchSortMode } from '../../searchState'
3import type { Result, UrlResult } from './types'
4
5// @ts-ignore
6import { escapeRegExp } from 'vitepress/dist/client/shared'
7
8export function escapeHtml(value: string) {
9 return value
10 .replace(/&/g, '&')
11 .replace(/</g, '<')
12 .replace(/>/g, '>')
13 .replace(/\"/g, '"')
14 .replace(/'/g, ''')
15}
16
17export function highlightUrl(url: string, query: string) {
18 const needle = query.trim()
19 if (!needle) return escapeHtml(url)
20
21 const lowerUrl = url.toLowerCase()
22 const lowerNeedle = needle.toLowerCase()
23 let out = ''
24 let cursor = 0
25 let index = lowerUrl.indexOf(lowerNeedle)
26
27 while (index !== -1) {
28 out += escapeHtml(url.slice(cursor, index))
29 out += `<mark class="url-highlight">${
30 escapeHtml(url.slice(index, index + needle.length))
31 }</mark>`
32 cursor = index + needle.length
33 index = lowerUrl.indexOf(lowerNeedle, cursor)
34 }
35
36 return out + escapeHtml(url.slice(cursor))
37}
38
39export function formMarkRegex(terms: Set<string>) {
40 return new RegExp(
41 [...terms]
42 .sort((a, b) => b.length - a.length)
43 .map((term) => `(${escapeRegExp(term)})`)
44 .join('|'),
45 'gi'
46 )
47}
48
49export function decodeHtml(html: string): string {
50 const txt = document.createElement('textarea')
51 txt.innerHTML = html
52 return txt.value
53}
54
55export function toHistoryPathHtml(html: string): string {
56 const stripped = decodeHtml(html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim())
57 if (stripped) return escapeHtml(stripped)
58 return html.trim()
59}
60
61export function hasExcerptPreview(html?: string) {
62 if (!html) return false
63 for (let i = 0; i < html.length; i++) {
64 const ch = html[i]
65 if (ch === '<') {
66 const close = html.indexOf('>', i + 1)
67 if (close === -1) return false
68 i = close
69 continue
70 }
71 if (ch === '&') {
72 const entity = html.slice(i, i + 6).toLowerCase()
73 if (entity === ' ' || entity === ' ') {
74 i += 5
75 continue
76 }
77 return true
78 }
79 if (!/\s/.test(ch)) return true
80 }
81 return false
82}
83
84export function getPageKey(id: string) {
85 return getDocId(id).replace(/\/$/, '')
86}
87
88export function getDocId(id: string) {
89 const hashIndex = id.indexOf('#')
90 return hashIndex === -1 ? id : id.slice(0, hashIndex)
91}
92
93export function getDocAnchor(id: string) {
94 const hashIndex = id.indexOf('#')
95 return hashIndex === -1 ? '' : id.slice(hashIndex + 1)
96}
97
98export function getPageLabel(key: string, pageMeta: Map<string, { label: string; order: number }>) {
99 return pageMeta.get(key)?.label ?? key.replace(/^\//, '')
100}
101
102export function getPageOrder(key: string, pageMeta: Map<string, { label: string; order: number }>) {
103 return pageMeta.get(key)?.order ?? Number.MAX_SAFE_INTEGER
104}
105
106export function buildResultHref(pageId: string, tabs?: string[], anchor = '') {
107 const params: string[] = []
108 if (tabs?.length) {
109 params.push(`t=${tabs.map((tab) => encodeURIComponent(tab)).join(',')}`)
110 }
111
112 let hash = ''
113 if (anchor.startsWith('collapsible-')) {
114 const collapsible = anchor.slice('collapsible-'.length)
115 if (collapsible) params.push(`c=${encodeURIComponent(collapsible)}`)
116 } else {
117 const lastTab = tabs?.length ? tabs[tabs.length - 1] : ''
118 const isRedundantTabHeading = Boolean(anchor) && anchor === `tab-${lastTab}`
119 if (anchor && !isRedundantTabHeading) {
120 hash = `#${encodeURIComponent(anchor)}`
121 }
122 }
123
124 const query = params.length ? `?${params.join('&')}` : ''
125 return `${pageId}${query}${hash}`
126}
127
128export function getSearchResultHref(item: SearchResult & Result) {
129 const id = String(item.id)
130 const hashIndex = id.indexOf('#')
131 if (hashIndex < 0) return buildResultHref(id, item.tabs)
132
133 return buildResultHref(
134 id.slice(0, hashIndex),
135 item.tabs,
136 id.slice(hashIndex + 1)
137 )
138}
139
140export function cycleSearchMode(searchMode: { value: SearchSortMode }) {
141 const modes = ['exact', 'fuzzy', 'url'] as const
142 const idx = modes.indexOf(searchMode.value as 'exact' | 'fuzzy' | 'url')
143 searchMode.value = modes[(idx + 1) % modes.length] as SearchSortMode
144}
145
146export function stripNonCloneable(value: unknown): unknown {
147 if (typeof value === 'function' || typeof value === 'symbol') return undefined
148 if (!value || typeof value !== 'object') return value
149 if (Array.isArray(value)) {
150 return value
151 .map((item) => stripNonCloneable(item))
152 .filter((item) => item !== undefined)
153 }
154
155 const out: Record<string, unknown> = {}
156 for (const [key, nestedValue] of Object.entries(value)) {
157 const cloneable = stripNonCloneable(nestedValue)
158 if (cloneable !== undefined) out[key] = cloneable
159 }
160 return out
161}
162
163export function getPageOrderEntries(pageMeta: Map<string, { label: string; order: number }>): [string, number][] {
164 return [...pageMeta.entries()].map(([key, meta]) => [key, meta.order])
165}
166
167export const nextFrame = () =>
168 new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))