Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1086 lines (1020 loc) · 41 KB
/
Copy pathapp.js
File metadata and controls
1086 lines (1020 loc) · 41 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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Page logic: the example tree, the editor and the output pane.
// Python runs in worker.js; see that file for the message protocol.
const $ = (id) => document.getElementById(id);
// "?v=<commit>" on this script when deployed: passed on to everything fetched
// later so a new deploy never mixes with cached files
const VERSION = new URL(document.currentScript.src).search;
const versioned = (path) => path + VERSION;
const output = $("output");
const SCRATCH = "scratch.py"; // the blank editor, at #scratch
const editor = BilbyEditor.createEditor($("code"), {
onRun: () => run(),
describedBy: "editor-help",
onChange: (text) => { if (current?.path === SCRATCH) store("bilby-scratch", text); },
placeholderText: "# A blank editor: bilby, its samplers and LALSuite are available.\n# Ctrl/⌘+Enter to run.",
});
let worker = null;
let current = null; // {path, version, files, original, header}
let versions = null; // examples/versions.json
let bilby = null; // the bilby version in use: an entry of versions.versions
let running = false;
// localStorage, which can be unavailable (private windows, blocked storage)
function stored(key) {
try { return localStorage.getItem(key); } catch { return null; }
}
function store(key, value) {
try { localStorage.setItem(key, value); } catch {}
}
// Tell screen-reader users what happened (run started, finished, failed...).
function announce(text) {
const region = $("announce");
region.textContent = "";
setTimeout(() => { region.textContent = text; }, 50);
}
function setStatus(text, cls = "") {
$("status").textContent = text;
$("status").className = cls;
}
function setRunning(value) {
running = value;
$("run").disabled = value || !worker?.ready;
$("stop").disabled = !value;
}
// ---- output ---------------------------------------------------------------
const nearBottom = () => output.scrollHeight - output.scrollTop - output.clientHeight < 40;
// where output goes: the latest run's block, or the pane itself
let block = output;
function scrolled(fn) {
const stick = nearBottom();
fn();
if (stick) output.scrollTop = output.scrollHeight;
}
function append(text, cls) {
scrolled(() => {
const pre = document.createElement("pre");
if (cls) pre.className = cls;
pre.textContent = text;
block.appendChild(pre);
});
line = null;
}
// Start a collapsible block for a run; earlier runs collapse.
function startRun(text, cls) {
for (const old of output.querySelectorAll("details.run-block")) old.open = false;
scrolled(() => {
const details = document.createElement("details");
details.className = "run-block";
details.open = true;
const summary = document.createElement("summary");
summary.className = cls;
summary.textContent = text;
details.appendChild(summary);
output.appendChild(details);
block = details;
});
line = null;
}
// Terminal-style stream output: "\r" rewrites the current line, which keeps
// dynesty and tqdm progress bars on one line.
let line = null;
let lineKind = null;
let carriageReturn = false;
function write(kind, text) {
scrolled(() => {
for (const part of text.split(/(\r\n|\n|\r)/)) {
if (part === "\n" || part === "\r\n") {
if (!line) newLine(kind);
line = null;
carriageReturn = false;
} else if (part === "\r") {
carriageReturn = true;
} else if (part) {
if (!line || lineKind !== kind) newLine(kind);
if (carriageReturn) line.raw = "";
carriageReturn = false;
line.raw += part;
render(line);
}
}
});
}
function newLine(kind) {
line = document.createElement("pre");
line.className = kind;
line.raw = "";
lineKind = kind;
block.appendChild(line);
}
// A line is shown as text, or, if it is a tqdm progress line, as a bar like
// tqdm's Jupyter one: description, bar (when tqdm knows the total), count,
// time and rate, with any extra stats (dynesty's) on a second line.
// "desc: 42%|████▏ | 42/100 [00:03<00:04, 12.5it/s, extra]"
// "desc: 3it [00:00, 25.64it/s, extra]"
const TQDM_TOTAL = /^(?:(.*?): ?)?\s*(\d+)%\|[^|]*\| ?(\S+)\/(\S+) \[([^\]]*)\]\s*$/;
const TQDM_COUNT = /^(?:(.*?): ?)?(\d[\d.]*[kMG]?)it \[([^\]]*)\]\s*$/;
function render(pre) {
const total = pre.raw.match(TQDM_TOTAL);
const count = total ? null : pre.raw.match(TQDM_COUNT);
if (!total && !count) {
pre.classList.remove("tqdm");
pre.textContent = pre.raw;
return;
}
const [desc, stats] = total ? [total[1], total[5]] : [count[1], count[3]];
const [time, rate, ...extra] = stats.split(", ");
pre.classList.add("tqdm");
pre.textContent = "";
const row = document.createElement("div");
row.className = "tqdm-row";
const span = (cls, text) => {
const el = document.createElement("span");
el.className = cls;
el.textContent = text;
row.appendChild(el);
return el;
};
if (desc) span("tqdm-desc", desc);
if (total) {
const bar = span("tqdm-bar", "");
const fill = document.createElement("span");
fill.style.width = `${Math.min(100, Number(total[2]))}%`;
bar.appendChild(fill);
span("tqdm-count", `${total[2]}% · ${total[3]}/${total[4]}`);
} else {
span("tqdm-count", `${count[2]} it`);
}
span("tqdm-meta", [time, rate].filter(Boolean).join(" · "));
pre.appendChild(row);
if (extra.length) {
const more = document.createElement("div");
more.className = "tqdm-extra";
more.textContent = extra.join(", ");
pre.appendChild(more);
}
}
function showImage(name, b64) {
scrolled(() => {
const figure = document.createElement("figure");
const img = document.createElement("img");
img.src = "data:image/png;base64," + b64;
img.alt = name;
img.addEventListener("click", () => openFigure(img.src, name));
const caption = document.createElement("figcaption");
caption.textContent = name;
const download = document.createElement("a");
download.href = img.src;
download.download = fileName(name);
download.textContent = "download";
caption.appendChild(download);
figure.append(img, caption);
block.appendChild(figure);
});
line = null;
}
// Save a Blob as a file.
function save(blob, name) {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
// The files a run wrote, zipped by the worker: a link in the run's output,
// and the Results button for the latest run.
let latestResults = null;
const resultUrls = [];
function showResults({ name, bytes, count }) {
const blob = new Blob([bytes], { type: "application/zip" });
latestResults = { blob, name };
$("download-results").disabled = false;
const url = URL.createObjectURL(blob);
resultUrls.push(url);
scrolled(() => {
const pre = document.createElement("pre");
pre.className = "info";
const tab = document.createElement("a");
tab.href = "#";
tab.className = "files-link";
tab.textContent = `${count} file${count === 1 ? "" : "s"} written`;
tab.title = "See them in the Files tab";
tab.addEventListener("click", (e) => { e.preventDefault(); showTab("files", true); });
pre.appendChild(tab);
const link = document.createElement("a");
link.href = url;
link.download = name;
link.textContent = `download ${name} (${formatSize(blob.size)})`;
pre.appendChild(link);
block.appendChild(pre);
});
line = null;
}
function formatSize(bytes) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(0)} kB`;
return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
}
// what a figure is saved as: its file name, or "figure 1.png" for figures
// that were only shown (plt.show), never saved
const fileName = (name) => {
const base = name.split("/").pop();
return /\.\w+$/.test(base) ? base : base + ".png";
};
// a figure enlarged over the page, with a download link
function openFigure(src, name) {
const box = $("lightbox");
box.querySelector("img").src = src;
box.querySelector("img").alt = name;
const download = box.querySelector("a");
download.href = src;
download.download = fileName(name);
box.showModal();
}
$("lightbox").addEventListener("click", (e) => { if (e.target.tagName !== "A") $("lightbox").close(); });
// ---- files tab -------------------------------------------------------------
// The files the latest run wrote, as the worker reports them while it runs
// (worker.js, watchFiles): a list, and a preview of the one picked, which
// follows its updates (a checkpoint plot redrawn by the sampler, say).
// Files the user uploaded are listed above them.
const files = new Map(); // path -> {size, mtime, bytes?, url?, missing?}
let shownFile = null;
let shownUpload = false; // whether shownFile names an upload
let workerHasFiles = false; // false once Stop has replaced the worker
const IMAGE_TYPES = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif",
svg: "image/svg+xml", webp: "image/webp" };
const TEXT_LIMIT = 200 * 1024;
const extension = (path) => (path.match(/\.(\w+)$/)?.[1] || "").toLowerCase();
function setFileList(list, reset = false) {
if (reset) {
for (const file of files.values()) if (file.url) URL.revokeObjectURL(file.url);
files.clear();
if (!shownUpload) shownFile = null;
workerHasFiles = true;
}
for (const { path, size, mtime } of list) {
const file = files.get(path) || {};
// a file too large to send while running (PUSH_LIMIT in worker.js) is
// read again after the run if it changed
if (file.bytes && mtime !== file.mtime && size > 5 * 1024 ** 2) {
delete file.bytes;
if (file.url) URL.revokeObjectURL(file.url);
file.url = null;
}
files.set(path, { ...file, size, mtime });
}
drawFileList();
if (reset) drawFile();
}
function receiveFile({ path, mtime, bytes, missing }) {
const file = files.get(path);
if (!file) return;
if (file.url) URL.revokeObjectURL(file.url);
file.url = null;
file.missing = Boolean(missing);
if (bytes) {
file.bytes = bytes;
file.size = bytes.length;
file.mtime = mtime;
}
drawFileList();
if (path === shownFile && !shownUpload) drawFile();
}
function fileUrl(file, path) {
file.url ||= URL.createObjectURL(new Blob([file.bytes], { type: IMAGE_TYPES[extension(path)] || "application/octet-stream" }));
return file.url;
}
function drawFileList() {
const list = $("file-list");
const paths = [...files.keys()].sort();
const count = paths.length + uploads.size;
$("file-count").textContent = count ? String(count) : "";
list.textContent = "";
if (uploads.size) {
list.appendChild(fileHeading("Uploaded: copied next to the script before each run"));
for (const name of [...uploads.keys()].sort()) {
const row = fileButton(name, uploads.get(name), true);
const remove = document.createElement("button");
remove.className = "remove";
remove.dataset.remove = name;
remove.textContent = "×";
remove.title = `Remove ${name}`;
remove.setAttribute("aria-label", remove.title);
const wrap = document.createElement("div");
wrap.className = "upload";
wrap.append(row, remove);
list.appendChild(wrap);
}
if (paths.length) list.appendChild(fileHeading("Written by the last run"));
}
for (const path of paths) list.appendChild(fileButton(path, files.get(path), false));
}
function fileHeading(text) {
const heading = document.createElement("div");
heading.className = "heading";
heading.textContent = text;
return heading;
}
function fileButton(path, file, upload) {
const button = document.createElement("button");
button.dataset.path = path;
if (upload) button.dataset.upload = "";
if (path === shownFile && upload === shownUpload) button.setAttribute("aria-current", "true");
const name = document.createElement("span");
name.className = "name";
const slash = path.lastIndexOf("/") + 1;
const dir = document.createElement("span");
dir.className = "dir";
dir.textContent = path.slice(0, slash);
name.append(dir, path.slice(slash));
const meta = document.createElement("span");
meta.className = "meta";
meta.textContent = `${formatSize(file.size)} · ${new Date(file.mtime).toLocaleTimeString()}`;
button.append(name, meta);
return button;
}
function drawFile() {
const view = $("file-view");
view.textContent = "";
const file = (shownUpload ? uploads : files).get(shownFile);
if (!file) return;
const head = document.createElement("div");
head.className = "head";
const title = document.createElement("strong");
title.textContent = shownFile;
head.append(title, `${formatSize(file.size)} · ${shownUpload ? "uploaded" : "written"} ${new Date(file.mtime).toLocaleTimeString()}`);
view.appendChild(head);
if (!file.bytes) {
const note = document.createElement("p");
if (file.missing) note.textContent = "This file could not be read; it may have been removed.";
else if (!workerHasFiles) note.textContent = "Not available: Python was restarted (Stop) before this file was sent.";
else if (running) note.textContent = "This file is large, so it is sent when the run finishes.";
else {
note.textContent = "Loading…";
worker.postMessage({ type: "read", path: shownFile });
}
view.appendChild(note);
return;
}
const download = document.createElement("button");
download.textContent = "Download";
download.addEventListener("click", () => save(new Blob([file.bytes]), shownFile.split("/").pop()));
head.appendChild(download);
const ext = extension(shownFile);
if (IMAGE_TYPES[ext]) {
const img = document.createElement("img");
img.src = fileUrl(file, shownFile);
img.alt = shownFile;
img.addEventListener("click", () => openFigure(img.src, shownFile));
view.appendChild(img);
return;
}
// text if there is no NUL byte near the start
const start = file.bytes.subarray(0, 4096);
if (start.includes(0)) {
const note = document.createElement("p");
note.textContent = "A binary file: download it to open it.";
view.appendChild(note);
return;
}
const pre = document.createElement("pre");
pre.textContent = new TextDecoder().decode(file.bytes.subarray(0, TEXT_LIMIT));
if (file.bytes.length > TEXT_LIMIT) {
const note = document.createElement("p");
note.textContent = `Showing the first ${formatSize(TEXT_LIMIT)}; download it for the rest.`;
view.appendChild(note);
}
view.appendChild(pre);
}
$("file-list").addEventListener("click", (e) => {
const remove = e.target.closest("button[data-remove]");
if (remove) return removeUpload(remove.dataset.remove);
const button = e.target.closest("button[data-path]");
if (!button) return;
shownFile = button.dataset.path;
shownUpload = "upload" in button.dataset;
drawFileList();
$("file-list").querySelector(`[data-path="${CSS.escape(shownFile)}"]${shownUpload ? "[data-upload]" : ":not([data-upload])"}`).focus();
$("file-view").scrollTop = 0;
drawFile();
});
// ---- uploads ---------------------------------------------------------------
// Files the user adds (Upload, or dropped anywhere on the page): kept in this
// page and written next to the script before every run, so it can open them
// by name. They are not stored, so they are gone when the page is closed.
const uploads = new Map(); // name -> {bytes, size, mtime, url?}
async function addUploads(list) {
const added = [];
for (const file of list) {
if (!file.name || file.name.startsWith(".")) continue;
const old = uploads.get(file.name);
if (old?.url) URL.revokeObjectURL(old.url);
const bytes = new Uint8Array(await file.arrayBuffer());
uploads.set(file.name, { bytes, size: bytes.length, mtime: Date.now() });
added.push(file.name);
}
if (!added.length) return;
shownFile = added[0];
shownUpload = true;
showTab("files");
if (document.body.classList.contains("output-hidden")) setPaneHidden("output", false);
drawFileList();
drawFile();
announce(`Uploaded ${added.join(", ")}` + (running ? "; available from the next run" : ""));
}
function removeUpload(name) {
const file = uploads.get(name);
if (file?.url) URL.revokeObjectURL(file.url);
uploads.delete(name);
if (shownUpload && shownFile === name) {
shownFile = null;
shownUpload = false;
drawFile();
}
drawFileList();
announce(`Removed ${name}`);
}
$("upload").addEventListener("click", () => $("upload-input").click());
$("upload-input").addEventListener("change", async (e) => {
await addUploads(e.target.files);
e.target.value = "";
});
// dropping files anywhere uploads them (captured before the editor, which
// would otherwise paste a dropped text file into the script)
let dragDepth = 0;
const dragsFiles = (e) => e.dataTransfer?.types.includes("Files");
document.addEventListener("dragenter", (e) => {
if (!dragsFiles(e)) return;
dragDepth++;
document.body.classList.add("dropping");
}, true);
document.addEventListener("dragleave", (e) => {
if (dragsFiles(e) && --dragDepth <= 0) {
dragDepth = 0;
document.body.classList.remove("dropping");
}
}, true);
document.addEventListener("dragover", (e) => {
if (!dragsFiles(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
}, true);
document.addEventListener("drop", (e) => {
if (!dragsFiles(e)) return;
e.preventDefault();
e.stopPropagation();
dragDepth = 0;
document.body.classList.remove("dropping");
addUploads(e.dataTransfer.files);
}, true);
// Output / Files tabs (arrow keys move between them)
const TABS = ["output", "files"];
function showTab(name, focus = false) {
for (const tab of TABS) {
const button = $("tab-" + tab);
button.setAttribute("aria-selected", String(tab === name));
button.tabIndex = tab === name ? 0 : -1;
$(tab).hidden = tab !== name;
}
$("output-pane").classList.toggle("files-tab", name === "files");
if (focus) $("tab-" + name).focus();
}
for (const tab of TABS) {
$("tab-" + tab).addEventListener("click", () => showTab(tab));
$("tab-" + tab).addEventListener("keydown", (e) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
e.preventDefault();
showTab(TABS[(TABS.indexOf(tab) + 1) % TABS.length], true);
});
}
// ---- worker ---------------------------------------------------------------
function startWorker() {
const url = new URL(versioned("worker.js"), location.href);
url.searchParams.set("bilby", bilby.name);
worker = new Worker(url.href);
worker.ready = false;
setRunning(false);
setStatus("Starting Python…");
worker.onmessage = ({ data }) => {
switch (data.type) {
case "status":
setStatus(data.text);
if (!running) announce(data.text);
break;
case "progress":
showProgress(data);
break;
case "ready":
worker.ready = true;
setStatus("Ready: " + data.text, "ok");
announce("Ready to run");
setRunning(running);
break;
case "info":
append(data.text, "info");
break;
case "stream":
write(data.kind, data.text);
break;
case "image":
showImage(data.name, data.b64);
break;
case "files":
setFileList(data.files, data.reset);
break;
case "file":
receiveFile(data);
break;
case "results":
showResults(data);
break;
case "done":
append(`finished in ${data.seconds.toFixed(1)} s`, "info");
announce(`Finished in ${data.seconds.toFixed(1)} seconds` + (block.querySelector("img") ? ", with figures" : ""));
setStatus("Ready", "ok");
setRunning(false);
if (shownFile) drawFile(); // a large file can be read now
break;
case "error":
append(data.text, "error");
markTracebackLine(data.text);
announce((data.fatal ? "Python failed to start: " : "The run failed: ") + data.text.trim().split("\n").pop());
setStatus(data.fatal ? "Failed to start Python" : "Ready (last run failed)", data.fatal ? "err" : "");
setRunning(false);
if (shownFile && !data.fatal) drawFile();
break;
}
};
}
// Download progress of start-up and installs: the bar under the header, and
// the amount in the status text. expected is 0 when the total is unknown.
function showProgress({ done, label, received, expected }) {
const bar = $("progress");
bar.classList.toggle("active", !done);
bar.setAttribute("aria-hidden", String(Boolean(done)));
if (done) return;
bar.classList.toggle("unknown", !expected);
const fraction = expected ? Math.min(1, received / expected) : 0;
bar.firstElementChild.style.width = expected ? `${(fraction * 100).toFixed(1)}%` : "";
if (expected) bar.setAttribute("aria-valuenow", Math.round(fraction * 100));
else bar.removeAttribute("aria-valuenow");
const amount = expected
? `${formatSize(Math.min(received, expected))} of ${formatSize(expected)}`
: formatSize(received);
setStatus(`${label}… ${amount}`);
}
// Highlight the line of the example that a traceback points at: the last
// frame in the example itself (the worker runs it with filename = its path).
function markTracebackLine(text) {
if (!current) return;
const frame = new RegExp(`File "${current.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}", line (\\d+)`, "g");
const lines = [...text.matchAll(frame)].map((m) => Number(m[1]));
if (lines.length) editor.markErrorLine(lines[lines.length - 1]);
}
function run() {
if (!current || running || !worker?.ready) return;
if (document.body.classList.contains("output-hidden")) setPaneHidden("output", false);
setRunning(true);
setStatus("Running " + current.path + "…");
const testMode = $("test-mode").checked;
startRun(">>> " + current.path + (testMode ? " (test mode)" : ""), testMode ? "run test" : "run");
announce(`Running ${current.path.split("/").pop()}` + (testMode ? " in test mode" : ""));
editor.markErrorLine(null);
worker.postMessage({
type: "run", path: current.path, code: editor.getValue(), files: current.files,
filesFrom: current.version, testMode,
logLevel: $("log-level").value,
uploads: [...uploads].map(([name, { bytes }]) => ({ name, bytes })),
});
}
function stop() {
if (!running) return;
restartWorker("stopped; restarting Python", "error");
}
function restartWorker(message, cls) {
worker.terminate();
append(message, cls);
announce(message[0].toUpperCase() + message.slice(1));
block = output;
running = false;
workerHasFiles = false;
if (shownFile) drawFile();
startWorker();
}
// ---- example tree ---------------------------------------------------------
function buildTree(node, parent, depth = 0) {
for (const dir of node.dirs) {
const details = document.createElement("details");
details.open = depth === 0;
const summary = document.createElement("summary");
summary.textContent = dir.name;
details.appendChild(summary);
const list = document.createElement("div");
list.className = "children";
details.appendChild(list);
buildTree(dir, list, depth + 1);
parent.appendChild(details);
}
for (const example of node.examples) {
const link = document.createElement("a");
link.href = "#" + example.path;
link.textContent = example.name;
link.title = example.description;
link.dataset.doc = JSON.stringify(example.doc || []);
link.dataset.headerLines = example.header_lines || 0;
link.dataset.path = example.path;
link.dataset.files = JSON.stringify(node.files);
link.dataset.info = JSON.stringify({ changes: example.changes || [], support: example.support || null });
if (example.support) {
link.classList.add(example.support.status);
const note = document.createElement("span");
note.className = "sr-only";
note.textContent = example.support.status === "unsupported" ? " (not supported in the browser)" : " (partly supported)";
link.appendChild(note);
link.title += `\n\n${example.support.status}: ${example.support.reason}`;
}
parent.appendChild(link);
}
}
// Show only the examples whose path matches every word typed, with their
// folders opened; an empty search restores the folders as they were.
let openBeforeSearch = null;
function filterTree(query) {
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
const folders = [...document.querySelectorAll("#tree details")];
if (words.length && !openBeforeSearch) openBeforeSearch = folders.map((d) => d.open);
let any = false;
for (const a of document.querySelectorAll("#tree a")) {
const match = words.every((w) => a.dataset.path.toLowerCase().includes(w));
a.classList.toggle("hidden", !match);
any ||= match;
}
// innermost folders first, so a parent sees whether its children are visible
for (const details of folders.reverse()) {
const visible = !words.length || details.querySelector(".children > :not(.hidden)") !== null;
details.classList.toggle("hidden", !visible);
if (words.length) details.open = visible;
}
if (!words.length && openBeforeSearch) {
folders.reverse().forEach((d, i) => { d.open = openBeforeSearch[i]; });
openBeforeSearch = null;
}
$("no-match").classList.toggle("hidden", any || !words.length);
}
$("search").addEventListener("input", (e) => filterTree(e.target.value));
$("search").addEventListener("keydown", (e) => {
if (e.key === "Enter") {
const first = document.querySelector("#tree a:not(.hidden)");
if (first) location.hash = first.dataset.path;
} else if (e.key === "Escape") {
e.target.value = "";
filterTree("");
}
});
// Open an example of the bilby version in use. With keepCode, the editor
// keeps what it has (edits made to the same example in another version).
// Returns false if this version has no such example.
async function select(path, { keepCode = false } = {}) {
if (path === "scratch") {
openScratch();
return true;
}
const link = document.querySelector(`#tree a[data-path="${CSS.escape(path)}"]`);
if (!link) return false;
for (const a of document.querySelectorAll("#tree a.active")) a.classList.remove("active");
link.classList.add("active");
// open the folders containing this example
for (let el = link.parentElement; el && el.id !== "tree"; el = el.parentElement) {
if (el.tagName === "DETAILS") el.open = true;
}
const response = await fetch(versioned(`examples/${bilby.name}/${path}`));
// the shebang and docstring are shown as formatted text above the editor
// instead of in it; Download puts them back
const lines = (await response.text()).split("\n");
const headerLines = Number(link.dataset.headerLines);
const code = lines.slice(headerLines).join("\n");
current = {
path, version: bilby.name, files: JSON.parse(link.dataset.files), original: code,
header: headerLines ? lines.slice(0, headerLines).join("\n") + "\n" : "",
};
if (!keepCode) editor.load(code);
$("title").textContent = path;
showDoc(JSON.parse(link.dataset.doc));
showNotes(JSON.parse(link.dataset.info));
return true;
}
// A blank editor, not tied to an example; its text is kept in this browser.
function openScratch() {
for (const a of document.querySelectorAll("#tree a.active")) a.classList.remove("active");
current = { path: SCRATCH, version: bilby.name, files: [], original: "", header: "" };
editor.load(stored("bilby-scratch") || "");
$("title").textContent = SCRATCH;
showDoc(["<p>A blank editor. Its contents are kept in this browser; Reset clears it.</p>"]);
showNotes({ changes: [], support: null });
editor.focus();
}
// The example's docstring (HTML blocks made by scripts/make_manifest.py):
// the first paragraph, and the rest behind "more"; expanded stays expanded.
let docExpanded = false;
function showDoc(blocks) {
const doc = $("description");
doc.innerHTML = blocks[0] || "";
doc.classList.toggle("expanded", docExpanded);
if (blocks.length > 1) {
const more = document.createElement("div");
more.className = "more";
more.innerHTML = blocks.slice(1).join("");
const toggle = document.createElement("button");
toggle.className = "toggle-doc";
const label = () => { toggle.textContent = docExpanded ? "less" : "more"; };
label();
toggle.addEventListener("click", () => {
docExpanded = !docExpanded;
doc.classList.toggle("expanded", docExpanded);
label();
});
doc.append(more, toggle);
}
// links open in a new tab, so edits here are not lost
for (const a of doc.querySelectorAll("a")) {
a.target = "_blank";
a.rel = "noopener";
}
}
// What differs from the upstream example, and whether it can run here.
function showNotes({ changes, support }) {
const notes = $("notes");
notes.innerHTML = "";
if (support) {
const p = document.createElement("p");
p.className = support.status;
p.textContent = (support.status === "unsupported" ? "Not supported in the browser: " : "Partly supported: ") + support.reason;
notes.appendChild(p);
}
if (changes.length) {
const p = document.createElement("p");
p.className = "changes";
p.textContent = "Changed from the bilby example: " + changes.join("; ");
notes.appendChild(p);
}
}
// ---- bilby versions ------------------------------------------------------
// The page offers each version in examples/versions.json; ?bilby=<name> in
// its URL picks one (the default otherwise). Switching restarts Python with
// that version and keeps the example open, with any edits.
const DEFAULT_EXAMPLE = "core_examples/linear_regression.py";
// Show the examples of this version (bilby and its tree; not the worker).
async function showVersion(name) {
bilby = versions.versions.find((v) => v.name === name);
$("bilby-version").value = name;
$("bilby-version").title = `bilby ${bilby.version}: the version the examples come from and run with`;
const manifest = await (await fetch(versioned(`examples/${name}/manifest.json`))).json();
const tree = document.createElement("div");
tree.id = "examples";
buildTree(manifest, tree);
$("examples")?.remove();
$("tree").insertBefore(tree, $("tree").querySelector(".links")); // links stay last (phones)
if ($("search").value) filterTree($("search").value);
const link = $("source");
link.href = `https://github.com/bilby-dev/bilby/tree/${bilby.tag || bilby.commit}/examples`;
link.textContent = bilby.tag ? `examples from bilby ${bilby.tag}` : `examples from bilby@${bilby.commit.slice(0, 8)}`;
}
async function switchVersion(name) {
const url = new URL(location.href);
if (name === versions.default) url.searchParams.delete("bilby");
else url.searchParams.set("bilby", name);
history.replaceState(null, "", url);
const before = current;
const edited = editor.getValue() !== before.original;
await showVersion(name);
const label = bilby.version === name ? name : `${name} (${bilby.version})`;
restartWorker(`switched to bilby ${label}; restarting Python`, "info");
if (before.path === SCRATCH) return;
if (await select(before.path, { keepCode: edited })) {
if (edited) append(`kept your edits to ${before.path}; Reset gives bilby ${name}'s version`, "info");
} else {
// not an example in this version: keep it (and its data files) as it was
current = before;
append(`${before.path} is not one of bilby ${name}'s examples; it stays open, from bilby ${before.version}`, "info");
}
}
async function main() {
versions = await (await fetch(versioned("examples/versions.json"))).json();
const picker = $("bilby-version");
for (const v of versions.versions) picker.add(new Option(v.name, v.name));
const wanted = new URLSearchParams(location.search).get("bilby");
await showVersion(versions.versions.some((v) => v.name === wanted) ? wanted : versions.default);
startWorker();
picker.addEventListener("change", () => switchVersion(picker.value));
window.addEventListener("hashchange", () => select(decodeURIComponent(location.hash.slice(1))));
const path = decodeURIComponent(location.hash.slice(1));
if (!(await select(path || DEFAULT_EXAMPLE)) && path) {
append(`${path} is not one of bilby ${bilby.name}'s examples`, "info");
history.replaceState(null, "", "#" + DEFAULT_EXAMPLE);
await select(DEFAULT_EXAMPLE);
}
}
// bilby test mode: on by default when served locally (development), off on
// the live site; a choice made with the switch is remembered per browser
const savedTestMode = stored("bilby-test-mode");
const local = ["localhost", "127.0.0.1", "[::1]"].includes(location.hostname);
$("test-mode").checked = savedTestMode === null ? local : savedTestMode === "1";
const showTestMode = () => {
const on = $("test-mode").checked;
document.body.classList.toggle("test-mode", on);
$("run").title = (on ? "Run in bilby test mode" : "Run") + " (Ctrl/⌘+Enter)";
};
showTestMode();
$("test-mode").addEventListener("change", (e) => {
store("bilby-test-mode", e.target.checked ? "1" : "0");
showTestMode();
});
// bilby's log level (ERROR unless changed); remembered per browser
const savedLogLevel = stored("bilby-log-level");
if ([...$("log-level").options].some((o) => o.value === savedLogLevel)) $("log-level").value = savedLogLevel;
$("log-level").addEventListener("change", (e) => store("bilby-log-level", e.target.value));
// the example list can be hidden; remembered per browser. On phones it is a
// drawer over the page instead, closed after picking an example.
const phone = matchMedia("(max-width: 700px)");
const treeVisible = () => phone.matches
? document.body.classList.contains("tree-open")
: !document.body.classList.contains("tree-hidden");
const showTree = () => {
const visible = treeVisible();
$("toggle-tree").setAttribute("aria-expanded", String(visible));
$("toggle-tree").title = visible ? "Hide the example list" : "Show the example list";
};
// while the drawer is open the page behind it cannot be reached; closing it
// returns focus to the button that opened it
function setDrawer(open) {
const wasOpen = document.body.classList.contains("tree-open");
document.body.classList.toggle("tree-open", open);
for (const el of [document.querySelector("header"), $("editor-pane"), $("output-pane")]) el.inert = open;
showTree();
if (open) $("search").focus({ preventScroll: true });
else if (wasOpen && (!document.activeElement || $("tree").contains(document.activeElement) || document.activeElement === document.body)) {
$("toggle-tree").focus({ preventScroll: true });
}
}
$("close-tree").addEventListener("click", () => setDrawer(false));
document.body.classList.toggle("tree-hidden", stored("bilby-tree-hidden") === "1");
showTree();
$("toggle-tree").addEventListener("click", () => {
if (phone.matches) return setDrawer(!treeVisible());
const hidden = !document.body.classList.contains("tree-hidden");
document.body.classList.toggle("tree-hidden", hidden);
store("bilby-tree-hidden", hidden ? "1" : "0");
showTree();
});
$("scrim").addEventListener("click", () => setDrawer(false));
// the editor and the output can be hidden as well, but never both: hiding one
// while the other is hidden swaps them. Remembered per browser.
const PANES = { editor: "the editor", output: "the output" };
function setPaneHidden(pane, hidden) {
const other = pane === "editor" ? "output" : "editor";
document.body.classList.toggle(pane + "-hidden", hidden);
if (hidden) document.body.classList.remove(other + "-hidden");
for (const name in PANES) {
const isHidden = document.body.classList.contains(name + "-hidden");
const button = $("toggle-" + name);
button.setAttribute("aria-expanded", String(!isHidden));
button.title = (isHidden ? "Show " : "Hide ") + PANES[name];
store("bilby-" + name + "-hidden", isHidden ? "1" : "0");
}
}
if (stored("bilby-output-hidden") === "1") setPaneHidden("output", true);
else if (stored("bilby-editor-hidden") === "1") setPaneHidden("editor", true);
for (const name in PANES) {
$("toggle-" + name).addEventListener("click", () =>
setPaneHidden(name, !document.body.classList.contains(name + "-hidden")));
}
// Run lives in the editor toolbar; with the editor hidden, Ctrl/⌘+Enter
// anywhere on the page still runs (the editor handles it otherwise)
document.addEventListener("keydown", (e) => {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey) && !e.repeat &&
document.body.classList.contains("editor-hidden")) {
e.preventDefault();
run();
}
});
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && document.body.classList.contains("tree-open")) setDrawer(false);
});
$("tree").addEventListener("click", (e) => {
if (phone.matches && e.target.closest("a[data-path]")) setDrawer(false);
});
// the header links live at the bottom of the drawer on phones
const placeLinks = () => {
const links = document.querySelector(".links");
if (phone.matches) $("tree").appendChild(links);
else document.querySelector("header").appendChild(links);
setDrawer(false);
};
placeLinks();
phone.addEventListener("change", placeLinks);
// iOS zooms in when focusing text smaller than 16px (the editor); stop that
// zoom there only (iOS still allows pinch zoom with maximum-scale set)
if (/iPhone|iPad|iPod/.test(navigator.userAgent)) {
document.querySelector('meta[name="viewport"]').content += ", maximum-scale=1";
}
$("run").addEventListener("click", run);
$("new").addEventListener("click", () => {
if (location.hash === "#scratch") openScratch();
else location.hash = "scratch";
});
$("stop").addEventListener("click", stop);
$("clear").addEventListener("click", () => {
output.innerHTML = "";
block = output;
line = null;
resultUrls.splice(0).forEach((url) => URL.revokeObjectURL(url));
latestResults = null;
$("download-results").disabled = true;
});
$("download-results").addEventListener("click", () => {
if (latestResults) save(latestResults.blob, latestResults.name);
});
$("download-script").addEventListener("click", () => {
if (current) save(new Blob([current.header + editor.getValue()], { type: "text/x-python" }), current.path.split("/").pop());
});