Skip to content
Merged
Show file tree
Hide file tree
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
26 changes: 16 additions & 10 deletions src/components/ui/AppTextFieldWithCopy.vue
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@

<script lang="ts">
import { Component, VModel, Vue } from 'vue-property-decorator'
import clipboardCopy from '@/util/clipboard-copy'
import sleep from '@/util/sleep'

@Component({
inheritAttrs: false
Expand All @@ -47,19 +49,23 @@ export default class AppTextFieldWithCopy extends Vue {
inputValue!: unknown

hasCopied = false
abortController: AbortController | null = null

handleCopy () {
if (
this.inputValue &&
navigator.clipboard
) {
navigator.clipboard.writeText(this.inputValue.toString())
async handleCopy () {
if (this.inputValue) {
if (await clipboardCopy(this.inputValue.toString(), this.$el)) {
this.abortController?.abort()

this.hasCopied = true
this.hasCopied = true

setTimeout(() => {
this.hasCopied = false
}, 2000)
try {
const abortController = this.abortController = new AbortController()

await sleep(2000, abortController.signal)

this.hasCopied = false
} catch {}
}
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions src/scss/misc.scss
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,11 @@ input[type=number] {
.v-application kbd {
background: #4A4A4F !important;
}

textarea.clipboard-copy {
position: absolute;
top: -9999px;
left: -9999px;
z-index: 100000;
opacity: 0;
}
40 changes: 40 additions & 0 deletions src/util/clipboard-copy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import consola from 'consola'

const clipboardCopy = async (text: string, parentElement?: Element): Promise<boolean> => {
if (navigator.clipboard) {
try {
await navigator.clipboard.writeText(text)

return true
} catch (e) {
consola.error('Error while copying text to clipboard', e)

return false
}
}

parentElement ??= document.body

const textarea = document.createElement('textarea')

textarea.value = text
textarea.classList.add('clipboard-copy')

parentElement.appendChild(textarea)

try {
textarea.focus()
textarea.select()
textarea.setSelectionRange(0, 99999)

return document.execCommand('copy')
} catch (e) {
consola.error('Error while copying text to clipboard', e)

return false
} finally {
parentElement.removeChild(textarea)
}
}

export default clipboardCopy
Loading