From 462b1cf2bc3bce61d71758a10188b96fc19bfa6f Mon Sep 17 00:00:00 2001 From: Joshua Chen Date: Fri, 25 Jun 2021 00:12:48 +0800 Subject: [PATCH] style(v2): reduce number of ESLint warnings (#4993) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Initial work Signed-off-by: Josh-Cena * More fixes Signed-off-by: Josh-Cena * Update packages/docusaurus-theme-classic/src/theme/ThemedImage/index.tsx Co-authored-by: Sébastien Lorber * Update packages/docusaurus-theme-bootstrap/src/theme/ThemedImage/index.tsx Co-authored-by: Sébastien Lorber * Fix Signed-off-by: Josh-Cena * Replace versionPathPart with function Signed-off-by: Josh-Cena * Prefer non-null assertions Signed-off-by: Josh-Cena * Substitute for-of with forEach Signed-off-by: Josh-Cena * Fill `catch` block with placeholder comment Signed-off-by: Josh-Cena * Ignore local require Signed-off-by: Josh-Cena * Revert global require change Signed-off-by: Josh-Cena * Tighten eslint disable range Signed-off-by: Josh-Cena * Make eslint ignore examples and more tolerating to templates Signed-off-by: Josh-Cena * Use reduce to handle doc items sequentially Signed-off-by: Josh-Cena * Revert "Use reduce to handle doc items sequentially" This reverts commit c7525d463b7f8d09b608aa8e978fd7622fd82d24. * Address change requests Signed-off-by: Josh-Cena Co-authored-by: Sébastien Lorber --- .eslintignore | 1 + .eslintrc.js | 4 +++- .../src/docs.ts | 3 +++ .../src/sidebars.ts | 20 +++++++++++++++++-- .../src/types.ts | 4 +++- .../src/versions.ts | 12 ++++++----- .../src/index.ts | 1 + .../src/theme/ThemedImage/index.tsx | 6 +++--- .../src/theme/ThemedImage/index.tsx | 6 +++--- .../src/theme/hooks/useTabGroupChoice.ts | 4 ++-- .../update-code-translations.js | 1 + .../src/utils/useAlternatePageUtils.ts | 10 +++++++++- .../src/utils/usePluralForm.ts | 4 +++- .../src/applyTrailingSlash.tsx | 9 ++++----- .../src/validationUtils.ts | 2 +- .../docusaurus-utils/src/markdownParser.ts | 12 +++++------ .../src/commands/buildRemoteBranchUrl.ts | 2 +- packages/docusaurus/src/server/i18n.ts | 5 ++++- packages/docusaurus/src/server/index.ts | 2 +- .../server/plugins/applyRouteTrailingSlash.ts | 2 +- 20 files changed, 75 insertions(+), 35 deletions(-) diff --git a/.eslintignore b/.eslintignore index 4fc82ac92d..da4eaf9be0 100644 --- a/.eslintignore +++ b/.eslintignore @@ -8,6 +8,7 @@ jest.config.js jest.transform.js website/ scripts +examples/ packages/docusaurus/lib/ packages/docusaurus-*/lib/* diff --git a/.eslintrc.js b/.eslintrc.js index 0220596f34..92f71292f9 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -92,6 +92,7 @@ module.exports = { 'no-unused-vars': OFF, 'no-nested-ternary': WARNING, '@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/ban-ts-comment': [ ERROR, @@ -113,7 +114,7 @@ module.exports = { 'prefer-destructuring': WARNING, yoda: WARNING, 'no-control-regex': WARNING, - 'no-empty': WARNING, + 'no-empty': [WARNING, {allowEmptyCatch: true}], 'no-prototype-builtins': WARNING, 'no-case-declarations': WARNING, 'no-undef': OFF, @@ -130,6 +131,7 @@ module.exports = { ], rules: { 'header/header': OFF, + 'global-require': OFF, }, }, { diff --git a/packages/docusaurus-plugin-content-docs/src/docs.ts b/packages/docusaurus-plugin-content-docs/src/docs.ts index 114ffd82cb..29e9bf5345 100644 --- a/packages/docusaurus-plugin-content-docs/src/docs.ts +++ b/packages/docusaurus-plugin-content-docs/src/docs.ts @@ -130,6 +130,7 @@ function doProcessDocMetadata({ // Strip number prefixes by default (01-MyFolder/01-MyDoc.md => MyFolder/MyDoc) by default, // but allow to disable this behavior with frontmatterr + // eslint-disable-next-line camelcase parse_number_prefixes = true, } = frontMatter; @@ -144,6 +145,7 @@ function doProcessDocMetadata({ // ex: myDoc -> . const sourceDirName = path.dirname(source); + // eslint-disable-next-line camelcase const {filename: unprefixedFileName, numberPrefix} = parse_number_prefixes ? options.numberPrefixParser(sourceFileNameWithoutExtension) : {filename: sourceFileNameWithoutExtension, numberPrefix: undefined}; @@ -172,6 +174,7 @@ function doProcessDocMetadata({ return undefined; } // Eventually remove the number prefixes from intermediate directories + // eslint-disable-next-line camelcase return parse_number_prefixes ? stripPathNumberPrefixes(sourceDirName, options.numberPrefixParser) : sourceDirName; diff --git a/packages/docusaurus-plugin-content-docs/src/sidebars.ts b/packages/docusaurus-plugin-content-docs/src/sidebars.ts index 4c00c41ef3..86d06312b3 100644 --- a/packages/docusaurus-plugin-content-docs/src/sidebars.ts +++ b/packages/docusaurus-plugin-content-docs/src/sidebars.ts @@ -127,7 +127,10 @@ function assertIsCategory( ); } // "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( `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); function getFirstDocIdOfFirstSidebar(): string | undefined { diff --git a/packages/docusaurus-plugin-content-docs/src/types.ts b/packages/docusaurus-plugin-content-docs/src/types.ts index d9967c0954..bdef70b03b 100644 --- a/packages/docusaurus-plugin-content-docs/src/types.ts +++ b/packages/docusaurus-plugin-content-docs/src/types.ts @@ -187,6 +187,8 @@ export type LastUpdateData = { }; export type DocFrontMatter = { + // Front matter uses snake case + /* eslint-disable camelcase */ id?: string; title?: string; hide_title?: boolean; @@ -200,6 +202,7 @@ export type DocFrontMatter = { pagination_label?: string; custom_edit_url?: string | null; parse_number_prefixes?: boolean; + /* eslint-enable camelcase */ }; export type DocMetadataBase = LastUpdateData & { @@ -213,7 +216,6 @@ export type DocMetadataBase = LastUpdateData & { sourceDirName: string; // relative to the docs folder (can be ".") slug: string; permalink: string; - // eslint-disable-next-line camelcase sidebarPosition?: number; editUrl?: string | null; frontMatter: DocFrontMatter & Record; diff --git a/packages/docusaurus-plugin-content-docs/src/versions.ts b/packages/docusaurus-plugin-content-docs/src/versions.ts index 4854d936c4..5cfbb4560a 100644 --- a/packages/docusaurus-plugin-content-docs/src/versions.ts +++ b/packages/docusaurus-plugin-content-docs/src/versions.ts @@ -341,11 +341,13 @@ function createVersionMetadata({ // retro-compatible values const defaultVersionLabel = versionName === CURRENT_VERSION_NAME ? 'Next' : versionName; - const defaultVersionPathPart = isLast - ? '' - : versionName === CURRENT_VERSION_NAME - ? 'next' - : versionName; + function getDefaultVersionPathPart() { + if (isLast) { + return ''; + } + return versionName === CURRENT_VERSION_NAME ? 'next' : versionName; + } + const defaultVersionPathPart = getDefaultVersionPathPart(); const versionOptions: VersionOptions = options.versions[versionName] ?? {}; diff --git a/packages/docusaurus-plugin-ideal-image/src/index.ts b/packages/docusaurus-plugin-ideal-image/src/index.ts index c3ddf74b93..be7c0a11b6 100644 --- a/packages/docusaurus-plugin-ideal-image/src/index.ts +++ b/packages/docusaurus-plugin-ideal-image/src/index.ts @@ -39,6 +39,7 @@ export default function ( options: { emitFile: !isServer, // don't emit for server-side rendering disable: !isProd, + // eslint-disable-next-line global-require adapter: require('@docusaurus/responsive-loader/sharp'), name: isProd ? 'assets/ideal-img/[name].[hash:hex:7].[width].[ext]' diff --git a/packages/docusaurus-theme-bootstrap/src/theme/ThemedImage/index.tsx b/packages/docusaurus-theme-bootstrap/src/theme/ThemedImage/index.tsx index d9e5961a18..cdd8eb52ab 100644 --- a/packages/docusaurus-theme-bootstrap/src/theme/ThemedImage/index.tsx +++ b/packages/docusaurus-theme-bootstrap/src/theme/ThemedImage/index.tsx @@ -21,10 +21,10 @@ const ThemedImage = (props: Props): JSX.Element => { type SourceName = keyof Props['sources']; + const clientThemes: SourceName[] = isDarkTheme ? ['dark'] : ['light']; + const renderedSourceNames: SourceName[] = isClient - ? isDarkTheme - ? ['dark'] - : ['light'] + ? clientThemes : // We need to render both images on the server to avoid flash // See https://github.com/facebook/docusaurus/pull/3730 ['light', 'dark']; diff --git a/packages/docusaurus-theme-classic/src/theme/ThemedImage/index.tsx b/packages/docusaurus-theme-classic/src/theme/ThemedImage/index.tsx index f5d59791bc..28bbfffee7 100644 --- a/packages/docusaurus-theme-classic/src/theme/ThemedImage/index.tsx +++ b/packages/docusaurus-theme-classic/src/theme/ThemedImage/index.tsx @@ -21,10 +21,10 @@ const ThemedImage = (props: Props): JSX.Element => { type SourceName = keyof Props['sources']; + const clientThemes: SourceName[] = isDarkTheme ? ['dark'] : ['light']; + const renderedSourceNames: SourceName[] = isClient - ? isDarkTheme - ? ['dark'] - : ['light'] + ? clientThemes : // We need to render both images on the server to avoid flash // See https://github.com/facebook/docusaurus/pull/3730 ['light', 'dark']; diff --git a/packages/docusaurus-theme-classic/src/theme/hooks/useTabGroupChoice.ts b/packages/docusaurus-theme-classic/src/theme/hooks/useTabGroupChoice.ts index 493ce2a747..1ddb0ebc9e 100644 --- a/packages/docusaurus-theme-classic/src/theme/hooks/useTabGroupChoice.ts +++ b/packages/docusaurus-theme-classic/src/theme/hooks/useTabGroupChoice.ts @@ -22,12 +22,12 @@ const useTabGroupChoice = (): useTabGroupChoiceReturns => { useEffect(() => { try { const localStorageChoices = {}; - for (const storageKey of listStorageKeys()) { + listStorageKeys().forEach((storageKey) => { if (storageKey.startsWith(TAB_CHOICE_PREFIX)) { const groupId = storageKey.substring(TAB_CHOICE_PREFIX.length); localStorageChoices[groupId] = createStorageSlot(storageKey).get(); } - } + }); setChoices(localStorageChoices); } catch (err) { console.error(err); diff --git a/packages/docusaurus-theme-classic/update-code-translations.js b/packages/docusaurus-theme-classic/update-code-translations.js index d4ef57fe3e..bbd76fcf22 100644 --- a/packages/docusaurus-theme-classic/update-code-translations.js +++ b/packages/docusaurus-theme-classic/update-code-translations.js @@ -53,6 +53,7 @@ async function extractThemeCodeMessages() { const { globSourceCodeFilePaths, extractAllSourceCodeFileTranslations, + // eslint-disable-next-line global-require } = require('@docusaurus/core/lib/server/translations/translationsExtractor'); const filePaths = ( diff --git a/packages/docusaurus-theme-common/src/utils/useAlternatePageUtils.ts b/packages/docusaurus-theme-common/src/utils/useAlternatePageUtils.ts index 22f1e62781..bff300a634 100644 --- a/packages/docusaurus-theme-common/src/utils/useAlternatePageUtils.ts +++ b/packages/docusaurus-theme-common/src/utils/useAlternatePageUtils.ts @@ -11,7 +11,15 @@ import {useLocation} from '@docusaurus/router'; // Permits to obtain the url of the current page in another locale // Useful to generate hreflang meta headers etc... // 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 { siteConfig: {baseUrl, url}, i18n: {defaultLocale, currentLocale}, diff --git a/packages/docusaurus-theme-common/src/utils/usePluralForm.ts b/packages/docusaurus-theme-common/src/utils/usePluralForm.ts index 19d853dfeb..66068d4503 100644 --- a/packages/docusaurus-theme-common/src/utils/usePluralForm.ts +++ b/packages/docusaurus-theme-common/src/utils/usePluralForm.ts @@ -107,7 +107,9 @@ function selectPluralMessage( } } -export function usePluralForm() { +export function usePluralForm(): { + selectMessage: (count: number, pluralMessages: string) => string; +} { const localePluralForm = useLocalePluralForms(); return { selectMessage: (count: number, pluralMessages: string): string => { diff --git a/packages/docusaurus-utils-common/src/applyTrailingSlash.tsx b/packages/docusaurus-utils-common/src/applyTrailingSlash.tsx index 6ae6650642..c62d48f396 100644 --- a/packages/docusaurus-utils-common/src/applyTrailingSlash.tsx +++ b/packages/docusaurus-utils-common/src/applyTrailingSlash.tsx @@ -21,6 +21,9 @@ export default function applyTrailingSlash( function removeTrailingSlash(str: string): string { 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 if (typeof trailingSlash === 'undefined') { @@ -32,10 +35,6 @@ export default function applyTrailingSlash( // Never transform '/' to '' const newPathname = - pathname === '/' - ? '/' - : trailingSlash - ? addTrailingSlash(pathname) - : removeTrailingSlash(pathname); + pathname === '/' ? '/' : handleTrailingSlash(pathname, trailingSlash); return path.replace(pathname, newPathname); } diff --git a/packages/docusaurus-utils-validation/src/validationUtils.ts b/packages/docusaurus-utils-validation/src/validationUtils.ts index 10e03eb1a9..3365a32955 100644 --- a/packages/docusaurus-utils-validation/src/validationUtils.ts +++ b/packages/docusaurus-utils-validation/src/validationUtils.ts @@ -35,7 +35,7 @@ export const logValidationBugReportHint = (): void => { ); }; -export function printWarning(warning?: Joi.ValidationError) { +export function printWarning(warning?: Joi.ValidationError): void { if (warning) { const warningMessages = warning.details .map(({message}) => message) diff --git a/packages/docusaurus-utils/src/markdownParser.ts b/packages/docusaurus-utils/src/markdownParser.ts index 00ee44e213..1f9377dfdd 100644 --- a/packages/docusaurus-utils/src/markdownParser.ts +++ b/packages/docusaurus-utils/src/markdownParser.ts @@ -36,17 +36,17 @@ export function createExcerpt(fileString: string): string | undefined { // Remove HTML tags. .replace(/<[^>]*>/g, '') // Remove Title headers - .replace(/^\#\s*([^#]*)\s*\#?/gm, '') + .replace(/^#\s*([^#]*)\s*#?/gm, '') // 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. - .replace(/([\*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2') + .replace(/([*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2') // Remove images. - .replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, '$1') + .replace(/!\[(.*?)\][[(].*?[\])]/g, '$1') // Remove footnotes. - .replace(/\[\^.+?\](\: .*?$)?/g, '') + .replace(/\[\^.+?\](: .*?$)?/g, '') // Remove inline links. - .replace(/\[(.*?)\][\[\(].*?[\]\)]/g, '$1') + .replace(/\[(.*?)\][[(].*?[\])]/g, '$1') // Remove inline code. .replace(/`(.+?)`/g, '$1') // Remove blockquotes. diff --git a/packages/docusaurus/src/commands/buildRemoteBranchUrl.ts b/packages/docusaurus/src/commands/buildRemoteBranchUrl.ts index 44cbc949e5..cfb1b8c03d 100644 --- a/packages/docusaurus/src/commands/buildRemoteBranchUrl.ts +++ b/packages/docusaurus/src/commands/buildRemoteBranchUrl.ts @@ -12,7 +12,7 @@ export function buildUrl( organizationName: string, projectName: string, useSSH: boolean | undefined, -) { +): string { return useSSH ? buildSshUrl(githubHost, organizationName, projectName, githubPort) : buildHttpsUrl( diff --git a/packages/docusaurus/src/server/i18n.ts b/packages/docusaurus/src/server/i18n.ts index fa8a021dde..0546522e70 100644 --- a/packages/docusaurus/src/server/i18n.ts +++ b/packages/docusaurus/src/server/i18n.ts @@ -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 isOlderNodeVersion = version < 14; return isOlderNodeVersion && !isOnlyEnglish; diff --git a/packages/docusaurus/src/server/index.ts b/packages/docusaurus/src/server/index.ts index 7d470700de..a944c58787 100644 --- a/packages/docusaurus/src/server/index.ts +++ b/packages/docusaurus/src/server/index.ts @@ -50,7 +50,7 @@ export async function loadSiteConfig({ }: { siteDir: string; customConfigFilePath?: string; -}) { +}): Promise<{siteConfig: DocusaurusConfig; siteConfigPath: string}> { const siteConfigPathUnresolved = customConfigFilePath ?? DEFAULT_CONFIG_FILE_NAME; diff --git a/packages/docusaurus/src/server/plugins/applyRouteTrailingSlash.ts b/packages/docusaurus/src/server/plugins/applyRouteTrailingSlash.ts index b625a8e9e2..38d2bb0efe 100644 --- a/packages/docusaurus/src/server/plugins/applyRouteTrailingSlash.ts +++ b/packages/docusaurus/src/server/plugins/applyRouteTrailingSlash.ts @@ -11,7 +11,7 @@ import {applyTrailingSlash} from '@docusaurus/utils-common'; export default function applyRouteTrailingSlash( route: RouteConfig, trailingSlash: boolean | undefined, -) { +): RouteConfig { return { ...route, path: applyTrailingSlash(route.path, trailingSlash),