@reactpy/client 0.1.0 → 0.2.0

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.
@@ -0,0 +1,261 @@
1
+ import React, { ComponentType } from "react";
2
+ import { ReactPyClient } from "./reactpy-client";
3
+ import serializeEvent from "event-to-object";
4
+
5
+ export async function loadImportSource(
6
+ vdomImportSource: ReactPyVdomImportSource,
7
+ client: ReactPyClient,
8
+ ): Promise<BindImportSource> {
9
+ let module: ReactPyModule;
10
+ if (vdomImportSource.sourceType === "URL") {
11
+ module = await import(vdomImportSource.source);
12
+ } else {
13
+ module = await client.loadModule(vdomImportSource.source);
14
+ }
15
+ if (typeof module.bind !== "function") {
16
+ throw new Error(
17
+ `${vdomImportSource.source} did not export a function 'bind'`,
18
+ );
19
+ }
20
+
21
+ return (node: HTMLElement) => {
22
+ const binding = module.bind(node, {
23
+ sendMessage: client.sendMessage,
24
+ onMessage: client.onMessage,
25
+ });
26
+ if (
27
+ !(
28
+ typeof binding.create === "function" &&
29
+ typeof binding.render === "function" &&
30
+ typeof binding.unmount === "function"
31
+ )
32
+ ) {
33
+ console.error(`${vdomImportSource.source} returned an impropper binding`);
34
+ return null;
35
+ }
36
+
37
+ return {
38
+ render: (model) =>
39
+ binding.render(
40
+ createImportSourceElement({
41
+ client,
42
+ module,
43
+ binding,
44
+ model,
45
+ currentImportSource: vdomImportSource,
46
+ }),
47
+ ),
48
+ unmount: binding.unmount,
49
+ };
50
+ };
51
+ }
52
+
53
+ function createImportSourceElement(props: {
54
+ client: ReactPyClient;
55
+ module: ReactPyModule;
56
+ binding: ReactPyModuleBinding;
57
+ model: ReactPyVdom;
58
+ currentImportSource: ReactPyVdomImportSource;
59
+ }): any {
60
+ let type: any;
61
+ if (props.model.importSource) {
62
+ if (
63
+ !isImportSourceEqual(props.currentImportSource, props.model.importSource)
64
+ ) {
65
+ console.error(
66
+ "Parent element import source " +
67
+ stringifyImportSource(props.currentImportSource) +
68
+ " does not match child's import source " +
69
+ stringifyImportSource(props.model.importSource),
70
+ );
71
+ return null;
72
+ } else if (!props.module[props.model.tagName]) {
73
+ console.error(
74
+ "Module from source " +
75
+ stringifyImportSource(props.currentImportSource) +
76
+ ` does not export ${props.model.tagName}`,
77
+ );
78
+ return null;
79
+ } else {
80
+ type = props.module[props.model.tagName];
81
+ }
82
+ } else {
83
+ type = props.model.tagName;
84
+ }
85
+ return props.binding.create(
86
+ type,
87
+ createAttributes(props.model, props.client),
88
+ createChildren(props.model, (child) =>
89
+ createImportSourceElement({
90
+ ...props,
91
+ model: child,
92
+ }),
93
+ ),
94
+ );
95
+ }
96
+
97
+ function isImportSourceEqual(
98
+ source1: ReactPyVdomImportSource,
99
+ source2: ReactPyVdomImportSource,
100
+ ) {
101
+ return (
102
+ source1.source === source2.source &&
103
+ source1.sourceType === source2.sourceType
104
+ );
105
+ }
106
+
107
+ function stringifyImportSource(importSource: ReactPyVdomImportSource) {
108
+ return JSON.stringify({
109
+ source: importSource.source,
110
+ sourceType: importSource.sourceType,
111
+ });
112
+ }
113
+
114
+ export function createChildren<Child>(
115
+ model: ReactPyVdom,
116
+ createChild: (child: ReactPyVdom) => Child,
117
+ ): (Child | string)[] {
118
+ if (!model.children) {
119
+ return [];
120
+ } else {
121
+ return model.children.map((child) => {
122
+ switch (typeof child) {
123
+ case "object":
124
+ return createChild(child);
125
+ case "string":
126
+ return child;
127
+ }
128
+ });
129
+ }
130
+ }
131
+
132
+ export function createAttributes(
133
+ model: ReactPyVdom,
134
+ client: ReactPyClient,
135
+ ): { [key: string]: any } {
136
+ return Object.fromEntries(
137
+ Object.entries({
138
+ // Normal HTML attributes
139
+ ...model.attributes,
140
+ // Construct event handlers
141
+ ...Object.fromEntries(
142
+ Object.entries(model.eventHandlers || {}).map(([name, handler]) =>
143
+ createEventHandler(client, name, handler),
144
+ ),
145
+ ),
146
+ // Convert snake_case to camelCase names
147
+ }).map(normalizeAttribute),
148
+ );
149
+ }
150
+
151
+ function createEventHandler(
152
+ client: ReactPyClient,
153
+ name: string,
154
+ { target, preventDefault, stopPropagation }: ReactPyVdomEventHandler,
155
+ ): [string, () => void] {
156
+ return [
157
+ name,
158
+ function () {
159
+ const data = Array.from(arguments).map((value) => {
160
+ if (!(typeof value === "object" && value.nativeEvent)) {
161
+ return value;
162
+ }
163
+ const event = value as React.SyntheticEvent<any>;
164
+ if (preventDefault) {
165
+ event.preventDefault();
166
+ }
167
+ if (stopPropagation) {
168
+ event.stopPropagation();
169
+ }
170
+ return serializeEvent(event.nativeEvent);
171
+ });
172
+ client.sendMessage({ type: "layout-event", data, target });
173
+ },
174
+ ];
175
+ }
176
+
177
+ function normalizeAttribute([key, value]: [string, any]): [string, any] {
178
+ let normKey = key;
179
+ let normValue = value;
180
+
181
+ if (key === "style" && typeof value === "object") {
182
+ normValue = Object.fromEntries(
183
+ Object.entries(value).map(([k, v]) => [snakeToCamel(k), v]),
184
+ );
185
+ } else if (
186
+ key.startsWith("data_") ||
187
+ key.startsWith("aria_") ||
188
+ DASHED_HTML_ATTRS.includes(key)
189
+ ) {
190
+ normKey = key.split("_").join("-");
191
+ } else {
192
+ normKey = snakeToCamel(key);
193
+ }
194
+ return [normKey, normValue];
195
+ }
196
+
197
+ function snakeToCamel(str: string): string {
198
+ return str.replace(/([_][a-z])/g, (group) =>
199
+ group.toUpperCase().replace("_", ""),
200
+ );
201
+ }
202
+
203
+ // see list of HTML attributes with dashes in them:
204
+ // https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#attribute_list
205
+ const DASHED_HTML_ATTRS = ["accept_charset", "http_equiv"];
206
+
207
+ export type ReactPyComponent = ComponentType<{ model: ReactPyVdom }>;
208
+
209
+ export type ReactPyVdom = {
210
+ tagName: string;
211
+ key?: string;
212
+ attributes?: { [key: string]: string };
213
+ children?: (ReactPyVdom | string)[];
214
+ error?: string;
215
+ eventHandlers?: { [key: string]: ReactPyVdomEventHandler };
216
+ importSource?: ReactPyVdomImportSource;
217
+ };
218
+
219
+ export type ReactPyVdomEventHandler = {
220
+ target: string;
221
+ preventDefault?: boolean;
222
+ stopPropagation?: boolean;
223
+ };
224
+
225
+ export type ReactPyVdomImportSource = {
226
+ source: string;
227
+ sourceType?: "URL" | "NAME";
228
+ fallback?: string | ReactPyVdom;
229
+ unmountBeforeUpdate?: boolean;
230
+ };
231
+
232
+ export type ReactPyModule = {
233
+ bind: (
234
+ node: HTMLElement,
235
+ context: ReactPyModuleBindingContext,
236
+ ) => ReactPyModuleBinding;
237
+ } & { [key: string]: any };
238
+
239
+ export type ReactPyModuleBindingContext = {
240
+ sendMessage: ReactPyClient["sendMessage"];
241
+ onMessage: ReactPyClient["onMessage"];
242
+ };
243
+
244
+ export type ReactPyModuleBinding = {
245
+ create: (
246
+ type: any,
247
+ props?: any,
248
+ children?: (any | string | ReactPyVdom)[],
249
+ ) => any;
250
+ render: (element: any) => void;
251
+ unmount: () => void;
252
+ };
253
+
254
+ export type BindImportSource = (
255
+ node: HTMLElement,
256
+ ) => ImportSourceBinding | null;
257
+
258
+ export type ImportSourceBinding = {
259
+ render: (model: ReactPyVdom) => void;
260
+ unmount: () => void;
261
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "../../../tsconfig.package.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src",
6
+ "composite": true
7
+ },
8
+ "include": ["src"],
9
+ "references": [
10
+ {
11
+ "path": "../../event-to-object"
12
+ }
13
+ ]
14
+ }
package/src/components.js DELETED
@@ -1,220 +0,0 @@
1
- import React from "react";
2
- import ReactDOM from "react-dom";
3
- import htm from "htm";
4
- import { set as setJsonPointer } from "json-pointer";
5
-
6
- import { useImportSource } from "./import-source.js";
7
- import { LayoutContext } from "./contexts.js";
8
-
9
- import {
10
- createElementAttributes,
11
- createElementChildren,
12
- } from "./element-utils.js";
13
-
14
- const html = htm.bind(React.createElement);
15
-
16
- export function Layout({ saveUpdateHook, sendEvent, loadImportSource }) {
17
- const currentModel = React.useState({})[0];
18
- const forceUpdate = useForceUpdate();
19
-
20
- const patchModel = React.useCallback(
21
- ({ path, model }) => {
22
- if (!path) {
23
- Object.assign(currentModel, model);
24
- } else {
25
- setJsonPointer(currentModel, path, model);
26
- }
27
- forceUpdate();
28
- },
29
- [currentModel]
30
- );
31
-
32
- React.useEffect(() => saveUpdateHook(patchModel), [patchModel]);
33
-
34
- if (!Object.keys(currentModel).length) {
35
- return html`<${React.Fragment} />`;
36
- }
37
-
38
- return html`
39
- <${LayoutContext.Provider} value=${{ sendEvent, loadImportSource }}>
40
- <${Element} model=${currentModel} />
41
- <//>
42
- `;
43
- }
44
-
45
- export function Element({ model }) {
46
- if (model.error !== undefined) {
47
- if (model.error) {
48
- return html`<pre>${model.error}</pre>`;
49
- } else {
50
- return null;
51
- }
52
- } else if (model.tagName == "script") {
53
- return html`<${ScriptElement} model=${model} />`;
54
- } else if (["input", "select", "textarea"].includes(model.tagName)) {
55
- return html`<${UserInputElement} model=${model} />`;
56
- } else if (model.importSource) {
57
- return html`<${ImportedElement} model=${model} />`;
58
- } else {
59
- return html`<${StandardElement} model=${model} />`;
60
- }
61
- }
62
-
63
- function StandardElement({ model }) {
64
- const layoutContext = React.useContext(LayoutContext);
65
-
66
- let type;
67
- if (model.tagName == "") {
68
- type = React.Fragment;
69
- } else {
70
- type = model.tagName;
71
- }
72
-
73
- // Use createElement here to avoid warning about variable numbers of children not
74
- // having keys. Warning about this must now be the responsibility of the server
75
- // providing the models instead of the client rendering them.
76
- return React.createElement(
77
- type,
78
- createElementAttributes(model, layoutContext.sendEvent),
79
- ...createElementChildren(
80
- model,
81
- (model) => html`<${Element} key=${model.key} model=${model} />`
82
- )
83
- );
84
- }
85
-
86
- // Element with a value attribute controlled by user input
87
- function UserInputElement({ model }) {
88
- const ref = React.useRef();
89
- const layoutContext = React.useContext(LayoutContext);
90
-
91
- const props = createElementAttributes(model, layoutContext.sendEvent);
92
-
93
- // Because we handle events asynchronously, we must leave the value uncontrolled in
94
- // order to allow all changes committed by the user to be recorded in the order they
95
- // occur. If we don't the user may commit multiple changes before we render next
96
- // causing the content of prior changes to be overwritten by subsequent changes.
97
- let value = props.value;
98
- delete props.value;
99
-
100
- // Instead of controlling the value, we set it in an effect.
101
- React.useEffect(() => {
102
- if (value !== undefined) {
103
- ref.current.value = value;
104
- }
105
- }, [ref.current, value]);
106
-
107
- // Track a buffer of observed values in order to avoid flicker
108
- const observedValues = React.useState([])[0];
109
- if (observedValues) {
110
- if (value === observedValues[0]) {
111
- observedValues.shift();
112
- value = observedValues[observedValues.length - 1];
113
- } else {
114
- observedValues.length = 0;
115
- }
116
- }
117
-
118
- const givenOnChange = props.onChange;
119
- if (typeof givenOnChange === "function") {
120
- props.onChange = (event) => {
121
- observedValues.push(event.target.value);
122
- givenOnChange(event);
123
- };
124
- }
125
-
126
- // Use createElement here to avoid warning about variable numbers of children not
127
- // having keys. Warning about this must now be the responsibility of the server
128
- // providing the models instead of the client rendering them.
129
- return React.createElement(
130
- model.tagName,
131
- {
132
- ...props,
133
- ref: (target) => {
134
- ref.current = target;
135
- },
136
- },
137
- ...createElementChildren(
138
- model,
139
- (model) => html`<${Element} key=${model.key} model=${model} />`
140
- )
141
- );
142
- }
143
-
144
- function ScriptElement({ model }) {
145
- const ref = React.useRef();
146
- React.useEffect(() => {
147
- if (model?.children?.length > 1) {
148
- console.error("Too many children for 'script' element.");
149
- }
150
-
151
- let scriptContent = model?.children?.[0];
152
-
153
- let scriptElement;
154
- if (model.attributes) {
155
- scriptElement = document.createElement("script");
156
- for (const [k, v] of Object.entries(model.attributes)) {
157
- scriptElement.setAttribute(k, v);
158
- }
159
- scriptElement.appendChild(document.createTextNode(scriptContent));
160
- ref.current.appendChild(scriptElement);
161
- } else {
162
- let scriptResult = eval(scriptContent);
163
- if (typeof scriptResult == "function") {
164
- return scriptResult();
165
- }
166
- }
167
- }, [model.key]);
168
- return html`<div ref=${ref} />`;
169
- }
170
-
171
- function ImportedElement({ model }) {
172
- const layoutContext = React.useContext(LayoutContext);
173
-
174
- const importSourceFallback = model.importSource.fallback;
175
- const importSource = useImportSource(model.importSource);
176
-
177
- if (!importSource) {
178
- // display a fallback if one was given
179
- if (!importSourceFallback) {
180
- return html`<div />`;
181
- } else if (typeof importSourceFallback === "string") {
182
- return html`<div>${importSourceFallback}</div>`;
183
- } else {
184
- return html`<${StandardElement} model=${importSourceFallback} />`;
185
- }
186
- } else {
187
- return html`<${_ImportedElement}
188
- model=${model}
189
- importSource=${importSource}
190
- />`;
191
- }
192
- }
193
-
194
- function _ImportedElement({ model, importSource }) {
195
- const layoutContext = React.useContext(LayoutContext);
196
- const mountPoint = React.useRef(null);
197
- const sourceBinding = React.useRef(null);
198
-
199
- React.useEffect(() => {
200
- sourceBinding.current = importSource.bind(mountPoint.current);
201
- if (!importSource.data.unmountBeforeUpdate) {
202
- return sourceBinding.current.unmount;
203
- }
204
- }, []);
205
-
206
- // this effect must run every time in case the model has changed
207
- React.useEffect(() => {
208
- sourceBinding.current.render(model);
209
- if (importSource.data.unmountBeforeUpdate) {
210
- return sourceBinding.current.unmount;
211
- }
212
- });
213
-
214
- return html`<div ref=${mountPoint} />`;
215
- }
216
-
217
- function useForceUpdate() {
218
- const [, updateState] = React.useState();
219
- return React.useCallback(() => updateState({}), []);
220
- }
package/src/contexts.js DELETED
@@ -1,6 +0,0 @@
1
- import React from "react";
2
-
3
- export const LayoutContext = React.createContext({
4
- sendEvent: undefined,
5
- loadImportSource: undefined,
6
- });
@@ -1,82 +0,0 @@
1
- import { serializeEvent } from "./event-to-object.js";
2
-
3
- export function createElementChildren(model, createElement) {
4
- if (!model.children) {
5
- return [];
6
- } else {
7
- return model.children
8
- .filter((x) => x) // filter nulls
9
- .map((child) => {
10
- switch (typeof child) {
11
- case "object":
12
- return createElement(child);
13
- case "string":
14
- return child;
15
- }
16
- });
17
- }
18
- }
19
-
20
- export function createElementAttributes(model, sendEvent) {
21
- const attributes = Object.assign({}, model.attributes);
22
-
23
- if (model.eventHandlers) {
24
- for (const [eventName, eventSpec] of Object.entries(model.eventHandlers)) {
25
- attributes[eventName] = createEventHandler(sendEvent, eventSpec);
26
- }
27
- }
28
-
29
- return Object.fromEntries(Object.entries(attributes).map(normalizeAttribute));
30
- }
31
-
32
- function createEventHandler(sendEvent, eventSpec) {
33
- return function () {
34
- const data = Array.from(arguments).map((value) => {
35
- if (typeof value === "object" && value.nativeEvent) {
36
- if (eventSpec["preventDefault"]) {
37
- value.preventDefault();
38
- }
39
- if (eventSpec["stopPropagation"]) {
40
- value.stopPropagation();
41
- }
42
- return serializeEvent(value);
43
- } else {
44
- return value;
45
- }
46
- });
47
- sendEvent({
48
- data: data,
49
- target: eventSpec["target"],
50
- });
51
- };
52
- }
53
-
54
- function normalizeAttribute([key, value]) {
55
- let normKey = key;
56
- let normValue = value;
57
-
58
- if (key === "style" && typeof value === "object") {
59
- normValue = Object.fromEntries(
60
- Object.entries(value).map(([k, v]) => [snakeToCamel(k), v])
61
- );
62
- } else if (
63
- key.startsWith("data_") ||
64
- key.startsWith("aria_") ||
65
- DASHED_HTML_ATTRS.includes(key)
66
- ) {
67
- normKey = key.replaceAll("_", "-");
68
- } else {
69
- normKey = snakeToCamel(key);
70
- }
71
- return [normKey, normValue];
72
- }
73
-
74
- function snakeToCamel(str) {
75
- return str.replace(/([_][a-z])/g, (group) =>
76
- group.toUpperCase().replace("_", "")
77
- );
78
- }
79
-
80
- // see list of HTML attributes with dashes in them:
81
- // https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#attribute_list
82
- const DASHED_HTML_ATTRS = ["accept_charset", "http_equiv"];