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 4 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,
},
})),
routeModules: {
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],
routeModules: {
content: metadataItem.source,
},
});
});
}
Expand Down
9 changes: 7 additions & 2 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 @@ -94,6 +94,11 @@ 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'),
);
});

test('idx', () => {
Expand Down
17 changes: 12 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,16 @@ 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);
const str = preferredName || modulePath;
if (!chunkName) {
const name = str === '/' ? 'index' : docuHash(str);
chunkName = prefix ? `${prefix}---${name}` : name;
chunkNameCache.set(modulePath, chunkName);
}
return chunkName;
}

function idx(target, keyPaths) {
Expand Down
77 changes: 77 additions & 0 deletions packages/docusaurus/lib/client/exports/ContentRenderer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* 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 cloneDeep from 'lodash/cloneDeep';
import routesAsyncModules from '@generated/routesAsyncModules';
import registry from '@generated/registry';

function ContentRenderer(props) {
const {query, render} = props;
const {path} = query;
const modules = routesAsyncModules[path];
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];
}

traverseModules(modules, []);

const LoadableComponent = Loadable.Map({
loading: Loading,
loader: mappedModules,
render: loaded => {
// Transform back loaded modules back into the original structure.
const loadedModules = cloneDeep(modules);
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;
});

return render(loadedModules, props);
},
});

return <LoadableComponent />;
}

export default ContentRenderer;
58 changes: 36 additions & 22 deletions packages/docusaurus/lib/default-theme/BlogPage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import React, {useContext} from 'react';
import Head from '@docusaurus/Head';
import ContentRenderer from '@docusaurus/ContentRenderer';
import Footer from '@theme/Footer'; // eslint-disable-line
import Layout from '@theme/Layout'; // eslint-disable-line
import DocusaurusContext from '@docusaurus/context';
Expand All @@ -18,32 +19,45 @@ function BlogPage(props) {
const {baseUrl, favicon} = siteConfig;
const {
metadata: {posts = []},
modules: BlogPosts,
} = props;

return (
<Layout>
<Head>
<title>Blog</title>
{favicon && <link rel="shortcut icon" href={baseUrl + favicon} />}
{language && <html lang={language} />}
{language && <meta name="docsearch:language" content={language} />}
</Head>
<div className="container margin-vert-xl">
<div className="row">
<div className="col col-6 col-offset-3">
{BlogPosts.map((PostContent, index) => (
<div className="margin-bottom-xl" key={index}>
<Post truncated metadata={posts[index]}>
<PostContent />
</Post>
<ContentRenderer
query={{
path: props.match.url,
}}
render={loaded => {
const {entries: BlogPosts} = loaded;
return (
<Layout>
<Head>
<title>Blog</title>
{favicon && <link rel="shortcut icon" href={baseUrl + favicon} />}
{language && <html lang={language} />}
{language && (
<meta name="docsearch:language" content={language} />
)}
</Head>
{BlogPosts && (
<div className="container margin-vert-xl">
<div className="row">
<div className="col col-6 col-offset-3">
{BlogPosts.map((PostContent, index) => (
<div className="margin-bottom-xl" key={index}>
<Post truncated metadata={posts[index]}>
<PostContent />
</Post>
</div>
))}
</div>
</div>
</div>
))}
</div>
</div>
</div>
<Footer />
</Layout>
)}
<Footer />
</Layout>
);
}}
/>
);
}

Expand Down
51 changes: 30 additions & 21 deletions packages/docusaurus/lib/default-theme/BlogPost/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import React, {useContext} from 'react';

import Head from '@docusaurus/Head';
import ContentRenderer from '@docusaurus/ContentRenderer';
import Layout from '@theme/Layout'; // eslint-disable-line
import Footer from '@theme/Footer'; // eslint-disable-line
import DocusaurusContext from '@docusaurus/context';
Expand All @@ -19,29 +20,37 @@ function BlogPost(props) {
);
const {baseUrl, favicon} = siteConfig;
const {language, title} = contextMetadata;
const {modules, metadata} = props;
const BlogPostContents = modules[0];

return (
<Layout>
<Head defaultTitle={siteConfig.title}>
{title && <title>{title}</title>}
{favicon && <link rel="shortcut icon" href={baseUrl + favicon} />}
{language && <html lang={language} />}
</Head>
{BlogPostContents && (
<div className="container margin-vert-xl">
<div className="row">
<div className="col col-6 col-offset-3">
<Post metadata={metadata}>
<BlogPostContents />
</Post>
</div>
</div>
</div>
)}
<Footer />
</Layout>
<ContentRenderer
query={{
path: props.match.url,
}}
render={loaded => {
const {content: BlogPostContents, metadata} = loaded;
return (
<Layout>
<Head defaultTitle={siteConfig.title}>
{title && <title>{title}</title>}
{favicon && <link rel="shortcut icon" href={baseUrl + favicon} />}
{language && <html lang={language} />}
</Head>
{BlogPostContents && (
<div className="container margin-vert-xl">
<div className="row">
<div className="col col-6 col-offset-3">
<Post metadata={metadata}>
<BlogPostContents />
</Post>
</div>
</div>
</div>
)}
<Footer />
</Layout>
);
}}
/>
);
}

Expand Down
12 changes: 8 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,23 @@ 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',
`module.exports = {
${Object.keys(registry)
.map(key => ` '${key}': ${registry[key]},`)
.join('\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