-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
91 lines (74 loc) · 2.79 KB
/
index.tsx
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
import React from 'react';
import ReactDOM from 'react-dom';
import whenDomReady from 'when-dom-ready';
interface Isomorphism<T> {
pageName: string;
render(args: T): JSX.Element;
}
namespace Isomorphism {
export class Builder<T> {
private _initAction: Array<() => void> = [];
private _domReady: Array<() => void> = [];
constructor(private pageName: string,
private readonly renderer: (args: T, isBorserSide: boolean) => JSX.Element,
private readonly renderArgsHolderId = 'x-render-args-holder') {
}
appendDomReadyAction(action: () => void): this {
this._domReady.push(action);
return this;
}
appendInitAction(action: () => void): this {
this._initAction.push(action);
return this;
}
build(): Isomorphism<T> {
if (typeof document != 'undefined') {
// Client side
this._initAction.forEach((fn) => {
try {
fn();
} catch (e) {
console.error(e);
}
});
let args: T;
let dataElement = document.getElementById(this.renderArgsHolderId);
try {
if (!dataElement)
throw new Error(`Element #${this.renderArgsHolderId} not found`);
if (dataElement.tagName.toLowerCase() === 'script')
args = JSON.parse(dataElement.innerHTML) as T;
else if (dataElement.tagName.toLowerCase() === 'meta')
args = JSON.parse(dataElement.getAttribute('content')) as T;
dataElement.remove();
} catch (e) {
console.error(e.message);
alert('Page is not setup properly');
}
let element = this.renderer(args, true);
whenDomReady()
.then(() => {
ReactDOM.hydrate(element, document.getElementById('x-react-container'));
this._domReady.forEach((fn) => {
try {
fn();
} catch (e) {
console.error(e);
}
});
});
}
return new ReactPage<T>(this.pageName, this.renderer);
}
}
}
export default Isomorphism;
class ReactPage<T> {
constructor(
public pageName: string,
private renderer: (args: T, isBrowserSide: boolean) => JSX.Element) {
}
render(args: T): JSX.Element {
return this.renderer(args, false);
}
}