chore(v2): fix code style (revert previous changes)

This commit is contained in:
Alexey Pyltsyn 2020-04-05 17:38:12 +03:00
parent 1480a7eb80
commit 1f00d15c74
143 changed files with 457 additions and 458 deletions

View file

@ -15,12 +15,12 @@ function getOutputCss(output) {
global.testStylelintRule = (config, tests) => { global.testStylelintRule = (config, tests) => {
describe(tests.ruleName, () => { describe(tests.ruleName, () => {
const checkTestCaseContent = testCase => const checkTestCaseContent = (testCase) =>
testCase.description || testCase.code || 'no description'; testCase.description || testCase.code || 'no description';
if (tests.accept && tests.accept.length) { if (tests.accept && tests.accept.length) {
describe('accept cases', () => { describe('accept cases', () => {
tests.accept.forEach(testCase => { tests.accept.forEach((testCase) => {
const spec = testCase.only ? it.only : it; const spec = testCase.only ? it.only : it;
spec(checkTestCaseContent(testCase), () => { spec(checkTestCaseContent(testCase), () => {
@ -30,7 +30,7 @@ global.testStylelintRule = (config, tests) => {
syntax: tests.syntax, syntax: tests.syntax,
}; };
return stylelint.lint(options).then(output => { return stylelint.lint(options).then((output) => {
expect(output.results[0].warnings).toEqual([]); expect(output.results[0].warnings).toEqual([]);
if (!tests.fix) { if (!tests.fix) {
@ -40,8 +40,8 @@ global.testStylelintRule = (config, tests) => {
// Check the fix. // Check the fix.
return stylelint return stylelint
.lint({...options, fix: true}) .lint({...options, fix: true})
.then(fixedOutput => getOutputCss(fixedOutput)) .then((fixedOutput) => getOutputCss(fixedOutput))
.then(fixedCode => expect(fixedCode).toBe(testCase.fixed)); .then((fixedCode) => expect(fixedCode).toBe(testCase.fixed));
}); });
}); });
}); });
@ -50,7 +50,7 @@ global.testStylelintRule = (config, tests) => {
if (tests.reject && tests.reject.length) { if (tests.reject && tests.reject.length) {
describe('reject cases', () => { describe('reject cases', () => {
tests.reject.forEach(testCase => { tests.reject.forEach((testCase) => {
const skip = testCase.skip ? it.skip : it; const skip = testCase.skip ? it.skip : it;
const spec = testCase.only ? it.only : skip; const spec = testCase.only ? it.only : skip;
@ -61,7 +61,7 @@ global.testStylelintRule = (config, tests) => {
syntax: tests.syntax, syntax: tests.syntax,
}; };
return stylelint.lint(options).then(output => { return stylelint.lint(options).then((output) => {
const {warnings} = output.results[0]; const {warnings} = output.results[0];
const warning = warnings[0]; const warning = warnings[0];
@ -93,8 +93,8 @@ global.testStylelintRule = (config, tests) => {
// Check the fix. // Check the fix.
return stylelint return stylelint
.lint({...options, fix: true}) .lint({...options, fix: true})
.then(fixedOutput => getOutputCss(fixedOutput)) .then((fixedOutput) => getOutputCss(fixedOutput))
.then(fixedCode => expect(fixedCode).toBe(testCase.fixed)); .then((fixedCode) => expect(fixedCode).toBe(testCase.fixed));
}); });
}); });
}); });

View file

@ -17,7 +17,7 @@ function Help(props) {
const {baseUrl, docsUrl} = siteConfig; const {baseUrl, docsUrl} = siteConfig;
const docsPart = `${docsUrl ? `${docsUrl}/` : ''}`; const docsPart = `${docsUrl ? `${docsUrl}/` : ''}`;
const langPart = `${language ? `${language}/` : ''}`; const langPart = `${language ? `${language}/` : ''}`;
const docUrl = doc => `${baseUrl}${docsPart}${langPart}${doc}`; const docUrl = (doc) => `${baseUrl}${docsPart}${langPart}${doc}`;
const supportLinks = [ const supportLinks = [
{ {

View file

@ -19,9 +19,9 @@ class HomeSplash extends React.Component {
const {baseUrl, docsUrl} = siteConfig; const {baseUrl, docsUrl} = siteConfig;
const docsPart = `${docsUrl ? `${docsUrl}/` : ''}`; const docsPart = `${docsUrl ? `${docsUrl}/` : ''}`;
const langPart = `${language ? `${language}/` : ''}`; const langPart = `${language ? `${language}/` : ''}`;
const docUrl = doc => `${baseUrl}${docsPart}${langPart}${doc}`; const docUrl = (doc) => `${baseUrl}${docsPart}${langPart}${doc}`;
const SplashContainer = props => ( const SplashContainer = (props) => (
<div className="homeContainer"> <div className="homeContainer">
<div className="homeSplashFade"> <div className="homeSplashFade">
<div className="wrapper homeWrapper">{props.children}</div> <div className="wrapper homeWrapper">{props.children}</div>
@ -29,20 +29,20 @@ class HomeSplash extends React.Component {
</div> </div>
); );
const Logo = props => ( const Logo = (props) => (
<div className="projectLogo"> <div className="projectLogo">
<img src={props.img_src} alt="Project Logo" /> <img src={props.img_src} alt="Project Logo" />
</div> </div>
); );
const ProjectTitle = props => ( const ProjectTitle = (props) => (
<h2 className="projectTitle"> <h2 className="projectTitle">
{props.title} {props.title}
<small>{props.tagline}</small> <small>{props.tagline}</small>
</h2> </h2>
); );
const PromoSection = props => ( const PromoSection = (props) => (
<div className="section promoSection"> <div className="section promoSection">
<div className="promoRow"> <div className="promoRow">
<div className="pluginRowBlock">{props.children}</div> <div className="pluginRowBlock">{props.children}</div>
@ -50,7 +50,7 @@ class HomeSplash extends React.Component {
</div> </div>
); );
const Button = props => ( const Button = (props) => (
<div className="pluginWrapper buttonWrapper"> <div className="pluginWrapper buttonWrapper">
<a className="button" href={props.href} target={props.target}> <a className="button" href={props.href} target={props.target}>
{props.children} {props.children}
@ -79,7 +79,7 @@ class Index extends React.Component {
const {config: siteConfig, language = ''} = this.props; const {config: siteConfig, language = ''} = this.props;
const {baseUrl} = siteConfig; const {baseUrl} = siteConfig;
const Block = props => ( const Block = (props) => (
<Container <Container
padding={['bottom', 'top']} padding={['bottom', 'top']}
id={props.id} id={props.id}
@ -170,14 +170,15 @@ class Index extends React.Component {
} }
const showcase = siteConfig.users const showcase = siteConfig.users
.filter(user => user.pinned) .filter((user) => user.pinned)
.map(user => ( .map((user) => (
<a href={user.infoLink} key={user.infoLink}> <a href={user.infoLink} key={user.infoLink}>
<img src={user.image} alt={user.caption} title={user.caption} /> <img src={user.image} alt={user.caption} title={user.caption} />
</a> </a>
)); ));
const pageUrl = page => baseUrl + (language ? `${language}/` : '') + page; const pageUrl = (page) =>
baseUrl + (language ? `${language}/` : '') + page;
return ( return (
<div className="productShowcaseSection paddingBottom"> <div className="productShowcaseSection paddingBottom">

View file

@ -18,7 +18,7 @@ class Users extends React.Component {
return null; return null;
} }
const showcase = siteConfig.users.map(user => ( const showcase = siteConfig.users.map((user) => (
<a href={user.infoLink} key={user.infoLink}> <a href={user.infoLink} key={user.infoLink}>
<img src={user.image} alt={user.caption} title={user.caption} /> <img src={user.image} alt={user.caption} title={user.caption} />
</a> </a>

View file

@ -79,7 +79,7 @@ function Versions(props) {
<table className="versions"> <table className="versions">
<tbody> <tbody>
{versions.map( {versions.map(
version => (version) =>
version !== latestVersion && ( version !== latestVersion && (
<tr key={version}> <tr key={version}>
<th>{version}</th> <th>{version}</th>

View file

@ -47,7 +47,7 @@ describe('Build files', () => {
glob(`${buildDir}/${siteConfig.projectName}/docs/**/*.html`), glob(`${buildDir}/${siteConfig.projectName}/docs/**/*.html`),
glob(`${docsDir}/assets/*`), glob(`${docsDir}/assets/*`),
glob(`${buildDir}/${siteConfig.projectName}/img/*`), glob(`${buildDir}/${siteConfig.projectName}/img/*`),
]).then(results => { ]).then((results) => {
[ [
inputMarkdownFiles, inputMarkdownFiles,
outputHTMLFiles, outputHTMLFiles,
@ -62,15 +62,15 @@ describe('Build files', () => {
}); });
test('Build folder exists', () => test('Build folder exists', () =>
fs.stat(buildDir).then(status => { fs.stat(buildDir).then((status) => {
expect(status.isDirectory()).toBeTruthy(); expect(status.isDirectory()).toBeTruthy();
})); }));
test('Generated HTML for each Markdown resource', () => { test('Generated HTML for each Markdown resource', () => {
const metadata = outputHTMLFiles.map(file => const metadata = outputHTMLFiles.map((file) =>
filepath.create(file).basename(), filepath.create(file).basename(),
); );
inputMarkdownFiles.forEach(file => { inputMarkdownFiles.forEach((file) => {
const data = fs.readFileSync(file, 'utf8'); const data = fs.readFileSync(file, 'utf8');
const frontmatter = fm(data); const frontmatter = fm(data);
expect(metadata).toContain(`${frontmatter.attributes.id}.html`); expect(metadata).toContain(`${frontmatter.attributes.id}.html`);
@ -78,17 +78,17 @@ describe('Build files', () => {
}); });
test('Generated table of contents', () => { test('Generated table of contents', () => {
outputHTMLFiles.forEach(file => { outputHTMLFiles.forEach((file) => {
const fileContents = fs.readFileSync(file, 'utf8'); const fileContents = fs.readFileSync(file, 'utf8');
expect(fileContents).not.toContain('<AUTOGENERATED_TABLE_OF_CONTENTS>'); expect(fileContents).not.toContain('<AUTOGENERATED_TABLE_OF_CONTENTS>');
}); });
}); });
test('Copied assets from /docs/assets', () => { test('Copied assets from /docs/assets', () => {
const metadata = outputAssetsFiles.map(file => const metadata = outputAssetsFiles.map((file) =>
filepath.create(file).basename(), filepath.create(file).basename(),
); );
inputAssetsFiles.forEach(file => { inputAssetsFiles.forEach((file) => {
const path = filepath.create(file); const path = filepath.create(file);
expect(metadata).toContain(path.basename()); expect(metadata).toContain(path.basename());
}); });

View file

@ -42,7 +42,7 @@ generate()
.then(() => { .then(() => {
console.log("Site built successfully. Generated files in 'build' folder."); console.log("Site built successfully. Generated files in 'build' folder.");
}) })
.catch(error => { .catch((error) => {
console.error(error); console.error(error);
process.exit(1); process.exit(1);
}); });

View file

@ -15,7 +15,7 @@ const path = require('path');
const CWD = process.cwd(); const CWD = process.cwd();
const toHex = color => { const toHex = (color) => {
const hex = color.toString(16); const hex = color.toString(16);
return hex.length === 1 ? `0${hex}` : hex; return hex.length === 1 ? `0${hex}` : hex;
}; };
@ -37,7 +37,7 @@ let feature;
commander commander
.arguments('[feature]') .arguments('[feature]')
.action(feat => { .action((feat) => {
feature = feat; feature = feat;
}) })
.parse(process.argv); .parse(process.argv);
@ -85,7 +85,7 @@ if (feature === 'translations') {
fs.copySync(`${folder}/crowdin.yaml`, `${CWD}/../crowdin.yaml`); fs.copySync(`${folder}/crowdin.yaml`, `${CWD}/../crowdin.yaml`);
} }
const files = glob.sync(`${folder}/**/*`); const files = glob.sync(`${folder}/**/*`);
files.forEach(file => { files.forEach((file) => {
if (fs.lstatSync(file).isDirectory()) { if (fs.lstatSync(file).isDirectory()) {
return; return;
} }
@ -112,7 +112,7 @@ if (feature === 'translations') {
// copy files for versions // copy files for versions
const folder = path.join(__dirname, '..', 'examples', 'versions'); const folder = path.join(__dirname, '..', 'examples', 'versions');
const files = glob.sync(`${folder}/**/*`); const files = glob.sync(`${folder}/**/*`);
files.forEach(file => { files.forEach((file) => {
if (fs.lstatSync(file).isDirectory()) { if (fs.lstatSync(file).isDirectory()) {
return; return;
} }
@ -189,7 +189,7 @@ if (feature === 'translations') {
// copy other files // copy other files
const files = glob.sync(`${folder}/**/*`); const files = glob.sync(`${folder}/**/*`);
const {primaryColor, secondaryColor} = colorScheme(); const {primaryColor, secondaryColor} = colorScheme();
files.forEach(file => { files.forEach((file) => {
if (fs.lstatSync(file).isDirectory()) { if (fs.lstatSync(file).isDirectory()) {
return; return;
} }
@ -235,7 +235,7 @@ if (feature === 'translations') {
}); });
const svgs = glob.sync(`${CWD}/static/img/**/*.svg`); const svgs = glob.sync(`${CWD}/static/img/**/*.svg`);
svgs.forEach(file => { svgs.forEach((file) => {
// Replace primary colors of SVGs. // Replace primary colors of SVGs.
const newImage = fs const newImage = fs
.readFileSync(file, 'utf8') .readFileSync(file, 'utf8')

View file

@ -14,7 +14,7 @@ const MetadataBlog = require('./MetadataBlog.js');
const MetadataPublicBlog = const MetadataPublicBlog =
process.env.NODE_ENV === 'development' process.env.NODE_ENV === 'development'
? MetadataBlog ? MetadataBlog
: MetadataBlog.filter(item => !item.unlisted); : MetadataBlog.filter((item) => !item.unlisted);
const Site = require('./Site.js'); const Site = require('./Site.js');
const utils = require('./utils.js'); const utils = require('./utils.js');
@ -48,7 +48,7 @@ class BlogPageLayout extends React.Component {
{MetadataPublicBlog.slice( {MetadataPublicBlog.slice(
page * perPage, page * perPage,
(page + 1) * perPage, (page + 1) * perPage,
).map(post => ( ).map((post) => (
<BlogPost <BlogPost
post={post} post={post}
content={post.content} content={post.content}

View file

@ -38,8 +38,9 @@ class BlogPostLayout extends React.Component {
{/* Facebook SDK require 'fb-comments' class */} {/* Facebook SDK require 'fb-comments' class */}
<div <div
className="fb-comments" className="fb-comments"
data-href={`${this.props.config.url + data-href={`${
this.props.config.baseUrl}blog/${post.path}`} this.props.config.url + this.props.config.baseUrl
}blog/${post.path}`}
data-width="100%" data-width="100%"
data-numposts="5" data-numposts="5"
data-order-by="time" data-order-by="time"
@ -52,8 +53,9 @@ class BlogPostLayout extends React.Component {
{/* Facebook SDK require 'fb-like' class */} {/* Facebook SDK require 'fb-like' class */}
<div <div
className="fb-like" className="fb-like"
data-href={`${this.props.config.url + data-href={`${
this.props.config.baseUrl}blog/${post.path}`} this.props.config.url + this.props.config.baseUrl
}blog/${post.path}`}
data-layout="standard" data-layout="standard"
data-share="true" data-share="true"
data-width="225" data-width="225"

View file

@ -13,7 +13,7 @@ const MetadataBlog = require('./MetadataBlog.js');
const MetadataPublicBlog = const MetadataPublicBlog =
process.env.NODE_ENV === 'development' process.env.NODE_ENV === 'development'
? MetadataBlog ? MetadataBlog
: MetadataBlog.filter(item => !item.unlisted); : MetadataBlog.filter((item) => !item.unlisted);
class BlogSidebar extends React.Component { class BlogSidebar extends React.Component {
render() { render() {
@ -33,7 +33,7 @@ class BlogSidebar extends React.Component {
{ {
type: 'CATEGORY', type: 'CATEGORY',
title: blogSidebarTitle, title: blogSidebarTitle,
children: MetadataPublicBlog.slice(0, blogSidebarCount).map(item => ({ children: MetadataPublicBlog.slice(0, blogSidebarCount).map((item) => ({
type: 'LINK', type: 'LINK',
item, item,
})), })),

View file

@ -27,7 +27,7 @@ const splitTabsToTitleAndContent = (lines, indents) => {
let current = { let current = {
content: [], content: [],
}; };
lines.forEach(line => { lines.forEach((line) => {
if (indents) { if (indents) {
line = line.replace(new RegExp(`^((\\t|\\s{4}){${indents}})`, 'g'), ''); line = line.replace(new RegExp(`^((\\t|\\s{4}){${indents}})`, 'g'), '');
} }
@ -135,7 +135,7 @@ const cleanTheCodeTag = (content, indents) => {
}; };
const contents = content.split(/(<pre>)(.*?)(<\/pre>)/gms); const contents = content.split(/(<pre>)(.*?)(<\/pre>)/gms);
let inCodeBlock = false; let inCodeBlock = false;
const cleanContents = contents.map(c => { const cleanContents = contents.map((c) => {
if (c === '<pre>') { if (c === '<pre>') {
inCodeBlock = true; inCodeBlock = true;
return c; return c;
@ -159,8 +159,8 @@ class Doc extends React.Component {
let indents = 0; let indents = 0;
return content.replace( return content.replace(
/(\t|\s{4})*?(<!--DOCUSAURUS_CODE_TABS-->\n)(.*?)((\n|\t|\s{4})<!--END_DOCUSAURUS_CODE_TABS-->)/gms, /(\t|\s{4})*?(<!--DOCUSAURUS_CODE_TABS-->\n)(.*?)((\n|\t|\s{4})<!--END_DOCUSAURUS_CODE_TABS-->)/gms,
m => { (m) => {
const contents = m.split('\n').filter(c => { const contents = m.split('\n').filter((c) => {
if (!indents) { if (!indents) {
indents = ( indents = (
c.match(/((\t|\s{4})+)<!--DOCUSAURUS_CODE_TABS-->/) || [] c.match(/((\t|\s{4})+)<!--DOCUSAURUS_CODE_TABS-->/) || []

View file

@ -11,7 +11,7 @@ const React = require('react');
class Head extends React.Component { class Head extends React.Component {
render() { render() {
const links = this.props.config.headerLinks; const links = this.props.config.headerLinks;
const hasBlog = links.some(link => link.blog); const hasBlog = links.some((link) => link.blog);
const highlight = { const highlight = {
version: '9.12.0', version: '9.12.0',
@ -130,7 +130,7 @@ class Head extends React.Component {
{/* External resources */} {/* External resources */}
{this.props.config.stylesheets && {this.props.config.stylesheets &&
this.props.config.stylesheets.map(source => this.props.config.stylesheets.map((source) =>
source.href ? ( source.href ? (
<link rel="stylesheet" key={source.href} {...source} /> <link rel="stylesheet" key={source.href} {...source} />
) : ( ) : (
@ -138,7 +138,7 @@ class Head extends React.Component {
), ),
)} )}
{this.props.config.scripts && {this.props.config.scripts &&
this.props.config.scripts.map(source => this.props.config.scripts.map((source) =>
source.src ? ( source.src ? (
<script type="text/javascript" key={source.src} {...source} /> <script type="text/javascript" key={source.src} {...source} />
) : ( ) : (

View file

@ -20,7 +20,7 @@ class Remarkable extends React.Component {
); );
} }
return React.Children.map(this.props.children, child => { return React.Children.map(this.props.children, (child) => {
if (typeof child === 'string') { if (typeof child === 'string') {
return ( return (
<span dangerouslySetInnerHTML={{__html: renderMarkdown(child)}} /> <span dangerouslySetInnerHTML={{__html: renderMarkdown(child)}} />

View file

@ -26,7 +26,7 @@ class Site extends React.Component {
const hasLanguageDropdown = const hasLanguageDropdown =
env.translation.enabled && env.translation.enabledLanguages().length > 1; env.translation.enabled && env.translation.enabledLanguages().length > 1;
const hasOrdinaryHeaderLinks = headerLinks.some( const hasOrdinaryHeaderLinks = headerLinks.some(
link => !(link.languages || link.search), (link) => !(link.languages || link.search),
); );
return !(hasLanguageDropdown || hasOrdinaryHeaderLinks); return !(hasLanguageDropdown || hasOrdinaryHeaderLinks);
} }

View file

@ -49,7 +49,7 @@ describe('utils', () => {
expect(utils.getPath(null, false)).toBeNull(); expect(utils.getPath(null, false)).toBeNull();
// transform to pretty/clean path // transform to pretty/clean path
const cleanPath = pathStr => utils.getPath(pathStr, true); const cleanPath = (pathStr) => utils.getPath(pathStr, true);
expect(cleanPath('/en/users')).toBe('/en/users'); expect(cleanPath('/en/users')).toBe('/en/users');
expect(cleanPath('/docs/versioning.html')).toBe('/docs/versioning'); expect(cleanPath('/docs/versioning.html')).toBe('/docs/versioning');
expect(cleanPath('/en/users.html')).toBe('/en/users'); expect(cleanPath('/en/users.html')).toBe('/en/users');
@ -168,7 +168,7 @@ describe('utils', () => {
}); });
expect(utils.idx(env, ['translation', 'enabled'])).toEqual(true); expect(utils.idx(env, ['translation', 'enabled'])).toEqual(true);
expect( expect(
utils.idx(env, ['translation', variable]).map(lang => lang.tag), utils.idx(env, ['translation', variable]).map((lang) => lang.tag),
).toEqual(['en', 'ja']); ).toEqual(['en', 'ja']);
expect(utils.idx(undefined)).toBeUndefined(); expect(utils.idx(undefined)).toBeUndefined();
expect(utils.idx(null)).toBeNull(); expect(utils.idx(null)).toBeNull();

View file

@ -14,7 +14,7 @@ const toSlug = require('./toSlug');
function anchors(md) { function anchors(md) {
const originalRender = md.renderer.rules.heading_open; const originalRender = md.renderer.rules.heading_open;
md.renderer.rules.heading_open = function(tokens, idx, options, env) { md.renderer.rules.heading_open = function (tokens, idx, options, env) {
if (!env.slugger) { if (!env.slugger) {
env.slugger = new GithubSlugger(); env.slugger = new GithubSlugger();
} }

View file

@ -39,8 +39,8 @@ class LanguageDropDown extends React.Component {
// add all enabled languages to dropdown // add all enabled languages to dropdown
const enabledLanguages = env.translation const enabledLanguages = env.translation
.enabledLanguages() .enabledLanguages()
.filter(lang => lang.tag !== this.props.language) .filter((lang) => lang.tag !== this.props.language)
.map(lang => { .map((lang) => {
// build the href so that we try to stay in current url but change the language. // build the href so that we try to stay in current url but change the language.
let href = siteConfig.baseUrl + lang.tag; let href = siteConfig.baseUrl + lang.tag;
if ( if (
@ -71,8 +71,8 @@ class LanguageDropDown extends React.Component {
// Get the current language full name for display in the header nav // Get the current language full name for display in the header nav
const currentLanguage = env.translation const currentLanguage = env.translation
.enabledLanguages() .enabledLanguages()
.filter(lang => lang.tag === this.props.language) .filter((lang) => lang.tag === this.props.language)
.map(lang => lang.name); .map((lang) => lang.name);
// add Crowdin project recruiting link // add Crowdin project recruiting link
if (siteConfig.translationRecruitingLink) { if (siteConfig.translationRecruitingLink) {
@ -179,10 +179,10 @@ class HeaderNav extends React.Component {
errorStr += errorStr +=
' It looks like there is no document with that id that exists in your docs directory. Please double check the spelling of your `doc` field and the `id` fields of your docs.'; ' It looks like there is no document with that id that exists in your docs directory. Please double check the spelling of your `doc` field and the `id` fields of your docs.';
} else { } else {
errorStr += `${'. Check the spelling of your `doc` field. If that seems sane, and a document in your docs folder exists with that `id` value, \nthen this is likely a bug in Docusaurus.' + errorStr += `${
' Docusaurus thinks one or both of translations (currently set to: '}${ '. Check the spelling of your `doc` field. If that seems sane, and a document in your docs folder exists with that `id` value, \nthen this is likely a bug in Docusaurus.' +
env.translation.enabled ' Docusaurus thinks one or both of translations (currently set to: '
}) or versioning (currently set to: ${ }${env.translation.enabled}) or versioning (currently set to: ${
env.versioning.enabled env.versioning.enabled
}) is enabled when maybe they should not be. \nThus my internal id for this doc is: '${id}'. Please file an issue for this possible bug on GitHub.`; }) is enabled when maybe they should not be. \nThus my internal id for this doc is: '${id}'. Please file an issue for this possible bug on GitHub.`;
} }
@ -236,7 +236,7 @@ class HeaderNav extends React.Component {
const headerLinks = this.props.config.headerLinks; const headerLinks = this.props.config.headerLinks;
// add language drop down to end if location not specified // add language drop down to end if location not specified
let languages = false; let languages = false;
headerLinks.forEach(link => { headerLinks.forEach((link) => {
if (link.languages) { if (link.languages) {
languages = true; languages = true;
} }
@ -245,7 +245,7 @@ class HeaderNav extends React.Component {
headerLinks.push({languages: true}); headerLinks.push({languages: true});
} }
let search = false; let search = false;
headerLinks.forEach(link => { headerLinks.forEach((link) => {
if ( if (
link.doc && link.doc &&
!fs.existsSync(`${CWD}/../${readMetadata.getDocsPath()}/`) !fs.existsSync(`${CWD}/../${readMetadata.getDocsPath()}/`)

View file

@ -23,7 +23,7 @@ const Headings = ({headings}) => {
if (!headings.length) return null; if (!headings.length) return null;
return ( return (
<ul className="toc-headings"> <ul className="toc-headings">
{headings.map(heading => ( {headings.map((heading) => (
<li key={heading.hashLink}> <li key={heading.hashLink}>
<Link hashLink={heading.hashLink} content={heading.content} /> <Link hashLink={heading.hashLink} content={heading.content} />
<Headings headings={heading.children} /> <Headings headings={heading.children} />

View file

@ -61,7 +61,7 @@ class SideNav extends React.Component {
return null; return null;
} }
renderCategory = categoryItem => { renderCategory = (categoryItem) => {
let ulClassName = ''; let ulClassName = '';
let categoryClassName = 'navGroupCategoryTitle'; let categoryClassName = 'navGroupCategoryTitle';
let arrow; let arrow;
@ -89,7 +89,7 @@ class SideNav extends React.Component {
{arrow} {arrow}
</h3> </h3>
<ul className={ulClassName}> <ul className={ulClassName}>
{categoryItem.children.map(item => { {categoryItem.children.map((item) => {
switch (item.type) { switch (item.type) {
case 'LINK': case 'LINK':
return this.renderItemLink(item); return this.renderItemLink(item);
@ -104,7 +104,7 @@ class SideNav extends React.Component {
); );
}; };
renderSubcategory = subcategoryItem => ( renderSubcategory = (subcategoryItem) => (
<div className="navGroup subNavGroup" key={subcategoryItem.title}> <div className="navGroup subNavGroup" key={subcategoryItem.title}>
<h4 className="navGroupSubcategoryTitle"> <h4 className="navGroupSubcategoryTitle">
{this.getLocalizedCategoryString(subcategoryItem.title)} {this.getLocalizedCategoryString(subcategoryItem.title)}
@ -113,7 +113,7 @@ class SideNav extends React.Component {
</div> </div>
); );
renderItemLink = linkItem => { renderItemLink = (linkItem) => {
const linkMetadata = linkItem.item; const linkMetadata = linkItem.item;
const itemClasses = classNames('navListItem', { const itemClasses = classNames('navListItem', {
navListItemActive: linkMetadata.id === this.props.current.id, navListItemActive: linkMetadata.id === this.props.current.id,

View file

@ -109,7 +109,7 @@ class MarkdownRenderer {
// Allow client sites to register their own plugins // Allow client sites to register their own plugins
if (siteConfig.markdownPlugins) { if (siteConfig.markdownPlugins) {
siteConfig.markdownPlugins.forEach(plugin => { siteConfig.markdownPlugins.forEach((plugin) => {
md.use(plugin); md.use(plugin);
}); });
} }
@ -128,4 +128,4 @@ class MarkdownRenderer {
const renderMarkdown = new MarkdownRenderer(); const renderMarkdown = new MarkdownRenderer();
module.exports = source => renderMarkdown.toHtml(source); module.exports = (source) => renderMarkdown.toHtml(source);

View file

@ -20,7 +20,7 @@ const tocRegex = new RegExp('<AUTOGENERATED_TABLE_OF_CONTENTS>', 'i');
* *
*/ */
function getTOC(content, headingTags = 'h2', subHeadingTags = 'h3') { function getTOC(content, headingTags = 'h2', subHeadingTags = 'h3') {
const tagToLevel = tag => Number(tag.slice(1)); const tagToLevel = (tag) => Number(tag.slice(1));
const headingLevels = [].concat(headingTags).map(tagToLevel); const headingLevels = [].concat(headingTags).map(tagToLevel);
const subHeadingLevels = subHeadingTags const subHeadingLevels = subHeadingTags
? [].concat(subHeadingTags).map(tagToLevel) ? [].concat(subHeadingTags).map(tagToLevel)
@ -35,7 +35,7 @@ function getTOC(content, headingTags = 'h2', subHeadingTags = 'h3') {
const slugger = new GithubSlugger(); const slugger = new GithubSlugger();
let current; let current;
headings.forEach(heading => { headings.forEach((heading) => {
const rawContent = heading.content; const rawContent = heading.content;
const rendered = md.renderInline(rawContent); const rendered = md.renderInline(rawContent);
@ -68,8 +68,8 @@ function insertTOC(rawContent) {
const filterRe = /^`[^`]*`/; const filterRe = /^`[^`]*`/;
const headers = getTOC(rawContent, 'h3', null); const headers = getTOC(rawContent, 'h3', null);
const tableOfContents = headers const tableOfContents = headers
.filter(header => filterRe.test(header.rawContent)) .filter((header) => filterRe.test(header.rawContent))
.map(header => ` - [${header.rawContent}](#${header.hashLink})`) .map((header) => ` - [${header.rawContent}](#${header.hashLink})`)
.join('\n'); .join('\n');
return rawContent.replace(tocRegex, tableOfContents); return rawContent.replace(tocRegex, tableOfContents);
} }

View file

@ -154,7 +154,7 @@ const excludePath = `${PROJECT_NAME}-${DEPLOYMENT_BRANCH}`;
fs.copy( fs.copy(
fromPath, fromPath,
toPath, toPath,
src => { (src) => {
if (src.indexOf('.DS_Store') !== -1) { if (src.indexOf('.DS_Store') !== -1) {
return false; return false;
} }
@ -164,7 +164,7 @@ fs.copy(
return true; return true;
}, },
error => { (error) => {
if (error) { if (error) {
shell.echo(`Error: Copying build assets failed with error '${error}'`); shell.echo(`Error: Copying build assets failed with error '${error}'`);
shell.exit(1); shell.exit(1);

View file

@ -21,7 +21,7 @@ const CWD = process.cwd();
// generate a doc header from metadata // generate a doc header from metadata
function makeHeader(metadata) { function makeHeader(metadata) {
let header = '---\n'; let header = '---\n';
Object.keys(metadata).forEach(key => { Object.keys(metadata).forEach((key) => {
header += `${key}: ${metadata[key]}\n`; header += `${key}: ${metadata[key]}\n`;
}); });
header += '---\n'; header += '---\n';
@ -91,7 +91,7 @@ if (fs.existsSync(`${CWD}/versioned_docs/version-${currentVersion}`)) {
); );
const files = glob.sync(`${CWD}/versioned_docs/version-${newVersion}/*`); const files = glob.sync(`${CWD}/versioned_docs/version-${newVersion}/*`);
files.forEach(file => { files.forEach((file) => {
const extension = path.extname(file); const extension = path.extname(file);
if (extension !== '.md' && extension !== '.markdown') { if (extension !== '.md' && extension !== '.markdown') {
return; return;

View file

@ -145,7 +145,7 @@ describe('getFile', () => {
'docs/doc1.md': 'Just another document', 'docs/doc1.md': 'Just another document',
}; };
fs.existsSync = jest.fn().mockReturnValue(true); fs.existsSync = jest.fn().mockReturnValue(true);
fs.readFileSync = jest.fn().mockImplementation(file => { fs.readFileSync = jest.fn().mockImplementation((file) => {
const fakePath = file.replace( const fakePath = file.replace(
process.cwd().replace(/website-1.x\/?$/, ''), process.cwd().replace(/website-1.x\/?$/, ''),
'', '',

View file

@ -21,7 +21,7 @@ module.exports = function loadConfig(configPath, deleteCache = true) {
customDocsPath: 'docs', customDocsPath: 'docs',
docsUrl: 'docs', docsUrl: 'docs',
}; };
Object.keys(defaultConfig).forEach(field => { Object.keys(defaultConfig).forEach((field) => {
if (!(field in config)) { if (!(field in config)) {
config[field] = defaultConfig[field]; config[field] = defaultConfig[field];
} }

View file

@ -54,7 +54,7 @@ function mdToHtmlify(oldContent, mdToHtml, metadata, siteConfig) {
let content = oldContent; let content = oldContent;
/* Replace internal markdown linking (except in fenced blocks) */ /* Replace internal markdown linking (except in fenced blocks) */
let fencedBlock = false; let fencedBlock = false;
const lines = content.split('\n').map(line => { const lines = content.split('\n').map((line) => {
if (line.trim().startsWith('```')) { if (line.trim().startsWith('```')) {
fencedBlock = !fencedBlock; fencedBlock = !fencedBlock;
} }

View file

@ -32,7 +32,7 @@ class Translation {
this.load(); this.load();
} }
enabledLanguages = () => this.languages.filter(lang => lang.enabled); enabledLanguages = () => this.languages.filter((lang) => lang.enabled);
load() { load() {
if (fs.existsSync(languagesFile)) { if (fs.existsSync(languagesFile)) {

View file

@ -21,7 +21,7 @@ const utils = require('../core/utils');
const renderMarkdown = require('../core/renderMarkdown.js'); const renderMarkdown = require('../core/renderMarkdown.js');
module.exports = function(type) { module.exports = function (type) {
console.log('feed.js triggered...'); console.log('feed.js triggered...');
type = type || 'rss'; type = type || 'rss';
@ -31,7 +31,7 @@ module.exports = function(type) {
const MetadataPublicBlog = const MetadataPublicBlog =
process.env.NODE_ENV === 'development' process.env.NODE_ENV === 'development'
? MetadataBlog ? MetadataBlog
: MetadataBlog.filter(item => !item.unlisted); : MetadataBlog.filter((item) => !item.unlisted);
const feed = new Feed({ const feed = new Feed({
title: `${siteConfig.title} Blog`, title: `${siteConfig.title} Blog`,
@ -43,7 +43,7 @@ module.exports = function(type) {
updated: new Date(MetadataPublicBlog[0].date), updated: new Date(MetadataPublicBlog[0].date),
}); });
MetadataPublicBlog.forEach(post => { MetadataPublicBlog.forEach((post) => {
const url = `${blogRootURL}/${post.path}`; const url = `${blogRootURL}/${post.path}`;
const description = utils.blogPostHasTruncateMarker(post.content) const description = utils.blogPostHasTruncateMarker(post.content)
? renderMarkdown(utils.extractBlogPostBeforeTruncate(post.content)) ? renderMarkdown(utils.extractBlogPostBeforeTruncate(post.content))

View file

@ -72,7 +72,7 @@ async function execute() {
// create html files for all docs by going through all doc ids // create html files for all docs by going through all doc ids
const mdToHtml = metadataUtils.mdToHtml(Metadata, siteConfig); const mdToHtml = metadataUtils.mdToHtml(Metadata, siteConfig);
Object.keys(Metadata).forEach(id => { Object.keys(Metadata).forEach((id) => {
const metadata = Metadata[id]; const metadata = Metadata[id];
const file = docs.getFile(metadata); const file = docs.getFile(metadata);
if (!file) { if (!file) {
@ -118,7 +118,7 @@ async function execute() {
files files
.sort() .sort()
.reverse() .reverse()
.forEach(file => { .forEach((file) => {
// Why normalize? In case we are on Windows. // Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
const normalizedFile = path.normalize(file); const normalizedFile = path.normalize(file);
@ -137,7 +137,7 @@ async function execute() {
// create html files for all blog pages (collections of article previews) // create html files for all blog pages (collections of article previews)
const blogPages = blog.getPagesMarkup(MetadataBlog.length, siteConfig); const blogPages = blog.getPagesMarkup(MetadataBlog.length, siteConfig);
Object.keys(blogPages).forEach(pagePath => { Object.keys(blogPages).forEach((pagePath) => {
const targetFile = join(buildDir, 'blog', pagePath); const targetFile = join(buildDir, 'blog', pagePath);
writeFileAndCreateFolder(targetFile, blogPages[pagePath]); writeFileAndCreateFolder(targetFile, blogPages[pagePath]);
}); });
@ -168,7 +168,7 @@ async function execute() {
// copy all static files from docusaurus // copy all static files from docusaurus
const libStaticDir = join(__dirname, '..', 'static'); const libStaticDir = join(__dirname, '..', 'static');
files = glob.sync(join(libStaticDir, '**')); files = glob.sync(join(libStaticDir, '**'));
files.forEach(file => { files.forEach((file) => {
// Why normalize? In case we are on Windows. // Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
const targetFile = path.normalize(file).replace(libStaticDir, buildDir); const targetFile = path.normalize(file).replace(libStaticDir, buildDir);
@ -188,15 +188,15 @@ async function execute() {
); );
} }
Object.keys(siteConfig.colors).forEach(key => { Object.keys(siteConfig.colors).forEach((key) => {
const color = siteConfig.colors[key]; const color = siteConfig.colors[key];
cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color); cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color);
}); });
if (siteConfig.fonts) { if (siteConfig.fonts) {
Object.keys(siteConfig.fonts).forEach(key => { Object.keys(siteConfig.fonts).forEach((key) => {
const fontString = siteConfig.fonts[key] const fontString = siteConfig.fonts[key]
.map(font => `"${font}"`) .map((font) => `"${font}"`)
.join(', '); .join(', ');
cssContent = cssContent.replace( cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'), new RegExp(`\\$${key}`, 'g'),
@ -216,7 +216,7 @@ async function execute() {
// Copy all static files from user. // Copy all static files from user.
const userStaticDir = join(CWD, 'static'); const userStaticDir = join(CWD, 'static');
files = glob.sync(join(userStaticDir, '**'), {dot: true}); files = glob.sync(join(userStaticDir, '**'), {dot: true});
files.forEach(file => { files.forEach((file) => {
// Why normalize? In case we are on Windows. // Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
const normalizedFile = path.normalize(file); const normalizedFile = path.normalize(file);
@ -229,15 +229,15 @@ async function execute() {
let cssContent = fs.readFileSync(normalizedFile, 'utf8'); let cssContent = fs.readFileSync(normalizedFile, 'utf8');
cssContent = `${fs.readFileSync(mainCss, 'utf8')}\n${cssContent}`; cssContent = `${fs.readFileSync(mainCss, 'utf8')}\n${cssContent}`;
Object.keys(siteConfig.colors).forEach(key => { Object.keys(siteConfig.colors).forEach((key) => {
const color = siteConfig.colors[key]; const color = siteConfig.colors[key];
cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color); cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color);
}); });
if (siteConfig.fonts) { if (siteConfig.fonts) {
Object.keys(siteConfig.fonts).forEach(key => { Object.keys(siteConfig.fonts).forEach((key) => {
const fontString = siteConfig.fonts[key] const fontString = siteConfig.fonts[key]
.map(font => `"${font}"`) .map((font) => `"${font}"`)
.join(', '); .join(', ');
cssContent = cssContent.replace( cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'), new RegExp(`\\$${key}`, 'g'),
@ -264,7 +264,7 @@ async function execute() {
}), }),
imageminGifsicle(), imageminGifsicle(),
], ],
}).catch(error => { }).catch((error) => {
// if image compression fail, just copy it as it is // if image compression fail, just copy it as it is
console.error(error); console.error(error);
fs.copySync(normalizedFile, targetFile); fs.copySync(normalizedFile, targetFile);
@ -287,10 +287,10 @@ async function execute() {
// compile/copy pages from user // compile/copy pages from user
const enabledLanguages = env.translation const enabledLanguages = env.translation
.enabledLanguages() .enabledLanguages()
.map(lang => lang.tag); .map((lang) => lang.tag);
const userPagesDir = join(CWD, 'pages'); const userPagesDir = join(CWD, 'pages');
files = glob.sync(join(userPagesDir, '**')); files = glob.sync(join(userPagesDir, '**'));
files.forEach(file => { files.forEach((file) => {
// Why normalize? In case we are on Windows. // Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
const normalizedFile = path.normalize(file); const normalizedFile = path.normalize(file);

View file

@ -20,7 +20,7 @@ function start(port) {
gaze( gaze(
[`../${readMetadata.getDocsPath()}/**/*`, '**/*', '!node_modules/**/*'], [`../${readMetadata.getDocsPath()}/**/*`, '**/*', '!node_modules/**/*'],
function() { function () {
this.on('all', () => { this.on('all', () => {
server.notifyClients(['/']); server.notifyClients(['/']);
}); });

View file

@ -49,10 +49,7 @@ function extractMetadata(content) {
for (let i = 0; i < lines.length - 1; ++i) { for (let i = 0; i < lines.length - 1; ++i) {
const keyvalue = lines[i].split(':'); const keyvalue = lines[i].split(':');
const key = keyvalue[0].trim(); const key = keyvalue[0].trim();
let value = keyvalue let value = keyvalue.slice(1).join(':').trim();
.slice(1)
.join(':')
.trim();
try { try {
value = JSON.parse(value); value = JSON.parse(value);
} catch (err) { } catch (err) {
@ -68,7 +65,7 @@ function extractMetadata(content) {
function mdToHtml(Metadata, siteConfig) { function mdToHtml(Metadata, siteConfig) {
const {baseUrl, docsUrl} = siteConfig; const {baseUrl, docsUrl} = siteConfig;
const result = {}; const result = {};
Object.keys(Metadata).forEach(id => { Object.keys(Metadata).forEach((id) => {
const metadata = Metadata[id]; const metadata = Metadata[id];
if (metadata.language !== 'en' || metadata.original_id) { if (metadata.language !== 'en' || metadata.original_id) {
return; return;

View file

@ -13,34 +13,34 @@ function readCategories(sidebar, allMetadata, languages) {
// Go through each language that might be defined. // Go through each language that might be defined.
languages languages
.filter(lang => lang.enabled) .filter((lang) => lang.enabled)
.map(lang => lang.tag) .map((lang) => lang.tag)
.forEach(language => { .forEach((language) => {
// Get all related metadata for the current sidebar and specific to the language. // Get all related metadata for the current sidebar and specific to the language.
const metadatas = Object.values(allMetadata) const metadatas = Object.values(allMetadata)
.filter( .filter(
metadata => (metadata) =>
metadata.sidebar === sidebar && metadata.language === language, metadata.sidebar === sidebar && metadata.language === language,
) )
.sort((a, b) => a.order - b.order); .sort((a, b) => a.order - b.order);
// Define the correct order of categories. // Define the correct order of categories.
const sortedCategories = _.uniq( const sortedCategories = _.uniq(
metadatas.map(metadata => metadata.category), metadatas.map((metadata) => metadata.category),
); );
const metadatasGroupedByCategory = _.chain(metadatas) const metadatasGroupedByCategory = _.chain(metadatas)
.groupBy(metadata => metadata.category) .groupBy((metadata) => metadata.category)
.mapValues(categoryItems => { .mapValues((categoryItems) => {
// Process subcategories. // Process subcategories.
const metadatasGroupedBySubcategory = _.groupBy( const metadatasGroupedBySubcategory = _.groupBy(
categoryItems, categoryItems,
item => item.subcategory, (item) => item.subcategory,
); );
const result = []; const result = [];
const seenSubcategories = new Set(); const seenSubcategories = new Set();
// categoryItems can be links or subcategories. Handle separately. // categoryItems can be links or subcategories. Handle separately.
categoryItems.forEach(item => { categoryItems.forEach((item) => {
// Has no subcategory. // Has no subcategory.
if (item.subcategory == null) { if (item.subcategory == null) {
result.push({ result.push({
@ -59,7 +59,7 @@ function readCategories(sidebar, allMetadata, languages) {
seenSubcategories.add(subcategory); seenSubcategories.add(subcategory);
const subcategoryLinks = metadatasGroupedBySubcategory[ const subcategoryLinks = metadatasGroupedBySubcategory[
subcategory subcategory
].map(subcategoryItem => ({ ].map((subcategoryItem) => ({
type: 'LINK', type: 'LINK',
item: subcategoryItem, item: subcategoryItem,
})); }));
@ -74,7 +74,7 @@ function readCategories(sidebar, allMetadata, languages) {
}) })
.value(); .value();
const categories = sortedCategories.map(category => ({ const categories = sortedCategories.map((category) => ({
type: 'CATEGORY', type: 'CATEGORY',
title: category, title: category,
children: metadatasGroupedByCategory[category], children: metadatasGroupedByCategory[category],

View file

@ -66,17 +66,17 @@ function readSidebar(sidebars = {}) {
const items = {}; const items = {};
Object.keys(sidebars).forEach(sidebar => { Object.keys(sidebars).forEach((sidebar) => {
const categories = sidebars[sidebar]; const categories = sidebars[sidebar];
const sidebarItems = []; const sidebarItems = [];
Object.keys(categories).forEach(category => { Object.keys(categories).forEach((category) => {
const categoryItems = categories[category]; const categoryItems = categories[category];
categoryItems.forEach(categoryItem => { categoryItems.forEach((categoryItem) => {
if (typeof categoryItem === 'object') { if (typeof categoryItem === 'object') {
switch (categoryItem.type) { switch (categoryItem.type) {
case 'subcategory': case 'subcategory':
categoryItem.ids.forEach(subcategoryItem => { categoryItem.ids.forEach((subcategoryItem) => {
sidebarItems.push({ sidebarItems.push({
id: subcategoryItem, id: subcategoryItem,
category, category,
@ -133,7 +133,7 @@ function processMetadata(file, refDir) {
const language = utils.getLanguage(file, refDir) || 'en'; const language = utils.getLanguage(file, refDir) || 'en';
const metadata = {}; const metadata = {};
Object.keys(result.metadata).forEach(fieldName => { Object.keys(result.metadata).forEach((fieldName) => {
if (SupportedHeaderFields.has(fieldName)) { if (SupportedHeaderFields.has(fieldName)) {
metadata[fieldName] = result.metadata[fieldName]; metadata[fieldName] = result.metadata[fieldName];
} else { } else {
@ -219,7 +219,7 @@ function generateMetadataDocs() {
const enabledLanguages = env.translation const enabledLanguages = env.translation
.enabledLanguages() .enabledLanguages()
.map(language => language.tag); .map((language) => language.tag);
const metadatas = {}; const metadatas = {};
const defaultMetadatas = {}; const defaultMetadatas = {};
@ -228,7 +228,7 @@ function generateMetadataDocs() {
// metadata for english files // metadata for english files
const docsDir = path.join(CWD, '../', getDocsPath()); const docsDir = path.join(CWD, '../', getDocsPath());
let files = glob.sync(`${docsDir}/**`); let files = glob.sync(`${docsDir}/**`);
files.forEach(file => { files.forEach((file) => {
const extension = path.extname(file); const extension = path.extname(file);
if (extension === '.md' || extension === '.markdown') { if (extension === '.md' || extension === '.markdown') {
@ -243,8 +243,8 @@ function generateMetadataDocs() {
// create a default list of documents for each enabled language based on docs in English // create a default list of documents for each enabled language based on docs in English
// these will get replaced if/when the localized file is downloaded from crowdin // these will get replaced if/when the localized file is downloaded from crowdin
enabledLanguages enabledLanguages
.filter(currentLanguage => currentLanguage !== 'en') .filter((currentLanguage) => currentLanguage !== 'en')
.forEach(currentLanguage => { .forEach((currentLanguage) => {
const baseMetadata = Object.assign({}, metadata); const baseMetadata = Object.assign({}, metadata);
baseMetadata.id = baseMetadata.id baseMetadata.id = baseMetadata.id
.toString() .toString()
@ -277,7 +277,7 @@ function generateMetadataDocs() {
// metadata for non-english docs // metadata for non-english docs
const translatedDir = path.join(CWD, 'translated_docs'); const translatedDir = path.join(CWD, 'translated_docs');
files = glob.sync(`${CWD}/translated_docs/**`); files = glob.sync(`${CWD}/translated_docs/**`);
files.forEach(file => { files.forEach((file) => {
if (!utils.getLanguage(file, translatedDir)) { if (!utils.getLanguage(file, translatedDir)) {
return; return;
} }
@ -297,7 +297,7 @@ function generateMetadataDocs() {
// metadata for versioned docs // metadata for versioned docs
const versionData = versionFallback.docData(); const versionData = versionFallback.docData();
versionData.forEach(metadata => { versionData.forEach((metadata) => {
const id = metadata.localized_id; const id = metadata.localized_id;
if (order[id]) { if (order[id]) {
metadata.sidebar = order[id].sidebar; metadata.sidebar = order[id].sidebar;
@ -329,7 +329,7 @@ function generateMetadataDocs() {
// Get the titles of the previous and next ids so that we can use them in // Get the titles of the previous and next ids so that we can use them in
// navigation buttons in DocsLayout.js // navigation buttons in DocsLayout.js
Object.keys(metadatas).forEach(metadata => { Object.keys(metadatas).forEach((metadata) => {
if (metadatas[metadata].previous) { if (metadatas[metadata].previous) {
if (metadatas[metadatas[metadata].previous]) { if (metadatas[metadatas[metadata].previous]) {
metadatas[metadata].previous_title = metadatas[metadata].previous_title =
@ -350,11 +350,13 @@ function generateMetadataDocs() {
fs.writeFileSync( fs.writeFileSync(
path.join(__dirname, '/../core/metadata.js'), path.join(__dirname, '/../core/metadata.js'),
`${'/**\n' + `${
' * @' + '/**\n' +
'generated\n' + // separate this out for Nuclide treating @generated as readonly ' * @' +
'generated\n' + // separate this out for Nuclide treating @generated as readonly
' */\n' + ' */\n' +
'module.exports = '}${JSON.stringify(metadatas, null, 2)};\n`, 'module.exports = '
}${JSON.stringify(metadatas, null, 2)};\n`,
); );
} }
@ -366,7 +368,7 @@ function generateMetadataBlog(config = siteConfig) {
files files
.sort() .sort()
.reverse() .reverse()
.forEach(file => { .forEach((file) => {
const extension = path.extname(file); const extension = path.extname(file);
if (extension !== '.md' && extension !== '.markdown') { if (extension !== '.md' && extension !== '.markdown') {
return; return;
@ -389,11 +391,13 @@ function generateMetadataBlog(config = siteConfig) {
fs.writeFileSync( fs.writeFileSync(
path.join(__dirname, '/../core/MetadataBlog.js'), path.join(__dirname, '/../core/MetadataBlog.js'),
`${'/**\n' + `${
' * @' + '/**\n' +
'generated\n' + // separate this out for Nuclide treating @generated as readonly ' * @' +
'generated\n' + // separate this out for Nuclide treating @generated as readonly
' */\n' + ' */\n' +
'module.exports = '}${JSON.stringify(sortedMetadatas, null, 2)};\n`, 'module.exports = '
}${JSON.stringify(sortedMetadatas, null, 2)};\n`,
); );
} }

View file

@ -26,7 +26,7 @@ function noExtension() {
} }
function page(siteConfig) { function page(siteConfig) {
const gr = regex => regex.toString().replace(/(^\/|\/$)/gm, ''); const gr = (regex) => regex.toString().replace(/(^\/|\/$)/gm, '');
if (siteConfig.docsUrl === '') { if (siteConfig.docsUrl === '') {
return new RegExp( return new RegExp(

View file

@ -34,7 +34,7 @@ function execute(port, host) {
function removeModulePathFromCache(moduleName) { function removeModulePathFromCache(moduleName) {
/* eslint-disable no-underscore-dangle */ /* eslint-disable no-underscore-dangle */
Object.keys(module.constructor._pathCache).forEach(cacheKey => { Object.keys(module.constructor._pathCache).forEach((cacheKey) => {
if (cacheKey.indexOf(moduleName) > 0) { if (cacheKey.indexOf(moduleName) > 0) {
delete module.constructor._pathCache[cacheKey]; delete module.constructor._pathCache[cacheKey];
} }
@ -46,7 +46,7 @@ function execute(port, host) {
function removeModuleAndChildrenFromCache(moduleName) { function removeModuleAndChildrenFromCache(moduleName) {
let mod = require.resolve(moduleName); let mod = require.resolve(moduleName);
if (mod && (mod = require.cache[mod])) { if (mod && (mod = require.cache[mod])) {
mod.children.forEach(child => { mod.children.forEach((child) => {
delete require.cache[child.id]; delete require.cache[child.id];
removeModulePathFromCache(mod.id); removeModulePathFromCache(mod.id);
}); });
@ -121,7 +121,7 @@ function execute(port, host) {
app.get(routing.docs(siteConfig), (req, res, next) => { app.get(routing.docs(siteConfig), (req, res, next) => {
const url = decodeURI(req.path.toString().replace(siteConfig.baseUrl, '')); const url = decodeURI(req.path.toString().replace(siteConfig.baseUrl, ''));
const metakey = Object.keys(Metadata).find( const metakey = Object.keys(Metadata).find(
id => Metadata[id].permalink === url, (id) => Metadata[id].permalink === url,
); );
let metadata = Metadata[metakey]; let metadata = Metadata[metakey];
@ -137,7 +137,7 @@ function execute(port, host) {
// if any of the followings is changed, reload the metadata // if any of the followings is changed, reload the metadata
const reloadTriggers = ['sidebar_label', 'hide_title', 'title']; const reloadTriggers = ['sidebar_label', 'hide_title', 'title'];
if (reloadTriggers.some(key => metadata[key] !== rawMetadata[key])) { if (reloadTriggers.some((key) => metadata[key] !== rawMetadata[key])) {
reloadMetadata(); reloadMetadata();
extractTranslations(); extractTranslations();
reloadTranslations(); reloadTranslations();
@ -163,10 +163,7 @@ function execute(port, host) {
app.get(routing.feed(siteConfig), (req, res, next) => { app.get(routing.feed(siteConfig), (req, res, next) => {
res.set('Content-Type', 'application/rss+xml'); res.set('Content-Type', 'application/rss+xml');
const file = req.path const file = req.path.toString().split('blog/')[1].toLowerCase();
.toString()
.split('blog/')[1]
.toLowerCase();
if (file === 'atom.xml') { if (file === 'atom.xml') {
res.send(feed('atom')); res.send(feed('atom'));
} else if (file === 'feed.xml') { } else if (file === 'feed.xml') {
@ -250,7 +247,7 @@ function execute(port, host) {
const parts = match[1].split('/'); const parts = match[1].split('/');
const enabledLangTags = env.translation const enabledLangTags = env.translation
.enabledLanguages() .enabledLanguages()
.map(lang => lang.tag); .map((lang) => lang.tag);
for (let i = 0; i < parts.length; i++) { for (let i = 0; i < parts.length; i++) {
if (enabledLangTags.indexOf(parts[i]) !== -1) { if (enabledLangTags.indexOf(parts[i]) !== -1) {
@ -321,7 +318,7 @@ function execute(port, host) {
const files = glob.sync(join(CWD, 'static', '**', '*.css')); const files = glob.sync(join(CWD, 'static', '**', '*.css'));
files.forEach(file => { files.forEach((file) => {
if (isSeparateCss(file, siteConfig.separateCss)) { if (isSeparateCss(file, siteConfig.separateCss)) {
return; return;
} }
@ -342,15 +339,15 @@ function execute(port, host) {
); );
} }
Object.keys(siteConfig.colors).forEach(key => { Object.keys(siteConfig.colors).forEach((key) => {
const color = siteConfig.colors[key]; const color = siteConfig.colors[key];
cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color); cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color);
}); });
if (siteConfig.fonts) { if (siteConfig.fonts) {
Object.keys(siteConfig.fonts).forEach(key => { Object.keys(siteConfig.fonts).forEach((key) => {
const fontString = siteConfig.fonts[key] const fontString = siteConfig.fonts[key]
.map(font => `"${font}"`) .map((font) => `"${font}"`)
.join(', '); .join(', ');
cssContent = cssContent.replace( cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'), new RegExp(`\\$${key}`, 'g'),

View file

@ -26,7 +26,7 @@ const Metadata = require('../core/metadata.js');
readMetadata.generateMetadataBlog(siteConfig); readMetadata.generateMetadataBlog(siteConfig);
const MetadataBlog = require('../core/MetadataBlog.js'); const MetadataBlog = require('../core/MetadataBlog.js');
module.exports = function(callback) { module.exports = function (callback) {
console.log('sitemap.js triggered...'); console.log('sitemap.js triggered...');
const files = glob.sync(`${CWD}/pages/en/**/*.js`); const files = glob.sync(`${CWD}/pages/en/**/*.js`);
@ -43,23 +43,23 @@ module.exports = function(callback) {
// If we have a languages.js file, get all the enabled languages in there // If we have a languages.js file, get all the enabled languages in there
if (fs.existsSync(`${CWD}/languages.js`)) { if (fs.existsSync(`${CWD}/languages.js`)) {
const languages = require(`${CWD}/languages.js`); const languages = require(`${CWD}/languages.js`);
enabledLanguages = languages.filter(lang => lang.enabled); enabledLanguages = languages.filter((lang) => lang.enabled);
} }
// Create a url mapping to all the enabled languages files // Create a url mapping to all the enabled languages files
const urls = files.map(file => { const urls = files.map((file) => {
let url = file.split('/pages/en')[1]; let url = file.split('/pages/en')[1];
url = siteConfig.cleanUrl url = siteConfig.cleanUrl
? url.replace(/\.js$/, '') ? url.replace(/\.js$/, '')
: url.replace(/\.js$/, '.html'); : url.replace(/\.js$/, '.html');
const links = enabledLanguages.map(lang => { const links = enabledLanguages.map((lang) => {
const langUrl = lang.tag + url; const langUrl = lang.tag + url;
return {lang: lang.tag, url: langUrl}; return {lang: lang.tag, url: langUrl};
}); });
return {url, changefreq: 'weekly', priority: 0.5, links}; return {url, changefreq: 'weekly', priority: 0.5, links};
}); });
MetadataBlog.forEach(blog => { MetadataBlog.forEach((blog) => {
urls.push({ urls.push({
url: `/blog/${utils.getPath(blog.path, siteConfig.cleanUrl)}`, url: `/blog/${utils.getPath(blog.path, siteConfig.cleanUrl)}`,
changefreq: 'weekly', changefreq: 'weekly',
@ -68,12 +68,12 @@ module.exports = function(callback) {
}); });
Object.keys(Metadata) Object.keys(Metadata)
.filter(key => Metadata[key].language === 'en') .filter((key) => Metadata[key].language === 'en')
.forEach(key => { .forEach((key) => {
const doc = Metadata[key]; const doc = Metadata[key];
const docUrl = utils.getPath(doc.permalink, siteConfig.cleanUrl); const docUrl = utils.getPath(doc.permalink, siteConfig.cleanUrl);
const docsPart = `${siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : ''}`; const docsPart = `${siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : ''}`;
const links = enabledLanguages.map(lang => { const links = enabledLanguages.map((lang) => {
const langUrl = docUrl.replace( const langUrl = docUrl.replace(
new RegExp(`^${docsPart}en/`), new RegExp(`^${docsPart}en/`),
`${docsPart}${lang.tag}/`, `${docsPart}${lang.tag}/`,

View file

@ -14,7 +14,7 @@ const server = require('./server.js');
const CWD = process.cwd(); const CWD = process.cwd();
function startLiveReloadServer() { function startLiveReloadServer() {
const promise = portFinder.getPortPromise({port: 35729}).then(port => { const promise = portFinder.getPortPromise({port: 35729}).then((port) => {
liveReloadServer.start(port); liveReloadServer.start(port);
}); });
return promise; return promise;
@ -26,7 +26,7 @@ function startServer() {
const host = program.host || 'localhost'; const host = program.host || 'localhost';
const promise = portFinder const promise = portFinder
.getPortPromise({port: initialServerPort}) .getPortPromise({port: initialServerPort})
.then(port => { .then((port) => {
server(port, host); server(port, host);
const {baseUrl} = require(`${CWD}/siteConfig.js`); const {baseUrl} = require(`${CWD}/siteConfig.js`);
const serverAddress = `http://${host}:${port}${baseUrl}`; const serverAddress = `http://${host}:${port}${baseUrl}`;
@ -39,7 +39,7 @@ function startServer() {
function startDocusaurus() { function startDocusaurus() {
if (program.watch) { if (program.watch) {
return startLiveReloadServer() return startLiveReloadServer()
.catch(ex => console.warn(`Failed to start live reload server: ${ex}`)) .catch((ex) => console.warn(`Failed to start live reload server: ${ex}`))
.then(() => startServer()); .then(() => startServer());
} }
return startServer(); return startServer();

View file

@ -25,14 +25,14 @@ if (fs.existsSync(`${CWD}/languages.js`)) {
]; ];
} }
const enabledLanguages = languages.filter(lang => lang.enabled); const enabledLanguages = languages.filter((lang) => lang.enabled);
const translation = {languages: enabledLanguages}; const translation = {languages: enabledLanguages};
const files = glob.sync(`${CWD}/i18n/**`); const files = glob.sync(`${CWD}/i18n/**`);
const langRegex = /\/i18n\/(.*)\.json$/; const langRegex = /\/i18n\/(.*)\.json$/;
files.forEach(file => { files.forEach((file) => {
const extension = path.extname(file); const extension = path.extname(file);
if (extension === '.json') { if (extension === '.json') {
const match = langRegex.exec(file); const match = langRegex.exec(file);

View file

@ -28,7 +28,7 @@ function getLanguage(file, refDir) {
if (match && env.translation.enabled) { if (match && env.translation.enabled) {
const enabledLanguages = env.translation const enabledLanguages = env.translation
.enabledLanguages() .enabledLanguages()
.map(language => language.tag); .map((language) => language.tag);
if (enabledLanguages.indexOf(match[1]) !== -1) { if (enabledLanguages.indexOf(match[1]) !== -1) {
return match[1]; return match[1];
} }
@ -55,7 +55,7 @@ function minifyCss(cssContent) {
zindex: false, zindex: false,
from: undefined, from: undefined,
}) })
.then(result => result.css); .then((result) => result.css);
} }
function autoPrefixCss(cssContent) { function autoPrefixCss(cssContent) {
@ -63,12 +63,12 @@ function autoPrefixCss(cssContent) {
.process(cssContent, { .process(cssContent, {
from: undefined, from: undefined,
}) })
.then(result => result.css); .then((result) => result.css);
} }
function replaceAssetsLink(oldContent, location) { function replaceAssetsLink(oldContent, location) {
let fencedBlock = false; let fencedBlock = false;
const lines = oldContent.split('\n').map(line => { const lines = oldContent.split('\n').map((line) => {
if (line.trim().startsWith('```')) { if (line.trim().startsWith('```')) {
fencedBlock = !fencedBlock; fencedBlock = !fencedBlock;
} }

View file

@ -49,7 +49,7 @@ const available = {};
// given version/id of a document // given version/id of a document
const versionFiles = {}; const versionFiles = {};
const files = glob.sync(`${versionFolder}**`); const files = glob.sync(`${versionFolder}**`);
files.forEach(file => { files.forEach((file) => {
const ext = path.extname(file); const ext = path.extname(file);
if (ext !== '.md' && ext !== '.markdown') { if (ext !== '.md' && ext !== '.markdown') {
return; return;
@ -210,8 +210,8 @@ function processVersionMetadata(file, version, useVersion, language) {
// return all metadata of versioned documents // return all metadata of versioned documents
function docData() { function docData() {
const allIds = new Set(); const allIds = new Set();
Object.keys(versionFiles).forEach(version => { Object.keys(versionFiles).forEach((version) => {
Object.keys(versionFiles[version]).forEach(id => { Object.keys(versionFiles[version]).forEach((id) => {
allIds.add(id); allIds.add(id);
}); });
}); });
@ -219,10 +219,10 @@ function docData() {
const metadatas = []; const metadatas = [];
languages languages
.filter(language => language.enabled) .filter((language) => language.enabled)
.forEach(language => { .forEach((language) => {
versions.forEach(version => { versions.forEach((version) => {
allIds.forEach(id => { allIds.forEach((id) => {
let useVersion; let useVersion;
try { try {
useVersion = docVersion(id, version); useVersion = docVersion(id, version);

View file

@ -48,7 +48,7 @@ program
.option('--host <host>', 'use specified host (default: localhost)') .option('--host <host>', 'use specified host (default: localhost)')
.parse(process.argv); .parse(process.argv);
startDocusaurus().catch(ex => { startDocusaurus().catch((ex) => {
console.error(chalk.red(`Failed to start Docusaurus server: ${ex}`)); console.error(chalk.red(`Failed to start Docusaurus server: ${ex}`));
process.exit(1); process.exit(1);
}); });

View file

@ -7,19 +7,19 @@
// Turn off ESLint for this file because it's sent down to users as-is. // Turn off ESLint for this file because it's sent down to users as-is.
/* eslint-disable */ /* eslint-disable */
window.addEventListener('load', function() { window.addEventListener('load', function () {
// add event listener for all tab // add event listener for all tab
document.querySelectorAll('.nav-link').forEach(function(el) { document.querySelectorAll('.nav-link').forEach(function (el) {
el.addEventListener('click', function(e) { el.addEventListener('click', function (e) {
var groupId = e.target.getAttribute('data-group'); var groupId = e.target.getAttribute('data-group');
document document
.querySelectorAll('.nav-link[data-group='.concat(groupId, ']')) .querySelectorAll('.nav-link[data-group='.concat(groupId, ']'))
.forEach(function(el) { .forEach(function (el) {
el.classList.remove('active'); el.classList.remove('active');
}); });
document document
.querySelectorAll('.tab-pane[data-group='.concat(groupId, ']')) .querySelectorAll('.tab-pane[data-group='.concat(groupId, ']'))
.forEach(function(el) { .forEach(function (el) {
el.classList.remove('active'); el.classList.remove('active');
}); });
e.target.classList.add('active'); e.target.classList.add('active');

View file

@ -21,7 +21,7 @@
return; return;
} }
timer = setTimeout(function() { timer = setTimeout(function () {
timer = null; timer = null;
var activeNavFound = false; var activeNavFound = false;
var headings = findHeadings(); // toc nav anchors var headings = findHeadings(); // toc nav anchors
@ -75,7 +75,7 @@
document.addEventListener('scroll', onScroll); document.addEventListener('scroll', onScroll);
document.addEventListener('resize', onScroll); document.addEventListener('resize', onScroll);
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function () {
// Cache the headings once the page has fully loaded. // Cache the headings once the page has fully loaded.
headingsCache = findHeadings(); headingsCache = findHeadings();
onScroll(); onScroll();

View file

@ -46,7 +46,7 @@ let version;
program program
.arguments('<version>') .arguments('<version>')
.action(ver => { .action((ver) => {
version = ver; version = ver;
}) })
.parse(process.argv); .parse(process.argv);
@ -85,7 +85,7 @@ if (versions.includes(version)) {
function makeHeader(metadata) { function makeHeader(metadata) {
let header = '---\n'; let header = '---\n';
Object.keys(metadata).forEach(key => { Object.keys(metadata).forEach((key) => {
header += `${key}: ${metadata[key]}\n`; header += `${key}: ${metadata[key]}\n`;
}); });
header += '---\n'; header += '---\n';
@ -104,7 +104,7 @@ mkdirp.sync(versionFolder);
// copy necessary files to new version, changing some of its metadata to reflect the versioning // copy necessary files to new version, changing some of its metadata to reflect the versioning
const files = glob.sync(`${CWD}/../${readMetadata.getDocsPath()}/**`); const files = glob.sync(`${CWD}/../${readMetadata.getDocsPath()}/**`);
files.forEach(file => { files.forEach((file) => {
const ext = path.extname(file); const ext = path.extname(file);
if (ext !== '.md' && ext !== '.markdown') { if (ext !== '.md' && ext !== '.markdown') {
return; return;
@ -153,21 +153,21 @@ if (versionFallback.diffLatestSidebar()) {
const sidebar = JSON.parse(fs.readFileSync(`${CWD}/sidebars.json`, 'utf8')); const sidebar = JSON.parse(fs.readFileSync(`${CWD}/sidebars.json`, 'utf8'));
const versioned = {}; const versioned = {};
Object.keys(sidebar).forEach(sb => { Object.keys(sidebar).forEach((sb) => {
const versionSidebar = `version-${version}-${sb}`; const versionSidebar = `version-${version}-${sb}`;
versioned[versionSidebar] = {}; versioned[versionSidebar] = {};
const categories = sidebar[sb]; const categories = sidebar[sb];
Object.keys(categories).forEach(category => { Object.keys(categories).forEach((category) => {
versioned[versionSidebar][category] = []; versioned[versionSidebar][category] = [];
const categoryItems = categories[category]; const categoryItems = categories[category];
categoryItems.forEach(categoryItem => { categoryItems.forEach((categoryItem) => {
let versionedCategoryItem = categoryItem; let versionedCategoryItem = categoryItem;
if (typeof categoryItem === 'object') { if (typeof categoryItem === 'object') {
if (categoryItem.ids && categoryItem.ids.length > 0) { if (categoryItem.ids && categoryItem.ids.length > 0) {
versionedCategoryItem.ids = categoryItem.ids.map( versionedCategoryItem.ids = categoryItem.ids.map(
id => `version-${version}-${id}`, (id) => `version-${version}-${id}`,
); );
} }
} else if (typeof categoryItem === 'string') { } else if (typeof categoryItem === 'string') {

View file

@ -102,27 +102,27 @@ function execute() {
} }
} }
}; };
glob.sync(`${docsDir}/**`).forEach(file => translateDoc(file, docsDir)); glob.sync(`${docsDir}/**`).forEach((file) => translateDoc(file, docsDir));
glob glob
.sync(`${versionedDocsDir}/**`) .sync(`${versionedDocsDir}/**`)
.forEach(file => translateDoc(file, versionedDocsDir)); .forEach((file) => translateDoc(file, versionedDocsDir));
// look through header links for text to translate // look through header links for text to translate
siteConfig.headerLinks.forEach(link => { siteConfig.headerLinks.forEach((link) => {
if (link.label) { if (link.label) {
translations['localized-strings'].links[link.label] = link.label; translations['localized-strings'].links[link.label] = link.label;
} }
}); });
// find sidebar category titles to translate // find sidebar category titles to translate
Object.keys(sidebars).forEach(sb => { Object.keys(sidebars).forEach((sb) => {
const categories = sidebars[sb]; const categories = sidebars[sb];
Object.keys(categories).forEach(category => { Object.keys(categories).forEach((category) => {
translations['localized-strings'].categories[category] = category; translations['localized-strings'].categories[category] = category;
}); });
}); });
glob.sync(`${CWD}/versioned_sidebars/*`).forEach(file => { glob.sync(`${CWD}/versioned_sidebars/*`).forEach((file) => {
if (!file.endsWith('-sidebars.json')) { if (!file.endsWith('-sidebars.json')) {
if (file.endsWith('-sidebar.json')) { if (file.endsWith('-sidebar.json')) {
console.warn( console.warn(
@ -139,16 +139,16 @@ function execute() {
process.exit(1); process.exit(1);
} }
Object.keys(sidebarContent).forEach(sb => { Object.keys(sidebarContent).forEach((sb) => {
const categories = sidebarContent[sb]; const categories = sidebarContent[sb];
Object.keys(categories).forEach(category => { Object.keys(categories).forEach((category) => {
translations['localized-strings'].categories[category] = category; translations['localized-strings'].categories[category] = category;
}); });
}); });
}); });
// go through pages to look for text inside translate tags // go through pages to look for text inside translate tags
glob.sync(`${CWD}/pages/en/**`).forEach(file => { glob.sync(`${CWD}/pages/en/**`).forEach((file) => {
const extension = nodePath.extname(file); const extension = nodePath.extname(file);
if (extension === '.js') { if (extension === '.js') {
const ast = babylon.parse(fs.readFileSync(file, 'utf8'), { const ast = babylon.parse(fs.readFileSync(file, 'utf8'), {

View file

@ -26,7 +26,7 @@ if (!semver.satisfies(process.version, requiredVersion)) {
function wrapCommand(fn) { function wrapCommand(fn) {
return (...args) => return (...args) =>
fn(...args).catch(err => { fn(...args).catch((err) => {
console.error(chalk.red(err.stack)); console.error(chalk.red(err.stack));
process.exitCode = 1; process.exitCode = 1;
}); });
@ -43,7 +43,7 @@ program
wrapCommand(init)(path.resolve(rootDir), siteName, template); wrapCommand(init)(path.resolve(rootDir), siteName, template);
}); });
program.arguments('<command>').action(cmd => { program.arguments('<command>').action((cmd) => {
program.outputHelp(); program.outputHelp();
console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}`); console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}`);
console.log(); console.log();

View file

@ -23,7 +23,7 @@ function hasYarn(): boolean {
} }
function isValidGitRepoUrl(gitRepoUrl: string): boolean { function isValidGitRepoUrl(gitRepoUrl: string): boolean {
return ['https://', 'git@'].some(item => gitRepoUrl.startsWith(item)); return ['https://', 'git@'].some((item) => gitRepoUrl.startsWith(item));
} }
async function updatePkg(pkgPath: string, obj: any): Promise<void> { async function updatePkg(pkgPath: string, obj: any): Promise<void> {
@ -43,7 +43,7 @@ export async function init(
const templatesDir = path.resolve(__dirname, '../templates'); const templatesDir = path.resolve(__dirname, '../templates');
const templates = fs const templates = fs
.readdirSync(templatesDir) .readdirSync(templatesDir)
.filter(d => !d.startsWith('.') && !d.startsWith('README')); .filter((d) => !d.startsWith('.') && !d.startsWith('README'));
const gitChoice = 'Git repository'; const gitChoice = 'Git repository';
const templateChoices = [...templates, gitChoice]; const templateChoices = [...templates, gitChoice];

View file

@ -19,7 +19,7 @@ const DEFAULT_OPTIONS = {
remarkPlugins: [emoji, slug, rightToc], remarkPlugins: [emoji, slug, rightToc],
}; };
module.exports = async function(fileString) { module.exports = async function (fileString) {
const callback = this.async(); const callback = this.async();
const {data, content} = matter(fileString); const {data, content} = matter(fileString);

View file

@ -14,15 +14,15 @@ const parseOptions = {
plugins: ['jsx'], plugins: ['jsx'],
sourceType: 'module', sourceType: 'module',
}; };
const isImport = child => child.type === 'import'; const isImport = (child) => child.type === 'import';
const hasImports = index => index > -1; const hasImports = (index) => index > -1;
const isExport = child => child.type === 'export'; const isExport = (child) => child.type === 'export';
const isTarget = (child, name) => { const isTarget = (child, name) => {
let found = false; let found = false;
const ast = parse(child.value, parseOptions); const ast = parse(child.value, parseOptions);
traverse(ast, { traverse(ast, {
VariableDeclarator: path => { VariableDeclarator: (path) => {
if (path.node.id.name === name) { if (path.node.id.name === name) {
found = true; found = true;
} }
@ -61,7 +61,7 @@ const getOrCreateExistingTargetIndex = (children, name) => {
const plugin = (options = {}) => { const plugin = (options = {}) => {
const name = options.name || 'rightToc'; const name = options.name || 'rightToc';
const transformer = node => { const transformer = (node) => {
const headings = search(node); const headings = search(node);
const {children} = node; const {children} = node;
const targetIndex = getOrCreateExistingTargetIndex(children, name); const targetIndex = getOrCreateExistingTargetIndex(children, name);

View file

@ -57,7 +57,7 @@ describe('slug plugin', () => {
test('should not overwrite `data` on headings', () => { test('should not overwrite `data` on headings', () => {
const result = process('# Normal\n', [ const result = process('# Normal\n', [
function() { function () {
function transform(tree) { function transform(tree) {
tree.children[0].data = {foo: 'bar'}; tree.children[0].data = {foo: 'bar'};
} }
@ -80,7 +80,7 @@ describe('slug plugin', () => {
test('should not overwrite `data.hProperties` on headings', () => { test('should not overwrite `data.hProperties` on headings', () => {
const result = process('# Normal\n', [ const result = process('# Normal\n', [
function() { function () {
function transform(tree) { function transform(tree) {
tree.children[0].data = {hProperties: {className: ['foo']}}; tree.children[0].data = {hProperties: {className: ['foo']}};
} }
@ -110,7 +110,7 @@ describe('slug plugin', () => {
'## Something also', '## Something also',
].join('\n\n'), ].join('\n\n'),
[ [
function() { function () {
function transform(tree) { function transform(tree) {
tree.children[1].data = {hProperties: {id: 'here'}}; tree.children[1].data = {hProperties: {id: 'here'}};
tree.children[3].data = {hProperties: {id: 'something'}}; tree.children[3].data = {hProperties: {id: 'something'}};

View file

@ -12,7 +12,7 @@ const toString = require('mdast-util-to-string');
const slugs = require('github-slugger')(); const slugs = require('github-slugger')();
function slug() { function slug() {
const transformer = ast => { const transformer = (ast) => {
slugs.reset(); slugs.reset();
function visitor(headingNode) { function visitor(headingNode) {

View file

@ -11,7 +11,7 @@ import {LoadContext} from '@docusaurus/types';
import {PluginOptions} from '../types'; import {PluginOptions} from '../types';
describe('blogFeed', () => { describe('blogFeed', () => {
['atom', 'rss'].forEach(feedType => { ['atom', 'rss'].forEach((feedType) => {
describe(`${feedType}`, () => { describe(`${feedType}`, () => {
test('can show feed without posts', async () => { test('can show feed without posts', async () => {
const siteConfig = { const siteConfig = {

View file

@ -49,7 +49,7 @@ describe('loadBlog', () => {
.replace(/-/g, '/')}/no date`; .replace(/-/g, '/')}/no date`;
expect({ expect({
...blogPosts.find(v => v.metadata.title === 'date-matter').metadata, ...blogPosts.find((v) => v.metadata.title === 'date-matter').metadata,
...{prevItem: undefined}, ...{prevItem: undefined},
}).toEqual({ }).toEqual({
editUrl: editUrl:
@ -70,7 +70,7 @@ describe('loadBlog', () => {
}); });
expect( expect(
blogPosts.find(v => v.metadata.title === 'Happy 1st Birthday Slash!') blogPosts.find((v) => v.metadata.title === 'Happy 1st Birthday Slash!')
.metadata, .metadata,
).toEqual({ ).toEqual({
editUrl: editUrl:
@ -94,7 +94,7 @@ describe('loadBlog', () => {
}); });
expect({ expect({
...blogPosts.find(v => v.metadata.title === 'no date').metadata, ...blogPosts.find((v) => v.metadata.title === 'no date').metadata,
...{prevItem: undefined}, ...{prevItem: undefined},
}).toEqual({ }).toEqual({
editUrl: editUrl:
@ -119,6 +119,6 @@ describe('loadBlog', () => {
process.env.NODE_ENV = 'production'; process.env.NODE_ENV = 'production';
const blogPosts = await getBlogPosts(); const blogPosts = await getBlogPosts();
expect(blogPosts.find(v => v.metadata.title === 'draft')).toBeUndefined(); expect(blogPosts.find((v) => v.metadata.title === 'draft')).toBeUndefined();
}); });
}); });

View file

@ -36,7 +36,7 @@ const blogPosts: BlogPost[] = [
}, },
]; ];
const transform = filepath => { const transform = (filepath) => {
const content = fs.readFileSync(filepath, 'utf-8'); const content = fs.readFileSync(filepath, 'utf-8');
const transformedContent = linkify(content, sitePath, blogPath, blogPosts); const transformedContent = linkify(content, sitePath, blogPath, blogPosts);
return [content, transformedContent]; return [content, transformedContent];

View file

@ -69,7 +69,7 @@ export async function generateBlogFeed(
copyright: feedOptions.copyright, copyright: feedOptions.copyright,
}); });
blogPosts.forEach(post => { blogPosts.forEach((post) => {
const { const {
id, id,
metadata: {title, permalink, date, description}, metadata: {title, permalink, date, description},
@ -184,7 +184,7 @@ export function linkify(
blogPosts: BlogPost[], blogPosts: BlogPost[],
) { ) {
let fencedBlock = false; let fencedBlock = false;
const lines = fileContent.split('\n').map(line => { const lines = fileContent.split('\n').map((line) => {
if (line.trim().startsWith('```')) { if (line.trim().startsWith('```')) {
fencedBlock = !fencedBlock; fencedBlock = !fencedBlock;
} }
@ -203,7 +203,7 @@ export function linkify(
)}`; )}`;
let blogPostPermalink = null; let blogPostPermalink = null;
blogPosts.forEach(blogPost => { blogPosts.forEach((blogPost) => {
if (blogPost.metadata.source === aliasedPostSource) { if (blogPost.metadata.source === aliasedPostSource) {
blogPostPermalink = blogPost.metadata.permalink; blogPostPermalink = blogPost.metadata.permalink;
} }

View file

@ -85,7 +85,7 @@ export default function pluginContentBlog(
getPathsToWatch() { getPathsToWatch() {
const {include = []} = options; const {include = []} = options;
const globPattern = include.map(pattern => `${contentPath}/${pattern}`); const globPattern = include.map((pattern) => `${contentPath}/${pattern}`);
return [...globPattern]; return [...globPattern];
}, },
@ -151,13 +151,13 @@ export default function pluginContentBlog(
}, },
items: blogPosts items: blogPosts
.slice(page * postsPerPage, (page + 1) * postsPerPage) .slice(page * postsPerPage, (page + 1) * postsPerPage)
.map(item => item.id), .map((item) => item.id),
}); });
} }
const blogTags: BlogTags = {}; const blogTags: BlogTags = {};
const tagsPath = normalizeUrl([basePageUrl, 'tags']); const tagsPath = normalizeUrl([basePageUrl, 'tags']);
blogPosts.forEach(blogPost => { blogPosts.forEach((blogPost) => {
const {tags} = blogPost.metadata; const {tags} = blogPost.metadata;
if (!tags || tags.length === 0) { if (!tags || tags.length === 0) {
// TODO: Extract tags out into a separate plugin. // TODO: Extract tags out into a separate plugin.
@ -167,7 +167,7 @@ export default function pluginContentBlog(
} }
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
blogPost.metadata.tags = tags.map(tag => { blogPost.metadata.tags = tags.map((tag) => {
if (typeof tag === 'string') { if (typeof tag === 'string') {
const normalizedTag = kebabCase(tag); const normalizedTag = kebabCase(tag);
const permalink = normalizeUrl([tagsPath, normalizedTag]); const permalink = normalizeUrl([tagsPath, normalizedTag]);
@ -235,7 +235,7 @@ export default function pluginContentBlog(
// Create routes for blog entries. // Create routes for blog entries.
await Promise.all( await Promise.all(
blogPosts.map(async blogPost => { blogPosts.map(async (blogPost) => {
const {id, metadata} = blogPost; const {id, metadata} = blogPost;
await createData( await createData(
// Note that this created data path must be in sync with // Note that this created data path must be in sync with
@ -259,7 +259,7 @@ export default function pluginContentBlog(
// Create routes for blog's paginated list entries. // Create routes for blog's paginated list entries.
await Promise.all( await Promise.all(
blogListPaginated.map(async listPage => { blogListPaginated.map(async (listPage) => {
const {metadata, items} = listPage; const {metadata, items} = listPage;
const {permalink} = metadata; const {permalink} = metadata;
const pageMetadataPath = await createData( const pageMetadataPath = await createData(
@ -272,7 +272,7 @@ export default function pluginContentBlog(
component: blogListComponent, component: blogListComponent,
exact: true, exact: true,
modules: { modules: {
items: items.map(postID => { items: items.map((postID) => {
const metadata = blogItemsToMetadata[postID]; const metadata = blogItemsToMetadata[postID];
// To tell routes.js this is an import and not a nested object to recurse. // To tell routes.js this is an import and not a nested object to recurse.
return { return {
@ -299,7 +299,7 @@ export default function pluginContentBlog(
const tagsModule: TagsModule = {}; const tagsModule: TagsModule = {};
await Promise.all( await Promise.all(
Object.keys(blogTags).map(async tag => { Object.keys(blogTags).map(async (tag) => {
const {name, items, permalink} = blogTags[tag]; const {name, items, permalink} = blogTags[tag];
tagsModule[tag] = { tagsModule[tag] = {
@ -320,7 +320,7 @@ export default function pluginContentBlog(
component: blogTagsPostsComponent, component: blogTagsPostsComponent,
exact: true, exact: true,
modules: { modules: {
items: items.map(postID => { items: items.map((postID) => {
const metadata = blogItemsToMetadata[postID]; const metadata = blogItemsToMetadata[postID];
return { return {
content: { content: {
@ -422,14 +422,14 @@ export default function pluginContentBlog(
const feedTypes = getFeedTypes(options.feedOptions?.type); const feedTypes = getFeedTypes(options.feedOptions?.type);
await Promise.all( await Promise.all(
feedTypes.map(feedType => { feedTypes.map((feedType) => {
const feedPath = path.join( const feedPath = path.join(
outDir, outDir,
options.routeBasePath, options.routeBasePath,
`${feedType}.xml`, `${feedType}.xml`,
); );
const feedContent = feedType === 'rss' ? feed.rss2() : feed.atom1(); const feedContent = feedType === 'rss' ? feed.rss2() : feed.atom1();
return fs.writeFile(feedPath, feedContent, err => { return fs.writeFile(feedPath, feedContent, (err) => {
if (err) { if (err) {
throw new Error(`Generating ${feedType} feed failed: ${err}`); throw new Error(`Generating ${feedType} feed failed: ${err}`);
} }
@ -462,7 +462,7 @@ export default function pluginContentBlog(
}; };
const headTags: HtmlTags = []; const headTags: HtmlTags = [];
feedTypes.map(feedType => { feedTypes.map((feedType) => {
const feedConfig = feedsConfig[feedType] || {}; const feedConfig = feedsConfig[feedType] || {};
if (!feedsConfig) { if (!feedsConfig) {

View file

@ -9,7 +9,7 @@ import {loader} from 'webpack';
import {truncate, linkify} from './blogUtils'; import {truncate, linkify} from './blogUtils';
const {parseQuery, getOptions} = require('loader-utils'); const {parseQuery, getOptions} = require('loader-utils');
export = function(fileString: string) { export = function (fileString: string) {
const callback = this.async(); const callback = this.async();
const {truncateMarker, siteDir, contentPath, blogPosts} = getOptions(this); const {truncateMarker, siteDir, contentPath, blogPosts} = getOptions(this);
// Linkify posts // Linkify posts

View file

@ -1,6 +0,0 @@
/// <reference types="node" />
// @mdx-js/mdx currently doesn't have any @types
declare module '@mdx-js/mdx' {
export default function mdx(content: string, options: any): JSX.Element;
}

View file

@ -47,7 +47,7 @@ test('site with wrong sidebar file', async () => {
}); });
return plugin return plugin
.loadContent() .loadContent()
.catch(e => .catch((e) =>
expect(e).toMatchInlineSnapshot( expect(e).toMatchInlineSnapshot(
`[Error: Improper sidebars file, document with id 'goku' not found.]`, `[Error: Improper sidebars file, document with id 'goku' not found.]`,
), ),
@ -110,7 +110,7 @@ describe('simple website', () => {
test('getPathToWatch', () => { test('getPathToWatch', () => {
const pathToWatch = plugin.getPathsToWatch(); const pathToWatch = plugin.getPathsToWatch();
const matchPattern = pathToWatch.map(filepath => const matchPattern = pathToWatch.map((filepath) =>
posixPath(path.relative(siteDir, filepath)), posixPath(path.relative(siteDir, filepath)),
); );
expect(matchPattern).not.toEqual([]); expect(matchPattern).not.toEqual([]);
@ -235,7 +235,7 @@ describe('versioned website', () => {
test('getPathToWatch', () => { test('getPathToWatch', () => {
const pathToWatch = plugin.getPathsToWatch(); const pathToWatch = plugin.getPathsToWatch();
const matchPattern = pathToWatch.map(filepath => const matchPattern = pathToWatch.map((filepath) =>
posixPath(path.relative(siteDir, filepath)), posixPath(path.relative(siteDir, filepath)),
); );
expect(matchPattern).not.toEqual([]); expect(matchPattern).not.toEqual([]);

View file

@ -183,7 +183,7 @@ describe('simple site', () => {
context, context,
options, options,
env, env,
}).catch(e => }).catch((e) =>
expect(e).toMatchInlineSnapshot( expect(e).toMatchInlineSnapshot(
`[Error: Document id cannot include "/".]`, `[Error: Document id cannot include "/".]`,
), ),

View file

@ -26,7 +26,7 @@ export function getVersionsJSONFile(siteDir: string) {
return path.join(siteDir, VERSIONS_JSON_FILE); return path.join(siteDir, VERSIONS_JSON_FILE);
} }
export default function(siteDir: string): Env { export default function (siteDir: string): Env {
const versioning: VersioningEnv = { const versioning: VersioningEnv = {
enabled: false, enabled: false,
versions: [], versions: [],

View file

@ -81,7 +81,7 @@ export default function pluginContentDocs(
docsDir: versionedDir, docsDir: versionedDir,
sidebarsDir: versionedSidebarsDir, sidebarsDir: versionedSidebarsDir,
} = versioning; } = versioning;
const versionsNames = versions.map(version => `version-${version}`); const versionsNames = versions.map((version) => `version-${version}`);
return { return {
name: 'docusaurus-plugin-content-docs', name: 'docusaurus-plugin-content-docs',
@ -91,7 +91,7 @@ export default function pluginContentDocs(
.command('docs:version') .command('docs:version')
.arguments('<version>') .arguments('<version>')
.description('Tag a new version for docs') .description('Tag a new version for docs')
.action(version => { .action((version) => {
docsVersion(version, siteDir, { docsVersion(version, siteDir, {
path: options.path, path: options.path,
sidebarPath: options.sidebarPath, sidebarPath: options.sidebarPath,
@ -101,17 +101,18 @@ export default function pluginContentDocs(
getPathsToWatch() { getPathsToWatch() {
const {include} = options; const {include} = options;
let globPattern = include.map(pattern => `${docsDir}/${pattern}`); let globPattern = include.map((pattern) => `${docsDir}/${pattern}`);
if (versioning.enabled) { if (versioning.enabled) {
const docsGlob = include const docsGlob = include
.map(pattern => .map((pattern) =>
versionsNames.map( versionsNames.map(
versionName => `${versionedDir}/${versionName}/${pattern}`, (versionName) => `${versionedDir}/${versionName}/${pattern}`,
), ),
) )
.reduce((a, b) => a.concat(b), []); .reduce((a, b) => a.concat(b), []);
const sidebarsGlob = versionsNames.map( const sidebarsGlob = versionsNames.map(
versionName => `${versionedSidebarsDir}/${versionName}-sidebars.json`, (versionName) =>
`${versionedSidebarsDir}/${versionName}-sidebars.json`,
); );
globPattern = [...globPattern, ...sidebarsGlob, ...docsGlob]; globPattern = [...globPattern, ...sidebarsGlob, ...docsGlob];
} }
@ -136,7 +137,7 @@ export default function pluginContentDocs(
}); });
docsPromises.push( docsPromises.push(
Promise.all( Promise.all(
docsFiles.map(async source => { docsFiles.map(async (source) => {
const metadata: MetadataRaw = await processMetadata({ const metadata: MetadataRaw = await processMetadata({
source, source,
refDir: docsDir, refDir: docsDir,
@ -152,8 +153,8 @@ export default function pluginContentDocs(
// Metadata for versioned docs. // Metadata for versioned docs.
if (versioning.enabled) { if (versioning.enabled) {
const versionedGlob = include const versionedGlob = include
.map(pattern => .map((pattern) =>
versionsNames.map(versionName => `${versionName}/${pattern}`), versionsNames.map((versionName) => `${versionName}/${pattern}`),
) )
.reduce((a, b) => a.concat(b), []); .reduce((a, b) => a.concat(b), []);
const versionedFiles = await globby(versionedGlob, { const versionedFiles = await globby(versionedGlob, {
@ -161,7 +162,7 @@ export default function pluginContentDocs(
}); });
docsPromises.push( docsPromises.push(
Promise.all( Promise.all(
versionedFiles.map(async source => { versionedFiles.map(async (source) => {
const metadata = await processMetadata({ const metadata = await processMetadata({
source, source,
refDir: versionedDir, refDir: versionedDir,
@ -179,7 +180,8 @@ export default function pluginContentDocs(
const sidebarPaths = [ const sidebarPaths = [
sidebarPath, sidebarPath,
...versionsNames.map( ...versionsNames.map(
versionName => `${versionedSidebarsDir}/${versionName}-sidebars.json`, (versionName) =>
`${versionedSidebarsDir}/${versionName}-sidebars.json`,
), ),
]; ];
const loadedSidebars: Sidebar = loadSidebars(sidebarPaths); const loadedSidebars: Sidebar = loadSidebars(sidebarPaths);
@ -191,7 +193,7 @@ export default function pluginContentDocs(
const docsMetadata: DocsMetadata = {}; const docsMetadata: DocsMetadata = {};
const permalinkToSidebar: PermalinkToSidebar = {}; const permalinkToSidebar: PermalinkToSidebar = {};
const versionToSidebars: VersionToSidebars = {}; const versionToSidebars: VersionToSidebars = {};
Object.keys(docsMetadataRaw).forEach(currentID => { Object.keys(docsMetadataRaw).forEach((currentID) => {
const {next: nextID, previous: previousID, sidebar} = const {next: nextID, previous: previousID, sidebar} =
order[currentID] || {}; order[currentID] || {};
const previous = previousID const previous = previousID
@ -291,7 +293,7 @@ export default function pluginContentDocs(
metadataItems: Metadata[], metadataItems: Metadata[],
): Promise<RouteConfig[]> => { ): Promise<RouteConfig[]> => {
const routes = await Promise.all( const routes = await Promise.all(
metadataItems.map(async metadataItem => { metadataItems.map(async (metadataItem) => {
await createData( await createData(
// Note that this created data path must be in sync with // Note that this created data path must be in sync with
// metadataPath provided to mdx-loader. // metadataPath provided to mdx-loader.
@ -345,7 +347,7 @@ export default function pluginContentDocs(
'version', 'version',
); );
await Promise.all( await Promise.all(
Object.keys(docsMetadataByVersion).map(async version => { Object.keys(docsMetadataByVersion).map(async (version) => {
const routes: RouteConfig[] = await genRoutes( const routes: RouteConfig[] = await genRoutes(
docsMetadataByVersion[version], docsMetadataByVersion[version],
); );
@ -364,8 +366,9 @@ export default function pluginContentDocs(
content.docsSidebars, content.docsSidebars,
Array.from(neededSidebars), Array.from(neededSidebars),
), ),
permalinkToSidebar: pickBy(content.permalinkToSidebar, sidebar => permalinkToSidebar: pickBy(
neededSidebars.has(sidebar), content.permalinkToSidebar,
(sidebar) => neededSidebars.has(sidebar),
), ),
version, version,
}; };

View file

@ -24,7 +24,7 @@ const sourceToPermalink: SourceToPermalink = {
'/docs/1.0.0/subdir/doc1', '/docs/1.0.0/subdir/doc1',
}; };
const transform = filepath => { const transform = (filepath) => {
const content = fs.readFileSync(filepath, 'utf-8'); const content = fs.readFileSync(filepath, 'utf-8');
const transformedContent = linkify( const transformedContent = linkify(
content, content,

View file

@ -9,7 +9,7 @@ import {getOptions} from 'loader-utils';
import {loader} from 'webpack'; import {loader} from 'webpack';
import linkify from './linkify'; import linkify from './linkify';
export = function(fileString: string) { export = function (fileString: string) {
const callback = this.async(); const callback = this.async();
const {docsDir, siteDir, versionedDir, sourceToPermalink} = getOptions(this); const {docsDir, siteDir, versionedDir, sourceToPermalink} = getOptions(this);
return ( return (

View file

@ -10,7 +10,7 @@ import {resolve} from 'url';
import {getSubFolder} from '@docusaurus/utils'; import {getSubFolder} from '@docusaurus/utils';
import {SourceToPermalink} from '../types'; import {SourceToPermalink} from '../types';
export default function( export default function (
fileString: string, fileString: string,
filePath: string, filePath: string,
docsDir: string, docsDir: string,
@ -36,7 +36,7 @@ export default function(
// Replace internal markdown linking (except in fenced blocks). // Replace internal markdown linking (except in fenced blocks).
if (sourceDir) { if (sourceDir) {
let fencedBlock = false; let fencedBlock = false;
const lines = content.split('\n').map(line => { const lines = content.split('\n').map((line) => {
if (line.trim().startsWith('```')) { if (line.trim().startsWith('```')) {
fencedBlock = !fencedBlock; fencedBlock = !fencedBlock;
} }

View file

@ -11,12 +11,12 @@ import {Sidebar, SidebarItem, Order} from './types';
export default function createOrder(allSidebars: Sidebar = {}): Order { export default function createOrder(allSidebars: Sidebar = {}): Order {
const order: Order = {}; const order: Order = {};
Object.keys(allSidebars).forEach(sidebarId => { Object.keys(allSidebars).forEach((sidebarId) => {
const sidebar = allSidebars[sidebarId]; const sidebar = allSidebars[sidebarId];
const ids: string[] = []; const ids: string[] = [];
const indexItems = ({items}: {items: SidebarItem[]}) => { const indexItems = ({items}: {items: SidebarItem[]}) => {
items.forEach(item => { items.forEach((item) => {
switch (item.type) { switch (item.type) {
case 'category': case 'category':
indexItems({ indexItems({

View file

@ -43,7 +43,7 @@ function normalizeCategoryShorthand(
*/ */
function assertItem(item: Object, keys: string[]): void { function assertItem(item: Object, keys: string[]): void {
const unknownKeys = Object.keys(item).filter( const unknownKeys = Object.keys(item).filter(
key => !keys.includes(key) && key !== 'type', (key) => !keys.includes(key) && key !== 'type',
); );
if (unknownKeys.length) { if (unknownKeys.length) {
@ -150,7 +150,7 @@ export default function loadSidebars(sidebarPaths?: string[]): Sidebar {
return {} as Sidebar; return {} as Sidebar;
} }
sidebarPaths.map(sidebarPath => { sidebarPaths.map((sidebarPath) => {
if (sidebarPath && fs.existsSync(sidebarPath)) { if (sidebarPath && fs.existsSync(sidebarPath)) {
const sidebar = importFresh(sidebarPath) as SidebarRaw; const sidebar = importFresh(sidebarPath) as SidebarRaw;
Object.assign(allSidebars, sidebar); Object.assign(allSidebars, sidebar);

View file

@ -31,7 +31,7 @@ export default function pluginContentPages(
getPathsToWatch() { getPathsToWatch() {
const {include = []} = options; const {include = []} = options;
const globPattern = include.map(pattern => `${contentPath}/${pattern}`); const globPattern = include.map((pattern) => `${contentPath}/${pattern}`);
return [...globPattern]; return [...globPattern];
}, },
@ -49,7 +49,7 @@ export default function pluginContentPages(
cwd: pagesDir, cwd: pagesDir,
}); });
return pagesFiles.map(relativeSource => { return pagesFiles.map((relativeSource) => {
const source = path.join(pagesDir, relativeSource); const source = path.join(pagesDir, relativeSource);
const aliasedSource = aliasedSitePath(source, siteDir); const aliasedSource = aliasedSitePath(source, siteDir);
const pathName = encodePath(fileToPath(relativeSource)); const pathName = encodePath(fileToPath(relativeSource));
@ -69,7 +69,7 @@ export default function pluginContentPages(
const {addRoute} = actions; const {addRoute} = actions;
await Promise.all( await Promise.all(
content.map(async metadataItem => { content.map(async (metadataItem) => {
const {permalink, source} = metadataItem; const {permalink, source} = metadataItem;
addRoute({ addRoute({
path: permalink, path: permalink,

View file

@ -7,7 +7,7 @@
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
export default (function() { export default (function () {
if (!ExecutionEnvironment.canUseDOM) { if (!ExecutionEnvironment.canUseDOM) {
return null; return null;
} }

View file

@ -7,7 +7,7 @@
const path = require('path'); const path = require('path');
module.exports = function(context) { module.exports = function (context) {
const {siteConfig} = context; const {siteConfig} = context;
const {themeConfig} = siteConfig; const {themeConfig} = siteConfig;
const {googleAnalytics} = themeConfig || {}; const {googleAnalytics} = themeConfig || {};

View file

@ -8,7 +8,7 @@
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
import siteConfig from '@generated/docusaurus.config'; import siteConfig from '@generated/docusaurus.config';
export default (function() { export default (function () {
if (!ExecutionEnvironment.canUseDOM) { if (!ExecutionEnvironment.canUseDOM) {
return null; return null;
} }

View file

@ -7,7 +7,7 @@
const path = require('path'); const path = require('path');
module.exports = function(context) { module.exports = function (context) {
const {siteConfig} = context; const {siteConfig} = context;
const {themeConfig} = siteConfig; const {themeConfig} = siteConfig;
const {gtag} = themeConfig || {}; const {gtag} = themeConfig || {};

View file

@ -10,7 +10,7 @@ import {Configuration} from 'webpack';
import path from 'path'; import path from 'path';
export default function(_context: LoadContext, options: PluginOptions) { export default function (_context: LoadContext, options: PluginOptions) {
const isProd = process.env.NODE_ENV === 'production'; const isProd = process.env.NODE_ENV === 'production';
return { return {

View file

@ -18,7 +18,7 @@ function Image(props) {
width={img.src.width || 100} width={img.src.width || 100}
placeholder={{lqip: img.preSrc}} placeholder={{lqip: img.preSrc}}
src={img.src.src} src={img.src.src}
srcSet={img.src.images.map(image => ({ srcSet={img.src.images.map((image) => ({
...image, ...image,
src: image.path, src: image.path,
}))} }))}

View file

@ -20,7 +20,7 @@ export default function createSitemap(
} }
const urls = routesPaths.map( const urls = routesPaths.map(
routesPath => (routesPath) =>
({ ({
url: routesPath, url: routesPath,
changefreq: options.changefreq, changefreq: options.changefreq,

View file

@ -6,7 +6,7 @@
*/ */
const admonitions = require('remark-admonitions'); const admonitions = require('remark-admonitions');
const addAdmonitions = pluginOptions => { const addAdmonitions = (pluginOptions) => {
if (pluginOptions == null) { if (pluginOptions == null) {
return { return {
remarkPlugins: [admonitions], remarkPlugins: [admonitions],

View file

@ -35,7 +35,7 @@ const noFlash = `(function() {
} }
})();`; })();`;
module.exports = function(context, options) { module.exports = function (context, options) {
const { const {
siteConfig: {themeConfig}, siteConfig: {themeConfig},
} = context; } = context;
@ -61,7 +61,7 @@ module.exports = function(context, options) {
configureWebpack() { configureWebpack() {
const prismLanguages = additionalLanguages const prismLanguages = additionalLanguages
.map(lang => `prism-${lang}`) .map((lang) => `prism-${lang}`)
.join('|'); .join('|');
return { return {

View file

@ -17,7 +17,7 @@ import siteConfig from '@generated/docusaurus.config';
window.Prism = Prism; window.Prism = Prism;
additionalLanguages.forEach(lang => { additionalLanguages.forEach((lang) => {
require(`prismjs/components/prism-${lang}`); // eslint-disable-line require(`prismjs/components/prism-${lang}`); // eslint-disable-line
}); });

View file

@ -19,7 +19,7 @@ function BlogTagsListPage(props) {
const {tags} = props; const {tags} = props;
const tagCategories = {}; const tagCategories = {};
Object.keys(tags).forEach(tag => { Object.keys(tags).forEach((tag) => {
const category = getCategoryOfTag(tag); const category = getCategoryOfTag(tag);
tagCategories[category] = tagCategories[category] || []; tagCategories[category] = tagCategories[category] || [];
tagCategories[category].push(tag); tagCategories[category].push(tag);
@ -34,7 +34,7 @@ function BlogTagsListPage(props) {
.map(([category, tagsForCategory]) => ( .map(([category, tagsForCategory]) => (
<div key={category}> <div key={category}>
<h3>{category}</h3> <h3>{category}</h3>
{tagsForCategory.map(tag => ( {tagsForCategory.map((tag) => (
<Link <Link
className="padding-right--md" className="padding-right--md"
href={tags[tag].permalink} href={tags[tag].permalink}
@ -45,7 +45,7 @@ function BlogTagsListPage(props) {
<hr /> <hr />
</div> </div>
)) ))
.filter(item => item != null); .filter((item) => item != null);
return ( return (
<Layout title="Tags" description="Blog Tags"> <Layout title="Tags" description="Blog Tags">

View file

@ -54,7 +54,7 @@ const getHighlightDirectiveRegex = (
// to be more reliable, the opening and closing comment must match // to be more reliable, the opening and closing comment must match
const commentPattern = languages const commentPattern = languages
.map( .map(
lang => (lang) =>
`(?:${comments[lang].start}\\s*(${directives})\\s*${comments[lang].end})`, `(?:${comments[lang].start}\\s*(${directives})\\s*${comments[lang].end})`,
) )
.join('|'); .join('|');
@ -62,7 +62,7 @@ const getHighlightDirectiveRegex = (
return new RegExp(`^\\s*(?:${commentPattern})\\s*$`); return new RegExp(`^\\s*(?:${commentPattern})\\s*$`);
}; };
// select comment styles based on language // select comment styles based on language
const highlightDirectiveRegex = lang => { const highlightDirectiveRegex = (lang) => {
switch (lang) { switch (lang) {
case 'js': case 'js':
case 'javascript': case 'javascript':
@ -120,7 +120,9 @@ export default ({children, className: languageClassName, metastring}) => {
if (metastring && highlightLinesRangeRegex.test(metastring)) { if (metastring && highlightLinesRangeRegex.test(metastring)) {
const highlightLinesRange = metastring.match(highlightLinesRangeRegex)[1]; const highlightLinesRange = metastring.match(highlightLinesRangeRegex)[1];
highlightLines = rangeParser.parse(highlightLinesRange).filter(n => n > 0); highlightLines = rangeParser
.parse(highlightLinesRange)
.filter((n) => n > 0);
} }
if (metastring && codeBlockTitleRegex.test(metastring)) { if (metastring && codeBlockTitleRegex.test(metastring)) {

View file

@ -39,7 +39,7 @@ function Headings({headings, isChild}) {
} }
return ( return (
<ul className={isChild ? '' : 'contents contents__left-border'}> <ul className={isChild ? '' : 'contents contents__left-border'}>
{headings.map(heading => ( {headings.map((heading) => (
<li key={heading.id}> <li key={heading.id}>
<a <a
href={`#${heading.id}`} href={`#${heading.id}`}

View file

@ -22,7 +22,7 @@ function DocPage(props) {
const {route: baseRoute, docsMetadata, location} = props; const {route: baseRoute, docsMetadata, location} = props;
// case-sensitive route such as it is defined in the sidebar // case-sensitive route such as it is defined in the sidebar
const currentRoute = const currentRoute =
baseRoute.routes.find(route => { baseRoute.routes.find((route) => {
return matchPath(location.pathname, route); return matchPath(location.pathname, route);
}) || {}; }) || {};
const {permalinkToSidebar, docsSidebars, version} = docsMetadata; const {permalinkToSidebar, docsSidebars, version} = docsMetadata;

View file

@ -30,9 +30,9 @@ function DocSidebarItem({item, onItemClick, collapsible}) {
setCollapsed(item.collapsed); setCollapsed(item.collapsed);
} }
const handleItemClick = useCallback(e => { const handleItemClick = useCallback((e) => {
e.preventDefault(); e.preventDefault();
setCollapsed(state => !state); setCollapsed((state) => !state);
}); });
switch (type) { switch (type) {
@ -54,7 +54,7 @@ function DocSidebarItem({item, onItemClick, collapsible}) {
{label} {label}
</a> </a>
<ul className="menu__list"> <ul className="menu__list">
{items.map(childItem => ( {items.map((childItem) => (
<DocSidebarItem <DocSidebarItem
key={childItem.label} key={childItem.label}
item={childItem} item={childItem}
@ -99,8 +99,8 @@ function mutateSidebarCollapsingState(item, path) {
case 'category': { case 'category': {
const anyChildItemsActive = const anyChildItemsActive =
items items
.map(childItem => mutateSidebarCollapsingState(childItem, path)) .map((childItem) => mutateSidebarCollapsingState(childItem, path))
.filter(val => val).length > 0; .filter((val) => val).length > 0;
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
item.collapsed = !anyChildItemsActive; item.collapsed = !anyChildItemsActive;
return anyChildItemsActive; return anyChildItemsActive;
@ -144,7 +144,7 @@ function DocSidebar(props) {
} }
if (sidebarCollapsible) { if (sidebarCollapsible) {
sidebarData.forEach(sidebarItem => sidebarData.forEach((sidebarItem) =>
mutateSidebarCollapsingState(sidebarItem, path), mutateSidebarCollapsingState(sidebarItem, path),
); );
} }
@ -201,7 +201,7 @@ function DocSidebar(props) {
)} )}
</button> </button>
<ul className="menu__list"> <ul className="menu__list">
{sidebarData.map(item => ( {sidebarData.map((item) => (
<DocSidebarItem <DocSidebarItem
key={item.label} key={item.label}
item={item} item={item}

View file

@ -14,7 +14,7 @@ import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import './styles.css'; import './styles.css';
import styles from './styles.module.css'; import styles from './styles.module.css';
const Heading = Tag => const Heading = (Tag) =>
function TargetComponent({id, ...props}) { function TargetComponent({id, ...props}) {
const { const {
siteConfig: { siteConfig: {

View file

@ -13,21 +13,21 @@ import Heading from '@theme/Heading';
import styles from './styles.module.css'; import styles from './styles.module.css';
export default { export default {
code: props => { code: (props) => {
const {children} = props; const {children} = props;
if (typeof children === 'string') { if (typeof children === 'string') {
return <CodeBlock {...props} />; return <CodeBlock {...props} />;
} }
return children; return children;
}, },
a: props => { a: (props) => {
if (/\.[^./]+$/.test(props.href)) { if (/\.[^./]+$/.test(props.href)) {
// eslint-disable-next-line jsx-a11y/anchor-has-content // eslint-disable-next-line jsx-a11y/anchor-has-content
return <a {...props} />; return <a {...props} />;
} }
return <Link {...props} />; return <Link {...props} />;
}, },
pre: props => <div className={styles.mdxCodeBlock} {...props} />, pre: (props) => <div className={styles.mdxCodeBlock} {...props} />,
h1: Heading('h1'), h1: Heading('h1'),
h2: Heading('h2'), h2: Heading('h2'),
h3: Heading('h3'), h3: Heading('h3'),

View file

@ -125,7 +125,7 @@ function Navbar() {
}, [setSidebarShown]); }, [setSidebarShown]);
const onToggleChange = useCallback( const onToggleChange = useCallback(
e => (e.target.checked ? setDarkTheme() : setLightTheme()), (e) => (e.target.checked ? setDarkTheme() : setLightTheme()),
[setLightTheme, setDarkTheme], [setLightTheme, setDarkTheme],
); );
@ -182,14 +182,14 @@ function Navbar() {
)} )}
</Link> </Link>
{links {links
.filter(linkItem => linkItem.position === 'left') .filter((linkItem) => linkItem.position === 'left')
.map((linkItem, i) => ( .map((linkItem, i) => (
<NavItem {...linkItem} key={i} /> <NavItem {...linkItem} key={i} />
))} ))}
</div> </div>
<div className="navbar__items navbar__items--right"> <div className="navbar__items navbar__items--right">
{links {links
.filter(linkItem => linkItem.position === 'right') .filter((linkItem) => linkItem.position === 'right')
.map((linkItem, i) => ( .map((linkItem, i) => (
<NavItem {...linkItem} key={i} /> <NavItem {...linkItem} key={i} />
))} ))}

View file

@ -32,7 +32,7 @@ function Tabs(props) {
} }
} }
const changeSelectedValue = newValue => { const changeSelectedValue = (newValue) => {
setSelectedValue(newValue); setSelectedValue(newValue);
if (groupId != null) { if (groupId != null) {
setTabGroupChoices(groupId, newValue); setTabGroupChoices(groupId, newValue);
@ -91,8 +91,8 @@ function Tabs(props) {
'tab-item--active': selectedValue === value, 'tab-item--active': selectedValue === value,
})} })}
key={value} key={value}
ref={tabControl => tabRefs.push(tabControl)} ref={(tabControl) => tabRefs.push(tabControl)}
onKeyDown={event => handleKeydown(tabRefs, event.target, event)} onKeyDown={(event) => handleKeydown(tabRefs, event.target, event)}
onFocus={() => changeSelectedValue(value)} onFocus={() => changeSelectedValue(value)}
onClick={() => changeSelectedValue(value)}> onClick={() => changeSelectedValue(value)}>
{label} {label}
@ -102,7 +102,7 @@ function Tabs(props) {
<div role="tabpanel" className="margin-vert--md"> <div role="tabpanel" className="margin-vert--md">
{ {
Children.toArray(children).filter( Children.toArray(children).filter(
child => child.props.value === selectedValue, (child) => child.props.value === selectedValue,
)[0] )[0]
} }
</div> </div>

View file

@ -16,7 +16,7 @@ import styles from './styles.module.css';
const Moon = () => <span className={classnames(styles.toggle, styles.moon)} />; const Moon = () => <span className={classnames(styles.toggle, styles.moon)} />;
const Sun = () => <span className={classnames(styles.toggle, styles.sun)} />; const Sun = () => <span className={classnames(styles.toggle, styles.sun)} />;
export default function(props) { export default function (props) {
const {isClient} = useDocusaurusContext(); const {isClient} = useDocusaurusContext();
return ( return (
<Toggle <Toggle

View file

@ -9,12 +9,12 @@ import {useState, useCallback, useEffect} from 'react';
import {useLocation} from '@docusaurus/router'; import {useLocation} from '@docusaurus/router';
import useLocationHash from '@theme/hooks/useLocationHash'; import useLocationHash from '@theme/hooks/useLocationHash';
const useHideableNavbar = hideOnScroll => { const useHideableNavbar = (hideOnScroll) => {
const [isNavbarVisible, setIsNavbarVisible] = useState(true); const [isNavbarVisible, setIsNavbarVisible] = useState(true);
const [isFocusedAnchor, setIsFocusedAnchor] = useState(false); const [isFocusedAnchor, setIsFocusedAnchor] = useState(false);
const [lastScrollTop, setLastScrollTop] = useState(0); const [lastScrollTop, setLastScrollTop] = useState(0);
const [navbarHeight, setNavbarHeight] = useState(0); const [navbarHeight, setNavbarHeight] = useState(0);
const navbarRef = useCallback(node => { const navbarRef = useCallback((node) => {
if (node !== null) { if (node !== null) {
setNavbarHeight(node.getBoundingClientRect().height); setNavbarHeight(node.getBoundingClientRect().height);
} }

View file

@ -38,7 +38,7 @@ const useTabGroupChoice = () => {
return { return {
tabGroupChoices, tabGroupChoices,
setTabGroupChoices: (groupId, newChoice) => { setTabGroupChoices: (groupId, newChoice) => {
setChoices(oldChoices => ({...oldChoices, [groupId]: newChoice})); setChoices((oldChoices) => ({...oldChoices, [groupId]: newChoice}));
setChoiceSyncWithLocalStorage(groupId, newChoice); setChoiceSyncWithLocalStorage(groupId, newChoice);
}, },
}; };

View file

@ -24,7 +24,7 @@ const useTheme = () => {
: themes.light, : themes.light,
); );
const setThemeSyncWithLocalStorage = useCallback( const setThemeSyncWithLocalStorage = useCallback(
newTheme => { (newTheme) => {
try { try {
localStorage.setItem('theme', newTheme); localStorage.setItem('theme', newTheme);
} catch (err) { } catch (err) {

View file

@ -7,7 +7,7 @@
const path = require('path'); const path = require('path');
module.exports = function() { module.exports = function () {
return { return {
name: 'docusaurus-theme-live-codeblock', name: 'docusaurus-theme-live-codeblock',

View file

@ -55,7 +55,7 @@ const getHighlightDirectiveRegex = (
// to be more reliable, the opening and closing comment must match // to be more reliable, the opening and closing comment must match
const commentPattern = languages const commentPattern = languages
.map( .map(
lang => (lang) =>
`(?:${comments[lang].start}\\s*(${directives})\\s*${comments[lang].end})`, `(?:${comments[lang].start}\\s*(${directives})\\s*${comments[lang].end})`,
) )
.join('|'); .join('|');
@ -63,7 +63,7 @@ const getHighlightDirectiveRegex = (
return new RegExp(`^\\s*(?:${commentPattern})\\s*$`); return new RegExp(`^\\s*(?:${commentPattern})\\s*$`);
}; };
// select comment styles based on language // select comment styles based on language
const highlightDirectiveRegex = lang => { const highlightDirectiveRegex = (lang) => {
switch (lang) { switch (lang) {
case 'js': case 'js':
case 'javascript': case 'javascript':
@ -127,7 +127,9 @@ export default ({
if (metastring && highlightLinesRangeRegex.test(metastring)) { if (metastring && highlightLinesRangeRegex.test(metastring)) {
const highlightLinesRange = metastring.match(highlightLinesRangeRegex)[1]; const highlightLinesRange = metastring.match(highlightLinesRangeRegex)[1];
highlightLines = rangeParser.parse(highlightLinesRange).filter(n => n > 0); highlightLines = rangeParser
.parse(highlightLinesRange)
.filter((n) => n > 0);
} }
if (metastring && codeBlockTitleRegex.test(metastring)) { if (metastring && codeBlockTitleRegex.test(metastring)) {

View file

@ -15,7 +15,7 @@ function Playground({children, theme, transformCode, ...props}) {
return ( return (
<LiveProvider <LiveProvider
code={children} code={children}
transformCode={transformCode || (code => `${code};`)} transformCode={transformCode || ((code) => `${code};`)}
theme={theme} theme={theme}
{...props}> {...props}>
<div <div

View file

@ -7,7 +7,7 @@
const path = require('path'); const path = require('path');
module.exports = function() { module.exports = function () {
return { return {
name: 'docusaurus-theme-search-algolia', name: 'docusaurus-theme-search-algolia',

View file

@ -13,7 +13,7 @@ import {useHistory} from '@docusaurus/router';
import './styles.css'; import './styles.css';
const Search = props => { const Search = (props) => {
const [algoliaLoaded, setAlgoliaLoaded] = useState(false); const [algoliaLoaded, setAlgoliaLoaded] = useState(false);
const searchBarRef = useRef(null); const searchBarRef = useRef(null);
const {siteConfig = {}} = useDocusaurusContext(); const {siteConfig = {}} = useDocusaurusContext();
@ -81,7 +81,7 @@ const Search = props => {
props.handleSearchBarToggle(!props.isSearchBarExpanded); props.handleSearchBarToggle(!props.isSearchBarExpanded);
}, [props.isSearchBarExpanded]); }, [props.isSearchBarExpanded]);
const handleSearchInput = useCallback(e => { const handleSearchInput = useCallback((e) => {
const needFocus = e.type !== 'mouseover'; const needFocus = e.type !== 'mouseover';
loadAlgolia(needFocus); loadAlgolia(needFocus);

View file

@ -27,7 +27,7 @@ describe('load utils', () => {
'@site/versioned_docs/foo/bar.md', '@site/versioned_docs/foo/bar.md',
'user/docs/test.md': '@site/../docs/test.md', 'user/docs/test.md': '@site/../docs/test.md',
}; };
Object.keys(asserts).forEach(file => { Object.keys(asserts).forEach((file) => {
expect(aliasedSitePath(file, 'user/website')).toBe(asserts[file]); expect(aliasedSitePath(file, 'user/website')).toBe(asserts[file]);
}); });
}); });
@ -42,7 +42,7 @@ describe('load utils', () => {
'foo\\bar/lol': 'foo/bar/lol', 'foo\\bar/lol': 'foo/bar/lol',
'website\\docs/**/*.{md,mdx}': 'website/docs/**/*.{md,mdx}', 'website\\docs/**/*.{md,mdx}': 'website/docs/**/*.{md,mdx}',
}; };
Object.keys(asserts).forEach(file => { Object.keys(asserts).forEach((file) => {
expect(posixPath(file)).toBe(asserts[file]); expect(posixPath(file)).toBe(asserts[file]);
}); });
}); });
@ -59,7 +59,7 @@ describe('load utils', () => {
'/blog/201712/14-introducing-docusaurus': '/blog/201712/14-introducing-docusaurus':
'Blog20171214IntroducingDocusaurusA93', 'Blog20171214IntroducingDocusaurusA93',
}; };
Object.keys(asserts).forEach(file => { Object.keys(asserts).forEach((file) => {
expect(genComponentName(file)).toBe(asserts[file]); expect(genComponentName(file)).toBe(asserts[file]);
}); });
}); });
@ -75,7 +75,7 @@ describe('load utils', () => {
'/yangshun/tay': 'yangshun-tay-48d', '/yangshun/tay': 'yangshun-tay-48d',
'/yangshun-tay': 'yangshun-tay-f3b', '/yangshun-tay': 'yangshun-tay-f3b',
}; };
Object.keys(asserts).forEach(file => { Object.keys(asserts).forEach((file) => {
expect(docuHash(file)).toBe(asserts[file]); expect(docuHash(file)).toBe(asserts[file]);
}); });
}); });
@ -91,7 +91,7 @@ describe('load utils', () => {
'foo.js': '/foo', 'foo.js': '/foo',
'foo/bar.js': '/foo/bar', 'foo/bar.js': '/foo/bar',
}; };
Object.keys(asserts).forEach(file => { Object.keys(asserts).forEach((file) => {
expect(fileToPath(file)).toBe(asserts[file]); expect(fileToPath(file)).toBe(asserts[file]);
}); });
}); });
@ -142,7 +142,7 @@ describe('load utils', () => {
'/users/en/': 'users-en-f7a', '/users/en/': 'users-en-f7a',
'/blog': 'blog-c06', '/blog': 'blog-c06',
}; };
Object.keys(firstAssert).forEach(str => { Object.keys(firstAssert).forEach((str) => {
expect(genChunkName(str)).toBe(firstAssert[str]); expect(genChunkName(str)).toBe(firstAssert[str]);
}); });
@ -156,7 +156,7 @@ describe('load utils', () => {
'/blog/1': 'blog-85-f-089', '/blog/1': 'blog-85-f-089',
'/blog/2': 'blog-353-489', '/blog/2': 'blog-353-489',
}; };
Object.keys(secondAssert).forEach(str => { Object.keys(secondAssert).forEach((str) => {
expect(genChunkName(str, undefined, 'blog')).toBe(secondAssert[str]); expect(genChunkName(str, undefined, 'blog')).toBe(secondAssert[str]);
}); });
@ -167,7 +167,7 @@ describe('load utils', () => {
c: '4a8a08f0', c: '4a8a08f0',
d: '8277e091', d: '8277e091',
}; };
Object.keys(thirdAssert).forEach(str => { Object.keys(thirdAssert).forEach((str) => {
expect(genChunkName(str, undefined, undefined, true)).toBe( expect(genChunkName(str, undefined, undefined, true)).toBe(
thirdAssert[str], thirdAssert[str],
); );
@ -210,10 +210,9 @@ describe('load utils', () => {
versions: [], versions: [],
}); });
expect(idx(obj, ['translation', 'enabled'])).toEqual(true); expect(idx(obj, ['translation', 'enabled'])).toEqual(true);
expect(idx(obj, ['translation', variable]).map(lang => lang.tag)).toEqual([ expect(
'en', idx(obj, ['translation', variable]).map((lang) => lang.tag),
'ja', ).toEqual(['en', 'ja']);
]);
expect(idx(test, ['arr', 0])).toEqual(1); expect(idx(test, ['arr', 0])).toEqual(1);
expect(idx(undefined)).toBeUndefined(); expect(idx(undefined)).toBeUndefined();
expect(idx(null)).toBeNull(); expect(idx(null)).toBeNull();
@ -283,7 +282,7 @@ describe('load utils', () => {
output: 'http://foobar.com/test/', output: 'http://foobar.com/test/',
}, },
]; ];
asserts.forEach(testCase => { asserts.forEach((testCase) => {
expect(normalizeUrl(testCase.input)).toBe(testCase.output); expect(normalizeUrl(testCase.input)).toBe(testCase.output);
}); });

View file

@ -35,15 +35,11 @@ export async function generate(
// This is to avoid unnecessary overwriting and we can reuse old file. // This is to avoid unnecessary overwriting and we can reuse old file.
if (!lastHash && fs.existsSync(filepath)) { if (!lastHash && fs.existsSync(filepath)) {
const lastContent = await fs.readFile(filepath, 'utf8'); const lastContent = await fs.readFile(filepath, 'utf8');
lastHash = createHash('md5') lastHash = createHash('md5').update(lastContent).digest('hex');
.update(lastContent)
.digest('hex');
fileHash.set(filepath, lastHash); fileHash.set(filepath, lastHash);
} }
const currentHash = createHash('md5') const currentHash = createHash('md5').update(content).digest('hex');
.update(content)
.digest('hex');
if (lastHash !== currentHash) { if (lastHash !== currentHash) {
await fs.ensureDir(path.dirname(filepath)); await fs.ensureDir(path.dirname(filepath));
@ -79,7 +75,7 @@ export function fileToPath(file: string): string {
export function encodePath(userpath: string): string { export function encodePath(userpath: string): string {
return userpath return userpath
.split('/') .split('/')
.map(item => encodeURIComponent(item)) .map((item) => encodeURIComponent(item))
.join('/'); .join('/');
} }
@ -91,10 +87,7 @@ export function docuHash(str: string): string {
if (str === '/') { if (str === '/') {
return 'index'; return 'index';
} }
const shortHash = createHash('md5') const shortHash = createHash('md5').update(str).digest('hex').substr(0, 3);
.update(str)
.digest('hex')
.substr(0, 3);
return `${kebabCase(str)}-${shortHash}`; return `${kebabCase(str)}-${shortHash}`;
} }
@ -200,10 +193,7 @@ export function parse(
} { } {
const options: {} = { const options: {} = {
excerpt: (file: matter.GrayMatterFile<string>): void => { excerpt: (file: matter.GrayMatterFile<string>): void => {
file.excerpt = file.content file.excerpt = file.content.trim().split('\n', 1).shift();
.trim()
.split('\n', 1)
.shift();
}, },
}; };

View file

@ -26,7 +26,7 @@ if (!semver.satisfies(process.version, requiredVersion)) {
function wrapCommand(fn) { function wrapCommand(fn) {
return (...args) => return (...args) =>
fn(...args).catch(err => { fn(...args).catch((err) => {
console.error(chalk.red(err.stack)); console.error(chalk.red(err.stack));
process.exitCode = 1; process.exitCode = 1;
}); });
@ -94,7 +94,7 @@ cli
}); });
}); });
cli.arguments('<command>').action(cmd => { cli.arguments('<command>').action((cmd) => {
cli.outputHelp(); cli.outputHelp();
console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}`); console.log(` ${chalk.red(`\n Unknown command ${chalk.yellow(cmd)}.`)}`);
console.log(); console.log();

Some files were not shown because too many files have changed in this diff Show more