refactor: ensure lodash is default-imported (#6716)

This commit is contained in:
Joshua Chen 2022-02-19 18:15:02 +08:00 committed by GitHub
parent 47c9a37c5f
commit ea6ceaa371
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
44 changed files with 239 additions and 221 deletions

View file

@ -8,7 +8,7 @@
import path from 'path';
import {isMatch} from 'picomatch';
import commander from 'commander';
import {kebabCase, orderBy} from 'lodash';
import _ from 'lodash';
import fs from 'fs-extra';
import pluginContentDocs from '../index';
@ -89,7 +89,7 @@ Entries created:
checkVersionMetadataPropCreated: (version: LoadedVersion) => {
const versionMetadataProp = getCreatedDataByPrefix(
`version-${kebabCase(version.versionName)}-metadata-prop`,
`version-${_.kebabCase(version.versionName)}-metadata-prop`,
);
expect(versionMetadataProp.docsSidebars).toEqual(toSidebarsProp(version));
},
@ -815,7 +815,7 @@ describe('site with custom sidebar items generator', () => {
): SidebarItemsGeneratorOptionArgs {
return {
...arg,
docs: orderBy(arg.docs, 'id'),
docs: _.orderBy(arg.docs, 'id'),
version: {
...arg.version,
contentPath: path.relative(siteDir, arg.version.contentPath),

View file

@ -17,7 +17,7 @@ import type {
GlobalVersion,
ActivePlugin,
} from '@docusaurus/plugin-content-docs/client';
import {shuffle} from 'lodash';
import _ from 'lodash';
describe('docsClientUtils', () => {
test('getActivePlugin', () => {
@ -227,7 +227,7 @@ describe('docsClientUtils', () => {
};
// shuffle, because order shouldn't matter
const versions: GlobalVersion[] = shuffle([
const versions: GlobalVersion[] = _.shuffle([
versionNext,
version2,
version1,
@ -356,7 +356,7 @@ describe('docsClientUtils', () => {
};
// shuffle, because order shouldn't matter
const versions: GlobalVersion[] = shuffle([
const versions: GlobalVersion[] = _.shuffle([
versionNext,
version2,
version1,

View file

@ -8,7 +8,6 @@
import path from 'path';
import fs from 'fs-extra';
import logger from '@docusaurus/logger';
import {keyBy} from 'lodash';
import {
aliasedSitePath,
getEditUrl,
@ -444,8 +443,10 @@ export function getDocIds(doc: DocMetadataBase): [string, string] {
export function createDocsByIdIndex<
Doc extends {id: string; unversionedId: string},
>(docs: Doc[]): Record<string, Doc> {
return {
...keyBy(docs, (doc) => doc.unversionedId),
...keyBy(docs, (doc) => doc.id),
};
return Object.fromEntries(
docs.flatMap((doc) => [
[doc.unversionedId, doc],
[doc.id, doc],
]),
);
}

View file

@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/
import {mapValues} from 'lodash';
import _ from 'lodash';
import {normalizeUrl} from '@docusaurus/utils';
import type {Sidebars} from './sidebars/types';
import {createSidebarsUtils} from './sidebars/utils';
@ -43,7 +43,7 @@ export function toGlobalSidebars(
version: LoadedVersion,
): Record<string, GlobalSidebar> {
const {getFirstLink} = createSidebarsUtils(sidebars);
return mapValues(sidebars, (sidebar, sidebarId) => {
return _.mapValues(sidebars, (sidebar, sidebarId) => {
const firstLink = getFirstLink(sidebarId);
if (!firstLink) {
return {};

View file

@ -42,7 +42,6 @@ import type {
import type {RuleSetRule} from 'webpack';
import {cliDocsVersionCommand} from './cli';
import {VERSIONS_JSON_FILE} from './constants';
import {keyBy, mapValues} from 'lodash';
import {toGlobalDataVersion} from './globalData';
import {toTagDocListProp} from './props';
import {
@ -311,9 +310,8 @@ export default async function pluginContentDocs(
function getSourceToPermalink(): SourceToPermalink {
const allDocs = content.loadedVersions.flatMap((v) => v.docs);
return mapValues(
keyBy(allDocs, (d) => d.source),
(d) => d.permalink,
return Object.fromEntries(
allDocs.map(({source, permalink}) => [source, permalink]),
);
}

View file

@ -22,7 +22,7 @@ import type {
PropTagDocListDoc,
PropSidebarItemLink,
} from '@docusaurus/plugin-content-docs';
import {compact, keyBy, mapValues} from 'lodash';
import _ from 'lodash';
import {createDocsByIdIndex} from './docs';
export function toSidebarsProp(loadedVersion: LoadedVersion): PropSidebars {
@ -93,18 +93,22 @@ Available document ids are:
// Transform the sidebar so that all sidebar item will be in the
// form of 'link' or 'category' only.
// This is what will be passed as props to the UI component.
return mapValues(loadedVersion.sidebars, (items) => items.map(normalizeItem));
return _.mapValues(loadedVersion.sidebars, (items) =>
items.map(normalizeItem),
);
}
function toVersionDocsProp(loadedVersion: LoadedVersion): PropVersionDocs {
return mapValues(
keyBy(loadedVersion.docs, (doc) => doc.unversionedId),
(doc) => ({
id: doc.unversionedId,
title: doc.title,
description: doc.description,
sidebar: doc.sidebar,
}),
return Object.fromEntries(
loadedVersion.docs.map((doc) => [
doc.unversionedId,
{
id: doc.unversionedId,
title: doc.title,
description: doc.description,
sidebar: doc.sidebar,
},
]),
);
}
@ -135,7 +139,7 @@ export function toTagDocListProp({
docs: Pick<DocMetadata, 'id' | 'title' | 'description' | 'permalink'>[];
}): PropTagDocList {
function toDocListProp(): PropTagDocListDoc[] {
const list = compact(
const list = _.compact(
tag.docIds.map((id) => docs.find((doc) => doc.id === id)),
);
// Sort docs by title

View file

@ -13,7 +13,7 @@ import type {
NormalizedSidebarItem,
SidebarItemCategoryLinkConfig,
} from './types';
import {sortBy, last} from 'lodash';
import _ from 'lodash';
import {addTrailingSlash, posixPath} from '@docusaurus/utils';
import logger from '@docusaurus/logger';
import path from 'path';
@ -25,7 +25,7 @@ const docIdPrefix = '$doc$/';
// Just an alias to the make code more explicit
function getLocalDocId(docId: string): string {
return last(docId.split('/'))!;
return _.last(docId.split('/'))!;
}
export const CategoryMetadataFilenameBase = '_category_';
@ -248,7 +248,7 @@ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async ({
}
return item;
});
const sortedSidebarItems = sortBy(
const sortedSidebarItems = _.sortBy(
processedSidebarItems,
(item) => item.position,
);

View file

@ -17,7 +17,7 @@ import {Globby} from '@docusaurus/utils';
import logger from '@docusaurus/logger';
import type {PluginOptions} from '@docusaurus/plugin-content-docs';
import Yaml from 'js-yaml';
import {groupBy, mapValues} from 'lodash';
import _ from 'lodash';
import combinePromises from 'combine-promises';
export const DefaultSidebars: SidebarsConfig = {
@ -46,9 +46,9 @@ async function readCategoriesMetadata(contentPath: string) {
const categoryFiles = await Globby('**/_category_.{json,yml,yaml}', {
cwd: contentPath,
});
const categoryToFile = groupBy(categoryFiles, path.dirname);
const categoryToFile = _.groupBy(categoryFiles, path.dirname);
return combinePromises(
mapValues(categoryToFile, async (files, folder) => {
_.mapValues(categoryToFile, async (files, folder) => {
const [filePath] = files;
if (files.length > 1) {
logger.warn`There are more than one category metadata files for path=${folder}: ${files.join(

View file

@ -17,7 +17,7 @@ import type {
NormalizedSidebarItemCategory,
} from './types';
import {isCategoriesShorthand} from './utils';
import {mapValues} from 'lodash';
import _ from 'lodash';
function normalizeCategoriesShorthand(
sidebar: SidebarCategoriesShorthand,
@ -81,5 +81,5 @@ function normalizeSidebar(sidebar: SidebarConfig): NormalizedSidebar {
export function normalizeSidebars(
sidebars: SidebarsConfig,
): NormalizedSidebars {
return mapValues(sidebars, normalizeSidebar);
return _.mapValues(sidebars, normalizeSidebar);
}

View file

@ -15,7 +15,7 @@ import type {
ProcessedSidebars,
SidebarItemCategoryLink,
} from './types';
import {mapValues} from 'lodash';
import _ from 'lodash';
function normalizeCategoryLink(
category: ProcessedSidebarItemCategory,
@ -88,7 +88,7 @@ export function postProcessSidebars(
sidebars: ProcessedSidebars,
params: SidebarProcessorParams,
): Sidebars {
return mapValues(sidebars, (sidebar) =>
return _.mapValues(sidebars, (sidebar) =>
sidebar.map((item) => postProcessSidebarItem(item, params)),
);
}

View file

@ -21,14 +21,14 @@ import type {
} from './types';
import {DefaultSidebarItemsGenerator} from './generator';
import {validateSidebars} from './validation';
import {mapValues, memoize, pick} from 'lodash';
import _ from 'lodash';
import combinePromises from 'combine-promises';
import {isCategoryIndex} from '../docs';
function toSidebarItemsGeneratorDoc(
doc: DocMetadataBase,
): SidebarItemsGeneratorDoc {
return pick(doc, [
return _.pick(doc, [
'id',
'unversionedId',
'frontMatter',
@ -41,7 +41,7 @@ function toSidebarItemsGeneratorDoc(
function toSidebarItemsGeneratorVersion(
version: VersionMetadata,
): SidebarItemsGeneratorVersion {
return pick(version, ['versionName', 'contentPath']);
return _.pick(version, ['versionName', 'contentPath']);
}
// Handle the generation of autogenerated sidebar items and other
@ -60,7 +60,7 @@ async function processSidebar(
} = params;
// Just a minor lazy transformation optimization
const getSidebarItemsGeneratorDocsAndVersion = memoize(() => ({
const getSidebarItemsGeneratorDocsAndVersion = _.memoize(() => ({
docs: docs.map(toSidebarItemsGeneratorDoc),
version: toSidebarItemsGeneratorVersion(version),
}));
@ -117,7 +117,7 @@ export async function processSidebars(
params: SidebarProcessorParams,
): Promise<ProcessedSidebars> {
const processedSidebars = await combinePromises(
mapValues(unprocessedSidebars, (unprocessedSidebar) =>
_.mapValues(unprocessedSidebars, (unprocessedSidebar) =>
processSidebar(unprocessedSidebar, categoriesMetadata, params),
),
);

View file

@ -19,7 +19,7 @@ import type {
SidebarNavigationItem,
} from './types';
import {mapValues, difference, uniq} from 'lodash';
import _ from 'lodash';
import {getElementsAround, toMessageRelativeFilePath} from '@docusaurus/utils';
import type {DocMetadataBase, DocNavLink} from '../types';
@ -110,13 +110,13 @@ export function collectSidebarNavigation(
export function collectSidebarsDocIds(
sidebars: Sidebars,
): Record<string, string[]> {
return mapValues(sidebars, collectSidebarDocIds);
return _.mapValues(sidebars, collectSidebarDocIds);
}
export function collectSidebarsNavigations(
sidebars: Sidebars,
): Record<string, SidebarNavigationItem[]> {
return mapValues(sidebars, collectSidebarNavigation);
return _.mapValues(sidebars, collectSidebarNavigation);
}
export type SidebarNavigation = {
@ -276,7 +276,7 @@ export function createSidebarsUtils(sidebars: Sidebars): SidebarsUtils {
function checkSidebarsDocIds(validDocIds: string[], sidebarFilePath: string) {
const allSidebarDocIds = Object.values(sidebarNameToDocIds).flat();
const invalidSidebarDocIds = difference(allSidebarDocIds, validDocIds);
const invalidSidebarDocIds = _.difference(allSidebarDocIds, validDocIds);
if (invalidSidebarDocIds.length > 0) {
throw new Error(
`Invalid sidebar file at "${toMessageRelativeFilePath(
@ -286,7 +286,7 @@ These sidebar document ids do not exist:
- ${invalidSidebarDocIds.sort().join('\n- ')}
Available document ids are:
- ${uniq(validDocIds).sort().join('\n- ')}`,
- ${_.uniq(validDocIds).sort().join('\n- ')}`,
);
}
}

View file

@ -7,11 +7,11 @@
import {groupTaggedItems} from '@docusaurus/utils';
import type {VersionTags, DocMetadata} from './types';
import {mapValues} from 'lodash';
import _ from 'lodash';
export function getVersionTags(docs: DocMetadata[]): VersionTags {
const groups = groupTaggedItems(docs, (doc) => doc.tags);
return mapValues(groups, (group) => ({
return _.mapValues(groups, (group) => ({
name: group.tag.label,
docIds: group.items.map((item) => item.id),
permalink: group.tag.permalink,

View file

@ -13,7 +13,7 @@ import type {
Sidebars,
} from './sidebars/types';
import {chain, mapValues, keyBy} from 'lodash';
import _ from 'lodash';
import {
collectSidebarCategories,
transformSidebarItems,
@ -146,13 +146,15 @@ function getSidebarTranslationFileContent(
);
const links = collectSidebarLinks(sidebar);
const linksContent: TranslationFileContent = chain(links)
.keyBy((link) => `sidebar.${sidebarName}.link.${link.label}`)
.mapValues((link) => ({
message: link.label,
description: `The label for link ${link.label} in sidebar ${sidebarName}, linking to ${link.href}`,
}))
.value();
const linksContent: TranslationFileContent = Object.fromEntries(
links.map((link) => [
`sidebar.${sidebarName}.link.${link.label}`,
{
message: link.label,
description: `The label for link ${link.label} in sidebar ${sidebarName}, linking to ${link.href}`,
},
]),
);
return mergeTranslations([categoryContent, linksContent]);
}
@ -230,7 +232,7 @@ function translateSidebars(
version: LoadedVersion,
sidebarsTranslations: TranslationFileContent,
): Sidebars {
return mapValues(version.sidebars, (sidebar, sidebarName) =>
return _.mapValues(version.sidebars, (sidebar, sidebarName) =>
translateSidebar({
sidebar,
sidebarName: getNormalizedSidebarName({
@ -302,7 +304,7 @@ export function translateLoadedContent(
loadedContent: LoadedContent,
translationFiles: TranslationFile[],
): LoadedContent {
const translationFilesMap: Record<string, TranslationFile> = keyBy(
const translationFilesMap: Record<string, TranslationFile> = _.keyBy(
translationFiles,
(f) => f.path,
);

View file

@ -28,7 +28,7 @@ import {
posixPath,
DEFAULT_PLUGIN_ID,
} from '@docusaurus/utils';
import {difference} from 'lodash';
import _ from 'lodash';
import {resolveSidebarPathOption} from './sidebars';
// retro-compatibility: no prefix for the default plugin id
@ -486,7 +486,7 @@ function checkVersionsOptions(
`Docs option lastVersion: ${options.lastVersion} is invalid. ${availableVersionNamesMsg}`,
);
}
const unknownVersionConfigNames = difference(
const unknownVersionConfigNames = _.difference(
Object.keys(options.versions),
availableVersionNames,
);
@ -504,7 +504,7 @@ function checkVersionsOptions(
`Invalid docs option "onlyIncludeVersions": an empty array is not allowed, at least one version is needed.`,
);
}
const unknownOnlyIncludeVersionNames = difference(
const unknownOnlyIncludeVersionNames = _.difference(
options.onlyIncludeVersions,
availableVersionNames,
);