cordis/client/webapp/elements/msg-img-res-cont.ts
2021-11-21 20:47:29 -06:00

56 lines
2.7 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 moment from 'moment';
import * as FileType from 'file-type';
import ElementsUtil from './require/elements-util.js';
import { Message, ShouldNeverHappenError } from '../data-types';
import Q from '../q-module';
import createImageOverlay from './overlay-image';
import createImageContextMenu from './context-menu-img';
import CombinedGuild from '../guild-combined';
export default function createImageResourceMessageContinued(document: Document, q: Q, guild: CombinedGuild, message: Message): HTMLElement {
if (!message.resourceId || !message.resourcePreviewId || !message.resourceName) {
throw new ShouldNeverHappenError('Message is not a resource message');
}
let element = q.create({ class: 'message continued', 'meta-id': message.id, 'meta-member-id': message.member.id, 'meta-guild-id': guild.id, content: [
{ class: 'timestamp', content: moment(message.sent).format('HH:mm') },
{ class: 'right', content: [
{ class: 'content image', style: `width: ${message.previewWidth}px; height: ${message.previewHeight}px;`, content:
{ tag: 'img', src: './img/loading.svg', alt: message.resourceName } }, // src will be replaced later
{ class: 'content text', content: ElementsUtil.parseMessageText(message.text ?? '') }
] }
] }) as HTMLElement;
q.$$$(element, '.content.image').addEventListener('click', () => {
document.body.appendChild(createImageOverlay(document, q, guild, message.resourceId as string, message.resourceName as string));
});
(async () => {
try {
let resource = await guild.fetchResource(message.resourcePreviewId as string);
let src = await ElementsUtil.getImageBufferSrc(resource.data);
(q.$$$(element, '.content.image img') as HTMLImageElement).src = src;
let { mime, ext } = (await FileType.fromBuffer(resource.data)) ?? { mime: null, ext: null };
if (mime === null || ext === null) throw new Error('unable to get mime/ext');
q.$$$(element, '.content.image').addEventListener('contextmenu', (e) => {
let contextMenu = createImageContextMenu(document, q, guild, message.resourceName as string, resource.data, mime as string, ext as string, true);
document.body.appendChild(contextMenu);
let relativeTo = { x: e.pageX, y: e.pageY };
ElementsUtil.alignContextElement(contextMenu, relativeTo, { top: 'centerY', left: 'right' });
});
} catch (e) {
LOG.error('error loading preview image', e);
(q.$$$(element, '.content.image img') as HTMLImageElement).src = './img/error.png';
}
})();
return element;
}