-
Notifications
You must be signed in to change notification settings - Fork 504
Expand file tree
/
Copy pathsession.js
More file actions
1612 lines (1353 loc) · 44.7 KB
/
Copy pathsession.js
File metadata and controls
1612 lines (1353 loc) · 44.7 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
import {
isMacOS,
isEditableElement,
clamp,
selectElementContent,
smoothlyScrollToElement,
setFavicon,
cancelEvent,
isElementInViewport,
isElementHidden,
} from "../lib/utils";
import { getAttributeOrDefault } from "../lib/attribute";
import KeyBuffer from "../lib/key_buffer";
import { globalPubSub } from "../lib/pub_sub";
import monaco from "./cell_editor/live_editor/monaco";
import { leaveChannel } from "./js_view/channel";
import { isDirectlyEditable, isEvaluable } from "../lib/notebook";
import { settingsStore } from "../lib/settings";
/**
* A hook managing the whole session.
*
* Serves as a coordinator handling all the global session events.
* Note that each cell has its own hook, so that LV keeps track of
* cells being added/removed from the DOM. We do however need to
* communicate between this global hook and cells and for that we
* use a simple local pubsub that the hooks subscribe to.
*
* ## Configuration
*
* * `data-autofocus-cell-id` - id of the cell that gets initial
* focus once the notebook is loaded
*
* ## Shortcuts
*
* This hook registers session shortcut handlers,
* see `LivebookWeb.SessionLive.ShortcutsComponent`
* for the complete list of available shortcuts.
*
* ## Navigation
*
* This hook handles focusing section titles, cells and moving the
* focus around, this is done purely on the client side because it is
* event-intensive and specific to this client only. The UI changes
* are handled by setting `data-js-*` attributes and applying CSS
* accordingly (see assets/css/js_interop.css). Navigation changes
* are also broadcasted to all cell hooks via PubSub.
*
* ## Location tracking and following
*
* Location describes where the given client is within the notebook
* (in which cell, and where specifically in that cell). When multiple
* clients are connected, they report own location to each other
* whenever it changes. We then each the location to show cursor and
* selection indicators.
*
* Additionally the current user may follow another client from the
* clients list. In such case, whenever a new location comes from that
* client we move there automatically (i.e. we focus the same cells
* to effectively mimic how the followed client moves around).
*
* Initially we load basic information about connected clients using
* the `"session_init"` event and then update this information whenever
* clients join/leave/update. This way location reports include only
* client id, as we already have the necessary hex_color/name locally.
*/
const Session = {
mounted() {
this.props = this.getProps();
this.focusedId = null;
this.insertMode = false;
this.view = null;
this.viewOptions = null;
this.keyBuffer = new KeyBuffer();
this.clientsMap = {};
this.lastLocationReportByClientId = {};
this.followedClientId = null;
this.outputPanelWindow = null;
this.handleExternalWindowMessage =
this.handleExternalWindowMessage.bind(this);
setFavicon(this.faviconForEvaluationStatus(this.props.globalStatus));
this.updateSectionListHighlight();
// DOM events
this._handleDocumentKeyDown = this.handleDocumentKeyDown.bind(this);
this._handleDocumentMouseDown = this.handleDocumentMouseDown.bind(this);
this._handleDocumentFocus = this.handleDocumentFocus.bind(this);
this._handleDocumentClick = this.handleDocumentClick.bind(this);
this.el.addEventListener("output_panel:activate", (event) => {
if (this.el.getAttribute("data-js-view") != "output-panel-popped-out") {
this.el.setAttribute("data-js-view", "output-panel");
}
});
document.addEventListener("keydown", this._handleDocumentKeyDown, true);
document.addEventListener("mousedown", this._handleDocumentMouseDown);
// Note: the focus event doesn't bubble, so we register for the capture phase
document.addEventListener("focus", this._handleDocumentFocus, true);
document.addEventListener("click", this._handleDocumentClick);
this.getElement("sections-list").addEventListener("click", (event) => {
this.handleSectionsListClick(event);
this.handleCellIndicatorsClick(event);
});
this.getElement("clients-list").addEventListener("click", (event) =>
this.handleClientsListClick(event)
);
this.getElement("sections-list-toggle").addEventListener("click", (event) =>
this.toggleSectionsList()
);
this.getElement("clients-list-toggle").addEventListener("click", (event) =>
this.toggleClientsList()
);
this.getElement("secrets-list-toggle").addEventListener("click", (event) =>
this.toggleSecretsList()
);
this.getElement("runtime-info-toggle").addEventListener("click", (event) =>
this.toggleRuntimeInfo()
);
this.getElement("app-info-toggle").addEventListener("click", (event) =>
this.toggleAppInfo()
);
this.getElement("files-list-toggle").addEventListener("click", (event) =>
this.toggleFilesList()
);
this.getElement("notebook").addEventListener("scroll", (event) =>
this.updateSectionListHighlight()
);
this.getElement("notebook-indicators").addEventListener("click", (event) =>
this.handleCellIndicatorsClick(event)
);
this.getElement("views").addEventListener("click", (event) =>
this.handleActivateViewClick(event)
);
this.getElement("view-deactivate-button").addEventListener(
"click",
(event) => this.handleDeactivateViewClick()
);
this.getElement("output-panel-close-button").addEventListener(
"click",
(event) => this.handleOutputPanelCloseClick()
);
this.getElement("output-panel-popout-button").addEventListener(
"click",
(event) => this.handleOutputPanelPopoutClick()
);
this.getElement("view-output-panel-popin-button").addEventListener(
"click",
(event) => this.handleOutputPanelPopinClick()
);
this.getElement("section-toggle-collapse-all-button").addEventListener(
"click",
(event) => this.toggleCollapseAllSections()
);
this.initializeDragAndDrop();
window.addEventListener(
"phx:page-loading-stop",
() => {
this.initializeFocus();
},
{ once: true }
);
// Server events
this.handleEvent("session_init", ({ clients }) => {
clients.forEach((client) => {
this.clientsMap[client.id] = client;
});
});
this.handleEvent("cell_inserted", ({ cell_id: cellId }) => {
this.handleCellInserted(cellId);
});
this.handleEvent(
"cell_deleted",
({ cell_id: cellId, sibling_cell_id: siblingCellId }) => {
this.handleCellDeleted(cellId, siblingCellId);
}
);
this.handleEvent("cell_restored", ({ cell_id: cellId }) => {
this.handleCellRestored(cellId);
});
this.handleEvent("cell_moved", ({ cell_id }) => {
this.handleCellMoved(cell_id);
});
this.handleEvent("section_inserted", ({ section_id }) => {
this.handleSectionInserted(section_id);
});
this.handleEvent("section_deleted", ({ section_id }) => {
this.handleSectionDeleted(section_id);
});
this.handleEvent("section_moved", ({ section_id }) => {
this.handleSectionMoved(section_id);
});
this.handleEvent("cell_upload", ({ cell_id, url }) => {
this.handleCellUpload(cell_id, url);
});
this.handleEvent("client_joined", ({ client }) => {
this.handleClientJoined(client);
});
this.handleEvent("client_left", ({ client_id }) => {
this.handleClientLeft(client_id);
});
this.handleEvent("clients_updated", ({ clients }) => {
this.handleClientsUpdated(clients);
});
this.handleEvent(
"secret_selected",
({ select_secret_ref, secret_name }) => {
this.handleSecretSelected(select_secret_ref, secret_name);
}
);
this.handleEvent(
"location_report",
({ client_id, focusable_id, selection }) => {
const report = {
focusableId: focusable_id,
selection: this.decodeSelection(selection),
};
this.handleLocationReport(client_id, report);
}
);
this.unsubscribeFromSessionEvents = globalPubSub.subscribe(
"session",
(event) => {
this.handleSessionEvent(event);
}
);
},
updated() {
const prevProps = this.props;
this.props = this.getProps();
if (this.props.globalStatus !== prevProps.globalStatus) {
setFavicon(this.faviconForEvaluationStatus(this.props.globalStatus));
}
},
disconnected() {
// Reinitialize on reconnection
this.el.removeAttribute("id");
// If we reconnect, a new hook is mounted and it becomes responsible
// for leaving the channel when destroyed
this.keepChannel = true;
},
destroyed() {
this.unsubscribeFromSessionEvents();
document.removeEventListener("keydown", this._handleDocumentKeyDown, true);
document.removeEventListener("mousedown", this._handleDocumentMouseDown);
document.removeEventListener("focus", this._handleDocumentFocus, true);
document.removeEventListener("click", this._handleDocumentClick);
setFavicon("favicon");
if (!this.keepChannel) {
leaveChannel();
}
},
getProps() {
return {
autofocusCellId: getAttributeOrDefault(
this.el,
"data-autofocus-cell-id",
null
),
globalStatus: getAttributeOrDefault(this.el, "data-global-status", null),
};
},
faviconForEvaluationStatus(evaluationStatus) {
if (evaluationStatus === "evaluating") return "favicon-evaluating";
if (evaluationStatus === "stale") return "favicon-stale";
if (evaluationStatus === "errored") return "favicon-errored";
return "favicon";
},
// DOM event handlers
/**
* Handles session keybindings.
*
* Make sure to keep the shortcuts help modal up to date.
*/
handleDocumentKeyDown(event) {
if (event.repeat) {
return;
}
const cmd = isMacOS() ? event.metaKey : event.ctrlKey;
const alt = event.altKey;
const shift = event.shiftKey;
const key = event.key;
const keyBuffer = this.keyBuffer;
// Universal shortcuts (ignore editable elements in cell output)
if (
!(
isEditableElement(event.target) &&
event.target.closest(`[data-el-outputs-container]`)
)
) {
if (cmd && shift && !alt && key === "Enter") {
cancelEvent(event);
this.queueFullCellsEvaluation(true);
return;
} else if (!cmd && shift && !alt && key === "Enter") {
cancelEvent(event);
if (isEvaluable(this.focusedCellType())) {
this.queueFocusedCellEvaluation();
}
this.moveFocus(1);
return;
} else if (cmd && !alt && key === "Enter") {
cancelEvent(event);
if (isEvaluable(this.focusedCellType())) {
this.queueFocusedCellEvaluation();
}
return;
} else if (cmd && key === "s") {
cancelEvent(event);
this.saveNotebook();
return;
} else if (cmd || alt) {
return;
}
}
if (this.insertMode) {
keyBuffer.reset();
if (key === "Escape") {
// Ignore Escape if it's supposed to close an editor widget
if (!this.escapesMonacoWidget(event)) {
this.escapeInsertMode();
}
}
// Ignore keystrokes on input fields
} else if (isEditableElement(event.target)) {
keyBuffer.reset();
// Use Escape for universal blur
if (key === "Escape") {
event.target.blur();
}
} else {
keyBuffer.push(event.key);
if (keyBuffer.tryMatch(["d", "d"])) {
this.deleteFocusedCell();
} else if (keyBuffer.tryMatch(["e", "a"])) {
this.queueFullCellsEvaluation(false);
} else if (keyBuffer.tryMatch(["e", "e"])) {
if (isEvaluable(this.focusedCellType())) {
this.queueFocusedCellEvaluation();
}
} else if (keyBuffer.tryMatch(["e", "s"])) {
this.queueFocusedSectionEvaluation();
} else if (keyBuffer.tryMatch(["s", "s"])) {
this.toggleSectionsList();
} else if (keyBuffer.tryMatch(["s", "e"])) {
this.toggleSecretsList();
} else if (keyBuffer.tryMatch(["s", "a"])) {
this.toggleAppInfo();
} else if (keyBuffer.tryMatch(["s", "u"])) {
this.toggleClientsList();
} else if (keyBuffer.tryMatch(["s", "f"])) {
this.toggleFilesList();
} else if (keyBuffer.tryMatch(["s", "r"])) {
this.toggleRuntimeInfo();
} else if (keyBuffer.tryMatch(["s", "b"])) {
this.showBin();
} else if (keyBuffer.tryMatch(["s", "p"])) {
this.showPackageSearch();
} else if (keyBuffer.tryMatch(["e", "x"])) {
this.cancelFocusedCellEvaluation();
} else if (keyBuffer.tryMatch(["0", "0"])) {
this.reconnectRuntime();
} else if (keyBuffer.tryMatch(["Escape", "Escape"])) {
this.setFocusedEl(null);
} else if (keyBuffer.tryMatch(["?"])) {
this.showShortcuts();
} else if (
keyBuffer.tryMatch(["i"]) ||
(event.target.matches(
`body, [data-el-cell-body], [data-el-heading], [data-focusable-id]`
) &&
this.focusedId &&
key === "Enter")
) {
cancelEvent(event);
if (this.isInsertModeAvailable()) {
this.enterInsertMode();
}
} else if (keyBuffer.tryMatch(["j"])) {
this.moveFocus(1);
} else if (keyBuffer.tryMatch(["k"])) {
this.moveFocus(-1);
} else if (keyBuffer.tryMatch(["J"])) {
this.moveFocusedCell(1);
} else if (keyBuffer.tryMatch(["K"])) {
this.moveFocusedCell(-1);
} else if (keyBuffer.tryMatch(["n"])) {
this.insertCellBelowFocused("code");
} else if (keyBuffer.tryMatch(["N"])) {
this.insertCellAboveFocused("code");
} else if (keyBuffer.tryMatch(["m"])) {
if (!this.view || this.viewOptions.showMarkdown) {
this.insertCellBelowFocused("markdown");
}
} else if (keyBuffer.tryMatch(["M"])) {
if (!this.view || this.viewOptions.showMarkdown) {
this.insertCellAboveFocused("markdown");
}
} else if (keyBuffer.tryMatch(["v", "z"])) {
this.toggleView("code-zen");
} else if (keyBuffer.tryMatch(["v", "p"])) {
this.toggleView("presentation");
} else if (keyBuffer.tryMatch(["v", "c"])) {
this.toggleView("custom");
} else if (keyBuffer.tryMatch(["c"])) {
if (!this.view || this.viewOptions.showSection) {
this.toggleCollapseSection();
}
} else if (keyBuffer.tryMatch(["C"])) {
if (!this.view || this.viewOptions.showSection) {
this.toggleCollapseAllSections();
}
}
}
},
escapesMonacoWidget(event) {
// Escape pressed in an editor input
if (event.target.closest(".monaco-inputbox")) {
return true;
}
const editor = event.target.closest(".monaco-editor.focused");
if (!editor) {
return false;
}
// Completion box open
if (editor.querySelector(".editor-widget.parameter-hints-widget.visible")) {
return true;
}
// Signature details open
if (editor.querySelector(".editor-widget.suggest-widget.visible")) {
return true;
}
// Multi-cursor selection enabled
if (editor.querySelectorAll(".cursor").length > 1) {
return true;
}
return false;
},
/**
* Focuses/blurs a cell when the user clicks somewhere.
*
* Note: we use mousedown event to more reliably focus editor
* (e.g. if the user starts selecting some text within the editor)
*/
handleDocumentMouseDown(event) {
if (
// If the click is outside the notebook element, keep the focus as is
!event.target.closest(`[data-el-notebook]`) ||
// If the click is inside the custom doctest editor widget, keep the focus as is
event.target.closest(`.doctest-details-widget`)
) {
if (this.insertMode) {
this.setInsertMode(false);
}
return;
}
// When clicking an insert button, keep focus and insert mode as is.
// This is relevant for markdown cells, since we show the markdown
// preview in insert mode and exiting insert mode on mousedown would
// result in layout shift, so mouseup would happen outside the target
// button and the click would be ignored
if (event.target.closest(`[data-el-insert-buttons] button`)) {
return;
}
// Find the focusable element, if one was clicked
const focusableEl = event.target.closest(`[data-focusable-id]`);
const focusableId = focusableEl ? focusableEl.dataset.focusableId : null;
const insertMode = this.editableElementClicked(event, focusableEl);
if (focusableId !== this.focusedId) {
this.setFocusedEl(focusableId, { scroll: false, focusElement: false });
}
// If a cell action is clicked, keep the insert mode as is
if (event.target.closest(`[data-el-actions]`)) {
return;
}
// Depending on whether the click targets editor or input disable/enable insert mode
if (this.insertMode !== insertMode) {
this.setInsertMode(insertMode);
}
},
editableElementClicked(event, focusableEl) {
if (focusableEl) {
const editableElement = event.target.closest(
`[data-el-editor-container], [data-el-heading]`
);
return editableElement && focusableEl.contains(editableElement);
}
return false;
},
/**
* Focuses a focusable element if the user "tab"s anywhere into it.
*/
handleDocumentFocus(event) {
const focusableEl =
event.target.closest && event.target.closest(`[data-focusable-id]`);
if (focusableEl) {
const focusableId = focusableEl.dataset.focusableId;
if (focusableId !== this.focusedId) {
this.setFocusedEl(focusableId, { scroll: false, focusElement: false });
}
}
},
/**
* Enters insert mode when markdown edit action is clicked.
*/
handleDocumentClick(event) {
if (event.target.closest(`[data-el-enable-insert-mode-button]`)) {
this.setInsertMode(true);
}
if (event.target.closest(`[data-btn-package-search]`) && this.insertMode) {
this.setInsertMode(false);
}
const evalButton = event.target.closest(
`[data-el-queue-cell-evaluation-button]`
);
if (evalButton) {
const cellId = evalButton.getAttribute("data-cell-id");
const disableDependenciesCache = evalButton.hasAttribute(
"data-disable-dependencies-cache"
);
this.queueCellEvaluation(cellId, disableDependenciesCache);
}
const hash = window.location.hash;
if (hash) {
const htmlId = hash.replace(/^#/, "");
const hashEl = document.getElementById(htmlId);
// Remove hash from the URL when the user clicks somewhere else on the page
if (!hashEl.contains(event.target) && !event.target.closest(`a`)) {
history.pushState(
null,
document.title,
window.location.pathname + window.location.search
);
}
}
},
/**
* Handles section link clicks in the section list.
*/
handleSectionsListClick(event) {
const sectionButton = event.target.closest(`[data-el-sections-list-item]`);
if (sectionButton) {
const sectionId = sectionButton.getAttribute("data-section-id");
const section = this.getSectionById(sectionId);
section.scrollIntoView({ behavior: "smooth", block: "start" });
}
},
/**
* Handles client link clicks in the clients list.
*/
handleClientsListClick(event) {
const clientListItem = event.target.closest(`[data-el-clients-list-item]`);
if (clientListItem) {
const clientId = clientListItem.getAttribute("data-client-id");
const clientLink = event.target.closest(`[data-el-client-link]`);
if (clientLink) {
this.handleClientLinkClick(clientId);
}
const clientFollowToggle = event.target.closest(
`[data-el-client-follow-toggle]`
);
if (clientFollowToggle) {
this.handleClientFollowToggleClick(clientId, clientListItem);
}
}
},
handleClientLinkClick(clientId) {
this.mirrorClientFocus(clientId);
},
handleClientFollowToggleClick(clientId, clientListItem) {
const followedClientListItem = this.el.querySelector(
`[data-el-clients-list-item][data-js-followed]`
);
if (followedClientListItem) {
followedClientListItem.removeAttribute("data-js-followed");
}
if (clientId === this.followedClientId) {
this.followedClientId = null;
} else {
clientListItem.setAttribute("data-js-followed", "");
this.followedClientId = clientId;
this.mirrorClientFocus(clientId);
}
},
mirrorClientFocus(clientId) {
const locationReport = this.lastLocationReportByClientId[clientId];
if (locationReport && locationReport.focusableId) {
this.setFocusedEl(locationReport.focusableId);
}
},
/**
* Handles button clicks within cell indicators section.
*/
handleCellIndicatorsClick(event) {
const button = event.target.closest(`[data-el-focus-cell-button]`);
if (button) {
const cellId = button.getAttribute("data-target");
this.setFocusedEl(cellId);
}
},
handleOutputPanelCloseClick() {
this.closeOutputPanelWindow();
this.el.removeAttribute("data-js-view");
},
handleOutputPanelPopoutClick() {
this.outputPanelWindow = window.open(
window.location.pathname + `/external-window?type=output-panel`,
"_blank",
"toolbar=no, location=no, directories=no, titlebar=no, toolbar=0, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=600, height=600"
);
window.addEventListener("message", this.handleExternalWindowMessage);
this.el.setAttribute("data-js-view", "output-panel-popped-out");
},
handleOutputPanelPopinClick() {
this.closeOutputPanelWindow();
this.el.setAttribute("data-js-view", "output-panel");
},
/**
* Focuses cell or any other element based on the current
* URL and hook attributes.
*/
initializeFocus() {
const hash = window.location.hash;
if (hash) {
const htmlId = hash.replace(/^#/, "");
const hashEl = document.getElementById(htmlId);
if (hashEl) {
const focusableEl = hashEl.closest("[data-focusable-id]");
if (focusableEl) {
this.setFocusedEl(focusableEl.dataset.focusableId);
} else {
// Explicitly scroll to the target element
// after the loading finishes
hashEl.scrollIntoView();
}
}
} else if (this.props.autofocusCellId) {
this.setFocusedEl(this.props.autofocusCellId, { scroll: false });
this.setInsertMode(true);
}
},
/**
* Handles the main notebook area being scrolled.
*/
updateSectionListHighlight() {
const currentListItem = this.el.querySelector(
`[data-el-sections-list-item][data-js-is-viewed]`
);
if (currentListItem) {
currentListItem.removeAttribute("data-js-is-viewed");
}
// Consider a section being viewed if it is within the top 35% of the screen
const viewedSection = this.getSections()
.reverse()
.find((section) => {
const { top } = section.getBoundingClientRect();
const scrollTop = document.documentElement.scrollTop;
return top <= scrollTop + window.innerHeight * 0.35;
});
if (viewedSection) {
const sectionId = viewedSection.getAttribute("data-section-id");
const listItem = this.el.querySelector(
`[data-el-sections-list-item][data-section-id="${sectionId}"]`
);
listItem.setAttribute("data-js-is-viewed", "");
}
},
/**
* Initializes drag and drop event handlers.
*/
initializeDragAndDrop() {
let isDragging = false;
let draggedEl = null;
let files = null;
const startDragging = (element = null) => {
if (!isDragging) {
isDragging = true;
draggedEl = element;
const type = element ? "internal" : "external";
this.el.setAttribute("data-js-dragging", type);
if (type === "external") {
this.toggleFilesList(true);
}
}
};
const stopDragging = () => {
if (isDragging) {
isDragging = false;
this.el.removeAttribute("data-js-dragging");
}
};
this.el.addEventListener("dragstart", (event) => {
startDragging(event.target);
});
this.el.addEventListener("dragenter", (event) => {
startDragging();
});
this.el.addEventListener("dragleave", (event) => {
if (!this.el.contains(event.relatedTarget)) {
stopDragging();
}
});
this.el.addEventListener("dragover", (event) => {
event.stopPropagation();
event.preventDefault();
});
this.el.addEventListener("drop", (event) => {
event.stopPropagation();
event.preventDefault();
const insertDropEl = event.target.closest(`[data-el-insert-drop-area]`);
const filesDropEl = event.target.closest(`[data-el-files-drop-area]`);
if (insertDropEl) {
const sectionId = insertDropEl.getAttribute("data-section-id") || null;
const cellId = insertDropEl.getAttribute("data-cell-id") || null;
if (event.dataTransfer.files.length > 0) {
files = event.dataTransfer.files;
this.pushEvent("handle_file_drop", {
section_id: sectionId,
cell_id: cellId,
});
} else if (draggedEl && draggedEl.matches("[data-el-file-entry]")) {
const fileEntryName = draggedEl.getAttribute("data-name");
this.pushEvent("insert_file", {
file_entry_name: fileEntryName,
section_id: sectionId,
cell_id: cellId,
});
}
} else if (filesDropEl) {
if (event.dataTransfer.files.length > 0) {
files = event.dataTransfer.files;
this.pushEvent("handle_file_drop", {});
}
}
stopDragging();
});
this.handleEvent("finish_file_drop", (event) => {
const inputEl = document.querySelector(
`#add-file-entry-modal input[type="file"]`
);
if (inputEl) {
inputEl.files = files;
inputEl.dispatchEvent(new Event("change", { bubbles: true }));
}
});
},
// User action handlers (mostly keybindings)
toggleSectionsList(force = null) {
this.toggleSidePanelContent("sections-list", force);
},
toggleClientsList(force = null) {
this.toggleSidePanelContent("clients-list", force);
},
toggleSecretsList(force = null) {
this.toggleSidePanelContent("secrets-list", force);
},
toggleAppInfo(force = null) {
this.toggleSidePanelContent("app-info", force);
},
toggleFilesList(force = null) {
this.toggleSidePanelContent("files-list", force);
},
toggleRuntimeInfo(force = null) {
this.toggleSidePanelContent("runtime-info", force);
},
toggleSidePanelContent(name, force = null) {
const shouldOpen =
force === null
? this.el.getAttribute("data-js-side-panel-content") !== name
: force;
if (shouldOpen) {
this.el.setAttribute("data-js-side-panel-content", name);
} else {
this.el.removeAttribute("data-js-side-panel-content");
}
},
showBin() {
const actionEl = this.el.querySelector(`[data-btn-show-bin]`);
actionEl && actionEl.click();
},
showPackageSearch() {
this.setFocusedEl("setup");
const actionEl = this.el.querySelector(`[data-btn-package-search]`);
actionEl && actionEl.click();
},
saveNotebook() {
this.pushEvent("save", {});
},
deleteFocusedCell() {
if (this.focusedId && this.isCell(this.focusedId)) {
this.pushEvent("delete_cell", { cell_id: this.focusedId });
}
},
queueCellEvaluation(cellId, disableDependenciesCache) {
this.dispatchQueueEvaluation(() => {
this.pushEvent("queue_cell_evaluation", {
cell_id: cellId,
disable_dependencies_cache: disableDependenciesCache,
});
});
},
queueFocusedCellEvaluation() {
if (this.focusedId && this.isCell(this.focusedId)) {
this.dispatchQueueEvaluation(() => {
this.pushEvent("queue_cell_evaluation", { cell_id: this.focusedId });
});
}
},
queueFullCellsEvaluation(includeFocused) {
const forcedCellIds =
includeFocused && this.focusedId && this.isCell(this.focusedId)
? [this.focusedId]
: [];
this.dispatchQueueEvaluation(() => {
this.pushEvent("queue_full_evaluation", {
forced_cell_ids: forcedCellIds,
});
});
},
queueFocusedSectionEvaluation() {
if (this.focusedId) {
const sectionId = this.getSectionIdByFocusableId(this.focusedId);
if (sectionId) {
this.dispatchQueueEvaluation(() => {
this.pushEvent("queue_section_evaluation", {
section_id: sectionId,
});
});
}
}
},
dispatchQueueEvaluation(dispatch) {
if (isEvaluable(this.focusedCellType())) {
// If an evaluable cell is focused, we forward the evaluation
// request to that cell, so it can synchronize itself before
// sending the request to the server
globalPubSub.broadcast(`cells:${this.focusedId}`, {
type: "dispatch_queue_evaluation",
dispatch,
});
} else {
dispatch();
}
},
cancelFocusedCellEvaluation() {
if (this.focusedId && this.isCell(this.focusedId)) {
this.pushEvent("cancel_cell_evaluation", {
cell_id: this.focusedId,
});
}
},
reconnectRuntime() {
this.pushEvent("reconnect_runtime", {});
},