forked from reactive-python/reactpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponents.tsx
More file actions
228 lines (197 loc) · 6.77 KB
/
components.tsx
File metadata and controls
228 lines (197 loc) · 6.77 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
import { set as setJsonPointer } from "json-pointer";
import type { ChangeEvent, MutableRefObject } from "preact/compat";
import { createContext, createElement, Fragment, type JSX } from "preact";
import { useContext, useEffect, useRef, useState } from "preact/hooks";
import type {
ImportSourceBinding,
ReactPyComponent,
ReactPyVdom,
} from "./types";
import { createAttributes, createChildren, loadImportSource } from "./vdom";
import type { ReactPyClient } from "./client";
const ClientContext = createContext<ReactPyClient>(null as any);
export function Layout(props: { client: ReactPyClient }): JSX.Element {
const currentModel: ReactPyVdom = useState({ tagName: "" })[0];
const forceUpdate = useForceUpdate();
useEffect(
() =>
props.client.onMessage("layout-update", ({ path, model }) => {
if (path === "") {
Object.assign(currentModel, model);
} else {
setJsonPointer(currentModel, path, model);
}
forceUpdate();
}),
[currentModel, props.client],
);
return (
<ClientContext.Provider value={props.client}>
<Element model={currentModel} />
</ClientContext.Provider>
);
}
export function Element({ model }: { model: ReactPyVdom }): JSX.Element | null {
if (model.error !== undefined) {
if (model.error) {
return <pre>{model.error}</pre>;
} else {
return null;
}
}
let SpecializedElement: ReactPyComponent;
if (model.tagName in SPECIAL_ELEMENTS) {
SpecializedElement =
SPECIAL_ELEMENTS[model.tagName as keyof typeof SPECIAL_ELEMENTS];
} else if (model.importSource) {
SpecializedElement = ImportedElement;
} else {
SpecializedElement = StandardElement;
}
return <SpecializedElement model={model} />;
}
function StandardElement({ model }: { model: ReactPyVdom }) {
const client = useContext(ClientContext);
// Use createElement here to avoid warning about variable numbers of children not
// having keys. Warning about this must now be the responsibility of the client
// providing the models instead of the client rendering them.
return createElement(
model.tagName === "" ? Fragment : model.tagName,
createAttributes(model, client),
...createChildren(model, (child) => {
return <Element model={child} key={child.attributes?.key} />;
}),
);
}
function UserInputElement({ model }: { model: ReactPyVdom }): JSX.Element {
const client = useContext(ClientContext);
const props = createAttributes(model, client);
const [value, setValue] = useState(props.value);
// honor changes to value from the client via props
useEffect(() => setValue(props.value), [props.value]);
const givenOnChange = props.onChange;
if (typeof givenOnChange === "function") {
props.onChange = (event: ChangeEvent<any>) => {
// immediately update the value to give the user feedback
if (event.target) {
setValue((event.target as HTMLInputElement).value);
}
// allow the client to respond (and possibly change the value)
givenOnChange(event);
};
}
// Use createElement here to avoid warning about variable numbers of children not
// having keys. Warning about this must now be the responsibility of the client
// providing the models instead of the client rendering them.
return createElement(
model.tagName,
// overwrite
{ ...props, value },
...createChildren(model, (child) => (
<Element model={child} key={child.attributes?.key} />
)),
);
}
function ScriptElement({ model }: { model: ReactPyVdom }) {
const ref = useRef<HTMLDivElement | null>(null);
useEffect(() => {
// Don't run if the parent element is missing
if (!ref.current) {
return;
}
// Create the script element
const scriptElement: HTMLScriptElement = document.createElement("script");
for (const [k, v] of Object.entries(model.attributes || {})) {
scriptElement.setAttribute(k, v);
}
// Add the script content as text
const scriptContent = model?.children?.filter(
(value): value is string => typeof value == "string",
)[0];
if (scriptContent) {
scriptElement.appendChild(document.createTextNode(scriptContent));
}
// Append the script element to the parent element
ref.current.appendChild(scriptElement);
// Remove the script element when the component is unmounted
return () => {
ref.current?.removeChild(scriptElement);
};
}, [model.attributes?.key]);
return <div ref={ref} />;
}
function ImportedElement({ model }: { model: ReactPyVdom }) {
const importSourceVdom = model.importSource;
const importSourceRef = useImportSource(model);
if (!importSourceVdom) {
return null;
}
const importSourceFallback = importSourceVdom.fallback;
if (!importSourceVdom) {
// display a fallback if one was given
if (!importSourceFallback) {
return null;
} else if (typeof importSourceFallback === "string") {
return <span>{importSourceFallback}</span>;
} else {
return <StandardElement model={importSourceFallback} />;
}
} else {
return <span ref={importSourceRef} />;
}
}
function useForceUpdate() {
const [, setState] = useState(false);
return () => setState((old) => !old);
}
function useImportSource(model: ReactPyVdom): MutableRefObject<any> {
const vdomImportSource = model.importSource;
const vdomImportSourceJsonString = JSON.stringify(vdomImportSource);
const mountPoint = useRef<HTMLElement>(null);
const client = useContext(ClientContext);
const [binding, setBinding] = useState<ImportSourceBinding | null>(null);
const bindingSource = useRef<string | null>(null);
useEffect(() => {
let unmounted = false;
let currentBinding: ImportSourceBinding | null = null;
if (vdomImportSource) {
loadImportSource(vdomImportSource, client).then((bind) => {
if (!unmounted && mountPoint.current) {
currentBinding = bind(mountPoint.current);
bindingSource.current = vdomImportSourceJsonString;
setBinding(currentBinding);
}
});
}
return () => {
unmounted = true;
if (
currentBinding &&
vdomImportSource &&
!vdomImportSource.unmountBeforeUpdate
) {
currentBinding.unmount();
}
};
}, [client, vdomImportSourceJsonString, setBinding, mountPoint.current]);
// this effect must run every time in case the model has changed
useEffect(() => {
if (!(binding && vdomImportSource)) {
return;
}
if (bindingSource.current !== vdomImportSourceJsonString) {
return;
}
binding.render(model);
if (vdomImportSource.unmountBeforeUpdate) {
return binding.unmount;
}
});
return mountPoint;
}
const SPECIAL_ELEMENTS = {
input: UserInputElement,
script: ScriptElement,
select: UserInputElement,
textarea: UserInputElement,
};