File size: 1,332 Bytes
5ac74dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
document.addEventListener('DOMContentLoaded', () => {
  const term = new Terminal({
    cursorBlink: true,
    theme: {
      background: '#000000', // Ensure terminal background is black
    },
  });
  const fitAddon = new FitAddon.FitAddon();
  term.loadAddon(fitAddon);
  term.open(document.getElementById('terminal'));
  term.write('Connecting to server...\r\n');

  // Connect to WebSocket server
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const ws = new WebSocket(`${protocol}//${window.location.host}/`);

  ws.onopen = () => {
    console.log('Connected to WebSocket server');
    term.write('Connected! Type commands below.\r\n');
    fitAddon.fit(); // Fit terminal to container on connection
  };

  ws.onmessage = (event) => {
    term.write(event.data);
  };

  term.onData((data) => {
    ws.send(data);
  });

  ws.onclose = () => {
    console.log('WebSocket connection closed');
    term.write('\r\nConnection closed.\r\n');
  };

  ws.onerror = (error) => {
    console.error('WebSocket error:', error);
    term.write('\r\nWebSocket error occurred.\r\n');
  };

  // Resize terminal on window resize
  window.addEventListener('resize', () => {
    fitAddon.fit();
  });

  // Initial fit after opening terminal
  fitAddon.fit();
});