Repository navigation
Expand file tree
/
Copy pathmidnight.js
More file actions
541 lines (499 loc) · 19.1 KB
/
Copy pathmidnight.js
File metadata and controls
541 lines (499 loc) · 19.1 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
(() => {
function getTabId() {
const key = "midnight:tab-id";
try {
let value = sessionStorage.getItem(key);
if (!value) {
value = globalThis.crypto?.randomUUID?.() || `tab-${Date.now()}-${Math.random().toString(36).slice(2)}`;
sessionStorage.setItem(key, value);
}
return value;
} catch {
return globalThis.crypto?.randomUUID?.() || `tab-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
}
const state = {
socket: null,
url: null,
tabId: getTabId(),
reconnect: true,
reconnectDelayMs: 500,
reconnectMaxDelayMs: 5000,
reconnectAttempt: 0,
reconnectTimer: null,
subscriptions: [],
listeners: new Map(),
compiled: new Map(),
pendingEvents: new Map(),
outbox: [],
nextEventId: 1,
serverEvents: 0,
localCompiledEvents: 0,
};
const compiledKey = (eventName, selector) => `${eventName}\u0000${selector ?? ""}`;
function runtimeEvent(name, detail = null) {
window.dispatchEvent(new CustomEvent(`midnight:${name}`, { detail }));
}
function targetInfo(element) {
if (!(element instanceof Element)) return {};
const info = {
tag: element.tagName.toLowerCase(),
id: element.id || null,
name: element.getAttribute("name"),
value: "value" in element ? element.value : null,
checked: "checked" in element ? Boolean(element.checked) : null,
};
if (element.dataset && Object.keys(element.dataset).length) info.dataset = { ...element.dataset };
return info;
}
function formDataFor(element) {
const form = element instanceof HTMLFormElement ? element : element?.closest?.("form");
if (!form) return null;
const out = {};
for (const [key, value] of new FormData(form)) {
const text = String(value);
if (key in out) out[key] = Array.isArray(out[key]) ? [...out[key], text] : [out[key], text];
else out[key] = text;
}
return out;
}
function serializeEvent(event, selector, matched) {
const payload = {
type: event.type,
selector,
target: targetInfo(matched || event.target),
time_stamp: Number(event.timeStamp || 0),
};
if (event instanceof KeyboardEvent) {
payload.key = event.key;
payload.code = event.code;
payload.repeat = event.repeat;
payload.alt = event.altKey;
payload.ctrl = event.ctrlKey;
payload.meta = event.metaKey;
payload.shift = event.shiftKey;
}
if (event instanceof MouseEvent) {
payload.button = event.button;
payload.buttons = event.buttons;
payload.x = event.clientX;
payload.y = event.clientY;
}
if (event.type === "submit" || event.type === "change" || event.type === "input") {
payload.form = formDataFor(matched || event.target);
}
return payload;
}
function propertyName(name) {
if (name === "text") return "textContent";
if (name === "html") return "innerHTML";
return String(name);
}
function readDom(selector, property) {
const element = document.querySelector(selector);
return element ? element[propertyName(property)] : null;
}
function setDom(selector, property, value) {
for (const element of document.querySelectorAll(selector)) {
const key = propertyName(property);
if (key in element) element[key] = value ?? "";
else if (value == null) element.removeAttribute(key);
else element.setAttribute(key, String(value));
}
}
function resolvePath(value, path) {
let current = value;
for (const part of path || []) current = current?.[part];
return current;
}
function resolveJsRef(path) {
let parent = null;
let value = globalThis;
for (const part of path || []) {
parent = value;
value = value?.[part];
}
return { parent, value };
}
async function evalClient(node, sourceEvent = null) {
if (!node || typeof node !== "object") return null;
switch (node.kind) {
case "literal": return node.value;
case "dom": return readDom(node.selector, node.property);
case "event": return resolvePath(sourceEvent, node.path);
case "event_get": {
const value = resolvePath(sourceEvent, node.path);
return value == null ? node.default : value;
}
case "js_ref": return resolveJsRef(node.path).value;
case "call": {
const args = [];
for (const arg of node.args || []) args.push(await evalClient(arg, sourceEvent));
if (node.callee?.kind === "js_ref") {
const ref = resolveJsRef(node.callee.path);
if (typeof ref.value !== "function") throw new TypeError(`${node.callee.path.join(".")} is not callable`);
return await ref.value.apply(ref.parent, args);
}
const fn = await evalClient(node.callee, sourceEvent);
if (typeof fn !== "function") throw new TypeError("client expression is not callable");
return await fn(...args);
}
case "binary": {
const left = await evalClient(node.left, sourceEvent);
const right = await evalClient(node.right, sourceEvent);
switch (node.op) {
case "add": return left + right;
case "sub": return left - right;
case "mul": return left * right;
case "div": return left / right;
case "mod": return left % right;
case "pow": return left ** right;
default: throw new Error(`unknown client operation: ${node.op}`);
}
}
default: throw new Error(`unknown client expression node: ${node.kind}`);
}
}
async function runProgram(program, sourceEvent = null) {
for (const instruction of program || []) {
if (instruction.op === "dom_set_expr") {
setDom(instruction.selector, instruction.property, await evalClient(instruction.expr, sourceEvent));
} else if (instruction.op === "dom_set") {
setDom(instruction.selector, instruction.property, instruction.value);
} else {
throw new Error(`unknown compiled Midnight instruction: ${instruction.op}`);
}
}
}
function programsFor(eventName, selector) {
const bucket = state.compiled.get(compiledKey(eventName, selector));
return bucket ? [...bucket.values()] : [];
}
function installCompiled(command) {
const key = compiledKey(command.event, command.selector);
let bucket = state.compiled.get(key);
if (!bucket) {
bucket = new Map();
state.compiled.set(key, bucket);
}
bucket.set(String(command.handler_id), command);
runtimeEvent("compiled-install", {
handler_id: command.handler_id,
event: command.event,
selector: command.selector,
exclusive: Boolean(command.exclusive),
});
}
function sendRaw(message) {
const text = typeof message === "string" ? message : JSON.stringify(message);
const socket = state.socket;
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(text);
return true;
}
state.outbox.push(text);
if (state.outbox.length > 256) state.outbox.splice(0, state.outbox.length - 256);
return false;
}
function sendEvent(payload, sourceEvent = null) {
const eventId = state.nextEventId++;
if (sourceEvent) state.pendingEvents.set(eventId, sourceEvent);
state.serverEvents += 1;
sendRaw({ type: "midnight-event", event_id: eventId, tab_id: state.tabId, event: payload });
runtimeEvent("server-event", { event_id: eventId, tab_id: state.tabId, payload });
return eventId;
}
async function applyCommand(command, sourceEvent = null) {
if (!command || typeof command !== "object") return;
const selector = command.selector;
switch (command.op) {
case "emit":
runtimeEvent(command.name, command.detail);
break;
case "text":
for (const element of document.querySelectorAll(selector)) element.textContent = String(command.value ?? "");
break;
case "html":
for (const element of document.querySelectorAll(selector)) element.innerHTML = String(command.value ?? "");
break;
case "value":
setDom(selector, "value", command.value);
break;
case "attr":
for (const element of document.querySelectorAll(selector)) {
if (command.value == null) element.removeAttribute(command.name);
else element.setAttribute(command.name, String(command.value));
}
break;
case "class_add":
for (const element of document.querySelectorAll(selector)) element.classList.add(...(command.names || []));
break;
case "class_remove":
for (const element of document.querySelectorAll(selector)) element.classList.remove(...(command.names || []));
break;
case "focus":
document.querySelector(selector)?.focus?.();
break;
case "bind":
for (const element of document.querySelectorAll("[data-midnight-bind]")) {
if (element.getAttribute("data-midnight-bind") === String(command.name)) {
element.textContent = String(command.value ?? "");
}
}
break;
case "dom_set":
setDom(command.selector, command.property, command.value);
break;
case "hybrid_client_set":
setDom(command.selector, command.property, await evalClient(command.expr, sourceEvent));
break;
case "hybrid_server_set": {
const values = (command.reads || []).map(item => readDom(item.selector, item.property));
sendEvent({
type: "custom:__hybrid_result",
selector: null,
detail: { request_id: command.request_id, values },
});
break;
}
case "compiled_install":
installCompiled(command);
if (command.execute_now) await runProgram(command.program, sourceEvent);
break;
case "hybrid_error":
runtimeEvent("error", command);
console.error("Midnight hybrid error", command);
break;
default:
runtimeEvent("unknown-command", command);
}
}
async function applyCommands(commands, sourceEvent = null) {
for (const command of commands || []) await applyCommand(command, sourceEvent);
}
function clearDomListeners() {
for (const [eventName, handler] of state.listeners) document.removeEventListener(eventName, handler, true);
state.listeners.clear();
}
function configure(subscriptions = []) {
clearDomListeners();
state.subscriptions = Array.isArray(subscriptions) ? subscriptions : [];
const events = [...new Set(state.subscriptions.map(item => item.event).filter(Boolean))];
for (const eventName of events) {
const handler = event => {
const items = state.subscriptions.filter(item => item.event === eventName);
for (const item of items) {
const selector = item.selector ?? null;
const matched = selector
? event.target instanceof Element ? event.target.closest(selector) : null
: event.target;
if (selector && !matched) continue;
if (item.prevent_default) event.preventDefault();
const programs = programsFor(eventName, selector);
if (programs.length) {
state.localCompiledEvents += 1;
void Promise.all(programs.map(program => runProgram(program.program, event))).then(() => {
runtimeEvent("compiled-execute", {
event: eventName,
selector,
handlers: programs.map(program => program.handler_id),
});
}).catch(error => runtimeEvent("error", { error: String(error) }));
if (programs.every(program => Boolean(program.exclusive))) continue;
}
sendEvent(serializeEvent(event, selector, matched), event);
}
};
state.listeners.set(eventName, handler);
document.addEventListener(eventName, handler, true);
}
runtimeEvent("configured", { subscriptions: state.subscriptions });
}
function clearReconnectTimer() {
if (state.reconnectTimer != null) clearTimeout(state.reconnectTimer);
state.reconnectTimer = null;
}
function scheduleReconnect() {
if (!state.reconnect || !state.url) return;
clearReconnectTimer();
state.reconnectAttempt += 1;
const delay = Math.min(
state.reconnectMaxDelayMs,
state.reconnectDelayMs * (2 ** Math.max(0, state.reconnectAttempt - 1)),
);
state.reconnectTimer = setTimeout(() => connectTransport(state.url, { _reconnect: true }), delay);
runtimeEvent("transport", { state: "reconnecting", attempt: state.reconnectAttempt, delay });
}
function connectTransport(url, options = {}) {
const reconnecting = Boolean(options._reconnect);
if (!reconnecting) {
state.url = String(url);
state.reconnect = options.reconnect !== false;
state.reconnectDelayMs = Math.max(0, Number(options.reconnectDelayMs ?? 500));
state.reconnectMaxDelayMs = Math.max(state.reconnectDelayMs, Number(options.reconnectMaxDelayMs ?? 5000));
state.reconnectAttempt = 0;
clearReconnectTimer();
if (state.socket) {
const old = state.socket;
state.socket = null;
old.close(1000, "replaced");
}
}
const socket = new WebSocket(state.url);
state.socket = socket;
runtimeEvent("transport", { state: "connecting", url: state.url, tab_id: state.tabId });
socket.addEventListener("open", () => {
if (state.socket !== socket) return;
state.reconnectAttempt = 0;
runtimeEvent("transport", { state: "open", url: state.url, tab_id: state.tabId });
const queued = state.outbox.splice(0);
for (const item of queued) socket.send(item);
});
socket.addEventListener("message", event => {
if (typeof event.data !== "string") return;
let message;
try { message = JSON.parse(event.data); }
catch { return; }
if (message.type === "midnight-config") {
configure(message.subscriptions || []);
return;
}
if (message.type === "midnight-commands") {
const eventId = Number(message.event_id || 0);
const sourceEvent = state.pendingEvents.get(eventId) || null;
state.pendingEvents.delete(eventId);
void applyCommands(message.commands || [], sourceEvent).catch(error => {
runtimeEvent("error", { error: String(error) });
});
return;
}
if (message.type === "midnight-error") runtimeEvent("error", message);
});
socket.addEventListener("close", event => {
if (state.socket !== socket) return;
state.socket = null;
runtimeEvent("transport", { state: "closed", code: event.code, reason: event.reason, tab_id: state.tabId });
scheduleReconnect();
});
socket.addEventListener("error", () => runtimeEvent("transport", { state: "error", tab_id: state.tabId }));
return socket;
}
function disconnectTransport(code = 1000, reason = "") {
state.reconnect = false;
clearReconnectTimer();
const socket = state.socket;
state.socket = null;
if (socket) socket.close(Number(code), String(reason));
}
function eachElement(selector, callback) {
const elements = [...document.querySelectorAll(String(selector))];
for (const element of elements) callback(element);
return elements.length;
}
function setStyle(selector, styles) {
if (!styles || typeof styles !== "object") throw new TypeError("midnight.style() expects a style object");
return eachElement(selector, element => {
for (const [name, value] of Object.entries(styles)) {
if (value == null) {
if (String(name).startsWith("--")) element.style.removeProperty(String(name));
else element.style[String(name)] = "";
continue;
}
if (String(name).startsWith("--") || String(name).includes("-")) {
element.style.setProperty(String(name), String(value));
} else {
element.style[String(name)] = String(value);
}
}
});
}
function hide(selector) {
return eachElement(selector, element => {
if (element.style.display !== "none") element.dataset.midnightDisplay = element.style.display || "";
element.style.display = "none";
});
}
function show(selector, display = null) {
return eachElement(selector, element => {
if (display != null) {
element.style.display = String(display);
} else if (Object.prototype.hasOwnProperty.call(element.dataset, "midnightDisplay")) {
element.style.display = element.dataset.midnightDisplay;
delete element.dataset.midnightDisplay;
} else {
element.style.removeProperty("display");
if (getComputedStyle(element).display === "none") element.style.display = "block";
}
});
}
function toggle(selector, force = null, display = null) {
let changed = 0;
for (const element of document.querySelectorAll(String(selector))) {
const hidden = getComputedStyle(element).display === "none";
const shouldShow = force == null ? hidden : Boolean(force);
if (shouldShow) showElement(element, display);
else hideElement(element);
changed += 1;
}
return changed;
}
function hideElement(element) {
if (element.style.display !== "none") element.dataset.midnightDisplay = element.style.display || "";
element.style.display = "none";
}
function showElement(element, display = null) {
if (display != null) {
element.style.display = String(display);
return;
}
if (Object.prototype.hasOwnProperty.call(element.dataset, "midnightDisplay")) {
element.style.display = element.dataset.midnightDisplay;
delete element.dataset.midnightDisplay;
return;
}
element.style.removeProperty("display");
if (getComputedStyle(element).display === "none") element.style.display = "block";
}
function css(cssText, id = "default") {
const key = String(id || "default");
const styleId = `midnight-css-${key.replace(/[^A-Za-z0-9_-]/g, "-")}`;
let element = document.getElementById(styleId);
if (!element) {
element = document.createElement("style");
element.id = styleId;
element.dataset.midnightCss = key;
(document.head || document.documentElement).appendChild(element);
}
element.textContent = String(cssText ?? "");
return element;
}
window.midnight = Object.freeze({
connectTransport,
disconnectTransport,
tabId: state.tabId,
style: setStyle,
show,
hide,
toggle,
css,
emit(name, detail = null) {
sendEvent({ type: `custom:${name}`, selector: null, detail });
},
on(name, handler, options) {
const wrapped = event => handler(event.detail, event);
window.addEventListener(`midnight:${name}`, wrapped, options);
return () => window.removeEventListener(`midnight:${name}`, wrapped, options);
},
stats() {
return {
connected: Boolean(state.socket && state.socket.readyState === WebSocket.OPEN),
tabId: state.tabId,
serverEvents: state.serverEvents,
localCompiledEvents: state.localCompiledEvents,
compiledPrograms: [...state.compiled.values()].reduce((count, bucket) => count + bucket.size, 0),
queued: state.outbox.length,
};
},
});
runtimeEvent("ready", { tab_id: state.tabId });
})();