forked from reactive-python/reactpy-django
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.tsx
More file actions
82 lines (75 loc) · 2.57 KB
/
index.tsx
File metadata and controls
82 lines (75 loc) · 2.57 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
import { ReactPyDjangoClient } from "./client";
import React from "react";
import { createRoot } from "react-dom";
import { Layout } from "@reactpy/client/src/components";
export function mountComponent(
mountElement: HTMLElement,
host: string,
urlPrefix: string,
componentPath: string,
resolvedJsModulesPath: string,
reconnectStartInterval: number,
reconnectMaxInterval: number,
reconnectMaxRetries: number,
reconnectBackoffMultiplier: number,
) {
// Protocols
let httpProtocol = window.location.protocol;
let wsProtocol = `ws${httpProtocol === "https:" ? "s" : ""}:`;
// WebSocket route (for Python components)
let wsOrigin: string;
if (host) {
wsOrigin = `${wsProtocol}//${host}`;
} else {
wsOrigin = `${wsProtocol}//${window.location.host}`;
}
// HTTP route (for JavaScript modules)
let httpOrigin: string;
let jsModulesPath: string;
if (host) {
httpOrigin = `${httpProtocol}//${host}`;
jsModulesPath = `${urlPrefix}/web_module`;
} else {
httpOrigin = `${httpProtocol}//${window.location.host}`;
if (resolvedJsModulesPath) {
jsModulesPath = resolvedJsModulesPath;
} else {
jsModulesPath = `${urlPrefix}/web_module`;
}
}
// Embed the initial HTTP path into the WebSocket URL
let componentUrl = new URL(`${wsOrigin}/${urlPrefix}/${componentPath}`);
componentUrl.searchParams.append("http_pathname", window.location.pathname);
if (window.location.search) {
componentUrl.searchParams.append("http_search", window.location.search);
}
// Configure a new ReactPy client
const client = new ReactPyDjangoClient({
urls: {
componentUrl: componentUrl,
query: document.location.search,
jsModules: `${httpOrigin}/${jsModulesPath}`,
},
reconnectOptions: {
startInterval: reconnectStartInterval,
maxInterval: reconnectMaxInterval,
backoffMultiplier: reconnectBackoffMultiplier,
maxRetries: reconnectMaxRetries,
},
mountElement: mountElement,
prerenderElement: document.getElementById(mountElement.id + "-prerender"),
offlineElement: document.getElementById(mountElement.id + "-offline"),
});
// Replace the prerender element with the real element on the first layout update
if (client.prerenderElement) {
client.onMessage("layout-update", ({ path, model }) => {
if (client.prerenderElement) {
client.prerenderElement.replaceWith(client.mountElement);
client.prerenderElement = null;
}
});
}
// Start rendering the component
const root = createRoot(client.mountElement);
root.render(<Layout client={client} />);
}