page8.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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: 5000,
  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. connectSSH();
  23. sshTerm.onData(data => {
  24. if (sshWS?.readyState === WebSocket.OPEN) {
  25. sshWS.send(JSON.stringify({
  26. type: "input",
  27. data: data
  28. }));
  29. }
  30. });
  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 = resizeSSH;
  39. sshWS.onmessage = e => {
  40. sshTerm?.write(e.data);
  41. };
  42. sshWS.onclose = () => {
  43. sshWS = null;
  44. sshTerm.write(
  45. "\r\n\x1b[33m[Connection closed]\x1b[0m\r\n"
  46. );
  47. };
  48. }
  49. function resizeSSH() {
  50. if (!sshFit || !sshTerm) {
  51. return;
  52. }
  53. clearTimeout(sshResizeTimer);
  54. sshResizeTimer = setTimeout(() => {
  55. sshFit.fit();
  56. if (sshWS?.readyState === WebSocket.OPEN) {
  57. sshWS.send(JSON.stringify({
  58. type: "resize",
  59. cols: sshTerm.cols,
  60. rows: sshTerm.rows
  61. }));
  62. }
  63. }, 100);
  64. }
  65. function exitPage8() {
  66. window.removeEventListener(
  67. "resize",
  68. resizeSSH
  69. );
  70. clearTimeout(sshResizeTimer);
  71. sshWS?.close();
  72. sshWS = null;
  73. sshTerm?.dispose();
  74. sshTerm = null;
  75. sshFit = null;
  76. }