Skip to content

Commit

Permalink
misc(v2): clean up comments in code (#2294)
Browse files Browse the repository at this point in the history
  • Loading branch information
yangshun authored Feb 18, 2020
1 parent d7f3dff commit 996b115
Show file tree
Hide file tree
Showing 45 changed files with 233 additions and 154 deletions.
12 changes: 6 additions & 6 deletions packages/docusaurus-init/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function init(

let name = siteName;

// Prompt if siteName is not passed from CLI
// Prompt if siteName is not passed from CLI.
if (!name) {
const {name: promptedName} = await inquirer.prompt({
type: 'input',
Expand All @@ -71,7 +71,7 @@ export async function init(
}

let template = reqTemplate;
// Prompt if template is not provided from CLI
// Prompt if template is not provided from CLI.
if (!template) {
const {template: promptedTemplate} = await inquirer.prompt({
type: 'list',
Expand All @@ -82,7 +82,7 @@ export async function init(
template = promptedTemplate;
}

// If user choose Git repository, we'll prompt for the url
// If user choose Git repository, we'll prompt for the url.
if (template === gitChoice) {
const {gitRepoUrl} = await inquirer.prompt({
type: 'input',
Expand Down Expand Up @@ -112,7 +112,7 @@ export async function init(
throw new Error(chalk.red(`Cloning Git template: ${template} failed!`));
}
} else if (template && templates.includes(template)) {
// Docusaurus templates
// Docusaurus templates.
try {
await fs.copy(path.resolve(templatesDir, template), dest);
} catch (err) {
Expand All @@ -125,7 +125,7 @@ export async function init(
throw new Error('Invalid template');
}

// Update package.json info
// Update package.json info.
try {
await updatePkg(path.join(dest, 'package.json'), {
name: kebabCase(name),
Expand All @@ -137,7 +137,7 @@ export async function init(
throw err;
}

// We need to Rename the gitignore file to .gitignore
// We need to rename the gitignore file to .gitignore
if (
!fs.pathExistsSync(path.join(dest, '.gitignore')) &&
fs.pathExistsSync(path.join(dest, 'gitignore'))
Expand Down
5 changes: 3 additions & 2 deletions packages/docusaurus-mdx-loader/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,13 @@ module.exports = async function(fileString) {

let exportStr = `export const frontMatter = ${stringifyObject(data)};`;

// Read metadata for this MDX and export it
// Read metadata for this MDX and export it.
if (options.metadataPath && typeof options.metadataPath === 'function') {
const metadataPath = options.metadataPath(this.resourcePath);

if (metadataPath) {
// Add as dependency of this loader result so that we can recompile if metadata is changed
// Add as dependency of this loader result so that we can
// recompile if metadata is changed.
this.addDependency(metadataPath);
const metadata = await readFile(metadataPath, 'utf8');
exportStr += `\nexport const metadata = ${metadata};`;
Expand Down
5 changes: 3 additions & 2 deletions packages/docusaurus-mdx-loader/src/remark/rightToc/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,13 @@ function toValue(node) {
default:
}
}

return toString(node);
}

// Visit all headings. We `slug` all headings (to account for
// duplicates), but only take h2 and h3 headings.
const search = node => {
function search(node) {
const headings = [];
let current = -1;
let currentDepth = 0;
Expand Down Expand Up @@ -65,6 +66,6 @@ const search = node => {
visit(node, 'heading', onHeading);

return headings;
};
}

module.exports = search;
5 changes: 4 additions & 1 deletion packages/docusaurus-plugin-content-blog/src/blogUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function truncate(fileString: string, truncateMarker: RegExp) {
}

// YYYY-MM-DD-{name}.mdx?
// prefer named capture, but old Node version does not support.
// Prefer named capture, but older Node versions do not support it.
const FILENAME_PATTERN = /^(\d{4}-\d{1,2}-\d{1,2})-?(.*?).mdx?$/;

function toUrl({date, link}: DateLink) {
Expand Down Expand Up @@ -111,15 +111,18 @@ export async function generateBlogPosts(
// Extract date and title from filename.
const match = blogFileName.match(FILENAME_PATTERN);
let linkName = blogFileName.replace(/\.mdx?$/, '');

if (match) {
const [, dateString, name] = match;
date = new Date(dateString);
linkName = name;
}

// Prefer user-defined date.
if (frontMatter.date) {
date = new Date(frontMatter.date);
}

// Use file create time for blog.
date = date || (await fs.stat(source)).birthtime;
frontMatter.title = frontMatter.title || linkName;
Expand Down
14 changes: 9 additions & 5 deletions packages/docusaurus-plugin-content-blog/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const DEFAULT_OPTIONS: PluginOptions = {
blogTagsPostsComponent: '@theme/BlogTagsPostsPage',
remarkPlugins: [],
rehypePlugins: [],
truncateMarker: /<!--\s*(truncate)\s*-->/, // Regex
truncateMarker: /<!--\s*(truncate)\s*-->/, // Regex.
};

function assertFeedTypes(val: any): asserts val is FeedType {
Expand Down Expand Up @@ -94,7 +94,7 @@ export default function pluginContentBlog(
return null;
}

// Colocate next and prev metadata
// Colocate next and prev metadata.
blogPosts.forEach((blogPost, index) => {
const prevItem = index > 0 ? blogPosts[index - 1] : null;
if (prevItem) {
Expand All @@ -103,6 +103,7 @@ export default function pluginContentBlog(
permalink: prevItem.metadata.permalink,
};
}

const nextItem =
index < blogPosts.length - 1 ? blogPosts[index + 1] : null;
if (nextItem) {
Expand Down Expand Up @@ -168,7 +169,8 @@ export default function pluginContentBlog(
const permalink = normalizeUrl([tagsPath, normalizedTag]);
if (!blogTags[normalizedTag]) {
blogTags[normalizedTag] = {
name: tag.toLowerCase(), // Will only use the name of the first occurrence of the tag.
// Will only use the name of the first occurrence of the tag.
name: tag.toLowerCase(),
items: [],
permalink,
};
Expand Down Expand Up @@ -232,7 +234,8 @@ export default function pluginContentBlog(
blogPosts.map(async blogPost => {
const {id, metadata} = blogPost;
await createData(
// Note that this created data path must be in sync with metadataPath provided to mdx-loader
// Note that this created data path must be in sync with
// metadataPath provided to mdx-loader.
`${docuHash(metadata.source)}.json`,
JSON.stringify(metadata, null, 2),
);
Expand Down Expand Up @@ -374,7 +377,8 @@ export default function pluginContentBlog(
options: {
remarkPlugins,
rehypePlugins,
// Note that metadataPath must be the same/ in-sync as the path from createData for each MDX
// Note that metadataPath must be the same/in-sync as
// the path from createData for each MDX.
metadataPath: (mdxPath: string) => {
const aliasedSource = aliasedSitePath(mdxPath, siteDir);
return path.join(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ export = function(fileString: string) {

let finalContent = fileString;

// Truncate content if requested (e.g: file.md?truncated=true)
// Truncate content if requested (e.g: file.md?truncated=true).
const {truncated} = this.resourceQuery && parseQuery(this.resourceQuery);
if (truncated) {
finalContent = truncate(fileString, truncateMarker);
}

return callback && callback(null, finalContent);
} as loader.Loader;
34 changes: 20 additions & 14 deletions packages/docusaurus-plugin-content-docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export default function pluginContentDocs(
'docusaurus-plugin-content-docs',
);

// Versioning
// Versioning.
const env = loadEnv(siteDir);
const {versioning} = env;
const {
Expand Down Expand Up @@ -128,7 +128,7 @@ export default function pluginContentDocs(
const docsMetadataRaw: DocsMetadataRaw = {};
const docsPromises = [];

// Metadata for default/ master docs files.
// Metadata for default/master docs files.
const docsFiles = await globby(include, {
cwd: docsDir,
});
Expand All @@ -147,7 +147,7 @@ export default function pluginContentDocs(
),
);

// Metadata for versioned docs
// Metadata for versioned docs.
if (versioning.enabled) {
const versionedGlob = _.flatten(
include.map(pattern =>
Expand All @@ -173,7 +173,7 @@ export default function pluginContentDocs(
);
}

// Load the sidebars & create docs ordering
// Load the sidebars and create docs ordering.
const sidebarPaths = [
sidebarPath,
...versionsNames.map(
Expand All @@ -185,7 +185,7 @@ export default function pluginContentDocs(

await Promise.all(docsPromises);

// Construct inter-metadata relationship in docsMetadata
// Construct inter-metadata relationship in docsMetadata.
const docsMetadata: DocsMetadata = {};
const permalinkToSidebar: PermalinkToSidebar = {};
const versionToSidebars: VersionToSidebars = {};
Expand All @@ -211,7 +211,7 @@ export default function pluginContentDocs(
next,
};

// sourceToPermalink and permalinkToSidebar mapping
// sourceToPermalink and permalinkToSidebar mapping.
const {source, permalink, version} = docsMetadataRaw[currentID];
sourceToPermalink[source] = permalink;
if (sidebar) {
Expand Down Expand Up @@ -255,8 +255,9 @@ export default function pluginContentDocs(
}
};

// 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
// 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.
const docsSidebars: DocsSidebar = Object.entries(loadedSidebars).reduce(
(acc: DocsSidebar, [sidebarId, sidebarItems]) => {
acc[sidebarId] = sidebarItems.map(normalizeItem);
Expand Down Expand Up @@ -290,10 +291,12 @@ export default function pluginContentDocs(
const routes = await Promise.all(
metadataItems.map(async metadataItem => {
await createData(
// Note that this created data path must be in sync with metadataPath provided to mdx-loader
// Note that this created data path must be in sync with
// metadataPath provided to mdx-loader.
`${docuHash(metadataItem.source)}.json`,
JSON.stringify(metadataItem, null, 2),
);

return {
path: metadataItem.permalink,
component: docItemComponent,
Expand All @@ -304,6 +307,7 @@ export default function pluginContentDocs(
};
}),
);

return routes.sort((a, b) =>
a.path > b.path ? 1 : b.path > a.path ? -1 : 0,
);
Expand Down Expand Up @@ -331,8 +335,8 @@ export default function pluginContentDocs(
});
};

// If versioning is enabled, we cleverly chunk the generated routes to be by version
// and pick only needed base metadata
// If versioning is enabled, we cleverly chunk the generated routes
// to be by version and pick only needed base metadata.
if (versioning.enabled) {
const docsMetadataByVersion = _.groupBy(
Object.values(content.docsMetadata),
Expand Down Expand Up @@ -365,8 +369,9 @@ export default function pluginContentDocs(
version,
};

// We want latest version route config to be placed last in the generated routeconfig.
// Otherwise, `/docs/next/foo` will match `/docs/:route` instead of `/docs/next/:route`
// We want latest version route config to be placed last in the
// generated routeconfig. Otherwise, `/docs/next/foo` will match
// `/docs/:route` instead of `/docs/next/:route`.
return addBaseRoute(
docsBaseRoute,
docsBaseMetadata,
Expand Down Expand Up @@ -410,7 +415,8 @@ export default function pluginContentDocs(
remarkPlugins,
rehypePlugins,
metadataPath: (mdxPath: string) => {
// Note that metadataPath must be the same/ in-sync as the path from createData for each MDX
// Note that metadataPath must be the same/in-sync as
// the path from createData for each MDX.
const aliasedSource = aliasedSitePath(mdxPath, siteDir);
return path.join(
dataDir,
Expand Down
3 changes: 2 additions & 1 deletion packages/docusaurus-plugin-content-docs/src/lastUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export default async function getFileLastUpdate(
: {timestamp: +temp[1], author: temp[2]};
}

// Wrap in try/catch in case the shell commands fail (e.g. project doesn't use Git, etc).
// Wrap in try/catch in case the shell commands fail
// (e.g. project doesn't use Git, etc).
try {
if (!shell.which('git')) {
if (!showedGitRequirementError) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export default function(
}
return modifiedLine;
});

content = lines.join('\n');
}

Expand Down
13 changes: 8 additions & 5 deletions packages/docusaurus-plugin-content-docs/src/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async function lastUpdated(
): Promise<LastUpdateData> {
const {showLastUpdateAuthor, showLastUpdateTime} = options;
if (showLastUpdateAuthor || showLastUpdateTime) {
// Use fake data in dev for faster development
// Use fake data in dev for faster development.
const fileLastUpdateData =
process.env.NODE_ENV === 'production'
? await lastUpdate(filePath)
Expand All @@ -49,6 +49,7 @@ async function lastUpdated(
};
}
}

return {};
}

Expand Down Expand Up @@ -83,7 +84,7 @@ export default async function processMetadata({
}
}

// The version portion of the url path. Eg: 'next', '1.0.0', and ''
// The version portion of the url path. Eg: 'next', '1.0.0', and ''.
const versionPath =
version && version !== versioning.latestVersion ? version : '';

Expand Down Expand Up @@ -112,7 +113,7 @@ export default async function processMetadata({

const description: string = frontMatter.description || excerpt;

// The last portion of the url path. Eg: 'foo/bar', 'bar'
// The last portion of the url path. Eg: 'foo/bar', 'bar'.
const routePath =
version && version !== 'next'
? id.replace(new RegExp(`^version-${version}/`), '')
Expand All @@ -126,8 +127,10 @@ export default async function processMetadata({

const {lastUpdatedAt, lastUpdatedBy} = await lastUpdatedPromise;

// Assign all of object properties during instantiation (if possible) for NodeJS optimization
// Adding properties to object after instantiation will cause hidden class transitions.
// Assign all of object properties during instantiation (if possible) for
// NodeJS optimization.
// Adding properties to object after instantiation will cause hidden
// class transitions.
const metadata: MetadataRaw = {
id,
title,
Expand Down
Loading

0 comments on commit 996b115

Please sign in to comment.