page8.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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.onData(data => {
  23. if (sshWS?.readyState === WebSocket.OPEN) {
  24. sshWS.send(JSON.stringify({
  25. type: "input",
  26. data: data
  27. }));
  28. }
  29. });
  30. connectSSH();
  31. window.addEventListener("resize", resizeSSH);
  32. resizeSSH();
  33. }
  34. function connectSSH() {
  35. sshWS = new WebSocket(
  36. "ws://" + location.host + "/api/ssh/ws"
  37. );
  38. sshWS.binaryType = "arraybuffer";
  39. sshWS.onopen = () => {
  40. resizeSSH();
  41. sshTerm?.focus();
  42. };
  43. sshWS.onmessage = e => {
  44. sshTerm?.write(new Uint8Array(e.data));
  45. };
  46. sshWS.onclose = () => {
  47. sshWS = null;
  48. sshTerm?.write(
  49. "\r\n\x1b[33m[Connection closed]\x1b[0m\r\n"
  50. );
  51. };
  52. }
  53. function resizeSSH() {
  54. if (!sshFit || !sshTerm) {
  55. return;
  56. }
  57. clearTimeout(sshResizeTimer);
  58. sshResizeTimer = null;
  59. sshResizeTimer = setTimeout(() => {
  60. if (!sshTerm || !sshFit) {
  61. return;
  62. }
  63. sshFit.fit();
  64. if (sshWS?.readyState === WebSocket.OPEN) {
  65. sshWS.send(JSON.stringify({
  66. type: "resize",
  67. cols: sshTerm.cols,
  68. rows: sshTerm.rows
  69. }));
  70. }
  71. },100);
  72. }
  73. function exitPage8() {
  74. window.removeEventListener(
  75. "resize",
  76. resizeSSH
  77. );
  78. clearTimeout(sshResizeTimer);
  79. if (sshWS) {
  80. sshWS.onclose = null;
  81. sshWS.close();
  82. sshWS = null;
  83. }
  84. sshTerm?.dispose();
  85. sshTerm = null;
  86. sshFit = null;
  87. }