Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: remove a few Lodash usages & ESLint enforcement #5807

Merged
merged 6 commits into from
Oct 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 26 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,36 @@ module.exports = {
'no-redeclare': OFF,
'@typescript-eslint/no-redeclare': ERROR,
'@typescript-eslint/no-empty-interface': [
'error',
ERROR,
{
allowSingleExtends: true,
},
],
'no-restricted-imports': [
ERROR,
{
paths: [
{
name: 'lodash',
importNames: [
// 'compact', // TODO: TS doesn't make Boolean a narrowing function yet, so filter(Boolean) is problematic type-wise
'filter',
'flatten',
'flatMap',
'map',
'reduce',
'take',
'takeRight',
'head',
'tail',
'initial',
'last',
],
message: 'These APIs have their ES counterparts.',
},
],
},
],
},
overrides: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import {flatten, uniqBy, difference, groupBy} from 'lodash';
import {uniqBy, difference, groupBy} from 'lodash';
import {
PluginContext,
RedirectMetadata,
Expand Down Expand Up @@ -165,7 +165,7 @@ function createRedirectsOptionRedirects(
}));
}

return flatten(redirectsOption.map(optionToRedirects));
return redirectsOption.flatMap(optionToRedirects);
}

// Create redirects from the "createRedirects" fn provided by the user
Expand All @@ -189,5 +189,5 @@ function createCreateRedirectsOptionRedirects(
});
}

return flatten(paths.map(createPathRedirects));
return paths.flatMap(createPathRedirects);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* LICENSE file in the root directory of this source tree.
*/

import {flatten} from 'lodash';
import {
addTrailingSlash,
removeSuffix,
Expand Down Expand Up @@ -62,7 +61,7 @@ export function createToExtensionsRedirects(
return [];
};

return flatten(paths.map(createPathRedirects));
return paths.flatMap(createPathRedirects);
}

// Create new /path.html/index.html that redirects to existing an /path
Expand Down Expand Up @@ -99,5 +98,5 @@ export function createFromExtensionsRedirects(
}));
};

return flatten(paths.map(createPathRedirects));
return paths.flatMap(createPathRedirects);
}
8 changes: 4 additions & 4 deletions packages/docusaurus-plugin-content-blog/src/blogUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import fs from 'fs-extra';
import chalk from 'chalk';
import path from 'path';
import readingTime from 'reading-time';
import {compact, keyBy, mapValues} from 'lodash';
import {keyBy, mapValues} from 'lodash';
import {
PluginOptions,
BlogPost,
Expand Down Expand Up @@ -267,7 +267,7 @@ export async function generateBlogPosts(
authorsMapPath: options.authorsMapPath,
});

const blogPosts: BlogPost[] = compact(
const blogPosts = (
await Promise.all(
blogSourceFiles.map(async (blogSourceFile: string) => {
try {
Expand All @@ -287,8 +287,8 @@ export async function generateBlogPosts(
throw e;
}
}),
),
);
)
).filter(Boolean) as BlogPost[];

blogPosts.sort(
(a, b) => b.metadata.date.getTime() - a.metadata.date.getTime(),
Expand Down
9 changes: 3 additions & 6 deletions packages/docusaurus-plugin-content-blog/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
DEFAULT_PLUGIN_ID,
} from '@docusaurus/core/lib/constants';
import {translateContent, getTranslationFiles} from './translations';
import {flatten, take} from 'lodash';

import {
PluginOptions,
Expand Down Expand Up @@ -98,10 +97,8 @@ export default function pluginContentBlog(

getPathsToWatch() {
const {include, authorsMapPath} = options;
const contentMarkdownGlobs = flatten(
getContentPathList(contentPaths).map((contentPath) => {
return include.map((pattern) => `${contentPath}/${pattern}`);
}),
const contentMarkdownGlobs = getContentPathList(contentPaths).flatMap(
(contentPath) => include.map((pattern) => `${contentPath}/${pattern}`),
);

// TODO: we should read this path in plugin! but plugins do not support async init for now :'(
Expand Down Expand Up @@ -244,7 +241,7 @@ export default function pluginContentBlog(
const sidebarBlogPosts =
options.blogSidebarCount === 'ALL'
? blogPosts
: take(blogPosts, options.blogSidebarCount);
: blogPosts.slice(0, options.blogSidebarCount);

const archiveUrl = normalizeUrl([
baseUrl,
Expand Down
6 changes: 3 additions & 3 deletions packages/docusaurus-plugin-content-docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import {
import {RuleSetRule} from 'webpack';
import {cliDocsVersionCommand} from './cli';
import {VERSIONS_JSON_FILE} from './constants';
import {keyBy, compact, mapValues} from 'lodash';
import {keyBy, mapValues} from 'lodash';
import {toGlobalDataVersion} from './globalData';
import {toTagDocListProp, toVersionMetadataProp} from './props';
import {
Expand Down Expand Up @@ -388,7 +388,7 @@ export default function pluginContentDocs(
include: contentDirs
// Trailing slash is important, see https://github.com/facebook/docusaurus/pull/3970
.map(addTrailingPathSeparator),
use: compact([
use: [
getJSLoader({isServer}),
{
loader: require.resolve('@docusaurus/mdx-loader'),
Expand All @@ -414,7 +414,7 @@ export default function pluginContentDocs(
loader: path.resolve(__dirname, './markdown/index.js'),
options: docsMarkdownOptions,
},
]),
].filter(Boolean),
};
}

Expand Down
7 changes: 2 additions & 5 deletions packages/docusaurus-plugin-content-pages/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ import {
Metadata,
PagesContentPaths,
} from './types';
import {flatten} from 'lodash';

export function getContentPathList(contentPaths: PagesContentPaths): string[] {
return [contentPaths.contentPathLocalized, contentPaths.contentPath];
Expand Down Expand Up @@ -86,10 +85,8 @@ export default function pluginContentPages(

getPathsToWatch() {
const {include = []} = options;
return flatten(
getContentPathList(contentPaths).map((contentPath) => {
return include.map((pattern) => `${contentPath}/${pattern}`);
}),
return getContentPathList(contentPaths).flatMap((contentPath) =>
include.map((pattern) => `${contentPath}/${pattern}`),
);
},

Expand Down
16 changes: 6 additions & 10 deletions packages/docusaurus-theme-classic/src/translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,16 @@ import {
Footer,
} from '@docusaurus/theme-common';

import {keyBy, chain, flatten} from 'lodash';
import {keyBy, chain} from 'lodash';
import {mergeTranslations} from '@docusaurus/utils';

function getNavbarTranslationFile(navbar: Navbar): TranslationFileContent {
// TODO handle properly all the navbar item types here!
function flattenNavbarItems(items: NavbarItem[]): NavbarItem[] {
const subItems = flatten(
items.map((item) => {
const allSubItems = flatten([item.items ?? []]);
return flattenNavbarItems(allSubItems);
}),
);
const subItems = items.flatMap((item) => {
const allSubItems = [item.items ?? []].flat();
return flattenNavbarItems(allSubItems);
});
return [...items, ...subItems];
}

Expand Down Expand Up @@ -84,9 +82,7 @@ function getFooterTranslationFile(footer: Footer): TranslationFileContent {
.value();

const footerLinkLabels: TranslationFileContent = chain(
flatten(footer.links.map((link) => link.items)).filter(
(link) => !!link.label,
),
footer.links.flatMap((link) => link.items).filter((link) => !!link.label),
)
.keyBy((linkItem) => `link.item.label.${linkItem.label}`)
.mapValues((linkItem) => ({
Expand Down
7 changes: 3 additions & 4 deletions packages/docusaurus/src/server/brokenLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import {matchRoutes, RouteConfig as RRRouteConfig} from 'react-router-config';
import resolvePathname from 'resolve-pathname';
import fs from 'fs-extra';
import {mapValues, pickBy, flatten, countBy} from 'lodash';
import {mapValues, pickBy, countBy} from 'lodash';
import {RouteConfig, ReportingSeverity} from '@docusaurus/types';
import {removePrefix, removeSuffix, reportMessage} from '@docusaurus/utils';
import {getAllFinalRoutes} from './utils';
Expand Down Expand Up @@ -110,10 +110,9 @@ export function getBrokenLinksErrorMessage(
// Add an additional message in such case to help user figure this out.
// see https://github.com/facebook/docusaurus/issues/3567#issuecomment-706973805
function getLayoutBrokenLinksHelpMessage() {
const flatList = flatten(
Object.entries(allBrokenLinks).map(([pagePage, brokenLinks]) =>
const flatList = Object.entries(allBrokenLinks).flatMap(
([pagePage, brokenLinks]) =>
brokenLinks.map((brokenLink) => ({pagePage, brokenLink})),
),
);

const countedBrokenLinks = countBy(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import traverse, {Node} from '@babel/traverse';
import generate from '@babel/generator';
import chalk from 'chalk';
import {parse, types as t, NodePath, TransformOptions} from '@babel/core';
import {flatten} from 'lodash';
import {
InitializedPlugin,
TranslationFileContent,
Expand Down Expand Up @@ -69,7 +68,7 @@ async function getSourceCodeFilePaths(
// The getPathsToWatch() generally returns the js/jsx/ts/tsx/md/mdx file paths
// We can use this method as well to know which folders we should try to extract translations from
// Hacky/implicit, but do we want to introduce a new lifecycle method for that???
const pluginsPaths = flatten(plugins.map(getPluginSourceCodeFilePaths));
const pluginsPaths = plugins.flatMap(getPluginSourceCodeFilePaths);

const allPaths = [...sitePaths, ...pluginsPaths];

Expand Down Expand Up @@ -133,11 +132,9 @@ export async function extractAllSourceCodeFileTranslations(
sourceCodeFilePaths: string[],
babelOptions: TransformOptions,
): Promise<SourceCodeFileTranslations[]> {
return flatten(
await Promise.all(
sourceCodeFilePaths.map((sourceFilePath) =>
extractSourceCodeFileTranslations(sourceFilePath, babelOptions),
),
return Promise.all(
sourceCodeFilePaths.flatMap((sourceFilePath) =>
extractSourceCodeFileTranslations(sourceFilePath, babelOptions),
),
);
}
Expand Down
6 changes: 3 additions & 3 deletions packages/docusaurus/src/server/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {flatMap} from 'lodash';

import {RouteConfig} from '@docusaurus/types';
import nodePath from 'path';
import {posixPath, Globby} from '@docusaurus/utils';

// Recursively get the final routes (routes with no subroutes)
export function getAllFinalRoutes(routeConfig: RouteConfig[]): RouteConfig[] {
function getFinalRoutes(route: RouteConfig): RouteConfig[] {
return route.routes ? flatMap(route.routes, getFinalRoutes) : [route];
return route.routes ? route.routes.flatMap(getFinalRoutes) : [route];
}
return flatMap(routeConfig, getFinalRoutes);
return routeConfig.flatMap(getFinalRoutes);
}

// Globby that fix Windows path patterns
Expand Down
1 change: 1 addition & 0 deletions website/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// This file is not used in compilation. It is here just for a nice editor experience.
"extends": "@tsconfig/docusaurus/tsconfig.json",
"compilerOptions": {
"lib": ["DOM", "ESNext"],
"baseUrl": ".",
"resolveJsonModule": true
},
Expand Down