From ab0736728aa836b3d64ac5fbd0c09872def875f8 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 17 Jan 2025 22:34:39 -0800 Subject: [PATCH] enh: utils --- src/render/lib/utils/index.ts | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/render/lib/utils/index.ts diff --git a/src/render/lib/utils/index.ts b/src/render/lib/utils/index.ts new file mode 100644 index 0000000..680d87c --- /dev/null +++ b/src/render/lib/utils/index.ts @@ -0,0 +1,43 @@ +export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +export const copyToClipboard = async (text) => { + let result = false; + if (!navigator.clipboard) { + const textArea = document.createElement('textarea'); + textArea.value = text; + + // Avoid scrolling to bottom + textArea.style.top = '0'; + textArea.style.left = '0'; + textArea.style.position = 'fixed'; + + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); + + try { + const successful = document.execCommand('copy'); + const msg = successful ? 'successful' : 'unsuccessful'; + console.log('Fallback: Copying text command was ' + msg); + result = true; + } catch (err) { + console.error('Fallback: Oops, unable to copy', err); + } + + document.body.removeChild(textArea); + return result; + } + + result = await navigator.clipboard + .writeText(text) + .then(() => { + console.log('Async: Copying to clipboard was successful!'); + return true; + }) + .catch((error) => { + console.error('Async: Could not copy text: ', error); + return false; + }); + + return result; +};