47 lines
2.3 KiB
TypeScript
47 lines
2.3 KiB
TypeScript
import * as path from 'path';
|
|
|
|
import * as sharp from 'sharp';
|
|
import * as electron from 'electron'
|
|
|
|
import BaseElements from './require/base-elements';
|
|
import IState from './require/elements-state';
|
|
import ElementsUtil from './require/elements-util';
|
|
|
|
import { $, $$, $$$, $$$$ } from './require/q-module';
|
|
import ClientController from '../client-controller';
|
|
|
|
export default function createImageContextMenu(state: IState, server: ClientController, resourceName: string, buffer: Buffer, mime: string, ext: string, isPreview: boolean): HTMLElement {
|
|
const { document } = state;
|
|
$.setDocument(document);
|
|
|
|
// TODO: try/catch around sharp?
|
|
|
|
let contextMenu = BaseElements.createContextMenu(document, { class: 'image', content: [
|
|
{ class: 'item copy-image', content: 'Copy Image' + (isPreview ? ' Preview' : '') },
|
|
{ class: 'item save-image', content: 'Save Image' + (isPreview ? ' Preview' : '') },
|
|
] });
|
|
$$$(contextMenu, '.copy-image').addEventListener('click', async () => {
|
|
$$$(contextMenu, '.copy-image').innerText = 'Copying...';
|
|
let nativeImage: electron.NativeImage;
|
|
if (mime != 'image/png' && mime != 'image/jpeg' && mime != 'image/jpg') {
|
|
// use sharp to convert to png since nativeImage only supports jpeg/png
|
|
nativeImage = electron.nativeImage.createFromBuffer(await sharp(buffer).png().toBuffer());
|
|
} else {
|
|
nativeImage = electron.nativeImage.createFromBuffer(buffer);
|
|
}
|
|
electron.clipboard.writeImage(nativeImage);
|
|
$$$(contextMenu, '.copy-image').innerText = 'Copied to Clipboard';
|
|
});
|
|
$$$(contextMenu, '.save-image').addEventListener('click', ElementsUtil.createDownloadListener({
|
|
downloadBuff: buffer, server: server,
|
|
resourceName: path.basename(resourceName, '.' + ext) + (isPreview ? '-preview.' : '.') + ext,
|
|
downloadStartFunc: () => {},
|
|
writeStartFunc: () => { $$$(contextMenu, '.save-image').innerText = 'Writing...'; },
|
|
writeFailFunc: () => {
|
|
$$$(contextMenu, '.save-image').innerText = 'Write Failed. Click to Try Again';
|
|
},
|
|
successFunc: () => { $$$(contextMenu, '.save-image').innerText = 'Reveal' + (isPreview ? ' Preview' : '') + ' in Explorer'; }
|
|
}));
|
|
return contextMenu;
|
|
}
|