aboutsummaryrefslogtreecommitdiffstats
path: root/src/App.js
blob: cdc2997a9784512721781494357bb0bc4a903fab (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
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
import React from 'react';
import { InputGroup } from 'reactstrap';
import ResizeObserver from "react-resize-observer";
import { ToggleSlider } from 'react-toggle-slider';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import { ThemeContext, themes } from './theme';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSun, faMoon } from '@fortawesome/free-solid-svg-icons';
import './App.css';
import './xterm.css';

function App() {
  const [darkMode, setDarkMode] = React.useState(true);

  return (
    <div className='App'>
      <header className='App-header'>
        <InputGroup>
          <ThemeContext.Consumer>
            {({ changeTheme }) => (
              <div className='toggle-slider'>
                <FontAwesomeIcon icon={faSun} size='xl' />
                <ToggleSlider
                  onToggle={() => {
                    setDarkMode(!darkMode);
                    changeTheme(darkMode ? themes.light : themes.dark);
                  }}
                />
                <FontAwesomeIcon icon={faMoon} size='xl' />
              </div>
            )}

          </ThemeContext.Consumer>
        </InputGroup>
        <TerminalComponent />
        <Sidebar />
      </header>
    </div>
  );
}

class TerminalComponent extends React.Component {
  constructor(props) {
    super(props);
    this.fitAddon = new FitAddon();
    this.term = new Terminal({
      screenKeys: true,
      useStyle: true,
      cursorBlink: true,
      fontSize: 18,
      fontWeight: 900,
      fontFamily: `'Fira Mono', monospace`,
      theme: {
        foreground: "#fff",
        background: "#000",
        cursor: "#fff",
        cursorAccent: "#000",
        selection: "#fff",
      },
    });
    this.command = "";
  }

  componentDidMount() {
    this.encoder = new TextEncoder();
    this.decoder = new TextDecoder();
    this.socket = new WebSocket('ws://localhost:8000/ws');
    this.socket.binaryType = 'arraybuffer';

    function ab2str(buf) {
      return String.fromCharCode.apply(null, new Uint8Array(buf));
    }

    this.term.loadAddon(this.fitAddon);
    this.term.open(document.getElementById("xterm"));
    this.fitAddon.fit();

    // Terminal events
    this.term.onData((data) => {
      //this.socket.send(this.encoder.encode("\x00" + data));

      switch (data) {  
        // text is Enter
            case '\r':
            if (this.command === "clear") {
                  this.term.clear();
                }
                else {
                  handleSend(this.encoder.encode("\x00" + this.command));
                }
                this.term.write("\r\n$ ");
                this.command = "";
                break;

            // text is Backspace
            case '\u007F':
                if (this.command.length > 0) {
                  this.command = this.command.substring(0, this.command.length - 1);
                  this.term.write('\b \b');
                }
                break;
            
            // text is Ctrl+C
            case '\u0003': // we don't want to send ctrl+c to the server
              //this.term.write('^C');
              break;

            default:
              this.command += data;
              this.term.write(data);
              // if ((data <= String.fromCharCode(0x7B) && data.String.fromCharCode(0x20)) || data >= '\u00a0') {
              // }
                break;
      }
    });

    this.term.onResize((evt) => {
      //this.socket.send(this.encoder.encode("\x01" + JSON.stringify({ cols: evt.cols, rows: evt.rows })))
      handleSend(this.encoder.encode("\x01" + JSON.stringify({ cols: evt.cols, rows: evt.rows })));
    });

    this.term.onTitleChange((title) => {
      document.title = title;
    });
    

    // Socket events
    this.socket.onmessage = (evt) => {
      if (evt.data instanceof ArrayBuffer) {
        this.term.write(ab2str(evt.data.slice(1)));
      } else {
        alert(evt.data)
      }
    }
    this.socket.onclose = (evt) => {
      this.term.write("Session terminated\r\n$ ");
    }

    this.socket.onerror = (evt) => {
      if (typeof console.log == "function") {
        console.log(evt)
      }
    }

    const handleSend = (message) => {
      if (this.socket.readyState === WebSocket.OPEN) {
        // If the socket is open, go ahead and send message
        this.socket.send(message);
      }
      else if (this.socket.readyState === WebSocket.CONNECTING) {
        // If the socket is connecting, wait until it is open 
        // and try again
        this.socket.addEventListener('open', () => handleSend(message));
      }
    }

    this.fitAddon.fit();
  }

  render() {

    return (
      <div className="terminalContainer">
        <div id="xterm" style={{ height: "100%", width: "100%" }} />
        <ResizeObserver
          onResize={() => {
            this.fitAddon.fit();
          }}
        />
      </div>
    );
  }
}

class Sidebar extends React.Component {
  // a sidebar which can take you to other pages
  // constructor(props) {
  //   super(props);
  // }

  createTemplate(){
    // location.replace("index.html");
    console.log("create template");
  }
  toStudentView() {
    // location.replace("index.html");
    console.log("student view");
  }

  logOut() {
    // location.replace("index.html");
    console.log("log out");
  }

  render() {
    return (
      <div className="sidenav">
        <ul>
        <li><div class="sidenavButton" onClick={() => this.createTemplate()}>Create Template</div></li>
        <li><div class="sidenavButton" onClick={() => this.toStudentView()}>View as Student</div></li>
        <li><div class="sidenavButton" onClick={() => this.logOut()}>Log Out</div></li>
        </ul>
      </div>
    );
  }
    
}


export default App;