|
| 1 | +import type { AstroIntegration } from "astro"; |
| 2 | +import { definePlugin } from "@barodoc/core"; |
| 3 | + |
| 4 | +export interface DocSearchPluginOptions { |
| 5 | + appId: string; |
| 6 | + apiKey: string; |
| 7 | + indexName: string; |
| 8 | + container?: string; |
| 9 | + placeholder?: string; |
| 10 | +} |
| 11 | + |
| 12 | +export default definePlugin<DocSearchPluginOptions>((options) => { |
| 13 | + return { |
| 14 | + name: "@barodoc/plugin-docsearch", |
| 15 | + hooks: { |
| 16 | + "config:loaded": (config) => { |
| 17 | + return { |
| 18 | + ...config, |
| 19 | + search: { ...config.search, enabled: false }, |
| 20 | + }; |
| 21 | + }, |
| 22 | + }, |
| 23 | + astroIntegration: () => { |
| 24 | + const integration: AstroIntegration = { |
| 25 | + name: "@barodoc/plugin-docsearch", |
| 26 | + hooks: { |
| 27 | + "astro:config:setup": ({ injectScript }) => { |
| 28 | + const cssUrl = "https://cdn.jsdelivr.net/npm/@docsearch/css@3/dist/style.min.css"; |
| 29 | + const jsUrl = "https://cdn.jsdelivr.net/npm/@docsearch/js@3"; |
| 30 | + |
| 31 | + injectScript( |
| 32 | + "head-inline", |
| 33 | + `document.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" href="${cssUrl}" />');` |
| 34 | + ); |
| 35 | + |
| 36 | + injectScript( |
| 37 | + "page", |
| 38 | + ` |
| 39 | +import docsearch from "${jsUrl}"; |
| 40 | +
|
| 41 | +function initDocSearch() { |
| 42 | + const container = document.querySelector('${options.container || "#docsearch"}'); |
| 43 | + if (!container || container.hasChildNodes()) return; |
| 44 | + docsearch({ |
| 45 | + appId: "${options.appId}", |
| 46 | + apiKey: "${options.apiKey}", |
| 47 | + indexName: "${options.indexName}", |
| 48 | + container: "${options.container || "#docsearch"}", |
| 49 | + placeholder: "${options.placeholder || "Search docs..."}", |
| 50 | + }); |
| 51 | +} |
| 52 | +
|
| 53 | +if (document.readyState === "complete") initDocSearch(); |
| 54 | +else document.addEventListener("DOMContentLoaded", initDocSearch); |
| 55 | +document.addEventListener("astro:page-load", initDocSearch); |
| 56 | +` |
| 57 | + ); |
| 58 | + }, |
| 59 | + }, |
| 60 | + }; |
| 61 | + return integration; |
| 62 | + }, |
| 63 | + }; |
| 64 | +}); |
0 commit comments