-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathotree-front-live.js
59 lines (53 loc) · 1.52 KB
/
otree-front-live.js
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
/*
// This file is originally a part of https://github.com/qwiglydee/otree-advanced-demos
// SPDX-FileCopyrightText: © 2024 Maxim Vasilyev <[email protected]>
// SPDX-License-Identifier: MIT
*/
/**
* Helpers to communicate with backend driven by `utils/live.py`
*/
if (window.liveSocket) {
window.liveSocket.onmessage = triggerLive;
} else {
throw new Error("otree-front-live.js doesn't see live socket")
}
/**
* Warapper for live handlers.
*
* @example
* onLive('message_type', handleLive);
*
* function handleLive(data) { ... }
*/
function onLive(name, handler) {
ot.onEvent('live', name, (e) => handler(e.detail.data));
}
/**
* Sending a live message.
*
* @example
* sendLive("something", { ... } );
* sendLive("something", "foo");
* sendLive("something");
*
* @param {string} type type of the message
* @param {object} [data] message payload
*/
function sendLive(type, data) {
window.liveSocket.send(JSON.stringify({ type, data }))
}
/**
* @event live
* @property {object} detail
* @property {string} detail.name type of a message
* @property {any} detail.data message payload
*/
/** converting live socket messages into ot-events */
function triggerLive(event) {
let data = JSON.parse(event.data);
if (!ot.isArray(data)) throw new Error("live socket received invalid data")
for (let msg of data) {
if (!ot.isObject(msg) || !Object.hasOwn(msg, 'type')) throw new Error("live socket received invalid data")
ot.emitEvent('live', { name: msg.type, data: msg.data });
}
}