frontend-tutorial-framework/src/app/services/terminado.service.ts

68 lines
2.1 KiB
TypeScript

import { Injectable } from '@angular/core';
import { Terminal } from 'xterm';
import * as fit from 'xterm/lib/addons/fit/fit';
import * as terminado from 'xterm/lib/addons/terminado/terminado';
@Injectable()
export class TerminadoService {
xterm: Terminal;
ws: WebSocket;
attached = false;
constructor() {
Terminal.applyAddon(fit);
Terminal.applyAddon(terminado);
this.xterm = new Terminal({
theme: {
foreground: '#ffffff',
background: '#0C0C0C', // $tao-gray-800
cursor: '#ffffff',
selection: 'rgba(255, 255, 255, 0.3)',
black: '#000000',
red: '#FF5252', // $tao-red-500
brightRed: '#FF7171', // $tao-red-400
green: '#2fd19f', // $tao-bright-green-500
brightGreen: '#2fd19f', // $tao-bright-green-500
brightYellow: '#FFD283', // $tao-warm-yellow-300
yellow: '#FFB83B', // $tao-warm-yellow-500
magenta: '#FF8FC6', // $tao-pink-200
brightMagenta: '#FF8FC6', // $tao-pink-200
cyan: '#277EEC', // $tao-blue-500
blue: '#277EEC', // $tao-blue-500
brightCyan: '#42B7DF', // $tao-sky-400
brightBlue: '#19A7D8', // $tao-sky-500
white: '#FAFAFA', // $tao-gray-50
brightBlack: '#808080',
brightWhite: '#ffffff'
},
fontSize: 14
});
const wsproto = (location.protocol === 'https:') ? 'wss://' : 'ws://';
this.ws = new WebSocket(wsproto + window.location.host + '/terminal');
}
attach(element: HTMLElement) {
this.ws.onopen = () => {
(<any>this.xterm).terminadoAttach(this.ws);
this.xterm.open(element);
this.fit();
this.xterm.blur();
this.attached = true;
};
}
detach() {
(<any>this.xterm).terminadoDetach(this.ws);
this.xterm.destroy();
this.ws.close();
this.attached = false;
}
fit() {
if (this.attached) {
(<any>this.xterm).fit();
}
}
}