-
-
Notifications
You must be signed in to change notification settings - Fork 292
/
Copy pathEditor.js
1778 lines (1645 loc) Β· 83.4 KB
/
Editor.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
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 { html, Component } from "../imports/Preact.js"
import * as preact from "../imports/Preact.js"
import immer, { applyPatches, produceWithPatches } from "../imports/immer.js"
import _ from "../imports/lodash.js"
import { empty_notebook_state, set_disable_ui_css } from "../editor.js"
import { create_pluto_connection, ws_address_from_base } from "../common/PlutoConnection.js"
import { init_feedback } from "../common/Feedback.js"
import { serialize_cells, deserialize_cells, detect_deserializer } from "../common/Serialization.js"
import { FilePicker } from "./FilePicker.js"
import { Preamble } from "./Preamble.js"
import { Notebook } from "./Notebook.js"
import { BottomRightPanel } from "./BottomRightPanel.js"
import { DropRuler } from "./DropRuler.js"
import { SelectionArea } from "./SelectionArea.js"
import { RecentlyDisabledInfo, UndoDelete } from "./UndoDelete.js"
import { SlideControls } from "./SlideControls.js"
import { Scroller } from "./Scroller.js"
import { ExportBanner } from "./ExportBanner.js"
import { Popup } from "./Popup.js"
import { slice_utf8, length_utf8 } from "../common/UnicodeTools.js"
import {
has_ctrl_or_cmd_pressed,
ctrl_or_cmd_name,
is_mac_keyboard,
in_textarea_or_input,
and,
control_name,
alt_or_options_name,
} from "../common/KeyboardShortcuts.js"
import { PlutoActionsContext, PlutoBondsContext, PlutoJSInitializingContext, SetWithEmptyCallback } from "../common/PlutoContext.js"
import { BackendLaunchPhase, count_stat } from "../common/Binder.js"
import { setup_mathjax } from "../common/SetupMathJax.js"
import { slider_server_actions, nothing_actions } from "../common/SliderServerClient.js"
import { ProgressBar } from "./ProgressBar.js"
import { NonCellOutput } from "./NonCellOutput.js"
import { IsolatedCell } from "./Cell.js"
import { RecordingPlaybackUI, RecordingUI } from "./RecordingUI.js"
import { HijackExternalLinksToOpenInNewTab } from "./HackySideStuff/HijackExternalLinksToOpenInNewTab.js"
import { FrontMatterInput } from "./FrontmatterInput.js"
import { EditorLaunchBackendButton } from "./Editor/LaunchBackendButton.js"
import { get_environment } from "../common/Environment.js"
import { ProcessStatus } from "../common/ProcessStatus.js"
import { SafePreviewUI } from "./SafePreviewUI.js"
import { open_pluto_popup } from "../common/open_pluto_popup.js"
// This is imported asynchronously - uncomment for development
// import environment from "../common/Environment.js"
export const default_path = ""
const DEBUG_DIFFING = false
// Be sure to keep this in sync with DEFAULT_CELL_METADATA in Cell.jl
/** @type {CellMetaData} */
const DEFAULT_CELL_METADATA = {
disabled: false,
show_logs: true,
skip_as_script: false,
}
// from our friends at https://stackoverflow.com/a/2117523
// i checked it and it generates Julia-legal UUIDs and that's all we need -SNOF
const uuidv4 = () =>
//@ts-ignore
"10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16))
/**
* @typedef {import('../imports/immer').Patch} Patch
* */
const Main = ({ children }) => {
return html`<main>${children}</main>`
}
/**
* Map of status => Bool. In order of decreasing priority.
*/
const statusmap = (/** @type {EditorState} */ state, /** @type {LaunchParameters} */ launch_params) => ({
disconnected: !(state.connected || state.initializing || state.static_preview),
loading:
(state.backend_launch_phase != null &&
BackendLaunchPhase.wait_for_user < state.backend_launch_phase &&
state.backend_launch_phase < BackendLaunchPhase.ready) ||
state.initializing ||
state.moving_file,
process_waiting_for_permission: state.notebook.process_status === ProcessStatus.waiting_for_permission && !state.initializing,
process_restarting: state.notebook.process_status === ProcessStatus.waiting_to_restart,
process_dead: state.notebook.process_status === ProcessStatus.no_process || state.notebook.process_status === ProcessStatus.waiting_to_restart,
nbpkg_restart_required: state.notebook.nbpkg?.restart_required_msg != null,
nbpkg_restart_recommended: state.notebook.nbpkg?.restart_recommended_msg != null,
nbpkg_disabled: state.notebook.nbpkg?.enabled === false || state.notebook.nbpkg?.waiting_for_permission_but_probably_disabled === true,
static_preview: state.static_preview,
bonds_disabled: !(state.connected || state.initializing || launch_params.slider_server_url != null),
offer_binder: state.backend_launch_phase === BackendLaunchPhase.wait_for_user && launch_params.binder_url != null,
offer_local: state.backend_launch_phase === BackendLaunchPhase.wait_for_user && launch_params.pluto_server_url != null,
binder: launch_params.binder_url != null && state.backend_launch_phase != null,
code_differs: state.notebook.cell_order.some(
(cell_id) => state.cell_inputs_local[cell_id] != null && state.notebook.cell_inputs[cell_id].code !== state.cell_inputs_local[cell_id].code
),
recording_waiting_to_start: state.recording_waiting_to_start,
is_recording: state.is_recording,
isolated_cell_view: launch_params.isolated_cell_ids != null && launch_params.isolated_cell_ids.length > 0,
sanitize_html: state.notebook.process_status === ProcessStatus.waiting_for_permission,
})
const first_true_key = (obj) => {
for (let [k, v] of Object.entries(obj)) {
if (v) {
return k
}
}
}
/**
* @typedef CellMetaData
* @type {{
* disabled: boolean,
* show_logs: boolean,
* skip_as_script: boolean
* }}
*
* @typedef CellInputData
* @type {{
* cell_id: string,
* code: string,
* code_folded: boolean,
* metadata: CellMetaData,
* }}
*/
/**
* @typedef LogEntryData
* @type {{
* level: number,
* msg: string,
* file: string,
* line: number,
* kwargs: Object,
* }}
*/
/**
* @typedef StatusEntryData
* @type {{
* name: string,
* success?: boolean,
* started_at: number?,
* finished_at: number?,
* timing?: "remote" | "local",
* subtasks: Record<string,StatusEntryData>,
* }}
*/
/**
* @typedef CellResultData
* @type {{
* cell_id: string,
* queued: boolean,
* running: boolean,
* errored: boolean,
* runtime: number?,
* downstream_cells_map: { string: [string]},
* upstream_cells_map: { string: [string]},
* precedence_heuristic: number?,
* depends_on_disabled_cells: boolean,
* depends_on_skipped_cells: boolean,
* output: {
* body: string,
* persist_js_state: boolean,
* last_run_timestamp: number,
* mime: string,
* rootassignee: string?,
* has_pluto_hook_features: boolean,
* },
* logs: Array<LogEntryData>,
* published_object_keys: [string],
* }}
*/
/**
* @typedef CellDependencyData
* @property {string} cell_id
* @property {Map<string, Array<string>>} downstream_cells_map A map where the keys are the variables *defined* by this cell, and a value is the list of cell IDs that reference a variable.
* @property {Map<string, Array<string>>} upstream_cells_map A map where the keys are the variables *referenced* by this cell, and a value is the list of cell IDs that define a variable.
* @property {number} precedence_heuristic
*/
/**
* @typedef NotebookPkgData
* @type {{
* enabled: boolean,
* waiting_for_permission: boolean?,
* waiting_for_permission_but_probably_disabled: boolean?,
* restart_recommended_msg: string?,
* restart_required_msg: string?,
* installed_versions: { [pkg_name: string]: string },
* terminal_outputs: { [pkg_name: string]: string },
* install_time_ns: number?,
* busy_packages: string[],
* instantiated: boolean,
* }}
*/
/**
* @typedef LaunchParameters
* @type {{
* notebook_id: string?,
* statefile: string?,
* statefile_integrity: string?,
* notebookfile: string?,
* notebookfile_integrity: string?,
* disable_ui: boolean,
* preamble_html: string?,
* isolated_cell_ids: string[]?,
* binder_url: string?,
* pluto_server_url: string?,
* slider_server_url: string?,
* recording_url: string?,
* recording_url_integrity: string?,
* recording_audio_url: string?,
* }}
*/
/**
* @typedef BondValueContainer
* @type {{ value: any }}
*/
/**
* @typedef BondValuesDict
* @type {{ [name: string]: BondValueContainer }}
*/
/**
* @typedef NotebookData
* @type {{
* pluto_version?: string,
* notebook_id: string,
* path: string,
* shortpath: string,
* in_temp_dir: boolean,
* process_status: string,
* last_save_time: number,
* last_hot_reload_time: number,
* cell_inputs: { [uuid: string]: CellInputData },
* cell_results: { [uuid: string]: CellResultData },
* cell_dependencies: { [uuid: string]: CellDependencyData },
* cell_order: Array<string>,
* cell_execution_order: Array<string>,
* published_objects: { [objectid: string]: any},
* bonds: BondValuesDict,
* nbpkg: NotebookPkgData?,
* metadata: object,
* status_tree: StatusEntryData?,
* }}
*/
const url_logo_big = document.head.querySelector("link[rel='pluto-logo-big']")?.getAttribute("href") ?? ""
export const url_logo_small = document.head.querySelector("link[rel='pluto-logo-small']")?.getAttribute("href") ?? ""
/**
* @typedef EditorProps
* @type {{
* launch_params: LaunchParameters,
* initial_notebook_state: NotebookData,
* preamble_element: preact.ReactElement?,
* }}
*/
/**
* @typedef EditorState
* @type {{
* notebook: NotebookData,
* cell_inputs_local: { [uuid: string]: { code: String } },
* desired_doc_query: ?String,
* recently_deleted: ?Array<{ index: number, cell: CellInputData }>,
* last_update_time: number,
* disable_ui: boolean,
* static_preview: boolean,
* backend_launch_phase: ?number,
* backend_launch_logs: ?string,
* binder_session_url: ?string,
* binder_session_token: ?string,
* refresh_target: ?string,
* connected: boolean,
* initializing: boolean,
* moving_file: boolean,
* scroller: {
* up: boolean,
* down: boolean,
* },
* export_menu_open: boolean,
* last_created_cell: ?string,
* selected_cells: Array<string>,
* extended_components: any,
* is_recording: boolean,
* recording_waiting_to_start: boolean,
* }}
*/
/**
* @augments Component<EditorProps,EditorState>
*/
export class Editor extends Component {
constructor(/** @type {EditorProps} */ props) {
super(props)
const { launch_params, initial_notebook_state } = this.props
this.state = {
notebook: /** @type {NotebookData} */ initial_notebook_state,
cell_inputs_local: /** @type {{ [id: string]: CellInputData }} */ ({}),
desired_doc_query: null,
recently_deleted: /** @type {Array<{ index: number, cell: CellInputData }>} */ ([]),
recently_auto_disabled_cells: /** @type {Map<string,[string,string]>} */ ({}),
last_update_time: 0,
disable_ui: launch_params.disable_ui,
static_preview: launch_params.statefile != null,
backend_launch_phase:
launch_params.notebookfile != null && (launch_params.binder_url != null || launch_params.pluto_server_url != null)
? BackendLaunchPhase.wait_for_user
: null,
backend_launch_logs: null,
binder_session_url: null,
binder_session_token: null,
refresh_target: null,
connected: false,
initializing: true,
moving_file: false,
scroller: {
up: false,
down: false,
},
export_menu_open: false,
last_created_cell: null,
selected_cells: /** @type {string[]} */ ([]),
extended_components: {
CustomHeader: null,
},
is_recording: false,
recording_waiting_to_start: false,
slider_server: {
connecting: false,
interactive: false,
},
}
this.setStatePromise = (fn) => new Promise((r) => this.setState(fn, r))
// these are things that can be done to the local notebook
this.real_actions = {
get_notebook: () => this?.state?.notebook || {},
send: (message_type, ...args) => this.client.send(message_type, ...args),
get_published_object: (objectid) => this.state.notebook.published_objects[objectid],
//@ts-ignore
update_notebook: (...args) => this.update_notebook(...args),
set_doc_query: (query) => this.setState({ desired_doc_query: query }),
set_local_cell: (cell_id, new_val) => {
return this.setStatePromise(
immer((/** @type {EditorState} */ state) => {
state.cell_inputs_local[cell_id] = {
code: new_val,
}
state.selected_cells = []
})
)
},
focus_on_neighbor: (cell_id, delta, line = delta === -1 ? Infinity : -1, ch = 0) => {
const i = this.state.notebook.cell_order.indexOf(cell_id)
const new_i = i + delta
if (new_i >= 0 && new_i < this.state.notebook.cell_order.length) {
window.dispatchEvent(
new CustomEvent("cell_focus", {
detail: {
cell_id: this.state.notebook.cell_order[new_i],
line: line,
ch: ch,
},
})
)
}
},
add_deserialized_cells: async (data, index_or_id, deserializer = deserialize_cells) => {
let new_codes = deserializer(data)
/** @type {Array<CellInputData>} Create copies of the cells with fresh ids */
let new_cells = new_codes.map((code) => ({
cell_id: uuidv4(),
code: code,
code_folded: false,
metadata: {
...DEFAULT_CELL_METADATA,
},
}))
let index
if (typeof index_or_id === "number") {
index = index_or_id
} else {
/* if the input is not an integer, try interpreting it as a cell id */
index = this.state.notebook.cell_order.indexOf(index_or_id)
if (index !== -1) {
/* Make sure that the cells are pasted after the current cell */
index += 1
}
}
if (index === -1) {
index = this.state.notebook.cell_order.length
}
/** Update local_code. Local code doesn't force CM to update it's state
* (the usual flow is keyboard event -> cm -> local_code and not the opposite )
* See ** 1 **
*/
this.setState(
immer((/** @type {EditorState} */ state) => {
// Deselect everything first, to clean things up
state.selected_cells = []
for (let cell of new_cells) {
state.cell_inputs_local[cell.cell_id] = cell
}
state.last_created_cell = new_cells[0]?.cell_id
})
)
/**
* Create an empty cell in the julia-side.
* Code will differ, until the user clicks 'run' on the new code
*/
await update_notebook((notebook) => {
for (const cell of new_cells) {
notebook.cell_inputs[cell.cell_id] = {
...cell,
// Fill the cell with empty code remotely, so it doesn't run unsafe code
code: "",
metadata: {
...DEFAULT_CELL_METADATA,
},
}
}
notebook.cell_order = [
...notebook.cell_order.slice(0, index),
...new_cells.map((x) => x.cell_id),
...notebook.cell_order.slice(index, Infinity),
]
})
},
wrap_remote_cell: async (cell_id, block_start = "begin", block_end = "end") => {
const cell = this.state.notebook.cell_inputs[cell_id]
const new_code = `${block_start}\n\t${cell.code.replace(/\n/g, "\n\t")}\n${block_end}`
await this.setStatePromise(
immer((/** @type {EditorState} */ state) => {
state.cell_inputs_local[cell_id] = {
code: new_code,
}
})
)
await this.actions.set_and_run_multiple([cell_id])
},
split_remote_cell: async (cell_id, boundaries, submit = false) => {
const cell = this.state.notebook.cell_inputs[cell_id]
const old_code = cell.code
const padded_boundaries = [0, ...boundaries]
/** @type {Array<String>} */
const parts = boundaries.map((b, i) => slice_utf8(old_code, padded_boundaries[i], b).trim()).filter((x) => x !== "")
/** @type {Array<CellInputData>} */
const cells_to_add = parts.map((code) => {
return {
cell_id: uuidv4(),
code: code,
code_folded: false,
metadata: {
...DEFAULT_CELL_METADATA,
},
}
})
this.setState(
immer((/** @type {EditorState} */ state) => {
for (let cell of cells_to_add) {
state.cell_inputs_local[cell.cell_id] = cell
}
})
)
await update_notebook((notebook) => {
// delete the old cell
delete notebook.cell_inputs[cell_id]
// add the new ones
for (let cell of cells_to_add) {
notebook.cell_inputs[cell.cell_id] = cell
}
notebook.cell_order = notebook.cell_order.flatMap((c) => {
if (cell_id === c) {
return cells_to_add.map((x) => x.cell_id)
} else {
return [c]
}
})
})
if (submit) {
await this.actions.set_and_run_multiple(cells_to_add.map((x) => x.cell_id))
}
},
interrupt_remote: (cell_id) => {
// TODO Make this cooler
// set_notebook_state((prevstate) => {
// return {
// cells: prevstate.cells.map((c) => {
// return { ...c, errored: c.errored || c.running || c.queued }
// }),
// }
// })
this.client.send("interrupt_all", {}, { notebook_id: this.state.notebook.notebook_id }, false)
},
move_remote_cells: (cell_ids, new_index) => {
return update_notebook((notebook) => {
new_index = Math.max(0, new_index)
let before = notebook.cell_order.slice(0, new_index).filter((x) => !cell_ids.includes(x))
let after = notebook.cell_order.slice(new_index, Infinity).filter((x) => !cell_ids.includes(x))
notebook.cell_order = [...before, ...cell_ids, ...after]
})
},
add_remote_cell_at: async (index, code = "") => {
let id = uuidv4()
this.setState({ last_created_cell: id })
await update_notebook((notebook) => {
notebook.cell_inputs[id] = {
cell_id: id,
code,
code_folded: false,
metadata: { ...DEFAULT_CELL_METADATA },
}
notebook.cell_order = [...notebook.cell_order.slice(0, index), id, ...notebook.cell_order.slice(index, Infinity)]
})
await this.client.send("run_multiple_cells", { cells: [id] }, { notebook_id: this.state.notebook.notebook_id })
return id
},
add_remote_cell: async (cell_id, before_or_after, code) => {
const index = this.state.notebook.cell_order.indexOf(cell_id)
const delta = before_or_after == "before" ? 0 : 1
return await this.actions.add_remote_cell_at(index + delta, code)
},
confirm_delete_multiple: async (verb, cell_ids) => {
if (cell_ids.length <= 1 || confirm(`${verb} ${cell_ids.length} cells?`)) {
if (cell_ids.some((cell_id) => this.state.notebook.cell_results[cell_id].running || this.state.notebook.cell_results[cell_id].queued)) {
if (confirm("This cell is still running - would you like to interrupt the notebook?")) {
this.actions.interrupt_remote(cell_ids[0])
}
} else {
this.setState({
recently_deleted: cell_ids.map((cell_id) => {
return {
index: this.state.notebook.cell_order.indexOf(cell_id),
cell: this.state.notebook.cell_inputs[cell_id],
}
}),
selected_cells: [],
})
await update_notebook((notebook) => {
for (let cell_id of cell_ids) {
delete notebook.cell_inputs[cell_id]
}
notebook.cell_order = notebook.cell_order.filter((cell_id) => !cell_ids.includes(cell_id))
})
await this.client.send("run_multiple_cells", { cells: [] }, { notebook_id: this.state.notebook.notebook_id })
}
}
},
fold_remote_cells: async (cell_ids, new_value) => {
await update_notebook((notebook) => {
for (let cell_id of cell_ids) {
notebook.cell_inputs[cell_id].code_folded = new_value ?? !notebook.cell_inputs[cell_id].code_folded
}
})
},
set_and_run_all_changed_remote_cells: () => {
const changed = this.state.notebook.cell_order.filter(
(cell_id) =>
this.state.cell_inputs_local[cell_id] != null &&
this.state.notebook.cell_inputs[cell_id].code !== this.state.cell_inputs_local[cell_id]?.code
)
this.actions.set_and_run_multiple(changed)
return changed.length > 0
},
set_and_run_multiple: async (cell_ids) => {
// TODO: this function is called with an empty list sometimes, where?
if (cell_ids.length > 0) {
window.dispatchEvent(
new CustomEvent("set_waiting_to_run_smart", {
detail: {
cell_ids,
},
})
)
await update_notebook((notebook) => {
for (let cell_id of cell_ids) {
if (this.state.cell_inputs_local[cell_id]) {
notebook.cell_inputs[cell_id].code = this.state.cell_inputs_local[cell_id].code
}
}
})
// This is a "dirty" trick, as this should actually be stored in some shared request_status => status state
// But for now... this is fine πΌ
await this.setStatePromise(
immer((/** @type {EditorState} */ state) => {
for (let cell_id of cell_ids) {
if (state.notebook.cell_results[cell_id] != null) {
state.notebook.cell_results[cell_id].queued = this.is_process_ready()
} else {
// nothing
}
}
})
)
const result = await this.client.send("run_multiple_cells", { cells: cell_ids }, { notebook_id: this.state.notebook.notebook_id })
const { disabled_cells } = result.message
if (Object.entries(disabled_cells).length > 0) {
await this.setStatePromise({
recently_auto_disabled_cells: disabled_cells,
})
}
}
},
/**
*
* @param {string} name name of bound variable
* @param {*} value value (not in wrapper object)
*/
set_bond: async (name, value) => {
await update_notebook((notebook) => {
// Wrap the bond value in an object so immer assumes it is changed
let new_bond = { value: value }
notebook.bonds[name] = new_bond
})
},
reshow_cell: (cell_id, objectid, dim) => {
this.client.send(
"reshow_cell",
{
objectid,
dim,
cell_id,
},
{ notebook_id: this.state.notebook.notebook_id },
false
)
},
request_js_link_response: (cell_id, link_id, input) => {
return this.client
.send(
"request_js_link_response",
{
cell_id,
link_id,
input,
},
{ notebook_id: this.state.notebook.notebook_id }
)
.then((r) => r.message)
},
/** This actions avoids pushing selected cells all the way down, which is too heavy to handle! */
get_selected_cells: (cell_id, /** @type {boolean} */ allow_other_selected_cells) =>
allow_other_selected_cells ? this.state.selected_cells : [cell_id],
get_avaible_versions: async ({ package_name, notebook_id }) => {
const { message } = await this.client.send("nbpkg_available_versions", { package_name: package_name }, { notebook_id: notebook_id })
return message.versions
},
}
this.actions = { ...this.real_actions }
const apply_notebook_patches = (patches, /** @type {NotebookData?} */ old_state = null, get_reverse_patches = false) =>
new Promise((resolve) => {
if (patches.length !== 0) {
const should_ignore_patch_error = (/** @type {string} */ failing_path) => failing_path.startsWith("status_tree")
let _copy_of_patches,
reverse_of_patches = []
this.setState(
immer((/** @type {EditorState} */ state) => {
let new_notebook
try {
// To test this, uncomment the lines below:
// if (Math.random() < 0.25) {
// throw new Error(`Error: [Immer] minified error nr: 15 '${patches?.[0]?.path?.join("/")}' .`)
// }
if (get_reverse_patches) {
;[new_notebook, _copy_of_patches, reverse_of_patches] = produceWithPatches(old_state ?? state.notebook, (state) => {
applyPatches(state, patches)
})
// TODO: why was `new_notebook` not updated?
// this is why the line below is also called when `get_reverse_patches === true`
}
new_notebook = applyPatches(old_state ?? state.notebook, patches)
} catch (exception) {
/** @type {String} Example: `"a.b[2].c"` */
const failing_path = String(exception).match(".*'(.*)'.*")?.[1].replace(/\//gi, ".") ?? exception
const path_value = _.get(this.state.notebook, failing_path, "Not Found")
console.log(String(exception).match(".*'(.*)'.*")?.[1].replace(/\//gi, ".") ?? exception, failing_path, typeof failing_path)
const ignore = should_ignore_patch_error(failing_path)
;(ignore ? console.log : console.error)(
`#######################**************************########################
PlutoError: StateOutOfSync: Failed to apply patches.
Please report this: https://github.com/fonsp/Pluto.jl/issues adding the info below:
failing path: ${failing_path}
notebook previous value: ${path_value}
patch: ${JSON.stringify(
patches?.find(({ path }) => path.join("") === failing_path),
null,
1
)}
all patches: ${JSON.stringify(patches, null, 1)}
#######################**************************########################`,
exception
)
let parts = failing_path.split(".")
for (let i = 0; i < parts.length; i++) {
let path = parts.slice(0, i).join(".")
console.log(path, _.get(this.state.notebook, path, "Not Found"))
}
if (ignore) {
console.info("Safe to ignore this patch failure...")
} else if (this.state.connected) {
console.error("Trying to recover: Refetching notebook...")
this.client.send(
"reset_shared_state",
{},
{
notebook_id: this.state.notebook.notebook_id,
},
false
)
} else if (this.state.static_preview && launch_params.slider_server_url != null) {
open_pluto_popup({
type: "warn",
body: html`Something went wrong while updating the notebook state. Please refresh the page to try again.`,
})
} else {
console.error("Trying to recover: reloading...")
window.parent.location.href = this.state.refresh_target ?? window.location.href
}
return
}
if (DEBUG_DIFFING) {
console.group("Update!")
for (let patch of patches) {
console.group(`Patch :${patch.op}`)
console.log(patch.path)
console.log(patch.value)
console.groupEnd()
}
console.groupEnd()
}
let cells_stuck_in_limbo = new_notebook.cell_order.filter((cell_id) => new_notebook.cell_inputs[cell_id] == null)
if (cells_stuck_in_limbo.length !== 0) {
console.warn(`cells_stuck_in_limbo:`, cells_stuck_in_limbo)
new_notebook.cell_order = new_notebook.cell_order.filter((cell_id) => new_notebook.cell_inputs[cell_id] != null)
}
this.on_patches_hook(patches)
state.notebook = new_notebook
}),
() => resolve(reverse_of_patches)
)
} else {
resolve([])
}
})
this.apply_notebook_patches = apply_notebook_patches
// these are update message that are _not_ a response to a `send(*, *, {create_promise: true})`
const on_update = (update, by_me) => {
if (this.state.notebook.notebook_id === update.notebook_id) {
const show_debugs = launch_params.binder_url != null
if (show_debugs) console.debug("on_update", update, by_me)
const message = update.message
switch (update.type) {
case "notebook_diff":
let apply_promise = Promise.resolve()
if (message?.response?.from_reset) {
console.log("Trying to reset state after failure")
apply_promise = apply_notebook_patches(
message.patches,
empty_notebook_state({ notebook_id: this.state.notebook.notebook_id })
).catch((e) => {
alert("Oopsie!! please refresh your browser and everything will be alright!")
throw e
})
} else if (message.patches.length !== 0) {
apply_promise = apply_notebook_patches(message.patches)
}
const set_waiting = () => {
let from_update = message?.response?.update_went_well != null
let is_just_acknowledgement = from_update && message.patches.length === 0
let is_relevant_for_bonds = message.patches.some(({ path }) => path.length === 0 || path[0] !== "status_tree")
// console.debug("Received patches!", is_just_acknowledgement, is_relevant_for_bonds, message.patches, message.response)
if (!is_just_acknowledgement && is_relevant_for_bonds) {
this.waiting_for_bond_to_trigger_execution = false
}
}
apply_promise.finally(set_waiting).then(() => {
this.maybe_send_queued_bond_changes()
})
break
default:
console.error("Received unknown update type!", update)
// alert("Something went wrong π\n Try clearing your browser cache and refreshing the page")
break
}
if (show_debugs) console.debug("on_update done")
} else {
// Update for a different notebook, TODO maybe log this as it shouldn't happen
}
}
const on_establish_connection = async (client) => {
// nasty
Object.assign(this.client, client)
try {
const environment = await get_environment(client)
const { custom_editor_header_component, custom_non_cell_output } = environment({ client, editor: this, imports: { preact } })
this.setState({
extended_components: {
...this.state.extended_components,
CustomHeader: custom_editor_header_component,
NonCellOutputComponents: custom_non_cell_output,
},
})
} catch (e) {}
// @ts-ignore
window.version_info = this.client.version_info // for debugging
// @ts-ignore
window.kill_socket = this.client.kill // for debugging
if (!client.notebook_exists) {
console.error("Notebook does not exist. Not connecting.")
return
}
console.debug("Sending update_notebook request...")
await this.client.send("update_notebook", { updates: [] }, { notebook_id: this.state.notebook.notebook_id }, false)
console.debug("Received update_notebook request")
this.setState({
initializing: false,
static_preview: false,
backend_launch_phase: this.state.backend_launch_phase == null ? null : BackendLaunchPhase.ready,
})
this.client.send("complete", { query: "sq" }, { notebook_id: this.state.notebook.notebook_id })
this.client.send("complete", { query: "\\sq" }, { notebook_id: this.state.notebook.notebook_id })
setTimeout(init_feedback, 2 * 1000) // 2 seconds - load feedback a little later for snappier UI
}
const on_connection_status = (val, hopeless) => {
this.setState({ connected: val })
if (hopeless) {
// https://github.com/fonsp/Pluto.jl/issues/55
// https://github.com/fonsp/Pluto.jl/issues/2398
open_pluto_popup({
type: "warn",
body: html`<p>A new server was started - this notebook session is no longer running.</p>
<p>Would you like to go back to the main menu?</p>
<br />
<a href="./">Go back</a>
<br />
<a
href="#"
onClick=${(e) => {
e.preventDefault()
window.dispatchEvent(new CustomEvent("close pluto popup"))
}}
>Stay here</a
>`,
should_focus: false,
})
}
}
const on_reconnect = async () => {
console.warn("Reconnected! Checking states")
await this.client.send(
"reset_shared_state",
{},
{
notebook_id: this.state.notebook.notebook_id,
},
false
)
return true
}
this.export_url = (/** @type {string} */ u) =>
this.state.binder_session_url == null
? `./${u}?id=${this.state.notebook.notebook_id}`
: `${this.state.binder_session_url}${u}?id=${this.state.notebook.notebook_id}&token=${this.state.binder_session_token}`
/** @type {import('../common/PlutoConnection').PlutoConnection} */
this.client = /** @type {import('../common/PlutoConnection').PlutoConnection} */ ({})
this.connect = (/** @type {string | undefined} */ ws_address = undefined) =>
create_pluto_connection({
ws_address: ws_address,
on_unrequested_update: on_update,
on_connection_status: on_connection_status,
on_reconnect: on_reconnect,
connect_metadata: { notebook_id: this.state.notebook.notebook_id },
}).then(on_establish_connection)
this.on_disable_ui = () => {
set_disable_ui_css(this.state.disable_ui)
// Pluto has three modes of operation:
// 1. (normal) Connected to a Pluto notebook.
// 2. Static HTML with PlutoSliderServer. All edits are ignored, but bond changes are processes by the PlutoSliderServer.
// 3. Static HTML without PlutoSliderServer. All interactions are ignored.
//
// To easily support all three with minimal changes to the source code, we sneakily swap out the `this.actions` object (`pluto_actions` in other source files) with a different one:
Object.assign(
this.actions,
// if we have no pluto server...
this.state.disable_ui || (launch_params.slider_server_url != null && !this.state.connected)
? // then use a modified set of actions
launch_params.slider_server_url != null
? slider_server_actions({
setStatePromise: this.setStatePromise,
actions: this.actions,
launch_params: launch_params,
apply_notebook_patches,
get_original_state: () => this.props.initial_notebook_state,
get_current_state: () => this.state.notebook,
})
: nothing_actions({
actions: this.actions,
})
: // otherwise, use the real actions
this.real_actions
)
}
this.on_disable_ui()
setInterval(() => {
if (!this.state.static_preview && document.visibilityState === "visible") {
// view stats on https://stats.plutojl.org/
//@ts-ignore
count_stat(`editing/${window?.version_info?.pluto ?? this.state.notebook.pluto_version ?? "unknown"}${window.plutoDesktop ? "-desktop" : ""}`)
}
}, 1000 * 15 * 60)
setInterval(() => {
if (!this.state.static_preview && document.visibilityState === "visible") {
update_stored_recent_notebooks(this.state.notebook.path)
}
}, 1000 * 5)
// Not completely happy with this yet, but it will do for now - DRAL
/** Patches that are being delayed until all cells have finished running. */
this.bond_changes_to_apply_when_done = []
this.maybe_send_queued_bond_changes = () => {
if (this.notebook_is_idle() && this.bond_changes_to_apply_when_done.length !== 0) {
// console.log("Applying queued bond changes!", this.bond_changes_to_apply_when_done)
let bonds_patches = this.bond_changes_to_apply_when_done
this.bond_changes_to_apply_when_done = []
this.update_notebook((notebook) => {
applyPatches(notebook, bonds_patches)
})
}
}
/** This tracks whether we just set a bond value which will trigger a cell to run, but we are still waiting for the server to process the bond value (and run the cell). During this time, we won't send new bond values. See https://github.com/fonsp/Pluto.jl/issues/1891 for more info. */
this.waiting_for_bond_to_trigger_execution = false
/** Number of local updates that have not yet been applied to the server's state. */
this.pending_local_updates = 0
/**
* User scripts that are currently running (possibly async).
* @type {SetWithEmptyCallback<HTMLElement>}