Prettify all JavaScript files (#964)

* Prettify all JavaScript files

* Make trailingComma all

* Delete v2/.prettierignore

* Remove v2 Prettier commands in package.json
This commit is contained in:
Yangshun Tay 2018-09-17 15:34:55 +08:00 committed by GitHub
parent a1de6dab04
commit 9d4a5d5359
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
101 changed files with 441 additions and 473 deletions

View file

@ -1 +0,0 @@
v2

View file

@ -5,5 +5,5 @@
"printWidth": 80, "printWidth": 80,
"proseWrap": "never", "proseWrap": "never",
"singleQuote": true, "singleQuote": true,
"trailingComma": "es5" "trailingComma": "all"
} }

View file

@ -7,53 +7,53 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
const shell = require("shelljs"); const shell = require('shelljs');
const chalk = require("chalk"); const chalk = require('chalk');
const fs = require("fs"); const fs = require('fs');
const CWD = process.cwd(); const CWD = process.cwd();
let useYarn = false; let useYarn = false;
if (shell.which("yarn")) { if (shell.which('yarn')) {
useYarn = true; useYarn = true;
} }
if (fs.existsSync(CWD + "/website")) { if (fs.existsSync(CWD + '/website')) {
console.error(chalk.yellow("Website folder already exists.\n")); console.error(chalk.yellow('Website folder already exists.\n'));
console.log( console.log(
"In order for Docusaurus to get set up as your static site generator, you will need to remove any existing 'website' folder from your root directory. If you are migrating from another static site generator, you may want to move your old website folder to a different location." "In order for Docusaurus to get set up as your static site generator, you will need to remove any existing 'website' folder from your root directory. If you are migrating from another static site generator, you may want to move your old website folder to a different location.",
); );
process.exit(1); process.exit(1);
} }
shell.cd(CWD); shell.cd(CWD);
shell.mkdir("website"); shell.mkdir('website');
console.log(chalk.green("Website folder created!\n")); console.log(chalk.green('Website folder created!\n'));
shell.cd("website"); shell.cd('website');
console.log( console.log(
chalk.yellow("Installing latest version of Docusaurus in website.\n") chalk.yellow('Installing latest version of Docusaurus in website.\n'),
); );
const packageContent = { scripts: { examples: "docusaurus-examples" } }; const packageContent = {scripts: {examples: 'docusaurus-examples'}};
fs.writeFileSync( fs.writeFileSync(
CWD + "/website/package.json", CWD + '/website/package.json',
JSON.stringify(packageContent, null, 2) + "\n" JSON.stringify(packageContent, null, 2) + '\n',
); );
if (useYarn) { if (useYarn) {
shell.exec("yarn add docusaurus --dev"); shell.exec('yarn add docusaurus --dev');
} else { } else {
shell.exec("npm install docusaurus --save-dev"); shell.exec('npm install docusaurus --save-dev');
} }
console.log(chalk.green("Docusaurus installed in website folder!\n")); console.log(chalk.green('Docusaurus installed in website folder!\n'));
if (useYarn) { if (useYarn) {
shell.exec("yarn run examples"); shell.exec('yarn run examples');
} else { } else {
shell.exec("npm run examples"); shell.exec('npm run examples');
} }

View file

@ -25,7 +25,7 @@ class Help extends React.Component {
{ {
content: `Learn more using the [documentation on this site.](${docUrl( content: `Learn more using the [documentation on this site.](${docUrl(
'doc1.html', 'doc1.html',
language language,
)})`, )})`,
title: 'Browse Docs', title: 'Browse Docs',
}, },

View file

@ -77,7 +77,7 @@ function Versions() {
<a href="">Release Notes</a> <a href="">Release Notes</a>
</td> </td>
</tr> </tr>
) ),
)} )}
</tbody> </tbody>
</table> </table>

View file

@ -68,7 +68,7 @@ describe('Build files', () => {
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');
@ -90,12 +90,12 @@ describe('Build files', () => {
siteConfig.projectName siteConfig.projectName
}/css/main.css`; }/css/main.css`;
const fileContents = await Promise.all( const fileContents = await Promise.all(
[combinedCSSFile, ...inputFiles].map(file => fs.readFile(file, 'utf8')) [combinedCSSFile, ...inputFiles].map(file => fs.readFile(file, 'utf8')),
); );
const [outputFileContent, ...inputFileContents] = fileContents; const [outputFileContent, ...inputFileContents] = fileContents;
const minifiedCssFiles = await Promise.all( const minifiedCssFiles = await Promise.all(
inputFileContents.map(utils.minifyCss) inputFileContents.map(utils.minifyCss),
); );
minifiedCssFiles.forEach(fileContent => { minifiedCssFiles.forEach(fileContent => {
@ -105,7 +105,7 @@ describe('Build files', () => {
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);

View file

@ -27,7 +27,7 @@ const CWD = process.cwd();
if (!fs.existsSync(`${CWD}/siteConfig.js`)) { if (!fs.existsSync(`${CWD}/siteConfig.js`)) {
console.error( console.error(
chalk.red('Error: No siteConfig.js file found in website folder!') chalk.red('Error: No siteConfig.js file found in website folder!'),
); );
process.exit(1); process.exit(1);
} }

View file

@ -27,7 +27,7 @@ commander
// add scripts to package.json file // add scripts to package.json file
if (fs.existsSync(`${CWD}/package.json`)) { if (fs.existsSync(`${CWD}/package.json`)) {
const packageContent = JSON.parse( const packageContent = JSON.parse(
fs.readFileSync(`${CWD}/package.json`, 'utf8') fs.readFileSync(`${CWD}/package.json`, 'utf8'),
); );
if (!packageContent.scripts) { if (!packageContent.scripts) {
packageContent.scripts = {}; packageContent.scripts = {};
@ -42,10 +42,10 @@ if (fs.existsSync(`${CWD}/package.json`)) {
packageContent.scripts['rename-version'] = 'docusaurus-rename-version'; packageContent.scripts['rename-version'] = 'docusaurus-rename-version';
fs.writeFileSync( fs.writeFileSync(
`${CWD}/package.json`, `${CWD}/package.json`,
`${JSON.stringify(packageContent, null, 2)}\n` `${JSON.stringify(packageContent, null, 2)}\n`,
); );
console.log( console.log(
`${chalk.green('Wrote docusaurus scripts to package.json file.')}\n` `${chalk.green('Wrote docusaurus scripts to package.json file.')}\n`,
); );
} }
@ -62,8 +62,8 @@ if (feature === 'translations') {
if (fs.existsSync(`${CWD}/../crowdin.yaml`)) { if (fs.existsSync(`${CWD}/../crowdin.yaml`)) {
console.log( console.log(
`${chalk.yellow('crowdin.yaml already exists')} in ${chalk.yellow( `${chalk.yellow('crowdin.yaml already exists')} in ${chalk.yellow(
`${outerFolder}/` `${outerFolder}/`,
)}. Rename or remove the file to regenerate an example version.\n` )}. Rename or remove the file to regenerate an example version.\n`,
); );
} else { } else {
fs.copySync(`${folder}/crowdin.yaml`, `${CWD}/../crowdin.yaml`); fs.copySync(`${folder}/crowdin.yaml`, `${CWD}/../crowdin.yaml`);
@ -87,10 +87,10 @@ if (feature === 'translations') {
} catch (e) { } catch (e) {
console.log( console.log(
`${chalk.yellow( `${chalk.yellow(
`${path.basename(filePath)} already exists` `${path.basename(filePath)} already exists`,
)} in ${chalk.yellow( )} in ${chalk.yellow(
`website${filePath.split(path.basename(filePath))[0]}` `website${filePath.split(path.basename(filePath))[0]}`,
)}. Rename or remove the file to regenerate an example version.\n` )}. Rename or remove the file to regenerate an example version.\n`,
); );
} }
}); });
@ -112,10 +112,10 @@ if (feature === 'translations') {
} catch (e) { } catch (e) {
console.log( console.log(
`${chalk.yellow( `${chalk.yellow(
`${path.basename(filePath)} already exists` `${path.basename(filePath)} already exists`,
)} in ${chalk.yellow( )} in ${chalk.yellow(
`website${filePath.split(path.basename(filePath))[0]}` `website${filePath.split(path.basename(filePath))[0]}`,
)}. Rename or remove the file to regenerate an example version.\n` )}. Rename or remove the file to regenerate an example version.\n`,
); );
} }
}); });
@ -125,13 +125,13 @@ if (feature === 'translations') {
if (fs.existsSync(`${CWD}/../docs-examples-from-docusaurus`)) { if (fs.existsSync(`${CWD}/../docs-examples-from-docusaurus`)) {
console.log( console.log(
`- ${chalk.green( `- ${chalk.green(
'docs-examples-from-docusaurus' 'docs-examples-from-docusaurus',
)} already exists in ${chalk.blue(outerFolder)}.` )} already exists in ${chalk.blue(outerFolder)}.`,
); );
} else { } else {
fs.copySync( fs.copySync(
`${folder}/docs-examples-from-docusaurus`, `${folder}/docs-examples-from-docusaurus`,
`${CWD}/../docs-examples-from-docusaurus` `${CWD}/../docs-examples-from-docusaurus`,
); );
exampleSiteCreated = true; exampleSiteCreated = true;
docsCreated = true; docsCreated = true;
@ -140,13 +140,13 @@ if (feature === 'translations') {
if (fs.existsSync(`${CWD}/blog-examples-from-docusaurus`)) { if (fs.existsSync(`${CWD}/blog-examples-from-docusaurus`)) {
console.log( console.log(
`- ${chalk.green( `- ${chalk.green(
'blog-examples-from-docusaurus' 'blog-examples-from-docusaurus',
)} already exists in ${chalk.blue(`${outerFolder}/website`)}.` )} already exists in ${chalk.blue(`${outerFolder}/website`)}.`,
); );
} else { } else {
fs.copySync( fs.copySync(
path.join(folder, 'blog-examples-from-docusaurus'), path.join(folder, 'blog-examples-from-docusaurus'),
path.join(CWD, 'blog-examples-from-docusaurus') path.join(CWD, 'blog-examples-from-docusaurus'),
); );
exampleSiteCreated = true; exampleSiteCreated = true;
blogCreated = true; blogCreated = true;
@ -159,8 +159,8 @@ if (feature === 'translations') {
if (fs.existsSync(dest)) { if (fs.existsSync(dest)) {
console.log( console.log(
`- ${chalk.green(copiedFileName)} already exists in ${chalk.blue( `- ${chalk.green(copiedFileName)} already exists in ${chalk.blue(
outerFolder outerFolder,
)}.` )}.`,
); );
} else { } else {
fs.copySync(src, dest); fs.copySync(src, dest);
@ -206,10 +206,10 @@ if (feature === 'translations') {
} catch (e) { } catch (e) {
console.log( console.log(
`- ${chalk.green( `- ${chalk.green(
`${path.basename(filePath)}` `${path.basename(filePath)}`,
)} already exists in ${chalk.blue( )} already exists in ${chalk.blue(
`${outerFolder}/website${filePath.split(path.basename(filePath))[0]}` `${outerFolder}/website${filePath.split(path.basename(filePath))[0]}`,
)}.` )}.`,
); );
} }
}); });
@ -233,19 +233,19 @@ if (feature === 'translations') {
if (docsCreated) { if (docsCreated) {
console.log( console.log(
`Rename ${chalk.yellow( `Rename ${chalk.yellow(
`${outerFolder}/docs-examples-from-docusaurus` `${outerFolder}/docs-examples-from-docusaurus`,
)} to ${chalk.yellow( )} to ${chalk.yellow(
`${outerFolder}/docs` `${outerFolder}/docs`,
)} to see the example docs on your site.\n` )} to see the example docs on your site.\n`,
); );
} }
if (blogCreated) { if (blogCreated) {
console.log( console.log(
`Rename ${chalk.yellow( `Rename ${chalk.yellow(
`${outerFolder}/website/blog-examples-from-docusaurus` `${outerFolder}/website/blog-examples-from-docusaurus`,
)} to ${chalk.yellow( )} to ${chalk.yellow(
`${outerFolder}/website/blog` `${outerFolder}/website/blog`,
)} to see the example blog posts on your site.\n` )} to see the example blog posts on your site.\n`,
); );
} }

View file

@ -52,7 +52,7 @@ class BlogPageLayout extends React.Component {
} }
config={this.props.config} config={this.props.config}
/> />
) ),
)} )}
<div className="docs-prevnext"> <div className="docs-prevnext">
{page > 0 && ( {page > 0 && (

View file

@ -25,7 +25,7 @@ class BlogPost extends React.Component {
className="button" className="button"
href={`${this.props.config.baseUrl}blog/${utils.getPath( href={`${this.props.config.baseUrl}blog/${utils.getPath(
this.props.post.path, this.props.post.path,
this.props.config.cleanUrl this.props.config.cleanUrl,
)}`}> )}`}>
Read More Read More
</a> </a>
@ -66,7 +66,7 @@ class BlogPost extends React.Component {
<a <a
href={`${this.props.config.baseUrl}blog/${utils.getPath( href={`${this.props.config.baseUrl}blog/${utils.getPath(
post.path, post.path,
this.props.config.cleanUrl this.props.config.cleanUrl,
)}`}> )}`}>
{post.title} {post.title}
</a> </a>

View file

@ -11,10 +11,10 @@ const MarkdownBlock = require('./MarkdownBlock.js');
const translate = require('../server/translate.js').translate; const translate = require('../server/translate.js').translate;
const editThisDoc = translate( const editThisDoc = translate(
'Edit this Doc|recruitment message asking to edit the doc source' 'Edit this Doc|recruitment message asking to edit the doc source',
); );
const translateThisDoc = translate( const translateThisDoc = translate(
'Translate this Doc|recruitment message asking to translate the docs' 'Translate this Doc|recruitment message asking to translate the docs',
); );
// inner doc component for article itself // inner doc component for article itself

View file

@ -30,7 +30,7 @@ class DocsLayout extends React.Component {
.replace(/^\.\.\//, '') + extension; .replace(/^\.\.\//, '') + extension;
return url.resolve( return url.resolve(
`${this.props.config.baseUrl}${this.props.metadata.permalink}`, `${this.props.config.baseUrl}${this.props.metadata.permalink}`,
relativeHref relativeHref,
); );
}; };
@ -95,7 +95,7 @@ class DocsLayout extends React.Component {
className="docs-prev button" className="docs-prev button"
href={this.getRelativeURL( href={this.getRelativeURL(
metadata.localized_id, metadata.localized_id,
metadata.previous_id metadata.previous_id,
)}> )}>
<span className="arrow-prev"> </span> <span className="arrow-prev"> </span>
<span <span
@ -112,7 +112,7 @@ class DocsLayout extends React.Component {
className="docs-next button" className="docs-next button"
href={this.getRelativeURL( href={this.getRelativeURL(
metadata.localized_id, metadata.localized_id,
metadata.next_id metadata.next_id,
)}> )}>
<span <span
className={ className={

View file

@ -143,7 +143,7 @@ class Head extends React.Component {
<link rel="stylesheet" key={source.href} {...source} /> <link rel="stylesheet" key={source.href} {...source} />
) : ( ) : (
<link rel="stylesheet" key={source} href={source} /> <link rel="stylesheet" key={source} href={source} />
) ),
)} )}
{this.props.config.scripts && {this.props.config.scripts &&
this.props.config.scripts.map( this.props.config.scripts.map(
@ -152,7 +152,7 @@ class Head extends React.Component {
<script type="text/javascript" key={source.src} {...source} /> <script type="text/javascript" key={source.src} {...source} />
) : ( ) : (
<script type="text/javascript" src={source} key={source} /> <script type="text/javascript" src={source} key={source} />
) ),
)} )}
{this.props.config.scrollToTop && ( {this.props.config.scrollToTop && (
@ -168,8 +168,8 @@ class Head extends React.Component {
Object.assign( Object.assign(
{}, {},
{zIndex: 100}, {zIndex: 100},
this.props.config.scrollToTopOptions this.props.config.scrollToTopOptions,
) ),
)} )}
) )
}); });

View file

@ -122,7 +122,7 @@ class Site extends React.Component {
indexName: '${this.props.config.algolia.indexName}', indexName: '${this.props.config.algolia.indexName}',
inputSelector: '#search_input_react', inputSelector: '#search_input_react',
algoliaOptions: ${JSON.stringify( algoliaOptions: ${JSON.stringify(
this.props.config.algolia.algoliaOptions this.props.config.algolia.algoliaOptions,
) )
.replace('VERSION', docsVersion) .replace('VERSION', docsVersion)
.replace('LANGUAGE', this.props.language)} .replace('LANGUAGE', this.props.language)}

View file

@ -22,10 +22,10 @@ const render = md.renderer.rules.heading_open;
test('Anchors rendering', () => { test('Anchors rendering', () => {
expect( expect(
render([{hLevel: 1}, {content: 'Hello world'}], 0, {}, {}) render([{hLevel: 1}, {content: 'Hello world'}], 0, {}, {}),
).toMatchSnapshot(); ).toMatchSnapshot();
expect( expect(
render([{hLevel: 2}, {content: 'Hello small world'}], 0, {}, {}) render([{hLevel: 2}, {content: 'Hello small world'}], 0, {}, {}),
).toMatchSnapshot(); ).toMatchSnapshot();
}); });
@ -48,22 +48,22 @@ test('Each anchor is unique across rendered document', () => {
const env = {}; const env = {};
expect(render(tokens, 0, options, env)).toContain( expect(render(tokens, 0, options, env)).toContain(
'id="almost-unique-heading"' 'id="almost-unique-heading"',
); );
expect(render(tokens, 2, options, env)).toContain( expect(render(tokens, 2, options, env)).toContain(
'id="almost-unique-heading-1"' 'id="almost-unique-heading-1"',
); );
expect(render(tokens, 4, options, env)).toContain( expect(render(tokens, 4, options, env)).toContain(
'id="almost-unique-heading-1-1"' 'id="almost-unique-heading-1-1"',
); );
expect(render(tokens, 6, options, env)).toContain( expect(render(tokens, 6, options, env)).toContain(
'id="almost-unique-heading-1-2"' 'id="almost-unique-heading-1-2"',
); );
expect(render(tokens, 8, options, env)).toContain( expect(render(tokens, 8, options, env)).toContain(
'id="almost-unique-heading-2"' 'id="almost-unique-heading-2"',
); );
expect(render(tokens, 10, options, env)).toContain( expect(render(tokens, 10, options, env)).toContain(
'id="almost-unique-heading-3"' 'id="almost-unique-heading-3"',
); );
}); });
@ -99,17 +99,17 @@ test('Anchor index resets on each render', () => {
const env2 = {}; const env2 = {};
expect(render(tokens, 0, options, env)).toContain( expect(render(tokens, 0, options, env)).toContain(
'id="almost-unique-heading"' 'id="almost-unique-heading"',
); );
expect(render(tokens, 2, options, env)).toContain( expect(render(tokens, 2, options, env)).toContain(
'id="almost-unique-heading-1"' 'id="almost-unique-heading-1"',
); );
expect(render(tokens, 0, options, env2)).toContain( expect(render(tokens, 0, options, env2)).toContain(
'id="almost-unique-heading"' 'id="almost-unique-heading"',
); );
expect(render(tokens, 2, options, env2)).toContain( expect(render(tokens, 2, options, env2)).toContain(
'id="almost-unique-heading-1"' 'id="almost-unique-heading-1"',
); );
}); });

View file

@ -12,12 +12,12 @@ const {extractMetadata} = require('../../server/metadataUtils');
const getTOCmd = readFileSync( const getTOCmd = readFileSync(
path.join(__dirname, '__fixtures__', 'getTOC.md'), path.join(__dirname, '__fixtures__', 'getTOC.md'),
'utf8' 'utf8',
); );
const insertTOCmd = readFileSync( const insertTOCmd = readFileSync(
path.join(__dirname, '__fixtures__', 'insertTOC.md'), path.join(__dirname, '__fixtures__', 'insertTOC.md'),
'utf8' 'utf8',
); );
describe('getTOC', () => { describe('getTOC', () => {

View file

@ -11,30 +11,30 @@ const utils = require('../utils');
const blogPostWithTruncateContents = fs.readFileSync( const blogPostWithTruncateContents = fs.readFileSync(
path.join(__dirname, '__fixtures__', 'blog-post-with-truncate.md'), path.join(__dirname, '__fixtures__', 'blog-post-with-truncate.md'),
'utf8' 'utf8',
); );
const blogPostWithoutTruncateContents = fs.readFileSync( const blogPostWithoutTruncateContents = fs.readFileSync(
path.join(__dirname, '__fixtures__', 'blog-post-without-truncate.md'), path.join(__dirname, '__fixtures__', 'blog-post-without-truncate.md'),
'utf8' 'utf8',
); );
describe('utils', () => { describe('utils', () => {
test('blogPostHasTruncateMarker', () => { test('blogPostHasTruncateMarker', () => {
expect(utils.blogPostHasTruncateMarker(blogPostWithTruncateContents)).toBe( expect(utils.blogPostHasTruncateMarker(blogPostWithTruncateContents)).toBe(
true true,
); );
expect( expect(
utils.blogPostHasTruncateMarker(blogPostWithoutTruncateContents) utils.blogPostHasTruncateMarker(blogPostWithoutTruncateContents),
).toBe(false); ).toBe(false);
}); });
test('extractBlogPostBeforeTruncate', () => { test('extractBlogPostBeforeTruncate', () => {
expect( expect(
utils.extractBlogPostBeforeTruncate(blogPostWithTruncateContents) utils.extractBlogPostBeforeTruncate(blogPostWithTruncateContents),
).toMatchSnapshot(); ).toMatchSnapshot();
expect( expect(
utils.extractBlogPostBeforeTruncate(blogPostWithoutTruncateContents) utils.extractBlogPostBeforeTruncate(blogPostWithoutTruncateContents),
).toMatchSnapshot(); ).toMatchSnapshot();
}); });
@ -42,7 +42,7 @@ describe('utils', () => {
// does not change/transform path // does not change/transform path
expect(utils.getPath('/en/users.html', false)).toBe('/en/users.html'); expect(utils.getPath('/en/users.html', false)).toBe('/en/users.html');
expect(utils.getPath('/docs/en/versioning.html', false)).toBe( expect(utils.getPath('/docs/en/versioning.html', false)).toBe(
'/docs/en/versioning.html' '/docs/en/versioning.html',
); );
expect(utils.getPath(undefined, false)).toBeUndefined(); expect(utils.getPath(undefined, false)).toBeUndefined();
expect(utils.getPath(null, false)).toBeNull(); expect(utils.getPath(null, false)).toBeNull();
@ -85,7 +85,7 @@ describe('utils', () => {
const nonExistingFilePath = path.join( const nonExistingFilePath = path.join(
__dirname, __dirname,
'__fixtures__', '__fixtures__',
'.nonExisting' '.nonExisting',
); );
expect(utils.getGitLastUpdated(null)).toBeNull(); expect(utils.getGitLastUpdated(null)).toBeNull();
expect(utils.getGitLastUpdated(undefined)).toBeNull(); expect(utils.getGitLastUpdated(undefined)).toBeNull();
@ -133,7 +133,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

@ -31,7 +31,7 @@ class LanguageDropDown extends React.Component {
render() { render() {
setLanguage(this.props.language || 'en'); setLanguage(this.props.language || 'en');
const helpTranslateString = translate( const helpTranslateString = translate(
'Help Translate|recruit community translators for your project' 'Help Translate|recruit community translators for your project',
); );
// add all enabled languages to dropdown // add all enabled languages to dropdown
const enabledLanguages = env.translation const enabledLanguages = env.translation
@ -49,7 +49,7 @@ class LanguageDropDown extends React.Component {
siteConfig.baseUrl + siteConfig.baseUrl +
this.props.current.permalink.replace( this.props.current.permalink.replace(
`/${this.props.language}/`, `/${this.props.language}/`,
`/${lang.tag}/` `/${lang.tag}/`,
); );
} else if (this.props.current.id && this.props.current.id !== 'index') { } else if (this.props.current.id && this.props.current.id !== 'index') {
href = `${siteConfig.baseUrl + lang.tag}/${this.props.current.id}`; href = `${siteConfig.baseUrl + lang.tag}/${this.props.current.id}`;
@ -81,7 +81,7 @@ class LanguageDropDown extends React.Component {
rel="noreferrer noopener"> rel="noreferrer noopener">
{helpTranslateString} {helpTranslateString}
</a> </a>
</li> </li>,
); );
} }
@ -251,20 +251,20 @@ class HeaderNav extends React.Component {
throw new Error( throw new Error(
`You have 'doc' in your headerLinks, but no '${readMetadata.getDocsPath()}' folder exists one level up from ` + `You have 'doc' in your headerLinks, but no '${readMetadata.getDocsPath()}' folder exists one level up from ` +
`'website' folder. Did you run \`docusaurus-init\` or \`npm run examples\`? If so, ` + `'website' folder. Did you run \`docusaurus-init\` or \`npm run examples\`? If so, ` +
`make sure you rename 'docs-examples-from-docusaurus' to 'docs'.` `make sure you rename 'docs-examples-from-docusaurus' to 'docs'.`,
); );
} }
if (link.blog && !fs.existsSync(`${CWD}/blog/`)) { if (link.blog && !fs.existsSync(`${CWD}/blog/`)) {
throw new Error( throw new Error(
"You have 'blog' in your headerLinks, but no 'blog' folder exists in your " + "You have 'blog' in your headerLinks, but no 'blog' folder exists in your " +
"'website' folder. Did you run `docusaurus-init` or `npm run examples`? If so, " + "'website' folder. Did you run `docusaurus-init` or `npm run examples`? If so, " +
"make sure you rename 'blog-examples-from-docusaurus' to 'blog'." "make sure you rename 'blog-examples-from-docusaurus' to 'blog'.",
); );
} }
if (link.page && !fs.existsSync(`${CWD}/pages/`)) { if (link.page && !fs.existsSync(`${CWD}/pages/`)) {
throw new Error( throw new Error(
"You have 'page' in your headerLinks, but no 'pages' folder exists in your " + "You have 'page' in your headerLinks, but no 'pages' folder exists in your " +
"'website' folder." "'website' folder.",
); );
} }
// We will add search bar to end if location not specified // We will add search bar to end if location not specified

View file

@ -55,7 +55,7 @@ class SideNav extends React.Component {
if (metadata.path) { if (metadata.path) {
return `${siteConfig.baseUrl}blog/${getPath( return `${siteConfig.baseUrl}blog/${getPath(
metadata.path, metadata.path,
siteConfig.cleanUrl siteConfig.cleanUrl,
)}`; )}`;
} }
return null; return null;

View file

@ -40,7 +40,7 @@ module.exports = (string, context = {}) => {
.toLowerCase() .toLowerCase()
// Handle accentuated characters // Handle accentuated characters
.replace(new RegExp(`[${accents}]`, 'g'), c => .replace(new RegExp(`[${accents}]`, 'g'), c =>
without.charAt(accents.indexOf(c)) without.charAt(accents.indexOf(c)),
) )
// Replace `.`, `(` and `?` with blank string like Github does // Replace `.`, `(` and `?` with blank string like Github does
.replace(/\.|\(|\?/g, '') .replace(/\.|\(|\?/g, '')

View file

@ -42,14 +42,14 @@ const GITHUB_HOST =
if (!ORGANIZATION_NAME) { if (!ORGANIZATION_NAME) {
shell.echo( shell.echo(
"Missing project organization name. Did you forget to define 'organizationName' in siteConfig.js? You may also export it via the ORGANIZATION_NAME environment variable." "Missing project organization name. Did you forget to define 'organizationName' in siteConfig.js? You may also export it via the ORGANIZATION_NAME environment variable.",
); );
shell.exit(0); shell.exit(0);
} }
if (!PROJECT_NAME) { if (!PROJECT_NAME) {
shell.echo( shell.echo(
"Missing project name. Did you forget to define 'projectName' in siteConfig.js? You may also export it via the PROJECT_NAME environment variable." "Missing project name. Did you forget to define 'projectName' in siteConfig.js? You may also export it via the PROJECT_NAME environment variable.",
); );
shell.exit(0); shell.exit(0);
} }
@ -71,7 +71,7 @@ const currentRepoUrl = shell
.exec('git config --get remote.origin.url') .exec('git config --get remote.origin.url')
.stdout.trim(); .stdout.trim();
const crossRepoPublish = !currentRepoUrl.endsWith( const crossRepoPublish = !currentRepoUrl.endsWith(
`${ORGANIZATION_NAME}/${PROJECT_NAME}.git` `${ORGANIZATION_NAME}/${PROJECT_NAME}.git`,
); );
// build static html files, then push to DEPLOYMENT_BRANCH branch of specified repo // build static html files, then push to DEPLOYMENT_BRANCH branch of specified repo
@ -160,7 +160,7 @@ fs.copy(
shell.exec('git add --all'); shell.exec('git add --all');
const commitResults = shell.exec( const commitResults = shell.exec(
`git commit -m "Deploy website" -m "Deploy website version based on ${currentCommit}"` `git commit -m "Deploy website" -m "Deploy website version based on ${currentCommit}"`,
); );
if (shell.exec(`git push origin ${DEPLOYMENT_BRANCH}`).code !== 0) { if (shell.exec(`git push origin ${DEPLOYMENT_BRANCH}`).code !== 0) {
shell.echo('Error: Git push failed'); shell.echo('Error: Git push failed');
@ -174,5 +174,5 @@ fs.copy(
shell.echo(`Website is live at: ${websiteURL}`); shell.echo(`Website is live at: ${websiteURL}`);
shell.exit(0); shell.exit(0);
} }
} },
); );

View file

@ -47,8 +47,8 @@ if (
) { ) {
console.error( console.error(
`${chalk.yellow( `${chalk.yellow(
'Version numbers are not properly specified!' 'Version numbers are not properly specified!',
)}\nSpecify as command line arguments: the current version you wish to rename, then the version number you want to rename it to. ` )}\nSpecify as command line arguments: the current version you wish to rename, then the version number you want to rename it to. `,
); );
process.exit(1); process.exit(1);
} }
@ -57,8 +57,8 @@ if (
if (!fs.existsSync(`${CWD}/versions.json`)) { if (!fs.existsSync(`${CWD}/versions.json`)) {
console.error( console.error(
`${chalk.yellow( `${chalk.yellow(
'No versions found!' 'No versions found!',
)}\nNo versions.json file currently exists. Use the \`versions\` script if you wish to create new versions.` )}\nNo versions.json file currently exists. Use the \`versions\` script if you wish to create new versions.`,
); );
process.exit(1); process.exit(1);
} }
@ -70,8 +70,8 @@ const versionIndex = versions.indexOf(currentVersion);
if (versionIndex < 0) { if (versionIndex < 0) {
console.error( console.error(
`${chalk.yellow( `${chalk.yellow(
`Version ${currentVersion} does not currently exist!` `Version ${currentVersion} does not currently exist!`,
)}\n Version ${currentVersion} is not in the versions.json file. You can only rename existing versions.` )}\n Version ${currentVersion} is not in the versions.json file. You can only rename existing versions.`,
); );
process.exit(1); process.exit(1);
} }
@ -79,7 +79,7 @@ if (versionIndex < 0) {
versions[versionIndex] = newVersion; versions[versionIndex] = newVersion;
fs.writeFileSync( fs.writeFileSync(
`${CWD}/versions.json`, `${CWD}/versions.json`,
`${JSON.stringify(versions, null, 2)}\n` `${JSON.stringify(versions, null, 2)}\n`,
); );
// if folder of docs for this version exists, rename folder and rewrite doc // if folder of docs for this version exists, rename folder and rewrite doc
@ -87,7 +87,7 @@ fs.writeFileSync(
if (fs.existsSync(`${CWD}/versioned_docs/version-${currentVersion}`)) { if (fs.existsSync(`${CWD}/versioned_docs/version-${currentVersion}`)) {
fs.renameSync( fs.renameSync(
`${CWD}/versioned_docs/version-${currentVersion}`, `${CWD}/versioned_docs/version-${currentVersion}`,
`${CWD}/versioned_docs/version-${newVersion}` `${CWD}/versioned_docs/version-${newVersion}`,
); );
const files = glob.sync(`${CWD}/versioned_docs/version-${newVersion}/*`); const files = glob.sync(`${CWD}/versioned_docs/version-${newVersion}/*`);
@ -104,7 +104,7 @@ if (fs.existsSync(`${CWD}/versioned_docs/version-${currentVersion}`)) {
} }
metadata.id = metadata.id.replace( metadata.id = metadata.id.replace(
`version-${currentVersion}-`, `version-${currentVersion}-`,
`version-${newVersion}-` `version-${newVersion}-`,
); );
fs.writeFileSync(file, makeHeader(metadata) + rawContent); fs.writeFileSync(file, makeHeader(metadata) + rawContent);
}); });
@ -119,13 +119,13 @@ if (fs.existsSync(currentSidebarFile)) {
let sidebarContent = fs.readFileSync(newSidebarFile, 'utf8'); let sidebarContent = fs.readFileSync(newSidebarFile, 'utf8');
sidebarContent = sidebarContent.replace( sidebarContent = sidebarContent.replace(
new RegExp(`version-${escapeStringRegexp(currentVersion)}-`, 'g'), new RegExp(`version-${escapeStringRegexp(currentVersion)}-`, 'g'),
`version-${newVersion}-` `version-${newVersion}-`,
); );
fs.writeFileSync(newSidebarFile, sidebarContent); fs.writeFileSync(newSidebarFile, sidebarContent);
} }
console.log( console.log(
`${chalk.green('Successfully renamed version ')}${chalk.yellow( `${chalk.green('Successfully renamed version ')}${chalk.yellow(
currentVersion currentVersion,
)}${chalk.green(' to version ')}${chalk.yellow(newVersion)}\n` )}${chalk.green(' to version ')}${chalk.yellow(newVersion)}\n`,
); );

View file

@ -11,7 +11,7 @@ const blog = require('../blog');
const testFile = path.join( const testFile = path.join(
__dirname, __dirname,
'__fixtures__', '__fixtures__',
'2018-08-17-docusaurus.md' '2018-08-17-docusaurus.md',
); );
fs.existsSync = jest.fn().mockReturnValue(true); fs.existsSync = jest.fn().mockReturnValue(true);
@ -59,10 +59,10 @@ describe('urlToSource', () => {
}); });
test('valid url path', () => { test('valid url path', () => {
expect(blog.urlToSource(`${blog.fileToUrl(testFile)}`)).toEqual( expect(blog.urlToSource(`${blog.fileToUrl(testFile)}`)).toEqual(
'2018-08-17-docusaurus.md' '2018-08-17-docusaurus.md',
); );
expect(blog.urlToSource('2018/03/04/test-name-lol.html')).toEqual( expect(blog.urlToSource('2018/03/04/test-name-lol.html')).toEqual(
'2018-03-04-test-name-lol.md' '2018-03-04-test-name-lol.md',
); );
}); });
}); });

View file

@ -42,12 +42,12 @@ const Metadata = require(path.join(__dirname, '__fixtures__', 'metadata.js'));
const doc1 = fs.readFileSync( const doc1 = fs.readFileSync(
path.join(__dirname, '__fixtures__', 'doc1.md'), path.join(__dirname, '__fixtures__', 'doc1.md'),
'utf8' 'utf8',
); );
const doc2 = fs.readFileSync( const doc2 = fs.readFileSync(
path.join(__dirname, '__fixtures__', 'doc2.md'), path.join(__dirname, '__fixtures__', 'doc2.md'),
'utf8' 'utf8',
); );
const rawContent1 = metadataUtils.extractMetadata(doc1).rawContent; const rawContent1 = metadataUtils.extractMetadata(doc1).rawContent;
@ -60,7 +60,7 @@ describe('mdToHtmlify', () => {
const content1 = docs.mdToHtmlify( const content1 = docs.mdToHtmlify(
rawContent1, rawContent1,
mdToHtml, mdToHtml,
Metadata['en-doc1'] Metadata['en-doc1'],
); );
expect(content1).not.toContain('/docs/en/next/'); expect(content1).not.toContain('/docs/en/next/');
expect(content1).toMatchSnapshot(); expect(content1).toMatchSnapshot();
@ -71,7 +71,7 @@ describe('mdToHtmlify', () => {
const content2 = docs.mdToHtmlify( const content2 = docs.mdToHtmlify(
rawContent2, rawContent2,
mdToHtml, mdToHtml,
Metadata['en-doc2'] Metadata['en-doc2'],
); );
expect(content2).toContain('/docs/en/next/'); expect(content2).toContain('/docs/en/next/');
expect(content2).toMatchSnapshot(); expect(content2).toMatchSnapshot();
@ -108,21 +108,21 @@ describe('getFile', () => {
test('translated docs', () => { test('translated docs', () => {
const metadata = Metadata['ko-doc1']; const metadata = Metadata['ko-doc1'];
expect(docs.getFile(metadata)).toEqual( expect(docs.getFile(metadata)).toEqual(
fakeContent['website/translated_docs/ko/doc1.md'] fakeContent['website/translated_docs/ko/doc1.md'],
); );
}); });
test('versioned docs', () => { test('versioned docs', () => {
const metadata = Metadata['en-version-1.0.0-doc2']; const metadata = Metadata['en-version-1.0.0-doc2'];
expect(docs.getFile(metadata)).toEqual( expect(docs.getFile(metadata)).toEqual(
fakeContent['website/versioned_docs/version-1.0.0/doc2.md'] fakeContent['website/versioned_docs/version-1.0.0/doc2.md'],
); );
}); });
test('translated & versioned docs', () => { test('translated & versioned docs', () => {
const metadata = Metadata['ko-version-1.0.0-doc1']; const metadata = Metadata['ko-version-1.0.0-doc1'];
expect(docs.getFile(metadata)).toEqual( expect(docs.getFile(metadata)).toEqual(
fakeContent['website/translated_docs/ko/version-1.0.0/doc1.md'] fakeContent['website/translated_docs/ko/version-1.0.0/doc1.md'],
); );
}); });

View file

@ -52,7 +52,7 @@ describe('start live reload', () => {
const unusedPortError = new Error('no unused port'); const unusedPortError = new Error('no unused port');
portFinder.getPortPromise.mockRejectedValue(unusedPortError); portFinder.getPortPromise.mockRejectedValue(unusedPortError);
return expect(start.startLiveReloadServer()).rejects.toEqual( return expect(start.startLiveReloadServer()).rejects.toEqual(
unusedPortError unusedPortError,
); );
}); });
}); });

View file

@ -30,11 +30,11 @@ describe('server utils', () => {
test('minify css', () => { test('minify css', () => {
const testCss = fs.readFileSync( const testCss = fs.readFileSync(
path.join(__dirname, '__fixtures__', 'test.css'), path.join(__dirname, '__fixtures__', 'test.css'),
'utf8' 'utf8',
); );
const notCss = fs.readFileSync( const notCss = fs.readFileSync(
path.join(__dirname, '__fixtures__', 'test.md'), path.join(__dirname, '__fixtures__', 'test.md'),
'utf8' 'utf8',
); );
utils.minifyCss(testCss).then(css => expect(css).toMatchSnapshot()); utils.minifyCss(testCss).then(css => expect(css).toMatchSnapshot());
utils.minifyCss(notCss).catch(e => expect(e).toMatchSnapshot()); utils.minifyCss(notCss).catch(e => expect(e).toMatchSnapshot());
@ -43,7 +43,7 @@ describe('server utils', () => {
test('autoprefix css', () => { test('autoprefix css', () => {
const testCss = fs.readFileSync( const testCss = fs.readFileSync(
path.join(__dirname, '__fixtures__', 'test.css'), path.join(__dirname, '__fixtures__', 'test.css'),
'utf8' 'utf8',
); );
utils.autoPrefixCss(testCss).then(css => expect(css).toMatchSnapshot()); utils.autoPrefixCss(testCss).then(css => expect(css).toMatchSnapshot());
@ -56,14 +56,14 @@ describe('server utils', () => {
'translated_docs', 'translated_docs',
'ja', 'ja',
'en', 'en',
'test.md' 'test.md',
); );
const testDocInSubfolder = path.join('docs', 'ro', 'test.md'); const testDocInSubfolder = path.join('docs', 'ro', 'test.md');
const testDocNoLanguage = path.join('docs', 'test.md'); const testDocNoLanguage = path.join('docs', 'test.md');
expect(utils.getLanguage(testDocEnglish, 'translated_docs')).toBe('en'); expect(utils.getLanguage(testDocEnglish, 'translated_docs')).toBe('en');
expect(utils.getLanguage(testDocJapanese, 'translated_docs')).toBe('ja'); expect(utils.getLanguage(testDocJapanese, 'translated_docs')).toBe('ja');
expect( expect(
utils.getLanguage(testDocJapaneseInSubfolder, 'translated_docs') utils.getLanguage(testDocJapaneseInSubfolder, 'translated_docs'),
).toBe('ja'); ).toBe('ja');
expect(utils.getLanguage(testDocInSubfolder, 'docs')).toBeNull(); expect(utils.getLanguage(testDocInSubfolder, 'docs')).toBeNull();
expect(utils.getLanguage(testDocNoLanguage, 'docs')).toBeNull(); expect(utils.getLanguage(testDocNoLanguage, 'docs')).toBeNull();

View file

@ -53,11 +53,11 @@ function getMetadata(file) {
return null; return null;
} }
const result = metadataUtils.extractMetadata( const result = metadataUtils.extractMetadata(
fs.readFileSync(file, {encoding: 'utf8'}) fs.readFileSync(file, {encoding: 'utf8'}),
); );
const metadata = Object.assign( const metadata = Object.assign(
{path: fileToUrl(file), content: result.rawContent}, {path: fileToUrl(file), content: result.rawContent},
result.metadata result.metadata,
); );
metadata.id = metadata.title; metadata.id = metadata.title;
return metadata; return metadata;

View file

@ -67,11 +67,11 @@ function mdToHtmlify(oldContent, mdToHtml, metadata) {
'/VERSION/', '/VERSION/',
metadata.version && metadata.version !== env.versioning.latestVersion metadata.version && metadata.version !== env.versioning.latestVersion
? `/${metadata.version}/` ? `/${metadata.version}/`
: '/' : '/',
); );
content = content.replace( content = content.replace(
new RegExp(`\\]\\((\\./)?${mdLink}`, 'g'), new RegExp(`\\]\\((\\./)?${mdLink}`, 'g'),
`](${htmlLink}` `](${htmlLink}`,
); );
} }
}); });
@ -108,7 +108,7 @@ function getMarkup(rawContent, mdToHtml, metadata) {
language={metadata.language} language={metadata.language}
config={siteConfig}> config={siteConfig}>
{content} {content}
</DocsLayout> </DocsLayout>,
); );
} }
@ -124,7 +124,7 @@ function getRedirectMarkup(metadata) {
language={metadata.language} language={metadata.language}
config={siteConfig} config={siteConfig}
redirect={siteConfig.baseUrl + redirectlink} redirect={siteConfig.baseUrl + redirectlink}
/> />,
); );
} }

View file

@ -57,7 +57,7 @@ class Versioning {
console.error( console.error(
`${chalk.yellow('No versions.js file found!')}` + `${chalk.yellow('No versions.js file found!')}` +
`\nYou should create your versions.js file in pages/en directory.` + `\nYou should create your versions.js file in pages/en directory.` +
`\nPlease refer to https://docusaurus.io/docs/en/versioning.html.` `\nPlease refer to https://docusaurus.io/docs/en/versioning.html.`,
); );
} }

View file

@ -87,7 +87,7 @@ async function execute() {
} }
const redirectFile = join( const redirectFile = join(
buildDir, buildDir,
metadata.permalink.replace('docs/en', 'docs') metadata.permalink.replace('docs/en', 'docs'),
); );
writeFileAndCreateFolder(redirectFile, redirectMarkup); writeFileAndCreateFolder(redirectFile, redirectMarkup);
}); });
@ -96,7 +96,7 @@ async function execute() {
if (fs.existsSync(join(CWD, '..', readMetadata.getDocsPath(), 'assets'))) { if (fs.existsSync(join(CWD, '..', readMetadata.getDocsPath(), 'assets'))) {
fs.copySync( fs.copySync(
join(CWD, '..', readMetadata.getDocsPath(), 'assets'), join(CWD, '..', readMetadata.getDocsPath(), 'assets'),
join(buildDir, 'docs', 'assets') join(buildDir, 'docs', 'assets'),
); );
} }
@ -176,8 +176,8 @@ async function execute() {
) { ) {
console.error( console.error(
`${chalk.yellow( `${chalk.yellow(
'Missing color configuration.' 'Missing color configuration.',
)} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.` )} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.`,
); );
} }
@ -193,7 +193,7 @@ async function execute() {
.join(', '); .join(', ');
cssContent = cssContent.replace( cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'), new RegExp(`\\$${key}`, 'g'),
fontString fontString,
); );
}); });
} }
@ -234,7 +234,7 @@ async function execute() {
.join(', '); .join(', ');
cssContent = cssContent.replace( cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'), new RegExp(`\\$${key}`, 'g'),
fontString fontString,
); );
}); });
} }
@ -296,7 +296,7 @@ async function execute() {
let tempFile = join(__dirname, '..', 'pages', relativeFile); let tempFile = join(__dirname, '..', 'pages', relativeFile);
tempFile = tempFile.replace( tempFile = tempFile.replace(
path.basename(normalizedFile), path.basename(normalizedFile),
`temp${path.basename(normalizedFile)}` `temp${path.basename(normalizedFile)}`,
); );
mkdirp.sync(path.dirname(tempFile)); mkdirp.sync(path.dirname(tempFile));
fs.copySync(normalizedFile, tempFile); fs.copySync(normalizedFile, tempFile);
@ -308,8 +308,8 @@ async function execute() {
const regexLang = new RegExp( const regexLang = new RegExp(
`${escapeStringRegexp(`${userPagesDir}${sep}`)}(.*)${escapeStringRegexp( `${escapeStringRegexp(`${userPagesDir}${sep}`)}(.*)${escapeStringRegexp(
sep sep,
)}` )}`,
); );
const match = regexLang.exec(normalizedFile); const match = regexLang.exec(normalizedFile);
const langParts = match[1].split(sep); const langParts = match[1].split(sep);
@ -321,7 +321,7 @@ async function execute() {
if ( if (
language === 'en' || language === 'en' ||
!fs.existsSync( !fs.existsSync(
normalizedFile.replace(`${sep}en${sep}`, sep + language + sep) normalizedFile.replace(`${sep}en${sep}`, sep + language + sep),
) )
) { ) {
translate.setLanguage(language); translate.setLanguage(language);
@ -333,12 +333,12 @@ async function execute() {
description={ReactComp.description} description={ReactComp.description}
metadata={{id: pageID}}> metadata={{id: pageID}}>
<ReactComp language={language} /> <ReactComp language={language} />
</Site> </Site>,
); );
writeFileAndCreateFolder( writeFileAndCreateFolder(
// TODO: use path functions // TODO: use path functions
targetFile.replace(`${sep}en${sep}`, sep + language + sep), targetFile.replace(`${sep}en${sep}`, sep + language + sep),
str str,
); );
} }
} }
@ -354,11 +354,11 @@ async function execute() {
description={ReactComp.description} description={ReactComp.description}
metadata={{id: pageID}}> metadata={{id: pageID}}>
<ReactComp language={language} /> <ReactComp language={language} />
</Site> </Site>,
); );
writeFileAndCreateFolder( writeFileAndCreateFolder(
targetFile.replace(`${sep}en${sep}`, sep), targetFile.replace(`${sep}en${sep}`, sep),
str str,
); );
} else { } else {
// allow for rendering of other files not in pages/en folder // allow for rendering of other files not in pages/en folder
@ -372,11 +372,11 @@ async function execute() {
description={ReactComp.description} description={ReactComp.description}
metadata={{id: pageID}}> metadata={{id: pageID}}>
<ReactComp language={language} /> <ReactComp language={language} />
</Site> </Site>,
); );
writeFileAndCreateFolder( writeFileAndCreateFolder(
targetFile.replace(`${sep}en${sep}`, sep), targetFile.replace(`${sep}en${sep}`, sep),
str str,
); );
} }
fs.removeSync(tempFile); fs.removeSync(tempFile);
@ -390,7 +390,7 @@ async function execute() {
__html: fs.readFileSync(normalizedFile, {encoding: 'utf8'}), __html: fs.readFileSync(normalizedFile, {encoding: 'utf8'}),
}} }}
/> />
</Site> </Site>,
); );
writeFileAndCreateFolder(targetFile, str); writeFileAndCreateFolder(targetFile, str);

View file

@ -24,7 +24,7 @@ function start(port) {
this.on('all', () => { this.on('all', () => {
server.notifyClients(['/']); server.notifyClients(['/']);
}); });
} },
); );
reloadScriptUrl = `http://localhost:${port}/livereload.js`; reloadScriptUrl = `http://localhost:${port}/livereload.js`;

View file

@ -64,7 +64,7 @@ function readCategories(sidebar) {
}' not found. Make sure that all documents with ids specified in this version's sidebar file exist and that no ids are repeated.` }' not found. Make sure that all documents with ids specified in this version's sidebar file exist and that no ids are repeated.`
: `Improper sidebars.json file, document with id '${ : `Improper sidebars.json file, document with id '${
metadata.next metadata.next
}' not found. Make sure that documents with the ids specified in sidebars.json exist and that no ids are repeated.` }' not found. Make sure that documents with the ids specified in sidebars.json exist and that no ids are repeated.`,
); );
} }
previous[articles[metadata.next].id] = metadata.id; previous[articles[metadata.next].id] = metadata.id;

View file

@ -251,7 +251,7 @@ function generateMetadataDocs() {
if (order[id].next) { if (order[id].next) {
metadata.next_id = order[id].next.replace( metadata.next_id = order[id].next.replace(
`version-${metadata.version}-`, `version-${metadata.version}-`,
'' '',
); );
metadata.next = metadata.next =
(env.translation.enabled ? `${metadata.language}-` : '') + (env.translation.enabled ? `${metadata.language}-` : '') +
@ -260,7 +260,7 @@ function generateMetadataDocs() {
if (order[id].previous) { if (order[id].previous) {
metadata.previous_id = order[id].previous.replace( metadata.previous_id = order[id].previous.replace(
`version-${metadata.version}-`, `version-${metadata.version}-`,
'' '',
); );
metadata.previous = metadata.previous =
(env.translation.enabled ? `${metadata.language}-` : '') + (env.translation.enabled ? `${metadata.language}-` : '') +
@ -297,7 +297,7 @@ function generateMetadataDocs() {
' * @' + ' * @' +
'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`,
); );
} }
@ -323,7 +323,7 @@ function generateMetadataBlog() {
metadata.date = new Date( metadata.date = new Date(
`${filePathDateArr[0]}-${filePathDateArr[1]}-${ `${filePathDateArr[0]}-${filePathDateArr[1]}-${
filePathDateArr[2] filePathDateArr[2]
}T06:00:00.000Z` }T06:00:00.000Z`,
); );
// allow easier sorting of blog by providing seconds since epoch // allow easier sorting of blog by providing seconds since epoch
metadata.seconds = Math.round(metadata.date.getTime() / 1000); metadata.seconds = Math.round(metadata.date.getTime() / 1000);
@ -332,7 +332,7 @@ function generateMetadataBlog() {
}); });
const sortedMetadatas = metadatas.sort( const sortedMetadatas = metadatas.sort(
(a, b) => parseInt(b.seconds, 10) - parseInt(a.seconds, 10) (a, b) => parseInt(b.seconds, 10) - parseInt(a.seconds, 10),
); );
fs.writeFileSync( fs.writeFileSync(
@ -341,7 +341,7 @@ function generateMetadataBlog() {
' * @' + ' * @' +
'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

@ -27,7 +27,7 @@ function noExtension() {
function page(baseUrl) { function page(baseUrl) {
const gr = regex => regex.toString().replace(/(^\/|\/$)/gm, ''); const gr = regex => regex.toString().replace(/(^\/|\/$)/gm, '');
return new RegExp( return new RegExp(
`(?!${gr(docs(baseUrl))}|${gr(blog(baseUrl))})^${baseUrl}.*.html$` `(?!${gr(docs(baseUrl))}|${gr(blog(baseUrl))})^${baseUrl}.*.html$`,
); );
} }

View file

@ -186,8 +186,8 @@ function execute(port) {
fs.existsSync( fs.existsSync(
(htmlFile = htmlFile.replace( (htmlFile = htmlFile.replace(
path.basename(htmlFile), path.basename(htmlFile),
join('en', path.basename(htmlFile)) join('en', path.basename(htmlFile)),
)) )),
) )
) { ) {
if (siteConfig.wrapPagesHTML) { if (siteConfig.wrapPagesHTML) {
@ -203,7 +203,7 @@ function execute(port) {
__html: fs.readFileSync(htmlFile, {encoding: 'utf8'}), __html: fs.readFileSync(htmlFile, {encoding: 'utf8'}),
}} }}
/> />
</Site> </Site>,
); );
res.send(str); res.send(str);
@ -244,8 +244,8 @@ function execute(port) {
fs.existsSync( fs.existsSync(
(userFile = userFile.replace( (userFile = userFile.replace(
path.basename(userFile), path.basename(userFile),
`en${sep}${path.basename(userFile)}` `en${sep}${path.basename(userFile)}`,
)) )),
) || ) ||
fs.existsSync((userFile = englishFile)) fs.existsSync((userFile = englishFile))
) { ) {
@ -254,7 +254,7 @@ function execute(port) {
let tempFile = join(__dirname, '..', 'pages', userFileParts[1]); let tempFile = join(__dirname, '..', 'pages', userFileParts[1]);
tempFile = tempFile.replace( tempFile = tempFile.replace(
path.basename(file), path.basename(file),
`temp${path.basename(file)}` `temp${path.basename(file)}`,
); );
mkdirp.sync(path.dirname(tempFile)); mkdirp.sync(path.dirname(tempFile));
fs.copySync(userFile, tempFile); fs.copySync(userFile, tempFile);
@ -273,7 +273,7 @@ function execute(port) {
description={ReactComp.description} description={ReactComp.description}
metadata={{id: path.basename(userFile, '.js')}}> metadata={{id: path.basename(userFile, '.js')}}>
<ReactComp language={language} /> <ReactComp language={language} />
</Site> </Site>,
); );
fs.removeSync(tempFile); fs.removeSync(tempFile);
@ -289,7 +289,7 @@ function execute(port) {
__dirname, __dirname,
'..', '..',
'static', 'static',
req.path.toString().replace(siteConfig.baseUrl, '/') req.path.toString().replace(siteConfig.baseUrl, '/'),
); );
let cssContent = fs.readFileSync(mainCssPath, {encoding: 'utf8'}); let cssContent = fs.readFileSync(mainCssPath, {encoding: 'utf8'});
@ -311,8 +311,8 @@ function execute(port) {
) { ) {
console.error( console.error(
`${chalk.yellow( `${chalk.yellow(
'Missing color configuration.' 'Missing color configuration.',
)} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.` )} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.`,
); );
} }
@ -328,7 +328,7 @@ function execute(port) {
.join(', '); .join(', ');
cssContent = cssContent.replace( cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'), new RegExp(`\\$${key}`, 'g'),
fontString fontString,
); );
}); });
} }
@ -340,11 +340,11 @@ function execute(port) {
// serve static assets from these locations // serve static assets from these locations
app.use( app.use(
`${siteConfig.baseUrl}docs/assets`, `${siteConfig.baseUrl}docs/assets`,
express.static(join(CWD, '..', readMetadata.getDocsPath(), 'assets')) express.static(join(CWD, '..', readMetadata.getDocsPath(), 'assets')),
); );
app.use( app.use(
`${siteConfig.baseUrl}blog/assets`, `${siteConfig.baseUrl}blog/assets`,
express.static(join(CWD, 'blog', 'assets')) express.static(join(CWD, 'blog', 'assets')),
); );
app.use(siteConfig.baseUrl, express.static(join(CWD, 'static'))); app.use(siteConfig.baseUrl, express.static(join(CWD, 'static')));
app.use(siteConfig.baseUrl, express.static(join(__dirname, '..', 'static'))); app.use(siteConfig.baseUrl, express.static(join(__dirname, '..', 'static')));
@ -360,7 +360,7 @@ function execute(port) {
? `${requestUrl}.html` ? `${requestUrl}.html`
: requestUrl.replace(/\/$/, '.html'), : requestUrl.replace(/\/$/, '.html'),
res, res,
next next,
); );
}); });
}); });

View file

@ -31,14 +31,14 @@ module.exports = function translatePlugin(babel) {
t.jSXExpressionContainer( t.jSXExpressionContainer(
t.callExpression(t.identifier('translate'), [ t.callExpression(t.identifier('translate'), [
t.stringLiteral(`${text}|${description}`), t.stringLiteral(`${text}|${description}`),
]) ]),
) ),
); );
} else { } else {
path.replaceWith( path.replaceWith(
t.callExpression(t.identifier('translate'), [ t.callExpression(t.identifier('translate'), [
t.stringLiteral(`${text}|${description}`), t.stringLiteral(`${text}|${description}`),
]) ]),
); );
} }
}, },

View file

@ -47,13 +47,13 @@ function translate(str) {
// if a translated string doesn't exist, but english does then fallback // if a translated string doesn't exist, but english does then fallback
if (doesTranslationExist(str, 'en')) { if (doesTranslationExist(str, 'en')) {
console.error( console.error(
`Could not find a string translation in '${language}' for string '${str}'. Using English version instead.` `Could not find a string translation in '${language}' for string '${str}'. Using English version instead.`,
); );
return parseEscapeSequences(translation.en['pages-strings'][str]); return parseEscapeSequences(translation.en['pages-strings'][str]);
} }
throw new Error( throw new Error(
`Text that you've identified for translation ('${str}') hasn't been added to the global list in 'en.json'. To solve this problem run 'yarn write-translations'.` `Text that you've identified for translation ('${str}') hasn't been added to the global list in 'en.json'. To solve this problem run 'yarn write-translations'.`,
); );
} }
return parseEscapeSequences(translation[language]['pages-strings'][str]); return parseEscapeSequences(translation[language]['pages-strings'][str]);

View file

@ -20,7 +20,7 @@ function getLanguage(file, refDir) {
const separator = escapeStringRegexp(path.sep); const separator = escapeStringRegexp(path.sep);
const baseDir = escapeStringRegexp(path.basename(refDir)); const baseDir = escapeStringRegexp(path.basename(refDir));
const regexSubFolder = new RegExp( const regexSubFolder = new RegExp(
`${baseDir}${separator}(.*?)${separator}.*` `${baseDir}${separator}(.*?)${separator}.*`,
); );
const match = regexSubFolder.exec(file); const match = regexSubFolder.exec(file);

View file

@ -58,10 +58,10 @@ files.forEach(file => {
if (!metadata.original_id) { if (!metadata.original_id) {
console.error( console.error(
`No 'original_id' field found in ${file}. Perhaps you forgot to add it when importing prior versions of your docs?` `No 'original_id' field found in ${file}. Perhaps you forgot to add it when importing prior versions of your docs?`,
); );
throw new Error( throw new Error(
`No 'original_id' field found in ${file}. Perhaps you forgot to add it when importing prior versions of your docs?` `No 'original_id' field found in ${file}. Perhaps you forgot to add it when importing prior versions of your docs?`,
); );
} }
if (!metadata.id) { if (!metadata.id) {
@ -69,10 +69,10 @@ files.forEach(file => {
throw new Error(`No 'id' field found in ${file}.`); throw new Error(`No 'id' field found in ${file}.`);
} else if (metadata.id.indexOf('version-') === -1) { } else if (metadata.id.indexOf('version-') === -1) {
console.error( console.error(
`The 'id' field in ${file} is missing the expected 'version-XX-' prefix. Perhaps you forgot to add it when importing prior versions of your docs?` `The 'id' field in ${file} is missing the expected 'version-XX-' prefix. Perhaps you forgot to add it when importing prior versions of your docs?`,
); );
throw new Error( throw new Error(
`The 'id' field in ${file} is missing the expected 'version-XX-' prefix. Perhaps you forgot to add it when importing prior versions of your docs?` `The 'id' field in ${file} is missing the expected 'version-XX-' prefix. Perhaps you forgot to add it when importing prior versions of your docs?`,
); );
} }
@ -85,7 +85,7 @@ files.forEach(file => {
// e.g. version-1.0.0-getting-started => 1.0.0 // e.g. version-1.0.0-getting-started => 1.0.0
const version = metadata.id.substring( const version = metadata.id.substring(
metadata.id.indexOf('version-') + 8, // version- is 8 characters metadata.id.indexOf('version-') + 8, // version- is 8 characters
metadata.id.lastIndexOf(`-${metadata.original_id}`) metadata.id.lastIndexOf(`-${metadata.original_id}`),
); );
available[metadata.original_id].add(version); available[metadata.original_id].add(version);
@ -161,13 +161,13 @@ function processVersionMetadata(file, version, useVersion, language) {
// and original_id `readme` will have metadata id of `version-1.1.6-projectA/readme` and original_id `projectA/readme` // and original_id `readme` will have metadata id of `version-1.1.6-projectA/readme` and original_id `projectA/readme`
const subDir = utils.getSubDir( const subDir = utils.getSubDir(
file, file,
path.join(CWD, 'versioned_docs', `version-${useVersion}`) path.join(CWD, 'versioned_docs', `version-${useVersion}`),
); );
if (subDir) { if (subDir) {
metadata.original_id = `${subDir}/${metadata.original_id}`; metadata.original_id = `${subDir}/${metadata.original_id}`;
metadata.id = metadata.id.replace( metadata.id = metadata.id.replace(
`version-${useVersion}-`, `version-${useVersion}-`,
`version-${useVersion}-${subDir}/` `version-${useVersion}-${subDir}/`,
); );
} }
@ -188,7 +188,7 @@ function processVersionMetadata(file, version, useVersion, language) {
} }
metadata.id = metadata.id.replace( metadata.id = metadata.id.replace(
`version-${useVersion}-`, `version-${useVersion}-`,
`version-${version}-` `version-${version}-`,
); );
metadata.localized_id = metadata.id; metadata.localized_id = metadata.id;
metadata.id = (env.translation.enabled ? `${language}-` : '') + metadata.id; metadata.id = (env.translation.enabled ? `${language}-` : '') + metadata.id;
@ -225,7 +225,7 @@ function docData() {
const file = versionFiles[useVersion][id]; const file = versionFiles[useVersion][id];
metadatas.push( metadatas.push(
processVersionMetadata(file, version, useVersion, language.tag) processVersionMetadata(file, version, useVersion, language.tag),
); );
}); });
}); });
@ -246,14 +246,14 @@ function sidebarVersion(reqVersion) {
if ( if (
requestedFound && requestedFound &&
fs.existsSync( fs.existsSync(
`${CWD}/versioned_sidebars/version-${versions[i]}-sidebars.json` `${CWD}/versioned_sidebars/version-${versions[i]}-sidebars.json`,
) )
) { ) {
return versions[i]; return versions[i];
} }
} }
throw new Error( throw new Error(
`No sidebar file available to use for version ${reqVersion}. Verify that 'version-${reqVersion}-sidebars.json' exists.` `No sidebar file available to use for version ${reqVersion}. Verify that 'version-${reqVersion}-sidebars.json' exists.`,
); );
} }
@ -281,7 +281,7 @@ function diffLatestSidebar() {
return ( return (
JSON.stringify(JSON.parse(fs.readFileSync(latestSidebar, 'utf8'))).replace( JSON.stringify(JSON.parse(fs.readFileSync(latestSidebar, 'utf8'))).replace(
new RegExp(`version-${version}-`, 'g'), new RegExp(`version-${version}-`, 'g'),
'' '',
) !== JSON.stringify(JSON.parse(fs.readFileSync(currentSidebar, 'utf8'))) ) !== JSON.stringify(JSON.parse(fs.readFileSync(currentSidebar, 'utf8')))
); );
} }
@ -296,12 +296,12 @@ function sidebarData() {
fs fs
.readFileSync( .readFileSync(
`${CWD}/versioned_sidebars/version-${version}-sidebars.json`, `${CWD}/versioned_sidebars/version-${version}-sidebars.json`,
'utf8' 'utf8',
) )
.replace( .replace(
new RegExp(`version-${version}-`, 'g'), new RegExp(`version-${version}-`, 'g'),
`version-${versions[i]}-` `version-${versions[i]}-`,
) ),
); );
Object.assign(allSidebars, sidebar); Object.assign(allSidebars, sidebar);
} }

View file

@ -29,7 +29,7 @@ const {startDocusaurus} = require('./server/start.js');
if (!fs.existsSync(`${CWD}/siteConfig.js`)) { if (!fs.existsSync(`${CWD}/siteConfig.js`)) {
console.error( console.error(
chalk.red('Error: No siteConfig.js file found in website folder!') chalk.red('Error: No siteConfig.js file found in website folder!'),
); );
process.exit(1); process.exit(1);
} }

View file

@ -56,8 +56,8 @@ if (env.versioning.missingVersionsPage) {
if (typeof version === 'undefined') { if (typeof version === 'undefined') {
console.error( console.error(
`${chalk.yellow( `${chalk.yellow(
'No version number specified!' 'No version number specified!',
)}\nPass the version you wish to create as an argument.\nEx: 1.0.0` )}\nPass the version you wish to create as an argument.\nEx: 1.0.0`,
); );
process.exit(1); process.exit(1);
} }
@ -65,8 +65,8 @@ if (typeof version === 'undefined') {
if (versions.includes(version)) { if (versions.includes(version)) {
console.error( console.error(
`${chalk.yellow( `${chalk.yellow(
'This version already exists!' 'This version already exists!',
)}\nSpecify a new version to create that does not already exist.` )}\nSpecify a new version to create that does not already exist.`,
); );
process.exit(1); process.exit(1);
} }
@ -131,7 +131,7 @@ files.forEach(file => {
writeFileAndCreateFolder( writeFileAndCreateFolder(
targetFile, targetFile,
makeHeader(metadata) + rawContent, makeHeader(metadata) + rawContent,
'utf8' 'utf8',
); );
}); });
@ -159,7 +159,7 @@ if (versionFallback.diffLatestSidebar()) {
fs.writeFileSync( fs.writeFileSync(
`${CWD}/versioned_sidebars/version-${version}-sidebars.json`, `${CWD}/versioned_sidebars/version-${version}-sidebars.json`,
`${JSON.stringify(versioned, null, 2)}\n`, `${JSON.stringify(versioned, null, 2)}\n`,
'utf8' 'utf8',
); );
} }
@ -167,7 +167,7 @@ if (versionFallback.diffLatestSidebar()) {
versions.unshift(version); versions.unshift(version);
fs.writeFileSync( fs.writeFileSync(
`${CWD}/versions.json`, `${CWD}/versions.json`,
`${JSON.stringify(versions, null, 2)}\n` `${JSON.stringify(versions, null, 2)}\n`,
); );
console.log(`${chalk.green(`Version ${version} created!\n`)}`); console.log(`${chalk.green(`Version ${version} created!\n`)}`);

View file

@ -45,9 +45,9 @@ let customTranslations = {
if (fs.existsSync(`${CWD}/data/custom-translation-strings.json`)) { if (fs.existsSync(`${CWD}/data/custom-translation-strings.json`)) {
customTranslations = deepmerge( customTranslations = deepmerge(
JSON.parse( JSON.parse(
fs.readFileSync(`${CWD}/data/custom-translation-strings.json`, 'utf8') fs.readFileSync(`${CWD}/data/custom-translation-strings.json`, 'utf8'),
), ),
customTranslations customTranslations,
); );
} }
@ -121,7 +121,7 @@ function execute() {
if (!file.endsWith('-sidebars.json')) { if (!file.endsWith('-sidebars.json')) {
if (file.endsWith('-sidebar.json')) { if (file.endsWith('-sidebar.json')) {
console.warn( console.warn(
`Skipping ${file}. Make sure your sidebar filenames follow this format: 'version-VERSION-sidebars.json'.` `Skipping ${file}. Make sure your sidebar filenames follow this format: 'version-VERSION-sidebars.json'.`,
); );
} }
return; return;
@ -185,11 +185,11 @@ function execute() {
] = 'Translate'; ] = 'Translate';
translations['pages-strings'] = Object.assign( translations['pages-strings'] = Object.assign(
translations['pages-strings'], translations['pages-strings'],
customTranslations['pages-strings'] customTranslations['pages-strings'],
); );
translations['localized-strings'] = deepmerge( translations['localized-strings'] = deepmerge(
translations['localized-strings'], translations['localized-strings'],
customTranslations['localized-strings'] customTranslations['localized-strings'],
); );
writeFileAndCreateFolder( writeFileAndCreateFolder(
`${CWD}/i18n/en.json`, `${CWD}/i18n/en.json`,
@ -198,11 +198,11 @@ function execute() {
{ {
_comment: 'This file is auto-generated by write-translations.js', _comment: 'This file is auto-generated by write-translations.js',
}, },
translations translations,
), ),
null, null,
2 2,
)}\n` )}\n`,
); );
} }

View file

@ -3,28 +3,17 @@
"description": "Easy to Maintain Open Source Documentation Websites", "description": "Easy to Maintain Open Source Documentation Websites",
"version": "1.4.0", "version": "1.4.0",
"license": "MIT", "license": "MIT",
"keywords": [ "keywords": ["documentation", "websites", "open source", "docusaurus"],
"documentation",
"websites",
"open source",
"docusaurus"
],
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/facebook/Docusaurus.git" "url": "https://github.com/facebook/Docusaurus.git"
}, },
"scripts": { "scripts": {
"ci-check": "yarn lint && yarn prettier:diff", "ci-check": "yarn lint && yarn prettier:diff",
"format:source": "prettier --config .prettierrc --write \"lib/**/*.js\"",
"format:examples": "prettier --config .prettierrc --write \"examples/**/*.js\"",
"format:website": "prettier --config .prettierrc --write \"website/**/*.js\"",
"lint": "eslint --cache \"lib/**/*.js\" \"examples/**/*.js\" \"website/**/*.js\"", "lint": "eslint --cache \"lib/**/*.js\" \"examples/**/*.js\" \"website/**/*.js\"",
"nit:source": "prettier --config .prettierrc --list-different \"lib/**/*.js\"",
"nit:examples": "prettier --config .prettierrc --list-different \"examples/**/*.js\"",
"nit:website": "prettier --config .prettierrc --list-different \"website/**/*.js\"",
"precommit": "lint-staged", "precommit": "lint-staged",
"prettier": "yarn format:source && yarn format:examples && yarn format:website", "prettier": "prettier --config .prettierrc --write \"**/*.js\"",
"prettier:diff": "yarn nit:source && yarn nit:examples && yarn nit:website", "prettier:diff": "prettier --config .prettierrc --list-different \"**/*.js\"",
"test": "jest", "test": "jest",
"start": "cd website && yarn start", "start": "cd website && yarn start",
"postinstall": "opencollective postinstall" "postinstall": "opencollective postinstall"
@ -39,11 +28,7 @@
} }
}, },
"jest": { "jest": {
"testPathIgnorePatterns": [ "testPathIgnorePatterns": ["/node_modules/", "__fixtures__", "v2"],
"/node_modules/",
"__fixtures__",
"v2"
],
"testURL": "http://localhost/" "testURL": "http://localhost/"
}, },
"bin": { "bin": {

View file

@ -1,3 +0,0 @@
generated
__fixtures__
dist

View file

@ -1,8 +0,0 @@
{
"bracketSpacing": false,
"jsxBracketSameLine": true,
"parser": "flow",
"printWidth": 80,
"proseWrap": "never",
"singleQuote": true
}

View file

@ -13,8 +13,8 @@ if (!semver.satisfies(process.version, requiredVersion)) {
chalk.yellow( chalk.yellow(
`\nYou are using Node ${ `\nYou are using Node ${
process.version process.version
}, Requirement: Node ${requiredVersion}.\n` }, Requirement: Node ${requiredVersion}.\n`,
) ),
); );
process.exit(1); process.exit(1);
} }
@ -36,7 +36,7 @@ program
.description('Build website') .description('Build website')
.option( .option(
'-sic, --skip-image-compression <skipImageCompression>', '-sic, --skip-image-compression <skipImageCompression>',
'Skip compression of image assets (default: false)' 'Skip compression of image assets (default: false)',
) )
.action((siteDir = '.', {skipImageCompression}) => { .action((siteDir = '.', {skipImageCompression}) => {
wrapCommand(build)(path.resolve(siteDir), {skipImageCompression}); wrapCommand(build)(path.resolve(siteDir), {skipImageCompression});

View file

@ -42,7 +42,7 @@ module.exports = async function build(siteDir, cliOptions = {}) {
// apply user webpack config // apply user webpack config
const { const {
siteConfig: {configureWebpack} siteConfig: {configureWebpack},
} = props; } = props;
clientConfig = applyConfigureWebpack(configureWebpack, clientConfig, false); clientConfig = applyConfigureWebpack(configureWebpack, clientConfig, false);
serverConfig = applyConfigureWebpack(configureWebpack, serverConfig, true); serverConfig = applyConfigureWebpack(configureWebpack, serverConfig, true);
@ -58,20 +58,20 @@ module.exports = async function build(siteDir, cliOptions = {}) {
const {outDir} = props; const {outDir} = props;
const staticDir = path.resolve(siteDir, 'static'); const staticDir = path.resolve(siteDir, 'static');
const staticFiles = await globby(['**'], { const staticFiles = await globby(['**'], {
cwd: staticDir cwd: staticDir,
}); });
await Promise.all( await Promise.all(
staticFiles.map(async source => { staticFiles.map(async source => {
const fromPath = path.resolve(staticDir, source); const fromPath = path.resolve(staticDir, source);
const toPath = path.resolve(outDir, source); const toPath = path.resolve(outDir, source);
return fs.copy(fromPath, toPath); return fs.copy(fromPath, toPath);
}) }),
); );
const relativeDir = path.relative(process.cwd(), outDir); const relativeDir = path.relative(process.cwd(), outDir);
console.log( console.log(
`\n${chalk.green('Success!')} Generated static files in ${chalk.cyan( `\n${chalk.green('Success!')} Generated static files in ${chalk.cyan(
relativeDir relativeDir,
)}.\n` )}.\n`,
); );
}; };

View file

@ -10,7 +10,7 @@ module.exports = async function eject(siteDir) {
const relativeDir = path.relative(process.cwd(), customTheme); const relativeDir = path.relative(process.cwd(), customTheme);
console.log( console.log(
`\n${chalk.green('Success!')} Copied default theme files to ${chalk.cyan( `\n${chalk.green('Success!')} Copied default theme files to ${chalk.cyan(
relativeDir relativeDir,
)}.\n` )}.\n`,
); );
}; };

View file

@ -44,8 +44,8 @@ module.exports = async function start(siteDir, cliOptions = {}) {
[`../${docsRelativeDir}/**/*.md`, 'blog/**/*.md', 'siteConfig.js'], [`../${docsRelativeDir}/**/*.md`, 'blog/**/*.md', 'siteConfig.js'],
{ {
cwd: siteDir, cwd: siteDir,
ignoreInitial: true ignoreInitial: true,
} },
); );
fsWatcher.on('add', reload); fsWatcher.on('add', reload);
fsWatcher.on('change', reload); fsWatcher.on('change', reload);
@ -69,14 +69,14 @@ module.exports = async function start(siteDir, cliOptions = {}) {
hash: true, hash: true,
template: path.resolve(__dirname, '../core/devTemplate.ejs'), template: path.resolve(__dirname, '../core/devTemplate.ejs'),
filename: 'index.html', filename: 'index.html',
title: siteConfig.title title: siteConfig.title,
} },
]); ]);
config = config.toConfig(); config = config.toConfig();
// apply user webpack config // apply user webpack config
const { const {
siteConfig: {configureWebpack} siteConfig: {configureWebpack},
} = props; } = props;
config = applyConfigureWebpack(configureWebpack, config, false); config = applyConfigureWebpack(configureWebpack, config, false);
@ -90,11 +90,11 @@ module.exports = async function start(siteDir, cliOptions = {}) {
compiler, compiler,
open: true, open: true,
devMiddleware: { devMiddleware: {
logLevel: 'silent' logLevel: 'silent',
}, },
hotClient: { hotClient: {
port: hotPort, port: hotPort,
logLevel: 'error' logLevel: 'error',
}, },
logLevel: 'error', logLevel: 'error',
port, port,
@ -113,12 +113,12 @@ module.exports = async function start(siteDir, cliOptions = {}) {
app.use( app.use(
convert( convert(
history({ history({
rewrites: [{from: /\.html$/, to: '/'}] rewrites: [{from: /\.html$/, to: '/'}],
}) }),
) ),
); );
} },
} },
); );
}, 1000); }, 1000);
}; };

View file

@ -11,5 +11,5 @@ export default () =>
docsMetadatas, docsMetadatas,
docsSidebars, docsSidebars,
pagesMetadatas, pagesMetadatas,
siteConfig siteConfig,
}); });

View file

@ -13,7 +13,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
<BrowserRouter> <BrowserRouter>
<App /> <App />
</BrowserRouter>, </BrowserRouter>,
document.getElementById('app') document.getElementById('app'),
); );
}); });
} }

View file

@ -13,6 +13,6 @@ export default function prerender(routeConfig, providedLocation) {
return component.preload(); return component.preload();
} }
return undefined; return undefined;
}) }),
); );
} }

View file

@ -15,7 +15,7 @@ export default function render(locals) {
const appHtml = ReactDOMServer.renderToString( const appHtml = ReactDOMServer.renderToString(
<StaticRouter location={locals.path} context={context}> <StaticRouter location={locals.path} context={context}>
<App /> <App />
</StaticRouter> </StaticRouter>,
); );
const helmet = Helmet.renderStatic(); const helmet = Helmet.renderStatic();
@ -24,7 +24,7 @@ export default function render(locals) {
const metaStrings = [ const metaStrings = [
helmet.title.toString(), helmet.title.toString(),
helmet.meta.toString(), helmet.meta.toString(),
helmet.link.toString() helmet.link.toString(),
]; ];
const metaHtml = metaStrings.filter(Boolean).join('\n '); const metaHtml = metaStrings.filter(Boolean).join('\n ');
@ -42,14 +42,14 @@ export default function render(locals) {
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
${cssFiles.map( ${cssFiles.map(
cssFile => cssFile =>
`<link rel="stylesheet" type="text/css" href="${baseUrl}${cssFile}" />` `<link rel="stylesheet" type="text/css" href="${baseUrl}${cssFile}" />`,
)} )}
</head> </head>
<body${bodyAttributes ? ` ${bodyAttributes}` : ''}> <body${bodyAttributes ? ` ${bodyAttributes}` : ''}>
<div id="app">${appHtml}</div> <div id="app">${appHtml}</div>
${jsFiles.map( ${jsFiles.map(
jsFile => jsFile =>
`<script type="text/javascript" src="${baseUrl}${jsFile}"></script>` `<script type="text/javascript" src="${baseUrl}${jsFile}"></script>`,
)} )}
</body> </body>
</html> </html>

View file

@ -7,5 +7,5 @@ module.exports = {
build, build,
eject, eject,
init, init,
start start,
}; };

View file

@ -16,7 +16,7 @@ module.exports = function loadConfig(siteDir, deleteCache = true) {
'tagline', 'tagline',
'organizationName', 'organizationName',
'projectName', 'projectName',
'baseUrl' 'baseUrl',
]; ];
const optionalFields = [ const optionalFields = [
'customDocsPath', 'customDocsPath',
@ -26,19 +26,19 @@ module.exports = function loadConfig(siteDir, deleteCache = true) {
'configureWebpack', 'configureWebpack',
'chainWebpack', 'chainWebpack',
'docsUrl', 'docsUrl',
'customFields' 'customFields',
]; ];
const missingFields = requiredFields.filter(field => !config[field]); const missingFields = requiredFields.filter(field => !config[field]);
if (missingFields && missingFields.length > 0) { if (missingFields && missingFields.length > 0) {
throw new Error( throw new Error(
`${missingFields.join(', ')} fields are missing in siteConfig.js` `${missingFields.join(', ')} fields are missing in siteConfig.js`,
); );
} }
/* Fill default value */ /* Fill default value */
const defaultConfig = { const defaultConfig = {
customDocsPath: 'docs', customDocsPath: 'docs',
docsUrl: 'docs' docsUrl: 'docs',
}; };
Object.keys(defaultConfig).forEach(field => { Object.keys(defaultConfig).forEach(field => {
if (!config[field]) { if (!config[field]) {
@ -55,11 +55,11 @@ module.exports = function loadConfig(siteDir, deleteCache = true) {
/* We don't allow useless/ not meaningful field */ /* We don't allow useless/ not meaningful field */
const allowedFields = [...requiredFields, ...optionalFields, ...customFields]; const allowedFields = [...requiredFields, ...optionalFields, ...customFields];
const uselessFields = Object.keys(config).filter( const uselessFields = Object.keys(config).filter(
field => !allowedFields.includes(field) field => !allowedFields.includes(field),
); );
if (uselessFields && uselessFields.length > 0) { if (uselessFields && uselessFields.length > 0) {
throw new Error( throw new Error(
`${uselessFields.join(', ')} fields are useless in siteConfig.js` `${uselessFields.join(', ')} fields are useless in siteConfig.js`,
); );
} }

View file

@ -28,7 +28,7 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
/* metadata for default docs files */ /* metadata for default docs files */
const docsFiles = await globby(['**/*.md'], { const docsFiles = await globby(['**/*.md'], {
cwd: docsDir cwd: docsDir,
}); });
await Promise.all( await Promise.all(
docsFiles.map(async source => { docsFiles.map(async source => {
@ -47,17 +47,17 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
docsDir, docsDir,
env, env,
order, order,
siteConfig siteConfig,
); );
docsMetadatas[metadata.id] = metadata; docsMetadatas[metadata.id] = metadata;
}) }),
); );
/* metadata for non-default-language docs */ /* metadata for non-default-language docs */
if (translationEnabled) { if (translationEnabled) {
const translatedDir = path.join(siteDir, 'translated_docs'); const translatedDir = path.join(siteDir, 'translated_docs');
const translatedFiles = await globby(['**/*.md'], { const translatedFiles = await globby(['**/*.md'], {
cwd: translatedDir cwd: translatedDir,
}); });
await Promise.all( await Promise.all(
translatedFiles.map(async source => { translatedFiles.map(async source => {
@ -79,10 +79,10 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
translatedDir, translatedDir,
env, env,
order, order,
siteConfig siteConfig,
); );
docsMetadatas[metadata.id] = metadata; docsMetadatas[metadata.id] = metadata;
}) }),
); );
} }
@ -90,7 +90,7 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
if (versioningEnabled) { if (versioningEnabled) {
const versionedDir = path.join(siteDir, 'versioned_docs'); const versionedDir = path.join(siteDir, 'versioned_docs');
const versionedFiles = await globby(['**/*.md'], { const versionedFiles = await globby(['**/*.md'], {
cwd: versionedDir cwd: versionedDir,
}); });
await Promise.all( await Promise.all(
versionedFiles.map(async source => { versionedFiles.map(async source => {
@ -99,10 +99,10 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
versionedDir, versionedDir,
env, env,
order, order,
siteConfig siteConfig,
); );
docsMetadatas[metadata.id] = metadata; docsMetadatas[metadata.id] = metadata;
}) }),
); );
} }
@ -122,7 +122,7 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
return { return {
docsSidebars, docsSidebars,
docsMetadatas docsMetadatas,
}; };
} }

View file

@ -41,7 +41,7 @@ module.exports = async function processMetadata(
refDir, refDir,
env, env,
order, order,
siteConfig siteConfig,
) { ) {
const filepath = path.resolve(refDir, source); const filepath = path.resolve(refDir, source);
const fileString = await fs.readFile(filepath, 'utf-8'); const fileString = await fs.readFile(filepath, 'utf-8');
@ -131,7 +131,7 @@ module.exports = async function processMetadata(
.replace(/:docsUrl/, docsUrl) .replace(/:docsUrl/, docsUrl)
.replace(/:langPart/, langPart) .replace(/:langPart/, langPart)
.replace(/:versionPart/, versionPart) .replace(/:versionPart/, versionPart)
.replace(/:id/, metadata.id) .replace(/:id/, metadata.id),
); );
} else { } else {
metadata.permalink = `${baseUrl}${docsUrl}/${langPart}${versionPart}${ metadata.permalink = `${baseUrl}${docsUrl}/${langPart}${versionPart}${

View file

@ -28,7 +28,7 @@ module.exports = function createOrder(allSidebars = {}) {
previous, previous,
next, next,
sidebar, sidebar,
category: categoryOrder[i] category: categoryOrder[i],
}; };
} }
}); });

View file

@ -19,7 +19,7 @@ module.exports = function loadSidebars({siteDir, env}) {
const versionedSidebarsJSONFile = path.join( const versionedSidebarsJSONFile = path.join(
siteDir, siteDir,
'versioned_sidebars', 'versioned_sidebars',
`version-${version}-sidebars.json` `version-${version}-sidebars.json`,
); );
if (fs.existsSync(versionedSidebarsJSONFile)) { if (fs.existsSync(versionedSidebarsJSONFile)) {
const sidebar = require(versionedSidebarsJSONFile); // eslint-disable-line const sidebar = require(versionedSidebarsJSONFile); // eslint-disable-line

View file

@ -7,7 +7,7 @@ module.exports = function loadEnv({siteDir, siteConfig}) {
const translation = { const translation = {
enabled: false, enabled: false,
enabledLanguages: [], enabledLanguages: [],
defaultLanguage: {} defaultLanguage: {},
}; };
const languagesFile = path.join(siteDir, 'languages.js'); const languagesFile = path.join(siteDir, 'languages.js');
@ -24,11 +24,11 @@ module.exports = function loadEnv({siteDir, siteConfig}) {
/* Default Language */ /* Default Language */
const {defaultLanguage: defaultLanguageTag} = siteConfig; const {defaultLanguage: defaultLanguageTag} = siteConfig;
const defaultLanguage = enabledLanguages.find( const defaultLanguage = enabledLanguages.find(
lang => lang.tag === defaultLanguageTag lang => lang.tag === defaultLanguageTag,
); );
if (!defaultLanguage) { if (!defaultLanguage) {
throw new Error( throw new Error(
`Please set a default language in 'siteConfig.js' which is enabled in 'languages.js'` `Please set a default language in 'siteConfig.js' which is enabled in 'languages.js'`,
); );
} }
translation.defaultLanguage = defaultLanguage; translation.defaultLanguage = defaultLanguage;
@ -41,7 +41,7 @@ module.exports = function loadEnv({siteDir, siteConfig}) {
enabled: false, enabled: false,
latestVersion: null, latestVersion: null,
defaultVersion: null, defaultVersion: null,
versions: [] versions: [],
}; };
const versionsJSONFile = path.join(siteDir, 'versions.json'); const versionsJSONFile = path.join(siteDir, 'versions.json');
@ -55,6 +55,6 @@ module.exports = function loadEnv({siteDir, siteConfig}) {
return { return {
translation, translation,
versioning versioning,
}; };
}; };

View file

@ -12,7 +12,7 @@ module.exports = async function load(siteDir) {
const siteConfig = loadConfig(siteDir); const siteConfig = loadConfig(siteDir);
await generate( await generate(
'siteConfig.js', 'siteConfig.js',
`export default ${JSON.stringify(siteConfig, null, 2)};` `export default ${JSON.stringify(siteConfig, null, 2)};`,
); );
// @tested - env // @tested - env
@ -24,15 +24,15 @@ module.exports = async function load(siteDir) {
siteDir, siteDir,
docsDir, docsDir,
env, env,
siteConfig siteConfig,
}); });
await generate( await generate(
'docsMetadatas.js', 'docsMetadatas.js',
`export default ${JSON.stringify(docsMetadatas, null, 2)};` `export default ${JSON.stringify(docsMetadatas, null, 2)};`,
); );
await generate( await generate(
'docsSidebars.js', 'docsSidebars.js',
`export default ${JSON.stringify(docsSidebars, null, 2)};` `export default ${JSON.stringify(docsSidebars, null, 2)};`,
); );
/* Create source to metadata mapping */ /* Create source to metadata mapping */
@ -42,9 +42,9 @@ module.exports = async function load(siteDir) {
sourceToMetadata[source] = { sourceToMetadata[source] = {
version, version,
permalink, permalink,
language language,
}; };
} },
); );
// pages // pages
@ -52,7 +52,7 @@ module.exports = async function load(siteDir) {
const pagesMetadatas = await loadPages(pagesDir); const pagesMetadatas = await loadPages(pagesDir);
await generate( await generate(
'pagesMetadatas.js', 'pagesMetadatas.js',
`export default ${JSON.stringify(pagesMetadatas, null, 2)};` `export default ${JSON.stringify(pagesMetadatas, null, 2)};`,
); );
// resolve outDir // resolve outDir
@ -79,7 +79,7 @@ module.exports = async function load(siteDir) {
baseUrl, baseUrl,
sourceToMetadata, sourceToMetadata,
versionedDir, versionedDir,
translatedDir translatedDir,
}; };
// Generate React Router Config // Generate React Router Config

View file

@ -3,14 +3,14 @@ const {encodePath, fileToPath} = require('./utils');
async function loadPages(pagesDir) { async function loadPages(pagesDir) {
const pagesFiles = await globby(['**/*.js'], { const pagesFiles = await globby(['**/*.js'], {
cwd: pagesDir cwd: pagesDir,
}); });
const pagesMetadatas = await Promise.all( const pagesMetadatas = await Promise.all(
pagesFiles.map(async source => ({ pagesFiles.map(async source => ({
path: encodePath(fileToPath(source)), path: encodePath(fileToPath(source)),
source source,
})) })),
); );
return pagesMetadatas; return pagesMetadatas;
} }

View file

@ -11,7 +11,7 @@ module.exports = function loadConfig(siteDir) {
themeComponents.forEach(component => { themeComponents.forEach(component => {
if (!require.resolve(path.join(themePath, component))) { if (!require.resolve(path.join(themePath, component))) {
throw new Error( throw new Error(
`Failed to load ${themePath}/${component}. It does not exist.` `Failed to load ${themePath}/${component}. It does not exist.`,
); );
} }
}); });

View file

@ -55,7 +55,7 @@ function getSubFolder(file, refDir) {
const separator = escapeStringRegexp(path.sep); const separator = escapeStringRegexp(path.sep);
const baseDir = escapeStringRegexp(path.basename(refDir)); const baseDir = escapeStringRegexp(path.basename(refDir));
const regexSubFolder = new RegExp( const regexSubFolder = new RegExp(
`${baseDir}${separator}(.*?)${separator}.*` `${baseDir}${separator}(.*?)${separator}.*`,
); );
const match = regexSubFolder.exec(file); const match = regexSubFolder.exec(file);
return match && match[1]; return match && match[1];
@ -77,5 +77,5 @@ module.exports = {
fileToComponentName, fileToComponentName,
getSubFolder, getSubFolder,
idx, idx,
parse parse,
}; };

View file

@ -24,7 +24,7 @@ export default class Docs extends React.Component {
const linkMetadata = docsMetadatas[linkID]; const linkMetadata = docsMetadatas[linkID];
if (!linkMetadata) { if (!linkMetadata) {
throw new Error( throw new Error(
`Improper sidebars.json file, document with id '${linkID}' not found.` `Improper sidebars.json file, document with id '${linkID}' not found.`,
); );
} }
const linkClassName = const linkClassName =
@ -50,7 +50,7 @@ export default class Docs extends React.Component {
siteConfig, siteConfig,
docsMetadatas, docsMetadatas,
docsSidebars, docsSidebars,
metadata metadata,
} = this.props; } = this.props;
return ( return (
<Layout {...this.props}> <Layout {...this.props}>

View file

@ -7,7 +7,7 @@ export default class Layout extends React.Component {
render() { render() {
const {children, pagesMetadatas, docsMetadatas = {}, location} = this.props; const {children, pagesMetadatas, docsMetadatas = {}, location} = this.props;
const docsLinks = Object.values(docsMetadatas).map(data => ({ const docsLinks = Object.values(docsMetadatas).map(data => ({
path: `${data.permalink}` path: `${data.permalink}`,
})); }));
const routeLinks = [...pagesMetadatas, ...docsLinks].map( const routeLinks = [...pagesMetadatas, ...docsLinks].map(
data => data =>
@ -15,7 +15,7 @@ export default class Layout extends React.Component {
<li key={data.path}> <li key={data.path}>
<Link to={data.path}>{data.path}</Link> <Link to={data.path}>{data.path}</Link>
</li> </li>
) ),
); );
return ( return (
<div> <div>

View file

@ -14,8 +14,8 @@ export default (str, rawLang) => {
} catch (e) { } catch (e) {
console.error( console.error(
chalk.yellow( chalk.yellow(
`Highlight.js syntax highlighting for language "${lang}" is not supported.` `Highlight.js syntax highlighting for language "${lang}" is not supported.`,
) ),
); );
} }
return hljs.highlightAuto(str).value; return hljs.highlightAuto(str).value;

View file

@ -12,7 +12,7 @@ class MarkdownBlock extends React.Component {
return ( return (
<span <span
dangerouslySetInnerHTML={{ dangerouslySetInnerHTML={{
__html: this.renderMarkdown(this.props.source) __html: this.renderMarkdown(this.props.source),
}} }}
/> />
); );
@ -31,14 +31,14 @@ class MarkdownBlock extends React.Component {
renderMarkdown(source) { renderMarkdown(source) {
const alias = { const alias = {
js: 'jsx' js: 'jsx',
}; };
const {siteConfig} = this.props; const {siteConfig} = this.props;
const md = new Markdown({ const md = new Markdown({
langPrefix: 'hljs css language-', langPrefix: 'hljs css language-',
highlight: highlight, highlight: highlight,
html: true, html: true,
linkify: true linkify: true,
}); });
// Register anchors plugin // Register anchors plugin
@ -64,9 +64,9 @@ class MarkdownBlock extends React.Component {
{}, {},
{ {
version: '9.12.0', version: '9.12.0',
theme: 'default' theme: 'default',
}, },
siteConfig.highlight siteConfig.highlight,
); );
// Use user-provided themeUrl if it exists, else construct one from version and theme. // Use user-provided themeUrl if it exists, else construct one from version and theme.
@ -88,7 +88,7 @@ class MarkdownBlock extends React.Component {
} }
MarkdownBlock.defaultProps = { MarkdownBlock.defaultProps = {
siteConfig: {} siteConfig: {},
}; };
export default MarkdownBlock; export default MarkdownBlock;

View file

@ -31,7 +31,7 @@ module.exports = (string, context = {}) => {
.toLowerCase() .toLowerCase()
// Handle accentuated characters // Handle accentuated characters
.replace(new RegExp(`[${accents}]`, 'g'), c => .replace(new RegExp(`[${accents}]`, 'g'), c =>
without.charAt(accents.indexOf(c)) without.charAt(accents.indexOf(c)),
) )
// Replace `.`, `(` and `?` with blank string like Github does // Replace `.`, `(` and `?` with blank string like Github does
.replace(/\.|\(|\?/g, '') .replace(/\.|\(|\?/g, '')

View file

@ -16,7 +16,7 @@ module.exports = function createBaseConfig(props, isServer) {
sourceToMetadata, sourceToMetadata,
versionedDir, versionedDir,
translatedDir, translatedDir,
baseUrl baseUrl,
} = props; } = props;
const config = new Config(); const config = new Config();
@ -52,7 +52,7 @@ module.exports = function createBaseConfig(props, isServer) {
.options({ .options({
babelrc: false, babelrc: false,
presets: ['env', 'react'], presets: ['env', 'react'],
plugins: [isServer ? 'dynamic-import-node' : 'syntax-dynamic-import'] plugins: [isServer ? 'dynamic-import-node' : 'syntax-dynamic-import'],
}); });
} }
@ -83,7 +83,7 @@ module.exports = function createBaseConfig(props, isServer) {
versionedDir, versionedDir,
translatedDir, translatedDir,
docsDir, docsDir,
sourceToMetadata sourceToMetadata,
}); });
const cssRule = config.module.rule('css').test(/\.css$/); const cssRule = config.module.rule('css').test(/\.css$/);
@ -103,15 +103,15 @@ module.exports = function createBaseConfig(props, isServer) {
importLoaders: 1, importLoaders: 1,
localIdentName: `[local]_[hash:base64:8]`, localIdentName: `[local]_[hash:base64:8]`,
sourceMap: !isProd, sourceMap: !isProd,
minimize: true minimize: true,
}); });
// mini-css-extract plugin // mini-css-extract plugin
config.plugin('extract-css').use(CSSExtractPlugin, [ config.plugin('extract-css').use(CSSExtractPlugin, [
{ {
filename: isProd ? '[name].[chunkhash].css' : '[name].css', filename: isProd ? '[name].[chunkhash].css' : '[name].css',
chunkFilename: isProd ? '[id].[chunkhash].css' : '[id].css' chunkFilename: isProd ? '[id].[chunkhash].css' : '[id].css',
} },
]); ]);
if (isProd) { if (isProd) {
@ -122,10 +122,10 @@ module.exports = function createBaseConfig(props, isServer) {
warnings: false, warnings: false,
compress: false, compress: false,
ecma: 6, ecma: 6,
mangle: true mangle: true,
}, },
sourceMap: true sourceMap: true,
}) }),
]); ]);
} }

View file

@ -8,7 +8,7 @@ module.exports = function(fileString) {
versionedDir, versionedDir,
docsDir, docsDir,
translatedDir, translatedDir,
sourceToMetadata sourceToMetadata,
} = options; } = options;
/* Extract content of markdown (without frontmatter) */ /* Extract content of markdown (without frontmatter) */

View file

@ -18,17 +18,17 @@ module.exports = function createServerConfig(props) {
// static site generator webpack plugin // static site generator webpack plugin
const docsLinks = Object.values(docsMetadatas).map(data => ({ const docsLinks = Object.values(docsMetadatas).map(data => ({
path: `${data.permalink}` path: `${data.permalink}`,
})); }));
const paths = [...docsLinks, ...pagesMetadatas].map(data => data.path); const paths = [...docsLinks, ...pagesMetadatas].map(data => data.path);
config.plugin('siteGenerator').use(staticSiteGenerator, [ config.plugin('siteGenerator').use(staticSiteGenerator, [
{ {
entry: 'main', entry: 'main',
locals: { locals: {
baseUrl: siteConfig.baseUrl baseUrl: siteConfig.baseUrl,
}, },
paths paths,
} },
]); ]);
// show compilation progress bar and build time // show compilation progress bar and build time

View file

@ -23,5 +23,5 @@ function applyChainWebpack(userChainWebpack, config, isServer) {
module.exports = { module.exports = {
applyConfigureWebpack, applyConfigureWebpack,
applyChainWebpack applyChainWebpack,
}; };

View file

@ -11,7 +11,6 @@
"start": "node bin/munseo start website", "start": "node bin/munseo start website",
"build": "node bin/munseo build website", "build": "node bin/munseo build website",
"eject": "node bin/munseo eject website", "eject": "node bin/munseo eject website",
"prettier": "prettier --config .prettierrc --write \"lib/**/*.js\" \"bin/**/*.js\" \"test/**/*.js\"",
"lint": "eslint --cache \"lib/**/*.js\" \"bin/**/*.js\" \"test/**/*.js\"", "lint": "eslint --cache \"lib/**/*.js\" \"bin/**/*.js\" \"test/**/*.js\"",
"test": "jest --config test/jest.config.js" "test": "jest --config test/jest.config.js"
}, },
@ -19,11 +18,7 @@
"type": "git", "type": "git",
"url": "git+https://github.com/endiliey/munseo.git" "url": "git+https://github.com/endiliey/munseo.git"
}, },
"keywords": [ "keywords": ["blog", "generator", "react"],
"blog",
"generator",
"react"
],
"author": "endiliey", "author": "endiliey",
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {

View file

@ -3,5 +3,5 @@ module.exports = {
tagline: 'This is not an ordinary site', tagline: 'This is not an ordinary site',
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'sakura', projectName: 'sakura',
baseUrl: '/sakura/' baseUrl: '/sakura/',
}; };

View file

@ -3,5 +3,5 @@ module.exports = {
tagline: 'Hello World', tagline: 'Hello World',
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
baseUrl: '/' baseUrl: '/',
}; };

View file

@ -4,5 +4,5 @@ module.exports = {
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
baseUrl: '/', baseUrl: '/',
defaultLanguage: 'en' defaultLanguage: 'en',
}; };

View file

@ -4,5 +4,5 @@ module.exports = {
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
baseUrl: '/', baseUrl: '/',
defaultLanguage: 'en' defaultLanguage: 'en',
}; };

View file

@ -3,5 +3,5 @@ module.exports = {
tagline: 'Hello World', tagline: 'Hello World',
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
baseUrl: '/' baseUrl: '/',
}; };

View file

@ -6,7 +6,7 @@ module.exports = {
testURL: 'http://localhost/', testURL: 'http://localhost/',
testEnvironment: 'node', testEnvironment: 'node',
moduleNameMapper: { moduleNameMapper: {
'^@lib/(.*)$': '<rootDir>/lib/$1' '^@lib/(.*)$': '<rootDir>/lib/$1',
}, },
testPathIgnorePatterns: ['/node_modules/', '__fixtures__'] testPathIgnorePatterns: ['/node_modules/', '__fixtures__'],
}; };

View file

@ -1,4 +1,4 @@
module.exports = { module.exports = {
title: 'Munseo', title: 'Munseo',
baseUrl: '/' baseUrl: '/',
}; };

View file

@ -3,5 +3,5 @@ module.exports = {
tagline: 'Hello World', tagline: 'Hello World',
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
baseUrl: '/' baseUrl: '/',
}; };

View file

@ -4,5 +4,5 @@ module.exports = {
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
baseUrl: '/', baseUrl: '/',
defaultLanguage: 'en' defaultLanguage: 'en',
}; };

View file

@ -4,5 +4,5 @@ module.exports = {
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
baseUrl: '/', baseUrl: '/',
defaultLanguage: 'en' defaultLanguage: 'en',
}; };

View file

@ -3,5 +3,5 @@ module.exports = {
tagline: 'Hello World', tagline: 'Hello World',
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
baseUrl: '/' baseUrl: '/',
}; };

View file

@ -7,5 +7,5 @@ module.exports = {
useLessField: 'what', useLessField: 'what',
superman: 'lol', superman: 'lol',
admin: 'endi', admin: 'endi',
customFields: ['admin', 'superman'] customFields: ['admin', 'superman'],
}; };

View file

@ -12,7 +12,7 @@ describe('loadConfig', () => {
docsUrl: 'docs', docsUrl: 'docs',
projectName: 'hello', projectName: 'hello',
tagline: 'Hello World', tagline: 'Hello World',
title: 'Hello' title: 'Hello',
}); });
expect(config).not.toEqual({}); expect(config).not.toEqual({});
}); });
@ -22,7 +22,7 @@ describe('loadConfig', () => {
expect(() => { expect(() => {
loadConfig(siteDir); loadConfig(siteDir);
}).toThrowErrorMatchingInlineSnapshot( }).toThrowErrorMatchingInlineSnapshot(
`"tagline, organizationName, projectName fields are missing in siteConfig.js"` `"tagline, organizationName, projectName fields are missing in siteConfig.js"`,
); );
}); });
@ -31,7 +31,7 @@ describe('loadConfig', () => {
expect(() => { expect(() => {
loadConfig(siteDir); loadConfig(siteDir);
}).toThrowErrorMatchingInlineSnapshot( }).toThrowErrorMatchingInlineSnapshot(
`"useLessField fields are useless in siteConfig.js"` `"useLessField fields are useless in siteConfig.js"`,
); );
}); });
@ -40,7 +40,7 @@ describe('loadConfig', () => {
expect(() => { expect(() => {
loadConfig(siteDir); loadConfig(siteDir);
}).toThrowErrorMatchingInlineSnapshot( }).toThrowErrorMatchingInlineSnapshot(
`"title, tagline, organizationName, projectName, baseUrl fields are missing in siteConfig.js"` `"title, tagline, organizationName, projectName, baseUrl fields are missing in siteConfig.js"`,
); );
}); });
}); });

View file

@ -17,7 +17,7 @@ describe('processMetadata', () => {
permalink: '/docs/foo/bar', permalink: '/docs/foo/bar',
source: '@docs/foo/bar.md', source: '@docs/foo/bar.md',
title: 'Bar', title: 'Bar',
version: undefined version: undefined,
}); });
expect(dataB).toEqual({ expect(dataB).toEqual({
id: 'hello', id: 'hello',
@ -26,7 +26,7 @@ describe('processMetadata', () => {
permalink: '/docs/hello', permalink: '/docs/hello',
source: '@docs/hello.md', source: '@docs/hello.md',
title: 'Hello, World !', title: 'Hello, World !',
version: undefined version: undefined,
}); });
}); });
@ -42,7 +42,7 @@ describe('processMetadata', () => {
permalink: '/docs/endiliey/permalink', permalink: '/docs/endiliey/permalink',
source: '@docs/permalink.md', source: '@docs/permalink.md',
title: 'Permalink', title: 'Permalink',
version: undefined version: undefined,
}); });
}); });
@ -61,7 +61,7 @@ describe('processMetadata', () => {
permalink: '/docs/1.0.0/foo/bar', permalink: '/docs/1.0.0/foo/bar',
source: '@versioned_docs/version-1.0.0/foo/bar.md', source: '@versioned_docs/version-1.0.0/foo/bar.md',
title: 'Bar', title: 'Bar',
version: '1.0.0' version: '1.0.0',
}); });
expect(dataB).toEqual({ expect(dataB).toEqual({
id: 'version-1.0.0-hello', id: 'version-1.0.0-hello',
@ -70,7 +70,7 @@ describe('processMetadata', () => {
permalink: '/docs/1.0.0/hello', permalink: '/docs/1.0.0/hello',
source: '@versioned_docs/version-1.0.0/hello.md', source: '@versioned_docs/version-1.0.0/hello.md',
title: 'Hello, World !', title: 'Hello, World !',
version: '1.0.0' version: '1.0.0',
}); });
}); });
@ -93,7 +93,7 @@ describe('processMetadata', () => {
permalink: '/docs/ko/1.0.0/foo/bar', permalink: '/docs/ko/1.0.0/foo/bar',
source: '@translated_docs/ko/version-1.0.0/foo/bar.md', source: '@translated_docs/ko/version-1.0.0/foo/bar.md',
title: 'Bar', title: 'Bar',
version: '1.0.0' version: '1.0.0',
}); });
expect(dataB).toEqual({ expect(dataB).toEqual({
id: 'ko-version-1.0.0-hello', id: 'ko-version-1.0.0-hello',
@ -102,7 +102,7 @@ describe('processMetadata', () => {
permalink: '/docs/ko/1.0.0/hello', permalink: '/docs/ko/1.0.0/hello',
source: '@translated_docs/ko/version-1.0.0/hello.md', source: '@translated_docs/ko/version-1.0.0/hello.md',
title: 'Hello, World !', title: 'Hello, World !',
version: '1.0.0' version: '1.0.0',
}); });
expect(dataC).toEqual({ expect(dataC).toEqual({
id: 'ko-version-1.0.1-foo/bar', id: 'ko-version-1.0.1-foo/bar',
@ -111,7 +111,7 @@ describe('processMetadata', () => {
permalink: '/docs/ko/foo/bar', permalink: '/docs/ko/foo/bar',
source: '@translated_docs/ko/version-1.0.1/foo/bar.md', source: '@translated_docs/ko/version-1.0.1/foo/bar.md',
title: 'Bar', title: 'Bar',
version: '1.0.1' version: '1.0.1',
}); });
expect(dataD).toEqual({ expect(dataD).toEqual({
id: 'ko-version-1.0.1-hello', id: 'ko-version-1.0.1-hello',
@ -120,7 +120,7 @@ describe('processMetadata', () => {
permalink: '/docs/ko/hello', permalink: '/docs/ko/hello',
source: '@translated_docs/ko/version-1.0.1/hello.md', source: '@translated_docs/ko/version-1.0.1/hello.md',
title: 'Hello, World !', title: 'Hello, World !',
version: '1.0.1' version: '1.0.1',
}); });
}); });
@ -139,7 +139,7 @@ describe('processMetadata', () => {
permalink: '/docs/ko/foo/bar', permalink: '/docs/ko/foo/bar',
source: '@translated_docs/ko/foo/bar.md', source: '@translated_docs/ko/foo/bar.md',
title: 'Bar', title: 'Bar',
version: undefined version: undefined,
}); });
expect(dataB).toEqual({ expect(dataB).toEqual({
id: 'ko-hello', id: 'ko-hello',
@ -148,7 +148,7 @@ describe('processMetadata', () => {
permalink: '/docs/ko/hello', permalink: '/docs/ko/hello',
source: '@translated_docs/ko/hello.md', source: '@translated_docs/ko/hello.md',
title: 'Hello, World !', title: 'Hello, World !',
version: undefined version: undefined,
}); });
}); });
}); });

View file

@ -5,75 +5,75 @@ describe('createOrder', () => {
const result = createOrder({ const result = createOrder({
docs: { docs: {
Category1: ['doc1', 'doc2'], Category1: ['doc1', 'doc2'],
Category2: ['doc3', 'doc4'] Category2: ['doc3', 'doc4'],
}, },
otherDocs: { otherDocs: {
Category1: ['doc5'] Category1: ['doc5'],
} },
}); });
expect(result).toEqual({ expect(result).toEqual({
doc1: { doc1: {
category: 'Category1', category: 'Category1',
next: 'doc2', next: 'doc2',
previous: undefined, previous: undefined,
sidebar: 'docs' sidebar: 'docs',
}, },
doc2: { doc2: {
category: 'Category1', category: 'Category1',
next: 'doc3', next: 'doc3',
previous: 'doc1', previous: 'doc1',
sidebar: 'docs' sidebar: 'docs',
}, },
doc3: { doc3: {
category: 'Category2', category: 'Category2',
next: 'doc4', next: 'doc4',
previous: 'doc2', previous: 'doc2',
sidebar: 'docs' sidebar: 'docs',
}, },
doc4: { doc4: {
category: 'Category2', category: 'Category2',
next: undefined, next: undefined,
previous: 'doc3', previous: 'doc3',
sidebar: 'docs' sidebar: 'docs',
}, },
doc5: { doc5: {
category: 'Category1', category: 'Category1',
next: undefined, next: undefined,
previous: undefined, previous: undefined,
sidebar: 'otherDocs' sidebar: 'otherDocs',
} },
}); });
}); });
test('should resolve docs from older versions', () => { test('should resolve docs from older versions', () => {
const result = createOrder({ const result = createOrder({
docs: { docs: {
Category1: ['doc1'] Category1: ['doc1'],
}, },
'version-1.2.3-docs': { 'version-1.2.3-docs': {
Category1: ['version-1.2.3-doc2'], Category1: ['version-1.2.3-doc2'],
Category2: ['version-1.2.3-doc1'] Category2: ['version-1.2.3-doc1'],
} },
}); });
expect(result).toEqual({ expect(result).toEqual({
doc1: { doc1: {
category: 'Category1', category: 'Category1',
next: undefined, next: undefined,
previous: undefined, previous: undefined,
sidebar: 'docs' sidebar: 'docs',
}, },
'version-1.2.3-doc1': { 'version-1.2.3-doc1': {
category: 'Category2', category: 'Category2',
next: undefined, next: undefined,
previous: 'version-1.2.3-doc2', previous: 'version-1.2.3-doc2',
sidebar: 'version-1.2.3-docs' sidebar: 'version-1.2.3-docs',
}, },
'version-1.2.3-doc2': { 'version-1.2.3-doc2': {
category: 'Category1', category: 'Category1',
next: 'version-1.2.3-doc1', next: 'version-1.2.3-doc1',
previous: undefined, previous: undefined,
sidebar: 'version-1.2.3-docs' sidebar: 'version-1.2.3-docs',
} },
}); });
}); });

View file

@ -21,8 +21,8 @@ describe('loadSidebars', () => {
const env = { const env = {
versioning: { versioning: {
enabled: true, enabled: true,
versions: ['1.0.1', '1.0.0'] versions: ['1.0.1', '1.0.0'],
} },
}; };
const siteDir = path.join(fixtures, 'versioned-site'); const siteDir = path.join(fixtures, 'versioned-site');
const result = loadSidebars({siteDir, env}); const result = loadSidebars({siteDir, env});
@ -33,14 +33,14 @@ describe('loadSidebars', () => {
const env = { const env = {
versioning: { versioning: {
enabled: true, enabled: true,
versions: ['2.0.0'] versions: ['2.0.0'],
} },
}; };
const siteDir = path.join(fixtures, 'versioned-site'); const siteDir = path.join(fixtures, 'versioned-site');
expect(() => { expect(() => {
loadSidebars({siteDir, env}); loadSidebars({siteDir, env});
}).toThrowErrorMatchingInlineSnapshot( }).toThrowErrorMatchingInlineSnapshot(
`"Failed to load versioned_sidebars/version-2.0.0-sidebars.json. It does not exist."` `"Failed to load versioned_sidebars/version-2.0.0-sidebars.json. It does not exist."`,
); );
}); });
}); });

View file

@ -9,7 +9,7 @@ describe('loadEnv', () => {
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
tagline: 'Hello World', tagline: 'Hello World',
title: 'Hello' title: 'Hello',
}; };
const env = loadEnv({siteDir, siteConfig}); const env = loadEnv({siteDir, siteConfig});
expect(env.versioning.enabled).toBe(false); expect(env.versioning.enabled).toBe(false);
@ -24,7 +24,7 @@ describe('loadEnv', () => {
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
tagline: 'Hello World', tagline: 'Hello World',
title: 'Hello' title: 'Hello',
}; };
const env = loadEnv({siteDir, siteConfig}); const env = loadEnv({siteDir, siteConfig});
expect(env.versioning.enabled).toBe(true); expect(env.versioning.enabled).toBe(true);
@ -40,7 +40,7 @@ describe('loadEnv', () => {
projectName: 'hello', projectName: 'hello',
tagline: 'Hello World', tagline: 'Hello World',
title: 'Hello', title: 'Hello',
defaultLanguage: 'en' defaultLanguage: 'en',
}; };
const env = loadEnv({siteDir, siteConfig}); const env = loadEnv({siteDir, siteConfig});
expect(env.versioning.enabled).toBe(false); expect(env.versioning.enabled).toBe(false);
@ -56,7 +56,7 @@ describe('loadEnv', () => {
projectName: 'hello', projectName: 'hello',
tagline: 'Hello World', tagline: 'Hello World',
title: 'Hello', title: 'Hello',
defaultLanguage: 'en' defaultLanguage: 'en',
}; };
const env = loadEnv({siteDir, siteConfig}); const env = loadEnv({siteDir, siteConfig});
expect(env.versioning.enabled).toBe(true); expect(env.versioning.enabled).toBe(true);
@ -71,12 +71,12 @@ describe('loadEnv', () => {
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
tagline: 'Hello World', tagline: 'Hello World',
title: 'Hello' title: 'Hello',
}; };
expect(() => { expect(() => {
loadEnv({siteDir, siteConfig}); loadEnv({siteDir, siteConfig});
}).toThrowErrorMatchingInlineSnapshot( }).toThrowErrorMatchingInlineSnapshot(
`"Please at least enable one language in 'languages.js'"` `"Please at least enable one language in 'languages.js'"`,
); );
}); });
@ -87,12 +87,12 @@ describe('loadEnv', () => {
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'hello', projectName: 'hello',
tagline: 'Hello World', tagline: 'Hello World',
title: 'Hello' title: 'Hello',
}; };
expect(() => { expect(() => {
loadEnv({siteDir, siteConfig}); loadEnv({siteDir, siteConfig});
}).toThrowErrorMatchingInlineSnapshot( }).toThrowErrorMatchingInlineSnapshot(
`"Please set a default language in 'siteConfig.js' which is enabled in 'languages.js'"` `"Please set a default language in 'siteConfig.js' which is enabled in 'languages.js'"`,
); );
}); });
}); });

View file

@ -9,20 +9,20 @@ describe('loadPages', () => {
expect(pagesMetadatas).toEqual([ expect(pagesMetadatas).toEqual([
{ {
path: '/', path: '/',
source: 'index.js' source: 'index.js',
}, },
{ {
path: '/bar/baz', path: '/bar/baz',
source: 'bar/baz.js' source: 'bar/baz.js',
}, },
{ {
path: '/foo', path: '/foo',
source: 'foo.js' source: 'foo.js',
}, },
{ {
path: '/foo/', path: '/foo/',
source: 'foo/index.js' source: 'foo/index.js',
} },
]); ]);
expect(pagesMetadatas).not.toBeNull(); expect(pagesMetadatas).not.toBeNull();
}); });

View file

@ -3,7 +3,7 @@ import {
fileToPath, fileToPath,
fileToComponentName, fileToComponentName,
idx, idx,
getSubFolder getSubFolder,
} from '@lib/load/utils'; } from '@lib/load/utils';
describe('load utils', () => { describe('load utils', () => {
@ -18,7 +18,7 @@ describe('load utils', () => {
'docusaurus/index.js': 'JSDocusaurusIndex', 'docusaurus/index.js': 'JSDocusaurusIndex',
'234.md': 'MD234', '234.md': 'MD234',
'2018-07-08-test.md': 'MD20180708Test', '2018-07-08-test.md': 'MD20180708Test',
'%asd.md': 'MDAsd' '%asd.md': 'MDAsd',
}; };
Object.keys(asserts).forEach(file => { Object.keys(asserts).forEach(file => {
expect(fileToComponentName(file)).toBe(asserts[file]); expect(fileToComponentName(file)).toBe(asserts[file]);
@ -34,7 +34,7 @@ describe('load utils', () => {
'index.js': '/', 'index.js': '/',
'hello/index.js': '/hello/', 'hello/index.js': '/hello/',
'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]);
@ -51,19 +51,19 @@ describe('load utils', () => {
{ {
enabled: true, enabled: true,
name: 'English', name: 'English',
tag: 'en' tag: 'en',
}, },
{ {
enabled: true, enabled: true,
name: '日本語', name: '日本語',
tag: 'ja' tag: 'ja',
} },
] ],
}, },
versioning: { versioning: {
enabled: false, enabled: false,
versions: [] versions: [],
} },
}; };
const test = {arr: [1, 2, 3]}; const test = {arr: [1, 2, 3]};
const variable = 'enabledLanguages'; const variable = 'enabledLanguages';
@ -73,12 +73,12 @@ describe('load utils', () => {
expect(idx(env, 'typo')).toBeUndefined(); expect(idx(env, 'typo')).toBeUndefined();
expect(idx(env, 'versioning')).toEqual({ expect(idx(env, 'versioning')).toEqual({
enabled: false, enabled: false,
versions: [] versions: [],
}); });
expect(idx(env, ['translation', 'enabled'])).toEqual(true); expect(idx(env, ['translation', 'enabled'])).toEqual(true);
expect(idx(env, ['translation', variable]).map(lang => lang.tag)).toEqual([ expect(idx(env, ['translation', variable]).map(lang => lang.tag)).toEqual([
'en', 'en',
'ja' 'ja',
]); ]);
expect(idx(test, ['arr', 0])).toEqual(1); expect(idx(test, ['arr', 0])).toEqual(1);
expect(idx(undefined)).toBeUndefined(); expect(idx(undefined)).toBeUndefined();

View file

@ -10,8 +10,8 @@ describe('extending generated webpack config', () => {
let config = { let config = {
output: { output: {
path: __dirname, path: __dirname,
filename: 'bundle.js' filename: 'bundle.js',
} },
}; };
/* eslint-disable */ /* eslint-disable */
@ -20,7 +20,7 @@ describe('extending generated webpack config', () => {
generatedConfig.entry = 'entry.js'; generatedConfig.entry = 'entry.js';
generatedConfig.output = { generatedConfig.output = {
path: path.join(__dirname, 'dist'), path: path.join(__dirname, 'dist'),
filename: 'new.bundle.js' filename: 'new.bundle.js',
}; };
} }
}; };
@ -31,8 +31,8 @@ describe('extending generated webpack config', () => {
entry: 'entry.js', entry: 'entry.js',
output: { output: {
path: path.join(__dirname, 'dist'), path: path.join(__dirname, 'dist'),
filename: 'new.bundle.js' filename: 'new.bundle.js',
} },
}); });
const errors = validate(config); const errors = validate(config);
@ -45,8 +45,8 @@ describe('extending generated webpack config', () => {
let config = { let config = {
output: { output: {
path: __dirname, path: __dirname,
filename: 'bundle.js' filename: 'bundle.js',
} },
}; };
/* eslint-disable */ /* eslint-disable */
@ -54,8 +54,8 @@ describe('extending generated webpack config', () => {
entry: 'entry.js', entry: 'entry.js',
output: { output: {
path: path.join(__dirname, 'dist'), path: path.join(__dirname, 'dist'),
filename: 'new.bundle.js' filename: 'new.bundle.js',
} },
}; };
/* eslint-enable */ /* eslint-enable */
@ -64,8 +64,8 @@ describe('extending generated webpack config', () => {
entry: 'entry.js', entry: 'entry.js',
output: { output: {
path: path.join(__dirname, 'dist'), path: path.join(__dirname, 'dist'),
filename: 'new.bundle.js' filename: 'new.bundle.js',
} },
}); });
const errors = validate(config); const errors = validate(config);
expect(errors.length).toBe(0); expect(errors.length).toBe(0);
@ -95,11 +95,11 @@ describe('extending generated webpack config', () => {
expect(config).toEqual({ expect(config).toEqual({
output: { output: {
path: path.join(__dirname, 'dist'), path: path.join(__dirname, 'dist'),
filename: 'new.bundle.js' filename: 'new.bundle.js',
}, },
entry: { entry: {
main: ['./entry.js'] main: ['./entry.js'],
} },
}); });
const errors = validate(config); const errors = validate(config);
expect(errors.length).toBe(0); expect(errors.length).toBe(0);

View file

@ -10,11 +10,11 @@ class Game extends React.Component {
this.state = { this.state = {
history: [ history: [
{ {
squares: Array(9).fill(null) squares: Array(9).fill(null),
} },
], ],
stepNumber: 0, stepNumber: 0,
xIsNext: true xIsNext: true,
}; };
} }
@ -27,7 +27,7 @@ class Game extends React.Component {
[1, 4, 7], [1, 4, 7],
[2, 5, 8], [2, 5, 8],
[0, 4, 8], [0, 4, 8],
[2, 4, 6] [2, 4, 6],
]; ];
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i]; const [a, b, c] = lines[i];
@ -53,18 +53,18 @@ class Game extends React.Component {
this.setState({ this.setState({
history: history.concat([ history: history.concat([
{ {
squares: squares squares: squares,
} },
]), ]),
stepNumber: history.length, stepNumber: history.length,
xIsNext: !this.state.xIsNext xIsNext: !this.state.xIsNext,
}); });
} }
jumpTo(step) { jumpTo(step) {
this.setState({ this.setState({
stepNumber: step, stepNumber: step,
xIsNext: step % 2 === 0 xIsNext: step % 2 === 0,
}); });
} }

View file

@ -9,7 +9,7 @@ export default class TodoItem extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
editText: props.todo.title editText: props.todo.title,
}; };
this.handleEdit = this.handleEdit.bind(this); this.handleEdit = this.handleEdit.bind(this);
this.handleSubmit = this.handleSubmit.bind(this); this.handleSubmit = this.handleSubmit.bind(this);
@ -68,7 +68,7 @@ export default class TodoItem extends React.Component {
<li <li
className={classNames({ className={classNames({
completed: this.props.todo.completed, completed: this.props.todo.completed,
editing: this.props.editing editing: this.props.editing,
})}> })}>
<div className="view"> <div className="view">
<input <input

View file

@ -17,33 +17,33 @@ const todos = [
{ {
id: 'ed0bcc48-bbbe-5f06-c7c9-2ccb0456ceba', id: 'ed0bcc48-bbbe-5f06-c7c9-2ccb0456ceba',
title: 'Build this Todo App.', title: 'Build this Todo App.',
completed: true completed: true,
}, },
{ {
id: '42582304-3c6e-311e-7f88-7e3791caf88c', id: '42582304-3c6e-311e-7f88-7e3791caf88c',
title: '?????', title: '?????',
completed: true completed: true,
}, },
{ {
id: '1cf63885-5f75-8deb-19dc-9b6765deae6c', id: '1cf63885-5f75-8deb-19dc-9b6765deae6c',
title: '1,000 stars on GitHub.', title: '1,000 stars on GitHub.',
completed: false completed: false,
}, },
{ {
id: '63a871b2-0b6f-4427-9c35-304bc680a4b7', id: '63a871b2-0b6f-4427-9c35-304bc680a4b7',
title: 'Write a popular medium post.', title: 'Write a popular medium post.',
completed: false completed: false,
}, },
{ {
id: '63a871b2-0b6f-4422-9c35-304bc680a4b7', id: '63a871b2-0b6f-4422-9c35-304bc680a4b7',
title: 'Contribute to open source.', title: 'Contribute to open source.',
completed: false completed: false,
}, },
{ {
id: '036af7f9-1181-fb8f-258f-3f06034c020f', id: '036af7f9-1181-fb8f-258f-3f06034c020f',
title: 'Write a blog post.', title: 'Write a blog post.',
completed: false completed: false,
} },
]; ];
class TodoApp extends React.Component { class TodoApp extends React.Component {
@ -53,7 +53,7 @@ class TodoApp extends React.Component {
this.state = { this.state = {
editing: null, editing: null,
newTodo: '', newTodo: '',
todos: todos todos: todos,
}; };
} }
@ -75,9 +75,9 @@ class TodoApp extends React.Component {
todos: this.state.todos.concat({ todos: this.state.todos.concat({
id: uuid(), id: uuid(),
title: val, title: val,
completed: false completed: false,
}), }),
newTodo: '' newTodo: '',
}); });
} }
} }
@ -86,8 +86,8 @@ class TodoApp extends React.Component {
const {checked} = event.target; const {checked} = event.target;
this.setState({ this.setState({
todos: this.state.todos.map(todo => todos: this.state.todos.map(todo =>
Object.assign({}, todo, {completed: checked}) Object.assign({}, todo, {completed: checked}),
) ),
}); });
} }
@ -96,17 +96,17 @@ class TodoApp extends React.Component {
todos: this.state.todos.map(todo => { todos: this.state.todos.map(todo => {
if (todo === todoToToggle) { if (todo === todoToToggle) {
return Object.assign({}, todo, { return Object.assign({}, todo, {
completed: !todo.completed completed: !todo.completed,
}); });
} }
return todo; return todo;
}) }),
}); });
} }
destroy(passedTodo) { destroy(passedTodo) {
this.setState({ this.setState({
todos: this.state.todos.filter(todo => todo !== passedTodo) todos: this.state.todos.filter(todo => todo !== passedTodo),
}); });
} }
@ -119,12 +119,12 @@ class TodoApp extends React.Component {
todos: this.state.todos.map(todo => { todos: this.state.todos.map(todo => {
if (todo === todoToSave) { if (todo === todoToSave) {
return Object.assign({}, todo, { return Object.assign({}, todo, {
title: text title: text,
}); });
} }
return todo; return todo;
}), }),
editing: null editing: null,
}); });
} }
@ -134,7 +134,7 @@ class TodoApp extends React.Component {
clearCompleted() { clearCompleted() {
this.setState({ this.setState({
todos: this.state.todos.filter(todo => !todo.completed) todos: this.state.todos.filter(todo => !todo.completed),
}); });
} }
@ -144,7 +144,7 @@ class TodoApp extends React.Component {
const activeTodoCount = todos.reduce( const activeTodoCount = todos.reduce(
(accum, todo) => (todo.completed ? accum : accum + 1), (accum, todo) => (todo.completed ? accum : accum + 1),
0 0,
); );
if (todos.length) { if (todos.length) {

View file

@ -9,8 +9,8 @@ export default class Player extends React.Component {
height: '390', height: '390',
width: '640', width: '640',
playerVars: { playerVars: {
autoplay: 1 autoplay: 1,
} },
}; };
return ( return (
@ -19,8 +19,8 @@ export default class Player extends React.Component {
<title>My Youtube</title> <title>My Youtube</title>
</Helmet> </Helmet>
<p align="center"> <p align="center">
{/* this is a React-youtube component */ } {/* this is a React-youtube component */}
<YouTube videoId="d9IxdwEFk1c" opts={opts} onReady={this._onReady} /> <YouTube videoId="d9IxdwEFk1c" opts={opts} onReady={this._onReady} />
</p> </p>
</Layout> </Layout>
); );

View file

@ -3,5 +3,5 @@ module.exports = {
tagline: '📝⚡️ Transform your document (문서) to a website', tagline: '📝⚡️ Transform your document (문서) to a website',
organizationName: 'endiliey', organizationName: 'endiliey',
projectName: 'munseo', projectName: 'munseo',
baseUrl: '/' baseUrl: '/',
}; };

View file

@ -95,7 +95,7 @@ function Versions(props) {
</a> </a>
</td> </td>
</tr> </tr>
) ),
)} )}
</tbody> </tbody>
</table> </table>

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