@docusaurus/theme-search-algolia 2.0.0-beta.15d451942 → 2.0.0-beta.18

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 +107 -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 +45 -50
  11. package/lib/theme/SearchBar/styles.css +21 -0
  12. package/lib/theme/SearchBar/styles.module.css +20 -0
  13. package/lib/theme/SearchPage/index.d.ts +8 -0
  14. package/{src → lib}/theme/SearchPage/index.js +95 -128
  15. package/lib/theme/SearchPage/styles.module.css +119 -0
  16. package/lib/validateThemeConfig.d.ts +15 -0
  17. package/lib/validateThemeConfig.js +50 -0
  18. package/package.json +34 -13
  19. package/src/client/index.ts +8 -0
  20. package/src/{theme/hooks/useAlgoliaContextualFacetFilters.js → client/useAlgoliaContextualFacetFilters.ts} +3 -3
  21. package/src/deps.d.ts +10 -0
  22. package/src/index.ts +116 -0
  23. package/src/templates/{opensearch.js → opensearch.ts} +7 -5
  24. package/src/theme/SearchBar/index.tsx +276 -0
  25. package/src/theme/SearchPage/index.tsx +528 -0
  26. package/src/theme/SearchPage/styles.module.css +15 -34
  27. package/src/theme-search-algolia.d.ts +35 -0
  28. package/src/types.d.ts +10 -0
  29. package/src/validateThemeConfig.ts +53 -0
  30. package/src/__tests__/validateThemeConfig.test.js +0 -121
  31. package/src/index.js +0 -92
  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
@@ -0,0 +1,7 @@
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
+ export { useAlgoliaContextualFacetFilters } from './useAlgoliaContextualFacetFilters';
@@ -0,0 +1,7 @@
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
+ export {useAlgoliaContextualFacetFilters} from './useAlgoliaContextualFacetFilters';
@@ -0,0 +1,7 @@
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
+ export declare function useAlgoliaContextualFacetFilters(): [string, string[]];
@@ -0,0 +1,15 @@
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
+ import {useContextualSearchFilters} from '@docusaurus/theme-common';
8
+ // Translate search-engine agnostic search filters to Algolia search filters
9
+ export function useAlgoliaContextualFacetFilters() {
10
+ const {locale, tags} = useContextualSearchFilters();
11
+ // seems safe to convert locale->language, see AlgoliaSearchMetadata comment
12
+ const languageFilter = `language:${locale}`;
13
+ const tagsFilter = tags.map((tag) => `docusaurus_tag:${tag}`);
14
+ return [languageFilter, tagsFilter];
15
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,9 @@
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
+ import type { LoadContext, Plugin } from '@docusaurus/types';
8
+ export default function themeSearchAlgolia(context: LoadContext): Plugin<void>;
9
+ export { validateThemeConfig } from './validateThemeConfig';
package/lib/index.js ADDED
@@ -0,0 +1,107 @@
1
+ 'use strict';
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, '__esModule', {value: true});
9
+ exports.validateThemeConfig = void 0;
10
+ const tslib_1 = require('tslib');
11
+ const path_1 = tslib_1.__importDefault(require('path'));
12
+ const fs_extra_1 = tslib_1.__importDefault(require('fs-extra'));
13
+ const eta_1 = require('eta');
14
+ const utils_1 = require('@docusaurus/utils');
15
+ const theme_translations_1 = require('@docusaurus/theme-translations');
16
+ const logger_1 = tslib_1.__importDefault(require('@docusaurus/logger'));
17
+ const opensearch_1 = tslib_1.__importDefault(require('./templates/opensearch'));
18
+ const lodash_1 = tslib_1.__importDefault(require('lodash'));
19
+ const getCompiledOpenSearchTemplate = lodash_1.default.memoize(() =>
20
+ (0, eta_1.compile)(opensearch_1.default.trim()),
21
+ );
22
+ function renderOpenSearchTemplate(data) {
23
+ const compiled = getCompiledOpenSearchTemplate();
24
+ return compiled(data, eta_1.defaultConfig);
25
+ }
26
+ const OPEN_SEARCH_FILENAME = 'opensearch.xml';
27
+ function themeSearchAlgolia(context) {
28
+ const {
29
+ baseUrl,
30
+ siteConfig: {title, url, favicon, themeConfig},
31
+ i18n: {currentLocale},
32
+ } = context;
33
+ const {
34
+ algolia: {searchPagePath},
35
+ } = themeConfig;
36
+ return {
37
+ name: 'docusaurus-theme-search-algolia',
38
+ getThemePath() {
39
+ return '../lib/theme';
40
+ },
41
+ getTypeScriptThemePath() {
42
+ return '../src/theme';
43
+ },
44
+ getDefaultCodeTranslationMessages() {
45
+ return (0, theme_translations_1.readDefaultCodeTranslationMessages)({
46
+ locale: currentLocale,
47
+ name: 'theme-search-algolia',
48
+ });
49
+ },
50
+ async contentLoaded({actions: {addRoute}}) {
51
+ if (searchPagePath) {
52
+ addRoute({
53
+ path: (0, utils_1.normalizeUrl)([baseUrl, searchPagePath]),
54
+ component: '@theme/SearchPage',
55
+ exact: true,
56
+ });
57
+ }
58
+ },
59
+ async postBuild({outDir}) {
60
+ if (searchPagePath) {
61
+ const siteUrl = (0, utils_1.normalizeUrl)([url, baseUrl]);
62
+ try {
63
+ await fs_extra_1.default.writeFile(
64
+ path_1.default.join(outDir, OPEN_SEARCH_FILENAME),
65
+ renderOpenSearchTemplate({
66
+ title,
67
+ siteUrl,
68
+ searchUrl: (0, utils_1.normalizeUrl)([siteUrl, searchPagePath]),
69
+ faviconUrl: favicon
70
+ ? (0, utils_1.normalizeUrl)([siteUrl, favicon])
71
+ : null,
72
+ }),
73
+ );
74
+ } catch (err) {
75
+ logger_1.default.error('Generating OpenSearch file failed.');
76
+ throw err;
77
+ }
78
+ }
79
+ },
80
+ injectHtmlTags() {
81
+ if (!searchPagePath) {
82
+ return {};
83
+ }
84
+ return {
85
+ headTags: [
86
+ {
87
+ tagName: 'link',
88
+ attributes: {
89
+ rel: 'search',
90
+ type: 'application/opensearchdescription+xml',
91
+ title,
92
+ href: (0, utils_1.normalizeUrl)([baseUrl, OPEN_SEARCH_FILENAME]),
93
+ },
94
+ },
95
+ ],
96
+ };
97
+ },
98
+ };
99
+ }
100
+ exports.default = themeSearchAlgolia;
101
+ var validateThemeConfig_1 = require('./validateThemeConfig');
102
+ Object.defineProperty(exports, 'validateThemeConfig', {
103
+ enumerable: true,
104
+ get: function () {
105
+ return validateThemeConfig_1.validateThemeConfig;
106
+ },
107
+ });
@@ -0,0 +1,8 @@
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
+ declare const _default: "\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\"\n xmlns:moz=\"http://www.mozilla.org/2006/browser/search/\">\n <ShortName><%= it.title %></ShortName>\n <Description>Search <%= it.title %></Description>\n <InputEncoding>UTF-8</InputEncoding>\n <% if (it.faviconUrl) { _%>\n <Image width=\"16\" height=\"16\" type=\"image/x-icon\"><%= it.faviconUrl %></Image>\n <% } _%>\n <Url type=\"text/html\" method=\"get\" template=\"<%= it.searchUrl %>?q={searchTerms}\"/>\n <Url type=\"application/opensearchdescription+xml\" rel=\"self\" template=\"<%= it.siteUrl %>opensearch.xml\" />\n <moz:SearchForm><%= it.siteUrl %></moz:SearchForm>\n</OpenSearchDescription>\n";
8
+ export default _default;
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+ /**
3
+ * Copyright (c) Facebook, Inc. and its affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ Object.defineProperty(exports, '__esModule', {value: true});
9
+ exports.default = `
10
+ <?xml version="1.0" encoding="UTF-8"?>
11
+ <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
12
+ xmlns:moz="http://www.mozilla.org/2006/browser/search/">
13
+ <ShortName><%= it.title %></ShortName>
14
+ <Description>Search <%= it.title %></Description>
15
+ <InputEncoding>UTF-8</InputEncoding>
16
+ <% if (it.faviconUrl) { _%>
17
+ <Image width="16" height="16" type="image/x-icon"><%= it.faviconUrl %></Image>
18
+ <% } _%>
19
+ <Url type="text/html" method="get" template="<%= it.searchUrl %>?q={searchTerms}"/>
20
+ <Url type="application/opensearchdescription+xml" rel="self" template="<%= it.siteUrl %>opensearch.xml" />
21
+ <moz:SearchForm><%= it.siteUrl %></moz:SearchForm>
22
+ </OpenSearchDescription>
23
+ `;
@@ -0,0 +1,8 @@
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
+ /// <reference types="react" />
8
+ export default function SearchBar(): JSX.Element;
@@ -4,7 +4,6 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
-
8
7
  import React, {useState, useRef, useCallback, useMemo} from 'react';
9
8
  import {createPortal} from 'react-dom';
10
9
  import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
@@ -12,59 +11,55 @@ import {useHistory} from '@docusaurus/router';
12
11
  import {useBaseUrlUtils} from '@docusaurus/useBaseUrl';
13
12
  import Link from '@docusaurus/Link';
14
13
  import Head from '@docusaurus/Head';
15
- import useSearchQuery from '@theme/hooks/useSearchQuery';
14
+ import {isRegexpStringMatch, useSearchPage} from '@docusaurus/theme-common';
16
15
  import {DocSearchButton, useDocSearchKeyboardEvents} from '@docsearch/react';
17
- import useAlgoliaContextualFacetFilters from '@theme/hooks/useAlgoliaContextualFacetFilters';
18
- import {translate} from '@docusaurus/Translate';
16
+ import {useAlgoliaContextualFacetFilters} from '@docusaurus/theme-search-algolia/client';
17
+ import Translate, {translate} from '@docusaurus/Translate';
19
18
  import styles from './styles.module.css';
20
-
21
19
  let DocSearchModal = null;
22
-
23
20
  function Hit({hit, children}) {
24
21
  return <Link to={hit.url}>{children}</Link>;
25
22
  }
26
-
27
23
  function ResultsFooter({state, onClose}) {
28
- const {generateSearchPageLink} = useSearchQuery();
29
-
24
+ const {generateSearchPageLink} = useSearchPage();
30
25
  return (
31
26
  <Link to={generateSearchPageLink(state.query)} onClick={onClose}>
32
- See all {state.context.nbHits} results
27
+ <Translate
28
+ id="theme.SearchBar.seeAll"
29
+ values={{count: state.context.nbHits}}>
30
+ {'See all {count} results'}
31
+ </Translate>
33
32
  </Link>
34
33
  );
35
34
  }
36
-
37
- function DocSearch({contextualSearch, ...props}) {
35
+ function mergeFacetFilters(f1, f2) {
36
+ const normalize = (f) => (typeof f === 'string' ? [f] : f);
37
+ return [...normalize(f1), ...normalize(f2)];
38
+ }
39
+ function DocSearch({contextualSearch, externalUrlRegex, ...props}) {
38
40
  const {siteMetadata} = useDocusaurusContext();
39
-
40
41
  const contextualSearchFacetFilters = useAlgoliaContextualFacetFilters();
41
-
42
42
  const configFacetFilters = props.searchParameters?.facetFilters ?? [];
43
-
44
43
  const facetFilters = contextualSearch
45
44
  ? // Merge contextual search filters with config filters
46
- [...contextualSearchFacetFilters, ...configFacetFilters]
45
+ mergeFacetFilters(contextualSearchFacetFilters, configFacetFilters)
47
46
  : // ... or use config facetFilters
48
47
  configFacetFilters;
49
-
50
48
  // we let user override default searchParameters if he wants to
51
49
  const searchParameters = {
52
50
  ...props.searchParameters,
53
51
  facetFilters,
54
52
  };
55
-
56
53
  const {withBaseUrl} = useBaseUrlUtils();
57
54
  const history = useHistory();
58
55
  const searchContainer = useRef(null);
59
56
  const searchButtonRef = useRef(null);
60
57
  const [isOpen, setIsOpen] = useState(false);
61
- const [initialQuery, setInitialQuery] = useState(null);
62
-
58
+ const [initialQuery, setInitialQuery] = useState(undefined);
63
59
  const importDocSearchModalIfNeeded = useCallback(() => {
64
60
  if (DocSearchModal) {
65
61
  return Promise.resolve();
66
62
  }
67
-
68
63
  return Promise.all([
69
64
  import('@docsearch/react/modal'),
70
65
  import('@docsearch/react/style'),
@@ -73,7 +68,6 @@ function DocSearch({contextualSearch, ...props}) {
73
68
  DocSearchModal = Modal;
74
69
  });
75
70
  }, []);
76
-
77
71
  const onOpen = useCallback(() => {
78
72
  importDocSearchModalIfNeeded().then(() => {
79
73
  searchContainer.current = document.createElement('div');
@@ -84,12 +78,10 @@ function DocSearch({contextualSearch, ...props}) {
84
78
  setIsOpen(true);
85
79
  });
86
80
  }, [importDocSearchModalIfNeeded, setIsOpen]);
87
-
88
81
  const onClose = useCallback(() => {
89
82
  setIsOpen(false);
90
- searchContainer.current.remove();
83
+ searchContainer.current?.remove();
91
84
  }, [setIsOpen]);
92
-
93
85
  const onInput = useCallback(
94
86
  (event) => {
95
87
  importDocSearchModalIfNeeded().then(() => {
@@ -99,45 +91,49 @@ function DocSearch({contextualSearch, ...props}) {
99
91
  },
100
92
  [importDocSearchModalIfNeeded, setIsOpen, setInitialQuery],
101
93
  );
102
-
103
94
  const navigator = useRef({
104
95
  navigate({itemUrl}) {
105
- history.push(itemUrl);
96
+ // Algolia results could contain URL's from other domains which cannot
97
+ // be served through history and should navigate with window.location
98
+ if (isRegexpStringMatch(externalUrlRegex, itemUrl)) {
99
+ window.location.href = itemUrl;
100
+ } else {
101
+ history.push(itemUrl);
102
+ }
106
103
  },
107
104
  }).current;
108
-
109
- const transformItems = useRef((items) => {
110
- return items.map((item) => {
105
+ const transformItems = useRef((items) =>
106
+ items.map((item) => {
107
+ // If Algolia contains a external domain, we should navigate without
108
+ // relative URL
109
+ if (isRegexpStringMatch(externalUrlRegex, item.url)) {
110
+ return item;
111
+ }
111
112
  // We transform the absolute URL into a relative URL.
112
- // Alternatively, we can use `new URL(item.url)` but it's not
113
- // supported in IE.
114
- const a = document.createElement('a');
115
- a.href = item.url;
116
-
113
+ const url = new URL(item.url);
117
114
  return {
118
115
  ...item,
119
- url: withBaseUrl(`${a.pathname}${a.hash}`),
116
+ url: withBaseUrl(`${url.pathname}${url.hash}`),
120
117
  };
121
- });
122
- }).current;
123
-
118
+ }),
119
+ ).current;
124
120
  const resultsFooterComponent = useMemo(
125
- () => (footerProps) => <ResultsFooter {...footerProps} onClose={onClose} />,
121
+ () =>
122
+ // eslint-disable-next-line react/no-unstable-nested-components
123
+ (footerProps) =>
124
+ <ResultsFooter {...footerProps} onClose={onClose} />,
126
125
  [onClose],
127
126
  );
128
-
129
127
  const transformSearchClient = useCallback(
130
128
  (searchClient) => {
131
129
  searchClient.addAlgoliaAgent(
132
130
  'docusaurus',
133
131
  siteMetadata.docusaurusVersion,
134
132
  );
135
-
136
133
  return searchClient;
137
134
  },
138
135
  [siteMetadata.docusaurusVersion],
139
136
  );
140
-
141
137
  useDocSearchKeyboardEvents({
142
138
  isOpen,
143
139
  onOpen,
@@ -145,13 +141,11 @@ function DocSearch({contextualSearch, ...props}) {
145
141
  onInput,
146
142
  searchButtonRef,
147
143
  });
148
-
149
144
  const translatedSearchLabel = translate({
150
145
  id: 'theme.SearchBar.label',
151
146
  message: 'Search',
152
147
  description: 'The ARIA label and placeholder for search button',
153
148
  });
154
-
155
149
  return (
156
150
  <>
157
151
  <Head>
@@ -180,6 +174,8 @@ function DocSearch({contextualSearch, ...props}) {
180
174
  </div>
181
175
 
182
176
  {isOpen &&
177
+ DocSearchModal &&
178
+ searchContainer.current &&
183
179
  createPortal(
184
180
  <DocSearchModal
185
181
  onClose={onClose}
@@ -188,8 +184,10 @@ function DocSearch({contextualSearch, ...props}) {
188
184
  navigator={navigator}
189
185
  transformItems={transformItems}
190
186
  hitComponent={Hit}
191
- resultsFooterComponent={resultsFooterComponent}
192
187
  transformSearchClient={transformSearchClient}
188
+ {...(props.searchPagePath && {
189
+ resultsFooterComponent,
190
+ })}
193
191
  {...props}
194
192
  searchParameters={searchParameters}
195
193
  />,
@@ -198,10 +196,7 @@ function DocSearch({contextualSearch, ...props}) {
198
196
  </>
199
197
  );
200
198
  }
201
-
202
- function SearchBar() {
199
+ export default function SearchBar() {
203
200
  const {siteConfig} = useDocusaurusContext();
204
201
  return <DocSearch {...siteConfig.themeConfig.algolia} />;
205
202
  }
206
-
207
- export default SearchBar;
@@ -0,0 +1,21 @@
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
+ :root {
9
+ --docsearch-primary-color: var(--ifm-color-primary);
10
+ --docsearch-text-color: var(--ifm-font-color-base);
11
+ }
12
+
13
+ .DocSearch-Button {
14
+ margin: 0;
15
+ transition: all var(--ifm-transition-fast)
16
+ var(--ifm-transition-timing-default);
17
+ }
18
+
19
+ .DocSearch-Container {
20
+ z-index: calc(var(--ifm-z-index-fixed) + 1);
21
+ }
@@ -0,0 +1,20 @@
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
+ @media (max-width: 996px) {
9
+ .searchBox {
10
+ position: absolute;
11
+ right: var(--ifm-navbar-padding-horizontal);
12
+ }
13
+ }
14
+
15
+ @media (min-width: 997px) {
16
+ .searchBox {
17
+ padding: var(--ifm-navbar-item-padding-vertical)
18
+ var(--ifm-navbar-item-padding-horizontal);
19
+ }
20
+ }
@@ -0,0 +1,8 @@
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
+ /// <reference types="react" />
8
+ export default function SearchPage(): JSX.Element;