chore(v2): generic styling improvements

This commit is contained in:
Yangshun Tay 2019-02-23 12:50:31 -08:00
parent c46a894a01
commit b33de00a32
16 changed files with 109 additions and 109 deletions

View file

@ -25,10 +25,10 @@ async function loadBlog({blogDir, env, siteConfig}) {
const {baseUrl} = siteConfig; const {baseUrl} = siteConfig;
/* Prepare metadata container */ // Prepare metadata container.
const blogMetadatas = []; const blogMetadatas = [];
/* the language for each blog page */ // Language for each blog page.
const defaultLangTag = idx(env, ['translation', 'defaultLanguage', 'tag']); const defaultLangTag = idx(env, ['translation', 'defaultLanguage', 'tag']);
await Promise.all( await Promise.all(
@ -58,13 +58,13 @@ async function loadBlog({blogDir, env, siteConfig}) {
); );
blogMetadatas.sort((a, b) => a.date - b.date); blogMetadatas.sort((a, b) => a.date - b.date);
// blogpage handling. Example: `/blog`, `/blog/page1`, `/blog/page2` // Blog page handling. Example: `/blog`, `/blog/page1`, `/blog/page2`
const perPage = 10; const perPage = 10;
const numOfBlog = blogMetadatas.length; const numOfBlog = blogMetadatas.length;
const numberOfPage = Math.ceil(numOfBlog / perPage); const numberOfPage = Math.ceil(numOfBlog / perPage);
const basePageUrl = path.join(baseUrl, 'blog'); const basePageUrl = path.join(baseUrl, 'blog');
/* eslint-disable */ // eslint-disable-next-line
for (let page = 0; page < numberOfPage; page++) { for (let page = 0; page < numberOfPage; page++) {
blogMetadatas.push({ blogMetadatas.push({
permalink: normalizeUrl([ permalink: normalizeUrl([

View file

@ -19,7 +19,7 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
// @tested - build the docs ordering such as next, previous, category and sidebar // @tested - build the docs ordering such as next, previous, category and sidebar
const order = createOrder(docsSidebars); const order = createOrder(docsSidebars);
/* Settle versions & translations from environment */ // Settle versions & translations from environment.
const translationEnabled = idx(env, ['translation', 'enabled']); const translationEnabled = idx(env, ['translation', 'enabled']);
const enabledLanguages = const enabledLanguages =
translationEnabled && idx(env, ['translation', 'enabledLanguages']); translationEnabled && idx(env, ['translation', 'enabledLanguages']);
@ -30,19 +30,17 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
const versions = const versions =
(versioningEnabled && idx(env, ['versioning', 'versions'])) || []; (versioningEnabled && idx(env, ['versioning', 'versions'])) || [];
/* Prepare metadata container */ // Prepare metadata container.
const docsMetadatas = {}; const docsMetadatas = {};
/* 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 => {
/* // Do not allow reserved version/ translated folder name in 'docs'
Do not allow reserved version/ translated folder name in 'docs' // e.g: 'docs/version-1.0.0/' should not be allowed as it can cause unwanted bug
e.g: 'docs/version-1.0.0/' should not be allowed as it can cause unwanted bug
*/
const subFolder = getSubFolder(path.resolve(docsDir, source), docsDir); const subFolder = getSubFolder(path.resolve(docsDir, source), docsDir);
const versionsFolders = versions.map(version => `version-${version}`); const versionsFolders = versions.map(version => `version-${version}`);
if ([...enabledLangTags, ...versionsFolders].includes(subFolder)) { if ([...enabledLangTags, ...versionsFolders].includes(subFolder)) {
@ -60,7 +58,7 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
}), }),
); );
/* 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'], {
@ -68,7 +66,7 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
}); });
await Promise.all( await Promise.all(
translatedFiles.map(async source => { translatedFiles.map(async source => {
/* /*
Do not process disabled & default languages folder in `translated_docs` Do not process disabled & default languages folder in `translated_docs`
e.g: 'translated_docs/ja/**' should not be processed if lang 'ja' is disabled e.g: 'translated_docs/ja/**' should not be processed if lang 'ja' is disabled
*/ */
@ -93,7 +91,7 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
); );
} }
/* metadata for versioned docs */ // Metadata for versioned docs.
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'], {
@ -113,7 +111,7 @@ async function loadDocs({siteDir, docsDir, env, siteConfig}) {
); );
} }
/* Get the titles of the previous and next ids so that we can use them */ // Get the titles of the previous and next ids so that we can use them.
Object.keys(docsMetadatas).forEach(currentID => { Object.keys(docsMetadatas).forEach(currentID => {
const previousID = idx(docsMetadatas, [currentID, 'previous']); const previousID = idx(docsMetadatas, [currentID, 'previous']);
if (previousID) { if (previousID) {

View file

@ -1,4 +1,4 @@
/** /*
* Copyright (c) 2017-present, Facebook, Inc. * Copyright (c) 2017-present, Facebook, Inc.
* *
* This source code is licensed under the MIT license found in the * This source code is licensed under the MIT license found in the
@ -11,6 +11,7 @@ const {getSubFolder, idx, parse, normalizeUrl} = require('../utils');
function getLanguage(filepath, refDir, env) { function getLanguage(filepath, refDir, env) {
const translationEnabled = idx(env, ['translation', 'enabled']); const translationEnabled = idx(env, ['translation', 'enabled']);
if (translationEnabled) { if (translationEnabled) {
const detectedLangTag = getSubFolder(filepath, refDir); const detectedLangTag = getSubFolder(filepath, refDir);
const enabledLanguages = idx(env, ['translation', 'enabledLanguages']); const enabledLanguages = idx(env, ['translation', 'enabledLanguages']);
@ -19,18 +20,22 @@ function getLanguage(filepath, refDir, env) {
if (langTags.includes(detectedLangTag)) { if (langTags.includes(detectedLangTag)) {
return detectedLangTag; return detectedLangTag;
} }
const defaultLanguage = idx(env, ['translation', 'defaultLanguage']); const defaultLanguage = idx(env, ['translation', 'defaultLanguage']);
if (defaultLanguage && defaultLanguage.tag) { if (defaultLanguage && defaultLanguage.tag) {
return defaultLanguage.tag; return defaultLanguage.tag;
} }
} }
return undefined;
return null;
} }
function getVersion(filepath, refDir, env) { function getVersion(filepath, refDir, env) {
const versioningEnabled = idx(env, ['versioning', 'enabled']); const versioningEnabled = idx(env, ['versioning', 'enabled']);
if (versioningEnabled) { if (versioningEnabled) {
const subFolder = getSubFolder(filepath, refDir); const subFolder = getSubFolder(filepath, refDir);
if (subFolder) { if (subFolder) {
const detectedVersion = subFolder.replace(/^version-/, ''); const detectedVersion = subFolder.replace(/^version-/, '');
const versions = idx(env, ['versioning', 'versions']) || []; const versions = idx(env, ['versioning', 'versions']) || [];
@ -38,9 +43,11 @@ function getVersion(filepath, refDir, env) {
return detectedVersion; return detectedVersion;
} }
} }
return 'next'; return 'next';
} }
return undefined;
return null;
} }
module.exports = async function processMetadata( module.exports = async function processMetadata(
@ -54,7 +61,7 @@ module.exports = async function processMetadata(
const fileString = await fs.readFile(filepath, 'utf-8'); const fileString = await fs.readFile(filepath, 'utf-8');
const {metadata} = parse(fileString); const {metadata} = parse(fileString);
/* default id is the file name */ // Default id is the file name.
if (!metadata.id) { if (!metadata.id) {
metadata.id = path.basename(source, path.extname(source)); metadata.id = path.basename(source, path.extname(source));
} }
@ -62,17 +69,17 @@ module.exports = async function processMetadata(
throw new Error('Document id cannot include "/".'); throw new Error('Document id cannot include "/".');
} }
/* default title is the id */ // Default title is the id.
if (!metadata.title) { if (!metadata.title) {
metadata.title = metadata.id; metadata.title = metadata.id;
} }
/* language */ // Language.
const language = getLanguage(filepath, refDir, env); const language = getLanguage(filepath, refDir, env);
metadata.language = language; metadata.language = language;
const langPart = (language && `${language}/`) || ''; const langPart = (language && `${language}/`) || '';
/* version */ // Version.
const defaultLangTag = idx(env, ['translation', 'defaultLanguage', 'tag']); const defaultLangTag = idx(env, ['translation', 'defaultLanguage', 'tag']);
let versionRefDir = refDir; let versionRefDir = refDir;
if (language && language !== defaultLangTag) { if (language && language !== defaultLangTag) {
@ -84,10 +91,8 @@ module.exports = async function processMetadata(
const versionPart = const versionPart =
(version && version !== latestVersion && `${version}/`) || ''; (version && version !== latestVersion && `${version}/`) || '';
/* // Convert temporarily metadata.id to the form of dirname/id without version/lang prefix.
Convert temporarily metadata.id to the form of dirname/id without version/lang prefix // e.g.: file `versioned_docs/version-1.0.0/en/foo/bar.md` with id `version-1.0.0-bar` => `foo/bar`
ex: file `versioned_docs/version-1.0.0/en/foo/bar.md` with id `version-1.0.0-bar` => `foo/bar`
*/
if (language) { if (language) {
metadata.id = metadata.id.replace(new RegExp(`^${language}-`), ''); metadata.id = metadata.id.replace(new RegExp(`^${language}-`), '');
} }
@ -112,19 +117,15 @@ module.exports = async function processMetadata(
} }
} }
/* // The docs absolute file source.
The docs absolute file source // e.g: `/end/docs/hello.md` or `/end/website/versioned_docs/version-1.0.0/hello.md`
e.g: `/end/docs/hello.md` or `/end/website/versioned_docs/version-1.0.0/hello.md`
*/
metadata.source = path.join(refDir, source); metadata.source = path.join(refDir, source);
/* Build the permalink */ // Build the permalink.
const {baseUrl, docsUrl} = siteConfig; const {baseUrl, docsUrl} = siteConfig;
/* // If user has own custom permalink defined in frontmatter
if user has own custom permalink defined in frontmatter // e.g: :baseUrl:docsUrl/:langPart/:versionPart/endiliey/:id
e.g: :baseUrl:docsUrl/:langPart/:versionPart/endiliey/:id
*/
if (metadata.permalink) { if (metadata.permalink) {
metadata.permalink = path.resolve( metadata.permalink = path.resolve(
metadata.permalink metadata.permalink
@ -144,20 +145,20 @@ module.exports = async function processMetadata(
]); ]);
} }
/* if version */ // If version.
if (version && version !== 'next') { if (version && version !== 'next') {
metadata.id = `version-${version}-${metadata.id}`; metadata.id = `version-${version}-${metadata.id}`;
} }
/* save localized id before adding language on it */ // Save localized id before adding language on it.
metadata.localized_id = metadata.id; metadata.localized_id = metadata.id;
/* if language */ // If language.
if (language) { if (language) {
metadata.id = `${language}-${metadata.id}`; metadata.id = `${language}-${metadata.id}`;
} }
/* Determine order */ // Determine order.
const id = metadata.localized_id; const id = metadata.localized_id;
if (order[id]) { if (order[id]) {
metadata.sidebar = order[id].sidebar; metadata.sidebar = order[id].sidebar;
@ -172,5 +173,6 @@ module.exports = async function processMetadata(
metadata.previous = (language ? `${language}-` : '') + order[id].previous; metadata.previous = (language ? `${language}-` : '') + order[id].previous;
} }
} }
return metadata; return metadata;
}; };

View file

@ -5,8 +5,7 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
*/ */
// build the docs meta such as next, previous, category and sidebar // Build the docs meta such as next, previous, category and sidebar.
module.exports = function createOrder(allSidebars = {}) { module.exports = function createOrder(allSidebars = {}) {
const order = {}; const order = {};
@ -28,7 +27,7 @@ module.exports = function createOrder(allSidebars = {}) {
break; break;
case 'ref': case 'ref':
case 'link': case 'link':
// refs and links should not be shown in navigation // Refs and links should not be shown in navigation.
break; break;
case 'doc': case 'doc':
ids.push(item.id); ids.push(item.id);

View file

@ -11,7 +11,7 @@ const {idx} = require('./utils');
const loadConfig = require('./config'); const loadConfig = require('./config');
module.exports = function loadEnv({siteDir, siteConfig}) { module.exports = function loadEnv({siteDir, siteConfig}) {
// Translation // Translation.
const translation = { const translation = {
enabled: false, enabled: false,
enabledLanguages: [], enabledLanguages: [],
@ -23,31 +23,32 @@ module.exports = function loadEnv({siteDir, siteConfig}) {
if (fs.existsSync(languagesFile)) { if (fs.existsSync(languagesFile)) {
const languages = require(languagesFile); // eslint-disable-line const languages = require(languagesFile); // eslint-disable-line
/* Enabled languages */ // Enabled languages.
const enabledLanguages = languages.filter(lang => lang.enabled); const enabledLanguages = languages.filter(lang => lang.enabled);
if (!enabledLanguages || enabledLanguages.length === 0) { if (!enabledLanguages || enabledLanguages.length === 0) {
throw new Error(`Please at least enable one language in 'languages.js'`); throw new Error(`Please at least enable one language in 'languages.js'`);
} }
translation.enabledLanguages = enabledLanguages; translation.enabledLanguages = enabledLanguages;
/* 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 ${ `Please set a default language in ${
loadConfig.configFileName loadConfig.configFileName
} which is enabled in 'languages.js'`, } which is enabled in languages.js`,
); );
} }
translation.defaultLanguage = defaultLanguage;
translation.defaultLanguage = defaultLanguage;
translation.enabled = true; translation.enabled = true;
} }
// Versioning // Versioning.
const versioning = { const versioning = {
enabled: false, enabled: false,
latestVersion: null, latestVersion: null,

View file

@ -16,18 +16,18 @@ const {generate} = require('./utils');
const genRoutesConfig = require('./routes'); const genRoutesConfig = require('./routes');
module.exports = async function load(siteDir) { module.exports = async function load(siteDir) {
// @tested - siteConfig // Site Config - @tested
const siteConfig = loadConfig.loadConfig(siteDir); const siteConfig = loadConfig.loadConfig(siteDir);
await generate( await generate(
loadConfig.configFileName, loadConfig.configFileName,
`export default ${JSON.stringify(siteConfig, null, 2)};`, `export default ${JSON.stringify(siteConfig, null, 2)};`,
); );
// @tested - env // Env - @tested
const env = loadEnv({siteDir, siteConfig}); const env = loadEnv({siteDir, siteConfig});
await generate('env.js', `export default ${JSON.stringify(env, null, 2)};`); await generate('env.js', `export default ${JSON.stringify(env, null, 2)};`);
// docs // Docs
const docsDir = path.resolve(siteDir, '..', siteConfig.customDocsPath); const docsDir = path.resolve(siteDir, '..', siteConfig.customDocsPath);
const {docsMetadatas, docsSidebars} = await loadDocs({ const {docsMetadatas, docsSidebars} = await loadDocs({
siteDir, siteDir,
@ -44,7 +44,7 @@ module.exports = async function load(siteDir) {
`export default ${JSON.stringify(docsSidebars, null, 2)};`, `export default ${JSON.stringify(docsSidebars, null, 2)};`,
); );
/* Create source to metadata mapping */ // Create source to metadata mapping.
const sourceToMetadata = {}; const sourceToMetadata = {};
Object.values(docsMetadatas).forEach( Object.values(docsMetadatas).forEach(
({source, version, permalink, language}) => { ({source, version, permalink, language}) => {
@ -56,7 +56,7 @@ module.exports = async function load(siteDir) {
}, },
); );
// pages // Pages.
const pagesDir = path.resolve(siteDir, 'pages'); const pagesDir = path.resolve(siteDir, 'pages');
const pagesMetadatas = await loadPages({pagesDir, env, siteConfig}); const pagesMetadatas = await loadPages({pagesDir, env, siteConfig});
await generate( await generate(
@ -64,7 +64,7 @@ module.exports = async function load(siteDir) {
`export default ${JSON.stringify(pagesMetadatas, null, 2)};`, `export default ${JSON.stringify(pagesMetadatas, null, 2)};`,
); );
// blog // Blog.
const blogDir = path.resolve(siteDir, 'blog'); const blogDir = path.resolve(siteDir, 'blog');
const blogMetadatas = await loadBlog({blogDir, env, siteConfig}); const blogMetadatas = await loadBlog({blogDir, env, siteConfig});
await generate( await generate(
@ -72,10 +72,10 @@ module.exports = async function load(siteDir) {
`export default ${JSON.stringify(blogMetadatas, null, 2)};`, `export default ${JSON.stringify(blogMetadatas, null, 2)};`,
); );
// resolve outDir // Resolve outDir.
const outDir = path.resolve(siteDir, 'build'); const outDir = path.resolve(siteDir, 'build');
// resolve the theme // Resolve theme.
const themePath = loadTheme(siteDir); const themePath = loadTheme(siteDir);
const {baseUrl} = siteConfig; const {baseUrl} = siteConfig;
@ -101,7 +101,7 @@ module.exports = async function load(siteDir) {
translatedDir, translatedDir,
}; };
// Generate React Router Config // Generate React Router Config.
const routesConfig = await genRoutesConfig(props); const routesConfig = await genRoutesConfig(props);
await generate('routes.js', routesConfig); await generate('routes.js', routesConfig);

View file

@ -16,10 +16,10 @@ async function loadPages({pagesDir, env, siteConfig}) {
const {baseUrl} = siteConfig; const {baseUrl} = siteConfig;
/* Prepare metadata container */ // Prepare metadata container.
const pagesMetadatas = []; const pagesMetadatas = [];
/* Translation */ // Translation.
const translationEnabled = idx(env, ['translation', 'enabled']); const translationEnabled = idx(env, ['translation', 'enabled']);
const enabledLanguages = const enabledLanguages =
translationEnabled && idx(env, ['translation', 'enabledLanguages']); translationEnabled && idx(env, ['translation', 'enabledLanguages']);
@ -33,7 +33,7 @@ async function loadPages({pagesDir, env, siteConfig}) {
const pathName = encodePath(fileToPath(relativeSource)); const pathName = encodePath(fileToPath(relativeSource));
if (translationEnabled && enabledLangTags.length > 0) { if (translationEnabled && enabledLangTags.length > 0) {
enabledLangTags.forEach(langTag => { enabledLangTags.forEach(langTag => {
/* default lang should also be available. E.g: /en/users and /users is the same */ // Default lang should also be available. E.g: /en/users and /users is the same.
if (langTag === defaultLangTag) { if (langTag === defaultLangTag) {
pagesMetadatas.push({ pagesMetadatas.push({
permalink: pathName.replace(/^\//, baseUrl), permalink: pathName.replace(/^\//, baseUrl),
@ -49,9 +49,8 @@ async function loadPages({pagesDir, env, siteConfig}) {
}; };
pagesMetadatas.push(metadata); pagesMetadatas.push(metadata);
}); });
// for defaultLanguage
} else { } else {
// Default Language.
const metadata = { const metadata = {
permalink: pathName.replace(/^\//, baseUrl), permalink: pathName.replace(/^\//, baseUrl),
source, source,

View file

@ -24,6 +24,7 @@ module.exports = function loadConfig(siteDir) {
'Markdown', 'Markdown',
'Search', 'Search',
]; ];
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(

View file

@ -17,7 +17,7 @@ module.exports = function createClientConfig(props) {
const config = createBaseConfig(props); const config = createBaseConfig(props);
config.entry('main').add(path.resolve(__dirname, '../core/clientEntry.js')); config.entry('main').add(path.resolve(__dirname, '../core/clientEntry.js'));
// remove/clean build folders before building bundles // Remove/clean build folders before building bundles.
const {outDir} = props; const {outDir} = props;
config config
.plugin('clean') .plugin('clean')
@ -33,7 +33,7 @@ module.exports = function createClientConfig(props) {
{filename: path.join(outDir, 'react-loadable.json')}, {filename: path.join(outDir, 'react-loadable.json')},
]); ]);
// show compilation progress bar and build time // Show compilation progress bar and build time.
const isProd = process.env.NODE_ENV === 'production'; const isProd = process.env.NODE_ENV === 'production';
config config
.plugin('niceLog') .plugin('niceLog')

View file

@ -26,10 +26,10 @@ module.exports = function(fileString) {
sourceToMetadata, sourceToMetadata,
} = options; } = options;
/* Extract content of markdown (without frontmatter) */ // Extract content of markdown (without frontmatter).
const {body} = fm(fileString); const {body} = fm(fileString);
/* Determine the source dir. e.g: /docs, /website/versioned_docs/version-1.0.0 */ // Determine the source dir. e.g: /docs, /website/versioned_docs/version-1.0.0
let sourceDir; let sourceDir;
const thisSource = this.resourcePath; const thisSource = this.resourcePath;
if (thisSource.startsWith(translatedDir)) { if (thisSource.startsWith(translatedDir)) {
@ -48,7 +48,7 @@ module.exports = function(fileString) {
sourceDir = docsDir; sourceDir = docsDir;
} }
/* Replace internal markdown linking (except in fenced blocks) */ // Replace internal markdown linking (except in fenced blocks).
let content = body; let content = body;
if (sourceDir) { if (sourceDir) {
let fencedBlock = false; let fencedBlock = false;
@ -59,14 +59,13 @@ module.exports = function(fileString) {
if (fencedBlock) return line; if (fencedBlock) return line;
let modifiedLine = line; let modifiedLine = line;
/* Replace inline-style links or reference-style links e.g: // Replace inline-style links or reference-style links e.g:
This is [Document 1](doc1.md) -> we replace this doc1.md with correct link // This is [Document 1](doc1.md) -> we replace this doc1.md with correct link
[doc1]: doc1.md -> we replace this doc1.md with correct link // [doc1]: doc1.md -> we replace this doc1.md with correct link
*/
const mdRegex = /(?:(?:\]\()|(?:\]:\s?))(?!https)([^'")\]\s>]+\.md)/g; const mdRegex = /(?:(?:\]\()|(?:\]:\s?))(?!https)([^'")\]\s>]+\.md)/g;
let mdMatch = mdRegex.exec(modifiedLine); let mdMatch = mdRegex.exec(modifiedLine);
while (mdMatch !== null) { while (mdMatch !== null) {
/* Replace it to correct html link */ // Replace it to correct html link.
const mdLink = mdMatch[1]; const mdLink = mdMatch[1];
const targetSource = `${sourceDir}/${mdLink}`; const targetSource = `${sourceDir}/${mdLink}`;
const {permalink} = const {permalink} =
@ -86,21 +85,21 @@ module.exports = function(fileString) {
const md = new Remarkable({ const md = new Remarkable({
langPrefix: 'hljs css language-', langPrefix: 'hljs css language-',
highlight(str, rawLang) { highlight(str, rawLang) {
// Default language fallback // Default language fallback.
const defaultLang = const defaultLang =
siteConfig.highlight && siteConfig.highlight.defaultLang; siteConfig.highlight && siteConfig.highlight.defaultLang;
// No syntax highlighting // No syntax highlighting.
if (rawLang === 'text' || (!rawLang && !defaultLang)) { if (rawLang === 'text' || (!rawLang && !defaultLang)) {
return escapeHtml(str); return escapeHtml(str);
} }
// User's own hljs function to register additional languages // User's own hljs function to register additional languages.
if (siteConfig.highlight && siteConfig.highlight.hljs) { if (siteConfig.highlight && siteConfig.highlight.hljs) {
siteConfig.highlight.hljs(hljs); siteConfig.highlight.hljs(hljs);
} }
// Syntax highlighting // Syntax highlighting.
const lang = rawLang.toLowerCase() || defaultLang; const lang = rawLang.toLowerCase() || defaultLang;
try { try {
if (hljs.getLanguage(lang)) { if (hljs.getLanguage(lang)) {
@ -119,10 +118,10 @@ module.exports = function(fileString) {
linkify: true, linkify: true,
}); });
// Register anchors plugin // Register anchors plugin.
md.use(anchors); md.use(anchors);
// Allow client sites to register their own plugins // Allow client sites to register their own plugins.
if (siteConfig.markdownPlugins) { if (siteConfig.markdownPlugins) {
siteConfig.markdownPlugins.forEach(plugin => { siteConfig.markdownPlugins.forEach(plugin => {
md.use(plugin); md.use(plugin);
@ -134,7 +133,8 @@ module.exports = function(fileString) {
const html = md const html = md
.render(content) .render(content)
.replace(/<pre><code>/g, '<pre><code class="hljs">'); .replace(/<pre><code>/g, '<pre><code class="hljs">');
/* Return a React component */
// Return a React component.
return ` return `
import React from 'react'; import React from 'react';
import Markdown from '@theme/Markdown'; import Markdown from '@theme/Markdown';

View file

@ -59,7 +59,7 @@ module.exports = (string, context = {}) => {
} }
if (typeof context.slugStats[slug] === 'number') { if (typeof context.slugStats[slug] === 'number') {
// search for an index, that will not clash with an existing headings // Search for an index, that will not clash with an existing headings
while ( while (
typeof context.slugStats[`${slug}-${++context.slugStats[slug]}`] === typeof context.slugStats[`${slug}-${++context.slugStats[slug]}`] ===
'number' 'number'
@ -67,7 +67,7 @@ module.exports = (string, context = {}) => {
slug += `-${context.slugStats[slug]}`; slug += `-${context.slugStats[slug]}`;
} }
// we are tracking both original anchors and suffixed to avoid future name // We are tracking both original anchors and suffixed to avoid future name
// clashing with headings with numbers e.g. `#Foo 1` may clash with the second `#Foo` // clashing with headings with numbers e.g. `#Foo 1` may clash with the second `#Foo`
context.slugStats[slug] = 0; context.slugStats[slug] = 0;

View file

@ -23,7 +23,7 @@ module.exports = function createServerConfig(props) {
const {siteConfig, blogMetadatas, docsMetadatas, pagesMetadatas} = props; const {siteConfig, blogMetadatas, docsMetadatas, pagesMetadatas} = props;
// static site generator webpack plugin // Static site generator webpack plugin.
const docsFlatMetadatas = Object.values(docsMetadatas); const docsFlatMetadatas = Object.values(docsMetadatas);
const paths = [...blogMetadatas, ...docsFlatMetadatas, ...pagesMetadatas].map( const paths = [...blogMetadatas, ...docsFlatMetadatas, ...pagesMetadatas].map(
data => data.permalink, data => data.permalink,
@ -38,7 +38,7 @@ module.exports = function createServerConfig(props) {
}, },
]); ]);
// show compilation progress bar // Show compilation progress bar.
const isProd = process.env.NODE_ENV === 'production'; const isProd = process.env.NODE_ENV === 'production';
config config
.plugin('niceLog') .plugin('niceLog')
@ -46,7 +46,7 @@ module.exports = function createServerConfig(props) {
{name: 'Server', color: 'yellow', skipBuildTime: isProd}, {name: 'Server', color: 'yellow', skipBuildTime: isProd},
]); ]);
// user extended webpack-chain config // User-extended webpack-chain config.
applyChainWebpack(props.siteConfig.chainWebpack, config, true); applyChainWebpack(props.siteConfig.chainWebpack, config, true);
return config; return config;

View file

@ -7,7 +7,7 @@
const merge = require('webpack-merge'); const merge = require('webpack-merge');
// Modify the generated webpack config with normal webpack config // Modify the generated webpack config with normal webpack config.
function applyConfigureWebpack(userConfig, config, isServer) { function applyConfigureWebpack(userConfig, config, isServer) {
if (typeof userConfig === 'object') { if (typeof userConfig === 'object') {
return merge(config, userConfig); return merge(config, userConfig);
@ -21,7 +21,7 @@ function applyConfigureWebpack(userConfig, config, isServer) {
return config; return config;
} }
// Modify the generated webpack config with webpack-chain API // Modify the generated webpack config with webpack-chain API.
function applyChainWebpack(userChainWebpack, config, isServer) { function applyChainWebpack(userChainWebpack, config, isServer) {
if (userChainWebpack) { if (userChainWebpack) {
userChainWebpack(config, isServer); userChainWebpack(config, isServer);

View file

@ -18,7 +18,7 @@ describe('loadDocs', () => {
expect(docsMetadatas.hello).toEqual({ expect(docsMetadatas.hello).toEqual({
category: 'Guides', category: 'Guides',
id: 'hello', id: 'hello',
language: undefined, language: null,
localized_id: 'hello', localized_id: 'hello',
permalink: '/docs/hello', permalink: '/docs/hello',
previous: 'foo/baz', previous: 'foo/baz',
@ -27,12 +27,12 @@ describe('loadDocs', () => {
sidebar: 'docs', sidebar: 'docs',
source: path.join(docsDir, 'hello.md'), source: path.join(docsDir, 'hello.md'),
title: 'Hello, World !', title: 'Hello, World !',
version: undefined, version: null,
}); });
expect(docsMetadatas['foo/bar']).toEqual({ expect(docsMetadatas['foo/bar']).toEqual({
category: 'Test', category: 'Test',
id: 'foo/bar', id: 'foo/bar',
language: undefined, language: null,
localized_id: 'foo/bar', localized_id: 'foo/bar',
next: 'foo/baz', next: 'foo/baz',
next_id: 'foo/baz', next_id: 'foo/baz',
@ -41,7 +41,7 @@ describe('loadDocs', () => {
sidebar: 'docs', sidebar: 'docs',
source: path.join(docsDir, 'foo', 'bar.md'), source: path.join(docsDir, 'foo', 'bar.md'),
title: 'Bar', title: 'Bar',
version: undefined, version: null,
}); });
}); });
@ -52,7 +52,7 @@ describe('loadDocs', () => {
expect(docsMetadatas['version-1.0.0-foo/bar']).toEqual({ expect(docsMetadatas['version-1.0.0-foo/bar']).toEqual({
category: 'Test', category: 'Test',
id: 'version-1.0.0-foo/bar', id: 'version-1.0.0-foo/bar',
language: undefined, language: null,
localized_id: 'version-1.0.0-foo/bar', localized_id: 'version-1.0.0-foo/bar',
next: 'version-1.0.0-foo/baz', next: 'version-1.0.0-foo/baz',
next_id: 'version-1.0.0-foo/baz', next_id: 'version-1.0.0-foo/baz',
@ -66,7 +66,7 @@ describe('loadDocs', () => {
expect(docsMetadatas['foo/bar']).toEqual({ expect(docsMetadatas['foo/bar']).toEqual({
category: 'Test', category: 'Test',
id: 'foo/bar', id: 'foo/bar',
language: undefined, language: null,
localized_id: 'foo/bar', localized_id: 'foo/bar',
next: 'foo/baz', next: 'foo/baz',
next_id: 'foo/baz', next_id: 'foo/baz',
@ -156,7 +156,7 @@ describe('loadDocs', () => {
sidebar: 'docs', sidebar: 'docs',
source: path.join(translatedDir, 'ko', 'foo', 'baz.md'), source: path.join(translatedDir, 'ko', 'foo', 'baz.md'),
title: 'baz', title: 'baz',
version: undefined, version: null,
}); });
expect(docsMetadatas['en-foo/bar']).toEqual({ expect(docsMetadatas['en-foo/bar']).toEqual({
category: 'Test', category: 'Test',
@ -170,7 +170,7 @@ describe('loadDocs', () => {
sidebar: 'docs', sidebar: 'docs',
source: path.join(docsDir, 'foo', 'bar.md'), source: path.join(docsDir, 'foo', 'bar.md'),
title: 'Bar', title: 'Bar',
version: undefined, version: null,
}); });
}); });
}); });

View file

@ -20,21 +20,21 @@ describe('processMetadata', () => {
const dataB = await processMetadata(sourceB, docsDir, env, {}, siteConfig); const dataB = await processMetadata(sourceB, docsDir, env, {}, siteConfig);
expect(dataA).toEqual({ expect(dataA).toEqual({
id: 'foo/bar', id: 'foo/bar',
language: undefined, language: null,
localized_id: 'foo/bar', localized_id: 'foo/bar',
permalink: '/docs/foo/bar', permalink: '/docs/foo/bar',
source: path.join(docsDir, sourceA), source: path.join(docsDir, sourceA),
title: 'Bar', title: 'Bar',
version: undefined, version: null,
}); });
expect(dataB).toEqual({ expect(dataB).toEqual({
id: 'hello', id: 'hello',
language: undefined, language: null,
localized_id: 'hello', localized_id: 'hello',
permalink: '/docs/hello', permalink: '/docs/hello',
source: path.join(docsDir, sourceB), source: path.join(docsDir, sourceB),
title: 'Hello, World !', title: 'Hello, World !',
version: undefined, version: null,
}); });
}); });
@ -45,12 +45,12 @@ describe('processMetadata', () => {
const data = await processMetadata(source, docsDir, env, {}, siteConfig); const data = await processMetadata(source, docsDir, env, {}, siteConfig);
expect(data).toEqual({ expect(data).toEqual({
id: 'permalink', id: 'permalink',
language: undefined, language: null,
localized_id: 'permalink', localized_id: 'permalink',
permalink: '/docs/endiliey/permalink', permalink: '/docs/endiliey/permalink',
source: path.join(docsDir, source), source: path.join(docsDir, source),
title: 'Permalink', title: 'Permalink',
version: undefined, version: null,
}); });
}); });
@ -80,7 +80,7 @@ describe('processMetadata', () => {
const dataD = await processMetadata(sourceD, docsDir, env, {}, siteConfig); const dataD = await processMetadata(sourceD, docsDir, env, {}, siteConfig);
expect(dataA).toEqual({ expect(dataA).toEqual({
id: 'version-1.0.0-foo/bar', id: 'version-1.0.0-foo/bar',
language: undefined, language: null,
localized_id: 'version-1.0.0-foo/bar', localized_id: 'version-1.0.0-foo/bar',
permalink: '/docs/1.0.0/foo/bar', permalink: '/docs/1.0.0/foo/bar',
source: path.join(versionedDir, sourceA), source: path.join(versionedDir, sourceA),
@ -89,7 +89,7 @@ describe('processMetadata', () => {
}); });
expect(dataB).toEqual({ expect(dataB).toEqual({
id: 'version-1.0.0-hello', id: 'version-1.0.0-hello',
language: undefined, language: null,
localized_id: 'version-1.0.0-hello', localized_id: 'version-1.0.0-hello',
permalink: '/docs/1.0.0/hello', permalink: '/docs/1.0.0/hello',
source: path.join(versionedDir, sourceB), source: path.join(versionedDir, sourceB),
@ -98,7 +98,7 @@ describe('processMetadata', () => {
}); });
expect(dataC).toEqual({ expect(dataC).toEqual({
id: 'foo/bar', id: 'foo/bar',
language: undefined, language: null,
localized_id: 'foo/bar', localized_id: 'foo/bar',
permalink: '/docs/next/foo/bar', permalink: '/docs/next/foo/bar',
source: path.join(docsDir, sourceC), source: path.join(docsDir, sourceC),
@ -107,7 +107,7 @@ describe('processMetadata', () => {
}); });
expect(dataD).toEqual({ expect(dataD).toEqual({
id: 'hello', id: 'hello',
language: undefined, language: null,
localized_id: 'hello', localized_id: 'hello',
permalink: '/docs/next/hello', permalink: '/docs/next/hello',
source: path.join(docsDir, sourceD), source: path.join(docsDir, sourceD),
@ -275,7 +275,7 @@ describe('processMetadata', () => {
permalink: '/docs/ko/foo/bar', permalink: '/docs/ko/foo/bar',
source: path.join(translatedDir, sourceA), source: path.join(translatedDir, sourceA),
title: 'Bar', title: 'Bar',
version: undefined, version: null,
}); });
expect(dataB).toEqual({ expect(dataB).toEqual({
id: 'ko-hello', id: 'ko-hello',
@ -284,7 +284,7 @@ describe('processMetadata', () => {
permalink: '/docs/ko/hello', permalink: '/docs/ko/hello',
source: path.join(translatedDir, sourceB), source: path.join(translatedDir, sourceB),
title: 'Hello, World !', title: 'Hello, World !',
version: undefined, version: null,
}); });
expect(dataC).toEqual({ expect(dataC).toEqual({
id: 'en-foo/bar', id: 'en-foo/bar',
@ -293,7 +293,7 @@ describe('processMetadata', () => {
permalink: '/docs/en/foo/bar', permalink: '/docs/en/foo/bar',
source: path.join(docsDir, sourceC), source: path.join(docsDir, sourceC),
title: 'Bar', title: 'Bar',
version: undefined, version: null,
}); });
expect(dataD).toEqual({ expect(dataD).toEqual({
id: 'en-hello', id: 'en-hello',
@ -302,7 +302,7 @@ describe('processMetadata', () => {
permalink: '/docs/en/hello', permalink: '/docs/en/hello',
source: path.join(docsDir, sourceD), source: path.join(docsDir, sourceD),
title: 'Hello, World !', title: 'Hello, World !',
version: undefined, version: null,
}); });
}); });
}); });

View file

@ -100,7 +100,7 @@ describe('loadEnv', () => {
expect(() => { expect(() => {
loadEnv({siteDir, siteConfig}); loadEnv({siteDir, siteConfig});
}).toThrowErrorMatchingInlineSnapshot( }).toThrowErrorMatchingInlineSnapshot(
`"Please set a default language in 'docusaurus.config.js' which is enabled in 'languages.js'"`, `"Please set a default language in docusaurus.config.js which is enabled in languages.js"`,
); );
}); });
}); });