Skip to content

Commit

Permalink
Merge branch 'develop' into pedrolamas/mpc-calibrate
Browse files Browse the repository at this point in the history
  • Loading branch information
pedrolamas authored Dec 29, 2024
2 parents 272ddfa + efe4771 commit 45cd8e4
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 10 deletions.
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

0 comments on commit 45cd8e4

Please sign in to comment.