> For AI agents: the complete documentation index is available at /rspress-russian/llms.txt, the full documentation bundle is available at /rspress-russian/llms-full.txt.

# @rspress/plugin-algolia 

[Исходный код](https://github.com/web-infra-dev/rspress/tree/main/packages/plugin-algolia)

Этот плагин, основанный на [DocSearch](https://docsearch.algolia.com), заменяет встроенную функцию поиска Rspress на поиск, предоставляемый [Algolia](https://www.algolia.com/).

## Установка


```sh [npm]
npm add @rspress/plugin-algolia -D
```

```sh [yarn]
yarn add @rspress/plugin-algolia -D
```

```sh [pnpm]
pnpm add @rspress/plugin-algolia -D
```

```sh [bun]
bun add @rspress/plugin-algolia -D
```

```sh [deno]
deno add npm:@rspress/plugin-algolia -D
```

## Использование

Сначала добавьте следующую конфигурацию в файл `rspress.config.ts`:

```ts
// rspress.config.ts
import path from 'path';
import { defineConfig } from '@rspress/core';
import { pluginAlgolia } from '@rspress/plugin-algolia';

export default defineConfig({
  plugins: [pluginAlgolia()],
});
```

Затем замените компонент `Search` на поле поиска, поддерживающее Algolia, с помощью [пользовательской темы](/rspress-russian/guide/basic/custom-theme.md).

```tsx
// theme/index.tsx
import { Search as PluginAlgoliaSearch } from '@rspress/plugin-algolia/runtime';

const Search = () => {
  return (
    <PluginAlgoliaSearch
      docSearchProps={{
        appId: 'R2IYF7ETH7', // Замените на ваш собственный идентификатор приложения Algolia
        apiKey: '599cec31baffa4868cae4e79f180729b', // Замените на ваш собственный ключ API Algolia
        indexName: 'docsearch', // Замените на ваше собственное имя индекса Algolia
      }}
    />
  );
};
export { Search };
export * from '@rspress/core/theme-original';
```

## Конфигурация

Плагин принимает объект параметров следующего типа:

```ts
interface Options {
  verificationContent?: string;
}
```

### verificationContent

- **Тип**: `string | undefined`
- **По умолчанию**: `undefined`

Используется для проверки мета-тега при создании краулера Algolia. Формат: `<meta name="algolia-site-verification" content="YOUR_VERIFICATION_CONTENT" />`. Подробности см. в документации [Создание нового краулера — Algolia](https://www.algolia.com/doc/tools/crawler/getting-started/create-crawler/#dns).

## SearchProps

Тип `SearchProps` из модуля `@rspress/plugin-algolia/runtime` имеет следующее определение:

```ts
import type { DocSearchProps } from '@docsearch/react';

type Locales = Record<
  string,
  { translations: DocSearchProps['translations']; placeholder: string }
>;
type SearchProps = {
  /**
   * @link https://docsearch.algolia.com/docs/api
   */
  docSearchProps?: DocSearchProps;
  locales?: Locales;
};
```

### docSearchProps

- **Тип**: `import('@docsearch/react').DocSearchProps`
- **По умолчанию**: `undefined`

`docSearchProps` передается непосредственно в компонент `<DocSearch />` из пакета `@docsearch/react`. Для получения подробной информации о типах обратитесь к [документации DocSearch](https://docsearch.algolia.com/docs/api).

### locales

- Тип:

```ts
type Locales = Record<
  string,
  { translations: DocSearchProps['translations']; placeholder: string }
>;
```

- **По умолчанию**: `{}`

Для настройки переведённого текста на разных языках Rspress предоставляет следующий текст, который можно импортировать с помощью оператора `import`.


```ts
import type { DocSearchProps } from '@docsearch/react';

export type Locales = Record<
  string,
  { translations: DocSearchProps['translations']; placeholder: string }
>;

// cspell:disable
export const ZH_LOCALES: Locales = {
  zh: {
    placeholder: '搜索文档',
    translations: {
      button: {
        buttonText: '搜索',
        buttonAriaLabel: '搜索',
      },
      modal: {
        searchBox: {
          clearButtonTitle: '清除查询条件',
          clearButtonAriaLabel: '清除查询条件',
          closeButtonText: '取消',
          closeButtonAriaLabel: '取消',
        },
        startScreen: {
          recentSearchesTitle: '搜索历史',
          noRecentSearchesText: '没有搜索历史',
          saveRecentSearchButtonTitle: '保存至搜索历史',
          removeRecentSearchButtonTitle: '从搜索历史中移除',
          favoriteSearchesTitle: '收藏',
          removeFavoriteSearchButtonTitle: '从收藏中移除',
        },
        errorScreen: {
          titleText: '无法获取结果',
          helpText: '你可能需要检查你的网络连接',
        },
        footer: {
          selectText: '选择',
          navigateText: '切换',
          closeText: '关闭',
          poweredByText: '搜索提供者',
        },
        noResultsScreen: {
          noResultsText: '无法找到相关结果',
          suggestedQueryText: '你可以尝试查询',
          reportMissingResultsText: '你认为该查询应该有结果？',
          reportMissingResultsLinkText: '点击反馈',
        },
      },
    },
  },
} as const;

export const RU_LOCALES: Locales = {
  ru: {
    placeholder: 'Поиск в документации',
    translations: {
      button: {
        buttonText: 'Поиск',
        buttonAriaLabel: 'Поиск',
      },
      modal: {
        searchBox: {
          clearButtonTitle: 'Очистить поиск',
          clearButtonAriaLabel: 'Очистить поиск',
          closeButtonText: 'Закрыть',
          closeButtonAriaLabel: 'Закрыть',
        },
        startScreen: {
          recentSearchesTitle: 'История поиска',
          noRecentSearchesText: 'Нет истории поиска',
          saveRecentSearchButtonTitle: 'Сохранить в истории поиска',
          removeRecentSearchButtonTitle: 'Удалить из истории поиска',
          favoriteSearchesTitle: 'Избранное',
          removeFavoriteSearchButtonTitle: 'Удалить из избранного',
        },
        errorScreen: {
          titleText: 'Невозможно получить результаты',
          helpText: 'Проверьте подключение к Интернету',
        },
        footer: {
          selectText: 'выбрать',
          navigateText: 'перейти',
          closeText: 'закрыть',
          poweredByText: 'поиск от',
        },
        noResultsScreen: {
          noResultsText: 'Ничего не найдено',
          suggestedQueryText: 'Попробуйте изменить запрос',
          reportMissingResultsText: 'Считаете, что результаты должны быть?',
          reportMissingResultsLinkText: 'Сообщите об этом',
        },
      },
    },
  },
} as const;
// cspell:enable
```

Rspress по умолчанию предоставляет перевод на китайский язык, но вы можете настроить переведённый текст на различных языках с помощью параметра `locales`.

- Пример:

```tsx
import { Search as PluginAlgoliaSearch, RU_LOCALES } from '@rspress/plugin-algolia/runtime';

<PluginAlgoliaSearch locales={RU_LOCALES} />
// или
<PluginAlgoliaSearch
  locales={{
    ru: {
      placeholder: 'Поиск в документации',
      translations: {
        button: {
          buttonText: 'Поиск',
          buttonAriaLabel: 'Поиск',
        }
      }
    },
    ...RU_LOCALES,
  }}
/>
```

## Конфигурация краулера Algolia

Вот пример конфигурации на основе того, что использует этот сайт:


```tsx
new Crawler({
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_API_KEY',
  rateLimit: 8,
  maxDepth: 10,
  startUrls: ['https://rspress.rs'],
  sitemaps: ['https://rspress.rs/sitemap.xml'],
  discoveryPatterns: ['https://rspress.rs/**'],
  actions: [
    {
      indexName: 'doc_search_rspress_v2_pages',
      pathsToMatch: ['https://rspress.rs/**'],
      recordExtractor: ({ $, helpers }) => {
        // Удаление элементов бейджей, чтобы их текст не индексировался
        $('.rp-badge').remove();
        // Удаление элементов, не относящихся к документации (например, переключатель версий) из h1, чтобы заголовок оставался чистым
        $('.rspress-doc h1 .rp-not-doc').remove();

        const $activeNavItem = $('.rp-nav-menu__item.rp-nav-menu__item--active')
          .first()
          .clone();

        const lvl0 = $activeNavItem.text().trim() || 'Документация';

        return helpers.docsearch({
          recordProps: {
            lvl0: {
              selectors: '',
              defaultValue: lvl0,
            },
            lvl1: '.rspress-doc h1',
            lvl2: '.rspress-doc h2',
            lvl3: '.rspress-doc h3',
            lvl4: '.rspress-doc h4',
            lvl5: '.rspress-doc h5',
            lvl6: '.rspress-doc pre > code', // добавьте, если хотите искать внутри блоков кода
            content: '.rspress-doc p, .rspress-doc li',
          },
          indexHeadings: true,
          aggregateContent: true,
          recordVersion: 'v3',
        });
      },
    },
  ],
  initialIndexSettings: {
    doc_search_rspress_v2_pages: {
      attributesForFaceting: ['type', 'lang'],
      attributesToRetrieve: ['hierarchy', 'content', 'anchor', 'url'],
      attributesToHighlight: ['hierarchy', 'content'],
      attributesToSnippet: ['content:10'],
      camelCaseAttributes: ['hierarchy', 'content'],
      searchableAttributes: [
        'unordered(hierarchy.lvl0)',
        'unordered(hierarchy.lvl1)',
        'unordered(hierarchy.lvl2)',
        'unordered(hierarchy.lvl3)',
        'unordered(hierarchy.lvl4)',
        'unordered(hierarchy.lvl5)',
        'unordered(hierarchy.lvl6)',
        'content',
      ],
      distinct: true,
      attributeForDistinct: 'url',
      customRanking: [
        'desc(weight.pageRank)',
        'desc(weight.level)',
        'asc(weight.position)',
      ],
      ranking: [
        'words',
        'filters',
        'typo',
        'attribute',
        'proximity',
        'exact',
        'custom',
      ],
      minWordSizefor1Typo: 3,
      minWordSizefor2Typos: 7,
      allowTyposOnNumericTokens: false,
      minProximity: 1,
      ignorePlurals: true,
      advancedSyntax: true,
      attributeCriteriaComputedByMinProximity: true,
      removeWordsIfNoResults: 'allOptional',
    },
  },
  schedule: 'on tuesday',
  indexPrefix: 'rspress-v2-crawler-',
});
```

## Разделение результатов поиска в зависимости от локализации

Вы можете добиться получения интернационализированных результатов поиска, комбинируя [Runtime API](/rspress-russian/ui/hooks/index.md) с параметром `docSearchProps`.

Вот пример использования параметра `docSearchProps.searchParameters`:

```tsx
// theme/index.tsx
import { useLang } from '@rspress/core/runtime';
import { Search as PluginAlgoliaSearch } from '@rspress/plugin-algolia/runtime';

const Search = () => {
  const lang = useLang();
  return (
    <PluginAlgoliaSearch
      docSearchProps={{
        appId: 'R2IYF7ETH7',
        apiKey: '599cec31baffa4868cae4e79f180729b',
        indexName: 'docsearch',
        searchParameters: {
          facetFilters: [`lang:${lang}`],
        },
      }}
    />
  );
};
export { Search };
export * from '@rspress/core/theme-original';
```
