@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.
package/package.json CHANGED
@@ -1,35 +1,37 @@
1
1
  {
2
2
  "author": "Ryan Morshead",
3
+ "main": "dist/index.js",
4
+ "types": "dist/index.d.ts",
5
+ "description": "A client for ReactPy implemented in React",
6
+ "license": "MIT",
7
+ "name": "@reactpy/client",
8
+ "type": "module",
9
+ "version": "0.2.0",
3
10
  "dependencies": {
4
- "htm": "^3.0.3",
11
+ "event-to-object": "^0.1.0",
5
12
  "json-pointer": "^0.6.2"
6
13
  },
7
- "description": "A client for ReactPy implemented in React",
8
14
  "devDependencies": {
9
- "jsdom": "16.5.0",
10
- "lodash": "^4.17.21",
11
- "prettier": "^2.5.1",
12
- "uvu": "^0.5.1"
15
+ "@types/json-pointer": "^1.0.31",
16
+ "@types/react": "^17.0",
17
+ "@types/react-dom": "^17.0",
18
+ "prettier": "^3.0.0-alpha.6",
19
+ "typescript": "^4.9.5"
13
20
  },
14
- "files": [
15
- "src/**/*.js"
16
- ],
17
- "license": "MIT",
18
- "main": "src/index.js",
19
- "name": "@reactpy/client",
20
21
  "peerDependencies": {
21
- "react": ">=16",
22
- "react-dom": ">=16"
22
+ "react": ">=16 <18",
23
+ "react-dom": ">=16 <18"
23
24
  },
24
25
  "repository": {
25
26
  "type": "git",
26
27
  "url": "https://github.com/reactive-python/reactpy"
27
28
  },
28
29
  "scripts": {
29
- "check-format": "prettier --check ./src ./tests",
30
- "format": "prettier --write ./src ./tests",
31
- "test": "uvu tests"
32
- },
33
- "type": "module",
34
- "version": "0.1.0"
30
+ "build": "tsc -b",
31
+ "format": "prettier --write .",
32
+ "test": "npm run check:tests",
33
+ "check:format": "prettier --check .",
34
+ "check:tests": "echo 'no tests'",
35
+ "check:types": "tsc --noEmit"
36
+ }
35
37
  }
@@ -0,0 +1,231 @@
1
+ import React, {
2
+ createElement,
3
+ createContext,
4
+ useState,
5
+ useRef,
6
+ useContext,
7
+ useEffect,
8
+ Fragment,
9
+ MutableRefObject,
10
+ ChangeEvent,
11
+ } from "react";
12
+ // @ts-ignore
13
+ import { set as setJsonPointer } from "json-pointer";
14
+ import { LayoutUpdateMessage } from "./messages";
15
+ import {
16
+ ReactPyVdom,
17
+ ReactPyComponent,
18
+ createChildren,
19
+ createAttributes,
20
+ loadImportSource,
21
+ ImportSourceBinding,
22
+ } from "./reactpy-vdom";
23
+ import { ReactPyClient } from "./reactpy-client";
24
+
25
+ const ClientContext = createContext<ReactPyClient>(null as any);
26
+
27
+ export function Layout(props: { client: ReactPyClient }): JSX.Element {
28
+ const currentModel: ReactPyVdom = useState({ tagName: "" })[0];
29
+ const forceUpdate = useForceUpdate();
30
+
31
+ useEffect(() => {
32
+ props.client.onMessage<LayoutUpdateMessage>(
33
+ "layout-update",
34
+ ({ path, model }) => {
35
+ if (path === "") {
36
+ Object.assign(currentModel, model);
37
+ } else {
38
+ setJsonPointer(currentModel, path, model);
39
+ }
40
+ forceUpdate();
41
+ },
42
+ );
43
+ props.client.start();
44
+ return () => props.client.stop();
45
+ }, [currentModel, props.client]);
46
+
47
+ return (
48
+ <ClientContext.Provider value={props.client}>
49
+ <Element model={currentModel} />
50
+ </ClientContext.Provider>
51
+ );
52
+ }
53
+
54
+ export function Element({ model }: { model: ReactPyVdom }): JSX.Element | null {
55
+ if (model.error !== undefined) {
56
+ if (model.error) {
57
+ return <pre>{model.error}</pre>;
58
+ } else {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ let SpecializedElement: ReactPyComponent;
64
+ if (model.tagName in SPECIAL_ELEMENTS) {
65
+ SpecializedElement =
66
+ SPECIAL_ELEMENTS[model.tagName as keyof typeof SPECIAL_ELEMENTS];
67
+ } else if (model.importSource) {
68
+ SpecializedElement = ImportedElement;
69
+ } else {
70
+ SpecializedElement = StandardElement;
71
+ }
72
+
73
+ return <SpecializedElement model={model} />;
74
+ }
75
+
76
+ function StandardElement({ model }: { model: ReactPyVdom }) {
77
+ const client = React.useContext(ClientContext);
78
+ // Use createElement here to avoid warning about variable numbers of children not
79
+ // having keys. Warning about this must now be the responsibility of the client
80
+ // providing the models instead of the client rendering them.
81
+ return createElement(
82
+ model.tagName === "" ? Fragment : model.tagName,
83
+ createAttributes(model, client),
84
+ ...createChildren(model, (child) => {
85
+ return <Element model={child} key={child.key} />;
86
+ }),
87
+ );
88
+ }
89
+
90
+ function UserInputElement({ model }: { model: ReactPyVdom }): JSX.Element {
91
+ const client = useContext(ClientContext);
92
+ const props = createAttributes(model, client);
93
+ const [value, setValue] = React.useState(props.value);
94
+
95
+ // honor changes to value from the client via props
96
+ React.useEffect(() => setValue(props.value), [props.value]);
97
+
98
+ const givenOnChange = props.onChange;
99
+ if (typeof givenOnChange === "function") {
100
+ props.onChange = (event: ChangeEvent<any>) => {
101
+ // immediately update the value to give the user feedback
102
+ setValue(event.target.value);
103
+ // allow the client to respond (and possibly change the value)
104
+ givenOnChange(event);
105
+ };
106
+ }
107
+
108
+ // Use createElement here to avoid warning about variable numbers of children not
109
+ // having keys. Warning about this must now be the responsibility of the client
110
+ // providing the models instead of the client rendering them.
111
+ return createElement(
112
+ model.tagName,
113
+ // overwrite
114
+ { ...props, value },
115
+ ...createChildren(model, (child) => (
116
+ <Element model={child} key={child.key} />
117
+ )),
118
+ );
119
+ }
120
+
121
+ function ScriptElement({ model }: { model: ReactPyVdom }) {
122
+ const ref = useRef<HTMLDivElement | null>(null);
123
+
124
+ React.useEffect(() => {
125
+ if (!ref.current) {
126
+ return;
127
+ }
128
+ const scriptContent = model?.children?.filter(
129
+ (value): value is string => typeof value == "string",
130
+ )[0];
131
+
132
+ let scriptElement: HTMLScriptElement;
133
+ if (model.attributes) {
134
+ scriptElement = document.createElement("script");
135
+ for (const [k, v] of Object.entries(model.attributes)) {
136
+ scriptElement.setAttribute(k, v);
137
+ }
138
+ if (scriptContent) {
139
+ scriptElement.appendChild(document.createTextNode(scriptContent));
140
+ }
141
+ ref.current.appendChild(scriptElement);
142
+ } else if (scriptContent) {
143
+ let scriptResult = eval(scriptContent);
144
+ if (typeof scriptResult == "function") {
145
+ return scriptResult();
146
+ }
147
+ }
148
+ }, [model.key, ref.current]);
149
+
150
+ return <div ref={ref} />;
151
+ }
152
+
153
+ function ImportedElement({ model }: { model: ReactPyVdom }) {
154
+ const importSourceVdom = model.importSource;
155
+ const importSourceRef = useImportSource(model);
156
+
157
+ if (!importSourceVdom) {
158
+ return null;
159
+ }
160
+
161
+ const importSourceFallback = importSourceVdom.fallback;
162
+
163
+ if (!importSourceVdom) {
164
+ // display a fallback if one was given
165
+ if (!importSourceFallback) {
166
+ return null;
167
+ } else if (typeof importSourceFallback === "string") {
168
+ return <div>{importSourceFallback}</div>;
169
+ } else {
170
+ return <StandardElement model={importSourceFallback} />;
171
+ }
172
+ } else {
173
+ return <div ref={importSourceRef} />;
174
+ }
175
+ }
176
+
177
+ function useForceUpdate() {
178
+ const [, setState] = useState(false);
179
+ return () => setState((old) => !old);
180
+ }
181
+
182
+ function useImportSource(model: ReactPyVdom): MutableRefObject<any> {
183
+ const vdomImportSource = model.importSource;
184
+
185
+ const mountPoint = useRef<HTMLElement>(null);
186
+ const client = React.useContext(ClientContext);
187
+ const [binding, setBinding] = useState<ImportSourceBinding | null>(null);
188
+
189
+ React.useEffect(() => {
190
+ let unmounted = false;
191
+
192
+ if (vdomImportSource) {
193
+ loadImportSource(vdomImportSource, client).then((bind) => {
194
+ if (!unmounted && mountPoint.current) {
195
+ setBinding(bind(mountPoint.current));
196
+ }
197
+ });
198
+ }
199
+
200
+ return () => {
201
+ unmounted = true;
202
+ if (
203
+ binding &&
204
+ vdomImportSource &&
205
+ !vdomImportSource.unmountBeforeUpdate
206
+ ) {
207
+ binding.unmount();
208
+ }
209
+ };
210
+ }, [client, vdomImportSource, setBinding, mountPoint.current]);
211
+
212
+ // this effect must run every time in case the model has changed
213
+ useEffect(() => {
214
+ if (!(binding && vdomImportSource)) {
215
+ return;
216
+ }
217
+ binding.render(model);
218
+ if (vdomImportSource.unmountBeforeUpdate) {
219
+ return binding.unmount;
220
+ }
221
+ });
222
+
223
+ return mountPoint;
224
+ }
225
+
226
+ const SPECIAL_ELEMENTS = {
227
+ input: UserInputElement,
228
+ script: ScriptElement,
229
+ select: UserInputElement,
230
+ textarea: UserInputElement,
231
+ };
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./components";
2
+ export * from "./messages";
3
+ export * from "./mount";
4
+ export * from "./reactpy-client";
5
+ export * from "./reactpy-vdom";
package/src/logger.ts ADDED
@@ -0,0 +1,5 @@
1
+ export default {
2
+ log: (...args: any[]): void => console.log("[ReactPy]", ...args),
3
+ warn: (...args: any[]): void => console.warn("[ReactPy]", ...args),
4
+ error: (...args: any[]): void => console.error("[ReactPy]", ...args),
5
+ };
@@ -0,0 +1,32 @@
1
+ import { ReactPyVdom } from "./reactpy-vdom";
2
+
3
+ export interface IMessage {
4
+ type: string;
5
+ }
6
+
7
+ export type ConnectionOpenMessage = {
8
+ type: "connection-open";
9
+ };
10
+
11
+ export type ConnectionCloseMessage = {
12
+ type: "connection-close";
13
+ };
14
+
15
+ export type LayoutUpdateMessage = {
16
+ type: "layout-update";
17
+ path: string;
18
+ model: ReactPyVdom;
19
+ };
20
+
21
+ export type LayoutEventMessage = {
22
+ type: "layout-event";
23
+ target: string;
24
+ data: any;
25
+ };
26
+
27
+ export type IncomingMessage =
28
+ | LayoutUpdateMessage
29
+ | ConnectionOpenMessage
30
+ | ConnectionCloseMessage;
31
+ export type OutgoingMessage = LayoutEventMessage;
32
+ export type Message = IncomingMessage | OutgoingMessage;
package/src/mount.tsx ADDED
@@ -0,0 +1,8 @@
1
+ import React from "react";
2
+ import { render } from "react-dom";
3
+ import { Layout } from "./components";
4
+ import { ReactPyClient } from "./reactpy-client";
5
+
6
+ export function mount(element: HTMLElement, client: ReactPyClient): void {
7
+ render(<Layout client={client} />, element);
8
+ }
@@ -0,0 +1,274 @@
1
+ import { OutgoingMessage, IncomingMessage } from "./messages";
2
+ import { ReactPyModule } from "./reactpy-vdom";
3
+ import logger from "./logger";
4
+
5
+ /**
6
+ * A client for communicating with a ReactPy server.
7
+ */
8
+ export interface ReactPyClient {
9
+ /**
10
+ * Connect to the server and start receiving messages.
11
+ *
12
+ * Message handlers should be registered before calling this method in order to
13
+ * garuntee that messages are not missed.
14
+ */
15
+ start: () => void;
16
+ /**
17
+ * Disconnect from the server and stop receiving messages.
18
+ */
19
+ stop: () => void;
20
+ /**
21
+ * Register a handler for a message type.
22
+ */
23
+ onMessage: <M extends IncomingMessage>(
24
+ type: M["type"],
25
+ handler: (message: M) => void,
26
+ ) => void;
27
+ /**
28
+ * Send a message to the server.
29
+ */
30
+ sendMessage: (message: OutgoingMessage) => void;
31
+ /**
32
+ * Dynamically load a module from the server.
33
+ */
34
+ loadModule: (moduleName: string) => Promise<ReactPyModule>;
35
+ }
36
+
37
+ export type SimpleReactPyClientProps = {
38
+ serverLocation?: LocationProps;
39
+ reconnectOptions?: ReconnectProps;
40
+ };
41
+
42
+ /**
43
+ * The location of the server.
44
+ *
45
+ * This is used to determine the location of the server's API endpoints. All endpoints
46
+ * are expected to be found at the base URL, with the following paths:
47
+ *
48
+ * - `_reactpy/stream/${route}${query}`: The websocket endpoint for the stream.
49
+ * - `_reactpy/modules`: The directory containing the dynamically loaded modules.
50
+ * - `_reactpy/assets`: The directory containing the static assets.
51
+ */
52
+ type LocationProps = {
53
+ /**
54
+ * The base URL of the server.
55
+ *
56
+ * @default - document.location.origin
57
+ */
58
+ url: string;
59
+ /**
60
+ * The route to the page being rendered.
61
+ *
62
+ * @default - document.location.pathname
63
+ */
64
+ route: string;
65
+ /**
66
+ * The query string of the page being rendered.
67
+ *
68
+ * @default - document.location.search
69
+ */
70
+ query: string;
71
+ };
72
+
73
+ type ReconnectProps = {
74
+ maxInterval?: number;
75
+ maxRetries?: number;
76
+ backoffRate?: number;
77
+ intervalJitter?: number;
78
+ };
79
+
80
+ export class SimpleReactPyClient implements ReactPyClient {
81
+ private resolveShouldOpen: (value: unknown) => void;
82
+ private resolveShouldClose: (value: unknown) => void;
83
+ private readonly urls: ServerUrls;
84
+ private readonly handlers: {
85
+ [key in IncomingMessage["type"]]: ((message: any) => void)[];
86
+ };
87
+ private readonly socket: { current?: WebSocket };
88
+
89
+ constructor(props: SimpleReactPyClientProps) {
90
+ this.handlers = {
91
+ "connection-open": [],
92
+ "connection-close": [],
93
+ "layout-update": [],
94
+ };
95
+
96
+ this.urls = getServerUrls(
97
+ props.serverLocation || {
98
+ url: document.location.origin,
99
+ route: document.location.pathname,
100
+ query: document.location.search,
101
+ },
102
+ );
103
+
104
+ this.resolveShouldOpen = () => {
105
+ throw new Error("Could not start client");
106
+ };
107
+ this.resolveShouldClose = () => {
108
+ throw new Error("Could not stop client");
109
+ };
110
+ const shouldOpen = new Promise((r) => (this.resolveShouldOpen = r));
111
+ const shouldClose = new Promise((r) => (this.resolveShouldClose = r));
112
+
113
+ this.socket = startReconnectingWebSocket({
114
+ shouldOpen,
115
+ shouldClose,
116
+ url: this.urls.stream,
117
+ onOpen: () => this.handleIncoming({ type: "connection-open" }),
118
+ onMessage: async ({ data }) => this.handleIncoming(JSON.parse(data)),
119
+ onClose: () => this.handleIncoming({ type: "connection-close" }),
120
+ ...props.reconnectOptions,
121
+ });
122
+ }
123
+
124
+ start(): void {
125
+ logger.log("starting client...");
126
+ this.resolveShouldOpen(undefined);
127
+ }
128
+
129
+ stop(): void {
130
+ logger.log("stopping client...");
131
+ this.resolveShouldClose(undefined);
132
+ }
133
+
134
+ onMessage<M extends IncomingMessage>(
135
+ type: M["type"],
136
+ handler: (message: M) => void,
137
+ ): void {
138
+ this.handlers[type].push(handler);
139
+ }
140
+
141
+ sendMessage(message: OutgoingMessage): void {
142
+ this.socket.current?.send(JSON.stringify(message));
143
+ }
144
+
145
+ loadModule(moduleName: string): Promise<ReactPyModule> {
146
+ return import(`${this.urls.modules}/${moduleName}`);
147
+ }
148
+
149
+ private handleIncoming(message: IncomingMessage): void {
150
+ if (!message.type) {
151
+ logger.warn("Received message without type", message);
152
+ return;
153
+ }
154
+
155
+ const messageHandlers: ((m: any) => void)[] | undefined =
156
+ this.handlers[message.type];
157
+ if (!messageHandlers) {
158
+ logger.warn("Received message without handler", message);
159
+ return;
160
+ }
161
+
162
+ messageHandlers.forEach((h) => h(message));
163
+ }
164
+ }
165
+
166
+ type ServerUrls = {
167
+ base: URL;
168
+ stream: string;
169
+ modules: string;
170
+ assets: string;
171
+ };
172
+
173
+ function getServerUrls(props: LocationProps): ServerUrls {
174
+ const base = new URL(`${props.url || document.location.origin}/_reactpy`);
175
+ const modules = `${base}/modules`;
176
+ const assets = `${base}/assets`;
177
+
178
+ const streamProtocol = `ws${base.protocol === "https:" ? "s" : ""}`;
179
+ const streamPath = rtrim(`${base.pathname}/stream${props.route || ""}`, "/");
180
+ const stream = `${streamProtocol}://${base.host}${streamPath}${props.query}`;
181
+
182
+ return { base, modules, assets, stream };
183
+ }
184
+
185
+ function startReconnectingWebSocket(
186
+ props: {
187
+ shouldOpen: Promise<any>;
188
+ shouldClose: Promise<any>;
189
+ url: string;
190
+ onOpen: () => void;
191
+ onMessage: (message: MessageEvent<any>) => void;
192
+ onClose: () => void;
193
+ } & ReconnectProps,
194
+ ) {
195
+ const {
196
+ maxInterval = 60000,
197
+ maxRetries = 50,
198
+ backoffRate = 1.1,
199
+ intervalJitter = 0.1,
200
+ } = props;
201
+
202
+ const startInterval = 750;
203
+ let retries = 0;
204
+ let interval = startInterval;
205
+ let closed = false;
206
+ let everConnected = false;
207
+ const socket: { current?: WebSocket } = {};
208
+
209
+ const connect = () => {
210
+ if (closed) {
211
+ return;
212
+ }
213
+ socket.current = new WebSocket(props.url);
214
+ socket.current.onopen = () => {
215
+ everConnected = true;
216
+ logger.log("client connected");
217
+ interval = startInterval;
218
+ retries = 0;
219
+ props.onOpen();
220
+ };
221
+ socket.current.onmessage = props.onMessage;
222
+ socket.current.onclose = () => {
223
+ if (!everConnected) {
224
+ logger.log("failed to connect");
225
+ return;
226
+ }
227
+
228
+ logger.log("client disconnected");
229
+ props.onClose();
230
+
231
+ if (retries >= maxRetries) {
232
+ return;
233
+ }
234
+
235
+ const thisInterval = addJitter(interval, intervalJitter);
236
+ logger.log(
237
+ `reconnecting in ${(thisInterval / 1000).toPrecision(4)} seconds...`,
238
+ );
239
+ setTimeout(connect, thisInterval);
240
+ interval = nextInterval(interval, backoffRate, maxInterval);
241
+ retries++;
242
+ };
243
+ };
244
+
245
+ props.shouldOpen.then(connect);
246
+ props.shouldClose.then(() => {
247
+ closed = true;
248
+ socket.current?.close();
249
+ });
250
+
251
+ return socket;
252
+ }
253
+
254
+ function nextInterval(
255
+ currentInterval: number,
256
+ backoffRate: number,
257
+ maxInterval: number,
258
+ ): number {
259
+ return Math.min(
260
+ currentInterval *
261
+ // increase interval by backoff rate
262
+ backoffRate,
263
+ // don't exceed max interval
264
+ maxInterval,
265
+ );
266
+ }
267
+
268
+ function addJitter(interval: number, jitter: number): number {
269
+ return interval + (Math.random() * jitter * interval * 2 - jitter * interval);
270
+ }
271
+
272
+ function rtrim(text: string, trim: string): string {
273
+ return text.replace(new RegExp(`${trim}+$`), "");
274
+ }