cordis/client/webapp/elements/events-add-guild.ts
2021-11-21 20:47:29 -06:00

86 lines
3.1 KiB
TypeScript

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 createAddGuildOverlay, { IAddGuildData } from './overlay-add-guild';
import Q from '../q-module';
import UI from '../ui';
import GuildsManager from '../guilds-manager';
import createErrorMessageOverlay from './overlay-error-message';
export default function bindAddGuildEvents(document: Document, q: Q, ui: UI, guildsManager: GuildsManager): void {
let choosingFile = false;
q.$('#add-guild').addEventListener('click', async () => {
if (choosingFile) return;
choosingFile = true;
let result = await electronRemote.dialog.showOpenDialog({
title: 'Select Guild File',
defaultPath: '.', // TODO: better path name
properties: [ 'openFile' ],
filters: [
{ name: 'Cordis Guild 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 addGuildData: any | null = null;
try {
addGuildData = JSON.parse(fileText);
if (
typeof addGuildData !== 'object' ||
typeof addGuildData?.name !== 'string' ||
typeof addGuildData?.url !== 'string' ||
typeof addGuildData?.cert !== 'string' ||
typeof addGuildData?.token !== 'string' ||
typeof addGuildData?.expires !== 'number' ||
typeof addGuildData?.iconSrc !== 'string'
) {
LOG.debug('bad guild data:', { addGuildData, fileText })
throw new Error('bad guild data');
}
let overlayElement = createAddGuildOverlay(document, q, ui, guildsManager, addGuildData as IAddGuildData);
document.body.appendChild(overlayElement);
} catch (e) {
LOG.error('Unable to parse guild data', e);
let errorOverlayElement = createErrorMessageOverlay(document, 'Unable to parse guild 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 Guild' }
]
} }) as HTMLElement;
q.$('#add-guild').addEventListener('mouseenter', () => {
document.body.appendChild(contextElement);
ElementsUtil.alignContextElement(contextElement, q.$('#add-guild'), { left: 'right', centerY: 'centerY' })
});
q.$('#add-guild').addEventListener('mouseleave', () => {
if (contextElement.parentElement) {
contextElement.parentElement.removeChild(contextElement);
}
});
}