Skip to content

Commit

Permalink
feat: support global search in multiple environments and fix pipeline…
Browse files Browse the repository at this point in the history
… errors
  • Loading branch information
zzcr committed Dec 9, 2024
1 parent c79dd29 commit 5e7c317
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 10 deletions.
5 changes: 3 additions & 2 deletions examples/sites/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@opentiny/vue-docs",
"version": "3.20.3",
"version": "3.20.5",
"license": "MIT",
"scripts": {
"start": "vite",
Expand Down Expand Up @@ -49,7 +49,8 @@
"vue-i18n": "^9.1.10",
"vue-router": "4.1.5",
"@docsearch/js": "^3.8.0",
"@docsearch/css": "^3.8.0"
"@docsearch/css": "^3.8.0",
"@docsearch/react": "npm:@docsearch/css"
},
"devDependencies": {
"@opentiny-internal/unplugin-virtual-template": "workspace:~",
Expand Down
20 changes: 12 additions & 8 deletions examples/sites/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,25 @@ import css from 'highlight.js/lib/languages/css'
import html from 'highlight.js/lib/languages/xml'
import docsearch from '@docsearch/js'
import '@docsearch/css'
import { doSearhEverySite } from './tools/docsearch'

const envTarget = import.meta.env.VITE_BUILD_TARGET || 'open'

hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('css', css)
hljs.registerLanguage('html', html)

if (envTarget === 'open') {
docsearch({
appId: 'AGPA5UXHMH',
apiKey: '5fa09fc20270efa61d68e2c2eb0f56df',
indexName: 'opentiny',
container: '.search-box',
debug: false
})
docsearch({
appId: 'AGPA5UXHMH',
apiKey: '5fa09fc20270efa61d68e2c2eb0f56df',
indexName: 'opentiny',
container: '.search-box',
debug: false
})

if (envTarget !== 'open') {
// 支持本地开发和内网使用全局搜索
doSearhEverySite()
}

// 实验后发现,先调用一次预热一下,后续再调用会有速度的提示,因此在main中预热一下。
Expand Down
26 changes: 26 additions & 0 deletions examples/sites/src/tools/docsearch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const HIT_CLASS = 'DocSearch-Hit'

const findUrlLink = (target) => {
if (target?.nodeName?.toLocaleLowerCase?.() === 'a') {
return target.getAttribute('href')
} else if (target?.parentElement) {
return findUrlLink(target.parentElement)
}
}

const isAlgoliaHitDom = (dom) =>
dom?.className?.includes?.(HIT_CLASS) || dom?.parentElement?.className?.includes?.(HIT_CLASS)

export const doSearhEverySite = () => {
window.addEventListener('click', (event) => {
const target = event.target
if (isAlgoliaHitDom(target)) {
const openUrl = findUrlLink(target)
if (openUrl) {
const urlObj = new URL(openUrl)
event.preventDefault()
window.location.href = openUrl.replace(urlObj.origin, window.location.origin)
}
}
})
}

0 comments on commit 5e7c317

Please sign in to comment.