Skip to content

Commit

Permalink
html: add tslint to webpack
Browse files Browse the repository at this point in the history
  • Loading branch information
tsl0922 committed May 17, 2019
1 parent ccea4d2 commit 2aa2035
Show file tree
Hide file tree
Showing 8 changed files with 315 additions and 98 deletions.
60 changes: 30 additions & 30 deletions html/js/app.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import '../sass/app.scss';

import { Terminal, ITerminalOptions, IDisposable } from 'xterm';
import * as fit from 'xterm/lib/addons/fit/fit'
import * as fit from 'xterm/lib/addons/fit/fit';
import * as Zmodem from 'zmodem.js/src/zmodem_browser';

import * as overlay from './overlay'
import { Modal } from './zmodem'
import * as overlay from './overlay';
import { Modal } from './zmodem';

Terminal.applyAddon(fit);
Terminal.applyAddon(overlay);
Expand All @@ -28,31 +28,31 @@ declare let window: IWindowWithTerminal;

const modal = new Modal();
const terminalContainer = document.getElementById('terminal-container');
const protocol = window.location.protocol === 'https:' ? 'wss://': 'ws://';
const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
const wsPath = window.location.pathname.endsWith('/') ? 'ws' : '/ws';
const url = [protocol, window.location.host, window.location.pathname, wsPath, window.location.search].join('');
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();

let authToken = (typeof window.tty_auth_token !== 'undefined') ? window.tty_auth_token : null;
const authToken = (typeof window.tty_auth_token !== 'undefined') ? window.tty_auth_token : null;
let autoReconnect = -1;
let term: ITtydTerminal;
let title: string;
let wsError: boolean;

let openWs = function() {
let ws = new WebSocket(url, ['tty']);
let sendMessage = function (message) {
const openWs = function(): void {
const ws = new WebSocket(url, ['tty']);
const sendMessage = function (message: string): void {
if (ws.readyState === WebSocket.OPEN) {
ws.send(textEncoder.encode(message));
}
};
let unloadCallback = function (event) {
let message = 'Close terminal? this will also terminate the command.';
const unloadCallback = function (event: BeforeUnloadEvent): string {
const message = 'Close terminal? this will also terminate the command.';
event.returnValue = message;
return message;
};
let resetTerm = function() {
const resetTerm = function(): void {
modal.hide();
clearTimeout(term.reconnectTimeout);
if (ws.readyState !== WebSocket.CLOSED) {
Expand All @@ -61,31 +61,31 @@ let openWs = function() {
openWs();
};

let zsentry = new Zmodem.Sentry({
to_terminal: function _to_terminal(octets) {
let buffer = new Uint8Array(octets).buffer;
const zsentry = new Zmodem.Sentry({
to_terminal: function(octets: ArrayBuffer): any {
const buffer = new Uint8Array(octets).buffer;
term.write(textDecoder.decode(buffer));
},

sender: function _ws_sender_func(octets) {
sender: function(octets: number[]): any {
// limit max packet size to 4096
while (octets.length) {
let chunk = octets.splice(0, 4095);
let buffer = new Uint8Array(chunk.length + 1);
buffer[0]= '0'.charCodeAt(0);
const chunk = octets.splice(0, 4095);
const buffer = new Uint8Array(chunk.length + 1);
buffer[0] = '0'.charCodeAt(0);
buffer.set(chunk, 1);
ws.send(buffer);
}
},

on_retract: function _on_retract() {
on_retract: function(): any {
// console.log('on_retract');
},

on_detect: function _on_detect(detection) {
on_detect: function(detection: any): any {
term.setOption('disableStdin', true);
let zsession = detection.confirm();
let promise = zsession.type === 'send' ? modal.handleSend(zsession) : modal.handleReceive(zsession);
const zsession = detection.confirm();
const promise = zsession.type === 'send' ? modal.handleSend(zsession) : modal.handleReceive(zsession);
promise.catch(console.error.bind(console)).then(() => {
modal.hide();
term.setOption('disableStdin', false);
Expand All @@ -95,7 +95,7 @@ let openWs = function() {

ws.binaryType = 'arraybuffer';

ws.onopen = function() {
ws.onopen = function(): void {
console.log('[ttyd] websocket opened');
wsError = false;
sendMessage(JSON.stringify({AuthToken: authToken}));
Expand Down Expand Up @@ -163,11 +163,11 @@ let openWs = function() {
term.focus();
};

ws.onmessage = function(event: MessageEvent) {
let rawData = new Uint8Array(event.data),
cmd = String.fromCharCode(rawData[0]),
data = rawData.slice(1).buffer;
switch(cmd) {
ws.onmessage = function(event: MessageEvent): void {
const rawData = new Uint8Array(event.data);
const cmd = String.fromCharCode(rawData[0]);
const data = rawData.slice(1).buffer;
switch (cmd) {
case '0':
try {
zsentry.consume(data);
Expand All @@ -181,7 +181,7 @@ let openWs = function() {
document.title = title;
break;
case '2':
let preferences = JSON.parse(textDecoder.decode(data));
const preferences = JSON.parse(textDecoder.decode(data));
Object.keys(preferences).forEach((key) => {
console.log('[ttyd] xterm option: ' + key + '=' + preferences[key]);
term.setOption(key, preferences[key]);
Expand All @@ -197,7 +197,7 @@ let openWs = function() {
}
};

ws.onclose = function(event: CloseEvent) {
ws.onclose = function(event: CloseEvent): void {
console.log('[ttyd] websocket closed, code: ' + event.code);
modal.hide();
if (term) {
Expand Down
23 changes: 14 additions & 9 deletions html/js/overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
import { Terminal } from 'xterm';

interface IOverlayAddonTerminal extends Terminal {
__overlayNode?: HTMLElement
__overlayTimeout?: number
__overlayNode?: HTMLElement;
__overlayTimeout?: number;
}

export function showOverlay(term: Terminal, msg: string, timeout: number): void {
const addonTerminal = <IOverlayAddonTerminal> term;
if (!addonTerminal.__overlayNode) {
if (!term.element)
if (!term.element) {
return;
}
addonTerminal.__overlayNode = document.createElement('div');
addonTerminal.__overlayNode.style.cssText = (
'border-radius: 15px;' +
Expand All @@ -29,32 +30,36 @@ export function showOverlay(term: Terminal, msg: string, timeout: number): void
e.stopPropagation();
}, true);
}
addonTerminal.__overlayNode.style.color = "#101010";
addonTerminal.__overlayNode.style.backgroundColor = "#f0f0f0";
addonTerminal.__overlayNode.style.color = '#101010';
addonTerminal.__overlayNode.style.backgroundColor = '#f0f0f0';

addonTerminal.__overlayNode.textContent = msg;
addonTerminal.__overlayNode.style.opacity = '0.75';

if (!addonTerminal.__overlayNode.parentNode)
if (!addonTerminal.__overlayNode.parentNode) {
term.element.appendChild(addonTerminal.__overlayNode);
}

const divSize = term.element.getBoundingClientRect();
const overlaySize = addonTerminal.__overlayNode.getBoundingClientRect();

addonTerminal.__overlayNode.style.top = (divSize.height - overlaySize.height) / 2 + 'px';
addonTerminal.__overlayNode.style.left = (divSize.width - overlaySize.width) / 2 + 'px';

if (addonTerminal.__overlayTimeout)
if (addonTerminal.__overlayTimeout) {
clearTimeout(addonTerminal.__overlayTimeout);
}

if (timeout === null)
if (timeout === null) {
return;
}

addonTerminal.__overlayTimeout = <number><any>setTimeout(() => {
addonTerminal.__overlayNode.style.opacity = '0';
addonTerminal.__overlayTimeout = <number><any>setTimeout(() => {
if (addonTerminal.__overlayNode.parentNode)
if (addonTerminal.__overlayNode.parentNode) {
addonTerminal.__overlayNode.parentNode.removeChild(addonTerminal.__overlayNode);
}
addonTerminal.__overlayTimeout = null;
addonTerminal.__overlayNode.style.opacity = '0.75';
}, 200);
Expand Down
42 changes: 21 additions & 21 deletions html/js/zmodem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ function bytesHuman (bytes: any, precision: number): string {
if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-';
if (bytes === 0) return '0';
if (typeof precision === 'undefined') precision = 1;
let units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'],
number = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number];
const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
const num = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, Math.floor(num))).toFixed(precision) + ' ' + units[num];
}

export class Modal {
Expand All @@ -69,7 +69,7 @@ export class Modal {
this.progress = new Progress();
}

public reset(title): void {
public reset(title: string): void {
this.header.textContent = title;
this.status.element.style.display = 'none';
this.choose.element.style.display = 'none';
Expand All @@ -85,7 +85,7 @@ export class Modal {
this.element.classList.remove('is-active');
}

public updateFileInfo(fileInfo): void {
public updateFileInfo(fileInfo: any): void {
this.status.element.style.display = '';
this.choose.element.style.display = 'none';
this.progress.element.style.display = '';
Expand All @@ -94,29 +94,29 @@ export class Modal {
this.progress.fileName.textContent = fileInfo.name;
}

public showReceive(xfer): void {
public showReceive(xfer: any): void {
this.reset('Receiving files');
this.updateFileInfo(xfer.get_details());
this.progress.skip.disabled = false;
this.progress.skip.onclick = function () {
this.progress.skip.onclick = function (): void {
(<HTMLLinkElement>this).disabled = true;
xfer.skip();
};
this.progress.skip.style.display = '';
this.element.classList.add('is-active');
}

public showSend(callback): void {
public showSend(callback: (files: FileList) => any): void {
this.reset('Sending files');
this.choose.element.style.display = '';
this.choose.files.disabled = false;
this.choose.files.value = '';
this.choose.filesNames.textContent = '';
let self:Modal = this;
this.choose.files.onchange = function () {
const self: Modal = this;
this.choose.files.onchange = function (): void {
(<HTMLInputElement>this).disabled = true;
let files:FileList = (<HTMLInputElement>this).files;
let fileNames:string = '';
const files: FileList = (<HTMLInputElement>this).files;
let fileNames: string = '';
for (let i = 0; i < files.length; i++) {
if (i === 0) {
fileNames = files[i].name;
Expand All @@ -130,20 +130,20 @@ export class Modal {
this.element.classList.add('is-active');
}

public updateProgress(xfer): void {
let size = xfer.get_details().size;
let offset = xfer.get_offset();
public updateProgress(xfer: any): void {
const size = xfer.get_details().size;
const offset = xfer.get_offset();
this.progress.bytesReceived.textContent = bytesHuman(offset, 2);
this.progress.bytesFile.textContent = bytesHuman(size, 2);

let percentReceived = (100 * offset / size).toFixed(2);
const percentReceived = (100 * offset / size).toFixed(2);
this.progress.percentReceived.textContent = percentReceived + '%';

this.progress.progressBar.textContent = percentReceived + '%';
this.progress.progressBar.setAttribute('value', percentReceived);
}

public handleSend(zsession): Promise<any> {
public handleSend(zsession: any): Promise<any> {
return new Promise((res) => {
this.showSend((files) => {
Zmodem.Browser.send_files(
Expand All @@ -166,10 +166,10 @@ export class Modal {
});
}

public handleReceive(zsession): Promise<any> {
public handleReceive(zsession: any): Promise<any> {
zsession.on('offer', (xfer) => {
this.showReceive(xfer);
let fileBuffer = [];
const fileBuffer = [];
xfer.on('input', (payload) => {
this.updateProgress(xfer);
fileBuffer.push(new Uint8Array(payload));
Expand All @@ -181,10 +181,10 @@ export class Modal {
);
}, console.error.bind(console));
});
let promise = new Promise((res) => {
const promise = new Promise((res) => {
zsession.on('session_end', () => res());
});
zsession.start();
return promise;
}
}
}
11 changes: 7 additions & 4 deletions html/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
"author": "Shuanglei Tao <tsl0922@gmail.com>",
"license": "MIT",
"scripts": {
"build": "NODE_ENV=production npx wp --config webpack.prod.js && gulp",
"start": "gulp clean && npx webpack-dev-server --config webpack.dev.js"
"build": "NODE_ENV=production webpack --config webpack.prod.js && gulp",
"prestart": "gulp clean",
"start": "webpack-dev-server --config webpack.dev.js"
},
"dependencies": {
"xterm": "^3.13.0",
Expand All @@ -32,11 +33,13 @@
"style-loader": "^0.23.1",
"terser-webpack-plugin": "^1.2.4",
"ts-loader": "^6.0.0",
"tslint": "^5.16.0",
"tslint-consistent-codestyle": "^1.15.1",
"tslint-loader": "^3.5.4",
"typescript": "^3.4.5",
"webpack": "^4.31.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1",
"webpack-merge": "^4.2.1",
"webpack-nano": "^0.6.2"
"webpack-merge": "^4.2.1"
}
}
Loading

0 comments on commit 2aa2035

Please sign in to comment.