index.vue 8.8 KB

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