Skip to content

Commit

Permalink
feat(docz): add preload async route
Browse files Browse the repository at this point in the history
  • Loading branch information
pedronauck committed Dec 4, 2018
1 parent caa8151 commit f800c70
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
17 changes: 10 additions & 7 deletions packages/docz/src/components/AsyncRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { EntryMap } from '../state'
import { ComponentsMap } from './DocPreview'
import { AsyncComponent } from './AsyncComponent'

async function loadFromImports(path: string): Promise<SFC<any>> {
export async function loadFromImports(path: string): Promise<SFC<any>> {
// tslint:disable-next-line
const { imports } = await import('~imports')
const { default: Component, getInitialData } = await imports[path]()
Expand All @@ -19,30 +19,33 @@ async function loadFromImports(path: string): Promise<SFC<any>> {
/>
)

return ExportedComponent
return withMDXComponents(ExportedComponent)
}

export const loadRoute = (path: string, LoadingComponent: any) =>
importedComponent(async () => loadFromImports(path), {
LoadingComponent,
})

interface AsyncRouteProps {
asyncComponent: any
components: ComponentsMap
path: string
entries: EntryMap
}

export const AsyncRoute: SFC<AsyncRouteProps> = ({
components,
asyncComponent,
path,
entries,
...routeProps
}) => {
const Page: any = components.page
const LoadingComponent: any = components.loading
const Component: any = asyncComponent
const entry = entries && entries[path]
const props = { ...routeProps, doc: entry }

const Component = withMDXComponents(
importedComponent(async () => loadFromImports(path), { LoadingComponent })
)

return Page ? (
<Page {...props}>
<Component {...props} />
Expand Down
11 changes: 9 additions & 2 deletions packages/docz/src/components/DocPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Switch, Route, RouteComponentProps } from 'react-router-dom'
import { MDXProvider } from '@mdx-js/tag'
import { get } from 'lodash/fp'

import { AsyncRoute } from './AsyncRoute'
import { AsyncRoute, loadRoute } from './AsyncRoute'
import { state, Entry } from '../state'

export type PageProps = RouteComponentProps<any> & {
Expand Down Expand Up @@ -92,13 +92,20 @@ export const DocPreview: SFC<DocPreviewProps> = ({
{Object.keys(entries).map(path => {
const entry = get(path, entries)
const props = { path, entries, components }
const component: any = loadRoute(path, components.loading)

component.preload()
return (
<Route
exact
key={entry.id}
path={entry.route}
render={routeProps => (
<AsyncRoute {...routeProps} {...props} />
<AsyncRoute
{...routeProps}
{...props}
asyncComponent={component}
/>
)}
/>
)
Expand Down

0 comments on commit f800c70

Please sign in to comment.