Use fat arrow functions `const foo = () => { ... };` for callbacks

and any other function that is passed around and it's not a top level function
This commit is contained in:
Juanjo Diaz 2018-07-09 22:47:29 +02:00
parent 0e4808bf6f
commit 651c23ece3
28 changed files with 177 additions and 191 deletions

View File

@ -13,5 +13,10 @@
"no-var": "error", "no-var": "error",
"no-useless-constructor": "error", "no-useless-constructor": "error",
"object-shorthand": ["error", "methods", { "avoidQuotes": true }], "object-shorthand": ["error", "methods", { "avoidQuotes": true }],
"prefer-arrow-callback": "error",
"arrow-body-style": ["error", "as-needed", { "requireReturnForObjectLiteral": false } ],
"arrow-parens": ["error", "as-needed", { "requireForBlockBody": true }],
"arrow-spacing": ["error"],
"no-confusing-arrow": ["error", { "allowParens": true }],
} }
} }

View File

@ -2,7 +2,10 @@
// native support in the browsers, so that our error handler // native support in the browsers, so that our error handler
// can catch script-loading errors. // can catch script-loading errors.
(function(){ // No ES6 can be used in this file since it's used for the translation
/* eslint-disable prefer-arrow-callback */
(function() {
"use strict"; "use strict";
// Fallback for all uncought errors // Fallback for all uncought errors

View File

@ -71,7 +71,7 @@ const UI = {
if (isTouchDevice) { if (isTouchDevice) {
document.documentElement.classList.add("noVNC_touch"); document.documentElement.classList.add("noVNC_touch");
// Remove the address bar // Remove the address bar
setTimeout(function() { window.scrollTo(0, 1); }, 100); setTimeout(() => window.scrollTo(0, 1), 100);
} }
// Restore control bar position // Restore control bar position
@ -230,13 +230,13 @@ const UI = {
addTouchSpecificHandlers() { addTouchSpecificHandlers() {
document.getElementById("noVNC_mouse_button0") document.getElementById("noVNC_mouse_button0")
.addEventListener('click', function () { UI.setMouseButton(1); }); .addEventListener('click', () => UI.setMouseButton(1));
document.getElementById("noVNC_mouse_button1") document.getElementById("noVNC_mouse_button1")
.addEventListener('click', function () { UI.setMouseButton(2); }); .addEventListener('click', () => UI.setMouseButton(2));
document.getElementById("noVNC_mouse_button2") document.getElementById("noVNC_mouse_button2")
.addEventListener('click', function () { UI.setMouseButton(4); }); .addEventListener('click', () => UI.setMouseButton(4));
document.getElementById("noVNC_mouse_button4") document.getElementById("noVNC_mouse_button4")
.addEventListener('click', function () { UI.setMouseButton(0); }); .addEventListener('click', () => UI.setMouseButton(0));
document.getElementById("noVNC_keyboard_button") document.getElementById("noVNC_keyboard_button")
.addEventListener('click', UI.toggleVirtualKeyboard); .addEventListener('click', UI.toggleVirtualKeyboard);
@ -250,7 +250,7 @@ const UI = {
document.getElementById("noVNC_keyboardinput") document.getElementById("noVNC_keyboardinput")
.addEventListener('blur', UI.onblurVirtualKeyboard); .addEventListener('blur', UI.onblurVirtualKeyboard);
document.getElementById("noVNC_keyboardinput") document.getElementById("noVNC_keyboardinput")
.addEventListener('submit', function () { return false; }); .addEventListener('submit', () => false);
document.documentElement document.documentElement
.addEventListener('mousedown', UI.keepVirtualKeyboard, true); .addEventListener('mousedown', UI.keepVirtualKeyboard, true);
@ -294,11 +294,11 @@ const UI = {
addMachineHandlers() { addMachineHandlers() {
document.getElementById("noVNC_shutdown_button") document.getElementById("noVNC_shutdown_button")
.addEventListener('click', function() { UI.rfb.machineShutdown(); }); .addEventListener('click', () => UI.rfb.machineShutdown());
document.getElementById("noVNC_reboot_button") document.getElementById("noVNC_reboot_button")
.addEventListener('click', function() { UI.rfb.machineReboot(); }); .addEventListener('click', () => UI.rfb.machineReboot());
document.getElementById("noVNC_reset_button") document.getElementById("noVNC_reset_button")
.addEventListener('click', function() { UI.rfb.machineReset(); }); .addEventListener('click', () => UI.rfb.machineReset());
document.getElementById("noVNC_power_button") document.getElementById("noVNC_power_button")
.addEventListener('click', UI.togglePowerPanel); .addEventListener('click', UI.togglePowerPanel);
}, },
@ -329,7 +329,7 @@ const UI = {
addSettingChangeHandler(name, changeFunc) { addSettingChangeHandler(name, changeFunc) {
const settingElem = document.getElementById("noVNC_setting_" + name); const settingElem = document.getElementById("noVNC_setting_" + name);
if (changeFunc === undefined) { if (changeFunc === undefined) {
changeFunc = function () { UI.saveSetting(name); }; changeFunc = () => UI.saveSetting(name);
} }
settingElem.addEventListener('change', changeFunc); settingElem.addEventListener('change', changeFunc);
}, },
@ -552,8 +552,7 @@ const UI = {
const barDisplayStyle = window.getComputedStyle(bar).display; const barDisplayStyle = window.getComputedStyle(bar).display;
if (barDisplayStyle !== 'none') { if (barDisplayStyle !== 'none') {
bar.style.transitionDuration = '0s'; bar.style.transitionDuration = '0s';
bar.addEventListener('transitionend', function () { bar.addEventListener('transitionend', () => bar.style.transitionDuration = '');
this.style.transitionDuration = ""; });
} }
const anchor = document.getElementById('noVNC_control_bar_anchor'); const anchor = document.getElementById('noVNC_control_bar_anchor');
@ -1029,7 +1028,7 @@ const UI = {
UI.rfb.addEventListener("disconnect", UI.disconnectFinished); UI.rfb.addEventListener("disconnect", UI.disconnectFinished);
UI.rfb.addEventListener("credentialsrequired", UI.credentials); UI.rfb.addEventListener("credentialsrequired", UI.credentials);
UI.rfb.addEventListener("securityfailure", UI.securityFailed); UI.rfb.addEventListener("securityfailure", UI.securityFailed);
UI.rfb.addEventListener("capabilities", function () { UI.updatePowerButton(); }); UI.rfb.addEventListener("capabilities", UI.updatePowerButton);
UI.rfb.addEventListener("clipboard", UI.clipboardReceive); UI.rfb.addEventListener("clipboard", UI.clipboardReceive);
UI.rfb.addEventListener("bell", UI.bell); UI.rfb.addEventListener("bell", UI.bell);
UI.rfb.addEventListener("desktopname", UI.updateDesktopName); UI.rfb.addEventListener("desktopname", UI.updateDesktopName);
@ -1153,9 +1152,8 @@ const UI = {
document.getElementById('noVNC_password_dlg') document.getElementById('noVNC_password_dlg')
.classList.add('noVNC_open'); .classList.add('noVNC_open');
setTimeout(function () { setTimeout(() => document
document.getElementById('noVNC_password_input').focus(); .getElementById('noVNC_password_input').focus(), 100);
}, 100);
Log.Warn("Server asked for a password"); Log.Warn("Server asked for a password");
UI.showStatus(_("Password is required"), "warning"); UI.showStatus(_("Password is required"), "warning");
@ -1624,7 +1622,7 @@ const UI = {
const promise = document.getElementById('noVNC_bell').play(); const promise = document.getElementById('noVNC_bell').play();
// The standards disagree on the return value here // The standards disagree on the return value here
if (promise) { if (promise) {
promise.catch(function(e) { promise.catch((e) => {
if (e.name === "NotAllowedError") { if (e.name === "NotAllowedError") {
// Ignore when the browser doesn't let us play audio. // Ignore when the browser doesn't let us play audio.
// It is common that the browsers require audio to be // It is common that the browsers require audio to be
@ -1655,12 +1653,12 @@ const UI = {
const LINGUAS = ["de", "el", "es", "nl", "pl", "sv", "tr", "zh_CN", "zh_TW"]; const LINGUAS = ["de", "el", "es", "nl", "pl", "sv", "tr", "zh_CN", "zh_TW"];
l10n.setup(LINGUAS); l10n.setup(LINGUAS);
if (l10n.language !== "en" && l10n.dictionary === undefined) { if (l10n.language !== "en" && l10n.dictionary === undefined) {
WebUtil.fetchJSON('app/locale/' + l10n.language + '.json', function (translations) { WebUtil.fetchJSON('app/locale/' + l10n.language + '.json', (translations) => {
l10n.dictionary = translations; l10n.dictionary = translations;
// wait for translations to load before loading the UI // wait for translations to load before loading the UI
UI.prime(); UI.prime();
}, function (err) { }, (err) => {
Log.Error("Failed to load translations: " + err); Log.Error("Failed to load translations: " + err);
UI.prime(); UI.prime();
}); });

View File

@ -119,7 +119,7 @@ export function initSettings (callback /*, ...callbackArgs */) {
"use strict"; "use strict";
const callbackArgs = Array.prototype.slice.call(arguments, 1); const callbackArgs = Array.prototype.slice.call(arguments, 1);
if (window.chrome && window.chrome.storage) { if (window.chrome && window.chrome.storage) {
window.chrome.storage.sync.get(function (cfg) { window.chrome.storage.sync.get((cfg) => {
settings = cfg; settings = cfg;
if (callback) { if (callback) {
callback.apply(this, callbackArgs); callback.apply(this, callbackArgs);
@ -201,7 +201,7 @@ export function injectParamIfMissing (path, param, value) {
query = []; query = [];
} }
if (!query.some(function (v) { return v.startsWith(param_eq); })) { if (!query.some(v => v.startsWith(param_eq))) {
query.push(param_eq + encodeURIComponent(value)); query.push(param_eq + encodeURIComponent(value));
elem.search = "?" + query.join("&"); elem.search = "?" + query.join("&");
} }
@ -224,7 +224,7 @@ export function fetchJSON(path, resolve, reject) {
const req = new XMLHttpRequest(); const req = new XMLHttpRequest();
req.open('GET', path); req.open('GET', path);
req.onload = function () { req.onload = () => {
if (req.status === 200) { if (req.status === 200) {
let resObj; let resObj;
try { try {
@ -238,13 +238,9 @@ export function fetchJSON(path, resolve, reject) {
} }
}; };
req.onerror = function (evt) { req.onerror = evt => reject(new Error("XHR encountered an error while trying to load '" + path + "': " + evt.message));
reject(new Error("XHR encountered an error while trying to load '" + path + "': " + evt.message));
};
req.ontimeout = function (evt) { req.ontimeout = evt => reject(new Error("XHR timed out while trying to load '" + path + "'"));
reject(new Error("XHR timed out while trying to load '" + path + "'"));
};
req.send(); req.send();
} }

View File

@ -307,7 +307,7 @@ export default class Keyboard {
const target = this._target; const target = this._target;
const downList = this._keyDownList; const downList = this._keyDownList;
['AltLeft', 'AltRight'].forEach(function (code) { ['AltLeft', 'AltRight'].forEach((code) => {
if (!(code in downList)) { if (!(code in downList)) {
return; return;
} }
@ -338,11 +338,10 @@ export default class Keyboard {
const handler = this._eventHandlers.checkalt; const handler = this._eventHandlers.checkalt;
['mousedown', 'mouseup', 'mousemove', 'wheel', ['mousedown', 'mouseup', 'mousemove', 'wheel',
'touchstart', 'touchend', 'touchmove', 'touchstart', 'touchend', 'touchmove',
'keydown', 'keyup'].forEach(function (type) { 'keydown', 'keyup'].forEach(type =>
document.addEventListener(type, handler, document.addEventListener(type, handler,
{ capture: true, { capture: true,
passive: true }); passive: true }));
});
} }
//Log.Debug("<< Keyboard.grab"); //Log.Debug("<< Keyboard.grab");
@ -355,9 +354,7 @@ export default class Keyboard {
const handler = this._eventHandlers.checkalt; const handler = this._eventHandlers.checkalt;
['mousedown', 'mouseup', 'mousemove', 'wheel', ['mousedown', 'mouseup', 'mousemove', 'wheel',
'touchstart', 'touchend', 'touchmove', 'touchstart', 'touchend', 'touchmove',
'keydown', 'keyup'].forEach(function (type) { 'keydown', 'keyup'].forEach(type => document.removeEventListener(type, handler));
document.removeEventListener(type, handler);
});
} }
this._target.removeEventListener('keydown', this._eventHandlers.keydown); this._target.removeEventListener('keydown', this._eventHandlers.keydown);

View File

@ -201,7 +201,7 @@ export default class RFB extends EventTargetMixin {
this._sock = new Websock(); this._sock = new Websock();
this._sock.on('message', this._handle_message.bind(this)); this._sock.on('message', this._handle_message.bind(this));
this._sock.on('open', function () { this._sock.on('open', () => {
if ((this._rfb_connection_state === 'connecting') && if ((this._rfb_connection_state === 'connecting') &&
(this._rfb_init_state === '')) { (this._rfb_init_state === '')) {
this._rfb_init_state = 'ProtocolVersion'; this._rfb_init_state = 'ProtocolVersion';
@ -210,8 +210,8 @@ export default class RFB extends EventTargetMixin {
this._fail("Unexpected server connection while " + this._fail("Unexpected server connection while " +
this._rfb_connection_state); this._rfb_connection_state);
} }
}.bind(this)); });
this._sock.on('close', function (e) { this._sock.on('close', (e) => {
Log.Debug("WebSocket on-close event"); Log.Debug("WebSocket on-close event");
let msg = ""; let msg = "";
if (e.code) { if (e.code) {
@ -244,10 +244,8 @@ export default class RFB extends EventTargetMixin {
break; break;
} }
this._sock.off('close'); this._sock.off('close');
}.bind(this));
this._sock.on('error', function (e) {
Log.Warn("WebSocket on-error event");
}); });
this._sock.on('error', e => Log.Warn("WebSocket on-error event"));
// Slight delay of the actual connection so that the caller has // Slight delay of the actual connection so that the caller has
// time to set up callbacks // time to set up callbacks
@ -459,7 +457,7 @@ export default class RFB extends EventTargetMixin {
const stats = this._encStats; const stats = this._encStats;
Log.Info("Encoding stats for this connection:"); Log.Info("Encoding stats for this connection:");
Object.keys(stats).forEach(function (key) { Object.keys(stats).forEach((key) => {
const s = stats[key]; const s = stats[key];
if (s[0] + s[1] > 0) { if (s[0] + s[1] > 0) {
Log.Info(" " + encodingName(key) + ": " + s[0] + " rects"); Log.Info(" " + encodingName(key) + ": " + s[0] + " rects");
@ -467,10 +465,7 @@ export default class RFB extends EventTargetMixin {
}); });
Log.Info("Encoding stats since page load:"); Log.Info("Encoding stats since page load:");
Object.keys(stats).forEach(function (key) { Object.keys(stats).forEach(key => Log.Info(" " + encodingName(key) + ": " + stats[key][1] + " rects"));
const s = stats[key];
Log.Info(" " + encodingName(key) + ": " + s[1] + " rects");
});
} }
_focusCanvas(event) { _focusCanvas(event) {
@ -489,10 +484,10 @@ export default class RFB extends EventTargetMixin {
_windowResize(event) { _windowResize(event) {
// If the window resized then our screen element might have // If the window resized then our screen element might have
// as well. Update the viewport dimensions. // as well. Update the viewport dimensions.
window.requestAnimationFrame(function () { window.requestAnimationFrame(() => {
this._updateClip(); this._updateClip();
this._updateScale(); this._updateScale();
}.bind(this)); });
if (this._resizeSession) { if (this._resizeSession) {
// Request changing the resolution of the remote display to // Request changing the resolution of the remote display to
@ -640,8 +635,7 @@ export default class RFB extends EventTargetMixin {
this._rfb_connection_state = state; this._rfb_connection_state = state;
const smsg = "New state '" + state + "', was '" + oldstate + "'."; Log.Debug("New state '" + state + "', was '" + oldstate + "'.");
Log.Debug(smsg);
if (this._disconnTimer && state !== 'disconnecting') { if (this._disconnTimer && state !== 'disconnecting') {
Log.Debug("Clearing disconnect timer"); Log.Debug("Clearing disconnect timer");
@ -664,10 +658,10 @@ export default class RFB extends EventTargetMixin {
case 'disconnecting': case 'disconnecting':
this._disconnect(); this._disconnect();
this._disconnTimer = setTimeout(function () { this._disconnTimer = setTimeout(() => {
Log.Error("Disconnection timed out."); Log.Error("Disconnection timed out.");
this._updateConnectionState('disconnected'); this._updateConnectionState('disconnected');
}.bind(this), DISCONNECT_TIMEOUT * 1000); }, DISCONNECT_TIMEOUT * 1000);
break; break;
case 'disconnected': case 'disconnected':
@ -2143,7 +2137,7 @@ RFB.encodingHandlers = {
let resetStreams = 0; let resetStreams = 0;
let streamId = -1; let streamId = -1;
const decompress = function (data, expected) { const decompress = (data, expected) => {
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
if ((resetStreams >> i) & 1) { if ((resetStreams >> i) & 1) {
this._FBU.zlibs[i].reset(); this._FBU.zlibs[i].reset();
@ -2159,9 +2153,9 @@ RFB.encodingHandlers = {
//return uncompressed.data; //return uncompressed.data;
return uncompressed; return uncompressed;
}.bind(this); };
const indexedToRGBX2Color = function (data, palette, width, height) { const indexedToRGBX2Color = (data, palette, width, height) => {
// Convert indexed (palette based) image data to RGB // Convert indexed (palette based) image data to RGB
// TODO: reduce number of calculations inside loop // TODO: reduce number of calculations inside loop
const dest = this._destBuff; const dest = this._destBuff;
@ -2220,9 +2214,9 @@ RFB.encodingHandlers = {
} }
return dest; return dest;
}.bind(this); };
const indexedToRGBX = function (data, palette, width, height) { const indexedToRGBX = (data, palette, width, height) => {
// Convert indexed (palette based) image data to RGB // Convert indexed (palette based) image data to RGB
const dest = this._destBuff; const dest = this._destBuff;
const total = width * height * 4; const total = width * height * 4;
@ -2235,14 +2229,14 @@ RFB.encodingHandlers = {
} }
return dest; return dest;
}.bind(this); };
const rQi = this._sock.get_rQi(); const rQi = this._sock.get_rQi();
const rQ = this._sock.rQwhole(); const rQ = this._sock.rQwhole();
let cmode, data; let cmode, data;
let cl_header, cl_data; let cl_header, cl_data;
const handlePalette = function () { const handlePalette = () => {
const numColors = rQ[rQi + 2] + 1; const numColors = rQ[rQi + 2] + 1;
const paletteSize = numColors * 3; const paletteSize = numColors * 3;
this._FBU.bytes += paletteSize; this._FBU.bytes += paletteSize;
@ -2300,9 +2294,9 @@ RFB.encodingHandlers = {
return true; return true;
}.bind(this); };
const handleCopy = function () { const handleCopy = () => {
let raw = false; let raw = false;
const uncompressedSize = this._FBU.width * this._FBU.height * 3; const uncompressedSize = this._FBU.width * this._FBU.height * 3;
if (uncompressedSize < 12) { if (uncompressedSize < 12) {
@ -2340,7 +2334,7 @@ RFB.encodingHandlers = {
this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false); this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false);
return true; return true;
}.bind(this); };
let ctl = this._sock.rQpeek8(); let ctl = this._sock.rQpeek8();

View File

@ -120,7 +120,7 @@ export function releaseCapture () {
// There might be events already queued, so we need to wait for // There might be events already queued, so we need to wait for
// them to flush. E.g. contextmenu in Microsoft Edge // them to flush. E.g. contextmenu in Microsoft Edge
window.setTimeout(function(expected) { window.setTimeout((expected) => {
// Only clear it if it's the expected grab (i.e. no one // Only clear it if it's the expected grab (i.e. no one
// else has initiated a new grab) // else has initiated a new grab)
if (_captureIndex === expected) { if (_captureIndex === expected) {

View File

@ -32,7 +32,7 @@ export default class EventTargetMixin {
if (!this._listeners || !this._listeners.has(event.type)) { if (!this._listeners || !this._listeners.has(event.type)) {
return true; return true;
} }
this._listeners.get(event.type).forEach(function (callback) { this._listeners.get(event.type).forEach((callback) => {
callback.call(this, event); callback.call(this, event);
}, this); }, this);
return !event.defaultPrevented; return !event.defaultPrevented;

View File

@ -12,10 +12,10 @@
let _log_level = 'warn'; let _log_level = 'warn';
let Debug = function (msg) {}; let Debug = () => {};
let Info = function (msg) {}; let Info = () => {};
let Warn = function (msg) {}; let Warn = () => {};
let Error = function (msg) {}; let Error = () => {};
export function init_logging (level) { export function init_logging (level) {
if (typeof level === 'undefined') { if (typeof level === 'undefined') {
@ -24,7 +24,7 @@ export function init_logging (level) {
_log_level = level; _log_level = level;
} }
Debug = Info = Warn = Error = function (msg) {}; Debug = Info = Warn = Error = () => {};
if (typeof window.console !== "undefined") { if (typeof window.console !== "undefined") {
/* eslint-disable no-console, no-fallthrough */ /* eslint-disable no-console, no-fallthrough */

View File

@ -38,8 +38,8 @@ if (typeof Object.assign != 'function') {
} }
/* CustomEvent constructor (taken from MDN) */ /* CustomEvent constructor (taken from MDN) */
(function () { (() => {
function CustomEvent ( event, params ) { function CustomEvent (event, params) {
params = params || { bubbles: false, cancelable: false, detail: undefined }; params = params || { bubbles: false, cancelable: false, detail: undefined };
const evt = document.createEvent( 'CustomEvent' ); const evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail ); evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );

View File

@ -164,14 +164,12 @@ export default class Websock {
} }
send_string(str) { send_string(str) {
this.send(str.split('').map(function (chr) { this.send(str.split('').map(chr => chr.charCodeAt(0)));
return chr.charCodeAt(0);
}));
} }
// Event Handlers // Event Handlers
off(evt) { off(evt) {
this._eventHandlers[evt] = function () {}; this._eventHandlers[evt] = () => {};
} }
on(evt, handler) { on(evt, handler) {
@ -196,7 +194,7 @@ export default class Websock {
this._websocket.binaryType = 'arraybuffer'; this._websocket.binaryType = 'arraybuffer';
this._websocket.onmessage = this._recv_message.bind(this); this._websocket.onmessage = this._recv_message.bind(this);
this._websocket.onopen = (function () { this._websocket.onopen = () => {
Log.Debug('>> WebSock.onopen'); Log.Debug('>> WebSock.onopen');
if (this._websocket.protocol) { if (this._websocket.protocol) {
Log.Info("Server choose sub-protocol: " + this._websocket.protocol); Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
@ -204,17 +202,17 @@ export default class Websock {
this._eventHandlers.open(); this._eventHandlers.open();
Log.Debug("<< WebSock.onopen"); Log.Debug("<< WebSock.onopen");
}).bind(this); };
this._websocket.onclose = (function (e) { this._websocket.onclose = (e) => {
Log.Debug(">> WebSock.onclose"); Log.Debug(">> WebSock.onclose");
this._eventHandlers.close(e); this._eventHandlers.close(e);
Log.Debug("<< WebSock.onclose"); Log.Debug("<< WebSock.onclose");
}).bind(this); };
this._websocket.onerror = (function (e) { this._websocket.onerror = (e) => {
Log.Debug(">> WebSock.onerror: " + e); Log.Debug(">> WebSock.onerror: " + e);
this._eventHandlers.error(e); this._eventHandlers.error(e);
Log.Debug("<< WebSock.onerror: " + e); Log.Debug("<< WebSock.onerror: " + e);
}).bind(this); };
} }
close() { close() {
@ -225,7 +223,7 @@ export default class Websock {
this._websocket.close(); this._websocket.close();
} }
this._websocket.onmessage = function (e) { return; }; this._websocket.onmessage = () => {};
} }
} }

View File

@ -1,6 +1,6 @@
// Karma configuration // Karma configuration
module.exports = function(config) { module.exports = (config) => {
const customLaunchers = {}; const customLaunchers = {};
let browsers = []; let browsers = [];
let useSauce = false; let useSauce = false;

View File

@ -89,7 +89,7 @@ for (let i = 0; i < opt.argv.length; i++) {
const dom = new jsdom.JSDOM(file, { includeNodeLocations: true }); const dom = new jsdom.JSDOM(file, { includeNodeLocations: true });
const body = dom.window.document.body; const body = dom.window.document.body;
const locator = function (elem) { const locator = (elem) => {
const offset = dom.nodeLocation(elem).startOffset; const offset = dom.nodeLocation(elem).startOffset;
const line = file.slice(0, offset).split("\n").length; const line = file.slice(0, offset).split("\n").length;
return fn + ":" + line; return fn + ":" + line;

View File

@ -5,5 +5,8 @@
}, },
"globals": { "globals": {
"chai": true "chai": true
},
"rules": {
"prefer-arrow-callback": 0
} }
} }

View File

@ -32,7 +32,7 @@ chai.use(function (_chai, utils) {
_chai.Assertion.addMethod('sent', function (target_data) { _chai.Assertion.addMethod('sent', function (target_data) {
const obj = this._obj; const obj = this._obj;
obj.inspect = function () { obj.inspect = () => {
const res = { _websocket: obj._websocket, rQi: obj._rQi, _rQ: new Uint8Array(obj._rQ.buffer, 0, obj._rQlen), const res = { _websocket: obj._websocket, rQi: obj._rQi, _rQ: new Uint8Array(obj._rQ.buffer, 0, obj._rQlen),
_sQ: new Uint8Array(obj._sQ.buffer, 0, obj._sQlen) }; _sQ: new Uint8Array(obj._sQ.buffer, 0, obj._sQlen) };
res.prototype = obj; res.prototype = obj;

View File

@ -74,7 +74,7 @@ FakeWebSocket.CLOSED = WebSocket.CLOSED;
FakeWebSocket.__is_fake = true; FakeWebSocket.__is_fake = true;
FakeWebSocket.replace = function () { FakeWebSocket.replace = () => {
if (!WebSocket.__is_fake) { if (!WebSocket.__is_fake) {
const real_version = WebSocket; const real_version = WebSocket;
// eslint-disable-next-line no-global-assign // eslint-disable-next-line no-global-assign
@ -83,7 +83,7 @@ FakeWebSocket.replace = function () {
} }
}; };
FakeWebSocket.restore = function () { FakeWebSocket.restore = () => {
if (WebSocket.__is_fake) { if (WebSocket.__is_fake) {
// eslint-disable-next-line no-global-assign // eslint-disable-next-line no-global-assign
WebSocket = WebSocket.__real_version; WebSocket = WebSocket.__real_version;

View File

@ -21,7 +21,7 @@ function loadFile() {
message("Loading " + fname); message("Loading " + fname);
return new Promise(function (resolve, reject) { return new Promise((resolve, reject) => {
const script = document.createElement("script"); const script = document.createElement("script");
script.onload = resolve; script.onload = resolve;
script.onerror = reject; script.onerror = reject;
@ -67,9 +67,9 @@ class IterationPlayer {
this._state = 'running'; this._state = 'running';
this.onfinish = function() {}; this.onfinish = () => {};
this.oniterationfinish = function() {}; this.oniterationfinish = () => {};
this.rfbdisconnected = function() {}; this.rfbdisconnected = () => {};
} }
start(mode) { start(mode) {
@ -147,15 +147,15 @@ function start() {
} }
const player = new IterationPlayer(iterations, frames, encoding); const player = new IterationPlayer(iterations, frames, encoding);
player.oniterationfinish = function (evt) { player.oniterationfinish = (evt) => {
message(`Iteration ${evt.number} took ${evt.duration}ms`); message(`Iteration ${evt.number} took ${evt.duration}ms`);
}; };
player.onrfbdisconnected = function (evt) { player.onrfbdisconnected = (evt) => {
if (!evt.clean) { if (!evt.clean) {
message(`noVNC sent disconnected during iteration ${evt.iteration} frame ${evt.frame}`); message(`noVNC sent disconnected during iteration ${evt.iteration} frame ${evt.frame}`);
} }
}; };
player.onfinish = function (evt) { player.onfinish = (evt) => {
const iterTime = parseInt(evt.duration / evt.iterations, 10); const iterTime = parseInt(evt.duration / evt.iterations, 10);
message(`${evt.iterations} iterations took ${evt.duration}ms (average ${iterTime}ms / iteration)`); message(`${evt.iterations} iterations took ${evt.duration}ms (average ${iterTime}ms / iteration)`);
@ -165,4 +165,4 @@ function start() {
player.start(mode); player.start(mode);
} }
loadFile().then(enableUI).catch(function (e) { message("Error loading recording: " + e); }); loadFile().then(enableUI).catch(e => message("Error loading recording: " + e));

View File

@ -13,18 +13,18 @@ if (window.setImmediate === undefined) {
let _immediateIdCounter = 1; let _immediateIdCounter = 1;
const _immediateFuncs = {}; const _immediateFuncs = {};
window.setImmediate = function (func) { window.setImmediate = (func) => {
const index = _immediateIdCounter++; const index = _immediateIdCounter++;
_immediateFuncs[index] = func; _immediateFuncs[index] = func;
window.postMessage("noVNC immediate trigger:" + index, "*"); window.postMessage("noVNC immediate trigger:" + index, "*");
return index; return index;
}; };
window.clearImmediate = function (id) { window.clearImmediate = (id) => {
_immediateFuncs[id]; _immediateFuncs[id];
}; };
const _onMessage = function (event) { const _onMessage = (event) => {
if ((typeof event.data !== "string") || if ((typeof event.data !== "string") ||
(event.data.indexOf("noVNC immediate trigger:") !== 0)) { (event.data.indexOf("noVNC immediate trigger:") !== 0)) {
return; return;
@ -71,7 +71,7 @@ export default class RecordingPlayer {
this._running = false; this._running = false;
this.onfinish = function () {}; this.onfinish = () => {};
} }
run(realtime, trafficManagement) { run(realtime, trafficManagement) {
@ -96,9 +96,9 @@ export default class RecordingPlayer {
// _enablePlaybackMode mocks out things not required for running playback // _enablePlaybackMode mocks out things not required for running playback
_enablePlaybackMode() { _enablePlaybackMode() {
this._rfb._sock.send = function (arr) {}; this._rfb._sock.send = () => {};
this._rfb._sock.close = function () {}; this._rfb._sock.close = () => {};
this._rfb._sock.flush = function () {}; this._rfb._sock.flush = () => {};
this._rfb._sock.open = function () { this._rfb._sock.open = function () {
this.init(); this.init();
this._eventHandlers.open(); this._eventHandlers.open();
@ -143,12 +143,11 @@ export default class RecordingPlayer {
_doPacket() { _doPacket() {
// Avoid having excessive queue buildup in non-realtime mode // Avoid having excessive queue buildup in non-realtime mode
if (this._trafficManagement && this._rfb._flushing) { if (this._trafficManagement && this._rfb._flushing) {
const player = this;
const orig = this._rfb._display.onflush; const orig = this._rfb._display.onflush;
this._rfb._display.onflush = function () { this._rfb._display.onflush = () => {
player._rfb._display.onflush = orig; this._rfb._display.onflush = orig;
player._rfb._onFlush(); this._rfb._onFlush();
player._doPacket(); this._doPacket();
}; };
return; return;
} }
@ -174,12 +173,11 @@ export default class RecordingPlayer {
_finish() { _finish() {
if (this._rfb._display.pending()) { if (this._rfb._display.pending()) {
const player = this; this._rfb._display.onflush = () => {
this._rfb._display.onflush = function () { if (this._rfb._flushing) {
if (player._rfb._flushing) { this._rfb._onFlush();
player._rfb._onFlush();
} }
player._finish(); this._finish();
}; };
this._rfb._display.flush(); this._rfb._display.flush();
} else { } else {

View File

@ -27,7 +27,7 @@ describe('Base64 Tools', function() {
}); });
it('should throw an error if we have extra characters at the end of the string', function() { it('should throw an error if we have extra characters at the end of the string', function() {
expect(function () { Base64.decode(B64_STR+'abcdef'); }).to.throw(Error); expect(() => Base64.decode(B64_STR+'abcdef')).to.throw(Error);
}); });
}); });
}); });

View File

@ -284,7 +284,7 @@ describe('Display/Canvas Helper', function () {
it('should draw the logo on #clear with a logo set', function (done) { it('should draw the logo on #clear with a logo set', function (done) {
display._logo = { width: 4, height: 4, type: "image/png", data: make_image_png(checked_data) }; display._logo = { width: 4, height: 4, type: "image/png", data: make_image_png(checked_data) };
display.clear(); display.clear();
display.onflush = function () { display.onflush = () => {
expect(display).to.have.displayed(checked_data); expect(display).to.have.displayed(checked_data);
expect(display._fb_width).to.equal(4); expect(display._fb_width).to.equal(4);
expect(display._fb_height).to.equal(4); expect(display._fb_height).to.equal(4);
@ -325,7 +325,7 @@ describe('Display/Canvas Helper', function () {
it('should support drawing images via #imageRect', function (done) { it('should support drawing images via #imageRect', function (done) {
display.imageRect(0, 0, "image/png", make_image_png(checked_data)); display.imageRect(0, 0, "image/png", make_image_png(checked_data));
display.flip(); display.flip();
display.onflush = function () { display.onflush = () => {
expect(display).to.have.displayed(checked_data); expect(display).to.have.displayed(checked_data);
done(); done();
}; };

View File

@ -24,7 +24,7 @@ describe('Key Event Handling', function() {
it('should decode keydown events', function(done) { it('should decode keydown events', function(done) {
if (browser.isIE() || browser.isEdge()) this.skip(); if (browser.isIE() || browser.isEdge()) this.skip();
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
expect(down).to.be.equal(true); expect(down).to.be.equal(true);
@ -36,7 +36,7 @@ describe('Key Event Handling', function() {
if (browser.isIE() || browser.isEdge()) this.skip(); if (browser.isIE() || browser.isEdge()) this.skip();
let calls = 0; let calls = 0;
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
if (calls++ === 1) { if (calls++ === 1) {
@ -57,7 +57,7 @@ describe('Key Event Handling', function() {
}); });
it('should decode keypress events', function(done) { it('should decode keypress events', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
expect(down).to.be.equal(true); expect(down).to.be.equal(true);
@ -75,7 +75,7 @@ describe('Key Event Handling', function() {
}); });
it('should handle keypress with missing code', function(done) { it('should handle keypress with missing code', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
expect(down).to.be.equal(true); expect(down).to.be.equal(true);
@ -86,7 +86,7 @@ describe('Key Event Handling', function() {
}); });
it('should guess key if no keypress and numeric key', function(done) { it('should guess key if no keypress and numeric key', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x32); expect(keysym).to.be.equal(0x32);
expect(code).to.be.equal('Digit2'); expect(code).to.be.equal('Digit2');
expect(down).to.be.equal(true); expect(down).to.be.equal(true);
@ -96,7 +96,7 @@ describe('Key Event Handling', function() {
}); });
it('should guess key if no keypress and alpha key', function(done) { it('should guess key if no keypress and alpha key', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
expect(down).to.be.equal(true); expect(down).to.be.equal(true);
@ -106,7 +106,7 @@ describe('Key Event Handling', function() {
}); });
it('should guess key if no keypress and alpha key (with shift)', function(done) { it('should guess key if no keypress and alpha key (with shift)', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x41); expect(keysym).to.be.equal(0x41);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
expect(down).to.be.equal(true); expect(down).to.be.equal(true);
@ -116,7 +116,7 @@ describe('Key Event Handling', function() {
}); });
it('should not guess key if no keypress and unknown key', function(done) { it('should not guess key if no keypress and unknown key', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0); expect(keysym).to.be.equal(0);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
expect(down).to.be.equal(true); expect(down).to.be.equal(true);
@ -161,7 +161,7 @@ describe('Key Event Handling', function() {
if (browser.isIE() || browser.isEdge()) this.skip(); if (browser.isIE() || browser.isEdge()) this.skip();
let count = 0; let count = 0;
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
switch (count++) { switch (count++) {
case 0: case 0:
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
@ -208,7 +208,7 @@ describe('Key Event Handling', function() {
if (browser.isIE() || browser.isEdge()) this.skip(); if (browser.isIE() || browser.isEdge()) this.skip();
let count = 0; let count = 0;
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
switch (count++) { switch (count++) {
case 0: case 0:
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
@ -233,7 +233,7 @@ describe('Key Event Handling', function() {
}); });
it('should send release using the same keysym as the press', function(done) { it('should send release using the same keysym as the press', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
if (!down) { if (!down) {
@ -246,7 +246,7 @@ describe('Key Event Handling', function() {
it('should send the same keysym for multiple presses', function() { it('should send the same keysym for multiple presses', function() {
let count = 0; let count = 0;
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('KeyA'); expect(code).to.be.equal('KeyA');
expect(down).to.be.equal(true); expect(down).to.be.equal(true);
@ -266,7 +266,7 @@ describe('Key Event Handling', function() {
describe('Legacy Events', function() { describe('Legacy Events', function() {
it('should track keys using keyCode if no code', function(done) { it('should track keys using keyCode if no code', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('Platform65'); expect(code).to.be.equal('Platform65');
if (!down) { if (!down) {
@ -278,7 +278,7 @@ describe('Key Event Handling', function() {
}); });
it('should ignore compositing code', function() { it('should ignore compositing code', function() {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('Unidentified'); expect(code).to.be.equal('Unidentified');
}; };
@ -286,7 +286,7 @@ describe('Key Event Handling', function() {
}); });
it('should track keys using keyIdentifier if no code', function(done) { it('should track keys using keyIdentifier if no code', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0x61); expect(keysym).to.be.equal(0x61);
expect(code).to.be.equal('Platform65'); expect(code).to.be.equal('Platform65');
if (!down) { if (!down) {
@ -328,7 +328,7 @@ describe('Key Event Handling', function() {
it('should change Alt to AltGraph', function() { it('should change Alt to AltGraph', function() {
let count = 0; let count = 0;
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
switch (count++) { switch (count++) {
case 0: case 0:
expect(keysym).to.be.equal(0xFF7E); expect(keysym).to.be.equal(0xFF7E);
@ -346,7 +346,7 @@ describe('Key Event Handling', function() {
}); });
it('should change left Super to Alt', function(done) { it('should change left Super to Alt', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0xFFE9); expect(keysym).to.be.equal(0xFFE9);
expect(code).to.be.equal('MetaLeft'); expect(code).to.be.equal('MetaLeft');
done(); done();
@ -355,7 +355,7 @@ describe('Key Event Handling', function() {
}); });
it('should change right Super to left Super', function(done) { it('should change right Super to left Super', function(done) {
const kbd = new Keyboard(document); const kbd = new Keyboard(document);
kbd.onkeyevent = function(keysym, code, down) { kbd.onkeyevent = (keysym, code, down) => {
expect(keysym).to.be.equal(0xFFEB); expect(keysym).to.be.equal(0xFFEB);
expect(code).to.be.equal('MetaRight'); expect(code).to.be.equal('MetaRight');
done(); done();

View File

@ -18,7 +18,7 @@ describe('Mouse Event Handling', function() {
// The real constructors might not work everywhere we // The real constructors might not work everywhere we
// want to run these tests // want to run these tests
const mouseevent = function(typeArg, MouseEventInit) { const mouseevent = (typeArg, MouseEventInit) => {
const e = { type: typeArg }; const e = { type: typeArg };
for (let key in MouseEventInit) { for (let key in MouseEventInit) {
e[key] = MouseEventInit[key]; e[key] = MouseEventInit[key];
@ -32,7 +32,7 @@ describe('Mouse Event Handling', function() {
describe('Decode Mouse Events', function() { describe('Decode Mouse Events', function() {
it('should decode mousedown events', function(done) { it('should decode mousedown events', function(done) {
const mouse = new Mouse(target); const mouse = new Mouse(target);
mouse.onmousebutton = function(x, y, down, bmask) { mouse.onmousebutton = (x, y, down, bmask) => {
expect(bmask).to.be.equal(0x01); expect(bmask).to.be.equal(0x01);
expect(down).to.be.equal(1); expect(down).to.be.equal(1);
done(); done();
@ -42,7 +42,7 @@ describe('Mouse Event Handling', function() {
it('should decode mouseup events', function(done) { it('should decode mouseup events', function(done) {
let calls = 0; let calls = 0;
const mouse = new Mouse(target); const mouse = new Mouse(target);
mouse.onmousebutton = function(x, y, down, bmask) { mouse.onmousebutton = (x, y, down, bmask) => {
expect(bmask).to.be.equal(0x01); expect(bmask).to.be.equal(0x01);
if (calls++ === 1) { if (calls++ === 1) {
expect(down).to.not.be.equal(1); expect(down).to.not.be.equal(1);
@ -54,7 +54,7 @@ describe('Mouse Event Handling', function() {
}); });
it('should decode mousemove events', function(done) { it('should decode mousemove events', function(done) {
const mouse = new Mouse(target); const mouse = new Mouse(target);
mouse.onmousemove = function(x, y) { mouse.onmousemove = (x, y) => {
// Note that target relative coordinates are sent // Note that target relative coordinates are sent
expect(x).to.be.equal(40); expect(x).to.be.equal(40);
expect(y).to.be.equal(10); expect(y).to.be.equal(10);
@ -66,7 +66,7 @@ describe('Mouse Event Handling', function() {
it('should decode mousewheel events', function(done) { it('should decode mousewheel events', function(done) {
let calls = 0; let calls = 0;
const mouse = new Mouse(target); const mouse = new Mouse(target);
mouse.onmousebutton = function(x, y, down, bmask) { mouse.onmousebutton = (x, y, down, bmask) => {
calls++; calls++;
expect(bmask).to.be.equal(1<<6); expect(bmask).to.be.equal(1<<6);
if (calls === 1) { if (calls === 1) {
@ -90,7 +90,7 @@ describe('Mouse Event Handling', function() {
it('should use same pos for 2nd tap if close enough', function(done) { it('should use same pos for 2nd tap if close enough', function(done) {
let calls = 0; let calls = 0;
const mouse = new Mouse(target); const mouse = new Mouse(target);
mouse.onmousebutton = function(x, y, down, bmask) { mouse.onmousebutton = (x, y, down, bmask) => {
calls++; calls++;
if (calls === 1) { if (calls === 1) {
expect(down).to.be.equal(1); expect(down).to.be.equal(1);
@ -121,7 +121,7 @@ describe('Mouse Event Handling', function() {
it('should not modify 2nd tap pos if far apart', function(done) { it('should not modify 2nd tap pos if far apart', function(done) {
let calls = 0; let calls = 0;
const mouse = new Mouse(target); const mouse = new Mouse(target);
mouse.onmousebutton = function(x, y, down, bmask) { mouse.onmousebutton = (x, y, down, bmask) => {
calls++; calls++;
if (calls === 1) { if (calls === 1) {
expect(down).to.be.equal(1); expect(down).to.be.equal(1);
@ -150,7 +150,7 @@ describe('Mouse Event Handling', function() {
it('should not modify 2nd tap pos if not soon enough', function(done) { it('should not modify 2nd tap pos if not soon enough', function(done) {
let calls = 0; let calls = 0;
const mouse = new Mouse(target); const mouse = new Mouse(target);
mouse.onmousebutton = function(x, y, down, bmask) { mouse.onmousebutton = (x, y, down, bmask) => {
calls++; calls++;
if (calls === 1) { if (calls === 1) {
expect(down).to.be.equal(1); expect(down).to.be.equal(1);
@ -179,7 +179,7 @@ describe('Mouse Event Handling', function() {
it('should not modify 2nd tap pos if not touch', function(done) { it('should not modify 2nd tap pos if not touch', function(done) {
let calls = 0; let calls = 0;
const mouse = new Mouse(target); const mouse = new Mouse(target);
mouse.onmousebutton = function(x, y, down, bmask) { mouse.onmousebutton = (x, y, down, bmask) => {
calls++; calls++;
if (calls === 1) { if (calls === 1) {
expect(down).to.be.equal(1); expect(down).to.be.equal(1);

View File

@ -8,7 +8,7 @@ import FakeWebSocket from './fake.websocket.js';
import sinon from '../vendor/sinon.js'; import sinon from '../vendor/sinon.js';
/* UIEvent constructor polyfill for IE */ /* UIEvent constructor polyfill for IE */
(function () { (() => {
if (typeof window.UIEvent === "function") return; if (typeof window.UIEvent === "function") return;
function UIEvent ( event, params ) { function UIEvent ( event, params ) {
@ -23,18 +23,18 @@ import sinon from '../vendor/sinon.js';
window.UIEvent = UIEvent; window.UIEvent = UIEvent;
})(); })();
const push8 = function (arr, num) { const push8 = (arr, num) => {
"use strict"; "use strict";
arr.push(num & 0xFF); arr.push(num & 0xFF);
}; };
const push16 = function (arr, num) { const push16 = (arr, num) => {
"use strict"; "use strict";
arr.push((num >> 8) & 0xFF, arr.push((num >> 8) & 0xFF,
num & 0xFF); num & 0xFF);
}; };
const push32 = function (arr, num) { const push32 = (arr, num) => {
"use strict"; "use strict";
arr.push((num >> 24) & 0xFF, arr.push((num >> 24) & 0xFF,
(num >> 16) & 0xFF, (num >> 16) & 0xFF,
@ -852,7 +852,7 @@ describe('Remote Frame Buffer Protocol Client', function() {
it('should not result in a connect event if the state is not "connected"', function () { it('should not result in a connect event if the state is not "connected"', function () {
const spy = sinon.spy(); const spy = sinon.spy();
client.addEventListener("connect", spy); client.addEventListener("connect", spy);
client._sock._websocket.open = function () {}; // explicitly don't call onopen client._sock._websocket.open = () => {}; // explicitly don't call onopen
client._updateConnectionState('connecting'); client._updateConnectionState('connecting');
expect(spy).to.not.have.been.called; expect(spy).to.not.have.been.called;
}); });
@ -866,7 +866,7 @@ describe('Remote Frame Buffer Protocol Client', function() {
it('should force disconnect if we do not call Websock.onclose within the disconnection timeout', function () { it('should force disconnect if we do not call Websock.onclose within the disconnection timeout', function () {
sinon.spy(client, '_updateConnectionState'); sinon.spy(client, '_updateConnectionState');
client._sock._websocket.close = function () {}; // explicitly don't call onclose client._sock._websocket.close = () => {}; // explicitly don't call onclose
client._updateConnectionState('disconnecting'); client._updateConnectionState('disconnecting');
this.clock.tick(3 * 1000); this.clock.tick(3 * 1000);
expect(client._updateConnectionState).to.have.been.calledTwice; expect(client._updateConnectionState).to.have.been.calledTwice;
@ -891,7 +891,7 @@ describe('Remote Frame Buffer Protocol Client', function() {
it('should not result in a disconnect event', function () { it('should not result in a disconnect event', function () {
const spy = sinon.spy(); const spy = sinon.spy();
client.addEventListener("disconnect", spy); client.addEventListener("disconnect", spy);
client._sock._websocket.close = function () {}; // explicitly don't call onclose client._sock._websocket.close = () => {}; // explicitly don't call onclose
client._updateConnectionState('disconnecting'); client._updateConnectionState('disconnecting');
expect(spy).to.not.have.been.called; expect(spy).to.not.have.been.called;
}); });
@ -1239,11 +1239,10 @@ describe('Remote Frame Buffer Protocol Client', function() {
}); });
function send_num_str_pairs(pairs, client) { function send_num_str_pairs(pairs, client) {
const pairs_len = pairs.length;
const data = []; const data = [];
push32(data, pairs_len); push32(data, pairs.length);
for (let i = 0; i < pairs_len; i++) { for (let i = 0; i < pairs.length; i++) {
push32(data, pairs[i][0]); push32(data, pairs[i][0]);
for (let j = 0; j < 4; j++) { for (let j = 0; j < 4; j++) {
data.push(pairs[i][1].charCodeAt(j)); data.push(pairs[i][1].charCodeAt(j));
@ -1618,7 +1617,7 @@ describe('Remote Frame Buffer Protocol Client', function() {
const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}};
RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20);
client._framebufferUpdate = function () { return true; }; client._framebufferUpdate = () => true;
client._sock._websocket._receive_data(new Uint8Array([0])); client._sock._websocket._receive_data(new Uint8Array([0]));
expect(client._sock).to.have.sent(expected_msg._sQ); expect(client._sock).to.have.sent(expected_msg._sQ);
@ -1645,7 +1644,7 @@ describe('Remote Frame Buffer Protocol Client', function() {
it('should not send a request in continuous updates mode', function () { it('should not send a request in continuous updates mode', function () {
client._enabledContinuousUpdates = true; client._enabledContinuousUpdates = true;
client._framebufferUpdate = function () { return true; }; client._framebufferUpdate = () => true;
client._sock._websocket._receive_data(new Uint8Array([0])); client._sock._websocket._receive_data(new Uint8Array([0]));
expect(client._sock._websocket._get_sent_data()).to.have.length(0); expect(client._sock._websocket._get_sent_data()).to.have.length(0);
@ -2231,7 +2230,7 @@ describe('Remote Frame Buffer Protocol Client', function() {
// close events // close events
it('should transition to "disconnected" from "disconnecting" on a close event', function () { it('should transition to "disconnected" from "disconnecting" on a close event', function () {
const real = client._sock._websocket.close; const real = client._sock._websocket.close;
client._sock._websocket.close = function () {}; client._sock._websocket.close = () => {};
client.disconnect(); client.disconnect();
expect(client._rfb_connection_state).to.equal('disconnecting'); expect(client._rfb_connection_state).to.equal('disconnecting');
client._sock._websocket.close = real; client._sock._websocket.close = real;

View File

@ -178,7 +178,7 @@ describe('Websock', function() {
it('should raise an error if we try to go back more than possible', function () { it('should raise an error if we try to go back more than possible', function () {
sock.set_rQi(5); sock.set_rQi(5);
expect(function () { sock.rQwait('hi', RQ_TEMPLATE.length, 6); }).to.throw(Error); expect(() => sock.rQwait('hi', RQ_TEMPLATE.length, 6)).to.throw(Error);
}); });
it('should not reduce rQi if there are enough bytes', function () { it('should not reduce rQi if there are enough bytes', function () {

View File

@ -108,7 +108,7 @@ out +=
"};\n" + "};\n" +
"\n" + "\n" +
"export default {\n" + "export default {\n" +
" lookup : function(u) {\n" + " lookup(u) {\n" +
" // Latin-1 is one-to-one mapping\n" + " // Latin-1 is one-to-one mapping\n" +
" if ((u >= 0x20) && (u <= 0xff)) {\n" + " if ((u >= 0x20) && (u <= 0xff)) {\n" +
" return u;\n" + " return u;\n" +

View File

@ -39,15 +39,14 @@ const no_transform_files = new Set([
path.join(paths.app, 'error-handler.js'), path.join(paths.app, 'error-handler.js'),
]); ]);
no_copy_files.forEach((file) => no_transform_files.add(file)); no_copy_files.forEach(file => no_transform_files.add(file));
// util.promisify requires Node.js 8.x, so we have our own // util.promisify requires Node.js 8.x, so we have our own
function promisify(original) { function promisify(original) {
return function () { return function () {
const obj = this;
const args = Array.prototype.slice.call(arguments); const args = Array.prototype.slice.call(arguments);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
original.apply(obj, args.concat((err, value) => { original.apply(this, args.concat((err, value) => {
if (err) return reject(err); if (err) return reject(err);
resolve(value); resolve(value);
})); }));
@ -70,29 +69,27 @@ const babelTransformFile = promisify(babel.transformFile);
// walkDir *recursively* walks directories trees, // walkDir *recursively* walks directories trees,
// calling the callback for all normal files found. // calling the callback for all normal files found.
const walkDir = function (base_path, cb, filter) { function walkDir(base_path, cb, filter) {
return readdir(base_path) return readdir(base_path)
.then(files => { .then((files) => {
const paths = files.map(filename => path.join(base_path, filename)); const paths = files.map(filename => path.join(base_path, filename));
return Promise.all(paths.map((filepath) => { return Promise.all(paths.map(filepath => lstat(filepath)
return lstat(filepath) .then((stats) => {
.then(stats => {
if (filter !== undefined && !filter(filepath, stats)) return; if (filter !== undefined && !filter(filepath, stats)) return;
if (stats.isSymbolicLink()) return; if (stats.isSymbolicLink()) return;
if (stats.isFile()) return cb(filepath); if (stats.isFile()) return cb(filepath);
if (stats.isDirectory()) return walkDir(filepath, cb, filter); if (stats.isDirectory()) return walkDir(filepath, cb, filter);
})));
}); });
})); }
});
};
const transform_html = function (legacy_scripts, only_legacy) { function transform_html (legacy_scripts, only_legacy) {
// write out the modified vnc.html file that works with the bundle // write out the modified vnc.html file that works with the bundle
const src_html_path = path.resolve(__dirname, '..', 'vnc.html'); const src_html_path = path.resolve(__dirname, '..', 'vnc.html');
const out_html_path = path.resolve(paths.out_dir_base, 'vnc.html'); const out_html_path = path.resolve(paths.out_dir_base, 'vnc.html');
return readFile(src_html_path) return readFile(src_html_path)
.then(contents_raw => { .then((contents_raw) => {
let contents = contents_raw.toString(); let contents = contents_raw.toString();
const start_marker = '<!-- begin scripts -->\n'; const start_marker = '<!-- begin scripts -->\n';
@ -141,7 +138,7 @@ const transform_html = function (legacy_scripts, only_legacy) {
}); });
} }
const make_lib_files = function (import_format, source_maps, with_app_dir, only_legacy) { function make_lib_files(import_format, source_maps, with_app_dir, only_legacy) {
if (!import_format) { if (!import_format) {
throw new Error("you must specify an import format to generate compiled noVNC libraries"); throw new Error("you must specify an import format to generate compiled noVNC libraries");
} else if (!SUPPORTED_FORMATS.has(import_format)) { } else if (!SUPPORTED_FORMATS.has(import_format)) {
@ -223,7 +220,7 @@ const make_lib_files = function (import_format, source_maps, with_app_dir, only_
} }
return babelTransformFile(filename, opts) return babelTransformFile(filename, opts)
.then(res => { .then((res) => {
console.log(`Writing ${legacy_path}`); console.log(`Writing ${legacy_path}`);
const {map} = res; const {map} = res;
let {code} = res; let {code} = res;
@ -275,7 +272,7 @@ const make_lib_files = function (import_format, source_maps, with_app_dir, only_
const out_app_path = path.join(legacy_path_base, 'app.js'); const out_app_path = path.join(legacy_path_base, 'app.js');
console.log(`Writing ${out_app_path}`); console.log(`Writing ${out_app_path}`);
return helper.appWriter(out_path_base, legacy_path_base, out_app_path) return helper.appWriter(out_path_base, legacy_path_base, out_app_path)
.then(extra_scripts => { .then((extra_scripts) => {
const rel_app_path = path.relative(out_path_base, out_app_path); const rel_app_path = path.relative(out_path_base, out_app_path);
const legacy_scripts = extra_scripts.concat([rel_app_path]); const legacy_scripts = extra_scripts.concat([rel_app_path]);
transform_html(legacy_scripts, only_legacy); transform_html(legacy_scripts, only_legacy);
@ -283,18 +280,17 @@ const make_lib_files = function (import_format, source_maps, with_app_dir, only_
.then(() => { .then(() => {
if (!helper.removeModules) return; if (!helper.removeModules) return;
console.log(`Cleaning up temporary files...`); console.log(`Cleaning up temporary files...`);
return Promise.all(outFiles.map(filepath => { return Promise.all(outFiles.map((filepath) => {
unlink(filepath) unlink(filepath)
.then(() => { .then(() => {
// Try to clean up any empty directories if this // Try to clean up any empty directories if this
// was the last file in there // was the last file in there
const rmdir_r = dir => { const rmdir_r = dir =>
return rmdir(dir) rmdir(dir)
.then(() => rmdir_r(path.dirname(dir))) .then(() => rmdir_r(path.dirname(dir)))
.catch(() => { .catch(() => {
// Assume the error was ENOTEMPTY and ignore it // Assume the error was ENOTEMPTY and ignore it
}); });
};
return rmdir_r(path.dirname(filepath)); return rmdir_r(path.dirname(filepath));
}); });
})); }));
@ -304,7 +300,7 @@ const make_lib_files = function (import_format, source_maps, with_app_dir, only_
console.error(`Failure converting modules: ${err}`); console.error(`Failure converting modules: ${err}`);
process.exit(1); process.exit(1);
}); });
}; }
if (program.clean) { if (program.clean) {
console.log(`Removing ${paths.lib_dir_base}`); console.log(`Removing ${paths.lib_dir_base}`);

View File

@ -5,10 +5,9 @@ const path = require('path');
// util.promisify requires Node.js 8.x, so we have our own // util.promisify requires Node.js 8.x, so we have our own
function promisify(original) { function promisify(original) {
return function () { return function () {
const obj = this;
const args = Array.prototype.slice.call(arguments); const args = Array.prototype.slice.call(arguments);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
original.apply(obj, args.concat((err, value) => { original.apply(this, args.concat((err, value) => {
if (err) return reject(err); if (err) return reject(err);
resolve(value); resolve(value);
})); }));
@ -24,7 +23,7 @@ module.exports = {
// setup for requirejs // setup for requirejs
const ui_path = path.relative(base_out_path, const ui_path = path.relative(base_out_path,
path.join(script_base_path, 'app', 'ui')); path.join(script_base_path, 'app', 'ui'));
return writeFile(out_path, `requirejs(["${ui_path}"], function (ui) {});`) return writeFile(out_path, `requirejs(["${ui_path}"], (ui) => {});`)
.then(() => { .then(() => {
console.log(`Please place RequireJS in ${path.join(script_base_path, 'require.js')}`); console.log(`Please place RequireJS in ${path.join(script_base_path, 'require.js')}`);
const require_path = path.relative(base_out_path, const require_path = path.relative(base_out_path,
@ -43,7 +42,7 @@ module.exports = {
const browserify = require('browserify'); const browserify = require('browserify');
const b = browserify(path.join(script_base_path, 'app/ui.js'), {}); const b = browserify(path.join(script_base_path, 'app/ui.js'), {});
return promisify(b.bundle).call(b) return promisify(b.bundle).call(b)
.then((buf) => writeFile(out_path, buf)) .then(buf => writeFile(out_path, buf))
.then(() => []); .then(() => []);
}, },
noCopyOverride: () => {}, noCopyOverride: () => {},

View File

@ -229,7 +229,7 @@
rfb.viewOnly = WebUtil.getConfigVar('view_only', false); rfb.viewOnly = WebUtil.getConfigVar('view_only', false);
rfb.addEventListener("connect", connected); rfb.addEventListener("connect", connected);
rfb.addEventListener("disconnect", disconnected); rfb.addEventListener("disconnect", disconnected);
rfb.addEventListener("capabilities", function () { updatePowerButtons(); }); rfb.addEventListener("capabilities", updatePowerButtons);
rfb.addEventListener("credentialsrequired", credentials); rfb.addEventListener("credentialsrequired", credentials);
rfb.addEventListener("desktopname", updateDesktopName); rfb.addEventListener("desktopname", updateDesktopName);
rfb.scaleViewport = WebUtil.getConfigVar('scale', false); rfb.scaleViewport = WebUtil.getConfigVar('scale', false);