forked from reactive-python/reactpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvdom.tsx
More file actions
238 lines (227 loc) · 6.21 KB
/
vdom.tsx
File metadata and controls
238 lines (227 loc) · 6.21 KB
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
import React from "react";
import { ReactPyClientInterface } from "./types";
import serializeEvent from "event-to-object";
import {
ReactPyVdom,
ReactPyVdomImportSource,
ReactPyVdomEventHandler,
ReactPyModule,
BindImportSource,
ReactPyModuleBinding,
} from "./types";
import log from "./logger";
export async function loadImportSource(
vdomImportSource: ReactPyVdomImportSource,
client: ReactPyClientInterface,
): Promise<BindImportSource> {
let module: ReactPyModule;
if (vdomImportSource.sourceType === "URL") {
module = await import(vdomImportSource.source);
} else {
module = await client.loadModule(vdomImportSource.source);
}
if (typeof module.bind !== "function") {
throw new Error(
`${vdomImportSource.source} did not export a function 'bind'`,
);
}
return (node: HTMLElement) => {
const binding = module.bind(node, {
sendMessage: client.sendMessage,
onMessage: client.onMessage,
});
if (
!(
typeof binding.create === "function" &&
typeof binding.render === "function" &&
typeof binding.unmount === "function"
)
) {
log.error(`${vdomImportSource.source} returned an impropper binding`);
return null;
}
return {
render: (model) =>
binding.render(
createImportSourceElement({
client,
module,
binding,
model,
currentImportSource: vdomImportSource,
}),
),
unmount: binding.unmount,
};
};
}
function createImportSourceElement(props: {
client: ReactPyClientInterface;
module: ReactPyModule;
binding: ReactPyModuleBinding;
model: ReactPyVdom;
currentImportSource: ReactPyVdomImportSource;
}): any {
let type: any;
if (props.model.importSource) {
if (
!isImportSourceEqual(props.currentImportSource, props.model.importSource)
) {
log.error(
"Parent element import source " +
stringifyImportSource(props.currentImportSource) +
" does not match child's import source " +
stringifyImportSource(props.model.importSource),
);
return null;
} else {
type = getComponentFromModule(
props.module,
props.model.tagName,
props.model.importSource,
);
if (!type) {
// Error message logged within getComponentFromModule
return null;
}
}
} else {
type = props.model.tagName;
}
return props.binding.create(
type,
createAttributes(props.model, props.client),
createChildren(props.model, (child) =>
createImportSourceElement({
...props,
model: child,
}),
),
);
}
function getComponentFromModule(
module: ReactPyModule,
componentName: string,
importSource: ReactPyVdomImportSource,
): any {
/* Gets the component with the provided name from the provided module.
Built specifically to work on inifinitely deep nested components.
For example, component "My.Nested.Component" is accessed from
ModuleA like so: ModuleA["My"]["Nested"]["Component"].
*/
const componentParts: string[] = componentName.split(".");
let Component: any = null;
for (let i = 0; i < componentParts.length; i++) {
const iterAttr = componentParts[i];
Component = i == 0 ? module[iterAttr] : Component[iterAttr];
if (!Component) {
if (i == 0) {
log.error(
"Module from source " +
stringifyImportSource(importSource) +
` does not export ${iterAttr}`,
);
} else {
console.error(
`Component ${componentParts.slice(0, i).join(".")} from source ` +
stringifyImportSource(importSource) +
` does not have subcomponent ${iterAttr}`,
);
}
break;
}
}
return Component;
}
function isImportSourceEqual(
source1: ReactPyVdomImportSource,
source2: ReactPyVdomImportSource,
) {
return (
source1.source === source2.source &&
source1.sourceType === source2.sourceType
);
}
function stringifyImportSource(importSource: ReactPyVdomImportSource) {
return JSON.stringify({
source: importSource.source,
sourceType: importSource.sourceType,
});
}
export function createChildren<Child>(
model: ReactPyVdom,
createChild: (child: ReactPyVdom) => Child,
): (Child | string)[] {
if (!model.children) {
return [];
} else {
return model.children.map((child) => {
switch (typeof child) {
case "object":
return createChild(child);
case "string":
return child;
}
});
}
}
export function createAttributes(
model: ReactPyVdom,
client: ReactPyClientInterface,
): { [key: string]: any } {
return Object.fromEntries(
Object.entries({
// Normal HTML attributes
...model.attributes,
// Construct event handlers
...Object.fromEntries(
Object.entries(model.eventHandlers || {}).map(([name, handler]) =>
createEventHandler(client, name, handler),
),
),
}),
);
}
function createEventHandler(
client: ReactPyClientInterface,
name: string,
{ target, preventDefault, stopPropagation }: ReactPyVdomEventHandler,
): [string, () => void] {
if (target.indexOf("__javascript__: ") == 0) {
return [
name,
function (...args: any[]) {
function handleEvent(...args: any[]) {
const evalResult = eval(target.replace("__javascript__: ", ""));
if (typeof evalResult == "function") {
return evalResult(...args);
}
}
if (args.length > 0 && args[0] instanceof Event) {
return handleEvent.call(args[0].target, ...args);
} else {
return handleEvent(...args);
}
},
];
}
return [
name,
function (...args: any[]) {
const data = Array.from(args).map((value) => {
if (!(typeof value === "object" && value.nativeEvent)) {
return value;
}
const event = value as React.SyntheticEvent<any>;
if (preventDefault) {
event.preventDefault();
}
if (stopPropagation) {
event.stopPropagation();
}
return serializeEvent(event.nativeEvent);
});
client.sendMessage({ type: "layout-event", data, target });
},
];
}