docs/.vitepress/theme/components/search/utils.ts

177 lines · 5174 bytes

17 symbols in this file
  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, '&lt;')
 12    .replace(/>/g, '&gt;')
 13    .replace(/\"/g, '&quot;')
 14    .replace(/'/g, '&#39;')
 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 === '&nbsp;' || entity === '&#160;') {
 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(
107  pageId: string,
108  tabs?: string[],
109  anchor = '',
110  tables?: string[]
111) {
112  const params: string[] = []
113  if (tabs?.length) {
114    params.push(`t=${tabs.map((tab) => encodeURIComponent(tab)).join(',')}`)
115  }
116
117  let hash = ''
118  if (anchor.startsWith('collapsible-')) {
119    const collapsible = anchor.slice('collapsible-'.length)
120    if (collapsible) params.push(`c=${encodeURIComponent(collapsible)}`)
121  } else {
122    const lastTab = tabs?.length ? tabs[tabs.length - 1] : ''
123    const isRedundantTabHeading = Boolean(anchor) && anchor === `tab-${lastTab}`
124    if (anchor && !isRedundantTabHeading) {
125      hash = `#${encodeURIComponent(anchor)}`
126    }
127  }
128
129  if (tables?.length) {
130    params.push(`m=${tables.map((table) => encodeURIComponent(table)).join(',')}`)
131  }
132
133  const query = params.length ? `?${params.join('&')}` : ''
134  return `${pageId}${query}${hash}`
135}
136
137export function getSearchResultHref(item: SearchResult & Result) {
138  const id = String(item.id)
139  const hashIndex = id.indexOf('#')
140  if (hashIndex < 0) return buildResultHref(id, item.tabs)
141
142  return buildResultHref(
143    id.slice(0, hashIndex),
144    item.tabs,
145    id.slice(hashIndex + 1)
146  )
147}
148
149export function cycleSearchMode(searchMode: { value: SearchSortMode }) {
150  const modes = ['exact', 'fuzzy', 'url'] as const
151  const idx = modes.indexOf(searchMode.value as 'exact' | 'fuzzy' | 'url')
152  searchMode.value = modes[(idx + 1) % modes.length] as SearchSortMode
153}
154
155export function stripNonCloneable(value: unknown): unknown {
156  if (typeof value === 'function' || typeof value === 'symbol') return undefined
157  if (!value || typeof value !== 'object') return value
158  if (Array.isArray(value)) {
159    return value
160      .map((item) => stripNonCloneable(item))
161      .filter((item) => item !== undefined)
162  }
163
164  const out: Record<string, unknown> = {}
165  for (const [key, nestedValue] of Object.entries(value)) {
166    const cloneable = stripNonCloneable(nestedValue)
167    if (cloneable !== undefined) out[key] = cloneable
168  }
169  return out
170}
171
172export function getPageOrderEntries(pageMeta: Map<string, { label: string; order: number }>): [string, number][] {
173  return [...pageMeta.entries()].map(([key, meta]) => [key, meta.order])
174}
175
176export const nextFrame = () =>
177  new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))