-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathApiProvider.js
More file actions
412 lines (372 loc) · 10.1 KB
/
Copy pathApiProvider.js
File metadata and controls
412 lines (372 loc) · 10.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
import $ from 'jquery';
import React, { useEffect, useRef, useState } from 'react';
import { showToast } from '../toasts/toastEvents';
import ApiContext from './ApiContext';
import Poller from './Legacy';
import serverPath from './serverPath';
const ApiProvider = ({ children }) => {
const [connected, setConnected] = useState(false);
const [sessionInfo, setSessionInfo] = useState({ id: null, readonly: false });
const _socket = useRef(null);
const apiHandlers = useRef(null);
// ---------------- //
// helper functions //
// ---------------- //
const correctPathname = serverPath;
// ------------------- //
// basic communication //
// ------------------- //
// Send a low-level message to the server
const sendSocketMessage = (data) => {
if (!_socket.current) {
// eslint-disable-next-line no-console
console.error(
'[Visdom API] Cannot send message: WebSocket is not connected.',
data
);
return;
}
let msg = null;
try {
msg = JSON.stringify(data);
} catch (e) {
// eslint-disable-next-line no-console
console.error('[Visdom API] Failed to serialize message:', e, data);
return;
}
try {
_socket.current.send(msg);
} catch (e) {
// WebSocket may be CLOSING or CLOSED state
// eslint-disable-next-line no-console
console.error('[Visdom API] Failed to send message:', e, data);
}
};
// Establish a connection to the server
const connect = () => {
if (_socket.current) {
return;
}
const _onConnect = () => {
setConnected(true);
};
const _onDisconnect = () => {
// Silent cleanup - logging handled by event handlers
apiHandlers.current.onDisconnect(_socket);
setConnected(false);
};
// eslint-disable-next-line no-undef
if (USE_POLLING) {
_socket.current = new Poller(
correctPathname,
handleMessage,
_onConnect,
_onDisconnect
);
return;
}
var url = window.location;
var ws_protocol = null;
if (url.protocol == 'https:') {
ws_protocol = 'wss';
} else {
ws_protocol = 'ws';
}
const wsUrl = ws_protocol + '://' + url.host + correctPathname() + 'socket';
var socket = new WebSocket(wsUrl);
socket.onmessage = handleMessage;
socket.onopen = _onConnect;
socket.onerror = (event) => {
// Log error but don't call _onDisconnect here (let onclose handle it)
// eslint-disable-next-line no-console
console.error(
'[Visdom API] WebSocket error - the socket will likely close next',
event
);
};
socket.onclose = (event) => {
// Determine if this was a clean close or an error
if (!event.wasClean) {
// eslint-disable-next-line no-console
console.warn(
'[Visdom API] WebSocket closed unexpectedly.',
`Code: ${event.code}`,
`Reason: ${event.reason || '(no reason provided)'}`
);
}
// Only call _onDisconnect from onclose to avoid duplicate handling
_onDisconnect();
};
_socket.current = socket;
};
// Close the server connection and reset the _socket ref
const disconnect = () => {
if (_socket.current) {
_socket.current.close();
_socket.current = null;
}
};
// ------------------ //
// API receive events //
// -------------------//
// Process messages received from the server by
// implicitly defining event handlers for
// different types of server-commands
const handleMessage = (evt) => {
var cmd = JSON.parse(evt.data);
switch (cmd.command) {
case 'register':
setSessionInfo((prev) => ({
...prev,
id: cmd.data,
readonly: cmd.readonly,
}));
if (cmd.envList) {
apiHandlers.current.onEnvUpdate(cmd.envList);
}
break;
case 'pane':
case 'window':
case 'window_update':
apiHandlers.current.onWindowMessage({
cmd: cmd,
update: cmd.command === 'window_update',
});
break;
case 'reload':
apiHandlers.current.onReloadMessage(cmd.data);
break;
case 'close':
apiHandlers.current.onCloseMessage(cmd.data);
break;
case 'layout':
case 'layout_update':
apiHandlers.current.onLayoutMessage({
data: cmd.data,
update: cmd.command === 'layout_update',
});
break;
case 'env_update':
apiHandlers.current.onEnvUpdate(cmd.data);
break;
case 'undo_state':
apiHandlers.current.onUndoState(cmd);
break;
case 'notification':
showToast(cmd.data.message, cmd.data.type, {
duration: cmd.data.duration,
});
break;
default:
// eslint-disable-next-line no-console
console.error('unrecognized command', cmd);
}
};
// we need to update the socket-callback so that we have an up-to date state
if (_socket.current) _socket.current.onmessage = handleMessage;
// --------------- //
// API send events //
// ----------------//
// Request environment data from the server
const sendEnvQuery = (envIDs, showAll) => {
// This kicks off a new stream of events from the socket so there's nothing
// to handle here. We might want to surface the error state.
if (envIDs.length == 1) {
$.post(
correctPathname() + 'env/' + envIDs[0],
JSON.stringify({
sid: sessionInfo.id,
})
).fail((xhr) => {
document.open();
document.write(xhr.responseText);
document.close();
});
} else if (envIDs.length > 1) {
$.post(
correctPathname() + 'compare/' + envIDs.join('+'),
JSON.stringify({
sid: sessionInfo.id,
show_all: !!showAll,
})
).fail((xhr) => {
document.open();
document.write(xhr.responseText);
document.close();
});
}
};
// Toggle connection state between online and offline
const toggleOnlineState = () => {
if (connected) {
disconnect();
} else {
connect();
}
};
// Send message to server backend for a specific pane and environment.
const sendPaneMessage = (data, targetPaneID, targetEnvID) => {
if (targetPaneID === null || sessionInfo.readonly) {
return;
}
let finalData = {
target: targetPaneID,
eid: targetEnvID,
};
$.extend(finalData, data);
sendSocketMessage({
cmd: 'forward_to_vis',
data: finalData,
});
};
// Send request to revert to the previous set of embeddings in the given pane
const sendEmbeddingPop = (data, targetPaneID, targetEnvID) => {
if (targetPaneID === null || sessionInfo.readonly) {
return;
}
let finalData = {
target: targetPaneID,
eid: targetEnvID,
};
$.extend(finalData, data);
sendSocketMessage({
cmd: 'pop_embeddings_pane',
data: finalData,
});
};
// Send request to close a specific pane
const sendPaneClose = (paneID, envID) => {
sendSocketMessage({
cmd: 'close',
data: paneID,
eid: envID,
});
};
const sendUndo = (envID) => {
sendSocketMessage({
cmd: 'undo',
eid: envID,
});
};
// Send request to delete an environment
const sendEnvDelete = (envID, previousEnv) => {
sendSocketMessage({
cmd: 'delete_env',
prev_eid: previousEnv,
eid: envID,
});
};
// Send request to save the current environment
const sendEnvSave = (envID, prev_envID, data) => {
sendSocketMessage({
cmd: 'save',
data: data,
prev_eid: prev_envID,
eid: envID,
});
};
const sendSaveAll = () => {
sendSocketMessage({
cmd: 'save_all',
});
};
// Update the pane layout item in the backend.
const sendPaneLayoutUpdate = (
envID,
{ i, h, w, x, y, moved, static: staticBool }
) => {
sendSocketMessage({
cmd: 'layout_item_update',
eid: envID,
win: i,
data: { i, h, w, x, y, moved, static: staticBool },
});
};
const sendPlotLayoutUpdate = (envID, win, layoutPatch, frame) => {
sendSocketMessage({
cmd: 'update_plot_layout',
eid: envID,
win: win,
data: layoutPatch,
frame: frame,
});
};
const sendCommentUpdate = (envID, win, comment) => {
if (win === null || sessionInfo.readonly) {
return;
}
sendSocketMessage({
cmd: 'update_comment',
eid: envID,
win: win,
data: comment,
});
};
// Save layout lists to the server
const sendLayoutsSave = (layoutLists) => {
// pushes layouts to the server
let objForm = {};
for (let [envName, layoutList] of layoutLists) {
objForm[envName] = {};
for (let [layoutName, layoutMap] of layoutList) {
objForm[envName][layoutName] = {};
for (let [contentID, contentLoc] of layoutMap) {
objForm[envName][layoutName][contentID] = contentLoc;
}
}
}
let exportForm = JSON.stringify(objForm);
sendSocketMessage({
cmd: 'save_layouts',
data: exportForm,
});
};
// ------- //
// Effects //
// ------- //
// Redirect for POST request errors
useEffect(() => {
$(document).on('ajaxError', () => {
window.location.href = correctPathname() + 'error/500';
});
return () => {
$(document).off('ajaxError');
};
}, []);
// connect on mount, disconnect on unmount
useEffect(() => {
connect();
return () => {
disconnect();
};
}, []);
// -------------- //
// Define Context //
// -------------- //
return (
<ApiContext.Provider
value={{
apiHandlers,
connected,
sendCommentUpdate,
sendEmbeddingPop,
sendEnvDelete,
sendEnvQuery,
sendEnvSave,
sendLayoutsSave,
sendPaneClose,
sendPaneLayoutUpdate,
sendPlotLayoutUpdate,
sendPaneMessage,
sendSaveAll,
sendUndo,
sessionInfo,
setConnected,
toggleOnlineState,
}}
>
{children}
</ApiContext.Provider>
);
};
export default ApiProvider;