-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathTerminal.tsx
255 lines (226 loc) · 8.91 KB
/
Terminal.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
import React, { useEffect, useRef, useState } from 'react'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import * as XtermWebfont from 'xterm-webfont'
import SockJS from 'sockjs-client'
import moment from 'moment'
import CopyToast, { handleSelectionChange } from '../CopyToast'
import { elementDidMount, useHeightObserver } from '../../../../../../common/helpers/Helpers'
import { CLUSTER_STATUS, SocketConnectionType } from '../../../../../../ClusterNodes/constants'
import { TERMINAL_STATUS } from './constants'
import './terminal.scss'
import { TerminalViewType } from './terminal.type'
import { restrictXtermAccessibilityWidth } from './terminal.utils'
import { logExceptionToSentry } from '@devtron-labs/devtron-fe-common-lib'
let clusterTimeOut
export default function TerminalView({
terminalRef,
sessionId,
socketConnection,
setSocketConnection,
isTerminalTab = true,
renderConnectionStrip,
registerLinkMatcher,
terminalMessageData,
clearTerminal,
dataTestId,
}: TerminalViewType) {
const socket = useRef(null)
const [firstMessageReceived, setFirstMessageReceived] = useState(false)
const [isReconnection, setIsReconnection] = useState(false)
const [popupText, setPopupText] = useState<boolean>(false)
const fitAddon = useRef(null)
function resizeSocket() {
if (terminalRef.current && fitAddon.current && isTerminalTab) {
const dim = fitAddon.current?.proposeDimensions()
if (dim && socket.current?.readyState === WebSocket.OPEN) {
socket.current?.send(JSON.stringify({ Op: 'resize', Cols: dim.cols, Rows: dim.rows }))
}
fitAddon.current?.fit()
}
}
const [myDivRef] = useHeightObserver(resizeSocket)
useEffect(() => {
if (!terminalRef.current) {
elementDidMount('#terminal-id').then(() => {
createNewTerminal()
})
}
if (sessionId && terminalRef.current) {
setIsReconnection(true)
restrictXtermAccessibilityWidth()
postInitialize(sessionId)
} else {
setSocketConnection(SocketConnectionType.DISCONNECTED)
}
}, [sessionId])
useEffect(() => {
if (popupText) {
setTimeout(() => setPopupText(false), 2000)
}
}, [popupText])
useEffect(() => {
if (socketConnection === SocketConnectionType.DISCONNECTING) {
if (clusterTimeOut) {
clearTimeout(clusterTimeOut)
}
if (socket.current) {
socket.current.close()
socket.current = undefined
}
}
}, [socketConnection])
const createNewTerminal = () => {
terminalRef.current = new Terminal({
scrollback: 99999,
fontSize: 14,
lineHeight: 1.4,
cursorBlink: false,
fontFamily: 'Inconsolata',
screenReaderMode: true,
theme: {
background: '#0B0F22',
foreground: '#FFFFFF',
},
})
handleSelectionChange(terminalRef.current, setPopupText)
fitAddon.current = new FitAddon()
/**
* Adding default check due to vite build changing the export
* for production the value will be `webFontAddon.current = new XtermWebfont.default()`
* for local the value will be `webFontAddon.current = new XtermWebfont()`
*/
const webFontAddon = XtermWebfont.default ? new XtermWebfont.default() : new XtermWebfont()
terminalRef.current.loadAddon(fitAddon.current)
terminalRef.current.loadAddon(webFontAddon)
if (typeof registerLinkMatcher === 'function') {
registerLinkMatcher(terminalRef.current)
}
terminalRef.current.loadWebfontAndOpen(document.getElementById('terminal-id'))
// terminalRef.current.open(document.getElementById('terminal-id'))
fitAddon.current?.fit()
terminalRef.current.reset()
terminalRef.current.attachCustomKeyEventHandler((event) => {
if ((event.metaKey && event.key === 'k') || event.key === 'K') {
terminalRef.current?.clear()
}
return true
})
}
const generateSocketURL = () => {
let socketURL = window.__ORCHESTRATOR_ROOT__
socketURL += '/k8s/pod/exec/sockjs/ws/'
return socketURL
}
const postInitialize = (sessionId: string) => {
const socketURL = generateSocketURL()
socket.current?.close()
setFirstMessageReceived(false)
socket.current = new SockJS(socketURL)
const _socket = socket.current
const _terminal = terminalRef.current
const _fitAddon = fitAddon.current
const disableInput = (): void => {
_terminal.setOption('cursorBlink', false)
_terminal.setOption('disableStdin', true)
setFirstMessageReceived(false)
}
const enableInput = (): void => {
_terminal.setOption('cursorBlink', true)
_terminal.setOption('disableStdin', false)
}
_terminal.onData(function (data) {
resizeSocket()
const inData = { Op: 'stdin', SessionID: '', Data: data }
if (_socket?.readyState === WebSocket.OPEN) {
_socket?.send(JSON.stringify(inData))
}
})
_socket.onopen = function () {
if (typeof terminalMessageData === 'function') {
terminalMessageData(CLUSTER_STATUS.RUNNING, TERMINAL_STATUS.SUCCEDED)
}
const startData = { Op: 'bind', SessionID: sessionId }
_socket.send(JSON.stringify(startData))
const dim = _fitAddon?.proposeDimensions()
if (dim) {
_socket.send(JSON.stringify({ Op: 'resize', Cols: dim.cols, Rows: dim.rows }))
}
_terminal.focus()
if (isReconnection) {
_terminal.writeln('')
_terminal.writeln('---------------------------------------------')
_terminal.writeln(`Reconnected at ${moment().format('DD-MMM-YYYY')} at ${moment().format('hh:mm A')}`)
_terminal.writeln('---------------------------------------------')
setIsReconnection(false)
}
}
_socket.onmessage = function (evt) {
_terminal.write(JSON.parse(evt.data).Data)
enableInput()
if (!firstMessageReceived) {
setFirstMessageReceived(true)
}
}
_socket.onclose = function (evt) {
if (window._env_.LOG_TERMINAL_EVENTS_TO_SENTRY && evt.reason !== 'Normal closure') logExceptionToSentry(evt)
disableInput()
_terminal.writeln('')
_terminal.writeln('---------------------------------------------')
_terminal.writeln(`Disconnected at ${moment().format('DD-MMM-YYYY')} at ${moment().format('hh:mm A')}`)
_terminal.writeln('---------------------------------------------')
setSocketConnection(SocketConnectionType.DISCONNECTED)
}
_socket.onerror = function (evt) {
disableInput()
setSocketConnection(SocketConnectionType.DISCONNECTED)
}
}
useEffect(() => {
if (firstMessageReceived) {
if (isTerminalTab) {
fitAddon.current?.fit()
}
terminalRef.current.setOption('cursorBlink', true)
setSocketConnection(SocketConnectionType.CONNECTED)
}
}, [firstMessageReceived, isTerminalTab])
useEffect(() => {
if (!window.location.origin) {
// Some browsers (mainly IE) do not have this property, so we need to build it manually...
// @ts-ignore
window.location.origin = `${window.location.protocol}//${
window.location.hostname
}${window.location.port ? `:${window.location.port}` : ''}`
}
setSocketConnection(SocketConnectionType.CONNECTING)
return () => {
socket.current?.close()
terminalRef.current?.dispose()
socket.current = undefined
terminalRef.current = undefined
terminalRef.current = undefined
fitAddon.current = null
clearTimeout(clusterTimeOut)
}
}, [])
useEffect(() => {
if (terminalRef.current) {
terminalRef.current.clear()
terminalRef.current.focus()
}
}, [clearTerminal])
return (
<div className="terminal-wrapper" data-testid={dataTestId}>
{renderConnectionStrip()}
<div
ref={myDivRef}
id="terminal-id"
data-testid="terminal-editor-container"
className="mt-8 mb-4 terminal-component ml-20"
>
<CopyToast showCopyToast={popupText} />
</div>
</div>
)
}