chore: upgrade Prettier + regenerate lock file (#5611)

* Bump deps

* Run prettier

* Format docs

* Minor refactor

* Collapse objects

* Fix type

* Update lock file
This commit is contained in:
Joshua Chen 2021-09-30 18:54:17 +08:00 committed by GitHub
parent 4dbc458a22
commit 3f1f8255a2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
70 changed files with 1534 additions and 1517 deletions

View file

@ -7,10 +7,11 @@ coverage
packages/docusaurus/lib/ packages/docusaurus/lib/
packages/docusaurus-*/lib/* packages/docusaurus-*/lib/*
packages/docusaurus-*/lib-next/ packages/docusaurus-*/lib-next/
packages/docusaurus-init/templates/*/docusaurus.config.js
__fixtures__ __fixtures__
website/i18n website/i18n
website/versions.json website/versions.json
website/docusaurus.config.js
examples/**/package.json examples/
examples/**/sandbox.config.json

View file

@ -1,7 +1,7 @@
{ {
"arrowParens": "always", "arrowParens": "always",
"bracketSpacing": false, "bracketSpacing": false,
"jsxBracketSameLine": true, "bracketSameLine": true,
"printWidth": 80, "printWidth": 80,
"proseWrap": "never", "proseWrap": "never",
"singleQuote": true, "singleQuote": true,

View file

@ -108,7 +108,7 @@
"netlify-cli": "^2.58.0", "netlify-cli": "^2.58.0",
"nodemon": "^2.0.13", "nodemon": "^2.0.13",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"prettier": "^2.2.1", "prettier": "^2.4.1",
"react": "^17.0.1", "react": "^17.0.1",
"react-dom": "^17.0.1", "react-dom": "^17.0.1",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",

View file

@ -1,7 +1,4 @@
#!/usr/bin/env node #!/usr/bin/env node
// TODO remove when fixed: https://github.com/Stuk/eslint-plugin-header/issues/39
/* eslint-disable header/header */
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *

View file

@ -30,8 +30,8 @@ interface PluginOptions {
const createJSX = (node: Image, pathUrl: string) => { const createJSX = (node: Image, pathUrl: string) => {
const jsxNode = node; const jsxNode = node;
((jsxNode as unknown) as Literal).type = 'jsx'; (jsxNode as unknown as Literal).type = 'jsx';
((jsxNode as unknown) as Literal).value = `<img ${ (jsxNode as unknown as Literal).value = `<img ${
node.alt ? `alt={"${escapeHtml(node.alt)}"} ` : '' node.alt ? `alt={"${escapeHtml(node.alt)}"} ` : ''
}${ }${
node.url node.url

View file

@ -68,8 +68,10 @@ function toAssetRequireNode({
const children = stringifyContent(node); const children = stringifyContent(node);
const title = node.title ? `title="${escapeHtml(node.title)}"` : ''; const title = node.title ? `title="${escapeHtml(node.title)}"` : '';
((node as unknown) as Literal).type = 'jsx'; (node as unknown as Literal).type = 'jsx';
((node as unknown) as Literal).value = `<a target="_blank" href={${href}}${title}>${children}</a>`; (
node as unknown as Literal
).value = `<a target="_blank" href={${href}}${title}>${children}</a>`;
} }
// If the link looks like an asset link, we'll link to the asset, // If the link looks like an asset link, we'll link to the asset,

View file

@ -1,7 +1,4 @@
#!/usr/bin/env node #!/usr/bin/env node
// TODO remove when fixed: https://github.com/Stuk/eslint-plugin-header/issues/39
/* eslint-disable header/header */
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *

View file

@ -592,9 +592,9 @@ function migrateVersionedSidebar(
acc: {[key: string]: Array<Record<string, unknown> | string>}, acc: {[key: string]: Array<Record<string, unknown> | string>},
val, val,
) => { ) => {
acc[ acc[val[0].replace(versionRegex, '')] = (
val[0].replace(versionRegex, '') val[1] as Array<SidebarEntry>
] = (val[1] as Array<SidebarEntry>).map((item) => { ).map((item) => {
if (typeof item === 'string') { if (typeof item === 'string') {
return item.replace(versionRegex, ''); return item.replace(versionRegex, '');
} }

View file

@ -86,8 +86,13 @@ declare module '@docusaurus/Head' {
} }
declare module '@docusaurus/Link' { declare module '@docusaurus/Link' {
import type {CSSProperties, ComponentProps} from 'react';
type NavLinkProps = Partial<import('react-router-dom').NavLinkProps>; type NavLinkProps = Partial<import('react-router-dom').NavLinkProps>;
export type LinkProps = NavLinkProps & { export type LinkProps = NavLinkProps &
ComponentProps<'a'> & {
readonly className?: string;
readonly style?: CSSProperties;
readonly isNavLink?: boolean; readonly isNavLink?: boolean;
readonly to?: string; readonly to?: string;
readonly href?: string; readonly href?: string;
@ -110,7 +115,7 @@ declare module '@docusaurus/Interpolate' {
export type InterpolateValues< export type InterpolateValues<
Str extends string, Str extends string,
Value extends ReactNode Value extends ReactNode,
> = Record<ExtractInterpolatePlaceholders<Str>, Value>; > = Record<ExtractInterpolatePlaceholders<Str>, Value>;
// TS function overload: if all the values are plain strings, then interpolate returns a simple string // TS function overload: if all the values are plain strings, then interpolate returns a simple string

View file

@ -291,7 +291,7 @@ describe('collectRedirects', () => {
{ {
createRedirects: (routePath) => { createRedirects: (routePath) => {
if (routePath === '/') { if (routePath === '/') {
return ([[`/fromPath`]] as unknown) as string; return [[`/fromPath`]] as unknown as string;
} }
return undefined; return undefined;
}, },

View file

@ -50,7 +50,7 @@ describe('normalizePluginOptions', () => {
test('should reject bad fromExtensions user inputs', () => { test('should reject bad fromExtensions user inputs', () => {
expect(() => expect(() =>
normalizePluginOptions({ normalizePluginOptions({
fromExtensions: ([null, undefined, 123, true] as unknown) as string[], fromExtensions: [null, undefined, 123, true] as unknown as string[],
}), }),
).toThrowErrorMatchingSnapshot(); ).toThrowErrorMatchingSnapshot();
}); });
@ -58,7 +58,7 @@ describe('normalizePluginOptions', () => {
test('should reject bad toExtensions user inputs', () => { test('should reject bad toExtensions user inputs', () => {
expect(() => expect(() =>
normalizePluginOptions({ normalizePluginOptions({
toExtensions: ([null, undefined, 123, true] as unknown) as string[], toExtensions: [null, undefined, 123, true] as unknown as string[],
}), }),
).toThrowErrorMatchingSnapshot(); ).toThrowErrorMatchingSnapshot();
}); });
@ -66,10 +66,7 @@ describe('normalizePluginOptions', () => {
test('should reject bad createRedirects user inputs', () => { test('should reject bad createRedirects user inputs', () => {
expect(() => expect(() =>
normalizePluginOptions({ normalizePluginOptions({
createRedirects: ([ createRedirects: ['bad', 'value'] as unknown as CreateRedirectsFnOption,
'bad',
'value',
] as unknown) as CreateRedirectsFnOption,
}), }),
).toThrowErrorMatchingSnapshot(); ).toThrowErrorMatchingSnapshot();
}); });

View file

@ -51,14 +51,14 @@ describe('validateRedirect', () => {
expect(() => expect(() =>
validateRedirect({ validateRedirect({
from: (null as unknown) as string, from: null as unknown as string,
to: '/toSomePath?queryString=xyz', to: '/toSomePath?queryString=xyz',
}), }),
).toThrowErrorMatchingSnapshot(); ).toThrowErrorMatchingSnapshot();
expect(() => expect(() =>
validateRedirect({ validateRedirect({
from: (['heyho'] as unknown) as string, from: ['heyho'] as unknown as string,
to: '/toSomePath?queryString=xyz', to: '/toSomePath?queryString=xyz',
}), }),
).toThrowErrorMatchingSnapshot(); ).toThrowErrorMatchingSnapshot();

View file

@ -62,7 +62,8 @@ export function getBlogTags(blogPosts: BlogPost[]): BlogTags {
}); });
} }
const DATE_FILENAME_REGEX = /^(?<date>\d{4}[-/]\d{1,2}[-/]\d{1,2})[-/]?(?<text>.*?)(\/index)?.mdx?$/; const DATE_FILENAME_REGEX =
/^(?<date>\d{4}[-/]\d{1,2}[-/]\d{1,2})[-/]?(?<text>.*?)(\/index)?.mdx?$/;
type ParsedBlogFileName = { type ParsedBlogFileName = {
date: Date | undefined; date: Date | undefined;
@ -199,12 +200,8 @@ async function processBlogSourceFile(
const blogSourceAbsolute = path.join(blogDirPath, blogSourceRelative); const blogSourceAbsolute = path.join(blogDirPath, blogSourceRelative);
const { const {frontMatter, content, contentTitle, excerpt} =
frontMatter, await parseBlogPostMarkdownFile(blogSourceAbsolute);
content,
contentTitle,
excerpt,
} = await parseBlogPostMarkdownFile(blogSourceAbsolute);
const aliasedSource = aliasedSitePath(blogSourceAbsolute, siteDir); const aliasedSource = aliasedSitePath(blogSourceAbsolute, siteDir);

View file

@ -563,12 +563,8 @@ describe('versioned site', () => {
options, options,
}); });
expect(versionsMetadata.length).toEqual(4); expect(versionsMetadata.length).toEqual(4);
const [ const [currentVersion, version101, version100, versionWithSlugs] =
currentVersion, versionsMetadata;
version101,
version100,
versionWithSlugs,
] = versionsMetadata;
const currentVersionTestUtils = createTestUtils({ const currentVersionTestUtils = createTestUtils({
siteDir, siteDir,

View file

@ -575,12 +575,8 @@ describe('versioned website', () => {
const {siteDir, plugin, pluginContentDir} = await loadSite(); const {siteDir, plugin, pluginContentDir} = await loadSite();
const content = await plugin.loadContent!(); const content = await plugin.loadContent!();
expect(content.loadedVersions.length).toEqual(4); expect(content.loadedVersions.length).toEqual(4);
const [ const [currentVersion, version101, version100, versionWithSlugs] =
currentVersion, content.loadedVersions;
version101,
version100,
versionWithSlugs,
] = content.loadedVersions;
// foo/baz.md only exists in version -1.0.0 // foo/baz.md only exists in version -1.0.0
expect(findDocById(currentVersion, 'foo/baz')).toBeUndefined(); expect(findDocById(currentVersion, 'foo/baz')).toBeUndefined();
@ -751,13 +747,8 @@ describe('versioned website (community)', () => {
} }
test('extendCli - docsVersion', async () => { test('extendCli - docsVersion', async () => {
const { const {siteDir, routeBasePath, sidebarPath, pluginId, plugin} =
siteDir, await loadSite();
routeBasePath,
sidebarPath,
pluginId,
plugin,
} = await loadSite();
const mock = jest const mock = jest
.spyOn(cliDocs, 'cliDocsVersionCommand') .spyOn(cliDocs, 'cliDocsVersionCommand')
.mockImplementation(); .mockImplementation();
@ -1784,12 +1775,11 @@ describe('site with custom sidebar items generator', () => {
}); });
test('sidebar is autogenerated according to a custom sidebarItemsGenerator', async () => { test('sidebar is autogenerated according to a custom sidebarItemsGenerator', async () => {
const customSidebarItemsGenerator: SidebarItemsGeneratorOption = async () => { const customSidebarItemsGenerator: SidebarItemsGeneratorOption =
return [ async () => [
{type: 'doc', id: 'API/api-overview'}, {type: 'doc', id: 'API/api-overview'},
{type: 'doc', id: 'API/api-end'}, {type: 'doc', id: 'API/api-end'},
]; ];
};
const {content} = await loadSite(customSidebarItemsGenerator); const {content} = await loadSite(customSidebarItemsGenerator);
const version = content.loadedVersions[0]; const version = content.loadedVersions[0];

View file

@ -646,11 +646,8 @@ describe('createSidebarsUtils', () => {
const sidebars: Sidebars = {sidebar1, sidebar2}; const sidebars: Sidebars = {sidebar1, sidebar2};
const { const {getFirstDocIdOfFirstSidebar, getSidebarNameByDocId, getDocNavigation} =
getFirstDocIdOfFirstSidebar, createSidebarsUtils(sidebars);
getSidebarNameByDocId,
getDocNavigation,
} = createSidebarsUtils(sidebars);
test('getSidebarNameByDocId', async () => { test('getSidebarNameByDocId', async () => {
expect(getFirstDocIdOfFirstSidebar()).toEqual('doc1'); expect(getFirstDocIdOfFirstSidebar()).toEqual('doc1');

View file

@ -324,14 +324,8 @@ describe('versioned site, pluginId=default', () => {
} }
test('readVersionsMetadata versioned site', async () => { test('readVersionsMetadata versioned site', async () => {
const { const {defaultOptions, defaultContext, vCurrent, v101, v100, vwithSlugs} =
defaultOptions, await loadSite();
defaultContext,
vCurrent,
v101,
v100,
vwithSlugs,
} = await loadSite();
const versionsMetadata = readVersionsMetadata({ const versionsMetadata = readVersionsMetadata({
options: defaultOptions, options: defaultOptions,
@ -342,13 +336,8 @@ describe('versioned site, pluginId=default', () => {
}); });
test('readVersionsMetadata versioned site with includeCurrentVersion=false', async () => { test('readVersionsMetadata versioned site with includeCurrentVersion=false', async () => {
const { const {defaultOptions, defaultContext, v101, v100, vwithSlugs} =
defaultOptions, await loadSite();
defaultContext,
v101,
v100,
vwithSlugs,
} = await loadSite();
const versionsMetadata = readVersionsMetadata({ const versionsMetadata = readVersionsMetadata({
options: {...defaultOptions, includeCurrentVersion: false}, options: {...defaultOptions, includeCurrentVersion: false},
@ -364,14 +353,8 @@ describe('versioned site, pluginId=default', () => {
}); });
test('readVersionsMetadata versioned site with version options', async () => { test('readVersionsMetadata versioned site with version options', async () => {
const { const {defaultOptions, defaultContext, vCurrent, v101, v100, vwithSlugs} =
defaultOptions, await loadSite();
defaultContext,
vCurrent,
v101,
v100,
vwithSlugs,
} = await loadSite();
const versionsMetadata = readVersionsMetadata({ const versionsMetadata = readVersionsMetadata({
options: { options: {
@ -424,14 +407,8 @@ describe('versioned site, pluginId=default', () => {
}); });
test('readVersionsMetadata versioned site with editUrl', async () => { test('readVersionsMetadata versioned site with editUrl', async () => {
const { const {defaultOptions, defaultContext, vCurrent, v101, v100, vwithSlugs} =
defaultOptions, await loadSite();
defaultContext,
vCurrent,
v101,
v100,
vwithSlugs,
} = await loadSite();
const versionsMetadata = readVersionsMetadata({ const versionsMetadata = readVersionsMetadata({
options: { options: {
@ -474,14 +451,8 @@ describe('versioned site, pluginId=default', () => {
}); });
test('readVersionsMetadata versioned site with editUrl and editCurrentVersion=true', async () => { test('readVersionsMetadata versioned site with editUrl and editCurrentVersion=true', async () => {
const { const {defaultOptions, defaultContext, vCurrent, v101, v100, vwithSlugs} =
defaultOptions, await loadSite();
defaultContext,
vCurrent,
v101,
v100,
vwithSlugs,
} = await loadSite();
const versionsMetadata = readVersionsMetadata({ const versionsMetadata = readVersionsMetadata({
options: { options: {

View file

@ -201,11 +201,8 @@ export default function pluginContentDocs(
// Add sidebar/next/previous to the docs // Add sidebar/next/previous to the docs
function addNavData(doc: DocMetadataBase): DocMetadata { function addNavData(doc: DocMetadataBase): DocMetadata {
const { const {sidebarName, previousId, nextId} =
sidebarName, sidebarsUtils.getDocNavigation(doc.id);
previousId,
nextId,
} = sidebarsUtils.getDocNavigation(doc.id);
const toDocNavLink = (navDocId: string): DocNavLink => { const toDocNavLink = (navDocId: string): DocNavLink => {
const {title, permalink, frontMatter} = docsBaseById[navDocId]; const {title, permalink, frontMatter} = docsBaseById[navDocId];
return { return {
@ -239,7 +236,8 @@ export default function pluginContentDocs(
(doc) => (doc) =>
doc.unversionedId === options.homePageId || doc.slug === '/', doc.unversionedId === options.homePageId || doc.slug === '/',
); );
const firstDocIdOfFirstSidebar = sidebarsUtils.getFirstDocIdOfFirstSidebar(); const firstDocIdOfFirstSidebar =
sidebarsUtils.getFirstDocIdOfFirstSidebar();
if (versionHomeDoc) { if (versionHomeDoc) {
return versionHomeDoc; return versionHomeDoc;
} else if (firstDocIdOfFirstSidebar) { } else if (firstDocIdOfFirstSidebar) {

View file

@ -10,7 +10,8 @@ import {NumberPrefixParser} from './types';
// Best-effort to avoid parsing some patterns as number prefix // Best-effort to avoid parsing some patterns as number prefix
const IgnoredPrefixPatterns = (function () { const IgnoredPrefixPatterns = (function () {
// ignore common date-like patterns: https://github.com/facebook/docusaurus/issues/4640 // ignore common date-like patterns: https://github.com/facebook/docusaurus/issues/4640
const DateLikePrefixRegex = /^((\d{2}|\d{4})[-_.]\d{2}([-_.](\d{2}|\d{4}))?)(.*)$/; const DateLikePrefixRegex =
/^((\d{2}|\d{4})[-_.]\d{2}([-_.](\d{2}|\d{4}))?)(.*)$/;
// ignore common versioning patterns: https://github.com/facebook/docusaurus/issues/4653 // ignore common versioning patterns: https://github.com/facebook/docusaurus/issues/4653
// note: we could try to parse float numbers in filenames but that is probably not worth it // note: we could try to parse float numbers in filenames but that is probably not worth it
@ -23,7 +24,8 @@ const IgnoredPrefixPatterns = (function () {
); );
})(); })();
const NumberPrefixRegex = /^(?<numberPrefix>\d+)(?<separator>\s*[-_.]+\s*)(?<suffix>.*)$/; const NumberPrefixRegex =
/^(?<numberPrefix>\d+)(?<separator>\s*[-_.]+\s*)(?<suffix>.*)$/;
// 0-myDoc => {filename: myDoc, numberPrefix: 0} // 0-myDoc => {filename: myDoc, numberPrefix: 0}
// 003 - myDoc => {filename: myDoc, numberPrefix: 3} // 003 - myDoc => {filename: myDoc, numberPrefix: 3}

View file

@ -194,8 +194,10 @@ declare module '@theme/hooks/useDocs' {
type GlobalVersion = import('./types').GlobalVersion; type GlobalVersion = import('./types').GlobalVersion;
type ActivePlugin = import('./client/docsClientUtils').ActivePlugin; type ActivePlugin = import('./client/docsClientUtils').ActivePlugin;
type ActiveDocContext = import('./client/docsClientUtils').ActiveDocContext; type ActiveDocContext = import('./client/docsClientUtils').ActiveDocContext;
type DocVersionSuggestions = import('./client/docsClientUtils').DocVersionSuggestions; type DocVersionSuggestions =
type GetActivePluginOptions = import('./client/docsClientUtils').GetActivePluginOptions; import('./client/docsClientUtils').DocVersionSuggestions;
type GetActivePluginOptions =
import('./client/docsClientUtils').GetActivePluginOptions;
export type {GlobalPluginData, GlobalVersion}; export type {GlobalPluginData, GlobalVersion};
export const useAllDocsData: () => Record<string, GlobalPluginData>; export const useAllDocsData: () => Record<string, GlobalPluginData>;

View file

@ -93,9 +93,10 @@ async function readCategoryMetadatasFile(
} }
// [...parents, tail] // [...parents, tail]
function parseBreadcrumb( function parseBreadcrumb(breadcrumb: string[]): {
breadcrumb: string[], parents: string[];
): {parents: string[]; tail: string} { tail: string;
} {
return { return {
parents: take(breadcrumb, breadcrumb.length - 1), parents: take(breadcrumb, breadcrumb.length - 1),
tail: last(breadcrumb)!, tail: last(breadcrumb)!,
@ -103,13 +104,13 @@ function parseBreadcrumb(
} }
// Comment for this feature: https://github.com/facebook/docusaurus/issues/3464#issuecomment-818670449 // Comment for this feature: https://github.com/facebook/docusaurus/issues/3464#issuecomment-818670449
export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async function defaultSidebarItemsGenerator({ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async ({
item, item,
docs: allDocs, docs: allDocs,
version, version,
numberPrefixParser, numberPrefixParser,
options, options,
}) { }) => {
// Doc at the root of the autogenerated sidebar dir // Doc at the root of the autogenerated sidebar dir
function isRootDoc(doc: SidebarItemsGeneratorDoc) { function isRootDoc(doc: SidebarItemsGeneratorDoc) {
return doc.sourceDirName === item.dirName; return doc.sourceDirName === item.dirName;
@ -245,9 +246,8 @@ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async functio
} else { } else {
sidebarItems.push(newCategory); sidebarItems.push(newCategory);
} }
categoriesByBreadcrumb[ categoriesByBreadcrumb[breadcrumb.join(BreadcrumbSeparator)] =
breadcrumb.join(BreadcrumbSeparator) newCategory;
] = newCategory;
return newCategory; return newCategory;
} }
} }

View file

@ -457,7 +457,7 @@ export async function processSidebars({
function collectSidebarItemsOfType< function collectSidebarItemsOfType<
Type extends SidebarItemType, Type extends SidebarItemType,
Item extends SidebarItem & {type: SidebarItemType} Item extends SidebarItem & {type: SidebarItemType},
>(type: Type, sidebar: Sidebar): Item[] { >(type: Type, sidebar: Sidebar): Item[] {
function collectRecursive(item: SidebarItem): Item[] { function collectRecursive(item: SidebarItem): Item[] {
const currentItemsCollected: Item[] = const currentItemsCollected: Item[] =
@ -508,14 +508,10 @@ export function collectSidebarsDocIds(
}); });
} }
export function createSidebarsUtils( export function createSidebarsUtils(sidebars: Sidebars): {
sidebars: Sidebars,
): {
getFirstDocIdOfFirstSidebar: () => string | undefined; getFirstDocIdOfFirstSidebar: () => string | undefined;
getSidebarNameByDocId: (docId: string) => string | undefined; getSidebarNameByDocId: (docId: string) => string | undefined;
getDocNavigation: ( getDocNavigation: (docId: string) => {
docId: string,
) => {
sidebarName: string | undefined; sidebarName: string | undefined;
previousId: string | undefined; previousId: string | undefined;
nextId: string | undefined; nextId: string | undefined;
@ -530,16 +526,14 @@ export function createSidebarsUtils(
function getSidebarNameByDocId(docId: string): string | undefined { function getSidebarNameByDocId(docId: string): string | undefined {
// TODO lookup speed can be optimized // TODO lookup speed can be optimized
const entry = Object.entries( const entry = Object.entries(sidebarNameToDocIds).find(
sidebarNameToDocIds, ([_sidebarName, docIds]) => docIds.includes(docId),
).find(([_sidebarName, docIds]) => docIds.includes(docId)); );
return entry?.[0]; return entry?.[0];
} }
function getDocNavigation( function getDocNavigation(docId: string): {
docId: string,
): {
sidebarName: string | undefined; sidebarName: string | undefined;
previousId: string | undefined; previousId: string | undefined;
nextId: string | undefined; nextId: string | undefined;

View file

@ -131,16 +131,13 @@ function translateSidebar({
sidebarName: string; sidebarName: string;
sidebarsTranslations: TranslationFileContent; sidebarsTranslations: TranslationFileContent;
}): Sidebar { }): Sidebar {
return transformSidebarItems( return transformSidebarItems(sidebar, (item: SidebarItem): SidebarItem => {
sidebar,
(item: SidebarItem): SidebarItem => {
if (item.type === 'category') { if (item.type === 'category') {
return { return {
...item, ...item,
label: label:
sidebarsTranslations[ sidebarsTranslations[`sidebar.${sidebarName}.category.${item.label}`]
`sidebar.${sidebarName}.category.${item.label}` ?.message ?? item.label,
]?.message ?? item.label,
}; };
} }
if (item.type === 'link') { if (item.type === 'link') {
@ -152,8 +149,7 @@ function translateSidebar({
}; };
} }
return item; return item;
}, });
);
} }
function getSidebarsTranslations( function getSidebarsTranslations(
@ -193,9 +189,8 @@ function getVersionTranslationFiles(version: LoadedVersion): TranslationFiles {
}, },
}; };
const sidebarsTranslations: TranslationFileContent = getSidebarsTranslations( const sidebarsTranslations: TranslationFileContent =
version, getSidebarsTranslations(version);
);
// const docsTranslations: TranslationFileContent = getDocsTranslations(version); // const docsTranslations: TranslationFileContent = getDocsTranslations(version);

View file

@ -306,6 +306,7 @@ export type DocsMarkdownOption = {
onBrokenMarkdownLink: (brokenMarkdownLink: BrokenMarkdownLink) => void; onBrokenMarkdownLink: (brokenMarkdownLink: BrokenMarkdownLink) => void;
}; };
export type NumberPrefixParser = ( export type NumberPrefixParser = (filename: string) => {
filename: string, filename: string;
) => {filename: string; numberPrefix?: number}; numberPrefix?: number;
};

View file

@ -355,15 +355,8 @@ function createVersionMetadata({
| 'editCurrentVersion' | 'editCurrentVersion'
>; >;
}): VersionMetadata { }): VersionMetadata {
const { const {sidebarFilePath, contentPath, contentPathLocalized} =
sidebarFilePath, getVersionMetadataPaths({versionName, context, options});
contentPath,
contentPathLocalized,
} = getVersionMetadataPaths({
versionName,
context,
options,
});
const isLast = versionName === lastVersionName; const isLast = versionName === lastVersionName;

View file

@ -5,8 +5,8 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
const LogPlugin = require('@docusaurus/core/lib/webpack/plugins/LogPlugin') const LogPlugin =
.default; require('@docusaurus/core/lib/webpack/plugins/LogPlugin').default;
const {compile} = require('@docusaurus/core/lib/webpack/utils'); const {compile} = require('@docusaurus/core/lib/webpack/utils');
const {normalizeUrl} = require('@docusaurus/utils'); const {normalizeUrl} = require('@docusaurus/utils');
const path = require('path'); const path = require('path');
@ -79,7 +79,8 @@ function plugin(context, options) {
`${config.output.publicPath || '/'}`, `${config.output.publicPath || '/'}`,
'sw.js', 'sw.js',
), ),
PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES: offlineModeActivationStrategies, PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES:
offlineModeActivationStrategies,
PWA_RELOAD_POPUP: reloadPopup, PWA_RELOAD_POPUP: reloadPopup,
}), }),
], ],

View file

@ -26,8 +26,7 @@ export const PluginOptionSchema = Joi.object({
.default(DEFAULT_OPTIONS.changefreq), .default(DEFAULT_OPTIONS.changefreq),
priority: Joi.number().min(0).max(1).default(DEFAULT_OPTIONS.priority), priority: Joi.number().min(0).max(1).default(DEFAULT_OPTIONS.priority),
trailingSlash: Joi.bool().default(false).warning('deprecate.error', { trailingSlash: Joi.bool().default(false).warning('deprecate.error', {
msg: msg: 'Please use the new Docusaurus global trailingSlash config instead, and the sitemaps plugin will use it.',
'Please use the new Docusaurus global trailingSlash config instead, and the sitemaps plugin will use it.',
}), }),
}).messages({ }).messages({
'deprecate.error': 'deprecate.error':

View file

@ -29,11 +29,7 @@ export default function preset(
): Preset { ): Preset {
const {siteConfig} = context; const {siteConfig} = context;
const {themeConfig} = siteConfig; const {themeConfig} = siteConfig;
const { const {algolia, googleAnalytics, gtag} = themeConfig as Partial<ThemeConfig>;
algolia,
googleAnalytics,
gtag,
} = (themeConfig as unknown) as ThemeConfig;
const isProd = process.env.NODE_ENV === 'production'; const isProd = process.env.NODE_ENV === 'production';
const themes: PluginConfig[] = []; const themes: PluginConfig[] = [];

View file

@ -21,15 +21,8 @@ function Layout(props: Props): JSX.Element {
const {siteConfig} = useDocusaurusContext(); const {siteConfig} = useDocusaurusContext();
const {favicon, url: siteUrl} = siteConfig; const {favicon, url: siteUrl} = siteConfig;
const {image: defaultImage, metadatas} = useThemeConfig(); const {image: defaultImage, metadatas} = useThemeConfig();
const { const {children, title, noFooter, description, image, keywords, permalink} =
children, props;
title,
noFooter,
description,
image,
keywords,
permalink,
} = props;
const metaTitle = useTitleFormatter(title); const metaTitle = useTitleFormatter(title);
const metaImage = image || defaultImage; const metaImage = image || defaultImage;
let metaImageUrl = siteUrl + useBaseUrl(metaImage); let metaImageUrl = siteUrl + useBaseUrl(metaImage);

View file

@ -20,15 +20,8 @@ import type {Props} from '@theme/Layout';
function Layout(props: Props): JSX.Element { function Layout(props: Props): JSX.Element {
const {siteConfig} = useDocusaurusContext(); const {siteConfig} = useDocusaurusContext();
const {favicon, title: siteTitle, url: siteUrl} = siteConfig; const {favicon, title: siteTitle, url: siteUrl} = siteConfig;
const { const {children, title, noFooter, description, image, keywords, permalink} =
children, props;
title,
noFooter,
description,
image,
keywords,
permalink,
} = props;
const {image: defaultImage, metadatas} = useThemeConfig(); const {image: defaultImage, metadatas} = useThemeConfig();
const metaTitle = title ? `${title} | ${siteTitle}` : siteTitle; const metaTitle = title ? `${title} | ${siteTitle}` : siteTitle;

View file

@ -161,8 +161,7 @@ describe('themeConfig', () => {
dropdownActiveClassDisabled: true, dropdownActiveClassDisabled: true,
dropdownItemsBefore: [ dropdownItemsBefore: [
{ {
href: href: 'https://www.npmjs.com/package/docusaurus?activeTab=versions',
'https://www.npmjs.com/package/docusaurus?activeTab=versions',
label: 'Versions on npm', label: 'Versions on npm',
className: 'npm-styled', className: 'npm-styled',
target: '_self', target: '_self',

View file

@ -191,7 +191,7 @@ export default function docusaurusThemeClassic(
if (file === resolvedInfimaFile) { if (file === resolvedInfimaFile) {
return {}; return {};
} }
return rtlcss((result.root as unknown) as rtlcss.ConfigOptions); return rtlcss(result.root as unknown as rtlcss.ConfigOptions);
}, },
}; };
postCssOptions.plugins.push(plugin); postCssOptions.plugins.push(plugin);

View file

@ -22,15 +22,8 @@ function BlogPostPage(props: Props): JSX.Element {
assets, assets,
metadata, metadata,
} = BlogPostContents; } = BlogPostContents;
const { const {title, description, nextItem, prevItem, date, tags, authors} =
title, metadata;
description,
nextItem,
prevItem,
date,
tags,
authors,
} = metadata;
const { const {
hide_table_of_contents: hideTableOfContents, hide_table_of_contents: hideTableOfContents,
keywords, keywords,

View file

@ -62,13 +62,8 @@ function EditMetaRow({
export default function DocItemFooter(props: Props): JSX.Element { export default function DocItemFooter(props: Props): JSX.Element {
const {content: DocContent} = props; const {content: DocContent} = props;
const {metadata} = DocContent; const {metadata} = DocContent;
const { const {editUrl, lastUpdatedAt, formattedLastUpdatedAt, lastUpdatedBy, tags} =
editUrl, metadata;
lastUpdatedAt,
formattedLastUpdatedAt,
lastUpdatedBy,
tags,
} = metadata;
const canDisplayTagsRow = tags.length > 0; const canDisplayTagsRow = tags.length > 0;
const canDisplayEditMetaRow = !!(editUrl || lastUpdatedAt || lastUpdatedBy); const canDisplayEditMetaRow = !!(editUrl || lastUpdatedAt || lastUpdatedBy);

View file

@ -125,10 +125,8 @@ function DocVersionBannerEnabled({versionMetadata}: Props): JSX.Element {
const {savePreferredVersionName} = useDocsPreferredVersion(pluginId); const {savePreferredVersionName} = useDocsPreferredVersion(pluginId);
const { const {latestDocSuggestion, latestVersionSuggestion} =
latestDocSuggestion, useDocVersionSuggestions(pluginId);
latestVersionSuggestion,
} = useDocVersionSuggestions(pluginId);
// try to link to same doc in latest version (not always possible) // try to link to same doc in latest version (not always possible)
// fallback to main doc of latest version // fallback to main doc of latest version

View file

@ -33,9 +33,8 @@ export default function DocsVersionDropdownNavbarItem({
const versions = useVersions(docsPluginId); const versions = useVersions(docsPluginId);
const latestVersion = useLatestVersion(docsPluginId); const latestVersion = useLatestVersion(docsPluginId);
const {preferredVersion, savePreferredVersionName} = useDocsPreferredVersion( const {preferredVersion, savePreferredVersionName} =
docsPluginId, useDocsPreferredVersion(docsPluginId);
);
function getItems() { function getItems() {
const versionLinks = versions.map((version) => { const versionLinks = versions.map((version) => {

View file

@ -30,8 +30,7 @@ export default function LocaleDropdownNavbarItem({
return localeConfigs[locale].label; return localeConfigs[locale].label;
} }
const localeItems = locales.map( const localeItems = locales.map((locale): LinkLikeNavbarItemProps => {
(locale): LinkLikeNavbarItemProps => {
const to = `pathname://${alternatePageUtils.createUrl({ const to = `pathname://${alternatePageUtils.createUrl({
locale, locale,
fullyQualified: false, fullyQualified: false,
@ -45,8 +44,7 @@ export default function LocaleDropdownNavbarItem({
className: locale === currentLocale ? 'dropdown__link--active' : '', className: locale === currentLocale ? 'dropdown__link--active' : '',
style: {textTransform: 'capitalize'}, style: {textTransform: 'capitalize'},
}; };
}, });
);
const items = [...dropdownItemsBefore, ...localeItems, ...dropdownItemsAfter]; const items = [...dropdownItemsBefore, ...localeItems, ...dropdownItemsAfter];

View file

@ -57,9 +57,9 @@ async function extractThemeCodeMessages() {
// eslint-disable-next-line global-require // eslint-disable-next-line global-require
} = require('@docusaurus/core/lib/server/translations/translationsExtractor'); } = require('@docusaurus/core/lib/server/translations/translationsExtractor');
const filePaths = ( const filePaths = (await globSourceCodeFilePaths(CodeDirPaths)).filter(
await globSourceCodeFilePaths(CodeDirPaths) (filePath) => ['.js', '.jsx'].includes(path.extname(filePath)),
).filter((filePath) => ['.js', '.jsx'].includes(path.extname(filePath))); );
const filesExtractedTranslations = await extractAllSourceCodeFileTranslations( const filesExtractedTranslations = await extractAllSourceCodeFileTranslations(
filePaths, filePaths,

View file

@ -89,7 +89,7 @@ function useShallowMemoizedObject<O extends Record<string, unknown>>(obj: O) {
// Fill the secondary menu placeholder with some real content // Fill the secondary menu placeholder with some real content
export function MobileSecondaryMenuFiller< export function MobileSecondaryMenuFiller<
Props extends Record<string, unknown> Props extends Record<string, unknown>,
>({ >({
component, component,
props, props,

View file

@ -247,11 +247,7 @@ export interface Plugin<Content = unknown> {
getPathsToWatch?(): string[]; getPathsToWatch?(): string[];
getClientModules?(): string[]; getClientModules?(): string[];
extendCli?(cli: Command): void; extendCli?(cli: Command): void;
injectHtmlTags?({ injectHtmlTags?({content}: {content: Content}): {
content,
}: {
content: Content;
}): {
headTags?: HtmlTags; headTags?: HtmlTags;
preBodyTags?: HtmlTags; preBodyTags?: HtmlTags;
postBodyTags?: HtmlTags; postBodyTags?: HtmlTags;

View file

@ -17,8 +17,10 @@ describe('pathUtils', () => {
'endi-lie-fd3': false, 'endi-lie-fd3': false,
'yangshun-tay-48d': false, 'yangshun-tay-48d': false,
'yangshun-tay-f3b': false, 'yangshun-tay-f3b': false,
'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-d46': true, 'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-d46':
'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-test-1-test-2-787': true, true,
'foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-foo-bar-test-1-test-2-787':
true,
}; };
Object.keys(asserts).forEach((path) => { Object.keys(asserts).forEach((path) => {
expect(isNameTooLong(path)).toBe(asserts[path]); expect(isNameTooLong(path)).toBe(asserts[path]);

View file

@ -427,9 +427,7 @@ export function updateTranslationFileMessages(
// Input: ## Some heading {#some-heading} // Input: ## Some heading {#some-heading}
// Output: {text: "## Some heading", id: "some-heading"} // Output: {text: "## Some heading", id: "some-heading"}
export function parseMarkdownHeadingId( export function parseMarkdownHeadingId(heading: string): {
heading: string,
): {
text: string; text: string;
id?: string; id?: string;
} { } {

View file

@ -76,9 +76,7 @@ export function createExcerpt(fileString: string): string | undefined {
return undefined; return undefined;
} }
export function parseFrontMatter( export function parseFrontMatter(markdownFileContent: string): {
markdownFileContent: string,
): {
frontMatter: Record<string, unknown>; frontMatter: Record<string, unknown>;
content: string; content: string;
} { } {
@ -107,9 +105,10 @@ export function parseMarkdownContentTitle(
const content = contentUntrimmed.trim(); const content = contentUntrimmed.trim();
const IMPORT_STATEMENT = /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/ const IMPORT_STATEMENT =
.source; /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/.source;
const REGULAR_TITLE = /(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>({#*[\w-]+})|#)?\n*?)/ const REGULAR_TITLE =
/(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>({#*[\w-]+})|#)?\n*?)/
.source; .source;
const ALTERNATE_TITLE = /(?<pattern>\s*(?<title>[^\n]*)\s*\n[=]+)/.source; const ALTERNATE_TITLE = /(?<pattern>\s*(?<title>[^\n]*)\s*\n[=]+)/.source;
@ -150,9 +149,8 @@ export function parseMarkdownString(
options?: {removeContentTitle?: boolean}, options?: {removeContentTitle?: boolean},
): ParsedMarkdown { ): ParsedMarkdown {
try { try {
const {frontMatter, content: contentWithoutFrontMatter} = parseFrontMatter( const {frontMatter, content: contentWithoutFrontMatter} =
markdownFileContent, parseFrontMatter(markdownFileContent);
);
const {content, contentTitle} = parseMarkdownContentTitle( const {content, contentTitle} = parseMarkdownContentTitle(
contentWithoutFrontMatter, contentWithoutFrontMatter,

View file

@ -1,7 +1,4 @@
#!/usr/bin/env node #!/usr/bin/env node
// TODO remove when fixed: https://github.com/Stuk/eslint-plugin-header/issues/39
/* eslint-disable header/header */
/** /**
* Copyright (c) Facebook, Inc. and its affiliates. * Copyright (c) Facebook, Inc. and its affiliates.
* *

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
import React, {useEffect, useRef} from 'react'; import React, {useEffect, useRef, ComponentType} from 'react';
import {NavLink, Link as RRLink} from 'react-router-dom'; import {NavLink, Link as RRLink} from 'react-router-dom';
import useDocusaurusContext from './useDocusaurusContext'; import useDocusaurusContext from './useDocusaurusContext';
@ -84,7 +84,9 @@ function Link({
} }
const preloaded = useRef(false); const preloaded = useRef(false);
const LinkComponent = isNavLink ? NavLink : RRLink; const LinkComponent = (
isNavLink ? NavLink : RRLink
) as ComponentType<LinkProps>;
const IOSupported = ExecutionEnvironment.canUseIntersectionObserver; const IOSupported = ExecutionEnvironment.canUseIntersectionObserver;

View file

@ -42,9 +42,8 @@ function addBaseUrl(
} }
export function useBaseUrlUtils(): BaseUrlUtils { export function useBaseUrlUtils(): BaseUrlUtils {
const { const {siteConfig: {baseUrl = '/', url: siteUrl} = {}} =
siteConfig: {baseUrl = '/', url: siteUrl} = {}, useDocusaurusContext();
} = useDocusaurusContext();
return { return {
withBaseUrl: (url, options) => { withBaseUrl: (url, options) => {
return addBaseUrl(siteUrl, baseUrl, url, options); return addBaseUrl(siteUrl, baseUrl, url, options);

View file

@ -49,7 +49,8 @@ export default async function render(locals) {
), ),
); );
const isNotDefinedErrorRegex = /(window|document|localStorage|navigator|alert|location|buffer|self) is not defined/i; const isNotDefinedErrorRegex =
/(window|document|localStorage|navigator|alert|location|buffer|self) is not defined/i;
if (isNotDefinedErrorRegex.test(e.message)) { if (isNotDefinedErrorRegex.test(e.message)) {
console.error( console.error(

View file

@ -190,13 +190,13 @@ describe('normalizeConfig', () => {
test('should throw error for required fields', () => { test('should throw error for required fields', () => {
expect( expect(
() => () =>
validateConfig(({ validateConfig({
invalidField: true, invalidField: true,
presets: {}, presets: {},
stylesheets: {}, stylesheets: {},
themes: {}, themes: {},
scripts: {}, scripts: {},
} as unknown) as DocusaurusConfig), // to fields not in the type } as unknown as DocusaurusConfig), // to fields not in the type
).toThrowErrorMatchingSnapshot(); ).toThrowErrorMatchingSnapshot();
}); });
}); });

View file

@ -14,8 +14,7 @@ describe('htmlTagObjectToString', () => {
tagName: 'script', tagName: 'script',
attributes: { attributes: {
type: 'text/javascript', type: 'text/javascript',
src: src: 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
async: true, async: true,
'data-options': '{"prop":true}', 'data-options': '{"prop":true}',
}, },

View file

@ -256,15 +256,8 @@ export async function load(
} = context; } = context;
// Plugins. // Plugins.
const pluginConfigs: PluginConfig[] = loadPluginConfigs(context); const pluginConfigs: PluginConfig[] = loadPluginConfigs(context);
const { const {plugins, pluginsRouteConfigs, globalData, themeConfigTranslated} =
plugins, await loadPlugins({pluginConfigs, context});
pluginsRouteConfigs,
globalData,
themeConfigTranslated,
} = await loadPlugins({
pluginConfigs,
context,
});
// Side-effect to replace the untranslated themeConfig by the translated one // Side-effect to replace the untranslated themeConfig by the translated one
context.siteConfig.themeConfig = themeConfigTranslated; context.siteConfig.themeConfig = themeConfigTranslated;
@ -299,12 +292,8 @@ export async function load(
const {headTags, preBodyTags, postBodyTags} = loadHtmlTags(plugins); const {headTags, preBodyTags, postBodyTags} = loadHtmlTags(plugins);
// Routing. // Routing.
const { const {registry, routesChunkNames, routesConfig, routesPaths} =
registry, await loadRoutes(pluginsRouteConfigs, baseUrl);
routesChunkNames,
routesConfig,
routesPaths,
} = await loadRoutes(pluginsRouteConfigs, baseUrl);
const genRegistry = generate( const genRegistry = generate(
generatedFilesDir, generatedFilesDir,

View file

@ -87,7 +87,8 @@ export async function loadPlugins({
type ContentLoadedTranslatedPlugin = LoadedPlugin & { type ContentLoadedTranslatedPlugin = LoadedPlugin & {
translationFiles: TranslationFiles; translationFiles: TranslationFiles;
}; };
const contentLoadedTranslatedPlugins: ContentLoadedTranslatedPlugin[] = await Promise.all( const contentLoadedTranslatedPlugins: ContentLoadedTranslatedPlugin[] =
await Promise.all(
loadedPlugins.map(async (contentLoadedPlugin) => { loadedPlugins.map(async (contentLoadedPlugin) => {
const translationFiles = const translationFiles =
(await contentLoadedPlugin?.getTranslationFiles?.({ (await contentLoadedPlugin?.getTranslationFiles?.({

View file

@ -193,9 +193,8 @@ export default function initPlugins({
pluginConfig, pluginConfig,
pluginRequire, pluginRequire,
); );
const pluginVersion: DocusaurusPluginVersionInformation = doGetPluginVersion( const pluginVersion: DocusaurusPluginVersionInformation =
normalizedPluginConfig, doGetPluginVersion(normalizedPluginConfig);
);
const pluginOptions = doValidatePluginOptions(normalizedPluginConfig); const pluginOptions = doValidatePluginOptions(normalizedPluginConfig);
// Side-effect: merge the normalized theme config in the original one // Side-effect: merge the normalized theme config in the original one

View file

@ -14,9 +14,7 @@ import {
PresetConfig, PresetConfig,
} from '@docusaurus/types'; } from '@docusaurus/types';
export default function loadPresets( export default function loadPresets(context: LoadContext): {
context: LoadContext,
): {
plugins: PluginConfig[]; plugins: PluginConfig[];
themes: PluginConfig[]; themes: PluginConfig[];
} { } {

View file

@ -98,7 +98,8 @@ export async function extractSiteSourceCodeTranslations(
...extraSourceCodeFilePaths, ...extraSourceCodeFilePaths,
]; ];
const sourceCodeFilesTranslations = await extractAllSourceCodeFileTranslations( const sourceCodeFilesTranslations =
await extractAllSourceCodeFileTranslations(
allSourceCodeFilePaths, allSourceCodeFilePaths,
babelOptions, babelOptions,
); );
@ -215,7 +216,8 @@ function extractSourceCodeAstTranslations(
if (attributePath) { if (attributePath) {
const attributeValue = attributePath.get('value') as NodePath; const attributeValue = attributePath.get('value') as NodePath;
const attributeValueEvaluated = attributeValue.isJSXExpressionContainer() const attributeValueEvaluated =
attributeValue.isJSXExpressionContainer()
? (attributeValue.get('expression') as NodePath).evaluate() ? (attributeValue.get('expression') as NodePath).evaluate()
: attributeValue.evaluate(); : attributeValue.evaluate();
@ -265,9 +267,9 @@ function extractSourceCodeAstTranslations(
singleChildren.isJSXExpressionContainer() && singleChildren.isJSXExpressionContainer() &&
(singleChildren.get('expression') as NodePath).evaluate().confident (singleChildren.get('expression') as NodePath).evaluate().confident
) { ) {
const message = (singleChildren.get( const message = (
'expression', singleChildren.get('expression') as NodePath
) as NodePath).evaluate().value; ).evaluate().value;
const id = evaluateJSXProp('id'); const id = evaluateJSXProp('id');
const description = evaluateJSXProp('description'); const description = evaluateJSXProp('description');

View file

@ -236,7 +236,8 @@ class CleanWebpackPlugin {
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) { } catch (error: any) {
const needsForce = /Cannot delete files\/folders outside the current working directory\./.test( const needsForce =
/Cannot delete files\/folders outside the current working directory\./.test(
error.message, error.message,
); );

View file

@ -151,15 +151,15 @@ function getDefaultBabelLoader({
}; };
} }
export const getCustomizableJSLoader = ( export const getCustomizableJSLoader =
jsLoader: 'babel' | ((isServer: boolean) => RuleSetRule) = 'babel', (jsLoader: 'babel' | ((isServer: boolean) => RuleSetRule) = 'babel') =>
) => ({ ({
isServer, isServer,
babelOptions, babelOptions,
}: { }: {
isServer: boolean; isServer: boolean;
babelOptions?: TransformOptions | string; babelOptions?: TransformOptions | string;
}): RuleSetRule => }): RuleSetRule =>
jsLoader === 'babel' jsLoader === 'babel'
? getDefaultBabelLoader({isServer, babelOptions}) ? getDefaultBabelLoader({isServer, babelOptions})
: jsLoader(isServer); : jsLoader(isServer);

View file

@ -19,9 +19,8 @@ module.exports = function (contentBuffer) {
config.palette = 'palette' in config ? config.palette : false; config.palette = 'palette' in config ? config.palette : false;
let content = contentBuffer.toString('utf8'); let content = contentBuffer.toString('utf8');
const contentIsUrlExport = /^(?:export default|module.exports =) "data:(.*)base64,(.*)/.test( const contentIsUrlExport =
content, /^(?:export default|module.exports =) "data:(.*)base64,(.*)/.test(content);
);
const contentIsFileExport = /^(?:export default|module.exports =) (.*)/.test( const contentIsFileExport = /^(?:export default|module.exports =) (.*)/.test(
content, content,
); );

View file

@ -361,8 +361,7 @@ module.exports = {
'https://docusaurus.io/script.js', 'https://docusaurus.io/script.js',
// Object format. // Object format.
{ {
src: src: 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
async: true, async: true,
}, },
], ],

View file

@ -68,9 +68,10 @@ type EditUrlFunction = (params: {
locale: string; locale: string;
}) => string | undefined; }) => string | undefined;
type PrefixParser = ( type PrefixParser = (filename: string) => {
filename: string, filename: string;
) => {filename: string; numberPrefix?: number}; numberPrefix?: number;
};
type SidebarGenerator = (generatorArgs: { type SidebarGenerator = (generatorArgs: {
item: {type: 'autogenerated'; dirName: string}; // the sidebar item with type "autogenerated" item: {type: 'autogenerated'; dirName: string}; // the sidebar item with type "autogenerated"

View file

@ -220,7 +220,6 @@ This option works best to get started, or for casual, irregular authors.
Prefer usage of the `authors` FrontMatter, but the legacy `author_*` FrontMatter remains supported: Prefer usage of the `authors` FrontMatter, but the legacy `author_*` FrontMatter remains supported:
<!-- prettier-ignore-start -->
```yml title="my-blog-post.md" ```yml title="my-blog-post.md"
--- ---
author: Joel Marcey author: Joel Marcey
@ -229,7 +228,6 @@ author_url: https://github.com/JoelMarcey
author_image_url: https://github.com/JoelMarcey.png author_image_url: https://github.com/JoelMarcey.png
--- ---
``` ```
<!-- prettier-ignore-end -->
::: :::
@ -293,7 +291,6 @@ The `authors` system is very flexible and can suit more advanced use-case:
You can use global authors most of the time, and still use inline authors: You can use global authors most of the time, and still use inline authors:
<!-- prettier-ignore-start -->
```yml title="my-blog-post.md" ```yml title="my-blog-post.md"
--- ---
authors: authors:
@ -305,7 +302,6 @@ authors:
image_url: https://github.com/inlineAuthor image_url: https://github.com/inlineAuthor
--- ---
``` ```
<!-- prettier-ignore-end -->
</details> </details>
@ -314,7 +310,6 @@ authors:
You can customize the global author's data on per-blog-post basis: You can customize the global author's data on per-blog-post basis:
<!-- prettier-ignore-start -->
```yml title="my-blog-post.md" ```yml title="my-blog-post.md"
--- ---
authors: authors:
@ -324,7 +319,6 @@ authors:
name: Sébastien Lorber's new name name: Sébastien Lorber's new name
--- ---
``` ```
<!-- prettier-ignore-end -->
</details> </details>

View file

@ -100,7 +100,6 @@ Read more about [importing partial pages](../markdown-features/markdown-features
Optionally, you can add tags to your doc pages, which introduces another dimension of categorization in addition to the [docs sidebar](./sidebar.md). Tags are passed in the front matter as a list of labels: Optionally, you can add tags to your doc pages, which introduces another dimension of categorization in addition to the [docs sidebar](./sidebar.md). Tags are passed in the front matter as a list of labels:
<!-- prettier-ignore-start -->
```yml "your-doc-page.md" ```yml "your-doc-page.md"
--- ---
id: doc-with-tags id: doc-with-tags
@ -110,7 +109,6 @@ tags:
- Getting started - Getting started
--- ---
``` ```
<!-- prettier-ignore-end -->
:::tip :::tip

View file

@ -42,6 +42,7 @@ It is **not possible** to use a TypeScript config file in Docusaurus, unless you
We recommend using [JSDoc type annotations](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html): We recommend using [JSDoc type annotations](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html):
<!-- prettier-ignore-start -->
```js title="docusaurus.config.js" ```js title="docusaurus.config.js"
// highlight-start // highlight-start
/** @type {import('@docusaurus/types').Plugin} */ /** @type {import('@docusaurus/types').Plugin} */
@ -99,6 +100,7 @@ function MyPlugin(context, options) {
}), }),
}); });
``` ```
<!-- prettier-ignore-end -->
:::tip :::tip

View file

@ -50,11 +50,10 @@ function useFilteredUsers(
selectedTags: TagType[], selectedTags: TagType[],
operator: Operator, operator: Operator,
) { ) {
return useMemo(() => filterUsers(users, selectedTags, operator), [ return useMemo(
users, () => filterUsers(users, selectedTags, operator),
selectedTags, [users, selectedTags, operator],
operator, );
]);
} }
const TagQueryStringKey = 'tags'; const TagQueryStringKey = 'tags';

View file

@ -361,8 +361,7 @@ module.exports = {
'https://docusaurus.io/script.js', 'https://docusaurus.io/script.js',
// Object format. // Object format.
{ {
src: src: 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
async: true, async: true,
}, },
], ],

View file

@ -67,9 +67,10 @@ type EditUrlFunction = (params: {
locale: string; locale: string;
}) => string | undefined; }) => string | undefined;
type PrefixParser = ( type PrefixParser = (filename: string) => {
filename: string, filename: string;
) => {filename: string; numberPrefix?: number}; numberPrefix?: number;
};
type SidebarGenerator = (generatorArgs: { type SidebarGenerator = (generatorArgs: {
item: {type: 'autogenerated'; dirName: string}; // the sidebar item with type "autogenerated" item: {type: 'autogenerated'; dirName: string}; // the sidebar item with type "autogenerated"

View file

@ -232,7 +232,6 @@ author_title: Co-creator of Docusaurus 1
author_url: https://github.com/JoelMarcey author_url: https://github.com/JoelMarcey
author_image_url: https://github.com/JoelMarcey.png author_image_url: https://github.com/JoelMarcey.png
--- ---
``` ```
::: :::
@ -312,7 +311,6 @@ authors:
url: https://github.com/inlineAuthor url: https://github.com/inlineAuthor
image_url: https://github.com/inlineAuthor image_url: https://github.com/inlineAuthor
--- ---
``` ```
</details> </details>
@ -330,7 +328,6 @@ authors:
- key: slorber - key: slorber
name: Sébastien Lorber's new name name: Sébastien Lorber's new name
--- ---
``` ```
</details> </details>

View file

@ -361,8 +361,7 @@ module.exports = {
'https://docusaurus.io/script.js', 'https://docusaurus.io/script.js',
// Object format. // Object format.
{ {
src: src: 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
async: true, async: true,
}, },
], ],

View file

@ -67,9 +67,10 @@ type EditUrlFunction = (params: {
locale: string; locale: string;
}) => string | undefined; }) => string | undefined;
type PrefixParser = ( type PrefixParser = (filename: string) => {
filename: string, filename: string;
) => {filename: string; numberPrefix?: number}; numberPrefix?: number;
};
type SidebarGenerator = (generatorArgs: { type SidebarGenerator = (generatorArgs: {
item: {type: 'autogenerated'; dirName: string}; // the sidebar item with type "autogenerated" item: {type: 'autogenerated'; dirName: string}; // the sidebar item with type "autogenerated"

View file

@ -42,6 +42,7 @@ It is **not possible** to use a TypeScript config file in Docusaurus, unless you
We recommend using [JSDoc type annotations](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html): We recommend using [JSDoc type annotations](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html):
<!-- prettier-ignore-start -->
```js title="docusaurus.config.js" ```js title="docusaurus.config.js"
// highlight-start // highlight-start
/** @type {import('@docusaurus/types').Plugin} */ /** @type {import('@docusaurus/types').Plugin} */
@ -99,6 +100,7 @@ function MyPlugin(context, options) {
}), }),
}); });
``` ```
<!-- prettier-ignore-end -->
:::tip :::tip

2403
yarn.lock

File diff suppressed because it is too large Load diff