Skip to content

Commit

Permalink
Fix compatibility issues with 2.0.0-rc1
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonbosco committed Jul 21, 2022
1 parent a30f233 commit bc9e74c
Show file tree
Hide file tree
Showing 27 changed files with 4,853 additions and 544 deletions.
3 changes: 1 addition & 2 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
copyUntypedFiles.mjs
.tsbuildinfo
.tsbuildinfo*
tsconfig*
__tests__
38 changes: 27 additions & 11 deletions copyUntypedFiles.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,31 @@
*/

import fs from 'fs-extra';
import {fileURLToPath} from 'url';
import path from 'path';
import chokidar from 'chokidar';

/**
* Copy all untyped and static assets files to lib.
*/
const srcDir = fileURLToPath(new URL('src', import.meta.url));
const libDir = fileURLToPath(new URL('lib', import.meta.url));
await fs.copy(srcDir, libDir, {
filter(filepath) {
return !/__tests__/.test(filepath) && !/\.tsx?$/.test(filepath);
},
});
const srcDir = path.join(process.cwd(), 'src');
const libDir = path.join(process.cwd(), 'lib');

const ignoredPattern = /(?:__tests__|\.tsx?$)/;

async function copy() {
await fs.copy(srcDir, libDir, {
filter(testedPath) {
return !ignoredPattern.test(testedPath);
},
});
}

if (process.argv.includes('--watch')) {
const watcher = chokidar.watch(srcDir, {
ignored: ignoredPattern,
ignoreInitial: true,
persistent: true,
});
['add', 'change', 'unlink', 'addDir', 'unlinkDir'].forEach((event) =>
watcher.on(event, copy),
);
} else {
await copy();
}
1 change: 1 addition & 0 deletions lib/.tsbuildinfo

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions lib/.tsbuildinfo-client

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion lib/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export {useTypesenseContextualFilters} from './useTypesenseContextualFacetFilters';
export { useTypesenseContextualFilters } from './useTypesenseContextualFacetFilters';
16 changes: 8 additions & 8 deletions lib/client/useTypesenseContextualFacetFilters.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
* LICENSE file in the root directory of this source tree.
*/
// @ts-ignore Imported from peer dependency
import {useContextualSearchFilters} from '@docusaurus/theme-common';
import { useContextualSearchFilters } from '@docusaurus/theme-common';
export function useTypesenseContextualFilters() {
const {locale, tags} = useContextualSearchFilters();
const languageFilter = `language:=${locale}`;
let tagsFilter;
if (tags.length > 0) {
tagsFilter = `docusaurus_tag:=[${tags.join(',')}]`;
}
return [languageFilter, tagsFilter].filter((e) => e).join(' && ');
const { locale, tags } = useContextualSearchFilters();
const languageFilter = `language:=${locale}`;
let tagsFilter;
if (tags.length > 0) {
tagsFilter = `docusaurus_tag:=[${tags.join(',')}]`;
}
return [languageFilter, tagsFilter].filter(e => e).join(' && ');
}
173 changes: 77 additions & 96 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,109 +1,90 @@
'use strict';
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, '__esModule', {value: true});
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateThemeConfig = void 0;
const tslib_1 = require('tslib');
const path_1 = tslib_1.__importDefault(require('path'));
const fs_extra_1 = tslib_1.__importDefault(require('fs-extra'));
const eta_1 = require('eta');
const utils_1 = require('@docusaurus/utils');
const theme_translations_1 = require('@docusaurus/theme-translations');
const logger_1 = tslib_1.__importDefault(require('@docusaurus/logger'));
const opensearch_1 = tslib_1.__importDefault(require('./templates/opensearch'));
const lodash_1 = tslib_1.__importDefault(require('lodash'));
const getCompiledOpenSearchTemplate = lodash_1.default.memoize(() =>
(0, eta_1.compile)(opensearch_1.default.trim()),
);
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const lodash_1 = tslib_1.__importDefault(require("lodash"));
const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
const eta_1 = require("eta");
const utils_1 = require("@docusaurus/utils");
const theme_translations_1 = require("@docusaurus/theme-translations");
const opensearch_1 = tslib_1.__importDefault(require("./templates/opensearch"));
const getCompiledOpenSearchTemplate = lodash_1.default.memoize(() => (0, eta_1.compile)(opensearch_1.default.trim()));
function renderOpenSearchTemplate(data) {
const compiled = getCompiledOpenSearchTemplate();
return compiled(data, eta_1.defaultConfig);
const compiled = getCompiledOpenSearchTemplate();
return compiled(data, eta_1.defaultConfig);
}
const OPEN_SEARCH_FILENAME = 'opensearch.xml';
function themeSearchTypesense(context) {
const {
baseUrl,
siteConfig: {title, url, favicon, themeConfig},
i18n: {currentLocale},
} = context;
const {
typesense: {searchPagePath},
} = themeConfig;
return {
name: 'docusaurus-theme-search-typesense',
getThemePath() {
return path_1.default.resolve(__dirname, '../lib/theme');
},
getTypeScriptThemePath() {
return path_1.default.resolve(__dirname, '../src/theme');
},
getDefaultCodeTranslationMessages() {
return (0, theme_translations_1.readDefaultCodeTranslationMessages)({
locale: currentLocale,
name: 'theme-search-typesense',
});
},
// @ts-ignore
async contentLoaded({actions: {addRoute}}) {
if (searchPagePath) {
addRoute({
path: (0, utils_1.normalizeUrl)([baseUrl, searchPagePath]),
component: '@theme/SearchPage',
exact: true,
});
}
},
// @ts-ignore
async postBuild({outDir}) {
if (searchPagePath) {
const siteUrl = (0, utils_1.normalizeUrl)([url, baseUrl]);
try {
await fs_extra_1.default.writeFile(
path_1.default.join(outDir, OPEN_SEARCH_FILENAME),
renderOpenSearchTemplate({
title,
siteUrl,
searchUrl: (0, utils_1.normalizeUrl)([siteUrl, searchPagePath]),
faviconUrl: favicon
? (0, utils_1.normalizeUrl)([siteUrl, favicon])
: null,
}),
);
} catch (err) {
logger_1.default.error('Generating OpenSearch file failed.');
throw err;
}
}
},
injectHtmlTags() {
if (!searchPagePath) {
return {};
}
return {
headTags: [
{
tagName: 'link',
attributes: {
rel: 'search',
type: 'application/opensearchdescription+xml',
title,
href: (0, utils_1.normalizeUrl)([baseUrl, OPEN_SEARCH_FILENAME]),
},
},
],
};
},
};
const { baseUrl, siteConfig: { title, url, favicon, themeConfig }, i18n: { currentLocale }, } = context;
const { typesense: { searchPagePath }, } = themeConfig;
return {
name: 'docusaurus-theme-search-typesense',
getThemePath() {
return '../lib/theme';
},
getTypeScriptThemePath() {
return '../src/theme';
},
getDefaultCodeTranslationMessages() {
return (0, theme_translations_1.readDefaultCodeTranslationMessages)({
locale: currentLocale,
name: 'theme-search-typesense',
});
},
contentLoaded({ actions: { addRoute } }) {
if (searchPagePath) {
addRoute({
path: (0, utils_1.normalizeUrl)([baseUrl, searchPagePath]),
component: '@theme/SearchPage',
exact: true,
});
}
},
async postBuild({ outDir }) {
if (searchPagePath) {
const siteUrl = (0, utils_1.normalizeUrl)([url, baseUrl]);
try {
await fs_extra_1.default.writeFile(path_1.default.join(outDir, OPEN_SEARCH_FILENAME), renderOpenSearchTemplate({
title,
siteUrl,
searchUrl: (0, utils_1.normalizeUrl)([siteUrl, searchPagePath]),
faviconUrl: favicon ? (0, utils_1.normalizeUrl)([siteUrl, favicon]) : null,
}));
}
catch (err) {
logger_1.default.error('Generating OpenSearch file failed.');
throw err;
}
}
},
injectHtmlTags() {
if (!searchPagePath) {
return {};
}
return {
headTags: [
{
tagName: 'link',
attributes: {
rel: 'search',
type: 'application/opensearchdescription+xml',
title,
href: (0, utils_1.normalizeUrl)([baseUrl, OPEN_SEARCH_FILENAME]),
},
},
],
};
},
};
}
exports.default = themeSearchTypesense;
var validateThemeConfig_1 = require('./validateThemeConfig');
Object.defineProperty(exports, 'validateThemeConfig', {
enumerable: true,
get: function () {
return validateThemeConfig_1.validateThemeConfig;
},
});
var validateThemeConfig_1 = require("./validateThemeConfig");
Object.defineProperty(exports, "validateThemeConfig", { enumerable: true, get: function () { return validateThemeConfig_1.validateThemeConfig; } });
4 changes: 2 additions & 2 deletions lib/templates/opensearch.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
'use strict';
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, '__esModule', {value: true});
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = `
<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
Expand Down
49 changes: 15 additions & 34 deletions lib/theme/SearchBar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ import {
} from 'typesense-docsearch-react';
import {useTypesenseContextualFilters} from '../../client';
// @ts-ignore
import Translate, {translate} from '@docusaurus/Translate';
import Translate from '@docusaurus/Translate';
// @ts-ignore
import styles from './styles.module.css';
import translations from '@theme/SearchTranslations';
let DocSearchModal = null;
function Hit({hit, children}) {
return <Link to={hit.url}>{children}</Link>;
Expand All @@ -44,16 +44,9 @@ function ResultsFooter({state, onClose}) {
);
}
function DocSearch({contextualSearch, externalUrlRegex, ...props}) {
var _a, _b;
const {siteMetadata} = useDocusaurusContext();
const contextualSearchFacetFilters = useTypesenseContextualFilters();
const configFacetFilters =
(_b =
(_a = props.typesenseSearchParameters) === null || _a === void 0
? void 0
: _a.filter_by) !== null && _b !== void 0
? _b
: '';
const configFacetFilters = props.typesenseSearchParameters?.filter_by ?? '';
const facetFilters = contextualSearch
? // Merge contextual search filters with config filters
[contextualSearchFacetFilters, configFacetFilters]
Expand Down Expand Up @@ -100,11 +93,8 @@ function DocSearch({contextualSearch, externalUrlRegex, ...props}) {
});
}, [importDocSearchModalIfNeeded, setIsOpen]);
const onClose = useCallback(() => {
var _a;
setIsOpen(false);
(_a = searchContainer.current) === null || _a === void 0
? void 0
: _a.remove();
searchContainer.current?.remove();
}, [setIsOpen]);
const onInput = useCallback(
(event) => {
Expand All @@ -128,7 +118,7 @@ function DocSearch({contextualSearch, externalUrlRegex, ...props}) {
}).current;
const transformItems = useRef((items) =>
items.map((item) => {
// If Algolia contains a external domain, we should navigate without
// If result contains a external domain, we should navigate without
// relative URL
if (isRegexpStringMatch(externalUrlRegex, item.url)) {
return item;
Expand All @@ -141,7 +131,6 @@ function DocSearch({contextualSearch, externalUrlRegex, ...props}) {
};
}),
).current;
//@ts-ignore
const resultsFooterComponent = useMemo(
() =>
// eslint-disable-next-line react/no-unstable-nested-components
Expand All @@ -156,26 +145,16 @@ function DocSearch({contextualSearch, externalUrlRegex, ...props}) {
onInput,
searchButtonRef,
});
const translatedSearchLabel = translate({
id: 'theme.SearchBar.label',
message: 'Search',
description: 'The ARIA label and placeholder for search button',
});
return (
<>
<div className={styles.searchBox}>
<DocSearchButton
onTouchStart={importDocSearchModalIfNeeded}
onFocus={importDocSearchModalIfNeeded}
onMouseOver={importDocSearchModalIfNeeded}
onClick={onOpen}
ref={searchButtonRef}
translations={{
buttonText: translatedSearchLabel,
buttonAriaLabel: translatedSearchLabel,
}}
/>
</div>
<DocSearchButton
onTouchStart={importDocSearchModalIfNeeded}
onFocus={importDocSearchModalIfNeeded}
onMouseOver={importDocSearchModalIfNeeded}
onClick={onOpen}
ref={searchButtonRef}
translations={translations.button}
/>

{isOpen &&
DocSearchModal &&
Expand All @@ -195,6 +174,8 @@ function DocSearch({contextualSearch, externalUrlRegex, ...props}) {
typesenseSearchParameters={typesenseSearchParameters}
typesenseServerConfig={typesenseServerConfig}
typesenseCollectionName={typesenseCollectionName}
placeholder={translations.placeholder}
translations={translations.modal}
/>,
searchContainer.current,
)}
Expand Down
2 changes: 1 addition & 1 deletion lib/theme/SearchBar/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
.DocSearch-Button {
margin: 0;
transition: all var(--ifm-transition-fast)
var(--ifm-transition-timing-default);
var(--ifm-transition-timing-default);
}

.DocSearch-Container {
Expand Down
Loading

0 comments on commit bc9e74c

Please sign in to comment.