terminal.ui.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. let isFirstMessage = true;
  2. let user = '';
  3. let socket = null;
  4. $(function()
  5. {
  6. $.getLib([config.webRoot + 'js/xterm/xterm.js', config.webRoot + 'js/xterm/addon-fit.js'], {root: false}, function()
  7. {
  8. const rows = Math.floor((window.innerHeight - 5) / 17);
  9. terminal = new Terminal({cursorBlink: false, rows: rows});
  10. terminal.open(document.getElementById('terminal'));
  11. const fitAddon = new FitAddon.FitAddon();
  12. terminal.loadAddon(fitAddon);
  13. fitAddon.fit()
  14. terminal.focus();
  15. initWebsocket();
  16. terminal.onResize(e => {
  17. sendWebsocketMessage({"type": "resize", "rows": e.rows, "cols": e.cols});
  18. });
  19. terminal.onData(e => {
  20. sendWebsocketMessage({"type": "input", "input": e});
  21. });
  22. terminal.paste = function (text) {
  23. sendWebsocketMessage({"type": "input", "input": text});
  24. };
  25. });
  26. })
  27. function sendWebsocketMessage(data) {
  28. if (socket && socket.readyState === 1)
  29. {
  30. socket.send(JSON.stringify(data));
  31. }
  32. if (socket && socket.status === 403)
  33. {
  34. console.error('您没有权限');
  35. return false;
  36. }
  37. }
  38. function initWebsocket() {
  39. const rows = Math.floor((window.innerHeight - 5) / 17);
  40. const cols = Math.floor((window.innerWidth - 5) / 9);
  41. const url = webSocketURL + `&rows=${rows}&columns=${cols}`;
  42. socket = new WebSocket(url);
  43. socket.onclose = e => {
  44. let connectionError = instanceLang.errors.connectClosed;
  45. if(e.reason && instanceLang.errors.connectErrors[e.reason]) connectionError = instanceLang.errors.connectErrors[e.reason];
  46. zui.Modal.confirm({message: connectionError, icon:'icon-exclamation-sign', iconClass: 'warning-pale rounded-full icon-2x'}).then((res) =>
  47. {
  48. if(res)
  49. {
  50. window.location.reload();
  51. }
  52. else
  53. {
  54. window.close();
  55. }
  56. });
  57. };
  58. socket.onerror = () => {
  59. zui.Modal.alert({message: instanceLang.errors.connectFailed, icon:'icon-exclamation-sign', iconClass: 'warning-pale rounded-full icon-2x'}).then(function(){window.close();});
  60. };
  61. socket.addEventListener('message', function (event) {
  62. const response = atob(event.data);
  63. terminal.write(decodeURIComponent(escape(response)));
  64. });
  65. }