-
Notifications
You must be signed in to change notification settings - Fork 2
/
renderer.js
562 lines (460 loc) · 18.7 KB
/
renderer.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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
require('codemirror/mode/python/python');
require('codemirror/addon/scroll/simplescrollbars');
require('codemirror/addon/display/placeholder');
const electron = require("electron");
const cm = require('codemirror');
const WebSocket = require('ws');
let editor;
let code_display;
const defaultFunction = 'def a(x, y, *, w=-1):\n\treturn w*y, x';
const dF_dimension_regex = /(?<=def\s+\w+\s*\()[^\*]+(?=,\s*\*)|(?<=def\s+\w+\s*\()[^\*]+(?=\))/;
let configuration = {};
let params = {};
let prev_params = {};
let dF_args = {};
let sliders = {};
let dF_args_length = 0;
let plot_visible = true;
let isLoading = true;
let alertId = 0;
let mpl_websocket;
let Figure;
let ws_uri = "ws://127.0.0.1:8080/";
window.onload = () => {
editor = cm.fromTextArea(document.getElementById('codemirror-container'), {
mode: 'python',
theme: 'material',
lineNumbers: true,
placeholder: defaultFunction,
});
editor.on("drop", (editor, e) => {return false;});
code_display = cm.fromTextArea(document.getElementById('codemirror-container-code-display'), {
mode: 'python',
theme: 'material',
lineNumbers: true,
});
editor.on('change', e => {
update_dF_args(e.getValue());
update_range_div();
});
let parameters_div = document.getElementById('parameters_div');
document.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
let _file = e.dataTransfer.files[0];
if (_file.type === "application/json"){
// loadJSON(_file.path, (data)=>{dF_args=data[0];});
data = require(_file.path);
set_params(data);
plot(data);
};
return false;
});
document.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
setLoadingState(true);
});
document.addEventListener('dragenter', (event) => {
setLoadingState(true);
});
document.addEventListener('dragleave', (event) => {
setLoadingState(false);
});
electron.ipcRenderer.send("request-configuration");
}
electron.ipcRenderer.on("load-configuration", (event, settings) => {
configuration = settings;
console.log(configuration);
if (configuration["dark"]) toggleDarkMode();
});
electron.ipcRenderer.on("load-plot", (event, FigId) => {
let fig_div = document.getElementById("figure");
while (fig_div.lastElementChild) {
fig_div.removeChild(fig_div.lastElementChild);
}
Figure = null;
if (!Figure) {
create_figure();
}
if (!plot_visible) {
document.getElementById("code_div").style.display = 'none';
plot_visible = !plot_visible;
}
setLoadingState(false);
});
electron.ipcRenderer.on("show-code", (event, code) => {
if (plot_visible) {
document.getElementById("figure").style.display = 'none';
plot_visible = !plot_visible;
}
document.getElementById("code_div").style.display = 'flex';
code_display.setValue(code);
setLoadingState(false);
});
electron.ipcRenderer.on("show-error", (event, message) => {
addAlert(message);
document.getElementById('error').style.display = 'flex';
setLoadingState(true)
setLoadingState(false);
});
function create_figure (){
let _websocket_type_ = get_websocket_type();
mpl_websocket = new _websocket_type_(`${ws_uri}ws`);
ondownload = (figure, format) => {
window.open('http://127.0.0.1:8080/download.' + format, '_blank')
};
Figure = new window.mpl.figure(
// A unique numeric identifier for the figure
0,
// A websocket object (or something that behaves like one)
mpl_websocket,
// A function called when a file type is selected for download
ondownload,
// The HTML element in which to place the figure
document.getElementById("figure"));
};
function add_dFarg(param_name, placeholder, min, max) {
if (dF_args_length == 0) {
document.getElementById('dF_args_div').style.display = null;
}
let param_div = document.createElement('div');
param_div.id = `${param_name}_div`
param_div.className = "container w-full flex gap-2 items-center";
let param_div_name = document.createElement('div');
param_div_name.className = "block uppercase tracking-wide text-gray-700 dark:text-gray-50 text-xs font-bold mb-1";
param_div_name.innerHTML = param_name;
param_div.append(param_div_name);
let param_slider_min = document.createElement('input');
param_slider_min.id = `${param_name}_slider_min`;
param_slider_min.type = "number";
param_slider_min.placeholder = String(min);
param_slider_min.className = "appearance-none block w-full bg-gray-200 dark:bg-[#263238] text-gray-700 " +
"border border-gray-200 dark:border-gray-500 rounded py-3 px-4 mb-3 dark:text-gray-100 leading-tight " +
"focus:outline-none focus:bg-white focus:border-gray-500";
param_div.append(param_slider_min);
let param_input = document.createElement('input');
param_input.id = `${param_name}_value`;
param_input.type = "number";
param_input.value = String(placeholder);
param_input.placeholder = String(placeholder);
param_input.className = "appearance-none block w-full bg-gray-200 dark:bg-[#263238] text-gray-700 " +
"border border-gray-200 dark:border-gray-500 rounded py-3 px-4 mb-3 dark:text-gray-100 leading-tight " +
"focus:outline-none focus:bg-white focus:border-gray-500";
param_div.append(param_input);
let param_slider_max = document.createElement('input');
param_slider_max.id = `${param_name}_slider_max`;
param_slider_max.type = "number";
param_slider_max.placeholder = String(max);
param_slider_max.className = "appearance-none block w-full bg-gray-200 dark:bg-[#263238] text-gray-700 " +
"border border-gray-200 dark:border-gray-500 rounded py-3 px-4 mb-3 dark:text-gray-100 leading-tight " +
"focus:outline-none focus:bg-white focus:border-gray-500";
param_div.append(param_slider_max);
document.getElementById('dF_args_container').append(param_div);
}
function remove_dFarg(param_name) {
document.getElementById(`${param_name}_div`)?.remove();
}
function update_range_div() {
// FEATURE: add automatic names for mandatory parameters
params['dF'] = !!editor.getValue() ? editor.getValue() : defaultFunction;
// Find dF mandatory parameters dimension
if (dF_dimension_regex.test(params['dF'])) {
const dF_dimension_match = params['dF'].match(dF_dimension_regex);
let dimension = dF_dimension_match[0].split(',').length;
if (dimension==3) {
document.getElementById('z_range_div').style.display = 'flex';
}
else
document.getElementById('z_range_div').style.display = 'none';
}
}
function update_dF_args(functionValue) {
const dF_args_new = {};
const sliders_new = {};
const dF_args_regex = /(?<=\*\s*,)[^\\)]*/;
// If function is not correctly writen remove all dF_args divs
if (!dF_args_regex.test(functionValue)) {
Object.keys(dF_args).forEach(function (key) {
if (!(key in dF_args_new)) {
remove_dFarg(key);
dF_args_length -= 1;
}
});
if (dF_args_length === 0) {
document.getElementById('dF_args_div').style.display = 'none'
}
dF_args = dF_args_new;
sliders = sliders_new;
return;
}
// Get new dF_args and values from dF functionValue
const dF_args_match = functionValue.match(dF_args_regex);
if (dF_args_match) {
const arguments = dF_args_match[0].replace(/\s+/g, '').split(',');
arguments.forEach(parameter => {
if (!parameter) return;
if (parameter.match(/=/)) {
const parameter_splited = parameter.split(/=/);
dF_args_new[parameter_splited[0]] = Number(parameter_splited[1]);
} else {
dF_args_new[parameter] = 0;
}
});
}
// For each dF_args_new get value, sliders min and max, and add div if not exists
Object.keys(dF_args_new).forEach(function (key) {
if (key in dF_args) {
dF_args_new[key] = Number(document.getElementById(`${key}_value`).value);
sliders_new[key] = {};
sliders_new[key]["min"] = document.getElementById(`${key}_slider_min`).value ? Number(document.getElementById(`${key}_slider_min`).value) : dF_args_new[key]-1;
sliders_new[key]["max"] = document.getElementById(`${key}_slider_max`).value ? Number(document.getElementById(`${key}_slider_max`).value) : dF_args_new[key]+1;
} else {
add_dFarg(key, dF_args_new[key], dF_args_new[key]-1, dF_args_new[key]+1);
dF_args_length += 1;
}
});
// Update dF_args to dF_args_new: remove div not valid
Object.keys(dF_args).forEach(function (key) {
if (!(key in dF_args_new)) {
remove_dFarg(key);
dF_args_length -= 1;
}
});
if (dF_args_length === 0) {
document.getElementById('dF_args_div').style.display = 'none'
}
dF_args = dF_args_new;
sliders = sliders_new;
}
function update_params() {
params = {};
// dF
params['dF'] = !!editor.getValue() ? editor.getValue() : defaultFunction;
// Find dF mandatory parameters dimension
const dF_dimension_match = params['dF'].match(dF_dimension_regex);
params["dimension"] = dF_dimension_match[0].split(',').length;
// if (params['dF'] === prev_params?['dF']:''){
// params = {};
// }
// dF_args_new
update_dF_args(params['dF']);
params['dF_args'] = dF_args;
params['sliders'] = sliders;
// Range
x_min = document.getElementById('x_min').value ? Number(document.getElementById('x_min').value) : 0;
x_max = document.getElementById('x_max').value ? Number(document.getElementById('x_max').value) : 1;
y_min = document.getElementById('y_min').value ? Number(document.getElementById('y_min').value) : 0;
y_max = document.getElementById('y_max').value ? Number(document.getElementById('y_max').value) : 1;
z_min = document.getElementById('z_min').value ? Number(document.getElementById('z_min').value) : 0;
z_max = document.getElementById('z_max').value ? Number(document.getElementById('z_max').value) : 1;
params['Range'] = {
x_min,
x_max,
y_min,
y_max
};
if (params['dimension'] == 3) {
params['Range'] = {
x_min,
x_max,
y_min,
y_max,
z_min,
z_max
};
}
// Optionals
MeshDim = Number(document.getElementById('MeshDim').value);
if (MeshDim) params['MeshDim'] = MeshDim;
// TODO: make other portraits available as trajectories or maps.
if (params["dimension"]==3) {
params['MeshDim'] = Math.min(params['MeshDim']?params['MeshDim']:8, 8);
params["phaseportrait_object_type"] = "PhasePortrait3D";
}
if (params["dimension"]==2) {
params["phaseportrait_object_type"] = "PhasePortrait2D";
}
Density = Number(document.getElementById('Density').value);
if (Density) params['Density'] = Density;
Polar = Boolean(document.getElementById('Polar').checked);
if (Polar) params['Polar'] = Polar;
xScale = document.getElementById('xScale').value;
if (xScale) params['xScale'] = xScale;
yScale = document.getElementById('yScale').value;
if (yScale) params['yScale'] = yScale;
Colorbar = Boolean(document.getElementById('Colorbar').checked);
if (Colorbar) params['Colorbar'] = Colorbar;
Title = document.getElementById('Title').value;
if (Title) params['Title'] = Title;
xlabel = document.getElementById('xlabel').value;
if (xlabel) params['xlabel'] = xlabel;
ylabel = document.getElementById('ylabel').value;
if (ylabel) params['ylabel'] = ylabel;
color = document.getElementById('color').value;
if (color) params['color'] = color;
// Nullclines
offset = Number(document.getElementById('offset').value);
precision = Number(document.getElementById('precision').value);
if (document.getElementById('precision').value) {
if (!offset) offset = 0;
params['nullcline'] = {
offset,
precision
};
}
params['path'] = `${__dirname}/svg/`;
prev_params = params;
return params
}
function set_params(new_params) {
// dF
editor.setValue(new_params['dF']);
// Range
document.getElementById('x_min').value = new_params["Range"]["x_min"];
document.getElementById('x_max').value = new_params["Range"]["x_max"];
document.getElementById('y_min').value = new_params["Range"]["y_min"];
document.getElementById('y_max').value = new_params["Range"]["y_max"];
// Optionals
if (!(new_params['MeshDim'] === undefined))
document.getElementById('MeshDim').value = new_params['MeshDim'];
if (!(new_params['Density'] === undefined))
document.getElementById('Density').value = new_params['Density'];
if (!(new_params['Polar'] === undefined))
document.getElementById('Polar').checked = Boolean(new_params['Polar']);
if (!(new_params['xScale'] === undefined))
document.getElementById('xScale').value = new_params['xScale'];
if (!(new_params['yScale'] === undefined))
document.getElementById('yScale').value = new_params['yScale'];
if (!(new_params['Colorbar'] === undefined))
document.getElementById('Colorbar').checked = Boolean(new_params['Colorbar']);
if (!(new_params['Title'] === undefined))
document.getElementById('Title').value = new_params['Title'];
if (!(new_params['xlabel'] === undefined))
document.getElementById('xlabel').value = new_params['xlabel'];
if (!(new_params['ylabel'] === undefined))
document.getElementById('ylabel').value = new_params['ylabel'];
if (!(new_params['color'] === undefined))
document.getElementById('color').value = new_params['color'];
// Nullclines
if (new_params['nullcline']){
document.getElementById('offset').value = Number(new_params['nullcline']['offset']);
document.getElementById('precision').value = Number(new_params['nullcline']['precision']);
}
prev_params = new_params;
return new_params
}
function plot(_params=false) {
exit_code_display()
params = (!_params)? update_params(): _params;
// In case plot button spam
if (isLoading){
addAlert("Please, wait until the plot is shown.")
return
}
setLoadingState(true);
electron.ipcRenderer.send("request-plot", params);
}
function get_python_code() {
params = update_params();
// setLoadingState(true);
electron.ipcRenderer.send("request-code", params);
}
function setLoadingState(loadingState) {
if (loadingState) {
document.getElementById('figure').style.display = 'none';
document.getElementById('code_div').style.display = 'none';
document.getElementById('error').style.display = 'none';
}
else{
if (plot_visible) {
document.getElementById('figure').style.display = 'flex';
}
else{
document.getElementById('code_div').style.display = 'flex';
}
}
document.getElementById('loader').style.display = loadingState ? 'flex' : 'none';
isLoading = loadingState;
}
function toggleDarkMode() {
const root = document.getElementsByTagName('html')[0];
let is_dark = root.classList.contains('dark');
if (is_dark) root.classList.remove('dark');
else root.classList.add('dark');
configuration["dark"] = !is_dark;
electron.ipcRenderer.send("save-configuration", configuration);
}
function toggleFullScreenMode() {
const imageArea = document.getElementById('image-area');
const formArea = document.getElementById('parameters_div');
const creditsArea = document.getElementById('credits-area');
const resultCode = document.getElementById('result-code');
if (imageArea.classList.contains('image-area--zoom')) {
imageArea.classList.remove('image-area--zoom');
formArea.style.display = 'flex';
creditsArea.style.display = 'flex';
resultCode.classList.remove('code-display--full-screen');
} else {
imageArea.classList.add('image-area--zoom');
formArea.style.display = 'none';
creditsArea.style.display = 'none';
resultCode.classList.add('code-display--full-screen');
}
}
function exit_code_display() {
if (!plot_visible) {
document.getElementById("figure").style.display = null;
document.getElementById("code_div").style.display = 'none';
plot_visible = !plot_visible;
}
}
function addAlert(message) {
const alerts = document.getElementById('alerts');
const alertsContainer = document.getElementById('alerts-container');
const newAlertId = alertId++;
const newAlert = `
<div id="alert-${newAlertId}" class="
flex bg-red-100 text-red-700 px-4 py-3 relative
dark:bg-red-300 dark:text-red-900 rounded-md
">
<span class="block flex-1 sm:inline pr-1">${message}</span>
<span onclick="removeAlert('alert-${newAlertId}')" class="cursor-pointer">
<svg class="fill-current h-6 w-6 text-red-500 hover:text-red-700 dark:text-red-600 dark:hover:text-red-900"
viewBox="0 0 20 20"><title>Close</title><path
d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1
1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1
1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg>
</span>
</div>`;
alerts.innerHTML = newAlert + alerts.innerHTML;
alertsContainer.style.display = 'flex';
}
function removeAlert(id) {
const alerts = document.getElementById('alerts');
const alertsContainer = document.getElementById('alerts-container');
document.getElementById(id).remove();
if (!alerts.innerHTML.trim()) {
alertsContainer.style.display = 'none';
}
}
function removeAllAlerts() {
const alerts = document.getElementById('alerts');
const alertsContainer = document.getElementById('alerts-container');
alertsContainer.style.display = 'none';
alerts.innerHTML = '';
}
function get_websocket_type() {
if (typeof WebSocket !== 'undefined') {
return WebSocket;
} else if (typeof MozWebSocket !== 'undefined') {
return MozWebSocket;
} else {
alert(
'Your browser does not have WebSocket support. ' +
'Please try Chrome, Safari or Firefox ≥ 6. ' +
'Firefox 4 and 5 are also supported but you ' +
'have to enable WebSockets in about:config.'
);
}
};