@teambit/ui 0.0.553 → 0.0.557

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/compose.d.ts +5 -0
  2. package/dist/open-browser.d.ts +4 -0
  3. package/dist/render-lifecycle.d.ts +31 -0
  4. package/dist/ssr/request-browser.d.ts +35 -0
  5. package/dist/ssr/request-server.d.ts +3 -0
  6. package/dist/start-plugin.d.ts +7 -0
  7. package/dist/start.cmd.d.ts +8 -1
  8. package/dist/ui-build.cmd.d.ts +8 -1
  9. package/dist/ui-root.d.ts +24 -0
  10. package/dist/ui-server.d.ts +14 -0
  11. package/dist/ui.main.runtime.d.ts +141 -1
  12. package/dist/ui.ui.runtime.d.ts +31 -1
  13. package/dist/webpack/html.d.ts +1 -0
  14. package/package.json +32 -24
  15. package/tsconfig.json +1 -2
  16. package/compose.tsx +0 -27
  17. package/create-root.ts +0 -94
  18. package/events/index.ts +0 -1
  19. package/events/ui-server-started-event.ts +0 -14
  20. package/exceptions/index.ts +0 -2
  21. package/exceptions/unknown-build-error.ts +0 -5
  22. package/exceptions/unknown-ui.ts +0 -9
  23. package/index.ts +0 -18
  24. package/open-browser.ts +0 -128
  25. package/package-tar/teambit-ui-0.0.553.tgz +0 -0
  26. package/render-lifecycle.tsx +0 -56
  27. package/ssr/render-middleware.ts +0 -129
  28. package/ssr/request-browser.ts +0 -86
  29. package/ssr/request-server.ts +0 -10
  30. package/ssr/ssr-content.ts +0 -9
  31. package/start-plugin.ts +0 -25
  32. package/start.cmd.tsx +0 -93
  33. package/types/asset.d.ts +0 -29
  34. package/types/style.d.ts +0 -42
  35. package/ui/client-context.module.scss +0 -4
  36. package/ui/client-context.tsx +0 -28
  37. package/ui-build.cmd.tsx +0 -27
  38. package/ui-root.tsx +0 -59
  39. package/ui-root.ui.ts +0 -7
  40. package/ui-server.ts +0 -249
  41. package/ui.aspect.ts +0 -10
  42. package/ui.cli.rt.tsx +0 -10
  43. package/ui.docs.md +0 -118
  44. package/ui.main.runtime.ts +0 -573
  45. package/ui.route.ts +0 -0
  46. package/ui.runtime.ts +0 -21
  47. package/ui.ui.runtime.tsx +0 -277
  48. package/webpack/html.ts +0 -24
  49. package/webpack/postcss.config.ts +0 -22
  50. package/webpack/webpack.base.config.ts +0 -392
  51. package/webpack/webpack.browser.config.ts +0 -125
  52. package/webpack/webpack.dev.config.ts +0 -336
  53. package/webpack/webpack.ssr.config.ts +0 -38
package/start.cmd.tsx DELETED
@@ -1,93 +0,0 @@
1
- import React from 'react';
2
- import open from 'open';
3
- import { Command, CommandOptions } from '@teambit/cli';
4
- import { Logger } from '@teambit/logger';
5
- import { UIServerConsole } from '@teambit/ui-foundation.cli.ui-server-console';
6
- import type { UiMain } from './ui.main.runtime';
7
-
8
- type StartArgs = [uiName: string, userPattern: string];
9
- type StartFlags = {
10
- dev: boolean;
11
- port: string;
12
- rebuild: boolean;
13
- verbose: boolean;
14
- noBrowser: boolean;
15
- skipCompilation: boolean;
16
- };
17
-
18
- export class StartCmd implements Command {
19
- name = 'start [type] [pattern]';
20
- description = 'Start a dev environment for a workspace or a specific component';
21
- alias = 'c';
22
- group = 'development';
23
- shortDescription = '';
24
- options = [
25
- ['d', 'dev', 'start UI server in dev mode.'],
26
- ['p', 'port [number]', 'port of the UI server.'],
27
- ['r', 'rebuild', 'rebuild the UI'],
28
- ['v', 'verbose', 'showing verbose output for inspection and prints stack trace'],
29
- ['', 'no-browser', 'do not automatically open browser when ready'],
30
- ['', 'skip-compilation', 'skip the auto-compilation before starting the web-server'],
31
- ] as CommandOptions;
32
-
33
- constructor(
34
- /**
35
- * access to the extension instance.
36
- */
37
- private ui: UiMain,
38
-
39
- private logger: Logger
40
- ) {}
41
-
42
- // async report([uiRootName, userPattern]: StartArgs, { dev, port, rebuild, verbose }: StartFlags): Promise<string> {
43
- // this.logger.off();
44
- // const pattern = userPattern && userPattern.toString();
45
-
46
- // const uiServer = await this.ui.createRuntime({
47
- // uiRootName,
48
- // pattern,
49
- // dev,
50
- // port: port ? parseInt(port) : undefined,
51
- // rebuild,
52
- // verbose,
53
- // });
54
-
55
- // return `Bit server has started on port ${uiServer.port}`;
56
- // }
57
-
58
- async render(
59
- [uiRootName, userPattern]: StartArgs,
60
- { dev, port, rebuild, verbose, noBrowser, skipCompilation }: StartFlags
61
- ): Promise<React.ReactElement> {
62
- this.logger.off();
63
- const appName = this.ui.getUiName(uiRootName);
64
- await this.ui.invokePreStart({ skipCompilation });
65
- const uiServer = this.ui.createRuntime({
66
- uiRootName,
67
- pattern: userPattern,
68
- dev,
69
- port: +port,
70
- rebuild,
71
- verbose,
72
- });
73
-
74
- if (!noBrowser) {
75
- uiServer
76
- .then(async (server) => {
77
- if (!server.buildOptions?.launchBrowserOnStart) return undefined;
78
-
79
- await server.whenReady;
80
-
81
- return open(this.ui.publicUrl || server.fullUrl);
82
- })
83
- .catch((error) => this.logger.error(error));
84
- }
85
-
86
- // DO NOT CHANGE THIS - this meant to be an async hook.
87
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
88
- this.ui.invokeOnStart();
89
- this.ui.clearConsole();
90
-
91
- return <UIServerConsole appName={appName} futureUiServer={uiServer} url={this.ui.publicUrl} />;
92
- }
93
- }
package/types/asset.d.ts DELETED
@@ -1,29 +0,0 @@
1
- declare module '*.png' {
2
- const value: any;
3
- export = value;
4
- }
5
- declare module '*.svg' {
6
- import type { FunctionComponent, SVGProps } from 'react';
7
-
8
- export const ReactComponent: FunctionComponent<SVGProps<SVGSVGElement> & { title?: string }>;
9
- const src: string;
10
- export default src;
11
- }
12
-
13
- // @TODO Gilad
14
- declare module '*.jpg' {
15
- const value: any;
16
- export = value;
17
- }
18
- declare module '*.jpeg' {
19
- const value: any;
20
- export = value;
21
- }
22
- declare module '*.gif' {
23
- const value: any;
24
- export = value;
25
- }
26
- declare module '*.bmp' {
27
- const value: any;
28
- export = value;
29
- }
package/types/style.d.ts DELETED
@@ -1,42 +0,0 @@
1
- declare module '*.module.css' {
2
- const classes: { readonly [key: string]: string };
3
- export default classes;
4
- }
5
- declare module '*.module.scss' {
6
- const classes: { readonly [key: string]: string };
7
- export default classes;
8
- }
9
- declare module '*.module.sass' {
10
- const classes: { readonly [key: string]: string };
11
- export default classes;
12
- }
13
-
14
- declare module '*.module.less' {
15
- const classes: { readonly [key: string]: string };
16
- export default classes;
17
- }
18
-
19
- declare module '*.less' {
20
- const classes: { readonly [key: string]: string };
21
- export default classes;
22
- }
23
-
24
- declare module '*.css' {
25
- const classes: { readonly [key: string]: string };
26
- export default classes;
27
- }
28
-
29
- declare module '*.sass' {
30
- const classes: { readonly [key: string]: string };
31
- export default classes;
32
- }
33
-
34
- declare module '*.scss' {
35
- const classes: { readonly [key: string]: string };
36
- export default classes;
37
- }
38
-
39
- declare module '*.mdx' {
40
- const component: any;
41
- export default component;
42
- }
@@ -1,4 +0,0 @@
1
- .loader {
2
- position: fixed;
3
- z-index: 20;
4
- }
@@ -1,28 +0,0 @@
1
- import React, { ReactNode } from 'react';
2
- import { Theme } from '@teambit/base-ui.theme.theme-provider';
3
- import { IconFont } from '@teambit/design.theme.icons-font';
4
- import { LoaderRibbon } from '@teambit/base-ui.loaders.loader-ribbon';
5
- import { Roboto } from '@teambit/base-ui.theme.fonts.roboto';
6
- import { TooltipMountPoint } from '@teambit/design.ui.tooltip';
7
-
8
- import { LoaderContext, useLoaderApi } from '@teambit/ui-foundation.ui.global-loader';
9
- import styles from './client-context.module.scss';
10
-
11
- export function ClientContext({ children }: { children: ReactNode }) {
12
- const [loaderApi, isLoading] = useLoaderApi();
13
-
14
- return (
15
- <React.StrictMode>
16
- {/* TODO - try moving LoaderContext to contextSlot, and LoaderRibbon to hudSlot */}
17
- <LoaderContext.Provider value={loaderApi}>
18
- <IconFont query="q76y7n" />
19
- <Theme>
20
- <Roboto />
21
- <LoaderRibbon active={isLoading} className={styles.loader} />
22
- {children}
23
- <TooltipMountPoint />
24
- </Theme>
25
- </LoaderContext.Provider>
26
- </React.StrictMode>
27
- );
28
- }
package/ui-build.cmd.tsx DELETED
@@ -1,27 +0,0 @@
1
- import { Command } from '@teambit/cli';
2
- import { UnknownBuildError } from './exceptions';
3
-
4
- import { UiMain } from './ui.main.runtime';
5
-
6
- export class UIBuildCmd implements Command {
7
- name = 'ui-build [type]';
8
- description = 'build production assets for deployment.';
9
- alias = 'c';
10
- group = 'development';
11
- shortDescription = '';
12
- options = [];
13
-
14
- constructor(
15
- /**
16
- * access to the extension instance.
17
- */
18
- private ui: UiMain
19
- ) {}
20
-
21
- async report([type]: [string]): Promise<string> {
22
- // teambit.workspace/variants should be the one to take care of component patterns.
23
- const stats = await this.ui.build(type);
24
- if (!stats) throw new UnknownBuildError();
25
- return stats.toString();
26
- }
27
- }
package/ui-root.tsx DELETED
@@ -1,59 +0,0 @@
1
- import { AspectDefinition } from '@teambit/aspect-loader';
2
- import { ComponentDir } from '@teambit/bundler';
3
- import { Component } from '@teambit/component';
4
- import { ProxyConfigArrayItem } from 'webpack-dev-server';
5
-
6
- // TODO: remove this extends "ComponentDir", this should be part of the workspace alone since scope
7
- // would never have componentDir and as it has nothing to do with `UIRoot`.
8
- export interface UIRoot extends ComponentDir {
9
- /**
10
- * unique name of the ui.
11
- */
12
- name: string;
13
-
14
- /**
15
- * path of the ui root.
16
- */
17
- path: string;
18
-
19
- /**
20
- * name of the UI root config file.
21
- */
22
- configFile: string;
23
-
24
- buildOptions?: {
25
- ssr?: boolean;
26
- launchBrowserOnStart?: boolean;
27
- };
28
-
29
- /**
30
- * resolve all aspects in the UI root.
31
- */
32
- resolveAspects(runtimeName: string): Promise<AspectDefinition[]>;
33
-
34
- /**
35
- * resolve components from a given pattern.
36
- */
37
- resolvePattern?(pattern: string): Promise<Component[]>;
38
-
39
- /**
40
- * listener for when the dev server starts. can be used for running the watcher.
41
- */
42
- postStart?(options: PostStartOptions): Promise<void>;
43
-
44
- /**
45
- * determine whether UI should get a priority.
46
- */
47
- priority?: boolean;
48
- }
49
-
50
- export type ProxyEntry = ProxyConfigArrayItem & {
51
- context: string[]; // limit type to simplify our code. (not required)
52
- };
53
-
54
- export type PostStartOptions = {
55
- /**
56
- * pattern for selecting components in the container.
57
- */
58
- pattern?: string;
59
- };
package/ui-root.ui.ts DELETED
@@ -1,7 +0,0 @@
1
- import { RouteProps } from 'react-router-dom';
2
-
3
- export type UIRootUI = {
4
- routes: RouteProps[];
5
- };
6
-
7
- export type UIRootFactory = () => UIRootUI;
package/ui-server.ts DELETED
@@ -1,249 +0,0 @@
1
- import { flatten } from 'lodash';
2
- import { ExpressMain } from '@teambit/express';
3
- import { GraphqlMain } from '@teambit/graphql';
4
- import { Logger } from '@teambit/logger';
5
- import express, { Express } from 'express';
6
- import fallback from 'express-history-api-fallback';
7
- import { Port } from '@teambit/toolbox.network.get-port';
8
- import { Server } from 'http';
9
- import httpProxy from 'http-proxy';
10
- import { join } from 'path';
11
- import webpack from 'webpack';
12
- import WebpackDevServer, { Configuration as WdsConfiguration } from 'webpack-dev-server';
13
- import { createSsrMiddleware } from './ssr/render-middleware';
14
- import { StartPlugin } from './start-plugin';
15
- import { ProxyEntry, UIRoot } from './ui-root';
16
- import { UIRuntime } from './ui.aspect';
17
- import { UiMain } from './ui.main.runtime';
18
-
19
- import { devConfig } from './webpack/webpack.dev.config';
20
-
21
- export type UIServerProps = {
22
- graphql: GraphqlMain;
23
- express: ExpressMain;
24
- ui: UiMain;
25
- uiRoot: UIRoot;
26
- uiRootExtension: string;
27
- logger: Logger;
28
- publicDir: string;
29
- startPlugins: StartPlugin[];
30
- };
31
-
32
- export type StartOptions = {
33
- /**
34
- * port range for the UI server to bind. default is a port range of 4000-4200.
35
- */
36
- portRange?: number[] | number;
37
- };
38
-
39
- export class UIServer {
40
- constructor(
41
- private graphql: GraphqlMain,
42
- private expressExtension: ExpressMain,
43
- private ui: UiMain,
44
- private uiRoot: UIRoot,
45
- private uiRootExtension: string,
46
- private logger: Logger,
47
- private publicDir: string,
48
- private plugins: StartPlugin[]
49
- ) {}
50
-
51
- getName() {
52
- return this.uiRoot.name;
53
- }
54
-
55
- private _port = 0;
56
-
57
- get port() {
58
- return this._port;
59
- }
60
-
61
- /** the hostname for the server to listen at. Currently statically 'localhost' */
62
- get host() {
63
- return 'localhost';
64
- }
65
-
66
- /** the server listens at this url */
67
- get fullUrl() {
68
- const port = this.port !== 80 ? `:${this.port}` : '';
69
- return `http://${this.host}${port}`;
70
- }
71
-
72
- get buildOptions() {
73
- return this.uiRoot.buildOptions;
74
- }
75
-
76
- /**
77
- * get the webpack configuration of the UI server.
78
- */
79
- async getDevConfig() {
80
- const aspects = await this.uiRoot.resolveAspects(UIRuntime.name);
81
- const aspectsPaths = aspects.map((aspect) => aspect.aspectPath);
82
-
83
- return devConfig(
84
- this.uiRoot.path,
85
- [await this.ui.generateRoot(aspects, this.uiRootExtension)],
86
- this.uiRoot.name,
87
- aspectsPaths
88
- );
89
- }
90
-
91
- private setReady: () => void;
92
- private startPromise = new Promise<void>((resolve) => (this.setReady = resolve));
93
- get whenReady() {
94
- return Promise.all([this.startPromise, ...this.plugins.map((x) => x?.whenReady)]);
95
- }
96
-
97
- /**
98
- * start a UI server.
99
- */
100
- async start({ portRange }: StartOptions = {}) {
101
- const app = this.expressExtension.createApp();
102
- const publicDir = `/${this.publicDir}`;
103
- const root = join(this.uiRoot.path, publicDir);
104
- const server = await this.graphql.createServer({ app });
105
-
106
- // set up proxy, for things like preview, e.g. '/preview/teambit.react/react'
107
- await this.configureProxy(app, server);
108
-
109
- // pass through files from public /folder:
110
- // setting `index: false` so index.html will be served by the fallback() middleware
111
- app.use(express.static(root, { index: false }));
112
-
113
- const port = await Port.getPortFromRange(portRange || [3100, 3200]);
114
-
115
- await this.setupServerSideRendering({ root, port, app });
116
-
117
- // in any and all other cases, serve index.html.
118
- // No any other endpoints past this will execute
119
- app.use(fallback('index.html', { root }));
120
-
121
- server.listen(port);
122
- this._port = port;
123
-
124
- // important: we use the string of the following message for the http.e2e.ts. if you change the message,
125
- // please make sure you change the `HTTP_SERVER_READY_MSG` const.
126
- this.logger.info(`UI server of ${this.uiRootExtension} is listening to port ${port}`);
127
-
128
- this.setReady();
129
- }
130
-
131
- getPluginsComponents() {
132
- return this.plugins.map((plugin) => plugin.render);
133
- }
134
-
135
- private async setupServerSideRendering({ root, port, app }: { root: string; port: number; app: Express }) {
136
- if (!this.buildOptions?.ssr) return;
137
-
138
- const ssrMiddleware = await createSsrMiddleware({
139
- root,
140
- port,
141
- title: this.uiRoot.name,
142
- logger: this.logger,
143
- });
144
-
145
- if (!ssrMiddleware) {
146
- this.logger.warn('[ssr] middleware failed setup');
147
- return;
148
- }
149
-
150
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
151
- app.get('*', ssrMiddleware);
152
- this.logger.debug('[ssr] serving for "*"');
153
- }
154
-
155
- private async configureProxy(app: Express, server: Server) {
156
- const proxServer = httpProxy.createProxyServer();
157
- proxServer.on('error', (e) => this.logger.error(e.message));
158
- const proxyEntries = await this.getProxyFromPlugins();
159
- server.on('upgrade', function (req, socket, head) {
160
- const entry = proxyEntries.find((proxy) => proxy.context.some((item) => item === req.url));
161
- if (!entry) return;
162
- proxServer.ws(req, socket, head, {
163
- target: entry.target,
164
- });
165
- });
166
-
167
- proxyEntries.forEach((entry) => {
168
- entry.context.forEach((route) => {
169
- app.use(`${route}/*`, (req, res) => {
170
- proxServer.web(req, res, { ...entry, target: `${entry.target}/${req.originalUrl}` });
171
- });
172
- });
173
- });
174
- }
175
-
176
- /**
177
- * start a UI dev server.
178
- */
179
- async dev({ portRange }: StartOptions = {}) {
180
- const devServerPort = await this.selectPort(portRange);
181
- await this.start({ portRange: [4100, 4200] });
182
- const expressAppPort = this._port;
183
-
184
- const config = await this.getDevConfig();
185
- const compiler = webpack(config);
186
- const devServerConfig = await this.getDevServerConfig(devServerPort, expressAppPort, config.devServer);
187
- // @ts-ignore in the capsules it throws an error about compatibilities issues between webpack.compiler and webpackDevServer/webpack/compiler
188
- const devServer = new WebpackDevServer(devServerConfig, compiler);
189
-
190
- await devServer.start();
191
- this._port = devServerPort;
192
- return devServer;
193
- }
194
-
195
- private async selectPort(portRange?: number[] | number) {
196
- return Port.getPortFromRange(portRange || [3100, 3200]);
197
- }
198
-
199
- private async getProxyFromPlugins(): Promise<ProxyEntry[]> {
200
- const proxiesByPlugin = this.plugins.map((plugin) => {
201
- return plugin.getProxy ? plugin.getProxy() : [];
202
- });
203
-
204
- return flatten(await Promise.all(proxiesByPlugin));
205
- }
206
-
207
- private async getProxy(port = 4000) {
208
- const proxyEntries = await this.getProxyFromPlugins();
209
-
210
- const gqlProxies: ProxyEntry[] = [
211
- {
212
- context: ['/graphql', '/api'],
213
- target: `http://${this.host}:${port}`,
214
- changeOrigin: true,
215
- },
216
- {
217
- context: ['/subscriptions'],
218
- target: `ws://${this.host}:${port}`,
219
- ws: true,
220
- },
221
- ];
222
-
223
- return gqlProxies.concat(proxyEntries);
224
- }
225
-
226
- private async getDevServerConfig(
227
- appPort: number,
228
- gqlPort: number,
229
- config?: WdsConfiguration
230
- ): Promise<WdsConfiguration> {
231
- const proxy = await this.getProxy(gqlPort);
232
- const devServerConf = { ...config, proxy, port: appPort };
233
-
234
- return devServerConf;
235
- }
236
-
237
- static create(props: UIServerProps) {
238
- return new UIServer(
239
- props.graphql,
240
- props.express,
241
- props.ui,
242
- props.uiRoot,
243
- props.uiRootExtension,
244
- props.logger,
245
- props.publicDir,
246
- props.startPlugins
247
- );
248
- }
249
- }
package/ui.aspect.ts DELETED
@@ -1,10 +0,0 @@
1
- import { Aspect, RuntimeDefinition } from '@teambit/harmony';
2
-
3
- export const UIRuntime = new RuntimeDefinition('ui');
4
-
5
- export const UIAspect = Aspect.create({
6
- id: 'teambit.ui-foundation/ui',
7
- declareRuntime: UIRuntime,
8
- });
9
-
10
- export default UIAspect;
package/ui.cli.rt.tsx DELETED
@@ -1,10 +0,0 @@
1
- // import { CLIExtension } from '../cli';
2
- // import { StartCmd } from './start.cmd';
3
- // import { Workspace } from '../workspace';
4
- // import { GraphQLExtension } from '../graphql';
5
-
6
- // export default ([cli, envs, workspace, graphql]: [CLIExtension, Environments, Workspace, GraphQLExtension]) => {
7
- // // const ui = new UIExtension(envs, graphql);
8
- // cli.register(new StartCmd(ui, workspace));
9
- // // return ui;
10
- // }
package/ui.docs.md DELETED
@@ -1,118 +0,0 @@
1
- ## Server-side rendering
2
-
3
- Server side rendering (or SSR) is done in the following form:
4
-
5
- ```tsx
6
- /** at server: */
7
- const dom = ReactDom.renderToString(<MountPoint>{app}</MountPoint>);
8
- const assets = { headers, scripts, ... };
9
- const html = ReactDom.renderStaticMarkup(<Html assets={assets}/>);
10
- Html.fillContent(html, dom);
11
- send(html);
12
-
13
- /** at client: */
14
- ReactDom.render(app, mountPoint);
15
- // or .hydrate()
16
- ```
17
-
18
- We can then enrich the page with hooks:
19
-
20
- ```tsx
21
- /** at server: */
22
- let context = hooks.serverInit();
23
- const app = (
24
- <hooks.reactContext value={context}>
25
- <App />
26
- </hooks.reactContext>
27
- );
28
-
29
- context = hooks.onBeforeRender(app, context);
30
- const dom = ...
31
-
32
- const assets = hooks.serialize(context);
33
- const html = ...
34
- send(html);
35
-
36
- /** at client: */
37
- const parsed = hooks.deserialize();
38
- const context = hooks.browserInit(parsed);
39
- const app = (
40
- <hooks.reactContext value={context}>
41
- <App />
42
- </hooks.reactContext>
43
- )
44
-
45
- hooks.onBeforeHydrate(app, context);
46
-
47
- const ref = ReactDom.render(app, mountPoint);
48
-
49
- hooks.onHydrate(ref, context);
50
- ```
51
-
52
- The rendering flow will ensure that the rendering Context will be unique per request, and separate between aspects.
53
-
54
- ### Hiding elements before JS execution
55
-
56
- Certain items look bad in the static HTML, and only get decent after JS executes. Tooltips are a notable example. They take up space in the DOM and only hide once their react code runs.
57
- For these cases, use the convenience class `--ssr-hidden`. Add this to any misbehaving elements, and it will hide them using `display: none` until reactDom.render() is complete.
58
-
59
- ### .rehydrate vs .render()
60
-
61
- .rehydrate() attach a React virtual dom to a mount point, without asserting the virtual-dom matches the actual dom.
62
- .render() updates the mount point to match the react virtual dom.
63
-
64
- On paper, `.rehydrate()` should be the preferred option, with better performance.
65
- In practice, `.render()` is backward compatible to React 15, and will know to "hydrate" according to the `data-reactroot` attribute on the mount point, with similar performance, and without revalidating the DOM.
66
- ReactDOM will also show warnings in dev mode about mismatch between ssr dom and the client side dom.
67
-
68
- ### Best practices
69
-
70
- - Use ReactContext instead of trying to mutate `App`.
71
- - Use existing context object.
72
- - Do not use other Aspects' context object.
73
- - Try to keep process symmetrical between server and client;
74
-
75
- #### Example: Server side GraphQL
76
-
77
- Graphql adds extra instructions to pre-fetch queries on the server:
78
-
79
- ```tsx
80
- // .registerRenderHooks() ?
81
- .registerRenderLifecycle({
82
- serverInit: ({ browser }) => {
83
- const { cookie } = browser;
84
- return { client: new Client(GQL_INTERNAL, { cookie }) };
85
- },
86
- beforeRender: ({ client }, app) => {
87
- await getDataFromTree(app);
88
- },
89
- serialize: ({ client }, app) => {
90
- return { json: JSON.stringify(client.extract()) };
91
- },
92
- deserialize: (raw) => {
93
- return { state: JSON.parse(raw) };
94
- },
95
- browserInit: ({ state }) => {
96
- return { client: new GraphqlClient(GQL_EXTERNAL, { cache: state })}
97
- },
98
- ReactContext: ({state, children}) =>
99
- <GqlContext client={state.client}>{children}</GqlContext>
100
- });
101
- ```
102
-
103
- #### Example: Server side Styled-components
104
-
105
- StyledComponents extracts css from page, and adds it to the `<head/>`:
106
-
107
- ```tsx
108
- .registerRenderLifecycle({
109
- init: () => {
110
- return { sheet: new ServerStyleSheet() };
111
- },
112
- serialize: (app, { sheet }) => {
113
- return { styles: sheet.getStyleTags() };
114
- };
115
- ReactContext: ({state, children}) =>
116
- <StyleSheetManager sheet={state.sheet}>{children}</StyleSheetManager>
117
- });
118
- ```