Skip to content

Commit

Permalink
chore: export hydrate from standalone build
Browse files Browse the repository at this point in the history
  • Loading branch information
RomanHotsiy committed Mar 7, 2018
1 parent 8757fa5 commit 0658b8e
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 23 deletions.
2 changes: 1 addition & 1 deletion custom.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ declare module '*.css' {
export default content;
}

declare var __DEV__: boolean;
declare var __REDOC_DEV__: boolean;
declare var __REDOC_VERSION__: string;
declare var __REDOC_REVISION__: string;

Expand Down
19 changes: 7 additions & 12 deletions demo/ssr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const server = http.createServer(async (request, response) => {
fs.createReadStream('bundles/redoc.standalone.js', 'utf8').pipe(response);
} else if (request.url === '/') {
const spec = yaml.load(readFileSync(resolve(__dirname, '../openapi.yaml')));
let store = await createStore(spec, '', { nativeScrollbars: true });
let store = await createStore(spec, 'path/to/spec.yaml');

const sheet = new ServerStyleSheet();

Expand All @@ -37,26 +37,21 @@ const server = http.createServer(async (request, response) => {
margin: 0;
}
</style>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<script src="redoc.standalone.js"></script>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
${css}
</head>
<body>
<div id="redoc">${html}</div>
<script>
const state = ${JSON.stringify(await store.toJS())};
const store = Redoc.AppStore.fromJS(state);
<script>
document.addEventListener('DOMContentLoaded', function() {
console.time('ReDoc hydrate');
ReactDOM.hydrate(React.createElement(Redoc.Redoc, {store: store}), document.getElementById('redoc'));
console.timeEnd('ReDoc hydrate');
const state = ${JSON.stringify(await store.toJS())};
Redoc.hydrate(state, document.getElementById('redoc'));
});
</script>
</script>
<div id="redoc">${html}</div>
</body>
</html>`;
response.writeHead(200);
response.writeHead(200, { 'Content-Length': res.length });
response.write(res);
response.end();
} else {
Expand Down
4 changes: 2 additions & 2 deletions src/__tests__/ssr.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import { resolve } from 'path';

describe('SSR', () => {
it('should render in SSR mode', async () => {
(global as any).__DEV__ = true;
(global as any).__REDOC_DEV__ = true;
const spec = yaml.load(readFileSync(resolve(__dirname, '../../demo/openapi.yaml')));
const store = await createStore(spec, '');
expect(() => {
renderToString(<Redoc store={store} />);
}).not.toThrow();

delete (global as any).__DEV__;
delete (global as any).__REDOC_DEV__;
});
});
6 changes: 3 additions & 3 deletions src/services/AppStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { RedocNormalizedOptions, RedocRawOptions } from './RedocNormalizedOption
import { ScrollService } from './ScrollService';
import { SearchStore } from './SearchStore';

interface StoreData {
export interface StoreState {
menu: {
activeItemIdx: number;
};
Expand All @@ -36,7 +36,7 @@ export class AppStore {
* **SUPER HACKY AND NOT OPTIMAL IMPLEMENTATION**
*/
// TODO:
static fromJS(state: StoreData): AppStore {
static fromJS(state: StoreState): AppStore {
const inst = new AppStore(state.spec.data, state.spec.url, state.options, false);
inst.menu.activeItemIdx = state.menu.activeItemIdx || 0;
inst.menu.activate(inst.menu.flatItems[inst.menu.activeItemIdx]);
Expand Down Expand Up @@ -114,7 +114,7 @@ export class AppStore {
* **SUPER HACKY AND NOT OPTIMAL IMPLEMENTATION**
*/
// TODO:
async toJS(): Promise<StoreData> {
async toJS(): Promise<StoreState> {
return {
menu: {
activeItemIdx: this.menu.activeItemIdx,
Expand Down
2 changes: 1 addition & 1 deletion src/services/OpenAPIParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export class OpenAPIParser {
* resets visited enpoints. should be run after
*/
resetVisited() {
if (__DEV__) {
if (__REDOC_DEV__) {
// check in dev mode
for (const k in this._refCounter._counter) {
if (this._refCounter._counter[k] > 0) {
Expand Down
24 changes: 21 additions & 3 deletions src/standalone.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import * as React from 'react';
import { render } from 'react-dom';
import { render, hydrate as hydrateComponent } from 'react-dom';

import { RedocStandalone } from './components/RedocStandalone';
import { RedocStandalone, Redoc } from './components/';
import { AppStore, StoreState } from './services/AppStore';
import { querySelector } from './utils/dom';
import { debugTime, debugTimeEnd } from './utils/debug';

export { Redoc, AppStore } from './index';
export { Redoc, AppStore } from '.';

export const version = __REDOC_VERSION__;
export const revision = __REDOC_REVISION__;
Expand Down Expand Up @@ -35,6 +37,7 @@ export function init(
specOrSpecUrl: string | any,
options: any = {},
element: Element | null = querySelector('redoc'),
callback?: () => void,
) {
if (element === null) {
throw new Error('"element" argument is not provided and <redoc> tag is not found on the page');
Expand All @@ -60,9 +63,24 @@ export function init(
['Loading...'],
),
element,
callback,
);
}

export function hydrate(
state: StoreState,
element: Element | null = querySelector('redoc'),
callback?: () => void,
) {
debugTime('Redoc create store');
const store = AppStore.fromJS(state);
debugTimeEnd('Redoc create store');

debugTime('Redoc hydrate');
hydrateComponent(<Redoc store={store} />, element, callback);
debugTimeEnd('Redoc hydrate');
}

/**
* autoinit ReDoc if <redoc> tag is found on the page with "spec-url" attr
*/
Expand Down
11 changes: 11 additions & 0 deletions src/utils/debug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function debugTime(label: string) {
if (__REDOC_DEV__) {
console.time(label);
}
}

export function debugTimeEnd(label: string) {
if (__REDOC_DEV__) {
console.timeEnd(label);
}
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export * from './highlight';
export * from './loadAndBundleSpec';
export * from './dom';
export * from './decorators';
export * from './debug';
2 changes: 1 addition & 1 deletion webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export default env => {
'process.env.NODE_ENV': env.prod ? '"production"' : '"development"',
__REDOC_VERSION__: VERSION,
__REDOC_REVISION__: REVISION,
__DEV__: env.prod ? 'false' : 'true',
__REDOC_DEV__: env.prod ? 'false' : 'true',
}),
new webpack.NamedModulesPlugin(),
],
Expand Down

0 comments on commit 0658b8e

Please sign in to comment.