ESLintify Part 2 (#841)

* ESLintify Part 2

* Fix

* Fix tests

* Fix tests

* Fix tests
This commit is contained in:
Yangshun Tay 2018-07-10 21:53:08 -07:00 committed by GitHub
parent 4267337fb0
commit 5ac2cee658
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
42 changed files with 188 additions and 190 deletions

View file

@ -12,39 +12,30 @@ module.exports = {
parser: 'babel-eslint', parser: 'babel-eslint',
extends: ['airbnb', 'prettier'], extends: ['airbnb', 'prettier'],
rules: { rules: {
// allow console 'no-console': OFF, // We have console.error, console.warn, etc.
'no-console': OFF,
// require radix argument in parseInt
radix: ERROR, radix: ERROR,
'class-methods-use-this': OFF, 'class-methods-use-this': OFF,
'react/no-multi-comp': OFF,
'import/no-extraneous-dependencies': OFF,
'react/no-danger': OFF,
'no-empty': [ERROR, {allowEmptyCatch: true}], 'no-empty': [ERROR, {allowEmptyCatch: true}],
'no-param-reassign': OFF,
'no-plusplus': OFF,
'import/no-extraneous-dependencies': OFF,
'react/jsx-closing-bracket-location': OFF, // Formatting is left to Prettier.
'react/jsx-filename-extension': OFF, // Enable in future when migrating.
'react/no-danger': OFF, // Need this to inject scripts.
'react/no-multi-comp': OFF, // One component per file creates too many files.
'react/no-unescaped-entities': [ERROR, {forbid: ['>', '}']}],
// Existing ESLint errors sorted by frequency, silencing first. // Existing ESLint errors sorted by frequency, silencing first.
'react/button-has-type': OFF, // 1 'react/button-has-type': OFF, // 1
'react/forbid-prop-types': OFF, // 1 'react/forbid-prop-types': OFF, // 1
'react/require-default-props': OFF, // 1 'react/require-default-props': OFF, // 1
'jsx-a11y/anchor-is-valid': OFF, // 9 'jsx-a11y/anchor-is-valid': OFF, // 9
'arrow-body-style': OFF, // 10
'react/jsx-curly-brace-presence': OFF, // 11
'react/no-unescaped-entities': OFF, // 12
'no-param-reassign': OFF, // 12
'spaced-comment': OFF, // 14
'import/no-unresolved': OFF, // 15 'import/no-unresolved': OFF, // 15
'object-shorthand': OFF, // 16
'dot-notation': OFF, // 19
'react/prefer-stateless-function': OFF, // 22 'react/prefer-stateless-function': OFF, // 22
'no-plusplus': OFF, // 23
'prefer-arrow-callback': OFF, // 30 'prefer-arrow-callback': OFF, // 30
'react/jsx-filename-extension': OFF, // 31
'import/newline-after-import': OFF, // 31
'react/jsx-closing-bracket-location': OFF, // 36
'func-names': OFF, // 37 'func-names': OFF, // 37
'import/no-dynamic-require': OFF, // 46 'import/no-dynamic-require': OFF, // 46
'prefer-destructuring': OFF, // 69 'prefer-destructuring': OFF, // 69
'prefer-const': OFF, // 71
'global-require': OFF, // 85 'global-require': OFF, // 85
'react/jsx-one-expression-per-line': OFF, // 129 'react/jsx-one-expression-per-line': OFF, // 129
'react/prop-types': OFF, // 197 'react/prop-types': OFF, // 197

View file

@ -8,6 +8,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js'); const CompLibrary = require('../../core/CompLibrary.js');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock; const GridBlock = CompLibrary.GridBlock;
@ -19,7 +20,7 @@ function docUrl(doc, language) {
class Help extends React.Component { class Help extends React.Component {
render() { render() {
let language = this.props.language || ''; const language = this.props.language || '';
const supportLinks = [ const supportLinks = [
{ {
content: `Learn more using the [documentation on this site.](${docUrl( content: `Learn more using the [documentation on this site.](${docUrl(

View file

@ -8,6 +8,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js'); const CompLibrary = require('../../core/CompLibrary.js');
const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */ const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock; const GridBlock = CompLibrary.GridBlock;
@ -73,7 +74,7 @@ const PromoSection = props => (
class HomeSplash extends React.Component { class HomeSplash extends React.Component {
render() { render() {
let language = this.props.language || ''; const language = this.props.language || '';
return ( return (
<SplashContainer> <SplashContainer>
<Logo img_src={imgUrl('docusaurus.svg')} /> <Logo img_src={imgUrl('docusaurus.svg')} />
@ -179,7 +180,7 @@ const Showcase = props => {
return ( return (
<div className="productShowcaseSection paddingBottom"> <div className="productShowcaseSection paddingBottom">
<h2>Who's Using This?</h2> <h2>Who is Using This?</h2>
<p>This project is used by all these people</p> <p>This project is used by all these people</p>
<div className="logos">{showcase}</div> <div className="logos">{showcase}</div>
<div className="more-users"> <div className="more-users">
@ -193,7 +194,7 @@ const Showcase = props => {
class Index extends React.Component { class Index extends React.Component {
render() { render() {
let language = this.props.language || ''; const language = this.props.language || '';
return ( return (
<div> <div>

View file

@ -8,6 +8,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js'); const CompLibrary = require('../../core/CompLibrary.js');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const siteConfig = require(process.cwd() + '/siteConfig.js'); const siteConfig = require(process.cwd() + '/siteConfig.js');
@ -30,7 +31,7 @@ class Users extends React.Component {
<Container padding={['bottom', 'top']}> <Container padding={['bottom', 'top']}>
<div className="showcaseSection"> <div className="showcaseSection">
<div className="prose"> <div className="prose">
<h1>Who's Using This?</h1> <h1>Who is Using This?</h1>
<p>This project is used by many folks</p> <p>This project is used by many folks</p>
</div> </div>
<div className="logos">{showcase}</div> <div className="logos">{showcase}</div>

View file

@ -5,10 +5,10 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
// See https://docusaurus.io/docs/site-config.html for all the possible // See https://docusaurus.io/docs/site-config for all the possible
// site configuration options. // site configuration options.
/* List of projects/orgs using your project for the users page */ // List of projects/orgs using your project for the users page.
const users = [ const users = [
{ {
caption: 'User1', caption: 'User1',
@ -21,10 +21,10 @@ const users = [
]; ];
const siteConfig = { const siteConfig = {
title: 'Test Site' /* title for your website */, title: 'Test Site', // Title for your website.
tagline: 'A website for testing', tagline: 'A website for testing',
url: 'https://your-docusaurus-test-site.com' /* your website url */, url: 'https://your-docusaurus-test-site.com', // Your website URL
baseUrl: '/' /* base url for your project */, baseUrl: '/', // Base URL for your project */
// For github.io type URLs, you would set the url and baseUrl like: // For github.io type URLs, you would set the url and baseUrl like:
// url: 'https://facebook.github.io', // url: 'https://facebook.github.io',
// baseUrl: '/test-site/', // baseUrl: '/test-site/',
@ -52,14 +52,15 @@ const siteConfig = {
footerIcon: 'img/docusaurus.svg', footerIcon: 'img/docusaurus.svg',
favicon: 'img/favicon.png', favicon: 'img/favicon.png',
/* colors for website */ /* Colors for website */
colors: { colors: {
primaryColor: '#2E8555', primaryColor: '#2E8555',
secondaryColor: '#205C3B', secondaryColor: '#205C3B',
}, },
/* custom fonts for website */ /* Custom fonts for website */
/*fonts: { /*
fonts: {
myFont: [ myFont: [
"Times New Roman", "Times New Roman",
"Serif" "Serif"
@ -68,26 +69,29 @@ const siteConfig = {
"-apple-system", "-apple-system",
"system-ui" "system-ui"
] ]
},*/ },
*/
// This copyright info is used in /core/Footer.js and blog rss/atom feeds. // This copyright info is used in /core/Footer.js and blog RSS/Atom feeds.
copyright: copyright:
'Copyright © ' + 'Copyright © ' +
new Date().getFullYear() + new Date().getFullYear() +
' Your Name or Your Company Name', ' Your Name or Your Company Name',
highlight: { highlight: {
// Highlight.js theme to use for syntax highlighting in code blocks // Highlight.js theme to use for syntax highlighting in code blocks.
theme: 'default', theme: 'default',
}, },
// Add custom scripts here that would be placed in <script> tags // Add custom scripts here that would be placed in <script> tags.
scripts: ['https://buttons.github.io/buttons.js'], scripts: ['https://buttons.github.io/buttons.js'],
/* On page navigation for the current documentation page */ // On page navigation for the current documentation page.
onPageNav: 'separate', onPageNav: 'separate',
// No .html extensions for paths.
cleanUrl: true,
/* Open Graph and Twitter card images */ // Open Graph and Twitter card images.
ogImage: 'img/docusaurus.png', ogImage: 'img/docusaurus.png',
twitterImage: 'img/docusaurus.png', twitterImage: 'img/docusaurus.png',

View file

@ -8,6 +8,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js'); const CompLibrary = require('../../core/CompLibrary.js');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock; const GridBlock = CompLibrary.GridBlock;

View file

@ -8,6 +8,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary'); const CompLibrary = require('../../core/CompLibrary');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const CWD = process.cwd(); const CWD = process.cwd();
@ -34,10 +35,10 @@ function Versions() {
<tr> <tr>
<th>{latestVersion}</th> <th>{latestVersion}</th>
<td> <td>
<a href={''}>Documentation</a> <a href="">Documentation</a>
</td> </td>
<td> <td>
<a href={''}>Release Notes</a> <a href="">Release Notes</a>
</td> </td>
</tr> </tr>
</tbody> </tbody>
@ -52,10 +53,10 @@ function Versions() {
<tr> <tr>
<th>master</th> <th>master</th>
<td> <td>
<a href={''}>Documentation</a> <a href="">Documentation</a>
</td> </td>
<td> <td>
<a href={''}>Release Notes</a> <a href="">Release Notes</a>
</td> </td>
</tr> </tr>
</tbody> </tbody>
@ -70,10 +71,10 @@ function Versions() {
<tr> <tr>
<th>{version}</th> <th>{version}</th>
<td> <td>
<a href={''}>Documentation</a> <a href="">Documentation</a>
</td> </td>
<td> <td>
<a href={''}>Release Notes</a> <a href="">Release Notes</a>
</td> </td>
</tr> </tr>
) )

View file

@ -15,6 +15,7 @@ const shell = require('shelljs');
const CWD = process.cwd(); const CWD = process.cwd();
const utils = require('../server/utils'); const utils = require('../server/utils');
const siteConfig = require(CWD + '/website/siteConfig.js'); const siteConfig = require(CWD + '/website/siteConfig.js');
const buildDir = CWD + '/website/build'; const buildDir = CWD + '/website/build';
const docsDir = CWD + '/docs'; const docsDir = CWD + '/docs';
@ -67,11 +68,9 @@ describe('Build files', () => {
}); });
test('Generated HTML for each Markdown resource', function() { test('Generated HTML for each Markdown resource', function() {
let metadata = []; const metadata = outputHTMLFiles.map(file =>
outputHTMLFiles.forEach(function(file) { filepath.create(file).basename()
const path = filepath.create(file); );
metadata.push(path.basename());
});
inputMarkdownFiles.forEach(function(file) { inputMarkdownFiles.forEach(function(file) {
const data = fs.readFileSync(file, 'utf8'); const data = fs.readFileSync(file, 'utf8');
const frontmatter = fm(data); const frontmatter = fm(data);
@ -105,11 +104,9 @@ describe('Build files', () => {
}); });
test('Copied assets from /docs/assets', function() { test('Copied assets from /docs/assets', function() {
let metadata = []; const metadata = outputAssetsFiles.map(file =>
outputAssetsFiles.forEach(function(file) { filepath.create(file).basename()
const path = filepath.create(file); );
metadata.push(path.basename());
});
inputAssetsFiles.forEach(function(file) { inputAssetsFiles.forEach(function(file) {
const path = filepath.create(file); const path = filepath.create(file);
expect(metadata).toContain(path.basename()); expect(metadata).toContain(path.basename());

View file

@ -22,6 +22,7 @@ require('babel-register')({
// initial check that required files are present // initial check that required files are present
const chalk = require('chalk'); const chalk = require('chalk');
const fs = require('fs'); const fs = require('fs');
const CWD = process.cwd(); const CWD = process.cwd();
if (!fs.existsSync(CWD + '/siteConfig.js')) { if (!fs.existsSync(CWD + '/siteConfig.js')) {
@ -33,6 +34,7 @@ if (!fs.existsSync(CWD + '/siteConfig.js')) {
// generate all static html files // generate all static html files
const generate = require('./server/generate.js'); const generate = require('./server/generate.js');
generate() generate()
.then(() => { .then(() => {
console.log("Site built successfully. Generated files in 'build' folder."); console.log("Site built successfully. Generated files in 'build' folder.");

View file

@ -32,13 +32,13 @@ if (fs.existsSync(CWD + '/package.json')) {
if (!packageContent.scripts) { if (!packageContent.scripts) {
packageContent.scripts = {}; packageContent.scripts = {};
} }
packageContent.scripts['start'] = 'docusaurus-start'; packageContent.scripts.start = 'docusaurus-start';
packageContent.scripts['build'] = 'docusaurus-build'; packageContent.scripts.build = 'docusaurus-build';
packageContent.scripts['publish-gh-pages'] = 'docusaurus-publish'; packageContent.scripts['publish-gh-pages'] = 'docusaurus-publish';
packageContent.scripts['examples'] = 'docusaurus-examples'; packageContent.scripts.examples = 'docusaurus-examples';
packageContent.scripts['write-translations'] = packageContent.scripts['write-translations'] =
'docusaurus-write-translations'; 'docusaurus-write-translations';
packageContent.scripts['version'] = 'docusaurus-version'; packageContent.scripts.version = 'docusaurus-version';
packageContent.scripts['rename-version'] = 'docusaurus-rename-version'; packageContent.scripts['rename-version'] = 'docusaurus-rename-version';
fs.writeFileSync( fs.writeFileSync(
CWD + '/package.json', CWD + '/package.json',
@ -69,7 +69,7 @@ if (feature === 'translations') {
fs.copySync(folder + '/crowdin.yaml', CWD + '/../crowdin.yaml'); fs.copySync(folder + '/crowdin.yaml', CWD + '/../crowdin.yaml');
exampleSiteCreated = true; exampleSiteCreated = true;
} }
let files = glob.sync(folder + '/**/*'); const files = glob.sync(folder + '/**/*');
files.forEach(file => { files.forEach(file => {
if (fs.lstatSync(file).isDirectory()) { if (fs.lstatSync(file).isDirectory()) {
return; return;
@ -97,7 +97,7 @@ if (feature === 'translations') {
} else if (feature === 'versions') { } else if (feature === 'versions') {
// copy files for versions // copy files for versions
const folder = path.join(__dirname, '..', 'examples', 'versions'); const folder = path.join(__dirname, '..', 'examples', 'versions');
let files = glob.sync(folder + '/**/*'); const files = glob.sync(folder + '/**/*');
files.forEach(file => { files.forEach(file => {
if (fs.lstatSync(file).isDirectory()) { if (fs.lstatSync(file).isDirectory()) {
return; return;
@ -171,7 +171,7 @@ if (feature === 'translations') {
); );
// copy other files // copy other files
let files = glob.sync(folder + '/**/*'); const files = glob.sync(folder + '/**/*');
files.forEach(file => { files.forEach(file => {
if (fs.lstatSync(file).isDirectory()) { if (fs.lstatSync(file).isDirectory()) {
return; return;

View file

@ -41,8 +41,7 @@ class BlogPageLayout extends React.Component {
<Container className="mainContainer postContainer blogContainer"> <Container className="mainContainer postContainer blogContainer">
<div className="posts"> <div className="posts">
{MetadataBlog.slice(page * perPage, (page + 1) * perPage).map( {MetadataBlog.slice(page * perPage, (page + 1) * perPage).map(
post => { post => (
return (
<BlogPost <BlogPost
post={post} post={post}
content={post.content} content={post.content}
@ -53,8 +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

@ -103,7 +103,7 @@ class BlogPostLayout extends React.Component {
const hasOnPageNav = this.props.config.onPageNav === 'separate'; const hasOnPageNav = this.props.config.onPageNav === 'separate';
const post = this.props.metadata; const post = this.props.metadata;
post.path = utils.getPath(post.path, this.props.config.cleanUrl); post.path = utils.getPath(post.path, this.props.config.cleanUrl);
let blogSidebarTitleConfig = this.props.config.blogSidebarTitle || {}; const blogSidebarTitleConfig = this.props.config.blogSidebarTitle || {};
return ( return (
<Site <Site
className={classNames('sideNavVisible', { className={classNames('sideNavVisible', {
@ -111,13 +111,13 @@ class BlogPostLayout extends React.Component {
})} })}
url={'blog/' + post.path} url={'blog/' + post.path}
title={this.props.metadata.title} title={this.props.metadata.title}
language={'en'} language="en"
description={this.getDescription()} description={this.getDescription()}
config={this.props.config} config={this.props.config}
metadata={{blog: true}}> metadata={{blog: true}}>
<div className="docMainWrapper wrapper"> <div className="docMainWrapper wrapper">
<BlogSidebar <BlogSidebar
language={'en'} language="en"
current={post} current={post}
config={this.props.config} config={this.props.config}
/> />
@ -126,7 +126,7 @@ class BlogPostLayout extends React.Component {
<BlogPost <BlogPost
post={post} post={post}
content={this.props.children} content={this.props.children}
language={'en'} language="en"
config={this.props.config} config={this.props.config}
/> />
{this.renderSocialButtons()} {this.renderSocialButtons()}

View file

@ -14,7 +14,7 @@ const MetadataBlog = require('./MetadataBlog.js');
class BlogSidebar extends React.Component { class BlogSidebar extends React.Component {
render() { render() {
let blogSidebarCount = 5; let blogSidebarCount = 5;
let blogSidebarTitleConfig = this.props.config.blogSidebarTitle || {}; const blogSidebarTitleConfig = this.props.config.blogSidebarTitle || {};
let blogSidebarTitle = blogSidebarTitleConfig.default || 'Recent Posts'; let blogSidebarTitle = blogSidebarTitleConfig.default || 'Recent Posts';
if (this.props.config.blogSidebarCount) { if (this.props.config.blogSidebarCount) {
if (this.props.config.blogSidebarCount === 'ALL') { if (this.props.config.blogSidebarCount === 'ALL') {

View file

@ -11,7 +11,7 @@ const GridBlock = require('./GridBlock.js');
// A collection of components to provide to users // A collection of components to provide to users
module.exports = { module.exports = {
MarkdownBlock: MarkdownBlock, MarkdownBlock,
Container: Container, Container,
GridBlock: GridBlock, GridBlock,
}; };

View file

@ -85,7 +85,7 @@ class DocsLayout extends React.Component {
][metadata.previous_id] || ][metadata.previous_id] ||
translation[this.props.metadata.language][ translation[this.props.metadata.language][
'localized-strings' 'localized-strings'
]['previous'] || ].previous ||
'Previous' 'Previous'
: metadata.previous_title || 'Previous'} : metadata.previous_title || 'Previous'}
</a> </a>
@ -103,7 +103,7 @@ class DocsLayout extends React.Component {
][metadata.next_id] || ][metadata.next_id] ||
translation[this.props.metadata.language][ translation[this.props.metadata.language][
'localized-strings' 'localized-strings'
]['next'] || ].next ||
'Next' 'Next'
: metadata.next_title || 'Next'}{' '} : metadata.next_title || 'Next'}{' '}

View file

@ -12,8 +12,8 @@ const readCategories = require('../server/readCategories.js');
class DocsSidebar extends React.Component { class DocsSidebar extends React.Component {
render() { render() {
let sidebar = this.props.metadata.sidebar; const sidebar = this.props.metadata.sidebar;
let docsCategories = readCategories(sidebar); const docsCategories = readCategories(sidebar);
const categoryName = docsCategories[this.props.metadata.language][0].name; const categoryName = docsCategories[this.props.metadata.language][0].name;
if (!categoryName) { if (!categoryName) {
return null; return null;

View file

@ -13,14 +13,14 @@ class Head extends React.Component {
const links = this.props.config.headerLinks; const links = this.props.config.headerLinks;
const hasBlog = links.some(link => link.blog); const hasBlog = links.some(link => link.blog);
let highlight = { const highlight = {
version: '9.12.0', version: '9.12.0',
theme: 'default', theme: 'default',
...this.props.config.highlight, ...this.props.config.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.
let highlightThemeURL = highlight.themeUrl const highlightThemeURL = highlight.themeUrl
? highlight.themeUrl ? highlight.themeUrl
: `//cdnjs.cloudflare.com/ajax/libs/highlight.js/${ : `//cdnjs.cloudflare.com/ajax/libs/highlight.js/${
highlight.version highlight.version
@ -143,17 +143,13 @@ class Head extends React.Component {
))} ))}
{this.props.config.scrollToTop && ( {this.props.config.scrollToTop && (
<script <script src="https://unpkg.com/vanilla-back-to-top@7.1.14/dist/vanilla-back-to-top.min.js" />
src={
'https://unpkg.com/vanilla-back-to-top@7.1.14/dist/vanilla-back-to-top.min.js'
}
/>
)} )}
{this.props.config.scrollToTop && ( {this.props.config.scrollToTop && (
<script <script
dangerouslySetInnerHTML={{ dangerouslySetInnerHTML={{
__html: ` __html: `
document.addEventListener("DOMContentLoaded", function(){ document.addEventListener('DOMContentLoaded', function() {
addBackToTop( addBackToTop(
${JSON.stringify( ${JSON.stringify(
Object.assign( Object.assign(

View file

@ -10,6 +10,7 @@ const fs = require('fs');
const HeaderNav = require('./nav/HeaderNav.js'); const HeaderNav = require('./nav/HeaderNav.js');
const Head = require('./Head.js'); const Head = require('./Head.js');
const Footer = require(process.cwd() + '/core/Footer.js'); const Footer = require(process.cwd() + '/core/Footer.js');
const translation = require('../server/translation.js'); const translation = require('../server/translation.js');
const constants = require('./constants'); const constants = require('./constants');

View file

@ -10,6 +10,7 @@ const CWD = process.cwd();
const React = require('react'); const React = require('react');
const fs = require('fs'); const fs = require('fs');
const classNames = require('classnames'); const classNames = require('classnames');
const siteConfig = require(CWD + '/siteConfig.js'); const siteConfig = require(CWD + '/siteConfig.js');
const translation = require('../../server/translation.js'); const translation = require('../../server/translation.js');
const env = require('../../server/env.js'); const env = require('../../server/env.js');
@ -18,16 +19,18 @@ const translate = require('../../server/translate.js').translate;
const setLanguage = require('../../server/translate.js').setLanguage; const setLanguage = require('../../server/translate.js').setLanguage;
const readMetadata = require('../../server/readMetadata.js'); const readMetadata = require('../../server/readMetadata.js');
readMetadata.generateMetadataDocs(); readMetadata.generateMetadataDocs();
const Metadata = require('../metadata.js'); const Metadata = require('../metadata.js');
const utils = require('../utils.js'); const utils = require('../utils.js');
const extension = siteConfig.cleanUrl ? '' : '.html'; const extension = siteConfig.cleanUrl ? '' : '.html';
// language dropdown nav item for when translations are enabled // language dropdown nav item for when translations are enabled
class LanguageDropDown extends React.Component { class LanguageDropDown extends React.Component {
render() { render() {
setLanguage(this.props.language || 'en'); setLanguage(this.props.language || 'en');
let 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

View file

@ -15,7 +15,7 @@ const utils = require('../utils.js');
class SideNav extends React.Component { class SideNav extends React.Component {
// return appropriately translated category string // return appropriately translated category string
getLocalizedCategoryString(category) { getLocalizedCategoryString(category) {
let categoryString = translation[this.props.language] const categoryString = translation[this.props.language]
? translation[this.props.language]['localized-strings'][category] || ? translation[this.props.language]['localized-strings'][category] ||
category category
: category; : category;

View file

@ -25,7 +25,7 @@ class MarkdownRenderer {
// Highlight.js expects hljs css classes on the code element. // Highlight.js expects hljs css classes on the code element.
// This results in <pre><code class="hljs css languages-jsx"> // This results in <pre><code class="hljs css languages-jsx">
langPrefix: 'hljs css languages-', langPrefix: 'hljs css languages-',
highlight: function(str, lang) { highlight(str, lang) {
lang = lang =
lang || (siteConfig.highlight && siteConfig.highlight.defaultLang); lang || (siteConfig.highlight && siteConfig.highlight.defaultLang);
if (lang) { if (lang) {
@ -90,6 +90,4 @@ class MarkdownRenderer {
const renderMarkdown = new MarkdownRenderer(); const renderMarkdown = new MarkdownRenderer();
module.exports = source => { module.exports = source => renderMarkdown.toHtml(source);
return renderMarkdown.toHtml(source);
};

View file

@ -42,9 +42,9 @@ module.exports = (string, context = {}) => {
// Handle uppercase characters // Handle uppercase characters
.toLowerCase() .toLowerCase()
// Handle accentuated characters // Handle accentuated characters
.replace(new RegExp('[' + accents + ']', 'g'), c => { .replace(new RegExp('[' + accents + ']', 'g'), c =>
return 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, '')
// Dash special characters // Dash special characters

View file

@ -17,6 +17,7 @@ require('babel-register')({
// initial check that required files are present // initial check that required files are present
const chalk = require('chalk'); const chalk = require('chalk');
const fs = require('fs'); const fs = require('fs');
const CWD = process.cwd(); const CWD = process.cwd();
if (!fs.existsSync(CWD + '/siteConfig.js')) { if (!fs.existsSync(CWD + '/siteConfig.js')) {
@ -28,4 +29,5 @@ if (!fs.existsSync(CWD + '/siteConfig.js')) {
// generate rss feed // generate rss feed
const feed = require('./server/feed.js'); const feed = require('./server/feed.js');
console.log(feed()); console.log(feed());

View file

@ -112,9 +112,9 @@ if (fs.existsSync(CWD + '/versioned_docs/version-' + currentVersion)) {
// if sidebar file exists for this version, rename sidebar file and rewrite // if sidebar file exists for this version, rename sidebar file and rewrite
// doc ids in the file // doc ids in the file
let currentSidebarFile = const currentSidebarFile =
CWD + '/versioned_sidebars/version-' + currentVersion + '-sidebars.json'; CWD + '/versioned_sidebars/version-' + currentVersion + '-sidebars.json';
let newSidebarFile = const newSidebarFile =
CWD + '/versioned_sidebars/version-' + newVersion + '-sidebars.json'; CWD + '/versioned_sidebars/version-' + newVersion + '-sidebars.json';
if (fs.existsSync(currentSidebarFile)) { if (fs.existsSync(currentSidebarFile)) {
fs.renameSync(currentSidebarFile, newSidebarFile); fs.renameSync(currentSidebarFile, newSidebarFile);

View file

@ -9,6 +9,7 @@ const CWD = process.cwd();
const fs = require('fs-extra'); const fs = require('fs-extra');
const path = require('path'); const path = require('path');
const chalk = require('chalk'); const chalk = require('chalk');
const siteConfig = require(CWD + '/siteConfig.js'); const siteConfig = require(CWD + '/siteConfig.js');
const join = path.join; const join = path.join;

View file

@ -6,9 +6,11 @@
*/ */
const Feed = require('feed'); const Feed = require('feed');
const CWD = process.cwd(); const CWD = process.cwd();
const siteConfig = require(CWD + '/siteConfig.js'); const siteConfig = require(CWD + '/siteConfig.js');
const readMetadata = require('./readMetadata.js'); const readMetadata = require('./readMetadata.js');
const blogRootURL = siteConfig.url + siteConfig.baseUrl + 'blog'; const blogRootURL = siteConfig.url + siteConfig.baseUrl + 'blog';
const siteImageURL = const siteImageURL =
siteConfig.url + siteConfig.baseUrl + siteConfig.headerIcon; siteConfig.url + siteConfig.baseUrl + siteConfig.headerIcon;

View file

@ -158,7 +158,7 @@ async function execute() {
rawContent = insertTableOfContents(rawContent); rawContent = insertTableOfContents(rawContent);
} }
let defaultVersion = env.versioning.defaultVersion; const defaultVersion = env.versioning.defaultVersion;
// replace any links to markdown files to their website html links // replace any links to markdown files to their website html links
Object.keys(mdToHtml).forEach(key => { Object.keys(mdToHtml).forEach(key => {
@ -250,7 +250,7 @@ async function execute() {
.forEach(file => { .forEach(file => {
// Why normalize? In case we are on Windows. // Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
let normalizedFile = path.normalize(file); const normalizedFile = path.normalize(file);
const extension = path.extname(normalizedFile); const extension = path.extname(normalizedFile);
if (extension !== '.md' && extension !== '.markdown') { if (extension !== '.md' && extension !== '.markdown') {
return; return;
@ -273,7 +273,7 @@ async function execute() {
); );
metadata.id = metadata.title; metadata.id = metadata.title;
let language = 'en'; const language = 'en';
const blogPostComp = ( const blogPostComp = (
<BlogPostLayout <BlogPostLayout
metadata={metadata} metadata={metadata}
@ -284,15 +284,15 @@ async function execute() {
); );
const str = renderToStaticMarkupWithDoctype(blogPostComp); const str = renderToStaticMarkupWithDoctype(blogPostComp);
let targetFile = join(buildDir, 'blog', filePath); const targetFile = join(buildDir, 'blog', filePath);
writeFileAndCreateFolder(targetFile, str); writeFileAndCreateFolder(targetFile, str);
}); });
// create html files for all blog pages (collections of article previews) // create html files for all blog pages (collections of article previews)
const BlogPageLayout = require('../core/BlogPageLayout.js'); const BlogPageLayout = require('../core/BlogPageLayout.js');
const perPage = 10; const perPage = 10;
for (let page = 0; page < Math.ceil(MetadataBlog.length / perPage); page++) { for (let page = 0; page < Math.ceil(MetadataBlog.length / perPage); page++) {
let language = 'en'; const language = 'en';
const metadata = {page: page, perPage: perPage}; const metadata = {page, perPage};
const blogPageComp = ( const blogPageComp = (
<BlogPageLayout <BlogPageLayout
metadata={metadata} metadata={metadata}
@ -302,7 +302,7 @@ async function execute() {
); );
const str = renderToStaticMarkupWithDoctype(blogPageComp); const str = renderToStaticMarkupWithDoctype(blogPageComp);
let targetFile = join( const targetFile = join(
buildDir, buildDir,
'blog', 'blog',
page > 0 ? 'page' + (page + 1) : '', page > 0 ? 'page' + (page + 1) : '',
@ -389,7 +389,7 @@ async function execute() {
files.forEach(file => { files.forEach(file => {
// Why normalize? In case we are on Windows. // Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
let normalizedFile = path.normalize(file); const normalizedFile = path.normalize(file);
// parse css files to replace colors and fonts according to siteConfig // parse css files to replace colors and fonts according to siteConfig
if (normalizedFile.match(/\.css$/) && !isSeparateCss(normalizedFile)) { if (normalizedFile.match(/\.css$/) && !isSeparateCss(normalizedFile)) {
const mainCss = join(buildDir, 'css', 'main.css'); const mainCss = join(buildDir, 'css', 'main.css');
@ -453,7 +453,7 @@ async function execute() {
files.forEach(file => { files.forEach(file => {
// Why normalize? In case we are on Windows. // Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
let normalizedFile = path.normalize(file); const normalizedFile = path.normalize(file);
// render .js files to strings // render .js files to strings
if (normalizedFile.match(/\.js$/)) { if (normalizedFile.match(/\.js$/)) {
const pageID = path.basename(normalizedFile, '.js'); const pageID = path.basename(normalizedFile, '.js');
@ -511,7 +511,7 @@ async function execute() {
} }
// write to base level // write to base level
let language = env.translation.enabled ? 'en' : ''; const language = env.translation.enabled ? 'en' : '';
translate.setLanguage(language); translate.setLanguage(language);
const str = renderToStaticMarkupWithDoctype( const str = renderToStaticMarkupWithDoctype(
<Site <Site
@ -529,7 +529,7 @@ async function execute() {
); );
} else { } else {
// allow for rendering of other files not in pages/en folder // allow for rendering of other files not in pages/en folder
let language = env.translation.enabled ? 'en' : ''; const language = env.translation.enabled ? 'en' : '';
translate.setLanguage(language); translate.setLanguage(language);
const str = renderToStaticMarkupWithDoctype( const str = renderToStaticMarkupWithDoctype(
<Site <Site
@ -564,8 +564,8 @@ async function execute() {
writeFileAndCreateFolder(targetFile, str); writeFileAndCreateFolder(targetFile, str);
} else if (!fs.lstatSync(normalizedFile).isDirectory()) { } else if (!fs.lstatSync(normalizedFile).isDirectory()) {
// copy other non .js files // copy other non .js files
let parts = normalizedFile.split('pages'); const parts = normalizedFile.split('pages');
let targetFile = join(buildDir, parts[1]); const targetFile = join(buildDir, parts[1]);
mkdirp.sync(path.dirname(targetFile)); mkdirp.sync(path.dirname(targetFile));
fs.copySync(normalizedFile, targetFile); fs.copySync(normalizedFile, targetFile);
} }
@ -573,7 +573,7 @@ async function execute() {
// Generate CNAME file if a custom domain is specified in siteConfig // Generate CNAME file if a custom domain is specified in siteConfig
if (siteConfig.cname) { if (siteConfig.cname) {
let targetFile = join(buildDir, 'CNAME'); const targetFile = join(buildDir, 'CNAME');
fs.writeFileSync(targetFile, siteConfig.cname); fs.writeFileSync(targetFile, siteConfig.cname);
} }
} }

View file

@ -14,6 +14,7 @@ const glob = require('glob');
const metadataUtils = require('./metadataUtils'); const metadataUtils = require('./metadataUtils');
const env = require('./env.js'); const env = require('./env.js');
const siteConfig = require(CWD + '/siteConfig.js'); const siteConfig = require(CWD + '/siteConfig.js');
const versionFallback = require('./versionFallback.js'); const versionFallback = require('./versionFallback.js');
const utils = require('./utils.js'); const utils = require('./utils.js');
@ -56,7 +57,7 @@ function readSidebar() {
const categories = allSidebars[sidebar]; const categories = allSidebars[sidebar];
let ids = []; let ids = [];
let categoryOrder = []; const categoryOrder = [];
Object.keys(categories).forEach(category => { Object.keys(categories).forEach(category => {
ids = ids.concat(categories[category]); ids = ids.concat(categories[category]);
for (let i = 0; i < categories[category].length; i++) { for (let i = 0; i < categories[category].length; i++) {
@ -71,9 +72,9 @@ function readSidebar() {
if (i > 0) previous = ids[i - 1]; if (i > 0) previous = ids[i - 1];
if (i < ids.length - 1) next = ids[i + 1]; if (i < ids.length - 1) next = ids[i + 1];
order[id] = { order[id] = {
previous: previous, previous,
next: next, next,
sidebar: sidebar, sidebar,
category: categoryOrder[i], category: categoryOrder[i],
}; };
} }
@ -156,7 +157,7 @@ function processMetadata(file, refDir) {
} }
} }
return {metadata, rawContent: rawContent}; return {metadata, rawContent};
} }
// process metadata for all docs and save into core/metadata.js // process metadata for all docs and save into core/metadata.js
@ -188,7 +189,7 @@ function generateMetadataDocs() {
if (!res) { if (!res) {
return; return;
} }
let metadata = res.metadata; const metadata = res.metadata;
metadatas[metadata.id] = metadata; metadatas[metadata.id] = metadata;
// create a default list of documents for each enabled language based on docs in English // create a default list of documents for each enabled language based on docs in English
@ -196,24 +197,24 @@ function generateMetadataDocs() {
enabledLanguages enabledLanguages
.filter(currentLanguage => currentLanguage !== 'en') .filter(currentLanguage => currentLanguage !== 'en')
.forEach(currentLanguage => { .forEach(currentLanguage => {
let baseMetadata = Object.assign({}, metadata); const baseMetadata = Object.assign({}, metadata);
baseMetadata['id'] = baseMetadata['id'] baseMetadata.id = baseMetadata.id
.toString() .toString()
.replace(/^en-/, currentLanguage + '-'); .replace(/^en-/, currentLanguage + '-');
if (baseMetadata['permalink']) if (baseMetadata.permalink)
baseMetadata['permalink'] = baseMetadata['permalink'] baseMetadata.permalink = baseMetadata.permalink
.toString() .toString()
.replace(/^docs\/en\//, 'docs/' + currentLanguage + '/'); .replace(/^docs\/en\//, 'docs/' + currentLanguage + '/');
if (baseMetadata['next']) if (baseMetadata.next)
baseMetadata['next'] = baseMetadata['next'] baseMetadata.next = baseMetadata.next
.toString() .toString()
.replace(/^en-/, currentLanguage + '-'); .replace(/^en-/, currentLanguage + '-');
if (baseMetadata['previous']) if (baseMetadata.previous)
baseMetadata['previous'] = baseMetadata['previous'] baseMetadata.previous = baseMetadata.previous
.toString() .toString()
.replace(/^en-/, currentLanguage + '-'); .replace(/^en-/, currentLanguage + '-');
baseMetadata['language'] = currentLanguage; baseMetadata.language = currentLanguage;
defaultMetadatas[baseMetadata['id']] = baseMetadata; defaultMetadatas[baseMetadata.id] = baseMetadata;
}); });
Object.assign(metadatas, defaultMetadatas); Object.assign(metadatas, defaultMetadatas);
} }
@ -234,7 +235,7 @@ function generateMetadataDocs() {
if (!res) { if (!res) {
return; return;
} }
let metadata = res.metadata; const metadata = res.metadata;
metadatas[metadata.id] = metadata; metadatas[metadata.id] = metadata;
} }
}); });
@ -305,7 +306,7 @@ function generateMetadataDocs() {
function generateMetadataBlog() { function generateMetadataBlog() {
const metadatas = []; const metadatas = [];
let files = glob.sync(CWD + '/blog/**/*.*'); const files = glob.sync(CWD + '/blog/**/*.*');
files files
.sort() .sort()
.reverse() .reverse()
@ -336,7 +337,7 @@ function generateMetadataBlog() {
metadata.id = metadata.title; metadata.id = metadata.title;
// Extract, YYYY, MM, DD from the file name // Extract, YYYY, MM, DD from the file name
let filePathDateArr = path const filePathDateArr = path
.basename(file) .basename(file)
.toString() .toString()
.split('-'); .split('-');

View file

@ -71,9 +71,7 @@ function execute(port, options) {
} }
} }
/****************************************************************************/ const readMetadata = require('./readMetadata.js');
let readMetadata = require('./readMetadata.js');
let Metadata; let Metadata;
let MetadataBlog; let MetadataBlog;
let siteConfig; let siteConfig;
@ -103,8 +101,6 @@ function execute(port, options) {
} }
} }
/****************************************************************************/
const TABLE_OF_CONTENTS_TOKEN = '<AUTOGENERATED_TABLE_OF_CONTENTS>'; const TABLE_OF_CONTENTS_TOKEN = '<AUTOGENERATED_TABLE_OF_CONTENTS>';
const insertTableOfContents = rawContent => { const insertTableOfContents = rawContent => {
@ -119,8 +115,6 @@ function execute(port, options) {
return rawContent.replace(TABLE_OF_CONTENTS_TOKEN, tableOfContents); return rawContent.replace(TABLE_OF_CONTENTS_TOKEN, tableOfContents);
}; };
/****************************************************************************/
function isSeparateCss(file) { function isSeparateCss(file) {
if (!siteConfig.separateCss) { if (!siteConfig.separateCss) {
return false; return false;
@ -181,8 +175,6 @@ function execute(port, options) {
); );
} }
/****************************************************************************/
reloadMetadata(); reloadMetadata();
reloadMetadataBlog(); reloadMetadataBlog();
extractTranslations(); extractTranslations();
@ -192,10 +184,10 @@ function execute(port, options) {
// handle all requests for document pages // handle all requests for document pages
app.get(docsRouting(siteConfig.baseUrl), (req, res, next) => { app.get(docsRouting(siteConfig.baseUrl), (req, res, next) => {
let url = req.path.toString().replace(siteConfig.baseUrl, ''); const url = req.path.toString().replace(siteConfig.baseUrl, '');
// links is a map from a permalink to an id for each document // links is a map from a permalink to an id for each document
let links = {}; const links = {};
Object.keys(Metadata).forEach(id => { Object.keys(Metadata).forEach(id => {
const metadata = Metadata[id]; const metadata = Metadata[id];
links[metadata.permalink] = id; links[metadata.permalink] = id;
@ -254,7 +246,7 @@ function execute(port, options) {
rawContent = insertTableOfContents(rawContent); rawContent = insertTableOfContents(rawContent);
} }
let defaultVersion = env.versioning.defaultVersion; const defaultVersion = env.versioning.defaultVersion;
// replace any links to markdown files to their website html links // replace any links to markdown files to their website html links
Object.keys(mdToHtml).forEach(key => { Object.keys(mdToHtml).forEach(key => {
@ -326,7 +318,7 @@ function execute(port, options) {
app.get(feedRouting(siteConfig.baseUrl), (req, res, next) => { app.get(feedRouting(siteConfig.baseUrl), (req, res, next) => {
res.set('Content-Type', 'application/rss+xml'); res.set('Content-Type', 'application/rss+xml');
let file = req.path const file = req.path
.toString() .toString()
.split('blog/')[1] .split('blog/')[1]
.toLowerCase(); .toLowerCase();
@ -354,8 +346,8 @@ function execute(port, options) {
page < Math.ceil(MetadataBlog.length / perPage); page < Math.ceil(MetadataBlog.length / perPage);
page++ page++
) { ) {
let language = 'en'; const language = 'en';
const metadata = {page: page, perPage: perPage}; const metadata = {page, perPage};
const blogPageComp = ( const blogPageComp = (
<BlogPageLayout <BlogPageLayout
metadata={metadata} metadata={metadata}
@ -369,7 +361,7 @@ function execute(port, options) {
blogPages[pagePath] = str; blogPages[pagePath] = str;
} }
let parts = req.path.toString().split('blog/'); const parts = req.path.toString().split('blog/');
// send corresponding blog page if appropriate // send corresponding blog page if appropriate
if (parts[1] === 'index.html') { if (parts[1] === 'index.html') {
res.send(blogPages['/index.html']); res.send(blogPages['/index.html']);
@ -412,7 +404,7 @@ function execute(port, options) {
); );
metadata.id = metadata.title; metadata.id = metadata.title;
let language = 'en'; const language = 'en';
removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPostLayout.js')); removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPostLayout.js'));
const BlogPostLayout = require(join('..', 'core', 'BlogPostLayout.js')); const BlogPostLayout = require(join('..', 'core', 'BlogPostLayout.js'));
@ -502,7 +494,7 @@ function execute(port, options) {
fs.existsSync((userFile = englishFile)) fs.existsSync((userFile = englishFile))
) { ) {
// copy into docusaurus so require paths work // copy into docusaurus so require paths work
let userFileParts = userFile.split('pages' + sep); const userFileParts = userFile.split('pages' + sep);
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),
@ -546,7 +538,7 @@ function execute(port, options) {
); );
let cssContent = fs.readFileSync(mainCssPath, {encoding: 'utf8'}); let cssContent = fs.readFileSync(mainCssPath, {encoding: 'utf8'});
let files = glob.sync(join(CWD, 'static', '**', '*.css')); const files = glob.sync(join(CWD, 'static', '**', '*.css'));
files.forEach(file => { files.forEach(file => {
if (isSeparateCss(file)) { if (isSeparateCss(file)) {
@ -604,8 +596,8 @@ function execute(port, options) {
// "redirect" requests to pages ending with "/" or no extension so that, // "redirect" requests to pages ending with "/" or no extension so that,
// for example, request to "blog" returns "blog/index.html" or "blog.html" // for example, request to "blog" returns "blog/index.html" or "blog.html"
app.get(noExtRouting(), (req, res, next) => { app.get(noExtRouting(), (req, res, next) => {
let slash = req.path.toString().endsWith('/') ? '' : '/'; const slash = req.path.toString().endsWith('/') ? '' : '/';
let requestUrl = 'http://localhost:' + port + req.path; const requestUrl = 'http://localhost:' + port + req.path;
requestFile(requestUrl + slash + 'index.html', res, () => { requestFile(requestUrl + slash + 'index.html', res, () => {
requestFile( requestFile(
slash === '/' slash === '/'

View file

@ -8,6 +8,7 @@
const fs = require('fs-extra'); const fs = require('fs-extra');
const glob = require('glob'); const glob = require('glob');
const CWD = process.cwd(); const CWD = process.cwd();
const sitemap = require('sitemap'); const sitemap = require('sitemap');
@ -15,24 +16,18 @@ const utils = require('../core/utils');
const siteConfig = require(CWD + '/siteConfig.js'); const siteConfig = require(CWD + '/siteConfig.js');
/****************************************************************************/ const readMetadata = require('./readMetadata.js');
let readMetadata;
let Metadata;
let MetadataBlog;
readMetadata = require('./readMetadata.js');
readMetadata.generateMetadataDocs(); readMetadata.generateMetadataDocs();
Metadata = require('../core/metadata.js'); const Metadata = require('../core/metadata.js');
readMetadata.generateMetadataBlog();
MetadataBlog = require('../core/MetadataBlog.js');
/****************************************************************************/ readMetadata.generateMetadataBlog();
const MetadataBlog = require('../core/MetadataBlog.js');
module.exports = function(callback) { module.exports = function(callback) {
console.log('sitemap.js triggered...'); console.log('sitemap.js triggered...');
let files = glob.sync(CWD + '/pages/en/**/*.js'); const files = glob.sync(CWD + '/pages/en/**/*.js');
// English-only is the default. // English-only is the default.
let enabledLanguages = [ let enabledLanguages = [
@ -45,7 +40,7 @@ module.exports = function(callback) {
// If we have a languages.js file, get all the enabled languages in there // If we have a languages.js file, get all the enabled languages in there
if (fs.existsSync(CWD + '/languages.js')) { if (fs.existsSync(CWD + '/languages.js')) {
let languages = require(CWD + '/languages.js'); const languages = require(CWD + '/languages.js');
enabledLanguages = languages.filter(lang => lang.enabled); enabledLanguages = languages.filter(lang => lang.enabled);
} }
@ -56,7 +51,7 @@ module.exports = function(callback) {
? url.replace(/\.js$/, '') ? url.replace(/\.js$/, '')
: url.replace(/\.js$/, '.html'); : url.replace(/\.js$/, '.html');
const links = enabledLanguages.map(lang => { const links = enabledLanguages.map(lang => {
let langUrl = lang.tag + url; const langUrl = lang.tag + url;
return {lang: lang.tag, url: langUrl}; return {lang: lang.tag, url: langUrl};
}); });
return {url, changefreq: 'weekly', priority: 0.5, links}; return {url, changefreq: 'weekly', priority: 0.5, links};
@ -73,10 +68,10 @@ module.exports = function(callback) {
Object.keys(Metadata) Object.keys(Metadata)
.filter(key => Metadata[key].language === 'en') .filter(key => Metadata[key].language === 'en')
.forEach(key => { .forEach(key => {
let doc = Metadata[key]; const doc = Metadata[key];
let docUrl = utils.getPath(doc.permalink, siteConfig.cleanUrl); const docUrl = utils.getPath(doc.permalink, siteConfig.cleanUrl);
let links = enabledLanguages.map(lang => { const links = enabledLanguages.map(lang => {
let langUrl = docUrl.replace('docs/en/', `docs/${lang.tag}/`); const langUrl = docUrl.replace('docs/en/', `docs/${lang.tag}/`);
return {lang: lang.tag, url: langUrl}; return {lang: lang.tag, url: langUrl};
}); });
urls.push({ urls.push({

View file

@ -38,7 +38,7 @@ function translate(str) {
if (!language || language === '') { if (!language || language === '') {
// Check English, just in case; otherwise, just return the raw string back // Check English, just in case; otherwise, just return the raw string back
if (doesTranslationExist(str, 'en')) { if (doesTranslationExist(str, 'en')) {
return parseEscapeSequences(translation['en']['pages-strings'][str]); return parseEscapeSequences(translation.en['pages-strings'][str]);
} }
return str; return str;
} }
@ -54,7 +54,7 @@ function translate(str) {
"'. Using English version instead." "'. 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 ('" + "Text that you've identified for translation ('" +
@ -66,6 +66,6 @@ function translate(str) {
} }
module.exports = { module.exports = {
setLanguage: setLanguage, setLanguage,
translate: translate, translate,
}; };

View file

@ -24,7 +24,7 @@ function getSubDir(file, refDir) {
// (file: '/website/translated_docs/ko/projectA/test.md', refDir: 'website/translated_docs') // (file: '/website/translated_docs/ko/projectA/test.md', refDir: 'website/translated_docs')
// returns 'ko' // returns 'ko'
function getLanguage(file, refDir) { function getLanguage(file, refDir) {
let regexSubFolder = new RegExp( const regexSubFolder = new RegExp(
'/' + escapeStringRegexp(path.basename(refDir)) + '/(.*)/.*/' '/' + escapeStringRegexp(path.basename(refDir)) + '/(.*)/.*/'
); );
const match = regexSubFolder.exec(file); const match = regexSubFolder.exec(file);

View file

@ -14,6 +14,7 @@ const metadataUtils = require('./metadataUtils');
const env = require('./env.js'); const env = require('./env.js');
const utils = require('./utils.js'); const utils = require('./utils.js');
const siteConfig = require(CWD + '/siteConfig.js'); const siteConfig = require(CWD + '/siteConfig.js');
const ENABLE_TRANSLATION = fs.existsSync(CWD + '/languages.js'); const ENABLE_TRANSLATION = fs.existsSync(CWD + '/languages.js');
@ -46,7 +47,7 @@ const available = {};
// versionFiles is used to keep track of what file to use with a // versionFiles is used to keep track of what file to use with a
// given version/id of a document // given version/id of a document
const versionFiles = {}; const versionFiles = {};
let files = glob.sync(versionFolder + '**'); const files = glob.sync(versionFolder + '**');
files.forEach(file => { files.forEach(file => {
const ext = path.extname(file); const ext = path.extname(file);
if (ext !== '.md' && ext !== '.markdown') { if (ext !== '.md' && ext !== '.markdown') {

View file

@ -80,7 +80,7 @@ const versionFolder = CWD + '/versioned_docs/version-' + version;
mkdirp.sync(versionFolder); mkdirp.sync(versionFolder);
// copy necessary files to new version, changing some of its metadata to reflect the versioning // copy necessary files to new version, changing some of its metadata to reflect the versioning
let files = glob.sync(CWD + '/../' + readMetadata.getDocsPath() + '/**'); const files = glob.sync(CWD + '/../' + readMetadata.getDocsPath() + '/**');
files.forEach(file => { files.forEach(file => {
const ext = path.extname(file); const ext = path.extname(file);
if (ext !== '.md' && ext !== '.markdown') { if (ext !== '.md' && ext !== '.markdown') {
@ -88,12 +88,12 @@ files.forEach(file => {
} }
const res = metadataUtils.extractMetadata(fs.readFileSync(file, 'utf8')); const res = metadataUtils.extractMetadata(fs.readFileSync(file, 'utf8'));
let metadata = res.metadata; const metadata = res.metadata;
// Don't version any docs without any metadata whatsoever. // Don't version any docs without any metadata whatsoever.
if (Object.keys(metadata).length === 0) { if (Object.keys(metadata).length === 0) {
return; return;
} }
let rawContent = res.rawContent; const rawContent = res.rawContent;
if (!metadata.id) { if (!metadata.id) {
metadata.id = path.basename(file, path.extname(file)); metadata.id = path.basename(file, path.extname(file));
} }

View file

@ -27,6 +27,7 @@ const mkdirp = require('mkdirp');
const nodePath = require('path'); const nodePath = require('path');
const readMetadata = require('./server/readMetadata.js'); const readMetadata = require('./server/readMetadata.js');
const CWD = process.cwd(); const CWD = process.cwd();
const siteConfig = require(CWD + '/siteConfig.js'); const siteConfig = require(CWD + '/siteConfig.js');
const sidebars = require(CWD + '/sidebars.json'); const sidebars = require(CWD + '/sidebars.json');
@ -47,7 +48,7 @@ function writeFileAndCreateFolder(file, content) {
} }
function execute() { function execute() {
let translations = { const translations = {
'localized-strings': { 'localized-strings': {
next: 'Next', next: 'Next',
previous: 'Previous', previous: 'Previous',

View file

@ -23,7 +23,8 @@
"precommit": "lint-staged", "precommit": "lint-staged",
"prettier": "yarn format:source && yarn format:examples", "prettier": "yarn format:source && yarn format:examples",
"prettier:diff": "yarn nit:source && yarn nit:examples", "prettier:diff": "yarn nit:source && yarn nit:examples",
"test": "jest" "test": "jest",
"start": "cd website && yarn start"
}, },
"lint-staged": { "lint-staged": {
"linters": { "linters": {

View file

@ -9,6 +9,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js'); const CompLibrary = require('../../core/CompLibrary.js');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const siteConfig = require(process.cwd() + '/siteConfig.js'); const siteConfig = require(process.cwd() + '/siteConfig.js');
const translate = require('../../server/translate.js').translate; const translate = require('../../server/translate.js').translate;

View file

@ -7,6 +7,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js'); const CompLibrary = require('../../core/CompLibrary.js');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock; const GridBlock = CompLibrary.GridBlock;
const siteConfig = require(process.cwd() + '/siteConfig.js'); const siteConfig = require(process.cwd() + '/siteConfig.js');

View file

@ -7,6 +7,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js'); const CompLibrary = require('../../core/CompLibrary.js');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock; const GridBlock = CompLibrary.GridBlock;
const siteConfig = require(process.cwd() + '/siteConfig.js'); const siteConfig = require(process.cwd() + '/siteConfig.js');
@ -72,7 +73,7 @@ class HomeSplash extends React.Component {
class Index extends React.Component { class Index extends React.Component {
render() { render() {
let language = this.props.language || 'en'; const language = this.props.language || 'en';
const showcase = siteConfig.users.filter(user => user.pinned).map(user => ( const showcase = siteConfig.users.filter(user => user.pinned).map(user => (
<a href={user.infoLink} key={user.infoLink}> <a href={user.infoLink} key={user.infoLink}>
<img src={user.image} alt={user.caption} title={user.caption} /> <img src={user.image} alt={user.caption} title={user.caption} />
@ -226,7 +227,7 @@ class Index extends React.Component {
</Container> </Container>
<div className="productShowcaseSection paddingBottom"> <div className="productShowcaseSection paddingBottom">
<h2> <h2>
<translate>Who's Using Docusaurus?</translate> <translate>Who is Using Docusaurus?</translate>
</h2> </h2>
<p> <p>
<translate> <translate>

View file

@ -7,6 +7,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js'); const CompLibrary = require('../../core/CompLibrary.js');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const siteConfig = require(process.cwd() + '/siteConfig.js'); const siteConfig = require(process.cwd() + '/siteConfig.js');
const translate = require('../../server/translate.js').translate; const translate = require('../../server/translate.js').translate;
@ -38,7 +39,7 @@ class Users extends React.Component {
<translate>Who is using Docusaurus?</translate> <translate>Who is using Docusaurus?</translate>
</h1> </h1>
<p> <p>
Docusaurus powers some of Facebook's popular{' '} Docusaurus powers some of Facebook&apos;s popular{' '}
<a href="https://code.facebook.com/projects/"> <a href="https://code.facebook.com/projects/">
open source projects open source projects
</a>. </a>.

View file

@ -8,6 +8,7 @@
const React = require('react'); const React = require('react');
const CompLibrary = require('../../core/CompLibrary'); const CompLibrary = require('../../core/CompLibrary');
const Container = CompLibrary.Container; const Container = CompLibrary.Container;
const CWD = process.cwd(); const CWD = process.cwd();

View file

@ -31,6 +31,8 @@ window.addEventListener('load', function() {
); );
const clipboard = new ClipboardJS('.btnClipboard', { const clipboard = new ClipboardJS('.btnClipboard', {
// Not gonna use the shorthand as this file is sent down to browsers without transpiling.
/* eslint-disable object-shorthand */
target: function(trigger) { target: function(trigger) {
return trigger.parentNode.querySelector('code'); return trigger.parentNode.querySelector('code');
}, },