summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/terminal/terminal.js.es6
blob: 67435aa3db0a3915c0f31bcc22d404bbacaa9525 (plain)
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
window.gl = window.gl || {};

gl.Terminal = class {

  constructor(options) {
    this.options = options || {};

    options.cursorBlink = options.cursorBlink || true;
    options.screenKeys  = options.screenKeys || true;
    options.cols = options.cols || 100;
    options.rows = options.rows || 40;
    this.container = document.querySelector(options.selector);

    this.setSocketUrl();
    this.createTerminal();
  }

  setSocketUrl() {
    const {protocol, hostname, port} = window.location;
    const wsProtocol = protocol === 'https:' ? 'wss://' : 'ws://';

    this.socketUrl = `${wsProtocol}${hostname}:${port}/gitlab-org/gitlab-ce/deployments/4/terminal_websocket`
  }

  createTerminal() {
    this.terminal = new Terminal(this.options);
    this.socket = new WebSocket(this.socketUrl);

    this.terminal.open(this.container);
    this.terminal.fit();

    this.socket.onopen = () => { this.runTerminal() };
    this.socket.onclose = () => { this.handleSocketFailure() };
    this.socket.onerror = () => { this.handleSocketFailure() };
  }

  runTerminal() {
    const {cols, rows} = this.terminal.proposeGeometry();
    const {offsetWidth, offsetHeight} = this.terminal.element;

    this.charWidth = Math.ceil(offsetWidth / cols);
    this.charHeight = Math.ceil(offsetHeight / rows);

    this.terminal.attach(this.socket);
    this.isTerminalInitialized = true;
    this.setTerminalSize(cols, rows);
  }

  setTerminalSize (cols, rows) {
    const width = `${(cols * this.charWidth).toString()}px`;
    const height = `${(rows * this.charHeight).toString()}px`;

    this.container.style.width = width;
    this.container.style.height = height;
    this.terminal.resize(cols, rows);
  }

  handleSocketFailure() {
    console.error('There is a problem with Terminal connection. Please try again!');
  }

}