style(v2): reduce number of ESLint warnings (#4993)

* Initial work

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* More fixes

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Update packages/docusaurus-theme-classic/src/theme/ThemedImage/index.tsx

Co-authored-by: Sébastien Lorber <slorber@users.noreply.github.com>

* Update packages/docusaurus-theme-bootstrap/src/theme/ThemedImage/index.tsx

Co-authored-by: Sébastien Lorber <slorber@users.noreply.github.com>

* Fix

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Replace versionPathPart with function

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Prefer non-null assertions

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Substitute for-of with forEach

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Fill `catch` block with placeholder comment

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Ignore local require

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Revert global require change

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Tighten eslint disable range

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Make eslint ignore examples and more tolerating to templates

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Use reduce to handle doc items sequentially

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

* Revert "Use reduce to handle doc items sequentially"

This reverts commit c7525d463b.

* Address change requests

Signed-off-by: Josh-Cena <sidachen2003@gmail.com>

Co-authored-by: Sébastien Lorber <slorber@users.noreply.github.com>
This commit is contained in:
Joshua Chen 2021-06-25 00:12:48 +08:00 committed by GitHub
parent 364051f232
commit 462b1cf2bc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 75 additions and 35 deletions

View file

@ -8,6 +8,7 @@ jest.config.js
jest.transform.js jest.transform.js
website/ website/
scripts scripts
examples/
packages/docusaurus/lib/ packages/docusaurus/lib/
packages/docusaurus-*/lib/* packages/docusaurus-*/lib/*

View file

@ -92,6 +92,7 @@ module.exports = {
'no-unused-vars': OFF, 'no-unused-vars': OFF,
'no-nested-ternary': WARNING, 'no-nested-ternary': WARNING,
'@typescript-eslint/no-empty-function': OFF, '@typescript-eslint/no-empty-function': OFF,
'@typescript-eslint/no-non-null-assertion': OFF, // Have to use type assertion anyways
'@typescript-eslint/no-unused-vars': [ERROR, {argsIgnorePattern: '^_'}], '@typescript-eslint/no-unused-vars': [ERROR, {argsIgnorePattern: '^_'}],
'@typescript-eslint/ban-ts-comment': [ '@typescript-eslint/ban-ts-comment': [
ERROR, ERROR,
@ -113,7 +114,7 @@ module.exports = {
'prefer-destructuring': WARNING, 'prefer-destructuring': WARNING,
yoda: WARNING, yoda: WARNING,
'no-control-regex': WARNING, 'no-control-regex': WARNING,
'no-empty': WARNING, 'no-empty': [WARNING, {allowEmptyCatch: true}],
'no-prototype-builtins': WARNING, 'no-prototype-builtins': WARNING,
'no-case-declarations': WARNING, 'no-case-declarations': WARNING,
'no-undef': OFF, 'no-undef': OFF,
@ -130,6 +131,7 @@ module.exports = {
], ],
rules: { rules: {
'header/header': OFF, 'header/header': OFF,
'global-require': OFF,
}, },
}, },
{ {

View file

@ -130,6 +130,7 @@ function doProcessDocMetadata({
// Strip number prefixes by default (01-MyFolder/01-MyDoc.md => MyFolder/MyDoc) by default, // Strip number prefixes by default (01-MyFolder/01-MyDoc.md => MyFolder/MyDoc) by default,
// but allow to disable this behavior with frontmatterr // but allow to disable this behavior with frontmatterr
// eslint-disable-next-line camelcase
parse_number_prefixes = true, parse_number_prefixes = true,
} = frontMatter; } = frontMatter;
@ -144,6 +145,7 @@ function doProcessDocMetadata({
// ex: myDoc -> . // ex: myDoc -> .
const sourceDirName = path.dirname(source); const sourceDirName = path.dirname(source);
// eslint-disable-next-line camelcase
const {filename: unprefixedFileName, numberPrefix} = parse_number_prefixes const {filename: unprefixedFileName, numberPrefix} = parse_number_prefixes
? options.numberPrefixParser(sourceFileNameWithoutExtension) ? options.numberPrefixParser(sourceFileNameWithoutExtension)
: {filename: sourceFileNameWithoutExtension, numberPrefix: undefined}; : {filename: sourceFileNameWithoutExtension, numberPrefix: undefined};
@ -172,6 +174,7 @@ function doProcessDocMetadata({
return undefined; return undefined;
} }
// Eventually remove the number prefixes from intermediate directories // Eventually remove the number prefixes from intermediate directories
// eslint-disable-next-line camelcase
return parse_number_prefixes return parse_number_prefixes
? stripPathNumberPrefixes(sourceDirName, options.numberPrefixParser) ? stripPathNumberPrefixes(sourceDirName, options.numberPrefixParser)
: sourceDirName; : sourceDirName;

View file

@ -127,7 +127,10 @@ function assertIsCategory(
); );
} }
// "collapsed" is an optional property // "collapsed" is an optional property
if (item.hasOwnProperty('collapsed') && typeof item.collapsed !== 'boolean') { if (
typeof item.collapsed !== 'undefined' &&
typeof item.collapsed !== 'boolean'
) {
throw new Error( throw new Error(
`Error loading ${JSON.stringify(item)}: "collapsed" must be a boolean.`, `Error loading ${JSON.stringify(item)}: "collapsed" must be a boolean.`,
); );
@ -438,7 +441,20 @@ export function collectSidebarsDocIds(
}); });
} }
export function createSidebarsUtils(sidebars: Sidebars) { export function createSidebarsUtils(
sidebars: Sidebars,
): {
getFirstDocIdOfFirstSidebar: () => string | undefined;
getSidebarNameByDocId: (docId: string) => string | undefined;
getDocNavigation: (
docId: string,
) => {
sidebarName: string | undefined;
previousId: string | undefined;
nextId: string | undefined;
};
checkSidebarsDocIds: (validDocIds: string[], sidebarFilePath: string) => void;
} {
const sidebarNameToDocIds = collectSidebarsDocIds(sidebars); const sidebarNameToDocIds = collectSidebarsDocIds(sidebars);
function getFirstDocIdOfFirstSidebar(): string | undefined { function getFirstDocIdOfFirstSidebar(): string | undefined {

View file

@ -187,6 +187,8 @@ export type LastUpdateData = {
}; };
export type DocFrontMatter = { export type DocFrontMatter = {
// Front matter uses snake case
/* eslint-disable camelcase */
id?: string; id?: string;
title?: string; title?: string;
hide_title?: boolean; hide_title?: boolean;
@ -200,6 +202,7 @@ export type DocFrontMatter = {
pagination_label?: string; pagination_label?: string;
custom_edit_url?: string | null; custom_edit_url?: string | null;
parse_number_prefixes?: boolean; parse_number_prefixes?: boolean;
/* eslint-enable camelcase */
}; };
export type DocMetadataBase = LastUpdateData & { export type DocMetadataBase = LastUpdateData & {
@ -213,7 +216,6 @@ export type DocMetadataBase = LastUpdateData & {
sourceDirName: string; // relative to the docs folder (can be ".") sourceDirName: string; // relative to the docs folder (can be ".")
slug: string; slug: string;
permalink: string; permalink: string;
// eslint-disable-next-line camelcase
sidebarPosition?: number; sidebarPosition?: number;
editUrl?: string | null; editUrl?: string | null;
frontMatter: DocFrontMatter & Record<string, unknown>; frontMatter: DocFrontMatter & Record<string, unknown>;

View file

@ -341,11 +341,13 @@ function createVersionMetadata({
// retro-compatible values // retro-compatible values
const defaultVersionLabel = const defaultVersionLabel =
versionName === CURRENT_VERSION_NAME ? 'Next' : versionName; versionName === CURRENT_VERSION_NAME ? 'Next' : versionName;
const defaultVersionPathPart = isLast function getDefaultVersionPathPart() {
? '' if (isLast) {
: versionName === CURRENT_VERSION_NAME return '';
? 'next' }
: versionName; return versionName === CURRENT_VERSION_NAME ? 'next' : versionName;
}
const defaultVersionPathPart = getDefaultVersionPathPart();
const versionOptions: VersionOptions = options.versions[versionName] ?? {}; const versionOptions: VersionOptions = options.versions[versionName] ?? {};

View file

@ -39,6 +39,7 @@ export default function (
options: { options: {
emitFile: !isServer, // don't emit for server-side rendering emitFile: !isServer, // don't emit for server-side rendering
disable: !isProd, disable: !isProd,
// eslint-disable-next-line global-require
adapter: require('@docusaurus/responsive-loader/sharp'), adapter: require('@docusaurus/responsive-loader/sharp'),
name: isProd name: isProd
? 'assets/ideal-img/[name].[hash:hex:7].[width].[ext]' ? 'assets/ideal-img/[name].[hash:hex:7].[width].[ext]'

View file

@ -21,10 +21,10 @@ const ThemedImage = (props: Props): JSX.Element => {
type SourceName = keyof Props['sources']; type SourceName = keyof Props['sources'];
const clientThemes: SourceName[] = isDarkTheme ? ['dark'] : ['light'];
const renderedSourceNames: SourceName[] = isClient const renderedSourceNames: SourceName[] = isClient
? isDarkTheme ? clientThemes
? ['dark']
: ['light']
: // We need to render both images on the server to avoid flash : // We need to render both images on the server to avoid flash
// See https://github.com/facebook/docusaurus/pull/3730 // See https://github.com/facebook/docusaurus/pull/3730
['light', 'dark']; ['light', 'dark'];

View file

@ -21,10 +21,10 @@ const ThemedImage = (props: Props): JSX.Element => {
type SourceName = keyof Props['sources']; type SourceName = keyof Props['sources'];
const clientThemes: SourceName[] = isDarkTheme ? ['dark'] : ['light'];
const renderedSourceNames: SourceName[] = isClient const renderedSourceNames: SourceName[] = isClient
? isDarkTheme ? clientThemes
? ['dark']
: ['light']
: // We need to render both images on the server to avoid flash : // We need to render both images on the server to avoid flash
// See https://github.com/facebook/docusaurus/pull/3730 // See https://github.com/facebook/docusaurus/pull/3730
['light', 'dark']; ['light', 'dark'];

View file

@ -22,12 +22,12 @@ const useTabGroupChoice = (): useTabGroupChoiceReturns => {
useEffect(() => { useEffect(() => {
try { try {
const localStorageChoices = {}; const localStorageChoices = {};
for (const storageKey of listStorageKeys()) { listStorageKeys().forEach((storageKey) => {
if (storageKey.startsWith(TAB_CHOICE_PREFIX)) { if (storageKey.startsWith(TAB_CHOICE_PREFIX)) {
const groupId = storageKey.substring(TAB_CHOICE_PREFIX.length); const groupId = storageKey.substring(TAB_CHOICE_PREFIX.length);
localStorageChoices[groupId] = createStorageSlot(storageKey).get(); localStorageChoices[groupId] = createStorageSlot(storageKey).get();
} }
} });
setChoices(localStorageChoices); setChoices(localStorageChoices);
} catch (err) { } catch (err) {
console.error(err); console.error(err);

View file

@ -53,6 +53,7 @@ async function extractThemeCodeMessages() {
const { const {
globSourceCodeFilePaths, globSourceCodeFilePaths,
extractAllSourceCodeFileTranslations, extractAllSourceCodeFileTranslations,
// eslint-disable-next-line global-require
} = require('@docusaurus/core/lib/server/translations/translationsExtractor'); } = require('@docusaurus/core/lib/server/translations/translationsExtractor');
const filePaths = ( const filePaths = (

View file

@ -11,7 +11,15 @@ import {useLocation} from '@docusaurus/router';
// Permits to obtain the url of the current page in another locale // Permits to obtain the url of the current page in another locale
// Useful to generate hreflang meta headers etc... // Useful to generate hreflang meta headers etc...
// See https://developers.google.com/search/docs/advanced/crawling/localized-versions // See https://developers.google.com/search/docs/advanced/crawling/localized-versions
export function useAlternatePageUtils() { export function useAlternatePageUtils(): {
createUrl: ({
locale,
fullyQualified,
}: {
locale: string;
fullyQualified: boolean;
}) => string;
} {
const { const {
siteConfig: {baseUrl, url}, siteConfig: {baseUrl, url},
i18n: {defaultLocale, currentLocale}, i18n: {defaultLocale, currentLocale},

View file

@ -107,7 +107,9 @@ function selectPluralMessage(
} }
} }
export function usePluralForm() { export function usePluralForm(): {
selectMessage: (count: number, pluralMessages: string) => string;
} {
const localePluralForm = useLocalePluralForms(); const localePluralForm = useLocalePluralForms();
return { return {
selectMessage: (count: number, pluralMessages: string): string => { selectMessage: (count: number, pluralMessages: string): string => {

View file

@ -21,6 +21,9 @@ export default function applyTrailingSlash(
function removeTrailingSlash(str: string): string { function removeTrailingSlash(str: string): string {
return str.endsWith('/') ? str.slice(0, -1) : str; return str.endsWith('/') ? str.slice(0, -1) : str;
} }
function handleTrailingSlash(str: string, trailing: boolean): string {
return trailing ? addTrailingSlash(str) : removeTrailingSlash(str);
}
// undefined = legacy retrocompatible behavior // undefined = legacy retrocompatible behavior
if (typeof trailingSlash === 'undefined') { if (typeof trailingSlash === 'undefined') {
@ -32,10 +35,6 @@ export default function applyTrailingSlash(
// Never transform '/' to '' // Never transform '/' to ''
const newPathname = const newPathname =
pathname === '/' pathname === '/' ? '/' : handleTrailingSlash(pathname, trailingSlash);
? '/'
: trailingSlash
? addTrailingSlash(pathname)
: removeTrailingSlash(pathname);
return path.replace(pathname, newPathname); return path.replace(pathname, newPathname);
} }

View file

@ -35,7 +35,7 @@ export const logValidationBugReportHint = (): void => {
); );
}; };
export function printWarning(warning?: Joi.ValidationError) { export function printWarning(warning?: Joi.ValidationError): void {
if (warning) { if (warning) {
const warningMessages = warning.details const warningMessages = warning.details
.map(({message}) => message) .map(({message}) => message)

View file

@ -36,17 +36,17 @@ export function createExcerpt(fileString: string): string | undefined {
// Remove HTML tags. // Remove HTML tags.
.replace(/<[^>]*>/g, '') .replace(/<[^>]*>/g, '')
// Remove Title headers // Remove Title headers
.replace(/^\#\s*([^#]*)\s*\#?/gm, '') .replace(/^#\s*([^#]*)\s*#?/gm, '')
// Remove Markdown + ATX-style headers // Remove Markdown + ATX-style headers
.replace(/^\#{1,6}\s*([^#]*)\s*(\#{1,6})?/gm, '$1') .replace(/^#{1,6}\s*([^#]*)\s*(#{1,6})?/gm, '$1')
// Remove emphasis and strikethroughs. // Remove emphasis and strikethroughs.
.replace(/([\*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2') .replace(/([*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2')
// Remove images. // Remove images.
.replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, '$1') .replace(/!\[(.*?)\][[(].*?[\])]/g, '$1')
// Remove footnotes. // Remove footnotes.
.replace(/\[\^.+?\](\: .*?$)?/g, '') .replace(/\[\^.+?\](: .*?$)?/g, '')
// Remove inline links. // Remove inline links.
.replace(/\[(.*?)\][\[\(].*?[\]\)]/g, '$1') .replace(/\[(.*?)\][[(].*?[\])]/g, '$1')
// Remove inline code. // Remove inline code.
.replace(/`(.+?)`/g, '$1') .replace(/`(.+?)`/g, '$1')
// Remove blockquotes. // Remove blockquotes.

View file

@ -12,7 +12,7 @@ export function buildUrl(
organizationName: string, organizationName: string,
projectName: string, projectName: string,
useSSH: boolean | undefined, useSSH: boolean | undefined,
) { ): string {
return useSSH return useSSH
? buildSshUrl(githubHost, organizationName, projectName, githubPort) ? buildSshUrl(githubHost, organizationName, projectName, githubPort)
: buildHttpsUrl( : buildHttpsUrl(

View file

@ -29,7 +29,10 @@ export function getDefaultLocaleConfig(locale: string): I18nLocaleConfig {
}; };
} }
export function shouldWarnAboutNodeVersion(version: number, locales: string[]) { export function shouldWarnAboutNodeVersion(
version: number,
locales: string[],
): boolean {
const isOnlyEnglish = locales.length === 1 && locales.includes('en'); const isOnlyEnglish = locales.length === 1 && locales.includes('en');
const isOlderNodeVersion = version < 14; const isOlderNodeVersion = version < 14;
return isOlderNodeVersion && !isOnlyEnglish; return isOlderNodeVersion && !isOnlyEnglish;

View file

@ -50,7 +50,7 @@ export async function loadSiteConfig({
}: { }: {
siteDir: string; siteDir: string;
customConfigFilePath?: string; customConfigFilePath?: string;
}) { }): Promise<{siteConfig: DocusaurusConfig; siteConfigPath: string}> {
const siteConfigPathUnresolved = const siteConfigPathUnresolved =
customConfigFilePath ?? DEFAULT_CONFIG_FILE_NAME; customConfigFilePath ?? DEFAULT_CONFIG_FILE_NAME;

View file

@ -11,7 +11,7 @@ import {applyTrailingSlash} from '@docusaurus/utils-common';
export default function applyRouteTrailingSlash( export default function applyRouteTrailingSlash(
route: RouteConfig, route: RouteConfig,
trailingSlash: boolean | undefined, trailingSlash: boolean | undefined,
) { ): RouteConfig {
return { return {
...route, ...route,
path: applyTrailingSlash(route.path, trailingSlash), path: applyTrailingSlash(route.path, trailingSlash),