组合式 API
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
组合式 API 自 >= 4.3 版本起可用
DocSearch 推出了全新的组合式 API 用于渲染搜索按钮和模态框。该 API 旨在提供更明确的控制能力,让开发者能精准决定组件在页面中的渲染位置和方式。
简介
组合式 API 的引入是为了提升在网站上渲染和使用 DocSearch 的灵活性。通过它,您可以完全掌控组件打包和渲染的时机、位置及具体实现方式。
组合式 API 包含两个新的 NPM 包:
-
@docsearch/core- 管理 DocSearch 各种状态的核心共享逻辑 -
@docsearch/modal- 用于 DocSearch 模态框的实际组件
由于其组合特性,此 API 仅在 React 环境中可用,不适用于 @docsearch/js 包。
开始使用
要开始使用组合式 API,您需要安装以下三个包:
- npm
- yarn
- pnpm
- bun
npm install @docsearch/core @docsearch/modal @docsearch/css
yarn add @docsearch/core @docsearch/modal @docsearch/css
pnpm add @docsearch/core @docsearch/modal @docsearch/css
bun add @docsearch/core @docsearch/modal @docsearch/css
或使用您选择的包管理器
实现
最简单的实现方式如下:
import { DocSearch } from '@docsearch/core';
import { DocSearchButton, DocSearchModal } from '@docsearch/modal';
import '@docsearch/css/style.css';
export function Search() {
return (
<DocSearch>
<DocSearchButton />
<DocSearchModal
indexName="YOUR_INDEX_NAME"
appId="YOUR_APP_ID"
apiKey="YOUR_SEARCH_API_KEY"
/>
</DocSearch>
);
}
实际组件必须在 <DocSearch> Provider 内部渲染,才能与全局状态通信。
此配置需要渲染三个不同组件,略微复杂:
-
<DocSearch>是父元素,负责控制并与子组件共享所有状态 -
<DocSearchButton />是实际渲染的按钮元素,用于触发打开 DocSearch 模态框 -
<DocSearchModal />是主模态框,包含搜索表单、搜索结果和 Ask AI
Ask AI
在组合式 API 中使用 Ask AI 与常规 DocSearch 用法非常相似,只需配置 askAi 参数:
import { DocSearch } from '@docsearch/core';
import { DocSearchButton, DocSearchModal } from '@docsearch/modal';
import '@docsearch/css/style.css';
export function Search() {
return (
<DocSearch>
<DocSearchButton />
<DocSearchModal
indexName="YOUR_INDEX_NAME"
appId="YOUR_APP_ID"
apiKey="YOUR_SEARCH_API_KEY"
// With just a simple assistant ID
askAi="YOUR_ALGOLIA_ASSISTANT_ID"
// Or with a more complex configuration
askAi={{
indexName: 'YOUR_MARKDOWN_INDEX', // Optional: use a different index for Ask AI
apiKey: 'YOUR_SEARCH_API_KEY', // Optional: use a different API key for Ask AI
appId: 'YOUR_APP_ID', // Optional: use a different App ID for Ask AI
assistantId: 'YOUR_ALGOLIA_ASSISTANT_ID',
searchParameters: {
facetFilters: ['language:en', 'version:1.0.0'], // Optional: filter Ask AI context
},
}}
/>
</DocSearch>
);
}
您可以在 专属文档 中找到关于 Ask AI 及其设置的更多信息。
进阶用法
export default function AdvancedSearch(): JSX.Element {
return (
<DocSearch
keyboardShortcuts={{
'/': false, // Disable opening/closing the DocSearchModal with '/' key
}}
>
<DocSearchButton
translations={{ buttonText: 'Advanced Search' }} // Change the displayed text on the DocSearchButton
/>
<DocSearchModal
indexName="YOUR_INDEX_NAME"
appId="YOUR_APP_ID"
apiKey="YOUR_SEARCH_API_KEY"
askAi={{ // Enable Ask AI
assistantId: 'YOUR_ALGOLIA_ASSISTANT_ID',
searchParameters: {
facetFilters: ['language:en'],
},
}}
portalContainer='#algolia-search' // Custom element that the DocSearchModal will be rendered into
/>
</DocSearch>
);
}
精简包体积导出
为帮助缩减初始包体积,@docsearch/modal 包还提供了显式文件导出:
import { DocSearchButton } from '@docsearch/modal/button';
import { DocSearchModal } from '@docsearch/modal/modal';
以下基础示例演示了如何延迟加载 DocSearchModal 代码直至点击搜索按钮:
import { DocSearch } from '@docsearch/core';
import { DocSearchButton } from '@docsearch/modal/button';
import type { DocSearchModal as DocSearchModalType } from '@docsearch/modal/modal';
import { useState } from 'react';
let DocSearchModal: typeof DocSearchModalType | null = null;
async function importDocSearchModalIfNeeded() {
if (DocSearchModal) {
return;
}
const { DocSearchModal: Modal } = await import('@docsearch/modal/modal');
DocSearchModal = Modal;
}
export default function DynamicModal() {
const [modalLoaded, setModalLoaded] = useState(false);
const loadModal = () => {
importDocSearchModalIfNeeded().then(() => {
setModalLoaded(true);
});
};
return (
<DocSearch>
<DocSearchButton onClick={loadModal} />
{modalLoaded && DocSearchModal && (
<DocSearchModal
indexName="YOUR_INDEX_NAME"
appId="YOUR_APP_ID"
apiKey="YOUR_SEARCH_API_KEY"
/>
)}
</DocSearch>
);
}
组件
<DocSearch />
来自 @docsearch/core 包的 <DocSearch /> 组件是 DocSearch 的核心状态管理器。它利用 React Context 实现状态在嵌套组件间的共享。
属性
interface DocSearchProps {
// React children to be rendered within the DocSearch Provider
children: Array<JSX.Element | null> | JSX.Element | React.ReactNode | null;
// Theme to be set enabling style changes for `light` or `dark` themes
theme?: 'light' | 'dark';
// Initial starting query for keyword search
initialQuery?: string;
// Manage supported keyboard shortcuts for opening/closing the DocSearch Modal
keyboardShortcuts?: {
'Ctrl/Cmd+K': boolean,
'/': boolean,
};
}
<DocSearchButton />
用于触发 DocSearch 模态框的主搜索按钮。
属性
interface DocSearchButtonProps {
// Optional callback for when the button is clicked. The original click event is passed.
onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
// Translation strings specific to the button.
translations: {
buttonText?: string;
buttonAriaLabel?: string;
};
}
<DocSearchModal />
用于文档搜索的主关键词搜索模态框。
属性
interface DocSearchModalProps {
/**
* Algolia application id used by the search client.
*/
appId: string;
/**
* Public api key with search permissions for the index.
*/
apiKey: string;
/**
* Name of the algolia index to query.
*
* @deprecated `indexName` will be removed in a future version. Please use `indices` property going forward.
*/
indexName?: string;
/**
* List of indices and _optional_ searchParameters to be used for search.
*
* @see {@link https://docsearch.algolia.com/docs/api#indices}
*/
indices?: Array<DocSearchIndex | string>;
/**
* Configuration or assistant id to enable ask ai mode. Pass a string assistant id or a full config object.
*/
askAi?: DocSearchAskAi | string;
// ...
}
更多属性文档请参阅 DocSearch API 参考 页面。