Make copy to clipboard an exported utility

This commit is contained in:
Andrew Kingston 2022-02-24 21:48:23 +00:00
parent 0137867f1a
commit 10be256302
4 changed files with 40 additions and 33 deletions

View File

@ -1,42 +1,21 @@
<script> <script>
import Icon from "../Icon/Icon.svelte" import Icon from "../Icon/Icon.svelte"
import { copyToClipboard } from "../helpers"
import { notifications } from "../Stores/notifications" import { notifications } from "../Stores/notifications"
export let value export let value
const onClick = e => { const onClick = async e => {
e.stopPropagation() e.stopPropagation()
copyToClipboard(value) try {
} await copyToClipboard(value)
notifications.success("Copied to clipboard")
const copyToClipboard = value => { } catch (error) {
return new Promise(res => { notifications.error(
if (navigator.clipboard && window.isSecureContext) { "Failed to copy to clipboard. Check the dev console for the value."
// Try using the clipboard API first )
navigator.clipboard.writeText(value).then(res) console.warn("Failed to copy the value", value)
} else { }
// Fall back to the textarea hack
let textArea = document.createElement("textarea")
textArea.value = value
textArea.style.position = "fixed"
textArea.style.left = "-9999px"
textArea.style.top = "-9999px"
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
document.execCommand("copy")
textArea.remove()
res()
}
})
.then(() => {
notifications.success("Copied to clipboard")
})
.catch(() => {
notifications.error(
"Failed to copy to clipboard. Check the dev console for the value."
)
console.warn("Failed to copy the value", value)
})
} }
</script> </script>

View File

@ -1,3 +1,5 @@
import { notifications } from "./Stores/notifications"
/** /**
* Generates a DOM safe UUID. * Generates a DOM safe UUID.
* Starting with a letter is important to make it DOM safe. * Starting with a letter is important to make it DOM safe.
@ -106,3 +108,29 @@ export const deepSet = (obj, key, value) => {
export const cloneDeep = obj => { export const cloneDeep = obj => {
return JSON.parse(JSON.stringify(obj)) return JSON.parse(JSON.stringify(obj))
} }
/**
* Copies a value to the clipboard
* @param value the value to copy
*/
export const copyToClipboard = value => {
return new Promise(res => {
if (navigator.clipboard && window.isSecureContext) {
// Try using the clipboard API first
navigator.clipboard.writeText(value).then(res)
} else {
// Fall back to the textarea hack
let textArea = document.createElement("textarea")
textArea.value = value
textArea.style.position = "fixed"
textArea.style.left = "-9999px"
textArea.style.top = "-9999px"
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
document.execCommand("copy")
textArea.remove()
res()
}
})
}