index.vue 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <script lang="ts">
  2. export default {
  3. name: "Search",
  4. };
  5. </script>
  6. <script setup lang="ts">
  7. import { ref, computed, watch, shallowRef, markRaw, nextTick } from "vue";
  8. import Mark from 'mark.js/src/vanilla.js'
  9. import localSearchIndex from '@localSearchIndex'
  10. import MiniSearch, { type SearchResult } from 'minisearch'
  11. import { Search } from "@element-plus/icons-vue";
  12. import { watchDebounced, useFocus, computedAsync } from "@vueuse/core";
  13. import { useI18n } from "vue-i18n";
  14. import { useData } from 'vitepress'
  15. import { LRUCache } from 'vitepress/dist/client/theme-default/support/lru'
  16. import { pathToFile } from 'vitepress/dist/client/app/utils'
  17. import { escapeRegExp } from 'vitepress/dist/client/shared'
  18. import _ from "lodash";
  19. const { t } = useI18n();
  20. /* Search */
  21. const searchIndexData = shallowRef(localSearchIndex)
  22. // hmr
  23. if (import.meta.hot) {
  24. import.meta.hot.accept('/@localSearchIndex', (m) => {
  25. if (m) {
  26. searchIndexData.value = m.default
  27. }
  28. })
  29. }
  30. interface Result {
  31. title: string
  32. titles: string[]
  33. text?: string
  34. }
  35. const vitePressData = useData()
  36. const { localeIndex, theme } = vitePressData
  37. const searchIndex = computedAsync(async () =>
  38. markRaw(
  39. MiniSearch.loadJSON<Result>(
  40. (await searchIndexData.value[localeIndex.value]?.())?.default,
  41. {
  42. fields: ['title', 'titles', 'text'],
  43. storeFields: ['title', 'titles'],
  44. searchOptions: {
  45. fuzzy: 0.2,
  46. prefix: true,
  47. boost: { title: 4, text: 2, titles: 1 },
  48. ...(theme.value.search?.provider === 'local' &&
  49. theme.value.search.options?.miniSearch?.searchOptions)
  50. },
  51. ...(theme.value.search?.provider === 'local' &&
  52. theme.value.search.options?.miniSearch?.options)
  53. }
  54. )
  55. )
  56. )
  57. const filterText = ref("");
  58. const input$ = ref();
  59. const { focused } = useFocus(computed(() => input$.value?.input));
  60. const results = shallowRef<(SearchResult & Result)[]>([])
  61. const loading = ref(false);
  62. const suggestionVisible = computed(() => {
  63. // TEST
  64. // return true
  65. const isValidData = results.value.length > 0;
  66. return !!( focused.value && (isValidData || loading.value || filterText.value) );
  67. });
  68. const resultsEl = shallowRef<HTMLElement>()
  69. const mark = computedAsync(async () => {
  70. if (!resultsEl.value) return
  71. return markRaw(new Mark(resultsEl.value))
  72. }, null)
  73. function formMarkRegex(terms: Set<string>) {
  74. return new RegExp(
  75. [...terms]
  76. .sort((a, b) => b.length - a.length)
  77. .map((term) => `(${escapeRegExp(term)})`)
  78. .join('|'),
  79. 'gi'
  80. )
  81. }
  82. watch(() => filterText.value, () => {
  83. if (!results.value.length) {
  84. loading.value = true
  85. }
  86. })
  87. watchDebounced(
  88. () => [searchIndex.value, filterText.value] as const,
  89. async ([index, filterTextValue], old, onCleanup) => {
  90. let canceled = false
  91. onCleanup(() => {
  92. canceled = true
  93. })
  94. if (!index) return
  95. // Search
  96. results.value = index
  97. .search(filterTextValue)
  98. .slice(0, 16) as (SearchResult & Result)[]
  99. console.log(results.value)
  100. // enableNoResults.value = true
  101. const terms = new Set<string>()
  102. results.value = results.value.map((r) => {
  103. for (const term in r.match) {
  104. terms.add(term)
  105. }
  106. return r
  107. })
  108. loading.value = false
  109. await nextTick()
  110. if (canceled) return
  111. await new Promise((r) => {
  112. mark.value?.unmark({
  113. done: () => {
  114. mark.value?.markRegExp(formMarkRegex(terms), { done: r })
  115. }
  116. })
  117. })
  118. // const excerpts = el.value?.querySelectorAll('.result .excerpt') ?? []
  119. // for (const excerpt of excerpts) {
  120. // excerpt
  121. // .querySelector('mark[data-markjs="true"]')
  122. // ?.scrollIntoView({ block: 'center' })
  123. // }
  124. // FIXME: without this whole page scrolls to the bottom
  125. // resultsEl.value?.firstElementChild?.scrollIntoView({ block: 'start' })
  126. },
  127. { debounce: 200, immediate: true }
  128. );
  129. </script>
  130. <template>
  131. <div class="search-container">
  132. <el-popover
  133. :visible="suggestionVisible"
  134. :show-arrow="false"
  135. :offset="0"
  136. :teleported="false"
  137. width="100%"
  138. >
  139. <template #reference>
  140. <div class="search-trigger" :class="{ 'has-content': suggestionVisible }">
  141. <el-input
  142. :ref="(el) => (input$ = el)"
  143. v-model="filterText"
  144. clearable
  145. :prefix-icon="Search"
  146. :placeholder="t('请输入关键词,如:课程、协同、AI')"
  147. ></el-input>
  148. </div>
  149. </template>
  150. <div class="search-content">
  151. <template v-if="loading">
  152. <el-skeleton animated />
  153. </template>
  154. <template v-else-if="results.length">
  155. <ul ref="resultsEl" class="results">
  156. <li v-for="(p, index) in results" :key="index">
  157. <a
  158. :href="p.id"
  159. class="result"
  160. :aria-label="[...p.titles, p.title].join(' > ')"
  161. >
  162. <div>
  163. <div class="titles">
  164. <span class="title-icon">#</span>
  165. <span v-for="(t, index) in p.titles" :key="index" class="title">
  166. <span class="text" v-html="t" />
  167. <span class="vpi-chevron-right local-search-icon" />
  168. </span>
  169. <span class="title main">
  170. <span class="text" v-html="p.title" />
  171. </span>
  172. </div>
  173. </div>
  174. </a>
  175. </li>
  176. </ul>
  177. </template>
  178. <template v-else-if="filterText">
  179. <el-empty :image-size="80">
  180. <template #description>
  181. <span
  182. >无法找到相关结果 <strong>"{{ filterText }}"</strong>
  183. </span>
  184. </template>
  185. </el-empty>
  186. </template>
  187. </div>
  188. </el-popover>
  189. </div>
  190. </template>
  191. <i18n locale="zh-HK">
  192. {
  193. "请输入关键词,如:课程、协同、AI": "TODO",
  194. }
  195. </i18n>
  196. <style lang="scss" scoped>
  197. .search-container {
  198. width: 514px;
  199. margin: auto;
  200. position: relative;
  201. .search-trigger {
  202. border: 1px solid #aeccfe;
  203. padding: 1px;
  204. width: 100%;
  205. height: 52px;
  206. border-radius: 26px;
  207. display: flex;
  208. align-items: center;
  209. padding: 0 10px;
  210. overflow: hidden;
  211. transition: all 0.2s;
  212. :deep(.el-input) {
  213. .el-input__wrapper {
  214. box-shadow: none;
  215. }
  216. }
  217. &:has(input:focus) {
  218. border: none;
  219. box-shadow: var(--el-box-shadow-light);
  220. }
  221. &.has-content {
  222. border-bottom: 1px solid #e2eeff;
  223. border-radius: 26px 26px 0 0;
  224. }
  225. }
  226. :deep(.el-popover) {
  227. border-radius: 0 0 26px 26px;
  228. border: none;
  229. clip-path: inset(0px -10px -10px -10px);
  230. padding: 0;
  231. overflow: hidden;
  232. max-height: 300px;
  233. overflow-y: scroll;
  234. }
  235. .search-content {
  236. .el-skeleton {
  237. padding: 10px 20px;
  238. }
  239. .results {
  240. display: flex;
  241. flex-direction: column;
  242. overflow-x: hidden;
  243. overflow-y: auto;
  244. overscroll-behavior: contain;
  245. list-style-type: none;
  246. padding: 0 0 5px;
  247. margin: 0;
  248. li {
  249. margin: 0;
  250. }
  251. .result {
  252. display: flex;
  253. align-items: center;
  254. gap: 8px;
  255. border-radius: 4px;
  256. transition: none;
  257. line-height: 1rem;
  258. outline: none;
  259. min-height: 40px;
  260. padding: 5px 20px;
  261. color: #333;
  262. :deep(mark) {
  263. color: #3681fc;
  264. background: transparent;
  265. }
  266. &:hover {
  267. background-color: #ecf5ff;
  268. }
  269. .titles {
  270. display: flex;
  271. flex-wrap: wrap;
  272. gap: 4px;
  273. position: relative;
  274. z-index: 1001;
  275. padding: 2px 0;
  276. }
  277. .title {
  278. display: flex;
  279. align-items: center;
  280. gap: 4px;
  281. }
  282. .title.main {
  283. font-weight: 500;
  284. }
  285. .title-icon {
  286. opacity: 0.5;
  287. font-weight: 500;
  288. color: var(--vp-c-brand-1);
  289. }
  290. .title svg {
  291. opacity: 0.5;
  292. }
  293. }
  294. }
  295. }
  296. }
  297. </style>