1
0
mirror of https://github.com/godotengine/godot.git synced 2025-11-11 13:10:58 +00:00

[HTML5] Run eslint --fix.

Should I write a poem about this whole new world? ;)
This commit is contained in:
Fabio Alessandrelli
2020-11-23 13:27:13 +01:00
parent 0813008b8a
commit f316a1719d
13 changed files with 518 additions and 510 deletions

View File

@@ -49,27 +49,27 @@ const GodotRTCDataChannel = {
p_on_error();
};
ref.onmessage = function (event) {
var buffer;
var is_string = 0;
let buffer;
let is_string = 0;
if (event.data instanceof ArrayBuffer) {
buffer = new Uint8Array(event.data);
} else if (event.data instanceof Blob) {
GodotRuntime.error("Blob type not supported");
GodotRuntime.error('Blob type not supported');
return;
} else if (typeof event.data === "string") {
} else if (typeof event.data === 'string') {
is_string = 1;
var enc = new TextEncoder("utf-8");
const enc = new TextEncoder('utf-8');
buffer = new Uint8Array(enc.encode(event.data));
} else {
GodotRuntime.error("Unknown message type");
GodotRuntime.error('Unknown message type');
return;
}
var len = buffer.length*buffer.BYTES_PER_ELEMENT;
var out = GodotRuntime.malloc(len);
const len = buffer.length * buffer.BYTES_PER_ELEMENT;
const out = GodotRuntime.malloc(len);
HEAPU8.set(buffer, out);
p_on_message(out, len, is_string);
GodotRuntime.free(out);
}
};
},
close: function (p_id) {
@@ -97,13 +97,13 @@ const GodotRTCDataChannel = {
}
switch (ref.readyState) {
case "connecting":
case 'connecting':
return 0;
case "open":
case 'open':
return 1;
case "closing":
case 'closing':
return 2;
case "closed":
case 'closed':
default:
return 3;
}
@@ -116,7 +116,7 @@ const GodotRTCDataChannel = {
}
const bytes_array = new Uint8Array(p_length);
for (var i = 0; i < p_length; i++) {
for (let i = 0; i < p_length; i++) {
bytes_array[i] = GodotRuntime.getHeapValue(p_buffer + i, 'i8');
}
@@ -208,25 +208,25 @@ const GodotRTCPeerConnection = {
if (!ref) {
return;
}
var state = 5; // CLOSED
let state = 5; // CLOSED
switch (p_conn.iceConnectionState) {
case "new":
case 'new':
state = 0;
break;
case "checking":
case 'checking':
state = 1;
break;
case "connected":
case "completed":
case 'connected':
case 'completed':
state = 2;
break;
case "disconnected":
case 'disconnected':
state = 3;
break;
case "failed":
case 'failed':
state = 4;
break;
case "closed":
case 'closed':
default:
state = 5;
break;
@@ -240,9 +240,9 @@ const GodotRTCPeerConnection = {
return;
}
let c = event.candidate;
let candidate_str = GodotRuntime.allocString(c.candidate);
let mid_str = GodotRuntime.allocString(c.sdpMid);
const c = event.candidate;
const candidate_str = GodotRuntime.allocString(c.candidate);
const mid_str = GodotRuntime.allocString(c.sdpMid);
callback(mid_str, c.sdpMLineIndex, candidate_str);
GodotRuntime.free(candidate_str);
GodotRuntime.free(mid_str);
@@ -263,8 +263,8 @@ const GodotRTCPeerConnection = {
if (!ref) {
return;
}
let type_str = GodotRuntime.allocString(session.type);
let sdp_str = GodotRuntime.allocString(session.sdp);
const type_str = GodotRuntime.allocString(session.type);
const sdp_str = GodotRuntime.allocString(session.sdp);
callback(type_str, sdp_str);
GodotRuntime.free(type_str);
GodotRuntime.free(sdp_str);
@@ -285,8 +285,8 @@ const GodotRTCPeerConnection = {
const oncandidate = GodotRuntime.get_func(p_on_candidate).bind(null, p_ref);
const ondatachannel = GodotRuntime.get_func(p_on_datachannel).bind(null, p_ref);
var config = JSON.parse(GodotRuntime.parseString(p_config));
var conn = null;
const config = JSON.parse(GodotRuntime.parseString(p_config));
let conn = null;
try {
conn = new RTCPeerConnection(config);
} catch (e) {
@@ -345,7 +345,7 @@ const GodotRTCPeerConnection = {
const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj);
ref.setLocalDescription({
'sdp': sdp,
'type': type
'type': type,
}).catch(function (error) {
GodotRTCPeerConnection.onerror(p_id, onerror, error);
});
@@ -362,7 +362,7 @@ const GodotRTCPeerConnection = {
const onsession = GodotRuntime.get_func(p_session_created).bind(null, p_obj);
ref.setRemoteDescription({
'sdp': sdp,
'type': type
'type': type,
}).then(function () {
if (type !== 'offer') {
return Promise.resolve();
@@ -380,12 +380,12 @@ const GodotRTCPeerConnection = {
if (!ref) {
return;
}
var sdpMidName = GodotRuntime.parseString(p_mid_name);
var sdpName = GodotRuntime.parseString(p_sdp);
const sdpMidName = GodotRuntime.parseString(p_mid_name);
const sdpName = GodotRuntime.parseString(p_sdp);
ref.addIceCandidate(new RTCIceCandidate({
"candidate": sdpName,
"sdpMid": sdpMidName,
"sdpMlineIndex": p_mline_idx,
'candidate': sdpName,
'sdpMid': sdpMidName,
'sdpMlineIndex': p_mline_idx,
}));
},
@@ -409,5 +409,5 @@ const GodotRTCPeerConnection = {
},
};
autoAddDeps(GodotRTCPeerConnection, '$GodotRTCPeerConnection')
autoAddDeps(GodotRTCPeerConnection, '$GodotRTCPeerConnection');
mergeInto(LibraryManager.library, GodotRTCPeerConnection);

View File

@@ -38,7 +38,7 @@ const GodotWebSocket = {
if (!ref) {
return; // Godot object is gone.
}
let c_str = GodotRuntime.allocString(ref.protocol);
const c_str = GodotRuntime.allocString(ref.protocol);
callback(c_str);
GodotRuntime.free(c_str);
},
@@ -49,23 +49,23 @@ const GodotWebSocket = {
if (!ref) {
return; // Godot object is gone.
}
var buffer;
var is_string = 0;
let buffer;
let is_string = 0;
if (event.data instanceof ArrayBuffer) {
buffer = new Uint8Array(event.data);
} else if (event.data instanceof Blob) {
GodotRuntime.error("Blob type not supported");
GodotRuntime.error('Blob type not supported');
return;
} else if (typeof event.data === "string") {
} else if (typeof event.data === 'string') {
is_string = 1;
var enc = new TextEncoder("utf-8");
const enc = new TextEncoder('utf-8');
buffer = new Uint8Array(enc.encode(event.data));
} else {
GodotRuntime.error("Unknown message type");
GodotRuntime.error('Unknown message type');
return;
}
var len = buffer.length*buffer.BYTES_PER_ELEMENT;
var out = GodotRuntime.malloc(len);
const len = buffer.length * buffer.BYTES_PER_ELEMENT;
const out = GodotRuntime.malloc(len);
HEAPU8.set(buffer, out);
callback(out, len, is_string);
GodotRuntime.free(out);
@@ -86,7 +86,7 @@ const GodotWebSocket = {
if (!ref) {
return; // Godot object is gone.
}
let c_str = GodotRuntime.allocString(event.reason);
const c_str = GodotRuntime.allocString(event.reason);
callback(event.code, c_str, event.wasClean ? 1 : 0);
GodotRuntime.free(c_str);
},
@@ -142,29 +142,29 @@ const GodotWebSocket = {
const on_close = GodotRuntime.get_func(p_on_close).bind(null, p_ref);
const url = GodotRuntime.parseString(p_url);
const protos = GodotRuntime.parseString(p_proto);
var socket = null;
let socket = null;
try {
if (protos) {
socket = new WebSocket(url, protos.split(","));
socket = new WebSocket(url, protos.split(','));
} else {
socket = new WebSocket(url);
}
} catch (e) {
return 0;
}
socket.binaryType = "arraybuffer";
socket.binaryType = 'arraybuffer';
return GodotWebSocket.create(socket, on_open, on_message, on_error, on_close);
},
godot_js_websocket_send: function (p_id, p_buf, p_buf_len, p_raw) {
var bytes_array = new Uint8Array(p_buf_len);
var i = 0;
const bytes_array = new Uint8Array(p_buf_len);
let i = 0;
for (i = 0; i < p_buf_len; i++) {
bytes_array[i] = GodotRuntime.getHeapValue(p_buf + i, 'i8');
}
var out = bytes_array.buffer;
let out = bytes_array.buffer;
if (!p_raw) {
out = new TextDecoder("utf-8").decode(bytes_array);
out = new TextDecoder('utf-8').decode(bytes_array);
}
return GodotWebSocket.send(p_id, out);
},
@@ -180,5 +180,5 @@ const GodotWebSocket = {
},
};
autoAddDeps(GodotWebSocket, '$GodotWebSocket')
autoAddDeps(GodotWebSocket, '$GodotWebSocket');
mergeInto(LibraryManager.library, GodotWebSocket);

View File

@@ -1,14 +1,14 @@
const Engine = (function () {
var preloader = new Preloader();
const preloader = new Preloader();
var wasmExt = '.wasm';
var unloadAfterInit = true;
var loadPath = '';
var loadPromise = null;
var initPromise = null;
var stderr = null;
var stdout = null;
var progressFunc = null;
let wasmExt = '.wasm';
let unloadAfterInit = true;
let loadPath = '';
let loadPromise = null;
let initPromise = null;
let stderr = null;
let stdout = null;
let progressFunc = null;
function load(basePath) {
if (loadPromise == null) {
@@ -18,11 +18,11 @@ const Engine = (function() {
requestAnimationFrame(preloader.animateProgress);
}
return loadPromise;
};
}
function unload() {
loadPromise = null;
};
}
/** @constructor */
function Engine() { // eslint-disable-line no-shadow
@@ -34,7 +34,7 @@ const Engine = (function() {
this.onExecute = null;
this.onExit = null;
this.persistentPaths = ['/userfs'];
};
}
Engine.prototype.init = /** @param {string=} basePath */ function (basePath) {
if (initPromise) {
@@ -42,17 +42,19 @@ const Engine = (function() {
}
if (loadPromise == null) {
if (!basePath) {
initPromise = Promise.reject(new Error("A base path must be provided when calling `init` and the engine is not loaded."));
initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
return initPromise;
}
load(basePath);
}
var config = {};
if (typeof stdout === 'function')
let config = {};
if (typeof stdout === 'function') {
config.print = stdout;
if (typeof stderr === 'function')
}
if (typeof stderr === 'function') {
config.printErr = stderr;
var me = this;
}
const me = this;
initPromise = new Promise(function (resolve, reject) {
config['locateFile'] = Utils.createLocateRewrite(loadPath);
config['instantiateWasm'] = Utils.createInstantiatePromise(loadPromise);
@@ -78,11 +80,11 @@ const Engine = (function() {
/** @type {function(...string):Object} */
Engine.prototype.start = function () {
// Start from arguments.
var args = [];
for (var i = 0; i < arguments.length; i++) {
const args = [];
for (let i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
var me = this;
const me = this;
return me.init().then(function () {
if (!me.rtenv) {
return Promise.reject(new Error('The engine must be initialized before it can be started'));
@@ -107,12 +109,12 @@ const Engine = (function() {
// Until context restoration is implemented warn the user of context loss.
me.canvas.addEventListener('webglcontextlost', function (ev) {
alert("WebGL context lost, please reload the page"); // eslint-disable-line no-alert
alert('WebGL context lost, please reload the page'); // eslint-disable-line no-alert
ev.preventDefault();
}, false);
// Browser locale, or custom one if defined.
var locale = me.customLocale;
let locale = me.customLocale;
if (!locale) {
locale = navigator.languages ? navigator.languages[0] : navigator.language;
locale = locale.split('.')[0];
@@ -156,14 +158,15 @@ const Engine = (function() {
Engine.prototype.startGame = function (execName, mainPack, extraArgs) {
// Start and init with execName as loadPath if not inited.
this.executableName = execName;
var me = this;
const me = this;
return Promise.all([
this.init(execName),
this.preloadFile(mainPack, mainPack)
this.preloadFile(mainPack, mainPack),
]).then(function () {
var args = ['--main-pack', mainPack];
if (extraArgs)
let args = ['--main-pack', mainPack];
if (extraArgs) {
args = args.concat(extraArgs);
}
return me.start.apply(me, args);
});
};
@@ -200,45 +203,47 @@ const Engine = (function() {
};
Engine.prototype.setStdoutFunc = function (func) {
var print = function(text) {
const print = function (text) {
let msg = text;
if (arguments.length > 1) {
msg = Array.prototype.slice.call(arguments).join(" ");
msg = Array.prototype.slice.call(arguments).join(' ');
}
func(msg);
};
if (this.rtenv)
if (this.rtenv) {
this.rtenv.print = print;
}
stdout = print;
};
Engine.prototype.setStderrFunc = function (func) {
var printErr = function(text) {
let msg = text
const printErr = function (text) {
let msg = text;
if (arguments.length > 1) {
msg = Array.prototype.slice.call(arguments).join(" ");
msg = Array.prototype.slice.call(arguments).join(' ');
}
func(msg);
};
if (this.rtenv)
if (this.rtenv) {
this.rtenv.printErr = printErr;
}
stderr = printErr;
};
Engine.prototype.setOnExecute = function (onExecute) {
this.onExecute = onExecute;
}
};
Engine.prototype.setOnExit = function (onExit) {
this.onExit = onExit;
}
};
Engine.prototype.copyToFS = function (path, buffer) {
if (this.rtenv == null) {
throw new Error("Engine must be inited before copying files");
throw new Error('Engine must be inited before copying files');
}
this.rtenv['copyToFS'](path, buffer);
}
};
Engine.prototype.setPersistentPaths = function (persistentPaths) {
this.persistentPaths = persistentPaths;
@@ -274,5 +279,7 @@ const Engine = (function() {
Engine.prototype['setPersistentPaths'] = Engine.prototype.setPersistentPaths;
Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
return Engine;
})();
if (typeof window !== 'undefined') window['Engine'] = Engine;
}());
if (typeof window !== 'undefined') {
window['Engine'] = Engine;
}

View File

@@ -1,5 +1,4 @@
var Preloader = /** @constructor */ function() { // eslint-disable-line no-unused-vars
const Preloader = /** @constructor */ function () { // eslint-disable-line no-unused-vars
const loadXHR = function (resolve, reject, file, tracker, attempts) {
const xhr = new XMLHttpRequest();
tracker[file] = {
@@ -9,7 +8,7 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
};
xhr.onerror = function () {
if (attempts <= 1) {
reject(new Error("Failed loading file '" + file + "'"));
reject(new Error(`Failed loading file '${file}'`));
} else {
setTimeout(function () {
loadXHR(resolve, reject, file, tracker, attempts - 1);
@@ -18,7 +17,7 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
};
xhr.onabort = function () {
tracker[file].final = true;
reject(new Error("Loading file '" + file + "' was aborted."));
reject(new Error(`Loading file '${file}' was aborted.`));
};
xhr.onloadstart = function (ev) {
tracker[file].total = ev.total;
@@ -31,7 +30,7 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
xhr.onload = function () {
if (xhr.status >= 400) {
if (xhr.status < 500 || attempts <= 1) {
reject(new Error("Failed loading file '" + file + "': " + xhr.statusText));
reject(new Error(`Failed loading file '${file}': ${xhr.statusText}`));
xhr.abort();
} else {
setTimeout(function () {
@@ -57,11 +56,10 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
let progressFunc = null;
const animateProgress = function () {
var loaded = 0;
var total = 0;
var totalIsValid = true;
var progressIsFinal = true;
let loaded = 0;
let total = 0;
let totalIsValid = true;
let progressIsFinal = true;
Object.keys(loadingFiles).forEach(function (file) {
const stat = loadingFiles[file];
@@ -79,35 +77,36 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
if (loaded !== lastProgress.loaded || total !== lastProgress.total) {
lastProgress.loaded = loaded;
lastProgress.total = total;
if (typeof progressFunc === 'function')
if (typeof progressFunc === 'function') {
progressFunc(loaded, total);
}
if (!progressIsFinal)
}
if (!progressIsFinal) {
requestAnimationFrame(animateProgress);
}
};
this.animateProgress = animateProgress;
this.setProgressFunc = function (callback) {
progressFunc = callback;
}
};
this.loadPromise = function (file) {
return new Promise(function (resolve, reject) {
loadXHR(resolve, reject, file, loadingFiles, DOWNLOAD_ATTEMPTS_MAX);
});
}
};
this.preloadedFiles = [];
this.preload = function (pathOrBuffer, destPath) {
let buffer = null;
if (typeof pathOrBuffer === 'string') {
var me = this;
const me = this;
return this.loadPromise(pathOrBuffer).then(function (xhr) {
me.preloadedFiles.push({
path: destPath || pathOrBuffer,
buffer: xhr.response
buffer: xhr.response,
});
return Promise.resolve();
});
@@ -119,11 +118,10 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
if (buffer) {
this.preloadedFiles.push({
path: destPath,
buffer: pathOrBuffer
buffer: pathOrBuffer,
});
return Promise.resolve();
} else {
return Promise.reject(new Error("Invalid object for preloading"));
}
return Promise.reject(new Error('Invalid object for preloading'));
};
};

View File

@@ -1,15 +1,15 @@
var Utils = { // eslint-disable-line no-unused-vars
const Utils = { // eslint-disable-line no-unused-vars
createLocateRewrite: function (execName) {
function rw(path) {
if (path.endsWith('.worker.js')) {
return execName + '.worker.js';
return `${execName}.worker.js`;
} else if (path.endsWith('.audio.worklet.js')) {
return execName + '.audio.worklet.js';
return `${execName}.audio.worklet.js`;
} else if (path.endsWith('.js')) {
return execName + '.js';
return `${execName}.js`;
} else if (path.endsWith('.wasm')) {
return execName + '.wasm';
return `${execName}.wasm`;
}
return path;
}
@@ -26,13 +26,13 @@ var Utils = { // eslint-disable-line no-unused-vars
});
loader = null;
return {};
};
}
return instantiateWasm;
},
findCanvas: function () {
var nodes = document.getElementsByTagName('canvas');
const nodes = document.getElementsByTagName('canvas');
if (nodes.length && nodes[0] instanceof HTMLCanvasElement) {
return nodes[0];
}
@@ -40,10 +40,9 @@ var Utils = { // eslint-disable-line no-unused-vars
},
isWebGLAvailable: function (majorVersion = 1) {
var testContext = false;
let testContext = false;
try {
var testCanvas = document.createElement('canvas');
const testCanvas = document.createElement('canvas');
if (majorVersion === 1) {
testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl');
} else if (majorVersion === 2) {
@@ -53,5 +52,5 @@ var Utils = { // eslint-disable-line no-unused-vars
// Not available
}
return !!testContext;
}
},
};

View File

@@ -105,7 +105,7 @@ class GodotProcessor extends AudioWorkletProcessor {
}
parse_message(p_cmd, p_data) {
if (p_cmd === "start" && p_data) {
if (p_cmd === 'start' && p_data) {
const state = p_data[0];
let idx = 0;
this.lock = state.subarray(idx, ++idx);
@@ -114,7 +114,7 @@ class GodotProcessor extends AudioWorkletProcessor {
const avail_out = state.subarray(idx, ++idx);
this.input = new RingBuffer(p_data[1], avail_in);
this.output = new RingBuffer(p_data[2], avail_out);
} else if (p_cmd === "stop") {
} else if (p_cmd === 'stop') {
this.runing = false;
this.output = null;
this.input = null;
@@ -143,7 +143,7 @@ class GodotProcessor extends AudioWorkletProcessor {
GodotProcessor.write_input(this.input_buffer, input);
this.input.write(this.input_buffer);
} else {
this.port.postMessage("Input buffer is full! Skipping input frame.");
this.port.postMessage('Input buffer is full! Skipping input frame.');
}
}
const process_output = GodotProcessor.array_has_data(outputs);
@@ -157,7 +157,7 @@ class GodotProcessor extends AudioWorkletProcessor {
this.output.read(this.output_buffer);
GodotProcessor.write_output(output, this.output_buffer);
} else {
this.port.postMessage("Output buffer has not enough frames! Skipping output frame.");
this.port.postMessage('Output buffer has not enough frames! Skipping output frame.');
}
}
this.process_notify();

View File

@@ -58,7 +58,7 @@ const GodotAudio = {
// no default
}
onstatechange(state);
}
};
ctx.onstatechange(); // Immeditately notify state.
// Update computed latency
GodotAudio.interval = setInterval(function () {
@@ -81,19 +81,23 @@ const GodotAudio = {
}
function gotMediaInput(stream) {
GodotAudio.input = GodotAudio.ctx.createMediaStreamSource(stream);
callback(GodotAudio.input)
callback(GodotAudio.input);
}
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({
"audio": true
}).then(gotMediaInput, function(e) { GodotRuntime.print(e) });
'audio': true,
}).then(gotMediaInput, function (e) {
GodotRuntime.print(e);
});
} else {
if (!navigator.getUserMedia) {
navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
}
navigator.getUserMedia({
"audio": true
}, gotMediaInput, function(e) { GodotRuntime.print(e) });
'audio': true,
}, gotMediaInput, function (e) {
GodotRuntime.print(e);
});
}
},
@@ -127,7 +131,7 @@ const GodotAudio = {
resolve();
}).catch(function (e) {
ctx.onstatechange = null;
GodotRuntime.error("Error closing AudioContext", e);
GodotRuntime.error('Error closing AudioContext', e);
resolve();
});
},
@@ -176,7 +180,7 @@ const GodotAudio = {
},
};
autoAddDeps(GodotAudio, "$GodotAudio");
autoAddDeps(GodotAudio, '$GodotAudio');
mergeInto(LibraryManager.library, GodotAudio);
/**
@@ -195,8 +199,8 @@ const GodotAudioWorklet = {
GodotAudio.ctx,
'godot-processor',
{
'outputChannelCount': [channels]
}
'outputChannelCount': [channels],
},
);
return Promise.resolve();
});
@@ -262,7 +266,7 @@ const GodotAudioWorklet = {
},
};
autoAddDeps(GodotAudioWorklet, "$GodotAudioWorklet");
autoAddDeps(GodotAudioWorklet, '$GodotAudioWorklet');
mergeInto(LibraryManager.library, GodotAudioWorklet);
/*
@@ -336,5 +340,5 @@ const GodotAudioScript = {
},
};
autoAddDeps(GodotAudioScript, "$GodotAudioScript");
autoAddDeps(GodotAudioScript, '$GodotAudioScript');
mergeInto(LibraryManager.library, GodotAudioScript);

View File

@@ -53,7 +53,7 @@ const GodotDisplayListeners = {
this.event = p_event;
this.method = p_method;
this.capture = p_capture;
};
}
GodotDisplayListeners.handlers.push(new Handler(target, event, method, capture));
target.addEventListener(event, method, capture);
},
@@ -90,7 +90,7 @@ const GodotDisplayDragDrop = {
} else if (entry.isFile) {
GodotDisplayDragDrop.add_file(entry);
} else {
GodotRuntime.error("Unrecognized entry...", entry);
GodotRuntime.error('Unrecognized entry...', entry);
}
},
@@ -112,25 +112,25 @@ const GodotDisplayDragDrop = {
const reader = new FileReader();
reader.onload = function () {
const f = {
"path": file.relativePath || file.webkitRelativePath,
"name": file.name,
"type": file.type,
"size": file.size,
"data": reader.result
'path': file.relativePath || file.webkitRelativePath,
'name': file.name,
'type': file.type,
'size': file.size,
'data': reader.result,
};
if (!f['path']) {
f['path'] = f['name'];
}
GodotDisplayDragDrop.pending_files.push(f);
resolve()
resolve();
};
reader.onerror = function () {
GodotRuntime.print("Error reading file");
GodotRuntime.print('Error reading file');
reject();
}
};
reader.readAsArrayBuffer(file);
}, function (err) {
GodotRuntime.print("Error!");
GodotRuntime.print('Error!');
reject();
});
}));
@@ -155,9 +155,9 @@ const GodotDisplayDragDrop = {
for (let i = 0; i < ev.dataTransfer.items.length; i++) {
const item = ev.dataTransfer.items[i];
let entry = null;
if ("getAsEntry" in item) {
if ('getAsEntry' in item) {
entry = item.getAsEntry();
} else if ("webkitGetAsEntry" in item) {
} else if ('webkitGetAsEntry' in item) {
entry = item.webkitGetAsEntry();
}
if (entry) {
@@ -165,24 +165,24 @@ const GodotDisplayDragDrop = {
}
}
} else {
GodotRuntime.error("File upload not supported");
GodotRuntime.error('File upload not supported');
}
new Promise(GodotDisplayDragDrop.process).then(function () {
const DROP = "/tmp/drop-" + parseInt(Math.random() * (1 << 30), 10) + "/";
const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
const drops = [];
const files = [];
FS.mkdir(DROP);
GodotDisplayDragDrop.pending_files.forEach((elem) => {
const path = elem['path'];
GodotFS.copy_to_fs(DROP + path, elem['data']);
let idx = path.indexOf("/");
let idx = path.indexOf('/');
if (idx === -1) {
// Root file
drops.push(DROP + path);
} else {
// Subdir
const sub = path.substr(0, idx);
idx = sub.indexOf("/");
idx = sub.indexOf('/');
if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
drops.push(DROP + sub);
}
@@ -196,24 +196,25 @@ const GodotDisplayDragDrop = {
// Remove temporary files
files.forEach(function (file) {
FS.unlink(file);
let dir = file.replace(DROP, "");
let idx = dir.lastIndexOf("/");
let dir = file.replace(DROP, '');
let idx = dir.lastIndexOf('/');
while (idx > 0) {
dir = dir.substr(0, idx);
if (dirs.indexOf(DROP + dir) === -1) {
dirs.push(DROP + dir);
}
idx = dir.lastIndexOf("/");
idx = dir.lastIndexOf('/');
}
});
// Remove dirs.
dirs.sort(function (a, b) {
const al = (a.match(/\//g) || []).length;
const bl = (b.match(/\//g) || []).length;
if (al > bl)
if (al > bl) {
return -1;
else if (al < bl)
} else if (al < bl) {
return 1;
}
return 0;
}).forEach(function (dir) {
FS.rmdir(dir);
@@ -249,7 +250,7 @@ const GodotDisplayCursor = {
let css = shape;
if (shape in GodotDisplayCursor.cursors) {
const c = GodotDisplayCursor.cursors[shape];
css = 'url("' + c.url + '") ' + c.x + ' ' + c.y + ', auto';
css = `url("${c.url}") ${c.x} ${c.y}, auto`;
}
if (GodotDisplayCursor.visible) {
GodotDisplayCursor.set_style(css);
@@ -281,7 +282,7 @@ const GodotDisplay = {
godot_js_display_is_swap_ok_cancel: function () {
const win = (['Windows', 'Win64', 'Win32', 'WinCE']);
const plat = navigator.platform || "";
const plat = navigator.platform || '';
if (win.indexOf(plat) !== -1) {
return 1;
}
@@ -330,7 +331,7 @@ const GodotDisplay = {
}
navigator.clipboard.writeText(text).catch(function (e) {
// Setting OS clipboard is only possible from an input callback.
GodotRuntime.error("Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:", e);
GodotRuntime.error('Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:', e);
});
return 0;
},
@@ -355,9 +356,9 @@ const GodotDisplay = {
*/
godot_js_display_window_request_fullscreen: function () {
const canvas = GodotConfig.canvas;
(canvas.requestFullscreen || canvas.msRequestFullscreen ||
canvas.mozRequestFullScreen || canvas.mozRequestFullscreen ||
canvas.webkitRequestFullscreen
(canvas.requestFullscreen || canvas.msRequestFullscreen
|| canvas.mozRequestFullScreen || canvas.mozRequestFullscreen
|| canvas.webkitRequestFullscreen
).call(canvas);
},
@@ -374,7 +375,7 @@ const GodotDisplay = {
document.head.appendChild(link);
}
const old_icon = GodotDisplay.window_icon;
const png = new Blob([GodotRuntime.heapCopy(HEAPU8, p_ptr, p_len)], { type: "image/png" });
const png = new Blob([GodotRuntime.heapCopy(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
GodotDisplay.window_icon = URL.createObjectURL(png);
link.href = GodotDisplay.window_icon;
if (old_icon) {
@@ -453,7 +454,7 @@ const GodotDisplay = {
},
godot_js_display_drop_files_cb: function (callback) {
const func = GodotRuntime.get_func(callback)
const func = GodotRuntime.get_func(callback);
const dropFiles = function (files) {
const args = files || [];
if (!args.length) {

View File

@@ -46,7 +46,6 @@ const GodotEval = {
}
switch (typeof eval_ret) {
case 'boolean':
GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'i32');
return 1; // BOOL
@@ -66,8 +65,7 @@ const GodotEval = {
if (ArrayBuffer.isView(eval_ret) && !(eval_ret instanceof Uint8Array)) {
eval_ret = new Uint8Array(eval_ret.buffer);
}
else if (eval_ret instanceof ArrayBuffer) {
} else if (eval_ret instanceof ArrayBuffer) {
eval_ret = new Uint8Array(eval_ret);
}
if (eval_ret instanceof Uint8Array) {
@@ -82,6 +80,6 @@ const GodotEval = {
}
return 0; // NIL
},
}
};
mergeInto(LibraryManager.library, GodotEval);

View File

@@ -34,14 +34,14 @@ const GodotHTTPRequest = {
requests: [],
getUnusedRequestId: function () {
var idMax = GodotHTTPRequest.requests.length;
for (var potentialId = 0; potentialId < idMax; ++potentialId) {
const idMax = GodotHTTPRequest.requests.length;
for (let potentialId = 0; potentialId < idMax; ++potentialId) {
if (GodotHTTPRequest.requests[potentialId] instanceof XMLHttpRequest) {
continue;
}
return potentialId;
}
GodotHTTPRequest.requests.push(null)
GodotHTTPRequest.requests.push(null);
return idMax;
},
@@ -51,14 +51,14 @@ const GodotHTTPRequest = {
},
godot_xhr_new: function () {
var newId = GodotHTTPRequest.getUnusedRequestId();
GodotHTTPRequest.requests[newId] = new XMLHttpRequest;
const newId = GodotHTTPRequest.getUnusedRequestId();
GodotHTTPRequest.requests[newId] = new XMLHttpRequest();
GodotHTTPRequest.setupRequest(GodotHTTPRequest.requests[newId]);
return newId;
},
godot_xhr_reset: function (xhrId) {
GodotHTTPRequest.requests[xhrId] = new XMLHttpRequest;
GodotHTTPRequest.requests[xhrId] = new XMLHttpRequest();
GodotHTTPRequest.setupRequest(GodotHTTPRequest.requests[xhrId]);
},
@@ -83,7 +83,7 @@ const GodotHTTPRequest = {
godot_xhr_send_string: function (xhrId, strPtr) {
if (!strPtr) {
GodotRuntime.error("Failed to send string per XHR: null pointer");
GodotRuntime.error('Failed to send string per XHR: null pointer');
return;
}
GodotHTTPRequest.requests[xhrId].send(GodotRuntime.parseString(strPtr));
@@ -91,11 +91,11 @@ const GodotHTTPRequest = {
godot_xhr_send_data: function (xhrId, ptr, len) {
if (!ptr) {
GodotRuntime.error("Failed to send data per XHR: null pointer");
GodotRuntime.error('Failed to send data per XHR: null pointer');
return;
}
if (len < 0) {
GodotRuntime.error("Failed to send data per XHR: buffer length less than 0");
GodotRuntime.error('Failed to send data per XHR: buffer length less than 0');
return;
}
GodotHTTPRequest.requests[xhrId].send(HEAPU8.subarray(ptr, ptr + len));
@@ -114,30 +114,32 @@ const GodotHTTPRequest = {
},
godot_xhr_get_response_headers_length: function (xhrId) {
var headers = GodotHTTPRequest.requests[xhrId].getAllResponseHeaders();
const headers = GodotHTTPRequest.requests[xhrId].getAllResponseHeaders();
return headers === null ? 0 : GodotRuntime.strlen(headers);
},
godot_xhr_get_response_headers: function (xhrId, dst, len) {
var str = GodotHTTPRequest.requests[xhrId].getAllResponseHeaders();
if (str === null)
const str = GodotHTTPRequest.requests[xhrId].getAllResponseHeaders();
if (str === null) {
return;
}
GodotRuntime.stringToHeap(str, dst, len);
},
godot_xhr_get_response_length: function (xhrId) {
var body = GodotHTTPRequest.requests[xhrId].response;
const body = GodotHTTPRequest.requests[xhrId].response;
return body === null ? 0 : body.byteLength;
},
godot_xhr_get_response: function (xhrId, dst, len) {
var buf = GodotHTTPRequest.requests[xhrId].response;
if (buf === null)
let buf = GodotHTTPRequest.requests[xhrId].response;
if (buf === null) {
return;
}
buf = new Uint8Array(buf).subarray(0, len);
HEAPU8.set(buf, dst);
},
};
autoAddDeps(GodotHTTPRequest, "$GodotHTTPRequest");
autoAddDeps(GodotHTTPRequest, '$GodotHTTPRequest');
mergeInto(LibraryManager.library, GodotHTTPRequest);

View File

@@ -49,7 +49,7 @@ const IDHandler = {
},
};
autoAddDeps(IDHandler, "$IDHandler");
autoAddDeps(IDHandler, '$IDHandler');
mergeInto(LibraryManager.library, IDHandler);
const GodotConfig = {
@@ -57,12 +57,12 @@ const GodotConfig = {
$GodotConfig__deps: ['$GodotRuntime'],
$GodotConfig: {
canvas: null,
locale: "en",
locale: 'en',
resize_on_start: false,
on_execute: null,
init_config: function (p_opts) {
GodotConfig.resize_on_start = p_opts['resizeCanvasOnStart'] ? true : false;
GodotConfig.resize_on_start = !!p_opts['resizeCanvasOnStart'];
GodotConfig.canvas = p_opts['canvas'];
GodotConfig.locale = p_opts['locale'] || GodotConfig.locale;
GodotConfig.on_execute = p_opts['onExecute'];
@@ -71,12 +71,12 @@ const GodotConfig = {
},
locate_file: function (file) {
return Module["locateFile"](file); // eslint-disable-line no-undef
return Module['locateFile'](file); // eslint-disable-line no-undef
},
},
godot_js_config_canvas_id_get: function (p_ptr, p_ptr_max) {
GodotRuntime.stringToHeap('#' + GodotConfig.canvas.id, p_ptr, p_ptr_max);
GodotRuntime.stringToHeap(`#${GodotConfig.canvas.id}`, p_ptr, p_ptr_max);
},
godot_js_config_locale_get: function (p_ptr, p_ptr_max) {
@@ -91,7 +91,6 @@ const GodotConfig = {
autoAddDeps(GodotConfig, '$GodotConfig');
mergeInto(LibraryManager.library, GodotConfig);
const GodotFS = {
$GodotFS__deps: ['$FS', '$IDBFS', '$GodotRuntime'],
$GodotFS__postset: [
@@ -142,7 +141,7 @@ const GodotFS = {
if (err) {
GodotFS._mount_points = [];
GodotFS._idbfs = false;
GodotRuntime.print("IndexedDB not available: " + err.message);
GodotRuntime.print(`IndexedDB not available: ${err.message}`);
} else {
GodotFS._idbfs = true;
}
@@ -157,7 +156,7 @@ const GodotFS = {
try {
FS.unmount(path);
} catch (e) {
GodotRuntime.print("Already unmounted", e);
GodotRuntime.print('Already unmounted', e);
}
if (GodotFS._idbfs && IDBFS.dbs[path]) {
IDBFS.dbs[path].close();
@@ -178,7 +177,7 @@ const GodotFS = {
return new Promise(function (resolve, reject) {
FS.syncfs(false, function (error) {
if (error) {
GodotRuntime.error('Failed to save IDB file system: ' + error.message);
GodotRuntime.error(`Failed to save IDB file system: ${error.message}`);
}
GodotFS._syncing = false;
resolve(error);
@@ -188,8 +187,8 @@ const GodotFS = {
// Copies a buffer to the internal file system. Creating directories recursively.
copy_to_fs: function (path, buffer) {
const idx = path.lastIndexOf("/");
let dir = "/";
const idx = path.lastIndexOf('/');
let dir = '/';
if (idx > 0) {
dir = path.slice(0, idx);
}

View File

@@ -116,5 +116,5 @@ const GodotRuntime = {
},
},
};
autoAddDeps(GodotRuntime, "$GodotRuntime");
autoAddDeps(GodotRuntime, '$GodotRuntime');
mergeInto(LibraryManager.library, GodotRuntime);