-
Notifications
You must be signed in to change notification settings - Fork 185
/
ScrollableTerminal.tsx
1604 lines (1401 loc) · 54.2 KB
/
ScrollableTerminal.tsx
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
/*
* Copyright 2020 The Kubernetes Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { v5 } from 'uuid'
import React from 'react'
import SplitInjector, { InjectorOptions, SplitSpec } from './SplitInjector'
import type {
ScalarResponse,
Tab as KuiTab,
ExecOptions,
ExecOptionsWithUUID,
CommandStartEvent,
CommandCompleteEvent,
TabLayoutModificationResponse,
NewSplitRequest
} from '@kui-shell/core'
import { i18n } from '@kui-shell/core/mdist/api/i18n'
import { getTabId } from '@kui-shell/core/mdist/api/Tab'
import { History } from '@kui-shell/core/mdist/api/History'
import { ExecType } from '@kui-shell/core/mdist/api/Command'
import { isWatchable } from '@kui-shell/core/mdist/api/Watch'
import { inBrowser } from '@kui-shell/core/mdist/api/Capabilities'
import { isExecutableClient } from '@kui-shell/core/mdist/api/Client'
import { SnapshotRequestEvent, eventBus, eventChannelUnsafe } from '@kui-shell/core/mdist/api/Events'
import {
isAbortableResponse,
isCommentaryResponse,
isNewSplitRequest,
isTabLayoutModificationResponse
} from '@kui-shell/core/mdist/api/Response'
import ScrollbackState, { ScrollbackOptions, Cleaner } from './ScrollbackState'
import Block from './Block'
import getSize from './getSize'
import { snapshot } from './Snapshot'
import SplitHeader from './SplitHeader'
import SplitPosition, { SplitPositionProps } from './SplitPosition'
import KuiConfiguration from '../../Client/KuiConfiguration'
import SessionInitStatus from '../../Client/SessionInitStatus'
import { onCopy, onCut, onPaste } from './ClipboardTransfer'
import {
Active,
Finished,
Announcement,
Cancelled,
isCancelled,
Rerun,
isRerunable,
isBeingRerun,
Processing,
isActive,
isAnnouncement,
isFinished,
isWithCompleteEvent,
isOk,
isOutputOnly,
isMaximized,
isProcessing,
hasStartEvent,
hasCommand,
hasUUID,
hasOriginalUUID,
BlockModel
} from './Block/BlockModel'
import isInViewport from './visible'
import '../../../../web/scss/components/Terminal/_index.scss'
const strings = i18n('plugin-client-common')
/** Hard limit on the number of Terminal splits */
const MAX_TERMINALS = 5
/** Remember the welcomed count in localStorage, using this key */
const NUM_WELCOMED = 'kui-shell.org/ScrollableTerminal/NumWelcomed'
/**
* Seed UUID for v5 sequences. THe particular value here does not
* matter, but if you change this, you will invalidate scrollback
* history for all users. Only change this if that is what you
* intended.
*/
const UUID_NAMESPACE = '5a04bbd1-fb7e-44f7-a5ea-16c0331772e3'
export interface TerminalOptions {
noActiveInput?: boolean
}
type Props = TerminalOptions &
SplitPositionProps &
React.PropsWithChildren<{
/** tab UUID */
uuid: string
/** tab model */
tab: KuiTab
snapshot?: Buffer
tabTitle?: string
/** Callback after we mount */
onReady?: () => void
/** handler for terminal clear */
onClear?: () => void
/** KuiConfiguration */
config: KuiConfiguration
/** Toggle attribute on Tab DOM */
toggleAttribute(attr: string): void
/** Status of the proxy session (for client-server architectures of Kui) */
sessionInit: SessionInitStatus
/** Reset any notion of left strip etc. */
resetSplitLayout(): void
/** Toggle whether we have a left strip split */
willToggleLeftStripMode(): void
/** Toggle whether we have a right strip split */
willToggleRightStripMode(): void
}>
interface State {
/** Index of the focused split (index into State.splits) */
focusedIdx: number
/** Splits model */
splits: ScrollbackState[]
}
/** get the selected texts in window */
export function getSelectionText() {
let text = ''
if (window.getSelection) {
text = window.getSelection().toString()
}
return text
}
/** Type guard that the given evt.relatedTarget is an HTML Element */
function isElement(target: EventTarget): target is Element {
return target && (target as Element).tagName !== undefined
}
export default class ScrollableTerminal extends React.PureComponent<Props, State> {
/**
* For UUID generation, keep a running counter of the total number
* of scrollbacks created. This index will be fed to the uuid.v5()
* generator. Note: we can't use the scrollback's index in the
* current split array, because the user might reorder them, e.g. by
* creating two splits, then deleting the *first*, then creating
* (again) a second split. What was the second split is now in the
* first position, and the new split will have the same ID as the
* (now) first-ordinal split. Thus, instead we keep a running
* counter. This will preserve cross-session UUID sequence equality,
* while avoiding the reordering dilemma.
*/
private scrollbackCounter = 0
private cleaners: Cleaner[] = []
public constructor(props: Props) {
super(props)
this.initClipboardEvents()
this.state = this.initialState()
this.initSnapshotEvents()
}
private initialState() {
const splits = [this.scrollbackWithWelcome()]
return {
focusedIdx: 0,
splits
}
}
/** Listen for copy and paste (TODO: cut) events to facilitate moving blocks */
private initClipboardEvents() {
const paste = onPaste.bind(this)
document.addEventListener('paste', paste)
this.cleaners.push(() => document.removeEventListener('paste', paste))
const copy = onCopy.bind(this)
document.addEventListener('copy', copy)
this.cleaners.push(() => document.removeEventListener('copy', copy))
const cut = onCut.bind(this)
document.addEventListener('cut', cut)
this.cleaners.push(() => document.removeEventListener('cut', cut))
}
/** Listen for snapshot request events */
private initSnapshotEvents() {
const onSnapshot = async (evt: SnapshotRequestEvent) => {
if (evt.execUUID && evt.cb) {
// capture just one block
this.state.splits.forEach(split => {
const block = split.blocks.find(_ => hasUUID(_) && _.execUUID === evt.execUUID)
if (block && isFinished(block)) {
const replacer = (key: string, value: any) => {
if (key === 'tab') {
return undefined
} else if (key === 'block') {
return undefined
} else {
return value
}
}
evt.cb(Buffer.from(JSON.stringify(snapshot(block), replacer)))
} else {
evt.cb(null)
}
})
} else {
// request that all commentary in this tab save themselves
await Promise.all(
this.state.splits.map(async ({ blocks }) => {
await Promise.all(
blocks.map(async block => {
if (isWithCompleteEvent(block) && isCommentaryResponse(block.completeEvent.response)) {
await eventChannelUnsafe.emit(`/kui/snapshot/request/${block.execUUID}`)
}
})
)
})
)
}
}
eventBus.onSnapshotRequest(onSnapshot, getTabId(this.props.tab))
this.cleaners.push(() => eventBus.offSnapshotRequest(onSnapshot, getTabId(this.props.tab)))
}
/** add welcome blocks at the top of scrollback */
private scrollbackWithWelcome() {
const scrollback = this.scrollback(undefined, { createdBy: 'default' })
const welcomeMax = this.props.config.showWelcomeMax
if (this.props.sessionInit === 'Done' && this.props.config.loadingDone && welcomeMax !== undefined) {
const welcomed = parseInt(localStorage.getItem(NUM_WELCOMED)) || 0
if ((welcomeMax === -1 || welcomed < welcomeMax) && this.props.config.loadingDone) {
const announcement = this.props.config.loadingDone(this.props.tab.REPL)
if (announcement) {
eventBus.emitCommandComplete({
tab: this.props.tab,
historyIdx: -1,
command: 'welcome',
completeTime: Date.now(),
argvNoOptions: ['welcome'],
parsedOptions: {},
execOptions: {},
pipeStages: { stages: [['welcome']] },
execUUID: '',
execType: ExecType.Nested,
cancelled: false,
echo: true,
evaluatorOptions: {},
response: { react: announcement },
responseType: 'ScalarResponse'
})
const welcomeBlocks: BlockModel[] = !announcement
? []
: [
Announcement({
react: this.props.config.loadingDone && (
<div className="kui--repl-message kui--session-init-done">{announcement}</div>
)
})
]
scrollback.blocks = welcomeBlocks.concat(scrollback.blocks)
if (welcomeMax !== -1) {
localStorage.setItem(NUM_WELCOMED, (welcomed + 1).toString())
}
}
}
}
return scrollback
}
/** Create a split with the given position and coloration */
private makePositionedSplit(
position: SplitPosition,
opts: ScrollbackOptions = {},
inverseColors = position === 'left-strip'
) {
const split = this.scrollback(undefined, Object.assign({}, opts, { position, inverseColors }))
this.setState(curState => ({
splits: curState.splits.concat([split])
}))
if (position === 'left-strip') {
this.props.willToggleLeftStripMode()
} else if (position === 'right-strip') {
this.props.willToggleRightStripMode()
}
return split
}
/**
* This is the `inject` handler for the `SplitInjector`
* interface. Injects the given React `node` into the given
* `position`. Uses `uuid` to determine whether the a prior version
* of the node already exists in that position.
*/
public readonly inject = (splitSpecs: SplitSpec[]) => setTimeout(() => splitSpecs.forEach(this.injectOne))
private readonly injectOne = ({
uuid,
node,
position,
count,
opts: { maximized, hasActiveInput, inverseColors }
}) => {
const split =
(position !== 'default'
? this.state.splits.find(_ => _.position === position)
: this.state.splits.filter(_ => _.position === 'default')[count]) ||
this.makePositionedSplit(position, { createdBy: 'kui', hasActiveInput, maximized })
if (split) {
this.splice(
split.uuid,
curState => {
// have we already inserted the given node?
const execUUID = `${uuid}-${position}`
const alreadyIdx = curState.blocks.findIndex(_ => isAnnouncement(_) && _.execUUID === execUUID)
// in either case, we will use this new BlockModel
const newBlock = Announcement({ react: node }, execUUID, maximized)
if (alreadyIdx >= 0) {
// yup! so splice out with the old, and in with the new!
return {
blocks: [
...curState.blocks.slice(0, alreadyIdx),
newBlock,
...curState.blocks.slice(alreadyIdx + 1) // skip over the existing version...
]
}
} else {
// then we splice in the new
const insertIdx = isActive(split.blocks[split.blocks.length - 1])
? split.blocks.length - 1
: split.blocks.length
return {
maximized: maximized === true || curState.maximized,
inverseColors: inverseColors === true || curState.inverseColors,
blocks: [...curState.blocks.slice(0, insertIdx), newBlock, ...curState.blocks.slice(insertIdx)]
}
}
},
{ focus: !!hasActiveInput }
)
}
}
/** This is the `modify` handler for the `SplitInjector`
* interface. Modifies the properties of an existing split as
* specified by `sbuuid`, and then returns the given `node`
* unchanged. */
public readonly modify = (
sbuuid: string,
node: React.ReactNode,
{ hasActiveInput, inverseColors, maximized = false }: InjectorOptions
): React.ReactNode => {
setTimeout(() =>
this.setState(curState => {
const sbidx = this.findSplit(curState, sbuuid)
if (sbidx < 0) {
return null
} else {
const splits = curState.splits.slice()
if (typeof maximized === 'boolean') {
splits[sbidx].maximized = maximized
}
if (typeof inverseColors === 'boolean') {
splits[sbidx].inverseColors = inverseColors
}
if (typeof hasActiveInput === 'boolean') {
splits[sbidx].hasActiveInput = hasActiveInput
}
return {
splits
}
}
})
)
return node
}
private allocateUUIDForScrollback() {
// this.props.uuid is the uuid for the whole tab
// on top of that, we allocate a "v5" uuid for this scrollback
const sbidx = this.scrollbackCounter++
const tabPart = this.props.uuid
const scrollbackPart = v5(sbidx.toString(), UUID_NAMESPACE)
return `${tabPart}_${scrollbackPart}`
}
/** Restore from localStorage for a given tab UUID */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private restoreBlocks(sbuuid: string): BlockModel[] {
// TODO:
/* return History(sbuuid)
.slice(-20)
.filter(_ => _.execUUID !== undefined && isScalarResponse(_.response) && _.isCurrentlyShown)
.map(_ => Finished(Processing(Active(), _.raw, _.execUUID), _.response as ScalarResponse, false, _.historyIdx)) */
return []
}
/** @return the number of splits with `position=default` */
private numDefaultSplits() {
return this.state.splits.reduce((N, _) => (N += _.position === 'default' ? 1 : 0), 0)
}
private scrollback(sbuuid = this.allocateUUIDForScrollback(), opts: ScrollbackOptions = {}): ScrollbackState {
const state: ScrollbackState = {
uuid: sbuuid,
cleaners: [],
inverseColors: opts.inverseColors,
blocks: this.restoreBlocks(sbuuid).concat([Active()]),
remove: undefined,
clear: undefined,
invert: undefined,
onClick: undefined,
onMouseDown: undefined,
onFocus: undefined,
onOutputRender: undefined,
setActiveBlock: undefined,
willFocusBlock: undefined,
willRemoveBlock: undefined,
willUpdateCommand: undefined,
tabRefFor: undefined,
scrollableRef: undefined,
hasActiveInput: opts.hasActiveInput,
createdBy: opts.createdBy || 'user',
position: opts.position || 'default',
willToggleSplitPosition: undefined
}
const getBlockIndexFromEvent = (evt: React.SyntheticEvent, doNotComplain = false) => {
const idxAttr = evt.currentTarget.getAttribute('data-input-count')
if (!idxAttr) {
if (!doNotComplain) {
console.error('Failed to focus, due to missing data-input-count attribute', evt.currentTarget, evt.target)
}
return -1
} else {
return parseInt(idxAttr, 10)
}
}
state.remove = () => this.removeSplit(sbuuid)
state.clear = () => this.clear(sbuuid)
state.invert = () => this.invert(sbuuid)
/**
* For inline-input clients, we want empty-space clicks to steal
* focus away from the other split, if we are switching splits;
* otherwise, we don't want empty-space clicks in the focused
* split to steal focus away from that split's active input
*/
state.onClick = () => {
if (getSelectionText().length === 0) {
this.doFocus(state)
}
}
/**
* For bottom-input clients, we don't want empty-space clicks to
* steal focus away from the bottom input
*/
state.onMouseDown = (evt: React.MouseEvent<HTMLElement>) => {
evt.preventDefault()
}
/** Output.tsx finished rendering something */
state.onOutputRender = () => {
if (!this.props.noActiveInput) {
// if we are using inline input, then scroll to the bottom
// whenever an output is rendered in this split
// problematic, see https://github.com/kubernetes-sigs/kui/issues/8174
// setTimeout(() => state.facade.scrollToBottom())
}
}
/** Update the active block */
state.setActiveBlock = (c: Block) => {
if (c && c.props && c.props.model && isActive(c.props.model)) {
const split = this.state.splits[this.findSplit(this.state, sbuuid)]
split._activeBlock = c
}
}
/**
* User clicked to focus a block.
*
* @param uuid scrollback UUID
* @param focusedBlockIdx index into the ScrollbackState of that scrollback
*
*/
state.willFocusBlock = (evt: React.SyntheticEvent) => {
const sbidx = this.findSplit(this.state, sbuuid)
if (sbidx >= 0) {
const idx = getBlockIndexFromEvent(evt)
evt.stopPropagation()
const split = typeof sbuuid === 'string' ? this.state.splits[this.findSplit(this.state, sbuuid)] : sbuuid
this.setFocusOnScrollback(split, idx)
}
}
state.willUpdateCommand = (idx: number, command: string) => {
return this.splice(sbuuid, curState => {
const block = Object.assign({}, curState.blocks[idx])
if (hasCommand(block)) {
block.command = command
}
if (hasStartEvent(block)) {
block.startEvent.command = command
}
if (isWithCompleteEvent(block)) {
block.completeEvent.command = command
}
return {
blocks: curState.blocks
.slice(0, idx)
.concat([block])
.concat(curState.blocks.slice(idx + 1))
}
})
}
/** The focus event is coming
* from the browser, e.g. when the user hits tab to
* navigate between the <li> of each block */
state.onFocus = (evt: React.FocusEvent) => {
const sbidx = this.findSplit(this.state, sbuuid)
if (sbidx >= 0) {
const scrollback = this.state.splits[sbidx]
const idx = getBlockIndexFromEvent(evt)
if (
isElement(evt.relatedTarget) &&
/li/i.test(evt.relatedTarget.tagName) &&
/li/i.test(evt.target.tagName) &&
scrollback.focusedBlockIdx !== idx
) {
scrollback.willFocusBlock(evt)
}
}
}
/** remove the block at the given index */
state.willRemoveBlock = (evt: React.SyntheticEvent, idx = getBlockIndexFromEvent(evt)) => {
if (idx >= 0) {
this.splice(sbuuid, curState => {
this.removeWatchableBlock(curState.blocks[idx])
const blocks = curState.blocks
.slice(0, idx)
.concat(curState.blocks.slice(idx + 1))
.concat(this.hasActiveBlock(curState) ? [] : [Active()]) // plus a new block, if needed
const focusedBlockIdx =
curState.focusedBlockIdx >= idx ? this.findActiveBlock({ blocks }) : curState.focusedBlockIdx
return {
blocks,
focusedBlockIdx
}
})
}
}
/** Reference for the scrollable part of the Split; helpful for scrollToTop/Bottom */
state.scrollableRef = (ref: HTMLElement) => {
if (ref) {
state.facade.scrollToTop = () => (ref.scrollTop = 0)
/**
* If given the optional parameter, only scroll into view if the
* specified block (identified by its execUUID) is the last block in
* this tab
*
*/
state.facade.scrollToBottom = (execUUID?: string) => {
const sbidx = this.findSplit(this.state, sbuuid)
if (sbidx >= 0) {
const { blocks } = this.state.splits[sbidx]
const lastBlock = blocks[blocks.length - 1]
if (!execUUID || (hasUUID(lastBlock) && lastBlock.execUUID === execUUID)) {
ref.scrollTop = ref.scrollHeight
}
}
}
state.facade.show = (sel: string) => {
const elt = this.props.tab.querySelector(sel)
if (elt) {
return elt.scrollIntoView()
}
}
}
}
/** Reference for the entire Split */
state.tabRefFor = (ref: HTMLElement) => {
const scrollback = state
if (ref) {
ref['facade'] = scrollback.facade
scrollback.facade.getSize = getSize.bind(ref)
scrollback.facade.splitCount = () => this.state.splits.length
scrollback.facade.hasSideBySideTerminals = () => this.numDefaultSplits() > 1
scrollback.facade.addTopClass = this.props.tab.addClass
scrollback.facade.addClass = (cls: string) => {
ref.classList.add(cls)
}
scrollback.facade.removeTopClass = this.props.tab.removeClass
scrollback.facade.removeClass = (cls: string) => {
ref.classList.remove(cls)
}
}
}
state.willToggleSplitPosition = () => {
const sbidx = this.findSplit(this.state, sbuuid)
if (sbidx >= 0) {
const scrollback = this.state.splits[sbidx]
if (scrollback.position === 'default') {
if (this.props.hasRightStrip) {
// this split is default, and we have a right split; make this a left split
scrollback.position = 'left-strip'
this.props.willToggleLeftStripMode()
} else {
// this split is default, and we don't have a right split; make this a right split
scrollback.position = 'right-strip'
this.props.willToggleRightStripMode()
}
} else if (scrollback.position === 'right-strip') {
if (this.props.hasLeftStrip) {
// this split is right, and we have a left split; revert this to default
scrollback.position = 'default'
this.props.willToggleRightStripMode()
} else {
// this split is right, and we don't have a left split; make this a left split
scrollback.position = 'left-strip'
this.props.willToggleLeftStripMode()
this.props.willToggleRightStripMode()
}
} else {
// this split is left; always return to default
this.props.willToggleLeftStripMode()
scrollback.position = 'default'
}
}
}
// prefetch command history; this helps with master history
History(sbuuid)
// associate a tab facade with the split
this.tabFor(state)
const onTabCloseRequest = async () => {
// async, to allow for e.g. command completion events to finish
// propagating to the split before we remove it
setTimeout(() => this.removeSplit(sbuuid))
}
eventBus.onceWithTabId('/tab/close/request', sbuuid, onTabCloseRequest)
state.cleaners.push(() => eventBus.offWithTabId('/tab/close/request', sbuuid, onTabCloseRequest))
if (opts.cmdline) {
setTimeout(() => {
const execUUID = this.execUUIDOfLastActiveBlock(state)
state.facade.REPL.pexec(opts.cmdline, { masquerade: opts.masquerade, data: opts.data, execUUID })
})
}
return this.initEvents(state)
}
private execUUIDOfLastActiveBlock(sb: ScrollbackState): string | undefined {
for (let idx = sb.blocks.length - 1; idx >= 0; idx--) {
const block = sb.blocks[idx]
if (isActive(block)) {
return block.execUUID
}
}
}
/** @return a reasonable default split */
private findMainSplit(excludedIndex?: number) {
return this.state.splits
.slice()
.reverse()
.find((split, idx) => {
const originalIdx = this.state.splits.length - idx - 1
return (
split &&
this.isOkSplitForContent(originalIdx) &&
(excludedIndex === undefined || originalIdx !== excludedIndex)
)
})
}
/** @return a reasonable default split */
private get current() {
return this.findMainSplit()
}
/** @return the uuid of a reasonable default split */
private get currentUUID() {
const cur = this.current
return cur ? cur.uuid : undefined
}
/** Invert colors of the given Scrollback uuid */
private invert(uuid: string) {
return this.splice(uuid, sbState => Object.assign({}, sbState, { inverseColors: !sbState.inverseColors }))
}
/** Clear Terminal; TODO: also clear persisted state, when we have it */
private clear(uuid: string) {
this.setState(curState => {
const focusedIdx = this.findSplit(curState, uuid)
return Object.assign(
{ focusedIdx: focusedIdx < 0 ? curState.focusedIdx : focusedIdx },
this.spliceMutate(curState, uuid, scrollback => {
const residualBlocks = scrollback.blocks
.filter(_ => {
this.removeWatchableBlock(_)
return false
})
.concat([Active(scrollback._activeBlock ? scrollback._activeBlock.inputValue() : '')])
return Object.assign(scrollback, {
blocks: residualBlocks,
focusedBlockIdx: residualBlocks.length - 1
})
})
)
})
if (this.props.onClear) {
setTimeout(() => this.props.onClear())
}
}
/** Some splits may not be ideal receptacles for arbitrary content */
private isOkSplitForContent(idx: number): boolean {
return this.state.splits[idx].position === 'default'
}
/**
* We want to direct the command execution UI to a default-position
* terminal.
*
* @return the sbuuid of a default-position split
*
*/
private redirectToPlainSplitIfNeeded(
sbuuid: string,
{ execType }: Pick<CommandStartEvent | CommandCompleteEvent, 'execType'>
): string {
if (execType === ExecType.ClickHandler) {
// <-- this is a click handler event
const idx = this.findSplit(this.state, sbuuid)
// note: idx may be < 0 if we are executing a command in-flight,
// e.g. executing a command in another split
if (idx >= 0 && !this.isOkSplitForContent(idx)) {
// then this is not a preferred target for displaying content
const plainSplit = this.findMainSplit()
if (plainSplit) {
// <-- we found a plain split!
return plainSplit.uuid
}
}
}
// otherwise, we are stuck with what we have
return sbuuid
}
/** the REPL started executing a command */
public onExecStart(uuid = this.currentUUID, asReplay: boolean, event: CommandStartEvent, _insertIdx?: number) {
if (event.execOptions && event.execOptions.echo === false) {
return
}
const processing = (block: BlockModel) => {
return [Processing(block, event, event.evaluatorOptions.isExperimental, asReplay || undefined)]
}
// uuid might be undefined if the split is going away
if (uuid) {
uuid = this.redirectToPlainSplitIfNeeded(uuid, event)
this.splice(uuid, curState => {
const idx = curState.blocks.length - 1
const insertIdx = typeof _insertIdx === 'number' ? _insertIdx : event.execOptions && event.execOptions.insertIdx
if (insertIdx !== undefined) {
// we were asked to splice in the startEvent at a particular index
return {
focusedBlockIdx: insertIdx,
blocks: (insertIdx === 0 ? [] : curState.blocks.slice(0, insertIdx))
.concat([Processing(Active(), event, event.evaluatorOptions.isExperimental)])
.concat(curState.blocks.slice(insertIdx))
}
}
const rerunIdx =
event.execType === ExecType.Rerun
? curState.blocks.findIndex(_ => {
return (
(hasOriginalUUID(_) && _.originalExecUUID === event.execUUID) ||
(hasUUID(_) && _.execUUID === event.execUUID)
)
})
: -1
if (event.execType === ExecType.Rerun) {
if (rerunIdx < 0) {
console.error(
'Cannot find block for rerun',
event.execType === ExecType.Rerun,
event,
curState.blocks.map(_ => {
return (hasOriginalUUID(_) && _.originalExecUUID) || (hasUUID(_) && _.execUUID)
}),
curState.blocks
)
} else if (isBeingRerun(curState.blocks[rerunIdx])) {
console.error('Block already being rerun', event)
}
}
// we are now pre-assigning a block's execUUID up front (see
// BlockModel.active); this may be falsely detected as a
// rerun, hence the guard here
if (rerunIdx >= 0 && !isActive(curState.blocks[rerunIdx])) {
const block = curState.blocks[rerunIdx]
this.removeWatchableBlock(block)
// The use case here is that the user clicked the Rerun
// button in the UI or clicked on an Input and hit Enter. In
// either case, the command execution will reuse the
// execUUID, hence the `findIndex` logic just above, which
// scans the blocks for an existing execUUID. So: we
// Transform the rerun block to Processing
return {
blocks: curState.blocks
.slice(0, rerunIdx) // everything before
.concat(isRerunable(block) ? [Rerun(block, event)] : [])
.concat(curState.blocks.slice(rerunIdx + 1)) // everything after
}
} else if (isProcessing(curState.blocks[idx])) {
// the last block is Processing; this can handle if the user
// causes a pexec to be sent to a split that is already
// processing
return {
blocks: curState.blocks.concat(processing(Active()))
}
} else {
// Transform the last block to Processing
const blocks = curState.blocks.slice(0, idx).concat(processing(curState.blocks[idx]))
return {
blocks
}
}
})
}
}
/** Format a MarkdownResponse */
private markdown(key: string) {
return {
content: strings(key),
contentType: 'text/markdown' as const
}
}
/** the REPL finished executing a command */
public async onExecEnd(
uuid = this.currentUUID,
asReplay: boolean,
event: CommandCompleteEvent<ScalarResponse>,
insertIdx?: number
) {
if (!uuid) return
else {
uuid = this.redirectToPlainSplitIfNeeded(uuid, event)
}
if (isTabLayoutModificationResponse(event.response)) {
const updatedResponse = await this.onTabLayoutModificationRequest(event.response, uuid)
if (updatedResponse) {
event.response = updatedResponse
}
}
if (event.execOptions && event.execOptions.echo === false) return
// note: even if the command registration asked for
// `outputOnly`, we ignore that if the response is a plain
// `true`; e.g. the `commentary` controller uses this to
// indicate an empty comment
const outputOnly = event.evaluatorOptions && event.evaluatorOptions.outputOnly && event.response !== true
const findBlock = (blocks: ScrollbackState['blocks']) => {
return blocks.findIndex(_ => {
return (
(isBeingRerun(_) && _.originalExecUUID === event.execUUID) ||
((isBeingRerun(_) || isProcessing(_)) && _.execUUID === event.execUUID)
)
})
}
// special case: replace all current content?
const replace = event.response && isCommentaryResponse(event.response) && event.response.props.replace
if (replace && !event.cancelled) {
const state = this.initialState()
const split = this.state.splits[this.findSplit(this.state, uuid)]
const maybeInProcess = split.blocks[findBlock(split.blocks)]
if (maybeInProcess && (isProcessing(maybeInProcess) || isBeingRerun(maybeInProcess))) {
const finishedBlock = Finished(maybeInProcess, event, outputOnly, asReplay || undefined)
state.splits[0].blocks.splice(0, 0, finishedBlock)
this.setState(state)
this.props.resetSplitLayout()
return
}
}
this.splice(uuid, curState => {
const inProcessIdx = findBlock(curState.blocks)
if (inProcessIdx >= 0) {
const inProcess = curState.blocks[inProcessIdx]
if (isProcessing(inProcess) || isBeingRerun(inProcess)) {
const finishedBlock = Finished(inProcess, event, outputOnly, asReplay || undefined)
try {
const blocks = (
replace
? [finishedBlock]
: curState.blocks
.slice(0, inProcessIdx) // everything before
.concat([finishedBlock]) // mark as finished
.concat(curState.blocks.slice(inProcessIdx + 1))
) // everything after
.concat(!isBeingRerun(inProcess) && inProcessIdx === curState.blocks.length - 1 ? [Active()] : []) // plus a new block!
return {
focusedBlockIdx: insertIdx === undefined ? blocks.length - 1 : insertIdx,
blocks
}
} catch (err) {
console.error('error updating state', err)
throw err
}
} else {
console.error('invalid state: got a command completion event for a block that is not processing', event)