page8.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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.onopen = () => {
  39. resizeSSH();
  40. sshTerm?.focus();
  41. };
  42. sshWS.onmessage = e => {
  43. sshTerm?.write(e.data);
  44. };
  45. sshWS.onclose = () => {
  46. sshWS = null;
  47. sshTerm?.write(
  48. "\r\n\x1b[33m[Connection closed]\x1b[0m\r\n"
  49. );
  50. };
  51. }
  52. function resizeSSH() {
  53. if (!sshFit || !sshTerm) {
  54. return;
  55. }
  56. clearTimeout(sshResizeTimer);
  57. sshResizeTimer = null;
  58. sshResizeTimer = setTimeout(() => {
  59. if (!sshTerm || !sshFit) {
  60. return;
  61. }
  62. sshFit.fit();
  63. if (sshWS?.readyState === WebSocket.OPEN) {
  64. sshWS.send(JSON.stringify({
  65. type: "resize",
  66. cols: sshTerm.cols,
  67. rows: sshTerm.rows
  68. }));
  69. }
  70. },100);
  71. }
  72. function exitPage8() {
  73. window.removeEventListener(
  74. "resize",
  75. resizeSSH
  76. );
  77. clearTimeout(sshResizeTimer);
  78. if (sshWS) {
  79. sshWS.onclose = null;
  80. sshWS.close();
  81. sshWS = null;
  82. }
  83. sshTerm?.dispose();
  84. sshTerm = null;
  85. sshFit = null;
  86. }