-
-
Notifications
You must be signed in to change notification settings - Fork 631
/
Copy pathclientStartup.ts
293 lines (250 loc) · 9 KB
/
clientStartup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import ReactDOM from 'react-dom';
import type { ReactElement } from 'react';
import type {
RailsContext,
ReactOnRails as ReactOnRailsType,
RegisteredComponent,
RenderFunction,
} from './types/index';
import createReactOutput from './createReactOutput';
import {isServerRenderHash} from './isServerRenderResult';
declare global {
interface Window {
ReactOnRails: ReactOnRailsType;
__REACT_ON_RAILS_EVENT_HANDLERS_RAN_ONCE__?: boolean;
}
namespace NodeJS {
interface Global {
ReactOnRails: ReactOnRailsType;
}
}
namespace Turbolinks {
interface TurbolinksStatic {
controller?: unknown;
}
}
}
declare const ReactOnRails: ReactOnRailsType;
const REACT_ON_RAILS_STORE_ATTRIBUTE = 'data-js-react-on-rails-store';
function findContext(): Window | NodeJS.Global {
if (typeof window.ReactOnRails !== 'undefined') {
return window;
} else if (typeof ReactOnRails !== 'undefined') {
return global;
}
throw new Error(`\
ReactOnRails is undefined in both global and window namespaces.
`);
}
function debugTurbolinks(...msg: string[]): void {
if (!window) {
return;
}
const context = findContext();
if (context.ReactOnRails && context.ReactOnRails.option('traceTurbolinks')) {
console.log('TURBO:', ...msg);
}
}
function turbolinksInstalled(): boolean {
return (typeof Turbolinks !== 'undefined');
}
function turboInstalled() {
const context = findContext();
if (context.ReactOnRails) {
return context.ReactOnRails.option('turbo') === true;
}
return false;
}
function reactOnRailsHtmlElements(): HTMLCollectionOf<Element> {
return document.getElementsByClassName('js-react-on-rails-component');
}
function forEachReactOnRailsComponentInitialize(fn: (element: Element, railsContext: RailsContext) => void, railsContext: RailsContext): void {
const els = reactOnRailsHtmlElements();
for (let i = 0; i < els.length; i += 1) {
fn(els[i], railsContext);
}
}
function initializeStore(el: Element, railsContext: RailsContext): void {
const context = findContext();
const name = el.getAttribute(REACT_ON_RAILS_STORE_ATTRIBUTE) || "";
const props = (el.textContent !== null) ? JSON.parse(el.textContent) : {};
const storeGenerator = context.ReactOnRails.getStoreGenerator(name);
const store = storeGenerator(props, railsContext);
context.ReactOnRails.setStore(name, store);
}
function forEachStore(railsContext: RailsContext): void {
const els = document.querySelectorAll(`[${REACT_ON_RAILS_STORE_ATTRIBUTE}]`);
for (let i = 0; i < els.length; i += 1) {
initializeStore(els[i], railsContext);
}
}
function turbolinksVersion5(): boolean {
return (typeof Turbolinks.controller !== 'undefined');
}
function turbolinksSupported(): boolean {
return Turbolinks.supported;
}
function delegateToRenderer(
componentObj: RegisteredComponent,
props: Record<string, string>,
railsContext: RailsContext,
domNodeId: string,
trace: boolean
): boolean {
const { name, component, isRenderer } = componentObj;
if (isRenderer) {
if (trace) {
console.log(`\
DELEGATING TO RENDERER ${name} for dom node with id: ${domNodeId} with props, railsContext:`,
props, railsContext);
}
(component as RenderFunction)(props, railsContext, domNodeId);
return true;
}
return false;
}
function domNodeIdForEl(el: Element): string {
return el.getAttribute('data-dom-id') || "";
}
/**
* Used for client rendering by ReactOnRails. Either calls ReactDOM.hydrate, ReactDOM.render, or
* delegates to a renderer registered by the user.
* @param el
*/
function render(el: Element, railsContext: RailsContext): void {
const context = findContext();
// This must match lib/react_on_rails/helper.rb
const name = el.getAttribute('data-component-name') || "";
const domNodeId = domNodeIdForEl(el);
const props = (el.textContent !== null) ? JSON.parse(el.textContent) : {};
const trace = el.getAttribute('data-trace') === "true";
try {
const domNode = document.getElementById(domNodeId);
if (domNode) {
const componentObj = context.ReactOnRails.getComponent(name);
if (delegateToRenderer(componentObj, props, railsContext, domNodeId, trace)) {
return;
}
// Hydrate if available and was server rendered
const shouldHydrate = !!ReactDOM.hydrate && !!domNode.innerHTML;
const reactElementOrRouterResult = createReactOutput({
componentObj,
props,
domNodeId,
trace,
railsContext,
shouldHydrate,
});
if (isServerRenderHash(reactElementOrRouterResult)) {
throw new Error(`\
You returned a server side type of react-router error: ${JSON.stringify(reactElementOrRouterResult)}
You should return a React.Component always for the client side entry point.`);
} else if (shouldHydrate) {
ReactDOM.hydrate(reactElementOrRouterResult as ReactElement, domNode);
} else {
ReactDOM.render(reactElementOrRouterResult as ReactElement, domNode);
}
}
} catch (e) {
e.message = `ReactOnRails encountered an error while rendering component: ${name}.\n` +
`Original message: ${e.message}`;
throw e;
}
}
function parseRailsContext(): RailsContext | null {
const el = document.getElementById('js-react-on-rails-context');
if (!el) {
// The HTML page will not have an element with ID 'js-react-on-rails-context' if there are no
// react on rails components
return null;
}
if (!el.textContent) {
throw new Error("The HTML element with ID 'js-react-on-rails-context' has no textContent");
}
return JSON.parse(el.textContent);
}
export function reactOnRailsPageLoaded(): void {
debugTurbolinks('reactOnRailsPageLoaded');
const railsContext = parseRailsContext();
// If no react on rails components
if (!railsContext) return;
forEachStore(railsContext);
forEachReactOnRailsComponentInitialize(render, railsContext);
}
function unmount(el: Element): void {
const domNodeId = domNodeIdForEl(el);
const domNode = document.getElementById(domNodeId);
if(domNode === null){return;}
try {
ReactDOM.unmountComponentAtNode(domNode);
} catch (e) {
console.info(`Caught error calling unmountComponentAtNode: ${e.message} for domNode`,
domNode, e);
}
}
function reactOnRailsPageUnloaded(): void {
debugTurbolinks('reactOnRailsPageUnloaded');
const els = reactOnRailsHtmlElements();
for (let i = 0; i < els.length; i += 1) {
unmount(els[i]);
}
}
function renderInit(): void {
// Install listeners when running on the client (browser).
// We must do this check for turbolinks AFTER the document is loaded because we load the
// Webpack bundles first.
if ((!turbolinksInstalled() || !turbolinksSupported()) && !turboInstalled()) {
debugTurbolinks('NOT USING TURBOLINKS: calling reactOnRailsPageLoaded');
reactOnRailsPageLoaded();
return;
}
if (turboInstalled()) {
debugTurbolinks(
'USING TURBO: document added event listeners ' +
'turbo:before-render and turbo:render.');
document.addEventListener('turbo:before-render', reactOnRailsPageUnloaded);
document.addEventListener('turbo:render', reactOnRailsPageLoaded);
reactOnRailsPageLoaded();
} else if (turbolinksVersion5()) {
debugTurbolinks(
'USING TURBOLINKS 5: document added event listeners ' +
'turbolinks:before-render and turbolinks:render.');
document.addEventListener('turbolinks:before-render', reactOnRailsPageUnloaded);
document.addEventListener('turbolinks:render', reactOnRailsPageLoaded);
reactOnRailsPageLoaded();
} else {
debugTurbolinks(
'USING TURBOLINKS 2: document added event listeners page:before-unload and ' +
'page:change.');
document.addEventListener('page:before-unload', reactOnRailsPageUnloaded);
document.addEventListener('page:change', reactOnRailsPageLoaded);
}
}
function isWindow (context: Window | NodeJS.Global): context is Window {
return (context as Window).document !== undefined;
}
export function clientStartup(context: Window | NodeJS.Global): void {
// Check if server rendering
if (!isWindow(context)) {
return;
}
const { document } = context;
// Tried with a file local variable, but the install handler gets called twice.
// eslint-disable-next-line no-underscore-dangle
if (context.__REACT_ON_RAILS_EVENT_HANDLERS_RAN_ONCE__) {
return;
}
// eslint-disable-next-line no-underscore-dangle, no-param-reassign
context.__REACT_ON_RAILS_EVENT_HANDLERS_RAN_ONCE__ = true;
debugTurbolinks('Adding DOMContentLoaded event to install event listeners.');
// So long as the document is not loading, we can assume:
// The document has finished loading and the document has been parsed
// but sub-resources such as images, stylesheets and frames are still loading.
// If lazy asynch loading is used, such as with loadable-components, then the init
// function will install some handler that will properly know when to do hyrdation.
if (document.readyState !== 'loading') {
window.setTimeout(renderInit);
} else {
document.addEventListener('DOMContentLoaded', renderInit);
}
}