-
-
Notifications
You must be signed in to change notification settings - Fork 553
/
notebook.ts
1075 lines (959 loc) Β· 31.2 KB
/
notebook.ts
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
// Vendor modules
import * as actionTypes from "@nteract/actions";
import {
CellId,
createFrozenMediaBundle,
createImmutableOutput,
deleteCell,
emptyCodeCell,
emptyMarkdownCell,
emptyNotebook,
ImmutableCell,
ImmutableCodeCell,
ImmutableMarkdownCell,
ImmutableNotebook,
ImmutableOutput,
insertCellAfter,
insertCellAt,
makeCodeCell,
makeMarkdownCell,
makeRawCell,
OnDiskDisplayData,
OnDiskExecuteResult,
OnDiskOutput,
OnDiskStreamOutput
} from "@nteract/commutable";
import { UpdateDisplayDataContent } from "@nteract/messaging";
import {
DocumentRecordProps,
makeDocumentRecord,
NotebookModel,
PayloadMessage
} from "@nteract/types";
import { escapeCarriageReturnSafe } from "escape-carriage";
import { fromJS, List, Map, RecordOf, Set } from "immutable";
import { has } from "lodash";
import uuid from "uuid/v4";
type KeyPath = List<string | number>;
type KeyPaths = List<KeyPath>;
/**
* An output can be a stream of data that does not arrive at a single time. This
* function handles the different types of outputs and accumulates the data
* into a reduced output.
*
* @param {Object} outputs - Kernel output messages
* @param {Object} output - Outputted to be reduced into list of outputs
* @return {List<Object>} updated-outputs - Outputs + Output
*/
export function reduceOutputs(
outputs: List<ImmutableOutput> = List(),
output: OnDiskOutput
): List<ImmutableOutput> {
// Find the last output to see if it's a stream type
// If we don't find one, default to null
const last = outputs.last(null);
if (!last || !last.output_type) {
return outputs.push(createImmutableOutput(output));
}
if (output.output_type !== "stream" || last.output_type !== "stream") {
// If the last output type or the incoming output type isn't a stream
// we just add it to the outputs
// This is kind of like a "break" between streams if we get error,
// display_data, execute_result, etc.
return outputs.push(createImmutableOutput(output));
}
const streamOutput: OnDiskStreamOutput = output;
if (typeof streamOutput.name === "undefined") {
return outputs.push(createImmutableOutput(streamOutput));
}
function appendText(text: string): string {
if (typeof streamOutput.text === "string") {
return escapeCarriageReturnSafe(text + streamOutput.text);
}
return text;
}
// Invariant: size > 0, outputs.last() exists
if (last.name === streamOutput.name) {
return outputs.updateIn([outputs.size - 1, "text"], appendText);
}
// Check if there's a separate stream to merge with
const nextToLast = outputs.butLast().last(null);
if (
nextToLast &&
nextToLast.output_type === "stream" &&
nextToLast.name === streamOutput.name
) {
return outputs.updateIn([outputs.size - 2, "text"], appendText);
}
// If nothing else matched, just append it
return outputs.push(createImmutableOutput(streamOutput));
}
export function cleanCellTransient(
state: NotebookModel,
id: string
): RecordOf<DocumentRecordProps> {
// Clear out key paths that should no longer be referenced
return state
.setIn(["cellPagers", id], List())
.updateIn(
["transient", "keyPathsForDisplays"],
(kpfd: Map<string, KeyPaths>) =>
(kpfd || Map()).map((keyPaths: KeyPaths) =>
keyPaths.filter((keyPath: KeyPath) => keyPath.get(2) !== id)
)
)
.setIn(["transient", "cellMap", id], Map());
}
function setNotebookCheckpoint(
state: NotebookModel
): RecordOf<DocumentRecordProps> {
// Use the current version of the notebook document
return state.set("savedNotebook", state.get("notebook"));
}
function focusCell(
state: NotebookModel,
action: actionTypes.FocusCell
): RecordOf<DocumentRecordProps> {
return state.set("cellFocused", action.payload.id);
}
function clearOutputs(
state: NotebookModel,
action: actionTypes.ClearOutputs
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
const type = state.getIn(["notebook", "cellMap", id, "cell_type"]);
const cleanedState = cleanCellTransient(state, id);
if (type === "code") {
return cleanedState
.setIn(["notebook", "cellMap", id, "outputs"], List())
.setIn(["notebook", "cellMap", id, "execution_count"], null)
.setIn(["cellPrompts", id], List());
}
return cleanedState;
}
function toggleTagInCell(
state: NotebookModel,
action: actionTypes.ToggleTagInCell
): RecordOf<DocumentRecordProps> {
const { id, tag } = action.payload;
return state.updateIn(
["notebook", "cellMap", id, "metadata", "tags"],
tags => {
if (tags) {
return tags.has(tag) ? tags.remove(tag) : tags.add(tag);
} else {
return Set([tag]);
}
}
);
}
function clearAllOutputs(
state: NotebookModel,
action: actionTypes.ClearAllOutputs | actionTypes.RestartKernel
): RecordOf<DocumentRecordProps> {
// If we get a restart kernel action that said to clear outputs, we'll
// handle it
if (
action.type === actionTypes.RESTART_KERNEL &&
action.payload.outputHandling !== "Clear All"
) {
return state;
}
// For every cell, clear the outputs and execution counts
const cellMap = state
.getIn(["notebook", "cellMap"])
// NOTE: My kingdom for a mergeMap
.map((cell: ImmutableCell) => {
if ((cell as any).get("cell_type") === "code") {
return (cell as ImmutableCodeCell).merge({
outputs: List(),
execution_count: null
});
}
return cell;
});
// Clear all the transient data too
const transient = Map({
keyPathsForDisplays: Map(),
cellMap: cellMap.map(() => Map())
});
return state
.setIn(["notebook", "cellMap"], cellMap)
.set("transient", transient)
.setIn("cellPrompts", Map());
}
type UpdatableOutputContent =
| OnDiskExecuteResult
| OnDiskDisplayData
| UpdateDisplayDataContent;
// Utility function used in two reducers below
function updateAllDisplaysWithID(
state: NotebookModel,
content: UpdatableOutputContent
): NotebookModel {
if (!content || !content.transient || !content.transient.display_id) {
return state;
}
const keyPaths: KeyPaths =
state.getIn([
"transient",
"keyPathsForDisplays",
content.transient.display_id
]) || List();
const updateOutput = (output: any) => {
if (output) {
// We already have something here, don't change the other fields
return output.merge({
data: createFrozenMediaBundle(content.data),
metadata: fromJS(content.metadata || {})
});
} else if (content.output_type === "update_display_data") {
// Nothing here and we have no valid output, just create a basic output
return {
data: createFrozenMediaBundle(content.data),
metadata: fromJS(content.metadata || {}),
output_type: "display_data"
};
} else {
// Nothing here, but we have a valid output
return createImmutableOutput(content);
}
};
const updateOneDisplay = (currState: NotebookModel, keyPath: KeyPath) =>
currState.updateIn(keyPath, updateOutput);
return keyPaths.reduce(updateOneDisplay, state);
}
function appendOutput(
state: NotebookModel,
action: actionTypes.AppendOutput
): RecordOf<DocumentRecordProps> {
const output = action.payload.output;
const cellId = action.payload.id;
/**
* If it is not a display_data or execute_result with
* a display_id, then treat it as a normal output and don't
* add its index to the keyPaths.
*/
if (
(output.output_type !== "execute_result" &&
output.output_type !== "display_data") ||
!has(output, "transient.display_id")
) {
return state.updateIn(
["notebook", "cellMap", cellId, "outputs"],
(outputs: List<ImmutableOutput>): List<ImmutableOutput> =>
reduceOutputs(outputs, output)
);
}
// We now have a display_data that includes a transient display_id
// output: {
// data: { 'text/html': '<b>woo</b>' }
// metadata: {}
// transient: { display_id: '12312' }
// }
// We now have a display to track
const displayID = output.transient!.display_id;
if (!displayID || typeof displayID !== "string") {
return state;
}
// Every time we see a display id we're going to capture the keypath
// to the output
// Determine the next output index
const outputIndex = state
.getIn(["notebook", "cellMap", cellId, "outputs"])
.count();
// Construct the path to the output for updating later
const keyPath: KeyPath = List([
"notebook",
"cellMap",
cellId,
"outputs",
outputIndex
]);
const keyPaths: KeyPaths = (
state
// Extract the current list of keypaths for this displayID
.getIn(["transient", "keyPathsForDisplays", displayID]) || List()
)
// Append our current output's keyPath
.push(keyPath);
return updateAllDisplaysWithID(
state.setIn(["transient", "keyPathsForDisplays", displayID], keyPaths),
output
);
}
function updateDisplay(
state: NotebookModel,
action: actionTypes.UpdateDisplay
): RecordOf<DocumentRecordProps> {
return updateAllDisplaysWithID(state, action.payload.content);
}
function focusNextCell(
state: NotebookModel,
action: actionTypes.FocusNextCell
): RecordOf<DocumentRecordProps> {
const cellOrder = state.getIn(["notebook", "cellOrder"]);
const id = action.payload.id ? action.payload.id : state.get("cellFocused");
// If for some reason we neither have an ID here or a focused cell, we just
// keep the state consistent
if (!id) {
return state;
}
const curIndex = cellOrder.findIndex((foundId: CellId) => id === foundId);
const curCellType = state.getIn(["notebook", "cellMap", id, "cell_type"]);
const nextIndex = curIndex + 1;
// When at the end, create a new cell
if (nextIndex >= cellOrder.size) {
if (!action.payload.createCellIfUndefined) {
return state;
}
const cellId: string = uuid();
const cell = curCellType === "code" ? emptyCodeCell : emptyMarkdownCell;
const notebook: ImmutableNotebook = state.get("notebook");
return state
.set("cellFocused", cellId)
.set("notebook", insertCellAt(notebook, cell, cellId, nextIndex));
}
// When in the middle of the notebook document, move to the next cell
return state.set("cellFocused", cellOrder.get(nextIndex));
}
function focusPreviousCell(
state: NotebookModel,
action: actionTypes.FocusPreviousCell
): RecordOf<DocumentRecordProps> {
const cellOrder = state.getIn(["notebook", "cellOrder"]);
const curIndex = cellOrder.findIndex(
(id: CellId) => id === action.payload.id
);
const nextIndex = Math.max(0, curIndex - 1);
return state.set("cellFocused", cellOrder.get(nextIndex));
}
function focusCellEditor(
state: NotebookModel,
action: actionTypes.FocusCellEditor
): RecordOf<DocumentRecordProps> {
return state.set("editorFocused", action.payload.id);
}
function focusNextCellEditor(
state: NotebookModel,
action: actionTypes.FocusNextCellEditor
): RecordOf<DocumentRecordProps> {
const cellOrder: List<CellId> = state.getIn(["notebook", "cellOrder"]);
const id = action.payload.id ? action.payload.id : state.get("editorFocused");
// If for some reason we neither have an ID here or a focused editor, we just
// keep the state consistent
if (!id) {
return state;
}
const curIndex = cellOrder.findIndex((foundId: CellId) => id === foundId);
const nextIndex = curIndex + 1;
return state.set("editorFocused", cellOrder.get(nextIndex));
}
function focusPreviousCellEditor(
state: NotebookModel,
action: actionTypes.FocusPreviousCellEditor
): RecordOf<DocumentRecordProps> {
const cellOrder: List<CellId> = state.getIn(["notebook", "cellOrder"]);
const curIndex = cellOrder.findIndex(
(id: CellId) => id === action.payload.id
);
const nextIndex = Math.max(0, curIndex - 1);
return state.set("editorFocused", cellOrder.get(nextIndex));
}
function moveCell(
state: NotebookModel,
action: actionTypes.MoveCell
): RecordOf<DocumentRecordProps> {
return state.updateIn(
["notebook", "cellOrder"],
(cellOrder: List<CellId>) => {
const oldIndex = cellOrder.findIndex(
(id: string) => id === action.payload.id
);
const newIndex =
cellOrder.findIndex(
(id: string) => id === action.payload.destinationId
) + (action.payload.above ? 0 : 1);
if (oldIndex === newIndex) {
return cellOrder;
}
return cellOrder
.splice(oldIndex, 1)
.splice(newIndex - (oldIndex < newIndex ? 1 : 0), 0, action.payload.id);
}
);
}
// DEPRECATION WARNING: The action type RemoveCell is being deprecated. Please use DeleteCell instead
function deleteCellFromState(
state: NotebookModel,
action: actionTypes.DeleteCell | actionTypes.RemoveCell
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
return cleanCellTransient(
state.update("notebook", (notebook: ImmutableNotebook) =>
deleteCell(notebook, id)
),
id
);
}
function createCellBelow(
state: NotebookModel,
action: actionTypes.CreateCellBelow
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
const { cellType, source } = action.payload;
const cell = cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell;
const cellId = uuid();
return state.update("notebook", (notebook: ImmutableNotebook) => {
const index = notebook.get("cellOrder", List()).indexOf(id) + 1;
return insertCellAt(
notebook,
(cell as ImmutableMarkdownCell).set("source", source),
cellId,
index
);
});
}
function createCellAbove(
state: NotebookModel,
action: actionTypes.CreateCellAbove
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
const { cellType } = action.payload;
const cell = cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell;
const cellId = uuid();
return state.update("notebook", (notebook: ImmutableNotebook) => {
const cellOrder: List<CellId> = notebook.get("cellOrder", List());
const index = cellOrder.indexOf(id);
return insertCellAt(notebook, cell, cellId, index);
});
}
function createCellAfter(
state: NotebookModel,
action: actionTypes.CreateCellAfter
): RecordOf<DocumentRecordProps> {
console.log(
"DEPRECATION WARNING: This function is being deprecated. Please use createCellBelow() instead"
);
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
const { cellType, source } = action.payload;
const cell = cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell;
const cellId = uuid();
return state.update("notebook", (notebook: ImmutableNotebook) => {
const index = notebook.get("cellOrder", List()).indexOf(id) + 1;
return insertCellAt(
notebook,
(cell as ImmutableMarkdownCell).set("source", source),
cellId,
index
);
});
}
function createCellBefore(
state: NotebookModel,
action: actionTypes.CreateCellBefore
): RecordOf<DocumentRecordProps> {
console.log(
"DEPRECATION WARNING: This function is being deprecated. Please use createCellAbove() instead"
);
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
const { cellType } = action.payload;
const cell = cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell;
const cellId = uuid();
return state.update("notebook", (notebook: ImmutableNotebook) => {
const cellOrder: List<CellId> = notebook.get("cellOrder", List());
const index = cellOrder.indexOf(id);
return insertCellAt(notebook, cell, cellId, index);
});
}
function createCellAppend(
state: NotebookModel,
action: actionTypes.CreateCellAppend
): RecordOf<DocumentRecordProps> {
const { cellType } = action.payload;
const notebook: ImmutableNotebook = state.get("notebook");
const cellOrder: List<CellId> = notebook.get("cellOrder", List());
const cell: ImmutableCell =
cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell;
const index = cellOrder.count();
const cellId = uuid();
return state.set("notebook", insertCellAt(notebook, cell, cellId, index));
}
function acceptPayloadMessage(
state: NotebookModel,
action: actionTypes.AcceptPayloadMessage
): NotebookModel {
const id: string = action.payload.id;
const payload: PayloadMessage = action.payload.payload;
if (payload.source === "page") {
// append pager
return state.updateIn(["cellPagers", id], l =>
(l || List()).push(payload.data)
);
} else if (payload.source === "set_next_input") {
if (payload.replace) {
// this payload is sent in IPython when you use %load
// and is intended to replace cell source
return state.setIn(["notebook", "cellMap", id, "source"], payload.text);
} else {
// create the next cell
// FIXME: This is a weird pattern. We're basically faking a dispatch here
// inside a reducer and then appending to the result. I think that both of
// these reducers should just handle the original action.
return createCellBelow(state, {
type: actionTypes.CREATE_CELL_BELOW,
payload: {
cellType: "code",
// TODO: is payload.text guaranteed to be defined?
source: payload.text || "",
id,
contentRef: action.payload.contentRef
}
});
}
}
// If the payload is unsupported, just return the current state
return state;
}
function sendExecuteRequest(
state: NotebookModel,
action: actionTypes.SendExecuteRequest
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
const contentRef = action.payload.contentRef;
if (!id) {
return state;
}
// TODO: Record the last execute request for this cell
// * Clear outputs
// * Set status to queued, as all we've done is submit the execution request
// FIXME: This is a weird pattern. We're basically faking a dispatch here
// inside a reducer and then appending to the result. I think that both of
// these reducers should just handle the original action.
return clearOutputs(state, {
type: "CLEAR_OUTPUTS",
payload: {
id,
contentRef
}
}).setIn(["transient", "cellMap", id, "status"], "queued");
}
function setInCell(
state: NotebookModel,
action: actionTypes.SetInCell<string>
): RecordOf<DocumentRecordProps> {
return state.setIn(
["notebook", "cellMap", action.payload.id].concat(action.payload.path),
action.payload.value
);
}
function toggleCellOutputVisibility(
state: NotebookModel,
action: actionTypes.ToggleCellOutputVisibility
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
return state.setIn(
["notebook", "cellMap", id, "metadata", "outputHidden"],
!state.getIn(["notebook", "cellMap", id, "metadata", "outputHidden"])
);
}
interface ICellVisibilityMetadata {
inputHidden?: boolean;
outputHidden?: boolean;
}
function unhideAll(
state: NotebookModel,
action: actionTypes.UnhideAll
): RecordOf<DocumentRecordProps> {
const metadataMixin: ICellVisibilityMetadata = {};
if (action.payload.outputHidden !== undefined) {
// TODO: Verify that we convert to one namespace
// for hidden input/output
metadataMixin.outputHidden = action.payload.outputHidden;
}
if (action.payload.inputHidden !== undefined) {
metadataMixin.inputHidden = action.payload.inputHidden;
}
return state.updateIn(["notebook", "cellMap"], cellMap =>
cellMap.map((cell: ImmutableCell) => {
if ((cell as any).get("cell_type") === "code") {
return cell.mergeIn(["metadata"], metadataMixin);
}
return cell;
})
);
}
function toggleCellInputVisibility(
state: NotebookModel,
action: actionTypes.ToggleCellInputVisibility
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
return state.setIn(
["notebook", "cellMap", id, "metadata", "inputHidden"],
!state.getIn(["notebook", "cellMap", id, "metadata", "inputHidden"])
);
}
function updateCellStatus(
state: NotebookModel,
action: actionTypes.UpdateCellStatus
): RecordOf<DocumentRecordProps> {
const { id, status } = action.payload;
return state.setIn(["transient", "cellMap", id, "status"], status);
}
function updateOutputMetadata(
state: NotebookModel,
action: actionTypes.UpdateOutputMetadata
): RecordOf<DocumentRecordProps> {
const { id, metadata, index, mediaType } = action.payload;
const currentOutputs = state.getIn(["notebook", "cellMap", id, "outputs"]);
const updatedOutputs = currentOutputs.update(index, (item: any) =>
item.set(
"metadata",
fromJS({
[mediaType]: metadata
})
)
);
return state.setIn(["notebook", "cellMap", id, "outputs"], updatedOutputs);
}
function setLanguageInfo(
state: NotebookModel,
action: actionTypes.SetLanguageInfo
): RecordOf<DocumentRecordProps> {
const langInfo = fromJS(action.payload.langInfo);
return state.setIn(["notebook", "metadata", "language_info"], langInfo);
}
function setKernelspecInfo(
state: NotebookModel,
action: actionTypes.SetKernelspecInfo
): RecordOf<DocumentRecordProps> {
const { kernelInfo } = action.payload;
return state
.setIn(
["notebook", "metadata", "kernelspec"],
fromJS({
name: kernelInfo.name,
language: kernelInfo.spec.language,
display_name: kernelInfo.spec.display_name
})
)
.setIn(["notebook", "metadata", "kernel_info", "name"], kernelInfo.name);
}
function setKernelInfo(
state: NotebookModel,
action: actionTypes.SetKernelInfo
): RecordOf<DocumentRecordProps> {
const { info } = action.payload;
return state
.setIn(
["notebook", "metadata", "kernelspec"],
fromJS({
name: info.languageName
})
)
.setIn(["notebook", "metadata", "kernel_info", "name"], info.languageName);
}
function overwriteMetadataField(
state: NotebookModel,
action: actionTypes.OverwriteMetadataField
): RecordOf<DocumentRecordProps> {
const { field, value } = action.payload;
return state.setIn(["notebook", "metadata", field], fromJS(value));
}
function deleteMetadataField(
state: NotebookModel,
action: actionTypes.DeleteMetadataField
): RecordOf<DocumentRecordProps> {
const { field } = action.payload;
return state.deleteIn(["notebook", "metadata", field]);
}
function copyCell(
state: NotebookModel,
action: actionTypes.CopyCell
): RecordOf<DocumentRecordProps> {
const id = action.payload.id || state.cellFocused;
const cell = state.getIn(["notebook", "cellMap", id]);
if (!cell) {
return state;
}
return state.set("copied", cell);
}
function cutCell(
state: NotebookModel,
action: actionTypes.CutCell
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
const cell = state.getIn(["notebook", "cellMap", id]);
if (!cell) {
return state;
}
// FIXME: If the cell that was cut was the focused cell, focus the cell below
return state
.set("copied", cell)
.update("notebook", (notebook: ImmutableNotebook) =>
deleteCell(notebook, id)
);
}
function pasteCell(state: NotebookModel): RecordOf<DocumentRecordProps> {
const copiedCell = state.get("copied");
const pasteAfter = state.cellFocused;
if (!copiedCell || !pasteAfter) {
return state;
}
// Create a new cell with `id` that will come after the currently focused cell
// using the contents of the originally copied cell
const id = uuid();
return state.update("notebook", (notebook: ImmutableNotebook) =>
insertCellAfter(notebook, copiedCell, id, pasteAfter)
);
}
function changeCellType(
state: NotebookModel,
action: actionTypes.ChangeCellType
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
const { to } = action.payload;
const cell = state.getIn(["notebook", "cellMap", id]);
const from = cell.cell_type;
// NOOP, since we're already that cell type
if (from === to) {
return state;
}
let nextState = state;
// from === "code"
if (from === "code") {
nextState = cleanCellTransient(
state
.deleteIn(["notebook", "cellMap", id, "execution_count"])
.deleteIn(["notebook", "cellMap", id, "outputs"]),
id
);
}
switch (to) {
case "code":
return nextState.setIn(
["notebook", "cellMap", id],
makeCodeCell({
source: cell.source
})
);
case "markdown":
return nextState.setIn(
["notebook", "cellMap", id],
makeMarkdownCell({
source: cell.source
})
);
case "raw":
return nextState.setIn(
["notebook", "cellMap", id],
makeRawCell({
source: cell.source
})
);
}
// If we didn't match on the `to`, we should change nothing as we don't implement
// other cell types (as there aren't any)
return state;
}
function toggleOutputExpansion(
state: NotebookModel,
action: actionTypes.ToggleCellExpansion
): RecordOf<DocumentRecordProps> {
const id = action.payload.id ? action.payload.id : state.cellFocused;
if (!id) {
return state;
}
return state.updateIn(
["notebook", "cellMap"],
(cells: Map<CellId, ImmutableCell>) =>
cells.setIn(
[id, "metadata", "outputExpanded"],
!cells.getIn([id, "metadata", "outputExpanded"])
)
);
}
function promptInputRequest(
state: NotebookModel,
action: actionTypes.PromptInputRequest
): RecordOf<DocumentRecordProps> {
const { id, password, prompt } = action.payload;
return state.updateIn(["cellPrompts", id], prompts =>
prompts.push({
prompt,
password
})
);
}
// DEPRECATION WARNING: Below, the following action types are being deprecated: RemoveCell, CreateCellAfter and CreateCellBefore
type DocumentAction =
| actionTypes.ToggleTagInCell
| actionTypes.FocusPreviousCellEditor
| actionTypes.FocusPreviousCell
| actionTypes.FocusNextCellEditor
| actionTypes.FocusNextCell
| actionTypes.FocusCellEditor
| actionTypes.FocusCell
| actionTypes.ClearOutputs
| actionTypes.AppendOutput
| actionTypes.UpdateDisplay
| actionTypes.MoveCell
| actionTypes.DeleteCell
| actionTypes.RemoveCell
| actionTypes.CreateCellBelow
| actionTypes.CreateCellAbove
| actionTypes.CreateCellAfter
| actionTypes.CreateCellBefore
| actionTypes.CreateCellAppend
| actionTypes.ToggleCellOutputVisibility
| actionTypes.ToggleCellInputVisibility
| actionTypes.UpdateCellStatus
| actionTypes.UpdateOutputMetadata
| actionTypes.SetLanguageInfo
| actionTypes.SetKernelspecInfo
| actionTypes.SetKernelInfo
| actionTypes.OverwriteMetadataField
| actionTypes.DeleteMetadataField
| actionTypes.CopyCell
| actionTypes.CutCell
| actionTypes.PasteCell
| actionTypes.ChangeCellType
| actionTypes.ToggleCellExpansion
| actionTypes.AcceptPayloadMessage
| actionTypes.SendExecuteRequest
| actionTypes.SaveFulfilled
| actionTypes.RestartKernel
| actionTypes.ClearAllOutputs
| actionTypes.SetInCell<any>
| actionTypes.UnhideAll
| actionTypes.PromptInputRequest;
const defaultDocument: NotebookModel = makeDocumentRecord({
notebook: emptyNotebook
});
export function notebook(
state: NotebookModel = defaultDocument,
action: DocumentAction
): RecordOf<DocumentRecordProps> {
switch (action.type) {
case actionTypes.TOGGLE_TAG_IN_CELL:
return toggleTagInCell(state, action);
case actionTypes.SEND_EXECUTE_REQUEST:
return sendExecuteRequest(state, action);
case actionTypes.SAVE_FULFILLED:
return setNotebookCheckpoint(state);
case actionTypes.FOCUS_CELL:
return focusCell(state, action);
case actionTypes.CLEAR_OUTPUTS:
return clearOutputs(state, action);
case actionTypes.CLEAR_ALL_OUTPUTS:
case actionTypes.RESTART_KERNEL:
return clearAllOutputs(state, action);
case actionTypes.APPEND_OUTPUT:
return appendOutput(state, action);
case actionTypes.UPDATE_DISPLAY:
return updateDisplay(state, action);