@docusaurus/theme-search-algolia 2.0.0-beta.1ec2c95e3 → 2.0.0-beta.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/lib/client/index.d.ts +7 -0
  2. package/lib/client/index.js +7 -0
  3. package/lib/client/useAlgoliaContextualFacetFilters.d.ts +7 -0
  4. package/lib/client/useAlgoliaContextualFacetFilters.js +15 -0
  5. package/lib/index.d.ts +9 -0
  6. package/lib/index.js +90 -0
  7. package/lib/templates/opensearch.d.ts +8 -0
  8. package/lib/templates/opensearch.js +23 -0
  9. package/lib/theme/SearchBar/index.d.ts +8 -0
  10. package/{src → lib}/theme/SearchBar/index.js +57 -65
  11. package/lib/theme/SearchBar/styles.css +21 -0
  12. package/lib/theme/SearchPage/index.d.ts +8 -0
  13. package/{src → lib}/theme/SearchPage/index.js +63 -92
  14. package/lib/theme/SearchPage/styles.module.css +119 -0
  15. package/lib/validateThemeConfig.d.ts +15 -0
  16. package/lib/validateThemeConfig.js +44 -0
  17. package/package.json +36 -13
  18. package/src/client/index.ts +8 -0
  19. package/src/{theme/hooks/useAlgoliaContextualFacetFilters.js → client/useAlgoliaContextualFacetFilters.ts} +3 -3
  20. package/src/deps.d.ts +10 -0
  21. package/src/index.ts +116 -0
  22. package/src/templates/{opensearch.js → opensearch.ts} +7 -5
  23. package/src/theme/SearchBar/index.tsx +276 -0
  24. package/src/theme/SearchPage/index.tsx +533 -0
  25. package/src/theme/SearchPage/styles.module.css +4 -4
  26. package/src/theme-search-algolia.d.ts +35 -0
  27. package/src/types.d.ts +10 -0
  28. package/src/validateThemeConfig.ts +53 -0
  29. package/src/__tests__/validateThemeConfig.test.js +0 -121
  30. package/src/index.js +0 -92
  31. package/src/theme/SearchBar/styles.module.css +0 -20
  32. package/src/theme/SearchMetadatas/index.js +0 -25
  33. package/src/theme/hooks/useSearchQuery.js +0 -44
  34. package/src/validateThemeConfig.js +0 -45
package/src/index.ts ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import path from 'path';
9
+ import fs from 'fs-extra';
10
+ import _ from 'lodash';
11
+ import logger from '@docusaurus/logger';
12
+ import {defaultConfig, compile} from 'eta';
13
+ import {normalizeUrl} from '@docusaurus/utils';
14
+ import {readDefaultCodeTranslationMessages} from '@docusaurus/theme-translations';
15
+ import openSearchTemplate from './templates/opensearch';
16
+
17
+ import type {LoadContext, Plugin} from '@docusaurus/types';
18
+ import type {ThemeConfig} from '@docusaurus/theme-search-algolia';
19
+
20
+ const getCompiledOpenSearchTemplate = _.memoize(() =>
21
+ compile(openSearchTemplate.trim()),
22
+ );
23
+
24
+ function renderOpenSearchTemplate(data: {
25
+ title: string;
26
+ siteUrl: string;
27
+ searchUrl: string;
28
+ faviconUrl: string | null;
29
+ }) {
30
+ const compiled = getCompiledOpenSearchTemplate();
31
+ return compiled(data, defaultConfig);
32
+ }
33
+
34
+ const OPEN_SEARCH_FILENAME = 'opensearch.xml';
35
+
36
+ export default function themeSearchAlgolia(context: LoadContext): Plugin<void> {
37
+ const {
38
+ baseUrl,
39
+ siteConfig: {title, url, favicon, themeConfig},
40
+ i18n: {currentLocale},
41
+ } = context;
42
+ const {
43
+ algolia: {searchPagePath},
44
+ } = themeConfig as ThemeConfig;
45
+
46
+ return {
47
+ name: 'docusaurus-theme-search-algolia',
48
+
49
+ getThemePath() {
50
+ return '../lib/theme';
51
+ },
52
+ getTypeScriptThemePath() {
53
+ return '../src/theme';
54
+ },
55
+
56
+ getDefaultCodeTranslationMessages() {
57
+ return readDefaultCodeTranslationMessages({
58
+ locale: currentLocale,
59
+ name: 'theme-search-algolia',
60
+ });
61
+ },
62
+
63
+ contentLoaded({actions: {addRoute}}) {
64
+ if (searchPagePath) {
65
+ addRoute({
66
+ path: normalizeUrl([baseUrl, searchPagePath]),
67
+ component: '@theme/SearchPage',
68
+ exact: true,
69
+ });
70
+ }
71
+ },
72
+
73
+ async postBuild({outDir}) {
74
+ if (searchPagePath) {
75
+ const siteUrl = normalizeUrl([url, baseUrl]);
76
+
77
+ try {
78
+ await fs.writeFile(
79
+ path.join(outDir, OPEN_SEARCH_FILENAME),
80
+ renderOpenSearchTemplate({
81
+ title,
82
+ siteUrl,
83
+ searchUrl: normalizeUrl([siteUrl, searchPagePath]),
84
+ faviconUrl: favicon ? normalizeUrl([siteUrl, favicon]) : null,
85
+ }),
86
+ );
87
+ } catch (err) {
88
+ logger.error('Generating OpenSearch file failed.');
89
+ throw err;
90
+ }
91
+ }
92
+ },
93
+
94
+ injectHtmlTags() {
95
+ if (!searchPagePath) {
96
+ return {};
97
+ }
98
+
99
+ return {
100
+ headTags: [
101
+ {
102
+ tagName: 'link',
103
+ attributes: {
104
+ rel: 'search',
105
+ type: 'application/opensearchdescription+xml',
106
+ title,
107
+ href: normalizeUrl([baseUrl, OPEN_SEARCH_FILENAME]),
108
+ },
109
+ },
110
+ ],
111
+ };
112
+ },
113
+ };
114
+ }
115
+
116
+ export {validateThemeConfig} from './validateThemeConfig';
@@ -5,16 +5,18 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- module.exports = `
8
+ export default `
9
9
  <?xml version="1.0" encoding="UTF-8"?>
10
10
  <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
11
11
  xmlns:moz="http://www.mozilla.org/2006/browser/search/">
12
12
  <ShortName><%= it.title %></ShortName>
13
13
  <Description>Search <%= it.title %></Description>
14
14
  <InputEncoding>UTF-8</InputEncoding>
15
- <Image width="16" height="16" type="image/x-icon"><%= it.favicon %></Image>
16
- <Url type="text/html" method="get" template="<%= it.url %>search?q={searchTerms}"/>
17
- <Url type="application/opensearchdescription+xml" rel="self" template="<%= it.url %>opensearch.xml" />
18
- <moz:SearchForm><%= it.url %></moz:SearchForm>
15
+ <% if (it.faviconUrl) { _%>
16
+ <Image width="16" height="16" type="image/x-icon"><%= it.faviconUrl %></Image>
17
+ <% } _%>
18
+ <Url type="text/html" method="get" template="<%= it.searchUrl %>?q={searchTerms}"/>
19
+ <Url type="application/opensearchdescription+xml" rel="self" template="<%= it.siteUrl %>opensearch.xml" />
20
+ <moz:SearchForm><%= it.siteUrl %></moz:SearchForm>
19
21
  </OpenSearchDescription>
20
22
  `;
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import React, {useState, useRef, useCallback, useMemo} from 'react';
9
+ import {createPortal} from 'react-dom';
10
+ import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
11
+ import {useHistory} from '@docusaurus/router';
12
+ import {useBaseUrlUtils} from '@docusaurus/useBaseUrl';
13
+ import Link from '@docusaurus/Link';
14
+ import Head from '@docusaurus/Head';
15
+ import {isRegexpStringMatch, useSearchPage} from '@docusaurus/theme-common';
16
+ import {DocSearchButton, useDocSearchKeyboardEvents} from '@docsearch/react';
17
+ import {useAlgoliaContextualFacetFilters} from '@docusaurus/theme-search-algolia/client';
18
+ import Translate, {translate} from '@docusaurus/Translate';
19
+
20
+ import type {
21
+ DocSearchModal as DocSearchModalType,
22
+ DocSearchModalProps,
23
+ } from '@docsearch/react';
24
+ import type {
25
+ InternalDocSearchHit,
26
+ StoredDocSearchHit,
27
+ } from '@docsearch/react/dist/esm/types';
28
+ import type {SearchClient} from 'algoliasearch/lite';
29
+ import type {AutocompleteState} from '@algolia/autocomplete-core';
30
+
31
+ type DocSearchProps = Omit<
32
+ DocSearchModalProps,
33
+ 'onClose' | 'initialScrollY'
34
+ > & {
35
+ contextualSearch?: string;
36
+ externalUrlRegex?: string;
37
+ searchPagePath: boolean | string;
38
+ };
39
+
40
+ let DocSearchModal: typeof DocSearchModalType | null = null;
41
+
42
+ function Hit({
43
+ hit,
44
+ children,
45
+ }: {
46
+ hit: InternalDocSearchHit | StoredDocSearchHit;
47
+ children: React.ReactNode;
48
+ }) {
49
+ return <Link to={hit.url}>{children}</Link>;
50
+ }
51
+
52
+ type ResultsFooterProps = {
53
+ state: AutocompleteState<InternalDocSearchHit>;
54
+ onClose: () => void;
55
+ };
56
+
57
+ function ResultsFooter({state, onClose}: ResultsFooterProps) {
58
+ const {generateSearchPageLink} = useSearchPage();
59
+
60
+ return (
61
+ <Link to={generateSearchPageLink(state.query)} onClick={onClose}>
62
+ <Translate
63
+ id="theme.SearchBar.seeAll"
64
+ values={{count: state.context.nbHits}}>
65
+ {'See all {count} results'}
66
+ </Translate>
67
+ </Link>
68
+ );
69
+ }
70
+
71
+ type FacetFilters = Required<
72
+ Required<DocSearchProps>['searchParameters']
73
+ >['facetFilters'];
74
+
75
+ function mergeFacetFilters(f1: FacetFilters, f2: FacetFilters): FacetFilters {
76
+ const normalize = (
77
+ f: FacetFilters,
78
+ ): readonly string[] | readonly (string | readonly string[])[] =>
79
+ typeof f === 'string' ? [f] : f;
80
+ return [...normalize(f1), ...normalize(f2)] as FacetFilters;
81
+ }
82
+
83
+ function DocSearch({
84
+ contextualSearch,
85
+ externalUrlRegex,
86
+ ...props
87
+ }: DocSearchProps) {
88
+ const {siteMetadata} = useDocusaurusContext();
89
+
90
+ const contextualSearchFacetFilters =
91
+ useAlgoliaContextualFacetFilters() as FacetFilters;
92
+
93
+ const configFacetFilters: FacetFilters =
94
+ props.searchParameters?.facetFilters ?? [];
95
+
96
+ const facetFilters: FacetFilters = contextualSearch
97
+ ? // Merge contextual search filters with config filters
98
+ mergeFacetFilters(contextualSearchFacetFilters, configFacetFilters)
99
+ : // ... or use config facetFilters
100
+ configFacetFilters;
101
+
102
+ // We let user override default searchParameters if she wants to
103
+ const searchParameters: DocSearchProps['searchParameters'] = {
104
+ ...props.searchParameters,
105
+ facetFilters,
106
+ };
107
+
108
+ const {withBaseUrl} = useBaseUrlUtils();
109
+ const history = useHistory();
110
+ const searchContainer = useRef<HTMLDivElement | null>(null);
111
+ const searchButtonRef = useRef<HTMLButtonElement>(null);
112
+ const [isOpen, setIsOpen] = useState(false);
113
+ const [initialQuery, setInitialQuery] = useState<string | undefined>(
114
+ undefined,
115
+ );
116
+
117
+ const importDocSearchModalIfNeeded = useCallback(() => {
118
+ if (DocSearchModal) {
119
+ return Promise.resolve();
120
+ }
121
+
122
+ return Promise.all([
123
+ import('@docsearch/react/modal') as Promise<
124
+ typeof import('@docsearch/react')
125
+ >,
126
+ import('@docsearch/react/style'),
127
+ import('./styles.css'),
128
+ ]).then(([{DocSearchModal: Modal}]) => {
129
+ DocSearchModal = Modal;
130
+ });
131
+ }, []);
132
+
133
+ const onOpen = useCallback(() => {
134
+ importDocSearchModalIfNeeded().then(() => {
135
+ searchContainer.current = document.createElement('div');
136
+ document.body.insertBefore(
137
+ searchContainer.current,
138
+ document.body.firstChild,
139
+ );
140
+ setIsOpen(true);
141
+ });
142
+ }, [importDocSearchModalIfNeeded, setIsOpen]);
143
+
144
+ const onClose = useCallback(() => {
145
+ setIsOpen(false);
146
+ searchContainer.current?.remove();
147
+ }, [setIsOpen]);
148
+
149
+ const onInput = useCallback(
150
+ (event: KeyboardEvent) => {
151
+ importDocSearchModalIfNeeded().then(() => {
152
+ setIsOpen(true);
153
+ setInitialQuery(event.key);
154
+ });
155
+ },
156
+ [importDocSearchModalIfNeeded, setIsOpen, setInitialQuery],
157
+ );
158
+
159
+ const navigator = useRef({
160
+ navigate({itemUrl}: {itemUrl?: string}) {
161
+ // Algolia results could contain URL's from other domains which cannot
162
+ // be served through history and should navigate with window.location
163
+ if (isRegexpStringMatch(externalUrlRegex, itemUrl)) {
164
+ window.location.href = itemUrl!;
165
+ } else {
166
+ history.push(itemUrl!);
167
+ }
168
+ },
169
+ }).current;
170
+
171
+ const transformItems = useRef<DocSearchModalProps['transformItems']>(
172
+ (items) =>
173
+ items.map((item) => {
174
+ // If Algolia contains a external domain, we should navigate without
175
+ // relative URL
176
+ if (isRegexpStringMatch(externalUrlRegex, item.url)) {
177
+ return item;
178
+ }
179
+
180
+ // We transform the absolute URL into a relative URL.
181
+ const url = new URL(item.url);
182
+ return {
183
+ ...item,
184
+ url: withBaseUrl(`${url.pathname}${url.hash}`),
185
+ };
186
+ }),
187
+ ).current;
188
+
189
+ const resultsFooterComponent: DocSearchProps['resultsFooterComponent'] =
190
+ useMemo(
191
+ () =>
192
+ // eslint-disable-next-line react/no-unstable-nested-components
193
+ (footerProps: Omit<ResultsFooterProps, 'onClose'>): JSX.Element =>
194
+ <ResultsFooter {...footerProps} onClose={onClose} />,
195
+ [onClose],
196
+ );
197
+
198
+ const transformSearchClient = useCallback(
199
+ (searchClient: SearchClient) => {
200
+ searchClient.addAlgoliaAgent(
201
+ 'docusaurus',
202
+ siteMetadata.docusaurusVersion,
203
+ );
204
+
205
+ return searchClient;
206
+ },
207
+ [siteMetadata.docusaurusVersion],
208
+ );
209
+
210
+ useDocSearchKeyboardEvents({
211
+ isOpen,
212
+ onOpen,
213
+ onClose,
214
+ onInput,
215
+ searchButtonRef,
216
+ });
217
+
218
+ const translatedSearchLabel = translate({
219
+ id: 'theme.SearchBar.label',
220
+ message: 'Search',
221
+ description: 'The ARIA label and placeholder for search button',
222
+ });
223
+
224
+ return (
225
+ <>
226
+ <Head>
227
+ {/* This hints the browser that the website will load data from Algolia,
228
+ and allows it to preconnect to the DocSearch cluster. It makes the first
229
+ query faster, especially on mobile. */}
230
+ <link
231
+ rel="preconnect"
232
+ href={`https://${props.appId}-dsn.algolia.net`}
233
+ crossOrigin="anonymous"
234
+ />
235
+ </Head>
236
+
237
+ <DocSearchButton
238
+ onTouchStart={importDocSearchModalIfNeeded}
239
+ onFocus={importDocSearchModalIfNeeded}
240
+ onMouseOver={importDocSearchModalIfNeeded}
241
+ onClick={onOpen}
242
+ ref={searchButtonRef}
243
+ translations={{
244
+ buttonText: translatedSearchLabel,
245
+ buttonAriaLabel: translatedSearchLabel,
246
+ }}
247
+ />
248
+
249
+ {isOpen &&
250
+ DocSearchModal &&
251
+ searchContainer.current &&
252
+ createPortal(
253
+ <DocSearchModal
254
+ onClose={onClose}
255
+ initialScrollY={window.scrollY}
256
+ initialQuery={initialQuery}
257
+ navigator={navigator}
258
+ transformItems={transformItems}
259
+ hitComponent={Hit}
260
+ transformSearchClient={transformSearchClient}
261
+ {...(props.searchPagePath && {
262
+ resultsFooterComponent,
263
+ })}
264
+ {...props}
265
+ searchParameters={searchParameters}
266
+ />,
267
+ searchContainer.current,
268
+ )}
269
+ </>
270
+ );
271
+ }
272
+
273
+ export default function SearchBar(): JSX.Element {
274
+ const {siteConfig} = useDocusaurusContext();
275
+ return <DocSearch {...(siteConfig.themeConfig.algolia as DocSearchProps)} />;
276
+ }