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-next/
packages/docusaurus-init/templates/*/docusaurus.config.js
__fixtures__
website/i18n
website/versions.json
website/docusaurus.config.js
examples/**/package.json
examples/**/sandbox.config.json
examples/

View file

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

View file

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

View file

@ -1,7 +1,4 @@
#!/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.
*

View file

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

View file

@ -68,8 +68,10 @@ function toAssetRequireNode({
const children = stringifyContent(node);
const title = node.title ? `title="${escapeHtml(node.title)}"` : '';
((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).type = 'jsx';
(
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,

View file

@ -1,7 +1,4 @@
#!/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.
*

View file

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

View file

@ -86,16 +86,21 @@ declare module '@docusaurus/Head' {
}
declare module '@docusaurus/Link' {
type NavLinkProps = Partial<import('react-router-dom').NavLinkProps>;
export type LinkProps = NavLinkProps & {
readonly isNavLink?: boolean;
readonly to?: string;
readonly href?: string;
readonly autoAddBaseUrl?: boolean;
import type {CSSProperties, ComponentProps} from 'react';
// escape hatch in case broken links check is annoying for a specific link
readonly 'data-noBrokenLinkCheck'?: boolean;
};
type NavLinkProps = Partial<import('react-router-dom').NavLinkProps>;
export type LinkProps = NavLinkProps &
ComponentProps<'a'> & {
readonly className?: string;
readonly style?: CSSProperties;
readonly isNavLink?: boolean;
readonly to?: string;
readonly href?: string;
readonly autoAddBaseUrl?: boolean;
// escape hatch in case broken links check is annoying for a specific link
readonly 'data-noBrokenLinkCheck'?: boolean;
};
const Link: (props: LinkProps) => JSX.Element;
export default Link;
}
@ -110,7 +115,7 @@ declare module '@docusaurus/Interpolate' {
export type InterpolateValues<
Str extends string,
Value extends ReactNode
Value extends ReactNode,
> = Record<ExtractInterpolatePlaceholders<Str>, Value>;
// 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) => {
if (routePath === '/') {
return ([[`/fromPath`]] as unknown) as string;
return [[`/fromPath`]] as unknown as string;
}
return undefined;
},

View file

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

View file

@ -51,14 +51,14 @@ describe('validateRedirect', () => {
expect(() =>
validateRedirect({
from: (null as unknown) as string,
from: null as unknown as string,
to: '/toSomePath?queryString=xyz',
}),
).toThrowErrorMatchingSnapshot();
expect(() =>
validateRedirect({
from: (['heyho'] as unknown) as string,
from: ['heyho'] as unknown as string,
to: '/toSomePath?queryString=xyz',
}),
).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 = {
date: Date | undefined;
@ -199,12 +200,8 @@ async function processBlogSourceFile(
const blogSourceAbsolute = path.join(blogDirPath, blogSourceRelative);
const {
frontMatter,
content,
contentTitle,
excerpt,
} = await parseBlogPostMarkdownFile(blogSourceAbsolute);
const {frontMatter, content, contentTitle, excerpt} =
await parseBlogPostMarkdownFile(blogSourceAbsolute);
const aliasedSource = aliasedSitePath(blogSourceAbsolute, siteDir);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -10,7 +10,8 @@ import {NumberPrefixParser} from './types';
// Best-effort to avoid parsing some patterns as number prefix
const IgnoredPrefixPatterns = (function () {
// 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
// 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}
// 003 - myDoc => {filename: myDoc, numberPrefix: 3}

View file

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

View file

@ -93,9 +93,10 @@ async function readCategoryMetadatasFile(
}
// [...parents, tail]
function parseBreadcrumb(
breadcrumb: string[],
): {parents: string[]; tail: string} {
function parseBreadcrumb(breadcrumb: string[]): {
parents: string[];
tail: string;
} {
return {
parents: take(breadcrumb, breadcrumb.length - 1),
tail: last(breadcrumb)!,
@ -103,13 +104,13 @@ function parseBreadcrumb(
}
// 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,
docs: allDocs,
version,
numberPrefixParser,
options,
}) {
}) => {
// Doc at the root of the autogenerated sidebar dir
function isRootDoc(doc: SidebarItemsGeneratorDoc) {
return doc.sourceDirName === item.dirName;
@ -245,9 +246,8 @@ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async functio
} else {
sidebarItems.push(newCategory);
}
categoriesByBreadcrumb[
breadcrumb.join(BreadcrumbSeparator)
] = newCategory;
categoriesByBreadcrumb[breadcrumb.join(BreadcrumbSeparator)] =
newCategory;
return newCategory;
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -57,9 +57,9 @@ async function extractThemeCodeMessages() {
// eslint-disable-next-line global-require
} = require('@docusaurus/core/lib/server/translations/translationsExtractor');
const filePaths = (
await globSourceCodeFilePaths(CodeDirPaths)
).filter((filePath) => ['.js', '.jsx'].includes(path.extname(filePath)));
const filePaths = (await globSourceCodeFilePaths(CodeDirPaths)).filter(
(filePath) => ['.js', '.jsx'].includes(path.extname(filePath)),
);
const filesExtractedTranslations = await extractAllSourceCodeFileTranslations(
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
export function MobileSecondaryMenuFiller<
Props extends Record<string, unknown>
Props extends Record<string, unknown>,
>({
component,
props,

View file

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

View file

@ -17,8 +17,10 @@ describe('pathUtils', () => {
'endi-lie-fd3': false,
'yangshun-tay-48d': 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-test-1-test-2-787': 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':
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) => {
expect(isNameTooLong(path)).toBe(asserts[path]);

View file

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

View file

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

View file

@ -1,7 +1,4 @@
#!/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.
*

View file

@ -5,7 +5,7 @@
* 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 useDocusaurusContext from './useDocusaurusContext';
@ -84,7 +84,9 @@ function Link({
}
const preloaded = useRef(false);
const LinkComponent = isNavLink ? NavLink : RRLink;
const LinkComponent = (
isNavLink ? NavLink : RRLink
) as ComponentType<LinkProps>;
const IOSupported = ExecutionEnvironment.canUseIntersectionObserver;

View file

@ -42,9 +42,8 @@ function addBaseUrl(
}
export function useBaseUrlUtils(): BaseUrlUtils {
const {
siteConfig: {baseUrl = '/', url: siteUrl} = {},
} = useDocusaurusContext();
const {siteConfig: {baseUrl = '/', url: siteUrl} = {}} =
useDocusaurusContext();
return {
withBaseUrl: (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)) {
console.error(

View file

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

View file

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

View file

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

View file

@ -87,28 +87,29 @@ export async function loadPlugins({
type ContentLoadedTranslatedPlugin = LoadedPlugin & {
translationFiles: TranslationFiles;
};
const contentLoadedTranslatedPlugins: ContentLoadedTranslatedPlugin[] = await Promise.all(
loadedPlugins.map(async (contentLoadedPlugin) => {
const translationFiles =
(await contentLoadedPlugin?.getTranslationFiles?.({
content: contentLoadedPlugin.content,
})) ?? [];
const localizedTranslationFiles = await Promise.all(
translationFiles.map((translationFile) =>
localizePluginTranslationFile({
locale: context.i18n.currentLocale,
siteDir: context.siteDir,
translationFile,
plugin: contentLoadedPlugin,
}),
),
);
return {
...contentLoadedPlugin,
translationFiles: localizedTranslationFiles,
};
}),
);
const contentLoadedTranslatedPlugins: ContentLoadedTranslatedPlugin[] =
await Promise.all(
loadedPlugins.map(async (contentLoadedPlugin) => {
const translationFiles =
(await contentLoadedPlugin?.getTranslationFiles?.({
content: contentLoadedPlugin.content,
})) ?? [];
const localizedTranslationFiles = await Promise.all(
translationFiles.map((translationFile) =>
localizePluginTranslationFile({
locale: context.i18n.currentLocale,
siteDir: context.siteDir,
translationFile,
plugin: contentLoadedPlugin,
}),
),
);
return {
...contentLoadedPlugin,
translationFiles: localizedTranslationFiles,
};
}),
);
const allContent: AllContent = chain(loadedPlugins)
.groupBy((item) => item.name)

View file

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

View file

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

View file

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

View file

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

View file

@ -151,18 +151,18 @@ function getDefaultBabelLoader({
};
}
export const getCustomizableJSLoader = (
jsLoader: 'babel' | ((isServer: boolean) => RuleSetRule) = 'babel',
) => ({
isServer,
babelOptions,
}: {
isServer: boolean;
babelOptions?: TransformOptions | string;
}): RuleSetRule =>
jsLoader === 'babel'
? getDefaultBabelLoader({isServer, babelOptions})
: jsLoader(isServer);
export const getCustomizableJSLoader =
(jsLoader: 'babel' | ((isServer: boolean) => RuleSetRule) = 'babel') =>
({
isServer,
babelOptions,
}: {
isServer: boolean;
babelOptions?: TransformOptions | string;
}): RuleSetRule =>
jsLoader === 'babel'
? getDefaultBabelLoader({isServer, babelOptions})
: jsLoader(isServer);
// TODO remove this before end of 2021?
const warnBabelLoaderOnce = memoize(function () {

View file

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

View file

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

View file

@ -68,9 +68,10 @@ type EditUrlFunction = (params: {
locale: string;
}) => string | undefined;
type PrefixParser = (
filename: string,
) => {filename: string; numberPrefix?: number};
type PrefixParser = (filename: string) => {
filename: string;
numberPrefix?: number;
};
type SidebarGenerator = (generatorArgs: {
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:
<!-- prettier-ignore-start -->
```yml title="my-blog-post.md"
---
author: Joel Marcey
@ -229,7 +228,6 @@ author_url: https://github.com/JoelMarcey
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:
<!-- prettier-ignore-start -->
```yml title="my-blog-post.md"
---
authors:
@ -305,7 +302,6 @@ authors:
image_url: https://github.com/inlineAuthor
---
```
<!-- prettier-ignore-end -->
</details>
@ -314,7 +310,6 @@ authors:
You can customize the global author's data on per-blog-post basis:
<!-- prettier-ignore-start -->
```yml title="my-blog-post.md"
---
authors:
@ -324,7 +319,6 @@ authors:
name: Sébastien Lorber's new name
---
```
<!-- prettier-ignore-end -->
</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:
<!-- prettier-ignore-start -->
```yml "your-doc-page.md"
---
id: doc-with-tags
@ -110,7 +109,6 @@ tags:
- Getting started
---
```
<!-- prettier-ignore-end -->
:::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):
<!-- prettier-ignore-start -->
```js title="docusaurus.config.js"
// highlight-start
/** @type {import('@docusaurus/types').Plugin} */
@ -99,6 +100,7 @@ function MyPlugin(context, options) {
}),
});
```
<!-- prettier-ignore-end -->
:::tip

View file

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

View file

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

View file

@ -67,9 +67,10 @@ type EditUrlFunction = (params: {
locale: string;
}) => string | undefined;
type PrefixParser = (
filename: string,
) => {filename: string; numberPrefix?: number};
type PrefixParser = (filename: string) => {
filename: string;
numberPrefix?: number;
};
type SidebarGenerator = (generatorArgs: {
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_image_url: https://github.com/JoelMarcey.png
---
```
:::
@ -312,7 +311,6 @@ authors:
url: https://github.com/inlineAuthor
image_url: https://github.com/inlineAuthor
---
```
</details>
@ -330,7 +328,6 @@ authors:
- key: slorber
name: Sébastien Lorber's new name
---
```
</details>

View file

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

View file

@ -67,9 +67,10 @@ type EditUrlFunction = (params: {
locale: string;
}) => string | undefined;
type PrefixParser = (
filename: string,
) => {filename: string; numberPrefix?: number};
type PrefixParser = (filename: string) => {
filename: string;
numberPrefix?: number;
};
type SidebarGenerator = (generatorArgs: {
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):
<!-- prettier-ignore-start -->
```js title="docusaurus.config.js"
// highlight-start
/** @type {import('@docusaurus/types').Plugin} */
@ -99,6 +100,7 @@ function MyPlugin(context, options) {
}),
});
```
<!-- prettier-ignore-end -->
:::tip

2403
yarn.lock

File diff suppressed because it is too large Load diff