-
Notifications
You must be signed in to change notification settings - Fork 862
/
Copy pathembed.ts
100 lines (90 loc) · 3.18 KB
/
embed.ts
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { DictTable } from "../components/ComponentType";
import { createTableFromFromObjectArray } from "../data/utils";
import { AppConfig } from "./utils";
interface Action {
actionName: string;
actionParams: object;
}
interface LoadDataAction extends Action {
actionName: "loadData";
actionParams: {
tableName: string;
table: object[];
}
}
interface SetConfigAction extends Action {
actionName: "setConfig";
actionParams: AppConfig;
}
export interface ActionSubscription {
loadData?: (table: DictTable) => void;
setAppConfig?: (appConfig: AppConfig) => void;
}
const actionQueue: Action[] = [];
const subscribers: ActionSubscription[] = [];
export const subscribe = (subscription: ActionSubscription) => {
subscribers.push(subscription);
if (actionQueue.length) {
//send queued events to subscribers, on the next thread cycle.
//remove events after they are sent.
setTimeout(() => {
actionQueue.forEach(sendEventToSubscribers);
actionQueue.length = 0;
}, 0);
}
};
export const unsubscribe = (subscription: ActionSubscription) => {
const index = subscribers.indexOf(subscription);
if (index !== -1) {
subscribers.splice(index, 1);
}
};
function sendEventToSubscribers(action: Action) {
subscribers.forEach(subscription => {
switch (action.actionName) {
case "loadData": {
if (subscription.loadData) {
let loadDataAction = action as LoadDataAction;
let table: undefined | DictTable = undefined;
try {
table = createTableFromFromObjectArray(loadDataAction.actionParams.tableName || 'dataset', loadDataAction.actionParams.table);
} catch (error) {
console.error("ActionQueue: error creating table from message", error);
}
if (table) {
console.log('ActionQueue: success creating table from message');
subscription.loadData(table);
}
}
break;
}
case "setConfig": {
if (subscription.setAppConfig) {
let setConfigAction = action as SetConfigAction;
subscription.setAppConfig(setConfigAction.actionParams as AppConfig);
}
break;
}
default: {
console.log("ActionQueue: unknown action", action.actionName);
break;
}
}
});
}
window.addEventListener("message", (event: MessageEvent<Action>) => {
const action = event.data;
//console.log("ActionQueue: received action message", action);
if (action?.actionName) {
if (subscribers.length === 0) {
console.log("ActionQueue: no subscribers, queuing event");
actionQueue.push(action);
return;
} else {
console.log("ActionQueue: sending event to subscribers");
sendEventToSubscribers(action);
}
}
});