Notes/apps/client/src/menus/image_context_menu.ts

64 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-01-09 18:07:02 +02:00
import { t } from "../services/i18n.js";
import utils from "../services/utils.js";
import contextMenu from "./context_menu.js";
import imageService from "../services/image.js";
const PROP_NAME = "imageContextMenuInstalled";
function setupContextMenu($image: JQuery<HTMLElement>) {
if (!utils.isElectron() || $image.prop(PROP_NAME)) {
return;
}
$image.prop(PROP_NAME, true);
2025-01-09 18:07:02 +02:00
$image.on("contextmenu", (e) => {
e.preventDefault();
contextMenu.show({
x: e.pageX,
y: e.pageY,
items: [
{
title: t("image_context_menu.copy_reference_to_clipboard"),
command: "copyImageReferenceToClipboard",
2024-11-20 10:13:52 +02:00
uiIcon: "bx bx-directions"
},
{
title: t("image_context_menu.copy_image_to_clipboard"),
2024-11-20 10:13:52 +02:00
command: "copyImageToClipboard",
uiIcon: "bx bx-copy"
2025-01-09 18:07:02 +02:00
}
],
2024-09-30 19:43:44 +00:00
selectMenuItemHandler: async ({ command }) => {
2025-01-09 18:07:02 +02:00
if (command === "copyImageReferenceToClipboard") {
imageService.copyImageReferenceToClipboard($image);
2025-01-09 18:07:02 +02:00
} else if (command === "copyImageToClipboard") {
try {
2025-01-09 18:07:02 +02:00
const nativeImage = utils.dynamicRequire("electron").nativeImage;
const clipboard = utils.dynamicRequire("electron").clipboard;
2024-09-30 19:43:44 +00:00
2025-01-09 18:07:02 +02:00
const src = $image.attr("src");
if (!src) {
console.error("Missing src");
return;
}
const response = await fetch(src);
2024-09-30 19:43:44 +00:00
const blob = await response.blob();
2025-01-09 18:07:02 +02:00
clipboard.writeImage(nativeImage.createFromBuffer(Buffer.from(await blob.arrayBuffer())));
} catch (error) {
2025-01-09 18:07:02 +02:00
console.error("Failed to copy image to clipboard:", error);
}
} else {
throw new Error(`Unrecognized command '${command}'`);
}
}
});
});
}
export default {
setupContextMenu
};