page8.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. let sshTerm = null;
  2. let sshFit = null;
  3. let sshWS = null;
  4. let sshResizeTimer = null;
  5. function initPage8() {
  6. const el = document.getElementById("ssh-terminal");
  7. if (!el || sshTerm) {
  8. return;
  9. }
  10. sshTerm = new Terminal({
  11. cursorBlink: true,
  12. scrollback: 2000,
  13. fontSize: 14,
  14. convertEol: true,
  15. theme: {
  16. background: "#111111"
  17. }
  18. });
  19. sshFit = new FitAddon.FitAddon();
  20. sshTerm.loadAddon(sshFit);
  21. sshTerm.open(el);
  22. sshTerm.focus();
  23. connectSSH();
  24. sshTerm.onData(data => {
  25. if (sshWS?.readyState === WebSocket.OPEN) {
  26. sshWS.send(JSON.stringify({
  27. type: "input",
  28. data: data
  29. }));
  30. }
  31. });
  32. window.addEventListener("resize", resizeSSH);
  33. resizeSSH();
  34. }
  35. function connectSSH() {
  36. sshWS = new WebSocket(
  37. "ws://" + location.host + "/api/ssh/ws"
  38. );
  39. sshWS.onopen = resizeSSH;
  40. sshWS.onmessage = e => {
  41. sshTerm?.write(e.data);
  42. };
  43. sshWS.onclose = () => {
  44. sshWS = null;
  45. sshTerm.write(
  46. "\r\n\x1b[33m[Connection closed]\x1b[0m\r\n"
  47. );
  48. };
  49. }
  50. function resizeSSH() {
  51. if (!sshFit || !sshTerm) {
  52. return;
  53. }
  54. clearTimeout(sshResizeTimer);
  55. sshResizeTimer = setTimeout(() => {
  56. sshFit.fit();
  57. if (sshWS?.readyState === WebSocket.OPEN) {
  58. sshWS.send(JSON.stringify({
  59. type: "resize",
  60. cols: sshTerm.cols,
  61. rows: sshTerm.rows
  62. }));
  63. }
  64. }, 100);
  65. }
  66. function exitPage8() {
  67. window.removeEventListener(
  68. "resize",
  69. resizeSSH
  70. );
  71. clearTimeout(sshResizeTimer);
  72. sshWS?.close();
  73. sshWS = null;
  74. sshTerm?.dispose();
  75. sshTerm = null;
  76. sshFit = null;
  77. }