From 23e4d761fd0579b4dec098fec09d3e492384e24e Mon Sep 17 00:00:00 2001 From: Nick Taylor Date: Tue, 27 Aug 2024 16:25:15 -0400 Subject: [PATCH] feat: now html2canvas-pro is dynamically imported only when needed and then cached (#4044) --- lib/utils/copy-to-clipboard.ts | 36 +++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/lib/utils/copy-to-clipboard.ts b/lib/utils/copy-to-clipboard.ts index 2ff7d72011..5eab077cf8 100644 --- a/lib/utils/copy-to-clipboard.ts +++ b/lib/utils/copy-to-clipboard.ts @@ -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) => Promise; +let html2canvas: Html2CanvasSignature; + export const copyToClipboard = async (content: string) => { try { const shortUrl = await shortenUrl(content); @@ -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; } } @@ -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 })); + } }), }), ]);