Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v2): implement ContentRenderer #1366

Merged
merged 7 commits into from
Apr 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ module.exports = {
'jsx-a11y/click-events-have-key-events': OFF, // Revisit in future™
'jsx-a11y/no-noninteractive-element-interactions': OFF, // Revisit in future™
'no-console': OFF,
'no-underscore-dangle': OFF,
'react/jsx-closing-bracket-location': OFF, // Conflicts with Prettier.
'react/jsx-filename-extension': OFF,
'react/jsx-one-expression-per-line': OFF,
Expand Down
21 changes: 14 additions & 7 deletions packages/docusaurus-plugin-content-blog/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,21 +129,28 @@ class DocusaurusPluginContentBlog {
path: permalink,
component: blogPageComponent,
metadata: metadataItem,
modules: metadataItem.posts.map(post => ({
path: post.source,
query: {
truncated: true,
},
})),
modules: {
entries: metadataItem.posts.map(post => ({
// To tell routes.js this is an import and not a nested object to recurse.
__import: true,
path: post.source,
query: {
truncated: true,
},
})),
},
});

return;
}

addRoute({
path: permalink,
component: blogPostComponent,
metadata: metadataItem,
modules: [metadataItem.source],
modules: {
content: metadataItem.source,
},
});
});
}
Expand Down
4 changes: 3 additions & 1 deletion packages/docusaurus-plugin-content-docs/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,9 @@ class DocusaurusPluginContentDocs {
path: metadataItem.permalink,
component: docItemComponent,
metadata: metadataItem,
modules: [metadataItem.source],
modules: {
content: metadataItem.source,
},
})),
});
}
Expand Down
4 changes: 3 additions & 1 deletion packages/docusaurus-plugin-content-pages/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ class DocusaurusPluginContentPages {
path: permalink,
component,
metadata: metadataItem,
modules: [source],
modules: {
content: source,
},
});
});
}
Expand Down
20 changes: 17 additions & 3 deletions packages/docusaurus-utils/src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe('load utils', () => {

test('genComponentName', () => {
const asserts = {
'/': 'Index',
'/': 'index',
'/foo-bar': 'FooBar096',
'/foo/bar': 'FooBar1Df',
'/blog/2017/12/14/introducing-docusaurus':
Expand All @@ -51,7 +51,7 @@ describe('load utils', () => {
test('docuHash', () => {
const asserts = {
'': '-d41',
'/': 'Index',
'/': 'index',
'/foo-bar': 'foo-bar-096',
'/foo/bar': 'foo-bar-1df',
'/endi/lie': 'endi-lie-9fa',
Expand Down Expand Up @@ -81,7 +81,7 @@ describe('load utils', () => {
});

test('genChunkName', () => {
const asserts = {
let asserts = {
'/docs/adding-blog': 'docs-adding-blog-062',
'/docs/versioning': 'docs-versioning-8a8',
'/': 'index',
Expand All @@ -94,6 +94,20 @@ describe('load utils', () => {
Object.keys(asserts).forEach(str => {
expect(genChunkName(str)).toBe(asserts[str]);
});

// Don't allow different chunk name for same path.
expect(genChunkName('path/is/similar', 'oldPrefix')).toEqual(
genChunkName('path/is/similar', 'newPrefix'),
);

// Even with same preferred name, still different chunk name for different path
asserts = {
'/blog/1': 'blog-85-f-089',
'/blog/2': 'blog-353-489',
};
Object.keys(asserts).forEach(str => {
expect(genChunkName(str, undefined, 'blog')).toBe(asserts[str]);
});
});

test('idx', () => {
Expand Down
24 changes: 19 additions & 5 deletions packages/docusaurus-utils/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function encodePath(userpath) {
*/
function docuHash(str) {
if (str === '/') {
return 'Index';
return 'index';
}
const shortHash = createHash('md5')
.update(str)
Expand All @@ -63,7 +63,7 @@ function docuHash(str) {
*/
function genComponentName(pagePath) {
if (pagePath === '/') {
return 'Index';
return 'index';
}
const pageHash = docuHash(pagePath);
const pascalCase = _.flow(
Expand All @@ -88,9 +88,23 @@ function posixPath(str) {
return str.replace(/\\/g, '/');
}

function genChunkName(str, prefix) {
const name = str === '/' ? 'index' : docuHash(str);
return prefix ? `${prefix}---${name}` : name;
const chunkNameCache = new Map();
function genChunkName(modulePath, prefix, preferredName) {
let chunkName = chunkNameCache.get(modulePath);
if (!chunkName) {
let str = modulePath;
if (preferredName) {
const shortHash = createHash('md5')
.update(modulePath)
.digest('hex')
.substr(0, 3);
str = `${preferredName}${shortHash}`;
}
const name = str === '/' ? 'index' : docuHash(str);
chunkName = prefix ? `${prefix}---${name}` : name;
chunkNameCache.set(modulePath, chunkName);
}
return chunkName;
}

function idx(target, keyPaths) {
Expand Down
84 changes: 84 additions & 0 deletions packages/docusaurus/lib/client/exports/ComponentCreator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import React from 'react';
import Loadable from 'react-loadable';
import Loading from '@theme/Loading';
import routesAsyncModules from '@generated/routesAsyncModules';
import registry from '@generated/registry';

function ComponentCreator(path) {
const modules = routesAsyncModules[path];
const originalModules = modules;
const optsModules = [];
const optsWebpack = [];
const mappedModules = {};

// Transform an object of
// {
// a: 'foo',
// b: { c: 'bar' },
// d: ['baz', 'qux']
// }
// into
// {
// a: () => import('foo'),
// b.c: () => import('bar'),
// d.0: () => import('baz'),
// d.1: () => import('qux'),
// }
// for React Loadable to process.
function traverseModules(module, keys) {
if (Array.isArray(module)) {
module.forEach((value, index) => {
traverseModules(value, [...keys, index]);
});
return;
}

if (typeof module === 'object') {
Object.keys(module).forEach(key => {
traverseModules(module[key], [...keys, key]);
});
return;
}

mappedModules[keys.join('.')] = registry[module].importStatement;
optsModules.push(registry[module].module);
optsWebpack.push(registry[module].webpack);
}

traverseModules(modules, []);

return Loadable.Map({
loading: Loading,
loader: mappedModules,
// We need to provide opts.modules and opts.webpack to React Loadable
// Our loader is now dynamical, the react-loadable/babel won't do the heavy lifting for us.
// https://github.com/jamiebuilds/react-loadable#declaring-which-modules-are-being-loaded
modules: optsModules,
webpack: () => optsWebpack,
render: (loaded, props) => {
// Transform back loaded modules back into the original structure.
const loadedModules = originalModules;
Object.keys(loaded).forEach(key => {
let val = loadedModules;
const keyPath = key.split('.');
for (let i = 0; i < keyPath.length - 1; i += 1) {
val = val[keyPath[i]];
}
val[keyPath[keyPath.length - 1]] = loaded[key].default;
});

const Component = loadedModules.component;
delete loadedModules.component;
return <Component {...loadedModules} {...props} />;
},
});
}

export default ComponentCreator;
2 changes: 1 addition & 1 deletion packages/docusaurus/lib/default-theme/BlogPage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function BlogPage(props) {
const {baseUrl, favicon} = siteConfig;
const {
metadata: {posts = []},
modules: BlogPosts,
entries: BlogPosts,
} = props;

return (
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus/lib/default-theme/BlogPost/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ function BlogPost(props) {
);
const {baseUrl, favicon} = siteConfig;
const {language, title} = contextMetadata;
const {modules, metadata} = props;
const BlogPostContents = modules[0];
const {content, metadata} = props;
const BlogPostContents = content;

return (
<Layout>
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus/lib/default-theme/DocBody/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ import Head from '@docusaurus/Head';
import styles from './styles.module.css';

function DocBody(props) {
const {metadata, modules} = props;
const {metadata, content} = props;
const {language, version} = metadata;
const context = useContext(DocusaurusContext);
useEffect(() => {
context.setContext({metadata});
}, []);

const DocContents = modules[0];
const DocContents = content;
return (
<div className={styles.docBody}>
<Head>
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus/lib/default-theme/Pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ import Layout from '@theme/Layout'; // eslint-disable-line

import DocusaurusContext from '@docusaurus/context';

function Pages({modules}) {
function Pages({content}) {
const context = useContext(DocusaurusContext);
const {metadata = {}, siteConfig = {}} = context;
const {baseUrl, favicon} = siteConfig;
const {language} = metadata;
const PageContents = modules[0];
const PageContents = content;

return (
<Layout>
Expand Down
16 changes: 12 additions & 4 deletions packages/docusaurus/lib/server/load/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,27 @@ module.exports = async function load(siteDir, cliOptions = {}) {

// Routing
const {
registry,
routesAsyncModules,
routesConfig,
routesMetadata,
routesMetadataPath,
routesPaths,
} = await loadRoutes(pluginsRouteConfigs);

// Mapping of routePath -> metadataPath. Example: '/blog' -> '@generated/metadata/blog-c06.json'
// Very useful to know which json metadata file is related to certain route
await generate(
generatedFilesDir,
'routesMetadataPath.json',
JSON.stringify(routesMetadataPath, null, 2),
'registry.js',
`export default {
${Object.keys(registry)
.map(
key => ` '${key}': {
'importStatement': ${registry[key].importStatement},
'module': '${registry[key].modulePath}',
'webpack': require.resolveWeak('${registry[key].modulePath}'),
},`,
)
.join('\n')}};\n`,
);

// Mapping of routePath -> async imported modules. Example: '/blog' -> ['@theme/BlogPage']
Expand Down
1 change: 1 addition & 0 deletions packages/docusaurus/lib/server/load/plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ module.exports = async function loadPlugins({pluginConfigs = [], context}) {

// 3. Plugin lifecycle - contentLoaded
const pluginsRouteConfigs = [];

const actions = {
addRoute: config => pluginsRouteConfigs.push(config),
};
Expand Down
Loading