fix clipboard
This commit is contained in:
parent
33c3bd1a2c
commit
cfc724ecce
1 changed files with 40 additions and 4 deletions
|
@ -1,5 +1,4 @@
|
|||
import { $, component$ } from "@builder.io/qwik";
|
||||
import ky from "ky";
|
||||
import { useNanostore$ } from "~/hooks/nanostores";
|
||||
import { api } from "~/lib/api";
|
||||
import { DashboardFiles } from "~/lib/stores";
|
||||
|
@ -35,10 +34,47 @@ export default component$(({ file }: FileProps) => {
|
|||
const addFileToClipboard = $(async (base64: string) => {
|
||||
if (!base64) return;
|
||||
try {
|
||||
const blob = await ky.get(`data:image/png;base64,${base64}`).then(res => res.blob());
|
||||
const item = new ClipboardItem({ "image/png": blob });
|
||||
let mime = "image/png";
|
||||
if (file.ID.endsWith(".png")) mime = "image/png";
|
||||
else if (file.ID.endsWith(".jpg") || file.ID.endsWith(".jpeg")) mime = "image/jpeg";
|
||||
else if (file.ID.endsWith(".gif")) mime = "image/gif";
|
||||
if (!mime.startsWith("image/")) {
|
||||
alert("Clipboard copy is only supported for images in your browser.");
|
||||
return;
|
||||
}
|
||||
|
||||
let pngBlob: Blob;
|
||||
if (mime !== "image/png") {
|
||||
const img = new window.Image();
|
||||
img.src = `data:${mime};base64,${base64}`;
|
||||
await new Promise((res, rej) => {
|
||||
img.onload = res;
|
||||
img.onerror = rej;
|
||||
});
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx?.drawImage(img, 0, 0);
|
||||
pngBlob = await new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob(blob => {
|
||||
if (blob) resolve(blob);
|
||||
else reject(new Error("Failed to convert image to PNG"));
|
||||
}, "image/png");
|
||||
});
|
||||
} else {
|
||||
const binary = atob(base64);
|
||||
const len = binary.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
pngBlob = new Blob([bytes], { type: "image/png" });
|
||||
}
|
||||
|
||||
const item = new ClipboardItem({ "image/png": pngBlob });
|
||||
await navigator.clipboard.write([item]);
|
||||
alert("File copied to clipboard!");
|
||||
alert("Image copied to clipboard as PNG!");
|
||||
} catch (error) {
|
||||
console.error("Failed to copy file to clipboard:", error);
|
||||
alert("Failed to copy file to clipboard.");
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue