import * as electronRemote from '@electron/remote'; const electronConsole = electronRemote.getGlobal('console') as Console; import Logger from '../../../logger/logger'; const LOG = Logger.create(__filename, electronConsole); import * as fs from 'fs/promises'; import ElementsUtil from './require/elements-util'; import createAddServerOverlay, { IAddServerData } from './overlay-add-server'; import Q from '../q-module'; import UI from '../ui'; import Controller from '../controller'; import createErrorMessageOverlay from './overlay-error-message'; import Actions from '../actions'; export default function bindAddServerEvents(document: Document, q: Q, ui: UI, actions: Actions, controller: Controller): void { let choosingFile = false; q.$('#add-server').addEventListener('click', async () => { if (choosingFile) return; choosingFile = true; let result = await electronRemote.dialog.showOpenDialog({ title: 'Select Server File', defaultPath: '.', // TODO: better path name properties: [ 'openFile' ], filters: [ { name: 'Cordis Server Files', extensions: [ 'cordis' ] } ] }); if (result.canceled) { choosingFile = false; return; } let filePath = result.filePaths[0]; let fileText = (await fs.readFile(filePath)).toString('utf-8'); // TODO: try/catch? let addServerData: any | null = null; try { addServerData = JSON.parse(fileText); if ( typeof addServerData !== 'object' || typeof addServerData?.name !== 'string' || typeof addServerData?.url !== 'string' || typeof addServerData?.cert !== 'string' || typeof addServerData?.token !== 'string' || typeof addServerData?.expires !== 'number' || typeof addServerData?.iconSrc !== 'string' ) { LOG.debug('bad server data:', { addServerData, fileText }) throw new Error('bad server data'); } let overlayElement = createAddServerOverlay(document, q, ui, actions, controller, addServerData as IAddServerData); document.body.appendChild(overlayElement); } catch (e) { LOG.error('Unable to parse server data', e); let errorOverlayElement = createErrorMessageOverlay(document, 'Unable to parse server file', e.message); document.body.appendChild(errorOverlayElement); } choosingFile = false; }); let contextElement = q.create({ class: 'context', content: { class: 'info', content: [ { ns: 'http://www.w3.org/2000/svg', tag: 'svg', width: 10, height: 20, viewBox: '0 0 8 12', content: [ { ns: 'http://www.w3.org/2000/svg', tag: 'path', fill: 'currentColor', //'fill-rule': 'evenodd', 'clip-rule': 'evenodd', d: 'M 0,6 ' + 'L 8,12 ' + 'L 8,0 ' + 'Z' } ] }, { class: 'content', content: 'Add a Server' } ] } }) as HTMLElement; q.$('#add-server').addEventListener('mouseenter', () => { document.body.appendChild(contextElement); ElementsUtil.alignContextElement(contextElement, q.$('#add-server'), { left: 'right', centerY: 'centerY' }) }); q.$('#add-server').addEventListener('mouseleave', () => { if (contextElement.parentElement) { contextElement.parentElement.removeChild(contextElement); } }); }