|
| 1 | +// @ts-nocheck |
| 2 | +import { useEffect, useState } from 'react' |
| 3 | +import useBaseUrl from '@docusaurus/useBaseUrl' |
| 4 | +import useIsBrowser from '@docusaurus/useIsBrowser' |
| 5 | +import { useColorMode } from '@docusaurus/theme-common' |
| 6 | +import { usePluginData } from '@docusaurus/useGlobalData' |
| 7 | +import { ungzip } from 'pako' |
| 8 | +import { presets } from '@orama/searchbox' |
| 9 | +import { OramaClient } from '@oramacloud/client' |
| 10 | +import { create, insertMultiple } from '@orama/orama' |
| 11 | +import { pluginAnalytics } from '@orama/plugin-analytics' |
| 12 | +import '@orama/searchbox/dist/index.css' |
| 13 | + |
| 14 | +export const useOrama = () => { |
| 15 | + const [searchBoxConfig, setSearchBoxConfig] = useState(null) |
| 16 | + const { colorMode } = useColorMode() |
| 17 | + const { searchData, endpoint, analytics }: PluginData = usePluginData('@orama/plugin-docusaurus-v3') as PluginData |
| 18 | + |
| 19 | + const baseURL = useBaseUrl('orama-search-index-current.json.gz') |
| 20 | + const isBrowser = useIsBrowser() |
| 21 | + useEffect(() => { |
| 22 | + async function loadOrama() { |
| 23 | + if (endpoint?.url) { |
| 24 | + setSearchBoxConfig({ |
| 25 | + oramaInstance: new OramaClient({ |
| 26 | + endpoint: endpoint.url, |
| 27 | + api_key: endpoint.key |
| 28 | + }) |
| 29 | + }) |
| 30 | + } else { |
| 31 | + let buffer |
| 32 | + |
| 33 | + if (searchData?.current) { |
| 34 | + buffer = searchData.current.data |
| 35 | + } else { |
| 36 | + const searchResponse = await fetch(baseURL) |
| 37 | + |
| 38 | + if (searchResponse.status === 0) { |
| 39 | + throw new Error(`Network error: ${await searchResponse.text()}`) |
| 40 | + } else if (searchResponse.status !== 200) { |
| 41 | + throw new Error(`HTTP error ${searchResponse.status}: ${await searchResponse.text()}`) |
| 42 | + } |
| 43 | + |
| 44 | + buffer = await searchResponse.arrayBuffer() |
| 45 | + } |
| 46 | + |
| 47 | + const deflated = ungzip(buffer, { to: 'string' }) |
| 48 | + const parsedDeflated = JSON.parse(deflated) |
| 49 | + |
| 50 | + const db = await create({ |
| 51 | + schema: { ...presets.docs.schema, version: 'enum' }, |
| 52 | + plugins: [ |
| 53 | + ...(analytics |
| 54 | + ? [ |
| 55 | + pluginAnalytics({ |
| 56 | + apiKey: analytics.apiKey, |
| 57 | + indexId: analytics.indexId, |
| 58 | + enabled: analytics.enabled |
| 59 | + }) |
| 60 | + ] |
| 61 | + : []) |
| 62 | + ] |
| 63 | + }) |
| 64 | + |
| 65 | + await insertMultiple(db, Object.values(parsedDeflated.docs.docs)) |
| 66 | + |
| 67 | + setSearchBoxConfig({ |
| 68 | + oramaInstance: db |
| 69 | + }) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + if (!isBrowser) { |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + loadOrama().catch((error) => { |
| 78 | + console.error('Cannot load search index.', error) |
| 79 | + }) |
| 80 | + }, [isBrowser]) |
| 81 | + |
| 82 | + return { searchBoxConfig, colorMode } |
| 83 | +} |
0 commit comments