-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLive.js
More file actions
305 lines (232 loc) · 6.7 KB
/
Live.js
File metadata and controls
305 lines (232 loc) · 6.7 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import morphdom from 'morphdom';
// ViewElement - Base class for Live.js custom elements
export class ViewElement extends HTMLElement {
static observedAttributes = [];
static connectedElements = new Set();
connectedCallback() {
if (!this.id) {
this.id = crypto.randomUUID();
}
ViewElement.connectedElements.add(this);
const window = this.ownerDocument.defaultView;
if (window && window.live) {
window.live.bind(this);
}
}
disconnectedCallback() {
ViewElement.connectedElements.delete(this);
const window = this.ownerDocument.defaultView;
if (window && window.live) {
window.live.unbind(this);
}
}
}
export class Live {
#window;
#document;
#server;
#events;
#failures;
#reconnectTimer;
static start(options = {}) {
let window = options.window || globalThis;
if (window.live) throw new Error("Live.js is already started!");
let path = options.path || 'live'
let base = options.base || window.location.href;
let url = new URL(path, base);
url.protocol = url.protocol.replace('http', 'ws');
window.live = new this(window, url);
if (!window.customElements.get('live-view')) {
window.customElements.define('live-view', ViewElement);
}
return window.live;
}
constructor(window, url) {
this.#window = window;
this.#document = window.document;
this.url = url;
this.#server = null;
this.#events = [];
this.#failures = 0;
this.#reconnectTimer = null;
// Track visibility state and connect if required:
this.#document.addEventListener("visibilitychange", () => this.#handleVisibilityChange());
this.#handleVisibilityChange();
}
// -- Connection Handling --
connect() {
if (this.#server) {
return this.#server;
}
let server = this.#server = new this.#window.WebSocket(this.url);
if (this.#reconnectTimer) {
clearTimeout(this.#reconnectTimer);
this.#reconnectTimer = null;
}
server.onopen = () => {
this.#failures = 0;
// Attach elements before flushing any pending events:
this.#attach();
this.#flush();
};
server.onmessage = (message) => {
const [name, ...args] = JSON.parse(message.data);
this[name](...args);
};
// The remote end has disconnected:
server.addEventListener('error', () => {
this.#failures += 1;
});
server.addEventListener('close', () => {
// Explicit disconnect will clear `this.#server`:
if (this.#server && !this.#reconnectTimer) {
// We need a minimum delay otherwise this can end up immediately invoking the callback:
const delay = Math.min(100 * (this.#failures ** 2), 60000);
this.#reconnectTimer = setTimeout(() => {
this.#reconnectTimer = null;
this.connect();
}, delay);
}
if (this.#server === server) {
this.#server = null;
}
});
return server;
}
disconnect() {
if (this.#server) {
const server = this.#server;
this.#server = null;
server.close();
}
if (this.#reconnectTimer) {
clearTimeout(this.#reconnectTimer);
this.#reconnectTimer = null;
}
}
#send(message) {
if (this.#server) {
try {
return this.#server.send(message);
} catch (error) {
// console.log("Live.send", "failed to send message to server", error);
}
}
this.#events.push(message);
}
#flush() {
if (this.#events.length === 0) return;
let events = this.#events;
this.#events = [];
for (var event of events) {
this.#send(event);
}
}
#handleVisibilityChange() {
if (this.#document.hidden) {
this.disconnect();
} else {
this.connect();
}
}
connected() {
return this.#server && this.#server.readyState === this.#window.WebSocket.OPEN;
}
bind(element) {
if (this.connected()) {
try {
return this.#server.send(JSON.stringify(['bind', element.id, element.dataset]));
} catch (error) {
// The server must be in a bad state, we will rebind in attach on connect, later.
}
}
}
unbind(element) {
if (this.connected()) {
try {
return this.#server.send(JSON.stringify(['unbind', element.id]));
} catch (error) {
// The server must be in a bad state, unbind is irrelelvant.
}
}
}
#attach() {
for (let element of ViewElement.connectedElements) {
this.bind(element);
}
}
#createDocumentFragment(html) {
return this.#document.createRange().createContextualFragment(html);
}
#reply(options, ...args) {
if (options?.reply) {
this.#send(JSON.stringify(['reply', options.reply, ...args]));
}
}
// -- RPC Methods --
script(id, code, options) {
let element = this.#document.getElementById(id);
try {
let result = this.#window.Function(code).call(element);
this.#reply(options, result);
} catch (error) {
this.#reply(options, null, {name: error.name, message: error.message, stack: error.stack});
}
}
update(id, html, options) {
let element = this.#document.getElementById(id);
let fragment = this.#createDocumentFragment(html);
morphdom(element, fragment);
this.#reply(options);
}
replace(selector, html, options) {
let elements = this.#document.querySelectorAll(selector);
let fragment = this.#createDocumentFragment(html);
elements.forEach(element => morphdom(element, fragment.cloneNode(true)));
this.#reply(options);
}
prepend(selector, html, options) {
let elements = this.#document.querySelectorAll(selector);
let fragment = this.#createDocumentFragment(html);
elements.forEach(element => element.prepend(fragment.cloneNode(true)));
this.#reply(options);
}
append(selector, html, options) {
let elements = this.#document.querySelectorAll(selector);
let fragment = this.#createDocumentFragment(html);
elements.forEach(element => element.append(fragment.cloneNode(true)));
this.#reply(options);
}
remove(selector, options) {
let elements = this.#document.querySelectorAll(selector);
elements.forEach(element => element.remove());
this.#reply(options);
}
dispatchEvent(selector, type, options) {
let elements = this.#document.querySelectorAll(selector);
elements.forEach(element => element.dispatchEvent(
new this.#window.CustomEvent(type, options)
));
this.#reply(options);
}
error(message) {
console.error("Live.error", ...arguments);
}
// -- Event Handling --
forward(id, event) {
this.connect();
this.#send(
JSON.stringify(['event', id, event])
);
}
forwardEvent(id, event, detail, preventDefault = false) {
if (preventDefault) event.preventDefault();
this.forward(id, {type: event.type, detail: detail});
}
forwardFormEvent(id, event, detail, preventDefault = true) {
if (preventDefault) event.preventDefault();
let form = event.form;
let formData = new FormData(form);
this.forward(id, {type: event.type, detail: detail, formData: [...formData]});
}
}