Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: now html2canvas-pro is dynamically imported only when needed and then cached #4044

Merged
merged 1 commit into from
Aug 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading