Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 69 additions & 6 deletions docs/src/content/docs/guides/site-search.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -199,36 +199,99 @@ Add translations of the modal UI for your language using Starlight’s built-in

```json title="src/content/i18n/en.json"
{
"docsearch.searchBox.resetButtonTitle": "Clear the query",
"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
"docsearch.searchBox.cancelButtonText": "Cancel",
"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
"docsearch.searchBox.clearButtonTitle": "Clear the query",
"docsearch.searchBox.clearButtonAriaLabel": "Clear the query",
"docsearch.searchBox.closeButtonText": "Close",
"docsearch.searchBox.closeButtonAriaLabel": "Close",
"docsearch.searchBox.placeholderText": "Search docs",
"docsearch.searchBox.placeholderTextAskAi": "Ask AI: ",
"docsearch.searchBox.placeholderTextAskAiStreaming": "Answering…",
"docsearch.searchBox.searchInputLabel": "Search",
"docsearch.searchBox.backToKeywordSearchButtonText": "Back to keyword search",
"docsearch.searchBox.backToKeywordSearchButtonAriaLabel": "Back to keyword search",

"docsearch.startScreen.recentSearchesTitle": "Recent",
"docsearch.startScreen.noRecentSearchesText": "No recent searches",
"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",
"docsearch.startScreen.recentConversationsTitle": "Recent conversations",
"docsearch.startScreen.removeRecentConversationButtonTitle": "Remove this conversation from history",

"docsearch.errorScreen.titleText": "Unable to fetch results",
"docsearch.errorScreen.helpText": "You might want to check your network connection.",

"docsearch.footer.selectText": "to select",
"docsearch.footer.submitQuestionText": "Submit question",
"docsearch.footer.selectKeyAriaLabel": "Enter key",
"docsearch.footer.navigateText": "to navigate",
"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
"docsearch.footer.closeText": "to close",
"docsearch.footer.backToSearchText": "Back to search",
"docsearch.footer.closeKeyAriaLabel": "Escape key",
"docsearch.footer.searchByText": "Search by",
"docsearch.footer.poweredByText": "Search by",

"docsearch.noResultsScreen.noResultsText": "No results for",
"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know.",

"docsearch.resultsScreen.askAiPlaceholder": "Ask AI: ",

"docsearch.askAiScreen.disclaimerText": "Answers are generated by AI and may be inaccurate.",
"docsearch.askAiScreen.relatedSourcesText": "Related sources",
"docsearch.askAiScreen.thinkingText": "Thinking…",
"docsearch.askAiScreen.copyButtonText": "Copy",
"docsearch.askAiScreen.copyButtonCopiedText": "Copied!",
"docsearch.askAiScreen.copyButtonTitle": "Copy",
"docsearch.askAiScreen.likeButtonTitle": "Like",
"docsearch.askAiScreen.dislikeButtonTitle": "Dislike",
"docsearch.askAiScreen.thanksForFeedbackText": "Thanks for your feedback!",
"docsearch.askAiScreen.preToolCallText": "Searching…",
"docsearch.askAiScreen.duringToolCallText": "Searching ",
"docsearch.askAiScreen.afterToolCallText": "Searched",
"docsearch.askAiScreen.aggregatedToolCallText": "Searched"
}
```

</Steps>

#### Algolia Ask&nbsp;AI

DocSearch v4 introduces an optional **Ask AI** conversational experience. To enable it, pass the `askAi` option to the Starlight DocSearch plugin — either as a plain string (your **assistant ID**) or as an object with overrides:

```ts title="astro.config.mjs" ins={15-20}
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import starlightDocSearch from '@astrojs/starlight-docsearch';

export default defineConfig({
integrations: [
starlight({
plugins: [
starlightDocSearch({
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_SEARCH_API_KEY',
indexName: 'YOUR_INDEX_NAME',
// simplest form — just the assistant ID
// askAi: 'YOUR_ASSISTANT_ID',

// or full form with per-assistant overrides
askAi: {
assistantId: 'YOUR_ASSISTANT_ID',
// apiKey, appId & indexName default to the top-level values
// but can be overridden individually if needed
// apiKey: '...',
// appId: '...',
// indexName: '...',
},
}),
],
}),
],
});
```

If you want to stick with keyword search only, simply omit the `askAi` property.
66 changes: 57 additions & 9 deletions packages/docsearch/DocSearch.astro
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import '@docsearch/css/dist/modal.css';
import type docsearch from '@docsearch/js';
import './variables.css';

type DocSearchTranslationProps = Pick<
Parameters<typeof docsearch>[0],
'placeholder' | 'translations'
>;
type DocSearchProps = Parameters<typeof docsearch>[0];

type DocSearchTranslationProps = Pick<DocSearchProps, 'placeholder' | 'translations'>;

const pick = (keyStart: string) =>
Object.fromEntries(
Expand All @@ -26,8 +25,10 @@ const docsearchTranslations: DocSearchTranslationProps = {
searchBox: pick('docsearch.searchBox.'),
startScreen: pick('docsearch.startScreen.'),
errorScreen: pick('docsearch.errorScreen.'),
footer: pick('docsearch.footer.'),
askAiScreen: pick('docsearch.askAiScreen.'),
resultsScreen: pick('docsearch.resultsScreen.'),
noResultsScreen: pick('docsearch.noResultsScreen.'),
footer: pick('docsearch.footer.'),
},
},
};
Expand Down Expand Up @@ -130,12 +131,59 @@ const docsearchTranslations: DocSearchTranslationProps = {
super();
window.addEventListener('DOMContentLoaded', async () => {
const { default: docsearch } = await import('@docsearch/js');
const options = { ...config, container: 'sl-doc-search' };
let translations;
try {
const translations = JSON.parse(this.dataset.translations || '{}');
Object.assign(options, translations);
translations = JSON.parse(this.dataset.translations || '{}');
} catch {}
docsearch(options);

// Extract the page language (e.g. <html lang="en">) and pass it to DocSearch
// as an Algolia facet filter so that the search results are scoped to the current
// language. If users already defined facet filters we preserve them while appending
// the new one.
let searchParameters: Record<string, any> | undefined;

// Rebuild the askAi prop as an object:
// If the askAi prop is a string, treat it as the assistantId and use
// the default indexName, apiKey and appId from the main options.
// If the askAi prop is an object, spread its explicit values.
const askAiProp = config.askAi;
const isAskAiString = typeof askAiProp === 'string';

const askAi = askAiProp
? {
indexName: isAskAiString ? config.indexName : askAiProp.indexName,
apiKey: isAskAiString ? config.apiKey : askAiProp.apiKey,
appId: isAskAiString ? config.appId : askAiProp.appId,
assistantId: isAskAiString ? askAiProp : askAiProp.assistantId,
searchParameters: {},
}
: undefined;

const pageLang = document.documentElement.getAttribute('lang');
if (pageLang) {
searchParameters = config.searchParameters || {};
const existingFilters = searchParameters?.facetFilters ?? [];
// Ensure facetFilters is always an array of strings for simplicity.
searchParameters.facetFilters = Array.isArray(existingFilters)
? [...existingFilters, `lang:${pageLang}`]
: [existingFilters, `lang:${pageLang}`].filter(Boolean);

if (askAi) {
// Re-use the merged facetFilters from the search parameters so that
// Ask AI uses the same language filtering as the regular search.
askAi.searchParameters = { facetFilters: searchParameters.facetFilters };
}

const options = {
...config,
container: 'sl-doc-search',
translations,
searchParameters,
askAi,
};

docsearch(options);
}
});
}
}
Expand Down
2 changes: 2 additions & 0 deletions packages/docsearch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Algolia DocSearch plugin for the [Starlight][starlight] documentation theme for [Astro][astro].

Supports DocSearch v4 with optional **Ask AI** conversational search.

## Documentation

See the [Starlight site search guide][docs] for how to use this plugin.
Expand Down
182 changes: 102 additions & 80 deletions packages/docsearch/index.ts
Original file line number Diff line number Diff line change
@@ -1,92 +1,114 @@
import type { StarlightPlugin } from '@astrojs/starlight/types';
import type docsearch from '@docsearch/js';
import type { AstroUserConfig, ViteUserConfig } from 'astro';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { z } from 'astro/zod';
import docsearch from '@docsearch/js';

export type DocSearchClientOptions = Omit<
Parameters<typeof docsearch>[0],
'container' | 'translations'
>;
export type DocSearchProps = Parameters<typeof docsearch>[0];

type SearchOptions = DocSearchClientOptions['searchParameters'];
type SearchOptions = Pick<DocSearchProps, 'searchParameters'>;

/** DocSearch configuration options. */
const DocSearchConfigSchema = z
.object({
// Required config without which DocSearch won’t work.
/** Your Algolia application ID. */
appId: z.string(),
/** Your Algolia Search API key. */
apiKey: z.string(),
/** Your Algolia index name. */
indexName: z.string(),
// Optional DocSearch component config (only the serializable properties can be included here)
/**
* The maximum number of results to display per search group.
* @default 5
*/
maxResultsPerGroup: z.number().optional(),
/**
* Disable saving recent searches and favorites to the local storage.
* @default false
*/
disableUserPersonalization: z.boolean().optional(),
/**
* Whether to enable the Algolia Insights plugin and send search events to your DocSearch index.
* @default false
*/
insights: z.boolean().optional(),
/**
* The Algolia Search Parameters.
* @see https://www.algolia.com/doc/api-reference/search-api-parameters/
*/
searchParameters: z.custom<SearchOptions>(),
})
.strict()
.or(
z
.object({
/**
* The path to a JavaScript or TypeScript file containing a default export of options to
* pass to the DocSearch client.
*
* The value can be a path to a local JS/TS file relative to the root of your project,
* e.g. `'/src/docsearch.js'`, or an npm module specifier for a package you installed,
* e.g. `'@company/docsearch-config'`.
*
* Use `clientOptionsModule` when you need to configure options that are not serializable,
* such as `transformSearchClient()` or `resultsFooterComponent()`.
*
* When `clientOptionsModule` is set, all options must be set via the module file. Other
* inline options passed to the plugin in `astro.config.mjs` will be ignored.
*
* @see https://docsearch.algolia.com/docs/api
*
* @example
* // astro.config.mjs
* // ...
* starlightDocSearch({ clientOptionsModule: './src/config/docsearch.ts' }),
* // ...
*
* // src/config/docsearch.ts
* import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';
*
* export default {
* appId: '...',
* apiKey: '...',
* indexName: '...',
* getMissingResultsUrl({ query }) {
* return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
* },
* } satisfies DocSearchClientOptions;
*/
clientOptionsModule: z.string(),
})
.strict()
);
// Base schema for shared Algolia configuration properties.
const AlgoliaConfigSchema = z.object({
/** Your Algolia application ID. */
appId: z.string(),
/** Your Algolia Search API key. */
apiKey: z.string(),
/** Your Algolia index name. */
indexName: z.string(),
/**
* The Algolia Search Parameters.
* @see https://www.algolia.com/doc/api-reference/search-api-parameters/
*/
searchParameters: z.custom<SearchOptions>().optional(),
});

// Schema for inline DocSearch client options (without `clientOptionsModule`).
const InlineDocSearchConfigSchema = AlgoliaConfigSchema.extend({
// Make searchParameters required for the main config
searchParameters: z.custom<SearchOptions>(),
// Optional DocSearch component config (only the serializable properties can be included here)
/**
* The maximum number of results to display per search group.
* @default 5
*/
maxResultsPerGroup: z.number().optional(),
/**
* Disable saving recent searches and favorites to the local storage.
* @default false
*/
disableUserPersonalization: z.boolean().optional(),
/**
* Whether to enable the Algolia Insights plugin and send search events to your DocSearch index.
* @default false
*/
insights: z.boolean().optional(),
/**
* Optional: Enable Algolia Ask AI.
* Can be provided as a string (your `assistantId`) or an object allowing
* per-assistant overrides.
*/
askAi: z
.union([
z.string(),
AlgoliaConfigSchema.partial().extend({
assistantId: z.string().nullable().optional(),
searchParameters: z
.object({
facetFilters: z.any().optional(),
})
.optional(),
}).strict(),
])
.optional(),
}).strict();

// Full schema that also allows referencing an external module via `clientOptionsModule`.
const DocSearchConfigSchema = InlineDocSearchConfigSchema.or(
z
.object({
/**
* The path to a JavaScript or TypeScript file containing a default export of options to
* pass to the DocSearch client.
*
* The value can be a path to a local JS/TS file relative to the root of your project,
* e.g. `'/src/docsearch.js'`, or an npm module specifier for a package you installed,
* e.g. `'@company/docsearch-config'`.
*
* Use `clientOptionsModule` when you need to configure options that are not serializable,
* such as `transformSearchClient()` or `resultsFooterComponent()`.
*
* When `clientOptionsModule` is set, all options must be set via the module file. Other
* inline options passed to the plugin in `astro.config.mjs` will be ignored.
*
* @see https://docsearch.algolia.com/docs/api
*
* @example
* // astro.config.mjs
* // ...
* starlightDocSearch({ clientOptionsModule: './src/config/docsearch.ts' }),
* // ...
*
* // src/config/docsearch.ts
* import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';
*
* export default {
* appId: '...',
* apiKey: '...',
* indexName: '...',
* getMissingResultsUrl({ query }) {
* return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
* },
* } satisfies DocSearchClientOptions;
*/
clientOptionsModule: z.string(),
})
.strict()
);

// Export the inline client options type (does NOT include `clientOptionsModule`).
export type DocSearchClientOptions = z.infer<typeof InlineDocSearchConfigSchema>;
type DocSearchUserConfig = z.infer<typeof DocSearchConfigSchema>;

/** Starlight DocSearch plugin. */
Expand Down
Loading