2018-05-09 12:01:36 +05:30
|
|
|
import $ from 'jquery';
|
2018-11-18 11:00:15 +05:30
|
|
|
import { Terminal } from 'xterm';
|
|
|
|
import * as fit from 'xterm/lib/addons/fit/fit';
|
2018-05-09 12:01:36 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
export default class GLTerminal {
|
|
|
|
constructor(options = {}) {
|
|
|
|
this.options = Object.assign({}, {
|
|
|
|
cursorBlink: true,
|
|
|
|
screenKeys: true,
|
|
|
|
}, options);
|
2018-03-27 19:54:05 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.container = document.querySelector(options.selector);
|
2018-03-27 19:54:05 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.setSocketUrl();
|
|
|
|
this.createTerminal();
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
$(window)
|
|
|
|
.off('resize.terminal')
|
|
|
|
.on('resize.terminal', () => {
|
2017-08-17 22:00:37 +05:30
|
|
|
this.terminal.fit();
|
|
|
|
});
|
2018-11-18 11:00:15 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
setSocketUrl() {
|
|
|
|
const { protocol, hostname, port } = window.location;
|
|
|
|
const wsProtocol = protocol === 'https:' ? 'wss://' : 'ws://';
|
|
|
|
const path = this.container.dataset.projectPath;
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.socketUrl = `${wsProtocol}${hostname}:${port}${path}`;
|
|
|
|
}
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
createTerminal() {
|
|
|
|
Terminal.applyAddon(fit);
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.terminal = new Terminal(this.options);
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.socket = new WebSocket(this.socketUrl, ['terminal.gitlab.com']);
|
|
|
|
this.socket.binaryType = 'arraybuffer';
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.terminal.open(this.container);
|
|
|
|
this.terminal.fit();
|
|
|
|
this.terminal.focus();
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.socket.onopen = () => {
|
|
|
|
this.runTerminal();
|
|
|
|
};
|
|
|
|
this.socket.onerror = () => {
|
|
|
|
this.handleSocketFailure();
|
|
|
|
};
|
|
|
|
}
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
runTerminal() {
|
|
|
|
const decoder = new TextDecoder('utf-8');
|
|
|
|
const encoder = new TextEncoder('utf-8');
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.terminal.on('data', data => {
|
|
|
|
this.socket.send(encoder.encode(data));
|
|
|
|
});
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.socket.addEventListener('message', ev => {
|
|
|
|
this.terminal.write(decoder.decode(ev.data));
|
|
|
|
});
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
this.isTerminalInitialized = true;
|
|
|
|
this.terminal.fit();
|
2017-08-17 22:00:37 +05:30
|
|
|
}
|
|
|
|
|
2018-11-18 11:00:15 +05:30
|
|
|
handleSocketFailure() {
|
|
|
|
this.terminal.write('\r\nConnection failure');
|
|
|
|
}
|
|
|
|
}
|