From 59e979087465c59678491d9ef2ea823f8a82bfbe Mon Sep 17 00:00:00 2001 From: Miodec Date: Tue, 21 Mar 2023 14:58:09 +0100 Subject: [PATCH] using await to reduce indentation always opening a new tab if copying to clipboard failed (not just firefox) closes #2815 --- frontend/src/ts/test/test-ui.ts | 60 +++++++++++++++------------------ 1 file changed, 27 insertions(+), 33 deletions(-) diff --git a/frontend/src/ts/test/test-ui.ts b/frontend/src/ts/test/test-ui.ts index e4f791122..0c4b7fc86 100644 --- a/frontend/src/ts/test/test-ui.ts +++ b/frontend/src/ts/test/test-ui.ts @@ -452,49 +452,43 @@ export async function screenshot(): Promise { try { const paddingX = Misc.convertRemToPixels(2); const paddingY = Misc.convertRemToPixels(2); - html2canvas(document.body, { + const canvas = await html2canvas(document.body, { backgroundColor: await ThemeColors.get("bg"), width: sourceWidth + paddingX * 2, height: sourceHeight + paddingY * 2, x: sourceX - paddingX, y: sourceY - paddingY, - }).then((canvas) => { - canvas.toBlob((blob) => { - try { - if (blob === null) return; - if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) { - open(URL.createObjectURL(blob)); - revertScreenshot(); - } else { - navigator.clipboard - .write([ - new ClipboardItem( - Object.defineProperty({}, blob.type, { - value: blob, - enumerable: true, - }) - ), - ]) - .then(() => { - Notifications.add("Copied to clipboard", 1, 2); - revertScreenshot(); - }) - .catch((e) => { - Notifications.add( - Misc.createErrorMessage(e, "Error saving image to clipboard"), - -1 - ); - revertScreenshot(); - }); - } - } catch (e) { + }); + canvas.toBlob(async (blob) => { + try { + if (blob === null) { + throw new Error("Could not create imgage, blob is null"); + } + const clipItem = new ClipboardItem( + Object.defineProperty({}, blob.type, { + value: blob, + enumerable: true, + }) + ); + await navigator.clipboard.write([clipItem]); + Notifications.add("Copied to clipboard", 1, 2); + } catch (e) { + console.error("Error while saving image to clipboard", e); + if (blob) { + Notifications.add( + "Could not save image to clipboard. Opening in new tab instead (make sure popups are allowed)", + 0, + 5 + ); + open(URL.createObjectURL(blob)); + } else { Notifications.add( Misc.createErrorMessage(e, "Error saving image to clipboard"), -1 ); - revertScreenshot(); } - }); + } + revertScreenshot(); }); } catch (e) { Notifications.add(Misc.createErrorMessage(e, "Error creating image"), -1);