Skip to content

Commit

Permalink
feat: now html2canvas-pro is dynamically imported only when needed an…
Browse files Browse the repository at this point in the history
…d then cached (#4044)
  • Loading branch information
nickytonline authored Aug 27, 2024
1 parent 423a77c commit 23e4d76
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions lib/utils/copy-to-clipboard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import html2canvas, { Options } from "html2canvas-pro";
import { captureException } from "@sentry/nextjs";
import type { Options } from "html2canvas-pro";
import { shortenUrl } from "./shorten-url";

type Html2CanvasSignature = (element: HTMLElement, options?: Partial<Options>) => Promise<HTMLCanvasElement>;
let html2canvas: Html2CanvasSignature;

export const copyToClipboard = async (content: string) => {
try {
const shortUrl = await shortenUrl(content);
Expand All @@ -25,6 +29,7 @@ export async function copyImageToClipboard(imageUrl: string) {
]);
return true;
} catch (err) {
captureException(new Error("Failed to copy image to clipboard", { cause: err }));
return false;
}
}
Expand All @@ -45,16 +50,25 @@ export async function copyNodeAsImage(node: HTMLElement | null, options?: Partia
await navigator.clipboard.write([
new ClipboardItem({
"image/png": new Promise(async (resolve, reject) => {
html2canvas(node, options).then((canvas) => {
canvas.toBlob((blob) => {
if (!blob) {
reject("Failed to copy image to clipboard");
return;
}

resolve(new Blob([blob], { type: "image/png" }));
}, "image/png");
});
try {
if (!html2canvas) {
html2canvas = (await import("html2canvas-pro")).default;
}

html2canvas(node, options).then((canvas) => {
canvas.toBlob((blob) => {
if (!blob) {
reject("Failed to copy image to clipboard");
return;
}

resolve(new Blob([blob], { type: "image/png" }));
}, "image/png");
});
} catch (err) {
reject("Failed to copy image to clipboard");
captureException(new Error("Failed to copy image to clipboard", { cause: err }));
}
}),
}),
]);
Expand Down

0 comments on commit 23e4d76

Please sign in to comment.