给你的网站添加 Algolia 搜索

官网

面向开发者官网

实现一个组件基于vue3

<script setup lang="ts">
import '@docsearch/css'
import docsearch from '@docsearch/js'
import { getCurrentInstance, onMounted, watch } from 'vue'
import type { DocSearchHit } from '@docsearch/react/dist/esm/types'

interface AlgoliaSearchOptions {
  appId?: string
  apiKey: string
  indexName: string
  placeholder?: string
  searchParameters?: any
  disableUserPersonalization?: boolean
  initialQuery?: string
}

const props = defineProps<{
  options: AlgoliaSearchOptions
  multilang?: boolean
}>()

const vm = getCurrentInstance()
const route = useRoute()
const router = useRouter()

watch(
  () => props.options,
  (value) => {
    update(value)
  },
)

onMounted(() => {
  initialize(props.options)
})

function isSpecialClick(event: MouseEvent) {
  return (
    event.button === 1
    || event.altKey
    || event.ctrlKey
    || event.metaKey
    || event.shiftKey
  )
}

function getRelativePath(absoluteUrl: string) {
  const { pathname, hash } = new URL(absoluteUrl)

  return pathname + hash
}

function update(options: any) {
  if (vm && vm.vnode.el) {
    vm.vnode.el.innerHTML
      = '<div class="algolia-search-box" id="docsearch"></div>'
    initialize(options)
  }
}

const lang = ref('ZH-CN')

// if the user has multiple locales, the search results should be filtered
// based on the language
const facetFilters: string[] = props.multilang ? [`lang:${lang.value}`] : []

if (props.options.searchParameters?.facetFilters)
  facetFilters.push(...props.options.searchParameters.facetFilters)

watch(lang, (newLang, oldLang) => {
  const index = facetFilters.findIndex(filter => filter === `lang:${oldLang}`)
  if (index > -1)
    facetFilters.splice(index, 1, `lang:${newLang}`)
})

function initialize(userOptions: any) {
  docsearch(
    Object.assign({}, userOptions, {
      container: '#docsearch',

      searchParameters: Object.assign({}, userOptions.searchParameters, {
        // pass a custom lang facetFilter to allow multiple language search
        // https://github.com/algolia/docsearch-configs/pull/3942
        facetFilters,
      }),

      navigator: {
        navigate: ({ itemUrl }: { itemUrl: string }) => {
          const { pathname: hitPathname } = new URL(
            window.location.origin + itemUrl,
          )

          // Router doesn't handle same-page navigation so we use the native
          // browser location API for anchor navigation
          if (route.path === hitPathname)
            window.location.assign(window.location.origin + itemUrl)

          else
            router.go(itemUrl)
        },
      },

      transformItems: (items: DocSearchHit[]) => {
        return items.map((item) => {
          return Object.assign({}, item, {
            url: getRelativePath(item.url),
          })
        })
      },

      hitComponent: ({
        hit,
        children,
      }: {
        hit: DocSearchHit
        children: any
      }) => {
        const relativeHit = hit.url.startsWith('http')
          ? getRelativePath(hit.url as string)
          : hit.url

        return {
          type: 'a',
          ref: undefined,
          constructor: undefined,
          key: undefined,
          props: {
            href: hit.url,
            onClick: (event: MouseEvent) => {
              if (isSpecialClick(event))
                return

              // we rely on the native link scrolling when user is already on
              // the right anchor because Router doesn't support duplicated
              // history entries
              if (route.path === relativeHit)
                return

              // if the hits goes to another page, we prevent the native link
              // behavior to leverage the Router loading feature
              if (route.path !== relativeHit)
                event.preventDefault()

              router.go(relativeHit)
            },
            children,
          },
          __v: null,
        }
      },
    }),
  )
}
</script>

<template>
  <div id="docsearch" class="algolia-search-box" />
</template>

<style lang="scss">
.algolia-search-box {
  padding-top: 1px;
}

@media (min-width: 720px) {
  .algolia-search-box {
    padding-left: 8px;
  }
}

@media (min-width: 751px) {
  .algolia-search-box {
    min-width: 176.3px;
    /* avoid layout shift */
  }

  .algolia-search-box .DocSearch-Button-Placeholder {
    padding-left: 8px;
    font-size: 0.9rem;
    font-weight: 500;
  }
}

.DocSearch {
  --docsearch-primary-color: var(--c-brand);
  --docsearch-highlight-color: var(--docsearch-primary-color);
  --docsearch-searchbox-shadow: inset 0 0 0 2px var(--docsearch-primary-color);
  --docsearch-text-color: var(--c-text-light);
  --docsearch-muted-color: var(--c-text-lighter);
  --docsearch-searchbox-background: #f2f2f2;
}
html.dark{
  .DocSearch {
    --docsearch-searchbox-focus-background: #1b1a1a;
    --docsearch-modal-background: var(--primary-bg);
    --docsearch-hit-background: var(--primary-bg);
    --docsearch-hit-shadow: 0 1px 3px 0 #1b1b1b;
    --docsearch-modal-shadow: inset 1px 1px 0 0 rgba(23, 18, 18, 0.5),0 3px 8px 0 #555a64;
    --docsearch-footer-background: ##1b1a1a;
    --docsearch-key-gradient: linear-gradient(-225deg,#252627,#5e5252);
    --docsearch-footer-shadow: 0 -1px 0 0 #202122,0 -3px 6px 0 rgba(69,98,155,0.12);
    --docsearch-hit-color: #767e8a;
    --docsearch-key-shadow: inset 0 -2px 0 0 #41414a,inset 0 0 1px 1px rgb(73, 69, 69),0 1px 2px 1px rgba(30,35,90,0.4);
  }
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

主要依赖

pnpm i @docsearch/css @docsearch/js
1

使用组件

<script>
const options = {
  appId: 'xxx',
  apiKey: 'xxx',
  indexName: 'artiely',
}
</script>
<template>
  <AlgoliaSearchBox :options="options" />
</template>
1
2
3
4
5
6
7
8
9
10

上传数据

  1. 配置你的索引级别 .content 为你页面的最外层class
const searchConfig = {
  index_name: 'artiely', // 索引名称
  start_urls: [], // 开始页面
  selectors: { // 选择器
    lvl0: { // 第一层
      selector: '',
      global: true,
      default_value: 'Documentation',
    },
    lvl1: '.content h1', // 第一级标题
    lvl2: '.content h2', // 第二级标题
    lvl3: '.content h3',
    lvl4: '.content h4',
    lvl5: '.content h5',
    lvl6: '.content p, .content li', // 段落
    text: '.content [class^=language-]', // 文本
  },
  nb_hits: 100, // 每页显示数量
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  1. 在打包应用时写入 start_urls 并将配置写入到config_algolia.json的文件中
try {
  const urls = files.map(v => `https://artiely.gitee.io${v.link}`)
  searchConfig.start_urls = [...searchConfig.start_urls, ...urls]
  fs.writeFile(
    path.join(path.dirname(__dirname), '../config_algolia.json'),
    JSON.stringify(searchConfig),
    (error) => {
      if (error) {
        console.log('写入失败')
      }
      else {
        // console.log("写入成功了");
      }
    },
  )
}
catch (error) {
  console.log('🚀 ~ file: config.js ~ error', error)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  1. 使用Docker容器运行爬虫

新建一个shell脚本 ,shell_algolia.sh

docker run -it --env-file=.env -e "CONFIG=$(cat config_algolia.json | jq -r tostring)" algolia/docsearch-scraper
1

注意

注意你的网站要先发布到域名上