From dda92bd41f4bee11e2cc5de265ce4fbf5221f1ff Mon Sep 17 00:00:00 2001 From: stonedDiscord Date: Wed, 20 Sep 2023 13:10:36 +0200 Subject: autoformat with eslint --- webAO/__tests__/iniParse.test.js | 40 +- webAO/client.ts | 460 +++++++++++------------ webAO/client/__tests__/setEmote.test.js | 132 +++---- webAO/client/aoHost.ts | 2 +- webAO/client/saveChatLogHandle.ts | 6 +- webAO/client/sender/sendIC.ts | 2 +- webAO/client/sender/sendServer.ts | 2 +- webAO/client/setEmote.ts | 76 ++-- webAO/components/__tests__/audioChannels.test.js | 10 +- webAO/components/__tests__/blips.test.js | 10 +- webAO/components/audioChannels.js | 10 +- webAO/components/blip.js | 14 +- webAO/constants/backgrounds.js | 46 +-- webAO/constants/characters.js | 102 ++--- webAO/constants/evidence.js | 16 +- webAO/constants/music.js | 98 ++--- webAO/dom/addEvidence.ts | 16 +- webAO/dom/changeBackgroundOOC.ts | 2 +- webAO/dom/changeMusicVolume.ts | 2 +- webAO/dom/changeVolume.js | 6 +- webAO/dom/musicListFilter.ts | 18 +- webAO/dom/muteListClick.ts | 20 +- webAO/dom/onEnter.ts | 183 +++++---- webAO/dom/opusCheck.ts | 28 +- webAO/dom/reconnectButton.ts | 2 +- webAO/dom/resetOffset.ts | 4 +- webAO/dom/toggleEffect.js | 10 +- webAO/dom/toggleElement.js | 12 +- webAO/dom/twofactor.ts | 4 +- webAO/dom/updateActionCommands.ts | 2 +- webAO/dom/updateBackgroundPreview.ts | 4 +- webAO/dom/window.ts | 2 +- webAO/encoding.ts | 36 +- webAO/iniParse.js | 58 +-- webAO/master.ts | 182 ++++----- webAO/packets/handlers/handleBN.ts | 135 ++++--- webAO/packets/handlers/handleCT.ts | 2 +- webAO/packets/handlers/handleDONE.ts | 6 +- webAO/packets/handlers/handleFL.ts | 73 ++-- webAO/packets/handlers/handleHP.ts | 25 +- webAO/packets/handlers/handleLE.ts | 2 +- webAO/packets/handlers/handleMS.ts | 2 + webAO/packets/handlers/handlePV.ts | 132 +++---- webAO/packets/handlers/handleRM.ts | 4 +- webAO/packets/handlers/handleSC.ts | 2 +- webAO/services/__tests__/downloadFile.test.ts | 6 +- webAO/services/downloadFile.ts | 12 +- webAO/services/request.js | 94 ++--- webAO/styles/chatbox/chatboxes.js | 52 +-- webAO/ui.js | 1 + webAO/utils/__tests__/aoml.test.ts | 92 ++--- webAO/utils/__tests__/tryUrls.test.ts | 18 +- webAO/utils/aoml.ts | 6 +- webAO/utils/calculateApngLength.js | 44 +-- webAO/utils/calculateGifLength.js | 34 +- webAO/utils/calculateWebpLength.js | 32 +- webAO/viewport/utils/handleICSpeaking.ts | 6 +- webAO/viewport/viewport.ts | 10 +- 58 files changed, 1203 insertions(+), 1204 deletions(-) (limited to 'webAO') diff --git a/webAO/__tests__/iniParse.test.js b/webAO/__tests__/iniParse.test.js index deb08f3..d9e1b7a 100644 --- a/webAO/__tests__/iniParse.test.js +++ b/webAO/__tests__/iniParse.test.js @@ -10,30 +10,30 @@ number = 9 1 = Normal#-#normal#0#1 `; describe('iniParse', () => { - test('should not lowercase value if key is showname', () => { - const parsedIni = iniParse(` + test('should not lowercase value if key is showname', () => { + const parsedIni = iniParse(` [test] showname = MATT `); - expect(parsedIni.test.showname).toBe('MATT'); - }); - test('should lowercase value if key is not showname', () => { - const parsedIni = iniParse(` + expect(parsedIni.test.showname).toBe('MATT'); + }); + test('should lowercase value if key is not showname', () => { + const parsedIni = iniParse(` [test] party = TIME `); - expect(parsedIni.test.party).toBe('time'); - }); - test('should parse sections', () => { - const parsedIni = iniParse(iniExample); - expect(Object.keys(parsedIni).length).toBe(2); - }); - test('should parse parameters', () => { - const parsedIni = iniParse(iniExample); - expect(Object.keys(parsedIni.options).length).toBe(2); - }); - test('should remove empty lines', () => { - const parsedIni = iniParse(` + expect(parsedIni.test.party).toBe('time'); + }); + test('should parse sections', () => { + const parsedIni = iniParse(iniExample); + expect(Object.keys(parsedIni).length).toBe(2); + }); + test('should parse parameters', () => { + const parsedIni = iniParse(iniExample); + expect(Object.keys(parsedIni.options).length).toBe(2); + }); + test('should remove empty lines', () => { + const parsedIni = iniParse(` [test] @@ -42,6 +42,6 @@ describe('iniParse', () => { `); - expect(Object.keys(parsedIni.test).length).toBe(2); - }); + expect(Object.keys(parsedIni.test).length).toBe(2); + }); }); diff --git a/webAO/client.ts b/webAO/client.ts index e5c5e2b..f7b8ebb 100644 --- a/webAO/client.ts +++ b/webAO/client.ts @@ -17,16 +17,16 @@ import { loadResources } from './client/loadResources' import { AO_HOST } from './client/aoHost' import { fetchBackgroundList, fetchEvidenceList, fetchCharacterList, fetchManifest } from './client/fetchLists' const version = process.env.npm_package_version; -let { ip: serverIP, mode, theme } = queryParser(); +const { ip: serverIP, mode, theme } = queryParser(); -let THEME: string = theme || "default"; +const THEME: string = theme || "default"; export let CHATBOX: string; export const setCHATBOX = (val: string) => { - CHATBOX = val + CHATBOX = val } export let client: Client; export const setClient = (val: Client) => { - client = val + client = val } export const UPDATE_INTERVAL = 60; @@ -38,316 +38,316 @@ export const UPDATE_INTERVAL = 60; */ export let oldLoading = false; export const setOldLoading = (val: boolean) => { - console.warn("old loading set to "+val) - oldLoading = val + console.warn("old loading set to "+val) + oldLoading = val } // presettings export let selectedMenu = 1; export const setSelectedMenu = (val: number) => { - selectedMenu = val + selectedMenu = val } export let selectedShout = 0; export const setSelectedShout = (val: number) => { - selectedShout = val + selectedShout = val } export let extrafeatures: string[] = []; export const setExtraFeatures = (val: any) => { - extrafeatures = val + extrafeatures = val } export let banned: boolean = false; export const setBanned = (val: boolean) => { - banned = val + banned = val } let hdid: string; const fpPromise = FingerprintJS.load(); fpPromise - .then((fp) => fp.get()) - .then((result) => { - hdid = result.visitorId; + .then((fp) => fp.get()) + .then((result) => { + hdid = result.visitorId; - client = new Client(serverIP); - client.connect() - isLowMemory(); - loadResources(); - }); + client = new Client(serverIP); + client.connect() + isLowMemory(); + loadResources(); + }); export const delay = (ms: number) => new Promise((res) => setTimeout(res, ms)); export let lastICMessageTime = new Date(0); export const setLastICMessageTime = (val: Date) => { - lastICMessageTime = val + lastICMessageTime = val } class Client extends EventEmitter { - serv: any; - hp: number[]; - playerID: number; - charID: number; - char_list_length: number; - evidence_list_length: number; - music_list_length: number; - testimonyID: number; - chars: any; - emotes: any; - evidences: any; - areas: any; - musics: any; - musics_time: boolean; - callwords: string[]; - banned: boolean; - resources: any; - selectedEmote: number; - selectedEvidence: number; - sender: ISender; - checkUpdater: any; - _lastTimeICReceived: any; - manifest: string[]; - viewport: Viewport; - partial_packet: boolean; - temp_packet: String; - connect: () => void; - loadResources: () => void - isLowMemory: () => void - constructor(address: string) { - super(); - - this.connect = () => { - this.on("open", this.onOpen.bind(this)); - this.on("close", this.onClose.bind(this)); - this.on("message", this.onMessage.bind(this)); - this.on("error", this.onError.bind(this)); - if (mode !== "replay") { - this.serv = new WebSocket(`ws://${address}`); - // Assign the websocket events - this.serv.addEventListener("open", this.emit.bind(this, "open")); - this.serv.addEventListener("close", this.emit.bind(this, "close")); - this.serv.addEventListener("message", this.emit.bind(this, "message")); - this.serv.addEventListener("error", this.emit.bind(this, "error")); - } else { - this.joinServer(); - } + serv: any; + hp: number[]; + playerID: number; + charID: number; + char_list_length: number; + evidence_list_length: number; + music_list_length: number; + testimonyID: number; + chars: any; + emotes: any; + evidences: any; + areas: any; + musics: any; + musics_time: boolean; + callwords: string[]; + banned: boolean; + resources: any; + selectedEmote: number; + selectedEvidence: number; + sender: ISender; + checkUpdater: any; + _lastTimeICReceived: any; + manifest: string[]; + viewport: Viewport; + partial_packet: boolean; + temp_packet: string; + connect: () => void; + loadResources: () => void + isLowMemory: () => void + constructor(address: string) { + super(); + + this.connect = () => { + this.on("open", this.onOpen.bind(this)); + this.on("close", this.onClose.bind(this)); + this.on("message", this.onMessage.bind(this)); + this.on("error", this.onError.bind(this)); + if (mode !== "replay") { + this.serv = new WebSocket(`ws://${address}`); + // Assign the websocket events + this.serv.addEventListener("open", this.emit.bind(this, "open")); + this.serv.addEventListener("close", this.emit.bind(this, "close")); + this.serv.addEventListener("message", this.emit.bind(this, "message")); + this.serv.addEventListener("error", this.emit.bind(this, "error")); + } else { + this.joinServer(); + } + } + + this.hp = [0, 0]; + this.playerID = 1; + this.charID = -1; + this.char_list_length = 0; + this.evidence_list_length = 0; + this.music_list_length = 0; + this.testimonyID = 0; + this.chars = []; + this.emotes = []; + this.evidences = []; + this.areas = []; + this.musics = []; + this.musics_time = false; + this.callwords = []; + this.manifest = []; + this.resources = getResources(AO_HOST, THEME); + this.selectedEmote = -1; + this.selectedEvidence = 0; + this.checkUpdater = null; + this.sender = sender + this.viewport = masterViewport(); + this._lastTimeICReceived = new Date(0); + this.partial_packet = false; + this.temp_packet = ""; + loadResources + isLowMemory } - this.hp = [0, 0]; - this.playerID = 1; - this.charID = -1; - this.char_list_length = 0; - this.evidence_list_length = 0; - this.music_list_length = 0; - this.testimonyID = 0; - this.chars = []; - this.emotes = []; - this.evidences = []; - this.areas = []; - this.musics = []; - this.musics_time = false; - this.callwords = []; - this.manifest = []; - this.resources = getResources(AO_HOST, THEME); - this.selectedEmote = -1; - this.selectedEvidence = 0; - this.checkUpdater = null; - this.sender = sender - this.viewport = masterViewport(); - this._lastTimeICReceived = new Date(0); - this.partial_packet = false; - this.temp_packet = ""; - loadResources - isLowMemory - } - - /** + /** * Gets the current player's character. */ - get character() { - return this.chars[this.charID]; - } + get character() { + return this.chars[this.charID]; + } - /** + /** * Gets the player's currently selected emote. */ - get emote() { - return this.emotes[this.selectedEmote]; - } + get emote() { + return this.emotes[this.selectedEmote]; + } - /** + /** * Gets the current evidence ID unless the player doesn't want to present any evidence */ - get evidence() { - return document.getElementById("button_present").classList.contains("dark") - ? this.selectedEvidence - : 0; - } + get evidence() { + return document.getElementById("button_present").classList.contains("dark") + ? this.selectedEvidence + : 0; + } - /** + /** * Hook for sending messages to the client * @param {string} message the message to send */ - handleSelf(message: string) { - const message_event = new MessageEvent("websocket", { data: message }); - setTimeout(() => this.onMessage(message_event), 1); - } + handleSelf(message: string) { + const message_event = new MessageEvent("websocket", { data: message }); + setTimeout(() => this.onMessage(message_event), 1); + } - /** + /** * Begins the handshake process by sending an identifier * to the server. */ - joinServer() { - this.sender.sendServer(`HI#${hdid}#%`); - if (mode !== "replay") { - this.checkUpdater = setInterval(() => this.sender.sendCheck(), 5000); + joinServer() { + this.sender.sendServer(`HI#${hdid}#%`); + if (mode !== "replay") { + this.checkUpdater = setInterval(() => this.sender.sendCheck(), 5000); + } } - } - /** + /** * Triggered when a connection is established to the server. */ - onOpen(_e: Event) { - client.joinServer(); - } + onOpen(_e: Event) { + client.joinServer(); + } - /** + /** * Triggered when the connection to the server closes. * @param {CloseEvent} e */ - onClose(e: CloseEvent) { - console.error(`The connection was closed: ${e.reason} (${e.code})`); - if (extrafeatures.length == 0 && banned === false) { - document.getElementById("client_errortext").textContent = + onClose(e: CloseEvent) { + console.error(`The connection was closed: ${e.reason} (${e.code})`); + if (extrafeatures.length == 0 && banned === false) { + document.getElementById("client_errortext").textContent = "Could not connect to the server"; + } + document.getElementById("client_waiting").style.display = "block"; + document.getElementById("client_error").style.display = "flex"; + document.getElementById("client_loading").style.display = "none"; + document.getElementById("error_id").textContent = String(e.code); + this.cleanup(); } - document.getElementById("client_waiting").style.display = "block"; - document.getElementById("client_error").style.display = "flex"; - document.getElementById("client_loading").style.display = "none"; - document.getElementById("error_id").textContent = String(e.code); - this.cleanup(); - } - - /** + + /** * Triggered when a packet is received from the server. * @param {MessageEvent} e */ - onMessage(e: MessageEvent) { - const msg = e.data; - console.debug(`S: ${msg}`); + onMessage(e: MessageEvent) { + const msg = e.data; + console.debug(`S: ${msg}`); - this.handle_server_packet(msg); + this.handle_server_packet(msg); - } + } - /** + /** * Decode the packet * @param {MessageEvent} e */ - handle_server_packet(p_data: string) -{ - let in_data = p_data; - - if (!p_data.endsWith("%")) { - this.partial_packet = true; - this.temp_packet = this.temp_packet + in_data - console.log("Partial packet") - return; - } - - else { - if (this.partial_packet) { - in_data = this.temp_packet + in_data - this.temp_packet = ""; - this.partial_packet = false; - } - } - - const packet_list = in_data.split("%"); - - for (var packet of packet_list) { - let f_contents; - // Packet should *always* end with # - if (packet.endsWith("#")) { - f_contents = packet.slice(0, -1).split("#"); - } - // But, if it somehow doesn't, we should still be able to handle it - else { - f_contents = packet.split("#"); - } - // Empty packets are suspicious! - if (f_contents.length == 0) { - console.warn("WARNING: Empty packet received from server, skipping..."); - continue; - } - // Take the first arg as the command - const command = f_contents[0]; - if(command!=="") + handle_server_packet(p_data: string) { - // The rest is contents of the packet - packetHandler.has(command) - ? packetHandler.get(command)(f_contents) - : console.warn(`Invalid packet header ${command}`); - }; + let in_data = p_data; + + if (!p_data.endsWith("%")) { + this.partial_packet = true; + this.temp_packet = this.temp_packet + in_data + console.log("Partial packet") + return; + } + + else { + if (this.partial_packet) { + in_data = this.temp_packet + in_data + this.temp_packet = ""; + this.partial_packet = false; + } + } + + const packet_list = in_data.split("%"); + + for (const packet of packet_list) { + let f_contents; + // Packet should *always* end with # + if (packet.endsWith("#")) { + f_contents = packet.slice(0, -1).split("#"); + } + // But, if it somehow doesn't, we should still be able to handle it + else { + f_contents = packet.split("#"); + } + // Empty packets are suspicious! + if (f_contents.length == 0) { + console.warn("WARNING: Empty packet received from server, skipping..."); + continue; + } + // Take the first arg as the command + const command = f_contents[0]; + if(command!=="") + { + // The rest is contents of the packet + packetHandler.has(command) + ? packetHandler.get(command)(f_contents) + : console.warn(`Invalid packet header ${command}`); + } + } } - } - /** + /** * Triggered when an network error occurs. * @param {ErrorEvent} e */ - onError(e: ErrorEvent) { - console.error(`A network error occurred`); - document.getElementById("client_error").style.display = "flex"; - this.cleanup(); - } + onError(e: ErrorEvent) { + console.error(`A network error occurred`); + document.getElementById("client_error").style.display = "flex"; + this.cleanup(); + } - /** + /** * Stop sending keepalives to the server. */ - cleanup() { - clearInterval(this.checkUpdater); - this.serv.close(); - } + cleanup() { + clearInterval(this.checkUpdater); + this.serv.close(); + } - /** + /** * Parse the lines in the OOC and play them * @param {*} args packet arguments */ - handleReplay() { - const ooclog = document.getElementById("client_ooclog"); - const rawLog = false; - let rtime: number = Number( - (document.getElementById("client_replaytimer")).value - ); - - const clines = ooclog.value.split(/\r?\n/); - if (clines[0]) { - const currentLine = String(clines[0]); - this.handleSelf(currentLine); - ooclog.value = clines.slice(1).join("\r\n"); - if (currentLine.substr(0, 4) === "wait" && rawLog === false) { - rtime = Number(currentLine.split("#")[1]); - } else if (currentLine.substr(0, 2) !== "MS") { - rtime = 0; - } - - setTimeout(() => onReplayGo(null), rtime); + handleReplay() { + const ooclog = document.getElementById("client_ooclog"); + const rawLog = false; + let rtime: number = Number( + (document.getElementById("client_replaytimer")).value + ); + + const clines = ooclog.value.split(/\r?\n/); + if (clines[0]) { + const currentLine = String(clines[0]); + this.handleSelf(currentLine); + ooclog.value = clines.slice(1).join("\r\n"); + if (currentLine.substr(0, 4) === "wait" && rawLog === false) { + rtime = Number(currentLine.split("#")[1]); + } else if (currentLine.substr(0, 2) !== "MS") { + rtime = 0; + } + + setTimeout(() => onReplayGo(null), rtime); + } } - } - resetMusicList() { - this.musics = []; - document.getElementById("client_musiclist").innerHTML = ""; - } + resetMusicList() { + this.musics = []; + document.getElementById("client_musiclist").innerHTML = ""; + } - resetAreaList() { - this.areas = []; - document.getElementById("areas").innerHTML = ""; + resetAreaList() { + this.areas = []; + document.getElementById("areas").innerHTML = ""; - fetchBackgroundList(); - fetchEvidenceList(); - fetchCharacterList(); - } + fetchBackgroundList(); + fetchEvidenceList(); + fetchCharacterList(); + } } diff --git a/webAO/client/__tests__/setEmote.test.js b/webAO/client/__tests__/setEmote.test.js index 829c94d..a0091c0 100644 --- a/webAO/client/__tests__/setEmote.test.js +++ b/webAO/client/__tests__/setEmote.test.js @@ -9,104 +9,104 @@ jest.mock('../../viewport/utils/createSfxAudio'); jest.mock('../../viewport/utils/createShoutAudio'); jest.mock('../../viewport/utils/createTestimonyAudio'); describe('setEmote', () => { - const AO_HOST = ''; + const AO_HOST = ''; - const client = new Client('127.0.0.1'); - const firstExtension = '.gif'; + const client = new Client('127.0.0.1'); + const firstExtension = '.gif'; - test('Should have a client_def_char_img with a valid source', async () => { - fileExists.mockReturnValue(true); - document.body.innerHTML = ` + test('Should have a client_def_char_img with a valid source', async () => { + fileExists.mockReturnValue(true); + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 0, 'def'); - const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; - expect(document.getElementById('client_def_char_img').src).toEqual(expected); - }); - test('Should have a client_pro_char_img to have a valid src', async () => { - document.body.innerHTML = ` + await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 0, 'def'); + const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; + expect(document.getElementById('client_def_char_img').src).toEqual(expected); + }); + test('Should have a client_pro_char_img to have a valid src', async () => { + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 0, 'pro'); - const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; - expect(document.getElementById('client_pro_char_img').src).toEqual(expected); - }); - test('Should have a client_wit_char_img', async () => { - document.body.innerHTML = ` + await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 0, 'pro'); + const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; + expect(document.getElementById('client_pro_char_img').src).toEqual(expected); + }); + test('Should have a client_wit_char_img', async () => { + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 0, 'wit'); - const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; + await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 0, 'wit'); + const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; - expect(document.getElementById('client_wit_char_img').src).toEqual(expected); - }); - test('Should have a client_def_pair_img', async () => { - document.body.innerHTML = ` + expect(document.getElementById('client_wit_char_img').src).toEqual(expected); + }); + test('Should have a client_def_pair_img', async () => { + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 1, 'def'); - const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; + await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 1, 'def'); + const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; - expect(document.getElementById('client_def_pair_img').src).toEqual(expected); - }); - test('Should have a client_pro_pair_img', async () => { - document.body.innerHTML = ` + expect(document.getElementById('client_def_pair_img').src).toEqual(expected); + }); + test('Should have a client_pro_pair_img', async () => { + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 1, 'pro'); - const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; + await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 1, 'pro'); + const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; - expect(document.getElementById('client_pro_pair_img').src).toEqual(expected); - }); - test('Should have a client_wit_pair_img', async () => { - document.body.innerHTML = ` + expect(document.getElementById('client_pro_pair_img').src).toEqual(expected); + }); + test('Should have a client_wit_pair_img', async () => { + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 1, 'wit'); - const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; + await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 1, 'wit'); + const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; - expect(document.getElementById('client_wit_pair_img').src).toEqual(expected); - }); - test('Should have a client_char_img', async () => { - document.body.innerHTML = ` + expect(document.getElementById('client_wit_pair_img').src).toEqual(expected); + }); + test('Should have a client_char_img', async () => { + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 0, 'notvalid'); - const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; + await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 0, 'notvalid'); + const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; - expect(document.getElementById('client_char_img').src).toEqual(expected); - }); - test('Should have a client_pair_img', async () => { - document.body.innerHTML = ` + expect(document.getElementById('client_char_img').src).toEqual(expected); + }); + test('Should have a client_pair_img', async () => { + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 1, 'notvalid'); - const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; + await setEmote(AO_HOST, client, 'salanto', 'coding', '(a)', 1, 'notvalid'); + const expected = `http://localhost/characters/salanto/(a)coding${firstExtension}`; - expect(document.getElementById('client_pair_img').src).toEqual(expected); - }); - test('Should handle .png urls differently', async () => { - fileExists.mockReturnValueOnce(false); - document.body.innerHTML = ` + expect(document.getElementById('client_pair_img').src).toEqual(expected); + }); + test('Should handle .png urls differently', async () => { + fileExists.mockReturnValueOnce(false); + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', 'prefixNotValid', 1, 'notvalid'); - const expected = 'http://localhost/characters/salanto/coding.png'; + await setEmote(AO_HOST, client, 'salanto', 'coding', 'prefixNotValid', 1, 'notvalid'); + const expected = 'http://localhost/characters/salanto/coding.png'; - expect(document.getElementById('client_pair_img').src).toEqual(expected); - }); - test('Should replace character if new character responds', async () => { - fileExists.mockReturnValue(false); - document.body.innerHTML = ` + expect(document.getElementById('client_pair_img').src).toEqual(expected); + }); + test('Should replace character if new character responds', async () => { + fileExists.mockReturnValue(false); + document.body.innerHTML = ` `; - await setEmote(AO_HOST, client, 'salanto', 'coding', 'prefixNotValid', 1, 'notvalid'); - const expected = transparentPng; - expect(document.getElementById('client_pair_img').src).toEqual(expected); - }); + await setEmote(AO_HOST, client, 'salanto', 'coding', 'prefixNotValid', 1, 'notvalid'); + const expected = transparentPng; + expect(document.getElementById('client_pair_img').src).toEqual(expected); + }); }); diff --git a/webAO/client/aoHost.ts b/webAO/client/aoHost.ts index 9b0a768..fa13e79 100644 --- a/webAO/client/aoHost.ts +++ b/webAO/client/aoHost.ts @@ -1,5 +1,5 @@ import queryParser from '../utils/queryParser' -let { asset } = queryParser(); +const { asset } = queryParser(); const DEFAULT_HOST = 'http://attorneyoffline.de/base/'; export let AO_HOST = asset || DEFAULT_HOST export const setAOhost = (val: string) => { diff --git a/webAO/client/saveChatLogHandle.ts b/webAO/client/saveChatLogHandle.ts index bcc1075..497dd50 100644 --- a/webAO/client/saveChatLogHandle.ts +++ b/webAO/client/saveChatLogHandle.ts @@ -14,9 +14,9 @@ export const saveChatlogHandle = async () => { messages.push(message); } const d = new Date(); - let ye = new Intl.DateTimeFormat("en", { year: "numeric" }).format(d); - let mo = new Intl.DateTimeFormat("en", { month: "short" }).format(d); - let da = new Intl.DateTimeFormat("en", { day: "2-digit" }).format(d); + const ye = new Intl.DateTimeFormat("en", { year: "numeric" }).format(d); + const mo = new Intl.DateTimeFormat("en", { month: "short" }).format(d); + const da = new Intl.DateTimeFormat("en", { day: "2-digit" }).format(d); const filename = `chatlog-${da}-${mo}-${ye}`.toLowerCase(); downloadFile(messages.join("\n"), filename); diff --git a/webAO/client/sender/sendIC.ts b/webAO/client/sender/sendIC.ts index 9064115..ca8984f 100644 --- a/webAO/client/sender/sendIC.ts +++ b/webAO/client/sender/sendIC.ts @@ -2,7 +2,7 @@ import { extrafeatures } from "../../client"; import { escapeChat } from "../../encoding"; import {client} from '../../client' import queryParser from "../../utils/queryParser"; -let {mode} = queryParser() +const {mode} = queryParser() /** * Sends an in-character chat message. diff --git a/webAO/client/sender/sendServer.ts b/webAO/client/sender/sendServer.ts index 7678381..ae95480 100644 --- a/webAO/client/sender/sendServer.ts +++ b/webAO/client/sender/sendServer.ts @@ -1,6 +1,6 @@ import { client } from "../../client"; import queryParser from "../../utils/queryParser"; -let { mode } = queryParser() +const { mode } = queryParser() /** * Hook for sending messages to the server * @param {string} message the message to send diff --git a/webAO/client/setEmote.ts b/webAO/client/setEmote.ts index f4fbdbb..2b5a614 100644 --- a/webAO/client/setEmote.ts +++ b/webAO/client/setEmote.ts @@ -8,48 +8,48 @@ import fileExists from "../utils/fileExists"; */ const setEmote = async ( - AO_HOST: string, - client: Client, - charactername: string, - emotename: string, - prefix: string, - pair: boolean, - side: string + AO_HOST: string, + client: Client, + charactername: string, + emotename: string, + prefix: string, + pair: boolean, + side: string ) => { - const pairID = pair ? "pair" : "char"; - const characterFolder = `${AO_HOST}characters/`; - const acceptedPositions = ["def", "pro", "wit"]; - const position = acceptedPositions.includes(side) ? `${side}_` : ""; - const emoteSelector = document.getElementById( - `client_${position}${pairID}_img` - ) as HTMLImageElement; - const extensionsMap = [".gif", ".png", ".apng", ".webp", ".webp.static"]; + const pairID = pair ? "pair" : "char"; + const characterFolder = `${AO_HOST}characters/`; + const acceptedPositions = ["def", "pro", "wit"]; + const position = acceptedPositions.includes(side) ? `${side}_` : ""; + const emoteSelector = document.getElementById( + `client_${position}${pairID}_img` + ) as HTMLImageElement; + const extensionsMap = [".gif", ".png", ".apng", ".webp", ".webp.static"]; - for (const extension of extensionsMap) { + for (const extension of extensionsMap) { // Hides all sprites before creating a new sprite - if (client.viewport.getLastCharacter() !== client.viewport.getChatmsg().name) { - emoteSelector.src = transparentPng; + if (client.viewport.getLastCharacter() !== client.viewport.getChatmsg().name) { + emoteSelector.src = transparentPng; + } + let url; + if (extension === ".png") { + url = `${characterFolder}${encodeURI(charactername)}/${encodeURI( + emotename + )}${extension}`; + } else if (extension === ".webp.static") { + url = `${characterFolder}${encodeURI(charactername)}/${encodeURI( + emotename + )}.webp`; + } else { + url = `${characterFolder}${encodeURI(charactername)}/${encodeURI( + prefix + )}${encodeURI(emotename)}${extension}`; + } + const exists = await fileExists(url); + if (exists) { + emoteSelector.src = url; + break; + } } - let url; - if (extension === ".png") { - url = `${characterFolder}${encodeURI(charactername)}/${encodeURI( - emotename - )}${extension}`; - } else if (extension === ".webp.static") { - url = `${characterFolder}${encodeURI(charactername)}/${encodeURI( - emotename - )}.webp`; - } else { - url = `${characterFolder}${encodeURI(charactername)}/${encodeURI( - prefix - )}${encodeURI(emotename)}${extension}`; - } - const exists = await fileExists(url); - if (exists) { - emoteSelector.src = url; - break; - } - } }; export default setEmote; diff --git a/webAO/components/__tests__/audioChannels.test.js b/webAO/components/__tests__/audioChannels.test.js index cd46d33..4407ae3 100644 --- a/webAO/components/__tests__/audioChannels.test.js +++ b/webAO/components/__tests__/audioChannels.test.js @@ -1,9 +1,9 @@ import createAudioChannels from '../audioChannels'; describe('createAudioChannels', () => { - test('Should create 4 channels', () => { - document.body.innerHTML = ''; - createAudioChannels(4); - expect(document.getElementsByClassName('audioChannel').length).toBe(4); - }); + test('Should create 4 channels', () => { + document.body.innerHTML = ''; + createAudioChannels(4); + expect(document.getElementsByClassName('audioChannel').length).toBe(4); + }); }); diff --git a/webAO/components/__tests__/blips.test.js b/webAO/components/__tests__/blips.test.js index 03468c9..dc90416 100644 --- a/webAO/components/__tests__/blips.test.js +++ b/webAO/components/__tests__/blips.test.js @@ -1,9 +1,9 @@ import createBlip from '../blip'; describe('createBlip', () => { - test('create 3 blips audios', () => { - document.body.innerHTML = ''; - createBlip(3); - expect(document.getElementsByClassName('blipSound').length).toBe(3); - }); + test('create 3 blips audios', () => { + document.body.innerHTML = ''; + createBlip(3); + expect(document.getElementsByClassName('blipSound').length).toBe(3); + }); }); diff --git a/webAO/components/audioChannels.js b/webAO/components/audioChannels.js index 80bdb4f..6032e66 100644 --- a/webAO/components/audioChannels.js +++ b/webAO/components/audioChannels.js @@ -3,11 +3,11 @@ * @param {number} amountOfChannels Amount of Blips to put on page */ const createAudioChannels = (amountOfChannels) => { - for (let i = 0; i < amountOfChannels; i++) { - const audioChannel = document.createElement('audio'); - audioChannel.setAttribute('class', 'audioChannel'); - document.body.appendChild(audioChannel); - } + for (let i = 0; i < amountOfChannels; i++) { + const audioChannel = document.createElement('audio'); + audioChannel.setAttribute('class', 'audioChannel'); + document.body.appendChild(audioChannel); + } }; createAudioChannels(4); export default createAudioChannels; diff --git a/webAO/components/blip.js b/webAO/components/blip.js index 02f5ced..86a674b 100644 --- a/webAO/components/blip.js +++ b/webAO/components/blip.js @@ -5,13 +5,13 @@ import { AO_HOST } from '../client/aoHost.ts'; * @param {number} amountOfBlips Amount of Blips to put on page */ const createBlip = (amountOfBlips) => { - for (let i = 0; i < amountOfBlips; i++) { - const audio = document.createElement('audio'); - const blipUrl = `${AO_HOST}sounds/blips/male.opus`; - audio.setAttribute('class', 'blipSound'); - audio.setAttribute('src', blipUrl); - document.body.appendChild(audio); - } + for (let i = 0; i < amountOfBlips; i++) { + const audio = document.createElement('audio'); + const blipUrl = `${AO_HOST}sounds/blips/male.opus`; + audio.setAttribute('class', 'blipSound'); + audio.setAttribute('src', blipUrl); + document.body.appendChild(audio); + } }; createBlip(6); export default createBlip; diff --git a/webAO/constants/backgrounds.js b/webAO/constants/backgrounds.js index c1807ce..a0a21f6 100644 --- a/webAO/constants/backgrounds.js +++ b/webAO/constants/backgrounds.js @@ -1,25 +1,25 @@ export default [ - 'Anime', - 'birthday', - 'Christmas', - 'CountyCourt', - 'CruiseCourt', - 'default', - 'DGSEnglishCourt', - 'DGSJapanCourt', - 'DualDestinies', - 'EnglishCourt', - 'gs4', - 'GS4Night', - 'HD', - "Khura'in", - 'mlp', - 'NewCourt', - 'RuinedCourt', - 'Sky', - 'SpaceCourt', - 'Themis', - 'TouhouCourt', - 'WitchTrialCourt', - 'Zetta', + 'Anime', + 'birthday', + 'Christmas', + 'CountyCourt', + 'CruiseCourt', + 'default', + 'DGSEnglishCourt', + 'DGSJapanCourt', + 'DualDestinies', + 'EnglishCourt', + 'gs4', + 'GS4Night', + 'HD', + "Khura'in", + 'mlp', + 'NewCourt', + 'RuinedCourt', + 'Sky', + 'SpaceCourt', + 'Themis', + 'TouhouCourt', + 'WitchTrialCourt', + 'Zetta', ]; diff --git a/webAO/constants/characters.js b/webAO/constants/characters.js index e046cf8..9586b1a 100644 --- a/webAO/constants/characters.js +++ b/webAO/constants/characters.js @@ -1,53 +1,53 @@ export default [ - 'Adrian', - 'Apollo', - 'April', - 'Armstrong', - 'Atmey', - 'Butz', - 'Diego', - 'Edgeworth', - 'Edgeworthw', - 'Ema', - 'Emaskye', - 'Franny', - 'Franziska', - 'Gant', - 'Gavin', - 'Gavin K', - 'Godot', - 'Gregory', - 'Grossberg', - 'Gumshoe', - 'Gumshoey', - 'Hawk', - 'Hobo_Phoenix', - 'Ini', - 'Judge', - "Judge's Bro", - 'Klav', - 'Klavier', - 'Kristoph', - 'Lana', - 'Layton', - 'Lotta', - 'Luis', - 'Maggey', - 'Manfred', - 'Marshall', - 'Matt', - 'Maya', - 'Mia', - 'Miles', - 'Oldbag', - 'Payne', - 'Pearl', - 'Phoenix', - 'Valant', - 'Vasquez', - 'Wellington', - 'Winston', - 'Winstonpayne', - 'Young Mia', - 'Zak', + 'Adrian', + 'Apollo', + 'April', + 'Armstrong', + 'Atmey', + 'Butz', + 'Diego', + 'Edgeworth', + 'Edgeworthw', + 'Ema', + 'Emaskye', + 'Franny', + 'Franziska', + 'Gant', + 'Gavin', + 'Gavin K', + 'Godot', + 'Gregory', + 'Grossberg', + 'Gumshoe', + 'Gumshoey', + 'Hawk', + 'Hobo_Phoenix', + 'Ini', + 'Judge', + "Judge's Bro", + 'Klav', + 'Klavier', + 'Kristoph', + 'Lana', + 'Layton', + 'Lotta', + 'Luis', + 'Maggey', + 'Manfred', + 'Marshall', + 'Matt', + 'Maya', + 'Mia', + 'Miles', + 'Oldbag', + 'Payne', + 'Pearl', + 'Phoenix', + 'Valant', + 'Vasquez', + 'Wellington', + 'Winston', + 'Winstonpayne', + 'Young Mia', + 'Zak', ]; diff --git a/webAO/constants/evidence.js b/webAO/constants/evidence.js index 900455e..da4933f 100644 --- a/webAO/constants/evidence.js +++ b/webAO/constants/evidence.js @@ -1,10 +1,10 @@ export default [ - '1.png', - '2.png', - '3.png', - '4.png', - '5.png', - '6.png', - 'empty.png', - 'lawyerbadge.png', + '1.png', + '2.png', + '3.png', + '4.png', + '5.png', + '6.png', + 'empty.png', + 'lawyerbadge.png', ]; diff --git a/webAO/constants/music.js b/webAO/constants/music.js index 09d830b..f040554 100644 --- a/webAO/constants/music.js +++ b/webAO/constants/music.js @@ -1,51 +1,51 @@ export default [ - 'Announce The Truth (AA).opus', - 'Announce The Truth (AJ).opus', - 'Announce The Truth (JFA).opus', - 'Announce The Truth (Miles).opus', - 'Announce The Truth (T&T).opus', - 'Confrontation ~ Presto 2009.opus', - 'Crises of Fate.opus', - 'Forgotten Legend.opus', - 'Godot - The Fragrance of Dark Coffee.opus', - 'Great Revival ~ Franziska von Karma.opus', - 'Great Revival ~ Miles Edgeworth.opus', - 'Hotline of Fate.opus', - 'Interesting People.opus', - 'Logic and Trick.opus', - 'Luke Atmey ~ I Just Want Love.opus', - 'Noisy People.opus', - 'OBJECTION (AA).opus', - 'Objection (AJ).opus', - 'OBJECTION (JFA).opus', - 'Objection (Miles).opus', - 'OBJECTION (T&T).opus', - 'Others ~ Guilty love.opus', - 'Prelude (AA).opus', - 'Prelude (AJ).opus', - 'Prologue (AA).opus', - 'Pursuit (AA) - variation.opus', - 'Pursuit (AA).opus', - 'Pursuit (AJ).opus', - 'Pursuit (DS).opus', - 'Pursuit (JFA) - variation.opus', - 'Pursuit (JFA).opus', - 'Pursuit (Miles).opus', - 'Pursuit (T&T) - variation.opus', - 'Pursuit (T&T).opus', - 'Pursuit ~ I Want to Find the Truth (Orchestra).opus', - 'Questioning AA (Allegro).opus', - 'Questioning AA (Moderato).opus', - 'Questioning AJ (Allegro).opus', - 'Questioning AJ (Moderato).opus', - 'Questioning JFA (Allegro).opus', - 'Questioning JFA (Moderato).opus', - 'Questioning T&T (Allegro).opus', - 'Questioning T&T (Moderato).opus', - 'Speak up Pup.opus', - 'Suspense (AA).opus', - 'The Great Truth Burglar.opus', - 'Trial (AA).opus', - 'Trial (AJ).opus', - 'Trial (Miles).opus', + 'Announce The Truth (AA).opus', + 'Announce The Truth (AJ).opus', + 'Announce The Truth (JFA).opus', + 'Announce The Truth (Miles).opus', + 'Announce The Truth (T&T).opus', + 'Confrontation ~ Presto 2009.opus', + 'Crises of Fate.opus', + 'Forgotten Legend.opus', + 'Godot - The Fragrance of Dark Coffee.opus', + 'Great Revival ~ Franziska von Karma.opus', + 'Great Revival ~ Miles Edgeworth.opus', + 'Hotline of Fate.opus', + 'Interesting People.opus', + 'Logic and Trick.opus', + 'Luke Atmey ~ I Just Want Love.opus', + 'Noisy People.opus', + 'OBJECTION (AA).opus', + 'Objection (AJ).opus', + 'OBJECTION (JFA).opus', + 'Objection (Miles).opus', + 'OBJECTION (T&T).opus', + 'Others ~ Guilty love.opus', + 'Prelude (AA).opus', + 'Prelude (AJ).opus', + 'Prologue (AA).opus', + 'Pursuit (AA) - variation.opus', + 'Pursuit (AA).opus', + 'Pursuit (AJ).opus', + 'Pursuit (DS).opus', + 'Pursuit (JFA) - variation.opus', + 'Pursuit (JFA).opus', + 'Pursuit (Miles).opus', + 'Pursuit (T&T) - variation.opus', + 'Pursuit (T&T).opus', + 'Pursuit ~ I Want to Find the Truth (Orchestra).opus', + 'Questioning AA (Allegro).opus', + 'Questioning AA (Moderato).opus', + 'Questioning AJ (Allegro).opus', + 'Questioning AJ (Moderato).opus', + 'Questioning JFA (Allegro).opus', + 'Questioning JFA (Moderato).opus', + 'Questioning T&T (Allegro).opus', + 'Questioning T&T (Moderato).opus', + 'Speak up Pup.opus', + 'Suspense (AA).opus', + 'The Great Truth Burglar.opus', + 'Trial (AA).opus', + 'Trial (AJ).opus', + 'Trial (Miles).opus', ]; diff --git a/webAO/dom/addEvidence.ts b/webAO/dom/addEvidence.ts index 8a13f06..84c7fae 100644 --- a/webAO/dom/addEvidence.ts +++ b/webAO/dom/addEvidence.ts @@ -4,17 +4,17 @@ import { cancelEvidence } from "./cancelEvidence"; /** * Add evidence. */ - export function addEvidence() { +export function addEvidence() { const evidence_select = ( document.getElementById("evi_select") ); client.sender.sendPE( - (document.getElementById("evi_name")).value, - (document.getElementById("evi_desc")).value, - evidence_select.selectedIndex === 0 - ? (document.getElementById("evi_filename")).value - : evidence_select.options[evidence_select.selectedIndex].text + (document.getElementById("evi_name")).value, + (document.getElementById("evi_desc")).value, + evidence_select.selectedIndex === 0 + ? (document.getElementById("evi_filename")).value + : evidence_select.options[evidence_select.selectedIndex].text ); cancelEvidence(); - } - window.addEvidence = addEvidence; \ No newline at end of file +} +window.addEvidence = addEvidence; \ No newline at end of file diff --git a/webAO/dom/changeBackgroundOOC.ts b/webAO/dom/changeBackgroundOOC.ts index 1608ebe..55ce238 100644 --- a/webAO/dom/changeBackgroundOOC.ts +++ b/webAO/dom/changeBackgroundOOC.ts @@ -1,7 +1,7 @@ import queryParser from '../utils/queryParser' import { client } from '../client' -let { mode } = queryParser() +const { mode } = queryParser() /** * Change background via OOC. diff --git a/webAO/dom/changeMusicVolume.ts b/webAO/dom/changeMusicVolume.ts index 9e5d51a..b54661b 100644 --- a/webAO/dom/changeMusicVolume.ts +++ b/webAO/dom/changeMusicVolume.ts @@ -5,7 +5,7 @@ export const changeMusicVolume = (volume: number = -1) => { const clientVolume = Number( (document.getElementById("client_mvolume")).value ); - let musicVolume = volume === -1 ? clientVolume : volume; + const musicVolume = volume === -1 ? clientVolume : volume; client.viewport.music.forEach( (channel: HTMLAudioElement) => (channel.volume = musicVolume) ); diff --git a/webAO/dom/changeVolume.js b/webAO/dom/changeVolume.js index b79204a..c62d933 100644 --- a/webAO/dom/changeVolume.js +++ b/webAO/dom/changeVolume.js @@ -5,7 +5,7 @@ import setCookie from '../utils/setCookie.ts'; */ export function changeSFXVolume() { - setCookie('sfxVolume', document.getElementById('client_sfxaudio').volume); + setCookie('sfxVolume', document.getElementById('client_sfxaudio').volume); } window.changeSFXVolume = changeSFXVolume; @@ -13,7 +13,7 @@ window.changeSFXVolume = changeSFXVolume; * Triggered by the testimony volume slider. */ export function changeTestimonyVolume() { - setCookie('testimonyVolume', document.getElementById('client_testimonyaudio').volume); + setCookie('testimonyVolume', document.getElementById('client_testimonyaudio').volume); } window.changeTestimonyVolume = changeTestimonyVolume; @@ -22,6 +22,6 @@ window.changeTestimonyVolume = changeTestimonyVolume; */ export function changeShoutVolume() { - setCookie('shoutVolume', document.getElementById('client_shoutaudio').volume); + setCookie('shoutVolume', document.getElementById('client_shoutaudio').volume); } window.changeShoutVolume = changeShoutVolume; diff --git a/webAO/dom/musicListFilter.ts b/webAO/dom/musicListFilter.ts index 3db7fcd..b5284a2 100644 --- a/webAO/dom/musicListFilter.ts +++ b/webAO/dom/musicListFilter.ts @@ -4,21 +4,21 @@ import { client } from '../client' * @param {MouseEvent} event */ export function musiclist_filter(_event: Event) { - const musiclist_element = ( + const musiclist_element = ( document.getElementById("client_musiclist") ); - const searchname = (( + const searchname = (( document.getElementById("client_musicsearch") )).value; - musiclist_element.innerHTML = ""; + musiclist_element.innerHTML = ""; - for (const trackname of client.musics) { - if (trackname.toLowerCase().indexOf(searchname.toLowerCase()) !== -1) { - const newentry = document.createElement("OPTION"); - newentry.text = trackname; - musiclist_element.options.add(newentry); + for (const trackname of client.musics) { + if (trackname.toLowerCase().indexOf(searchname.toLowerCase()) !== -1) { + const newentry = document.createElement("OPTION"); + newentry.text = trackname; + musiclist_element.options.add(newentry); + } } - } } window.musiclist_filter = musiclist_filter; \ No newline at end of file diff --git a/webAO/dom/muteListClick.ts b/webAO/dom/muteListClick.ts index e7c9357..51bdd3d 100644 --- a/webAO/dom/muteListClick.ts +++ b/webAO/dom/muteListClick.ts @@ -4,16 +4,16 @@ import { client } from "../client"; * @param {MouseEvent} event */ export function mutelist_click(_event: Event) { - const mutelist = (document.getElementById('mute_select')); - const selected_character = mutelist.options[mutelist.selectedIndex]; + const mutelist = (document.getElementById('mute_select')); + const selected_character = mutelist.options[mutelist.selectedIndex]; - if (client.chars[selected_character.value].muted === false) { - client.chars[selected_character.value].muted = true; - selected_character.text = `${client.chars[selected_character.value].name} (muted)`; - console.info(`muted ${client.chars[selected_character.value].name}`); - } else { - client.chars[selected_character.value].muted = false; - selected_character.text = client.chars[selected_character.value].name; - } + if (client.chars[selected_character.value].muted === false) { + client.chars[selected_character.value].muted = true; + selected_character.text = `${client.chars[selected_character.value].name} (muted)`; + console.info(`muted ${client.chars[selected_character.value].name}`); + } else { + client.chars[selected_character.value].muted = false; + selected_character.text = client.chars[selected_character.value].name; + } } window.mutelist_click = mutelist_click; \ No newline at end of file diff --git a/webAO/dom/onEnter.ts b/webAO/dom/onEnter.ts index 5ab532c..4948783 100644 --- a/webAO/dom/onEnter.ts +++ b/webAO/dom/onEnter.ts @@ -1,103 +1,102 @@ import { client, selectedShout } from "../client"; import { escapeChat } from "../encoding"; - /** * Triggered when the Return key is pressed on the in-character chat input box. * @param {KeyboardEvent} event */ - export function onEnter(event: KeyboardEvent) { +export function onEnter(event: KeyboardEvent) { if (event.keyCode === 13) { - const mychar = client.character; - const myemo = client.emote; - const evi = client.evidence; - const flip = Boolean( - document.getElementById("button_flip")!.classList.contains("dark") - ); - const flash = Boolean( - document.getElementById("button_flash")!.classList.contains("dark") - ); - const screenshake = Boolean( - document.getElementById("button_shake")!.classList.contains("dark") - ); - const noninterrupting_preanim = Boolean( - (document.getElementById("check_nonint")).checked - ); - const looping_sfx = Boolean( - (document.getElementById("check_loopsfx")).checked - ); - const color = Number( - (document.getElementById("textcolor")).value - ); - const showname = escapeChat( - (document.getElementById("ic_chat_name")).value - ); - const text = (document.getElementById("client_inputbox")) - .value; - const pairchar = (document.getElementById("pair_select")) - .value; - const pairoffset = Number( - (document.getElementById("pair_offset")).value - ); - const pairyoffset = Number( - (document.getElementById("pair_y_offset")).value - ); - const myrole = (document.getElementById("role_select")) - .value - ? (document.getElementById("role_select")).value - : mychar.side; - const additive = Boolean( - (document.getElementById("check_additive")).checked - ); - const effect = (document.getElementById("effect_select")) - .value; - - let sfxname = "0"; - let sfxdelay = 0; - let emote_mod = myemo.zoom; - if ((document.getElementById("sendsfx")).checked) { - sfxname = myemo.sfx; - sfxdelay = myemo.sfxdelay; - } - - // not to overwrite a 5 from the ini or anything else - if ((document.getElementById("sendpreanim")).checked) { - if (emote_mod === 0) { - emote_mod = 1; + const mychar = client.character; + const myemo = client.emote; + const evi = client.evidence; + const flip = Boolean( + document.getElementById("button_flip")!.classList.contains("dark") + ); + const flash = Boolean( + document.getElementById("button_flash")!.classList.contains("dark") + ); + const screenshake = Boolean( + document.getElementById("button_shake")!.classList.contains("dark") + ); + const noninterrupting_preanim = Boolean( + (document.getElementById("check_nonint")).checked + ); + const looping_sfx = Boolean( + (document.getElementById("check_loopsfx")).checked + ); + const color = Number( + (document.getElementById("textcolor")).value + ); + const showname = escapeChat( + (document.getElementById("ic_chat_name")).value + ); + const text = (document.getElementById("client_inputbox")) + .value; + const pairchar = (document.getElementById("pair_select")) + .value; + const pairoffset = Number( + (document.getElementById("pair_offset")).value + ); + const pairyoffset = Number( + (document.getElementById("pair_y_offset")).value + ); + const myrole = (document.getElementById("role_select")) + .value + ? (document.getElementById("role_select")).value + : mychar.side; + const additive = Boolean( + (document.getElementById("check_additive")).checked + ); + const effect = (document.getElementById("effect_select")) + .value; + + let sfxname = "0"; + let sfxdelay = 0; + let emote_mod = myemo.zoom; + if ((document.getElementById("sendsfx")).checked) { + sfxname = myemo.sfx; + sfxdelay = myemo.sfxdelay; } - } else if (emote_mod === 1) { - emote_mod = 0; - } - - client.sender.sendIC( - myemo.deskmod, - myemo.preanim, - mychar.name, - myemo.emote, - text, - myrole, - sfxname, - emote_mod, - sfxdelay, - selectedShout, - evi, - flip, - flash, - color, - showname, - pairchar, - pairoffset, - pairyoffset, - noninterrupting_preanim, - looping_sfx, - screenshake, - "-", - "-", - "-", - additive, - effect - ); + + // not to overwrite a 5 from the ini or anything else + if ((document.getElementById("sendpreanim")).checked) { + if (emote_mod === 0) { + emote_mod = 1; + } + } else if (emote_mod === 1) { + emote_mod = 0; + } + + client.sender.sendIC( + myemo.deskmod, + myemo.preanim, + mychar.name, + myemo.emote, + text, + myrole, + sfxname, + emote_mod, + sfxdelay, + selectedShout, + evi, + flip, + flash, + color, + showname, + pairchar, + pairoffset, + pairyoffset, + noninterrupting_preanim, + looping_sfx, + screenshake, + "-", + "-", + "-", + additive, + effect + ); } return false; - } - window.onEnter = onEnter; \ No newline at end of file +} +window.onEnter = onEnter; diff --git a/webAO/dom/opusCheck.ts b/webAO/dom/opusCheck.ts index 5f0248d..608a30a 100644 --- a/webAO/dom/opusCheck.ts +++ b/webAO/dom/opusCheck.ts @@ -3,20 +3,20 @@ * @param {HTMLAudioElement} image the element containing the missing sound */ export function opusCheck( - channel: HTMLAudioElement + channel: HTMLAudioElement ): OnErrorEventHandlerNonNull { - const audio = channel.src; - if (audio === "") { - return; - } - console.warn(`failed to load sound ${channel.src}`); - let oldsrc = ""; - let newsrc = ""; - oldsrc = channel.src; - if (!oldsrc.endsWith(".opus")) { - newsrc = oldsrc.replace(".mp3", ".opus"); - newsrc = newsrc.replace(".wav", ".opus"); - channel.src = newsrc; // unload so the old sprite doesn't persist - } + const audio = channel.src; + if (audio === "") { + return; + } + console.warn(`failed to load sound ${channel.src}`); + let oldsrc = ""; + let newsrc = ""; + oldsrc = channel.src; + if (!oldsrc.endsWith(".opus")) { + newsrc = oldsrc.replace(".mp3", ".opus"); + newsrc = newsrc.replace(".wav", ".opus"); + channel.src = newsrc; // unload so the old sprite doesn't persist + } } window.opusCheck = opusCheck; \ No newline at end of file diff --git a/webAO/dom/reconnectButton.ts b/webAO/dom/reconnectButton.ts index 4031ccd..76a6b51 100644 --- a/webAO/dom/reconnectButton.ts +++ b/webAO/dom/reconnectButton.ts @@ -1,6 +1,6 @@ import Client, { client, setClient } from "../client"; import queryParser from "../utils/queryParser"; -let { ip: serverIP } = queryParser(); +const { ip: serverIP } = queryParser(); /** * Triggered when the reconnect button is pushed. diff --git a/webAO/dom/resetOffset.ts b/webAO/dom/resetOffset.ts index 86dfd5b..8b1a2fd 100644 --- a/webAO/dom/resetOffset.ts +++ b/webAO/dom/resetOffset.ts @@ -1,6 +1,6 @@ export function resetOffset(_event: Event) { - (document.getElementById("pair_offset")).value = "0"; - (document.getElementById("pair_y_offset")).value = "0"; + (document.getElementById("pair_offset")).value = "0"; + (document.getElementById("pair_y_offset")).value = "0"; } window.resetOffset = resetOffset; \ No newline at end of file diff --git a/webAO/dom/toggleEffect.js b/webAO/dom/toggleEffect.js index 699937b..d9ba421 100644 --- a/webAO/dom/toggleEffect.js +++ b/webAO/dom/toggleEffect.js @@ -6,11 +6,11 @@ * @param {string} effect the new effect to be selected */ export function toggleEffect(button) { - if (button.classList.contains('dark')) { - button.className = 'client_button'; - } else { - button.className = 'client_button dark'; - } + if (button.classList.contains('dark')) { + button.className = 'client_button'; + } else { + button.className = 'client_button dark'; + } } window.toggleEffect = toggleEffect; export default toggleEffect; diff --git a/webAO/dom/toggleElement.js b/webAO/dom/toggleElement.js index 6d4c194..3d4ceb2 100644 --- a/webAO/dom/toggleElement.js +++ b/webAO/dom/toggleElement.js @@ -3,12 +3,12 @@ * @param {string} elementId the id of the element to toggle */ export function toggleElement(elementId) { - const element = document.getElementById(elementId); - if (element.style.display !== 'none') { - element.style.display = 'none'; - } else { - element.style.display = 'block'; - } + const element = document.getElementById(elementId); + if (element.style.display !== 'none') { + element.style.display = 'none'; + } else { + element.style.display = 'block'; + } } window.toggleElement = toggleElement; export default toggleElement; diff --git a/webAO/dom/twofactor.ts b/webAO/dom/twofactor.ts index b7e947a..d0076bf 100644 --- a/webAO/dom/twofactor.ts +++ b/webAO/dom/twofactor.ts @@ -2,9 +2,9 @@ import { client } from "../client"; function handleCredentialResponse(response: any) { client.sender.sendServer(`2T#${response.credential}#%`); - } +} window.handleCredentialResponse = handleCredentialResponse; export function showFactorDialog(args: string[]) { - document.getElementById("client_secondfactor").style.display = args[1]; + document.getElementById("client_secondfactor").style.display = args[1]; } \ No newline at end of file diff --git a/webAO/dom/updateActionCommands.ts b/webAO/dom/updateActionCommands.ts index 9d0bd82..ca8ca60 100644 --- a/webAO/dom/updateActionCommands.ts +++ b/webAO/dom/updateActionCommands.ts @@ -14,7 +14,7 @@ export function updateActionCommands(side: string) { // Update role selector for ( let i = 0, - role_select = document.getElementById("role_select"); + role_select = document.getElementById("role_select"); i < role_select.options.length; i++ ) { diff --git a/webAO/dom/updateBackgroundPreview.ts b/webAO/dom/updateBackgroundPreview.ts index 01b5c44..659d4cb 100644 --- a/webAO/dom/updateBackgroundPreview.ts +++ b/webAO/dom/updateBackgroundPreview.ts @@ -21,8 +21,8 @@ export function updateBackgroundPreview() { background_filename.style.display = "none"; } tryUrls(`${AO_HOST}background/${encodeURI( - background_select.value.toLowerCase() - )}/defenseempty`).then((resp) => { + background_select.value.toLowerCase() + )}/defenseempty`).then((resp) => { background_preview.src = resp; }); } diff --git a/webAO/dom/window.ts b/webAO/dom/window.ts index 0b3bd34..ca9cde5 100644 --- a/webAO/dom/window.ts +++ b/webAO/dom/window.ts @@ -20,7 +20,7 @@ declare global { updateIniswap: () => void; resizeChatbox: () => void; setChatbox: (style: string) => void; - getIndexFromSelect: (select_box: string, value: string) => Number; + getIndexFromSelect: (select_box: string, value: string) => number; cancelEvidence: () => void; deleteEvidence: () => void; editEvidence: () => void; diff --git a/webAO/encoding.ts b/webAO/encoding.ts index 697e1d0..c878cb5 100644 --- a/webAO/encoding.ts +++ b/webAO/encoding.ts @@ -3,11 +3,11 @@ * @param {string} estring the string to be escaped */ export function escapeChat(estring: string): string { - return estring - .replaceAll('#', '') - .replaceAll('&', '') - .replaceAll('%', '') - .replaceAll('$', ''); + return estring + .replaceAll('#', '') + .replaceAll('&', '') + .replaceAll('%', '') + .replaceAll('$', ''); } /** @@ -15,11 +15,11 @@ export function escapeChat(estring: string): string { * @param {string} estring the string to be unescaped */ export function unescapeChat(estring: string): string { - return estring - .replaceAll('', '#') - .replaceAll('', '&') - .replaceAll('', '%') - .replaceAll('', '$'); + return estring + .replaceAll('', '#') + .replaceAll('', '&') + .replaceAll('', '%') + .replaceAll('', '$'); } /** @@ -29,12 +29,12 @@ export function unescapeChat(estring: string): string { * @param {string} unsafe an unsanitized string */ export function safeTags(unsafe: string): string { - if (unsafe) { - return unsafe - .replaceAll('>', '>') - .replaceAll('<', '<'); - } - return ''; + if (unsafe) { + return unsafe + .replaceAll('>', '>') + .replaceAll('<', '<'); + } + return ''; } /** @@ -51,6 +51,6 @@ export function decodeChat(estring: string): string { * @param {string} msg chat message to prepare for display */ export function prepChat(msg: string): string { - // TODO: make this less awful - return safeTags(unescapeChat(decodeChat(msg))); + // TODO: make this less awful + return safeTags(unescapeChat(decodeChat(msg))); } diff --git a/webAO/iniParse.js b/webAO/iniParse.js index fb04e67..d3a9a90 100644 --- a/webAO/iniParse.js +++ b/webAO/iniParse.js @@ -1,42 +1,42 @@ const regexPatterns = { - section: /^\s*\[\s*([^\]]*)\s*\]\s*$/, - param: /^\s*([\w.\-_]+)\s*=\s*(.*?)\s*$/, - comment: /^\s*;.*$/, + section: /^\s*\[\s*([^\]]*)\s*\]\s*$/, + param: /^\s*([\w.\-_]+)\s*=\s*(.*?)\s*$/, + comment: /^\s*;.*$/, }; const valueHandler = (matchKey, matchValue) => (matchKey === 'showname' ? matchValue : matchValue.toLowerCase()); const lineFilter = (value) => { - const isEmpty = value.length === 0; - const isComment = regexPatterns.comment.test(value); - if (isComment || isEmpty) { - return false; - } - return true; + const isEmpty = value.length === 0; + const isComment = regexPatterns.comment.test(value); + if (isComment || isEmpty) { + return false; + } + return true; }; const iniParse = (data) => { - const parsedIni = {}; - const lines = data.split(/\r\n|\r|\n/); - const filteredLines = lines.filter(lineFilter); + const parsedIni = {}; + const lines = data.split(/\r\n|\r|\n/); + const filteredLines = lines.filter(lineFilter); - let currentSection; - filteredLines.forEach((line) => { - const isParameter = regexPatterns.param.test(line); - const isSection = regexPatterns.section.test(line); - if (isParameter && currentSection) { - const match = line.match(regexPatterns.param); - const matchKey = match[1].toLowerCase(); - const matchValue = match[2]; - parsedIni[currentSection][matchKey] = valueHandler(matchKey, matchValue); - } else if (isSection) { - const match = line.match(regexPatterns.section); - const matchKey = match[1].toLowerCase(); - parsedIni[matchKey] = {}; - currentSection = matchKey; - } - }); - return parsedIni; + let currentSection; + filteredLines.forEach((line) => { + const isParameter = regexPatterns.param.test(line); + const isSection = regexPatterns.section.test(line); + if (isParameter && currentSection) { + const match = line.match(regexPatterns.param); + const matchKey = match[1].toLowerCase(); + const matchValue = match[2]; + parsedIni[currentSection][matchKey] = valueHandler(matchKey, matchValue); + } else if (isSection) { + const match = line.match(regexPatterns.section); + const matchKey = match[1].toLowerCase(); + parsedIni[matchKey] = {}; + currentSection = matchKey; + } + }); + return parsedIni; }; export default iniParse; diff --git a/webAO/master.ts b/webAO/master.ts index 8640001..32d3a9b 100644 --- a/webAO/master.ts +++ b/webAO/master.ts @@ -3,9 +3,9 @@ import FingerprintJS from '@fingerprintjs/fingerprintjs'; import { unescapeChat, safeTags } from './encoding'; declare global { - interface Window { - setServ: (ID: any) => void; - } + interface Window { + setServ: (ID: any) => void; + } } const myStorage = window.localStorage; @@ -18,136 +18,136 @@ let hdid: string; let selectedServer: number = -1; -let servers: { name: string, description: string, ip: string, port: number, ws_port: number, assets: string, online: string }[] = []; +const servers: { name: string, description: string, ip: string, port: number, ws_port: number, assets: string, online: string }[] = []; servers[-2] = { - name: 'Singleplayer', description: 'Build cases, try out new things', ip: '127.0.0.1', port: 50001, ws_port: 50001, assets: '', online: 'Online: 0/1', + name: 'Singleplayer', description: 'Build cases, try out new things', ip: '127.0.0.1', port: 50001, ws_port: 50001, assets: '', online: 'Online: 0/1', }; servers[-1] = { - name: 'Localhost', description: 'This is your computer on port 50001', ip: '127.0.0.1', port: 50001, ws_port: 50001, assets: '', online: 'Offline', + name: 'Localhost', description: 'This is your computer on port 50001', ip: '127.0.0.1', port: 50001, ws_port: 50001, assets: '', online: 'Offline', }; const fpPromise = FingerprintJS.load(); fpPromise - .then((fp) => fp.get()) - .then((result) => { - hdid = result.visitorId; + .then((fp) => fp.get()) + .then((result) => { + hdid = result.visitorId; - check_https(); + check_https(); - fetch('https://servers.aceattorneyonline.com/servers') - .then(cachedServerlist) - .then((response) => loadServerlist(response)) - .catch(cachedServerlist); + fetch('https://servers.aceattorneyonline.com/servers') + .then(cachedServerlist) + .then((response) => loadServerlist(response)) + .catch(cachedServerlist); - fetch('https://servers.aceattorneyonline.com/version') - .then((response) => response.text()) - .then((response) => processVersion(response)); + fetch('https://servers.aceattorneyonline.com/version') + .then((response) => response.text()) + .then((response) => processVersion(response)); - // i don't need the ms to play alone - setTimeout(() => checkOnline(-1, '127.0.0.1:50001'), 0); - }); + // i don't need the ms to play alone + setTimeout(() => checkOnline(-1, '127.0.0.1:50001'), 0); + }); export function check_https() { - if (document.location.protocol === 'https:') { - document.getElementById('https_error').style.display = ''; - setTimeout(() => window.location.replace("http://web.aceattorneyonline.com/"), 5000); - } + if (document.location.protocol === 'https:') { + document.getElementById('https_error').style.display = ''; + setTimeout(() => window.location.replace("http://web.aceattorneyonline.com/"), 5000); + } } export function setServ(ID: number) { - selectedServer = ID; + selectedServer = ID; - if (document.getElementById(`server${ID}`).className === '') { checkOnline(ID, `${servers[ID].ip}:${servers[ID].ws_port}`); } + if (document.getElementById(`server${ID}`).className === '') { checkOnline(ID, `${servers[ID].ip}:${servers[ID].ws_port}`); } - document.getElementById('serverdescription_content').innerHTML = `${servers[ID].online}
${safeTags(servers[ID].description)}`; + document.getElementById('serverdescription_content').innerHTML = `${servers[ID].online}
${safeTags(servers[ID].description)}`; } window.setServ = setServ; function checkOnline(serverID: number, coIP: string) { - let serverConnection: WebSocket; - if (serverID !== -2) { - try { - serverConnection = new WebSocket(`ws://${coIP}`); - } catch (SecurityError) { - document.getElementById(`server${serverID}`).className = 'unavailable'; - return; + let serverConnection: WebSocket; + if (serverID !== -2) { + try { + serverConnection = new WebSocket(`ws://${coIP}`); + } catch (SecurityError) { + document.getElementById(`server${serverID}`).className = 'unavailable'; + return; + } } - } - - // define what the callbacks do - function onCOOpen() { - document.getElementById(`server${serverID}`).className = 'available'; - serverConnection.send(`HI#${hdid}#%`); - serverConnection.send('ID#webAO#webAO#%'); - } - - function onCOMessage(e: MessageEvent) { - const comsg = e.data; - const coheader = comsg.split('#', 2)[0]; - const coarguments = comsg.split('#').slice(1); - if (coheader === 'PN') { - servers[serverID].online = `Online: ${Number(coarguments[0])}/${Number(coarguments[1])}`; - serverConnection.close(); - return; - } if (coheader === 'BD') { - servers[serverID].online = 'Banned'; - servers[serverID].description = coarguments[0]; - serverConnection.close(); - return; + + // define what the callbacks do + function onCOOpen() { + document.getElementById(`server${serverID}`).className = 'available'; + serverConnection.send(`HI#${hdid}#%`); + serverConnection.send('ID#webAO#webAO#%'); } - if (serverID === selectedServer) { - document.getElementById('serverdescription_content').innerHTML = `${servers[serverID].online}
${safeTags(servers[serverID].description)}`; + + function onCOMessage(e: MessageEvent) { + const comsg = e.data; + const coheader = comsg.split('#', 2)[0]; + const coarguments = comsg.split('#').slice(1); + if (coheader === 'PN') { + servers[serverID].online = `Online: ${Number(coarguments[0])}/${Number(coarguments[1])}`; + serverConnection.close(); + return; + } if (coheader === 'BD') { + servers[serverID].online = 'Banned'; + servers[serverID].description = coarguments[0]; + serverConnection.close(); + return; + } + if (serverID === selectedServer) { + document.getElementById('serverdescription_content').innerHTML = `${servers[serverID].online}
${safeTags(servers[serverID].description)}`; + } } - } - // assign the callbacks - serverConnection.onopen = function () { - onCOOpen(); - }; + // assign the callbacks + serverConnection.onopen = function () { + onCOOpen(); + }; - serverConnection.onmessage = function (evt: MessageEvent) { - onCOMessage(evt); - }; + serverConnection.onmessage = function (evt: MessageEvent) { + onCOMessage(evt); + }; - serverConnection.onerror = function (_evt: Event) { - document.getElementById(`server${serverID}`).className = 'unavailable'; - }; + serverConnection.onerror = function (_evt: Event) { + document.getElementById(`server${serverID}`).className = 'unavailable'; + }; } function loadServerlist(thelist: { name: string, description: string, ip: string, port: number, ws_port: number, assets: string, online: string }[]) { - localStorage.setItem('masterlist', JSON.stringify(thelist)); - processServerlist(thelist); + localStorage.setItem('masterlist', JSON.stringify(thelist)); + processServerlist(thelist); } function cachedServerlist(response: Response) { - if (!response.ok) { - document.getElementById('ms_error').style.display = 'block'; - processServerlist(JSON.parse(localStorage.getItem('masterlist'))); - return; - } - return response.json(); + if (!response.ok) { + document.getElementById('ms_error').style.display = 'block'; + processServerlist(JSON.parse(localStorage.getItem('masterlist'))); + return; + } + return response.json(); } function processServerlist(thelist: { name: string, description: string, ip: string, port: number, ws_port: number, assets: string, online: string }[]) { - const myURL: string = window.location.href.replace('https://','http://').replace('index.html',''); - for (let i = 0; i < thelist.length - 1; i++) { - const serverEntry: { name: string, description: string, ip: string, port: number, ws_port: number, assets: string, online: string } = thelist[i]; + const myURL: string = window.location.href.replace('https://', 'http://').replace('index.html', ''); + for (let i = 0; i < thelist.length - 1; i++) { + const serverEntry: { name: string, description: string, ip: string, port: number, ws_port: number, assets: string, online: string } = thelist[i]; - servers[i] = serverEntry; - servers[i].online = "Offline"; + servers[i] = serverEntry; + servers[i].online = "Offline"; - const ipport = `${serverEntry.ip}:${serverEntry.ws_port}`; + const ipport = `${serverEntry.ip}:${serverEntry.ws_port}`; - if (serverEntry.ws_port) { - document.getElementById('masterlist').innerHTML - += `
  • ${safeTags(serverEntry.name)}

    ` - + `Watch` - + `Join
  • `; + if (serverEntry.ws_port) { + document.getElementById('masterlist').innerHTML + += `
  • ${safeTags(serverEntry.name)}

    ` + + `Watch` + + `Join
  • `; + } } - } } function processVersion(data: string) { - document.getElementById('clientinfo').innerHTML = `Client version: ${version}`; - document.getElementById('serverinfo').innerHTML = `Master server version: ${data}`; + document.getElementById('clientinfo').innerHTML = `Client version: ${version}`; + document.getElementById('serverinfo').innerHTML = `Master server version: ${data}`; } diff --git a/webAO/packets/handlers/handleBN.ts b/webAO/packets/handlers/handleBN.ts index 3c5d95f..c561884 100644 --- a/webAO/packets/handlers/handleBN.ts +++ b/webAO/packets/handlers/handleBN.ts @@ -5,80 +5,79 @@ import { updateBackgroundPreview } from '../../dom/updateBackgroundPreview' import { getIndexFromSelect } from '../../dom/getIndexFromSelect' import tryUrls from "../../utils/tryUrls"; - /** * Handles a background change. * @param {Array} args packet arguments */ export const handleBN = (args: string[]) => { - const bgFromArgs = safeTags(args[1]); - client.viewport.setBackgroundName(bgFromArgs); - const bgfolder = client.viewport.getBackgroundFolder(); - const bg_index = getIndexFromSelect( - "bg_select", - client.viewport.getBackgroundName() - ); - (document.getElementById("bg_select")).selectedIndex = - bg_index; - updateBackgroundPreview(); - if (bg_index === 0) { - (document.getElementById("bg_filename")).value = - client.viewport.getBackgroundName(); - } - - tryUrls( - `${AO_HOST}background/${encodeURI(args[1].toLowerCase())}/defenseempty` - ).then((resp) => { - (document.getElementById("bg_preview")).src = resp; - }); - tryUrls(`${bgfolder}defensedesk`).then((resp) => { - (document.getElementById("client_def_bench")).src = - resp; - }); - tryUrls(`${bgfolder}stand`).then((resp) => { - (document.getElementById("client_wit_bench")).src = - resp; - }); - tryUrls(`${bgfolder}prosecutiondesk`).then((resp) => { - (document.getElementById("client_pro_bench")).src = - resp; - }); - tryUrls(`${bgfolder}full`).then((resp) => { - (document.getElementById("client_court")).src = resp; - }); - tryUrls(`${bgfolder}defenseempty`).then((resp) => { - (document.getElementById("client_court_def")).src = - resp; - }); - tryUrls(`${bgfolder}transition_def`).then((resp) => { - (document.getElementById("client_court_deft")).src = - resp; - }); - tryUrls(`${bgfolder}witnessempty`).then((resp) => { - (document.getElementById("client_court_wit")).src = - resp; - }); - tryUrls(`${bgfolder}transition_pro`).then((resp) => { - (document.getElementById("client_court_prot")).src = - resp; - }); - tryUrls(`${bgfolder}prosecutorempty`).then((resp) => { - (document.getElementById("client_court_pro")).src = - resp; - }); + const bgFromArgs = safeTags(args[1]); + client.viewport.setBackgroundName(bgFromArgs); + const bgfolder = client.viewport.getBackgroundFolder(); + const bg_index = getIndexFromSelect( + "bg_select", + client.viewport.getBackgroundName() + ); + (document.getElementById("bg_select")).selectedIndex = + bg_index; + updateBackgroundPreview(); + if (bg_index === 0) { + (document.getElementById("bg_filename")).value = + client.viewport.getBackgroundName(); + } - if (client.charID === -1) { - client.viewport.set_side({ - position: "jud", - showSpeedLines: false, - showDesk: true, + tryUrls( + `${AO_HOST}background/${encodeURI(args[1].toLowerCase())}/defenseempty` + ).then((resp) => { + (document.getElementById("bg_preview")).src = resp; + }); + tryUrls(`${bgfolder}defensedesk`).then((resp) => { + (document.getElementById("client_def_bench")).src = + resp; + }); + tryUrls(`${bgfolder}stand`).then((resp) => { + (document.getElementById("client_wit_bench")).src = + resp; + }); + tryUrls(`${bgfolder}prosecutiondesk`).then((resp) => { + (document.getElementById("client_pro_bench")).src = + resp; + }); + tryUrls(`${bgfolder}full`).then((resp) => { + (document.getElementById("client_court")).src = resp; }); - } else { - client.viewport.set_side({ - position: client.chars[client.charID].side, - showSpeedLines: false, - showDesk: true, + tryUrls(`${bgfolder}defenseempty`).then((resp) => { + (document.getElementById("client_court_def")).src = + resp; }); - } -} \ No newline at end of file + tryUrls(`${bgfolder}transition_def`).then((resp) => { + (document.getElementById("client_court_deft")).src = + resp; + }); + tryUrls(`${bgfolder}witnessempty`).then((resp) => { + (document.getElementById("client_court_wit")).src = + resp; + }); + tryUrls(`${bgfolder}transition_pro`).then((resp) => { + (document.getElementById("client_court_prot")).src = + resp; + }); + tryUrls(`${bgfolder}prosecutorempty`).then((resp) => { + (document.getElementById("client_court_pro")).src = + resp; + }); + + if (client.charID === -1) { + client.viewport.set_side({ + position: "jud", + showSpeedLines: false, + showDesk: true, + }); + } else { + client.viewport.set_side({ + position: client.chars[client.charID].side, + showSpeedLines: false, + showDesk: true, + }); + } +} diff --git a/webAO/packets/handlers/handleCT.ts b/webAO/packets/handlers/handleCT.ts index cff9b24..247f1a7 100644 --- a/webAO/packets/handlers/handleCT.ts +++ b/webAO/packets/handlers/handleCT.ts @@ -1,6 +1,6 @@ import queryParser from '../../utils/queryParser' import { prepChat } from '../../encoding' -let { mode } = queryParser(); +const { mode } = queryParser(); /** * Handles an out-of-character chat message. diff --git a/webAO/packets/handlers/handleDONE.ts b/webAO/packets/handlers/handleDONE.ts index 3cafd5e..6ca31bf 100644 --- a/webAO/packets/handlers/handleDONE.ts +++ b/webAO/packets/handlers/handleDONE.ts @@ -1,7 +1,7 @@ import queryParser from "../../utils/queryParser"; -let { mode } = queryParser() - /** +const { mode } = queryParser() +/** * Handles the handshake completion packet, meaning the player * is ready to select a character. * @@ -13,4 +13,4 @@ export const handleDONE = (_args: string[]) => { // Spectators don't need to pick a character document.getElementById("client_waiting")!.style.display = "none"; } - } \ No newline at end of file +} \ No newline at end of file diff --git a/webAO/packets/handlers/handleFL.ts b/webAO/packets/handlers/handleFL.ts index 89df4ed..e77e968 100644 --- a/webAO/packets/handlers/handleFL.ts +++ b/webAO/packets/handlers/handleFL.ts @@ -1,45 +1,44 @@ import { setExtraFeatures } from "../../client"; - /** * With this the server tells us which features it supports * @param {Array} args list of features */ export const handleFL = (args: string[]) => { - console.info("Server-supported features:"); - console.info(args); - setExtraFeatures(args); - - if (args.includes("yellowtext")) { - const colorselect = ( - document.getElementById("textcolor") - ); - - colorselect.options[colorselect.options.length] = new Option("Yellow","5"); - colorselect.options[colorselect.options.length] = new Option("Pink", "6"); - colorselect.options[colorselect.options.length] = new Option("Cyan", "7"); - colorselect.options[colorselect.options.length] = new Option("Grey", "8"); - } - - if (args.includes("cccc_ic_support")) { - document.getElementById("cccc")!.style.display = ""; - document.getElementById("pairing")!.style.display = ""; - } - - if (args.includes("flipping")) { - document.getElementById("button_flip")!.style.display = ""; - } - - if (args.includes("looping_sfx")) { - document.getElementById("button_shake")!.style.display = ""; - document.getElementById("2.7")!.style.display = ""; - } - - if (args.includes("effects")) { - document.getElementById("2.8")!.style.display = ""; - } - - if (args.includes("y_offset")) { - document.getElementById("y_offset")!.style.display = ""; - } + console.info("Server-supported features:"); + console.info(args); + setExtraFeatures(args); + + if (args.includes("yellowtext")) { + const colorselect = ( + document.getElementById("textcolor") + ); + + colorselect.options[colorselect.options.length] = new Option("Yellow", "5"); + colorselect.options[colorselect.options.length] = new Option("Pink", "6"); + colorselect.options[colorselect.options.length] = new Option("Cyan", "7"); + colorselect.options[colorselect.options.length] = new Option("Grey", "8"); + } + + if (args.includes("cccc_ic_support")) { + document.getElementById("cccc")!.style.display = ""; + document.getElementById("pairing")!.style.display = ""; + } + + if (args.includes("flipping")) { + document.getElementById("button_flip")!.style.display = ""; + } + + if (args.includes("looping_sfx")) { + document.getElementById("button_shake")!.style.display = ""; + document.getElementById("2.7")!.style.display = ""; + } + + if (args.includes("effects")) { + document.getElementById("2.8")!.style.display = ""; + } + + if (args.includes("y_offset")) { + document.getElementById("y_offset")!.style.display = ""; + } } diff --git a/webAO/packets/handlers/handleHP.ts b/webAO/packets/handlers/handleHP.ts index f365590..81dee64 100644 --- a/webAO/packets/handlers/handleHP.ts +++ b/webAO/packets/handlers/handleHP.ts @@ -1,23 +1,22 @@ import { client } from "../../client"; - - /** - * Handles a change in the health bars' states. - * @param {Array} args packet arguments - */ +/** + * Handles a change in the health bars' states. + * @param {Array} args packet arguments + */ export const handleHP = (args: string[]) => { const percent_hp = Number(args[2]) * 10; let healthbox; if (args[1] === "1") { - // Def hp - client.hp[0] = Number(args[2]); - healthbox = document.getElementById("client_defense_hp"); + // Def hp + client.hp[0] = Number(args[2]); + healthbox = document.getElementById("client_defense_hp"); } else { - // Pro hp - client.hp[1] = Number(args[2]); - healthbox = document.getElementById("client_prosecutor_hp"); + // Pro hp + client.hp[1] = Number(args[2]); + healthbox = document.getElementById("client_prosecutor_hp"); } (( - healthbox.getElementsByClassName("health-bar")[0] + healthbox.getElementsByClassName("health-bar")[0] )).style.width = `${percent_hp}%`; - } \ No newline at end of file +} diff --git a/webAO/packets/handlers/handleLE.ts b/webAO/packets/handlers/handleLE.ts index e8c263b..97cf979 100644 --- a/webAO/packets/handlers/handleLE.ts +++ b/webAO/packets/handlers/handleLE.ts @@ -23,7 +23,7 @@ export const handleLE = (args: string[]) => { const evidence_box = document.getElementById("evidences")!; evidence_box.innerHTML = ""; for (let i = 1; i <= client.evidences.length; i++) { - let evi_item = new Image(); + const evi_item = new Image(); evi_item.id = "evi_"+i; evi_item.className = "evi_icon" evi_item.src = client.evidences[i - 1].icon; diff --git a/webAO/packets/handlers/handleMS.ts b/webAO/packets/handlers/handleMS.ts index 3be4eef..8464942 100644 --- a/webAO/packets/handlers/handleMS.ts +++ b/webAO/packets/handlers/handleMS.ts @@ -1,3 +1,5 @@ +/* eslint indent: ["error", 2, { "SwitchCase": 1 }] */ + import { client, extrafeatures, UPDATE_INTERVAL } from "../../client"; import { handleCharacterInfo } from "../../client/handleCharacterInfo"; import { resetICParams } from "../../client/resetICParams"; diff --git a/webAO/packets/handlers/handlePV.ts b/webAO/packets/handlers/handlePV.ts index 180fbea..938fb0d 100644 --- a/webAO/packets/handlers/handlePV.ts +++ b/webAO/packets/handlers/handlePV.ts @@ -10,79 +10,79 @@ import { AO_HOST } from "../../client/aoHost"; * @param {Array} args packet arguments */ export const handlePV = async (args: string[]) => { - client.charID = Number(args[3]); - document.getElementById("client_waiting")!.style.display = "none"; - document.getElementById("client_charselect")!.style.display = "none"; + client.charID = Number(args[3]); + document.getElementById("client_waiting")!.style.display = "none"; + document.getElementById("client_charselect")!.style.display = "none"; - const me = client.chars[client.charID]; - client.selectedEmote = -1; - const { emotes } = client; - const emotesList = document.getElementById("client_emo")!; - emotesList.style.display = ""; - emotesList.innerHTML = ""; // Clear emote box - const ini = me.inifile; - me.side = ini.options.side; - updateActionCommands(me.side); - if (ini.emotions.number === 0) { - emotesList.innerHTML = `No emotes available`; - } else { - for (let i = 1; i <= ini.emotions.number; i++) { - try { - const emoteinfo = ini.emotions[i].split("#"); - let esfx; - let esfxd; - try { - esfx = ini.soundn[i] || "0"; - esfxd = Number(ini.soundt[i]) || 0; - } catch (e) { - console.warn("ini sound is completly missing"); - esfx = "0"; - esfxd = 0; - } - // Make sure the asset server is case insensitive, or that everything on it is lowercase + } else { + for (let i = 1; i <= ini.emotions.number; i++) { + try { + const emoteinfo = ini.emotions[i].split("#"); + let esfx; + let esfxd; + try { + esfx = ini.soundn[i] || "0"; + esfxd = Number(ini.soundt[i]) || 0; + } catch (e) { + console.warn("ini sound is completly missing"); + esfx = "0"; + esfxd = 0; + } + // Make sure the asset server is case insensitive, or that everything on it is lowercase - emotes[i] = { - desc: emoteinfo[0].toLowerCase(), - preanim: emoteinfo[1].toLowerCase(), - emote: emoteinfo[2].toLowerCase(), - zoom: Number(emoteinfo[3]) || 0, - deskmod: Number(emoteinfo[4]) || 1, - sfx: esfx.toLowerCase(), - sfxdelay: esfxd, - frame_screenshake: "", - frame_realization: "", - frame_sfx: "", - button: `${AO_HOST}characters/${encodeURI( - me.name.toLowerCase() - )}/emotions/button${i}_off.png`, - }; + emotes[i] = { + desc: emoteinfo[0].toLowerCase(), + preanim: emoteinfo[1].toLowerCase(), + emote: emoteinfo[2].toLowerCase(), + zoom: Number(emoteinfo[3]) || 0, + deskmod: Number(emoteinfo[4]) || 1, + sfx: esfx.toLowerCase(), + sfxdelay: esfxd, + frame_screenshake: "", + frame_realization: "", + frame_sfx: "", + button: `${AO_HOST}characters/${encodeURI( + me.name.toLowerCase() + )}/emotions/button${i}_off.png`, + }; - let emote_item = new Image(); - emote_item.id = "emo_"+i; - emote_item.className = "emote_button"; - emote_item.src = emotes[i].button; - emote_item.alt = emotes[i].desc; - emote_item.title = emotes[i].desc; - emote_item.onclick = () => { window.pickEmotion(i) } - emotesList.appendChild(emote_item); - } catch (e) { - console.error(`missing emote ${i}`); - } + const emote_item = new Image(); + emote_item.id = "emo_" + i; + emote_item.className = "emote_button"; + emote_item.src = emotes[i].button; + emote_item.alt = emotes[i].desc; + emote_item.title = emotes[i].desc; + emote_item.onclick = () => { window.pickEmotion(i) } + emotesList.appendChild(emote_item); + } catch (e) { + console.error(`missing emote ${i}`); + } + } + pickEmotion(1); } - pickEmotion(1); - } - if ( - await fileExists( - `${AO_HOST}characters/${encodeURI(me.name.toLowerCase())}/custom.gif` - ) - ) { - document.getElementById("button_4")!.style.display = ""; - } else { - document.getElementById("button_4")!.style.display = "none"; - } + if ( + await fileExists( + `${AO_HOST}characters/${encodeURI(me.name.toLowerCase())}/custom.gif` + ) + ) { + document.getElementById("button_4")!.style.display = ""; + } else { + document.getElementById("button_4")!.style.display = "none"; + } } diff --git a/webAO/packets/handlers/handleRM.ts b/webAO/packets/handlers/handleRM.ts index c18821b..e11abc8 100644 --- a/webAO/packets/handlers/handleRM.ts +++ b/webAO/packets/handlers/handleRM.ts @@ -1,10 +1,10 @@ import {client} from '../../client' import vanilla_music_arr from "../../constants/music.js"; - /** +/** * we are asking ourselves what characters there are * @param {Array} args packet arguments */ export const handleRM = (_args: string[]) => { client.sender.sendSelf(`SM#${vanilla_music_arr.join("#")}#%`); - } \ No newline at end of file +} \ No newline at end of file diff --git a/webAO/packets/handlers/handleSC.ts b/webAO/packets/handlers/handleSC.ts index a31762a..b870cb0 100644 --- a/webAO/packets/handlers/handleSC.ts +++ b/webAO/packets/handlers/handleSC.ts @@ -2,7 +2,7 @@ import queryParser from "../../utils/queryParser"; import { client } from '../../client' import { handleCharacterInfo } from "../../client/handleCharacterInfo"; -let { mode } = queryParser(); +const { mode } = queryParser(); /** * Handles incoming character information, containing all characters diff --git a/webAO/services/__tests__/downloadFile.test.ts b/webAO/services/__tests__/downloadFile.test.ts index b217b2c..b541095 100644 --- a/webAO/services/__tests__/downloadFile.test.ts +++ b/webAO/services/__tests__/downloadFile.test.ts @@ -1,9 +1,9 @@ import downloadFile from '../downloadFile' jest - .useFakeTimers() - .setSystemTime(new Date('2020-01-01').getTime()); + .useFakeTimers() + .setSystemTime(new Date('2020-01-01').getTime()); - global.URL.createObjectURL = jest.fn(); +global.URL.createObjectURL = jest.fn(); (window as any).global.Blob = function (content, options){return ({content, options})} describe('downloadFile', () => { diff --git a/webAO/services/downloadFile.ts b/webAO/services/downloadFile.ts index 058075f..d272249 100644 --- a/webAO/services/downloadFile.ts +++ b/webAO/services/downloadFile.ts @@ -1,8 +1,8 @@ const downloadFile = (content: string, filename: string) => { - const a = document.createElement('a'); - const file = new Blob([content], {type: 'text'}); - a.href= URL.createObjectURL(file); - a.download = filename; - a.click(); + const a = document.createElement('a'); + const file = new Blob([content], { type: 'text' }); + a.href = URL.createObjectURL(file); + a.download = filename; + a.click(); } -export default downloadFile \ No newline at end of file +export default downloadFile diff --git a/webAO/services/request.js b/webAO/services/request.js index 88613e5..25a8567 100644 --- a/webAO/services/request.js +++ b/webAO/services/request.js @@ -5,31 +5,31 @@ * @throws {Error} if status code is not 2xx, or a network error occurs */ export async function requestBuffer(url) { - return new Promise((resolve, reject) => { - const xhr = new XMLHttpRequest(); - xhr.responseType = 'arraybuffer'; - xhr.addEventListener('error', () => { - const err = new Error(`Request for ${url} failed: ${xhr.statusText}`); - err.code = xhr.status; - reject(err); - }); - xhr.addEventListener('abort', () => { - const err = new Error(`Request for ${url} was aborted!`); - err.code = xhr.status; - reject(err); - }); - xhr.addEventListener('load', () => { - if (xhr.status < 200 || xhr.status >= 300) { - const err = new Error(`Request for ${url} failed with status code ${xhr.status}`); - err.code = xhr.status; - reject(err); - } else { - resolve(xhr.response); - } + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.responseType = 'arraybuffer'; + xhr.addEventListener('error', () => { + const err = new Error(`Request for ${url} failed: ${xhr.statusText}`); + err.code = xhr.status; + reject(err); + }); + xhr.addEventListener('abort', () => { + const err = new Error(`Request for ${url} was aborted!`); + err.code = xhr.status; + reject(err); + }); + xhr.addEventListener('load', () => { + if (xhr.status < 200 || xhr.status >= 300) { + const err = new Error(`Request for ${url} failed with status code ${xhr.status}`); + err.code = xhr.status; + reject(err); + } else { + resolve(xhr.response); + } + }); + xhr.open('GET', url, true); + xhr.send(); }); - xhr.open('GET', url, true); - xhr.send(); - }); } /** @@ -39,28 +39,28 @@ export async function requestBuffer(url) { * @throws {Error} if status code is not 2xx, or a network error occurs */ export const request = async (url) => new Promise((resolve, reject) => { - const xhr = new XMLHttpRequest(); - xhr.responseType = 'text'; - xhr.addEventListener('error', () => { - const err = new Error(`Request for ${url} failed: ${xhr.statusText}`); - err.code = xhr.status; - reject(err); - }); - xhr.addEventListener('abort', () => { - const err = new Error(`Request for ${url} was aborted!`); - err.code = xhr.status; - reject(err); - }); - xhr.addEventListener('load', () => { - if (xhr.status < 200 || xhr.status >= 300) { - const err = new Error(`Request for ${url} failed with status code ${xhr.status}`); - err.code = xhr.status; - reject(err); - } else { - resolve(xhr.response); - } - }); - xhr.open('GET', url, true); - xhr.send(); + const xhr = new XMLHttpRequest(); + xhr.responseType = 'text'; + xhr.addEventListener('error', () => { + const err = new Error(`Request for ${url} failed: ${xhr.statusText}`); + err.code = xhr.status; + reject(err); + }); + xhr.addEventListener('abort', () => { + const err = new Error(`Request for ${url} was aborted!`); + err.code = xhr.status; + reject(err); + }); + xhr.addEventListener('load', () => { + if (xhr.status < 200 || xhr.status >= 300) { + const err = new Error(`Request for ${url} failed with status code ${xhr.status}`); + err.code = xhr.status; + reject(err); + } else { + resolve(xhr.response); + } + }); + xhr.open('GET', url, true); + xhr.send(); }); export default request; diff --git a/webAO/styles/chatbox/chatboxes.js b/webAO/styles/chatbox/chatboxes.js index 9e52d43..5dc70e0 100644 --- a/webAO/styles/chatbox/chatboxes.js +++ b/webAO/styles/chatbox/chatboxes.js @@ -1,28 +1,28 @@ export default [ - 'aa', - 'acww', - 'dd', - 'dgs', - 'plvsaa', - 'trilogy', - 'future', - 'legacy', - 'ddlc', - 'dr1', - 'dr2', - 'drv3', - 'drae', - 'p3', - 'p4', - 'p5', - '999', - 'halla', - 'homestuck', - 'key', - 'sonic', - 'yakuza', - 'yttd', - 'whentheycry', - 'n64zelda', - 'papermario', + 'aa', + 'acww', + 'dd', + 'dgs', + 'plvsaa', + 'trilogy', + 'future', + 'legacy', + 'ddlc', + 'dr1', + 'dr2', + 'drv3', + 'drae', + 'p3', + 'p4', + 'p5', + '999', + 'halla', + 'homestuck', + 'key', + 'sonic', + 'yakuza', + 'yttd', + 'whentheycry', + 'n64zelda', + 'papermario', ]; diff --git a/webAO/ui.js b/webAO/ui.js index dc3c342..f82688c 100644 --- a/webAO/ui.js +++ b/webAO/ui.js @@ -1,3 +1,4 @@ +/* eslint indent: ["error", 2, { "SwitchCase": 1 }] */ /* eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsFor": ["container"] }] */ import { GoldenLayout } from 'golden-layout'; diff --git a/webAO/utils/__tests__/aoml.test.ts b/webAO/utils/__tests__/aoml.test.ts index 90967d7..78355ed 100644 --- a/webAO/utils/__tests__/aoml.test.ts +++ b/webAO/utils/__tests__/aoml.test.ts @@ -39,75 +39,75 @@ c6_talking = 0 const mockRequest = request as jest.MockedFunction; mockRequest.mockReturnValue(Promise.resolve(networkRequest)) - describe('mlConfig', () => { +describe('mlConfig', () => { beforeEach(() => { - // Clear all instances and calls to constructor and all methods: - mockRequest.mockClear(); + // Clear all instances and calls to constructor and all methods: + mockRequest.mockClear(); }); it('Should make a network request', () => { mlConfig('localhost') expect(mockRequest).toHaveBeenCalledTimes(1); - }); - }) - describe('applyMarkdown', () => { + }); +}) +describe('applyMarkdown', () => { const config = mlConfig('localhost') beforeEach(() => { - // Clear all instances and calls to constructor and all methods: - mockRequest.mockClear(); + // Clear all instances and calls to constructor and all methods: + mockRequest.mockClear(); }); - + it('Should create an array of spans containing letters', async () => { - const word = `hello` - const actual = await config.applyMarkdown(`hello`, `blue`) - let index = 0 - for (const element of actual) { - expect(element.innerHTML).toBe(word[index]) - index++ - } + const word = `hello` + const actual = await config.applyMarkdown(`hello`, `blue`) + let index = 0 + for (const element of actual) { + expect(element.innerHTML).toBe(word[index]) + index++ + } }) it('Should add colors based on settings', async () => { - const config = mlConfig('localhost') - const actual = await config.applyMarkdown(`(heya)`, `blue`) - expect(actual[0].getAttribute('style')).toBe('color: rgb(107, 198, 247);') + const config = mlConfig('localhost') + const actual = await config.applyMarkdown(`(heya)`, `blue`) + expect(actual[0].getAttribute('style')).toBe('color: rgb(107, 198, 247);') }) it('Should keep a letter if remove = 0', async () => { - const config = mlConfig('localhost') - - const actual = await config.applyMarkdown(`(What())Hey!`, `white`) - const expected = `(` - expect(actual[5].innerHTML).toBe(expected) + const config = mlConfig('localhost') + + const actual = await config.applyMarkdown(`(What())Hey!`, `white`) + const expected = `(` + expect(actual[5].innerHTML).toBe(expected) }) it('Should remove a letter if remove = 1', async () => { - const config = mlConfig('localhost') - - const actual = await config.applyMarkdown(`~What~()Hey!`, `white`) - const expected = `` - expect(actual[0].innerHTML).toBe(expected) + const config = mlConfig('localhost') + + const actual = await config.applyMarkdown(`~What~()Hey!`, `white`) + const expected = `` + expect(actual[0].innerHTML).toBe(expected) }) it('Should remove a letter if remove = 1', async () => { - const config = mlConfig('localhost') - - const actual = await config.applyMarkdown(`~What~()Hey!`, `white`) - const expected = `` - expect(actual[0].innerHTML).toBe(expected) + const config = mlConfig('localhost') + + const actual = await config.applyMarkdown(`~What~()Hey!`, `white`) + const expected = `` + expect(actual[0].innerHTML).toBe(expected) }) it('Should keep a closing letter if remove = 0', async () => { - const config = mlConfig('localhost') - - const actual = await config.applyMarkdown(`~NO[]~!`, `white`) - const expected = `` - expect(actual[4].innerHTML).toBe(expected) + const config = mlConfig('localhost') + + const actual = await config.applyMarkdown(`~NO[]~!`, `white`) + const expected = `` + expect(actual[4].innerHTML).toBe(expected) }) it('Should remove a closing letter if remove = 1', async () => { - const config = mlConfig('localhost') - const actual = await config.applyMarkdown(`~NO||~!`, `white`) - const expected = `` - expect(actual[5].innerHTML).toBe(expected) + const config = mlConfig('localhost') + const actual = await config.applyMarkdown(`~NO||~!`, `white`) + const expected = `` + expect(actual[5].innerHTML).toBe(expected) }) - - }) - + +}) + diff --git a/webAO/utils/__tests__/tryUrls.test.ts b/webAO/utils/__tests__/tryUrls.test.ts index 444664e..ebc2f6b 100644 --- a/webAO/utils/__tests__/tryUrls.test.ts +++ b/webAO/utils/__tests__/tryUrls.test.ts @@ -9,23 +9,23 @@ describe('tryUrls', () => { it('Should try multiple file extensions', async () => { const url = "localhost/stoneddiscord/assets" mockFileExists - .mockReturnValueOnce(Promise.resolve(false)) - .mockReturnValueOnce(Promise.resolve(false)) - .mockReturnValueOnce(Promise.resolve(false)) - .mockReturnValueOnce(Promise.resolve(true)) + .mockReturnValueOnce(Promise.resolve(false)) + .mockReturnValueOnce(Promise.resolve(false)) + .mockReturnValueOnce(Promise.resolve(false)) + .mockReturnValueOnce(Promise.resolve(true)) const actual = await tryUrls(url) const expected = 'localhost/stoneddiscord/assets.apng' expect(actual).toBe(expected); - }); - + }); + it('Should return a transparent png if it cant find any assets', async () => { const url = "localhost/stoneddiscord/assets" mockFileExists - .mockReturnValue(Promise.resolve(false)) + .mockReturnValue(Promise.resolve(false)) const actual = await tryUrls(url) const expected = transparentPng expect(actual).toBe(expected); - }); + }); }) - + diff --git a/webAO/utils/aoml.ts b/webAO/utils/aoml.ts index 1f2f482..a2c1dd5 100644 --- a/webAO/utils/aoml.ts +++ b/webAO/utils/aoml.ts @@ -64,10 +64,10 @@ const mlConfig = (AO_HOST: string) => { const closingStack = [] const colorStack = [] // each value in output will be an html element - let output: HTMLSpanElement[] = [] + const output: HTMLSpanElement[] = [] for (const letter of text) { - let currentSelector = document.createElement('span') - let currentIdentifier = identifiers.get(letter) + const currentSelector = document.createElement('span') + const currentIdentifier = identifiers.get(letter) const currentClosingLetter = closingStack[closingStack.length - 1] const keepChar = Number(currentIdentifier?.remove) === 0 if (currentClosingLetter === letter) { diff --git a/webAO/utils/calculateApngLength.js b/webAO/utils/calculateApngLength.js index 0a84d46..ab8682a 100644 --- a/webAO/utils/calculateApngLength.js +++ b/webAO/utils/calculateApngLength.js @@ -3,28 +3,28 @@ * @param {data} apngFile the APNG data */ const calculateApngLength = (apngFile) => { - const d = new Uint8Array(apngFile); - // https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chunk - let duration = 0; - for (let i = 0; i < d.length; i++) { - // Find fcTL header (66 63 54 4C) - if (d[i] === 0x66 - && d[i + 1] === 0x63 - && d[i + 2] === 0x54 - && d[i + 3] === 0x4C) { - // numerator and denominator - const delayNum = Number(d[i + 23]); - const delayDen = Number(d[i + 25]); - let delay; - // minimum is 100ms - if (delayDen === 0) { - delay = delayNum / 100; - } else { - delay = delayNum / delayDen; - } - duration += delay; + const d = new Uint8Array(apngFile); + // https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chunk + let duration = 0; + for (let i = 0; i < d.length; i++) { + // Find fcTL header (66 63 54 4C) + if (d[i] === 0x66 + && d[i + 1] === 0x63 + && d[i + 2] === 0x54 + && d[i + 3] === 0x4C) { + // numerator and denominator + const delayNum = Number(d[i + 23]); + const delayDen = Number(d[i + 25]); + let delay; + // minimum is 100ms + if (delayDen === 0) { + delay = delayNum / 100; + } else { + delay = delayNum / delayDen; + } + duration += delay; + } } - } - return duration * 10; + return duration * 10; }; export default calculateApngLength; diff --git a/webAO/utils/calculateGifLength.js b/webAO/utils/calculateGifLength.js index 3ed6aa4..eccfc77 100644 --- a/webAO/utils/calculateGifLength.js +++ b/webAO/utils/calculateGifLength.js @@ -6,24 +6,24 @@ * @param {data} gifFile the GIF data */ const calculateGifLength = (gifFile) => { - const d = new Uint8Array(gifFile); - // Thanks to http://justinsomnia.org/2006/10/gif-animation-duration-calculation/ - // And http://www.w3.org/Graphics/GIF/spec-gif89a.txt - let duration = 0; - for (let i = 0; i < d.length; i++) { - // Find a Graphic Control Extension hex(21F904__ ____ __00) - if (d[i] === 0x21 - && d[i + 1] === 0xF9 - && d[i + 2] === 0x04 - && d[i + 7] === 0x00) { - // Swap 5th and 6th bytes to get the delay per frame - const delay = (d[i + 5] << 8) | (d[i + 4] & 0xFF); + const d = new Uint8Array(gifFile); + // Thanks to http://justinsomnia.org/2006/10/gif-animation-duration-calculation/ + // And http://www.w3.org/Graphics/GIF/spec-gif89a.txt + let duration = 0; + for (let i = 0; i < d.length; i++) { + // Find a Graphic Control Extension hex(21F904__ ____ __00) + if (d[i] === 0x21 + && d[i + 1] === 0xF9 + && d[i + 2] === 0x04 + && d[i + 7] === 0x00) { + // Swap 5th and 6th bytes to get the delay per frame + const delay = (d[i + 5] << 8) | (d[i + 4] & 0xFF); - // Should be aware browsers have a minimum frame delay - // e.g. 6ms for IE, 2ms modern browsers (50fps) - duration += delay < 2 ? 10 : delay; + // Should be aware browsers have a minimum frame delay + // e.g. 6ms for IE, 2ms modern browsers (50fps) + duration += delay < 2 ? 10 : delay; + } } - } - return duration * 10; + return duration * 10; }; export default calculateGifLength; diff --git a/webAO/utils/calculateWebpLength.js b/webAO/utils/calculateWebpLength.js index ea7eb80..e81a77b 100644 --- a/webAO/utils/calculateWebpLength.js +++ b/webAO/utils/calculateWebpLength.js @@ -1,24 +1,24 @@ /* eslint no-bitwise: "off" */ const calculateWebpLength = (webpFile) => { - const d = new Uint8Array(webpFile); - // https://developers.google.com/speed/webp/docs/riff_container#animation - let duration = 0; - for (let i = 0; i < d.length; i++) { - // Find ANMF header (41 4E 4D 46) - if (d[i] === 0x41 - && d[i + 1] === 0x4E - && d[i + 2] === 0x4D - && d[i + 3] === 0x46) { - // Swap 5th and 6th bytes to get the delay per frame - const delay = (d[i + 21] << 8) | (d[i + 20] & 0xFF); + const d = new Uint8Array(webpFile); + // https://developers.google.com/speed/webp/docs/riff_container#animation + let duration = 0; + for (let i = 0; i < d.length; i++) { + // Find ANMF header (41 4E 4D 46) + if (d[i] === 0x41 + && d[i + 1] === 0x4E + && d[i + 2] === 0x4D + && d[i + 3] === 0x46) { + // Swap 5th and 6th bytes to get the delay per frame + const delay = (d[i + 21] << 8) | (d[i + 20] & 0xFF); - // Should be aware browsers have a minimum frame delay - // e.g. 6ms for IE, 2ms modern browsers (50fps) - duration += delay < 2 ? 10 : delay; + // Should be aware browsers have a minimum frame delay + // e.g. 6ms for IE, 2ms modern browsers (50fps) + duration += delay < 2 ? 10 : delay; + } } - } - return duration; + return duration; }; export default calculateWebpLength; diff --git a/webAO/viewport/utils/handleICSpeaking.ts b/webAO/viewport/utils/handleICSpeaking.ts index 220dd58..2cea926 100644 --- a/webAO/viewport/utils/handleICSpeaking.ts +++ b/webAO/viewport/utils/handleICSpeaking.ts @@ -275,7 +275,7 @@ export const handle_ic_speaking = async (playerChatMsg: ChatMsg) => { intensity = intensity - fg.childElementCount; for (let i = 0; i < intensity; i++) { - let drop = document.createElement("p"); + const drop = document.createElement("p"); drop.style.left = (Math.random() * 100) + "%"; drop.style.animationDelay = String(Math.random()) + "s"; fg.appendChild(drop) @@ -310,9 +310,9 @@ export const handle_ic_speaking = async (playerChatMsg: ChatMsg) => { ); } catch (error) { console.warn("markdown failed"); - let output: HTMLSpanElement[] = [] + const output: HTMLSpanElement[] = [] for (const letter of client.viewport.getChatmsg().content) { - let currentSelector = document.createElement('span'); + const currentSelector = document.createElement('span'); currentSelector.innerHTML = letter; currentSelector.className = `text_${COLORS[client.viewport.getChatmsg().color]}`; output.push(currentSelector); diff --git a/webAO/viewport/viewport.ts b/webAO/viewport/viewport.ts index 3410f46..838a2c8 100644 --- a/webAO/viewport/viewport.ts +++ b/webAO/viewport/viewport.ts @@ -20,18 +20,18 @@ import { setStartFirstTickCheck, setStartSecondTickCheck, startFirstTickCheck, s const viewport = (): Viewport => { let animating = false; - let blipChannels = createBlipsChannels(); + const blipChannels = createBlipsChannels(); let chatmsg = defaultChatMsg; let currentBlipChannel = 0; let lastChar = ""; let lastEvi = 0; - let music = createMusic(); - let musicVolume = 0; + const music = createMusic(); + const musicVolume = 0; let sfxAudio = createSfxAudio(); let sfxplayed = 0; let shoutTimer = 0; - let shoutaudio = createShoutAudio(); - let testimonyAudio = createTestimonyAudio(); + const shoutaudio = createShoutAudio(); + const testimonyAudio = createTestimonyAudio(); let testimonyTimer = 0; let testimonyUpdater: any; let textnow = ""; -- cgit