82 lines
2.1 KiB
TypeScript
82 lines
2.1 KiB
TypeScript
/* Copy to Clipboard */
|
|
export async function copyToClipboard() {
|
|
const toast = useToast()
|
|
|
|
const selection = window.getSelection()
|
|
|
|
const container = document.createElement('div')
|
|
const range = selection?.getRangeAt(0)
|
|
container.appendChild(range.cloneContents())
|
|
|
|
const htmlOutput = container.innerHTML
|
|
const textOutput = selection?.toString()
|
|
|
|
try {
|
|
// Modern Clipboard API requires ClipboardItem
|
|
const clipboardItem = new ClipboardItem({
|
|
'text/html': new Blob([htmlOutput], { type: 'text/html' }),
|
|
'text/plain': new Blob([textOutput], { type: 'text/plain' })
|
|
})
|
|
|
|
await navigator.clipboard.write([clipboardItem])
|
|
|
|
window.getSelection()?.removeAllRanges()
|
|
|
|
toast.add({
|
|
title: 'Texto copiado!',
|
|
description: `${textOutput}`,
|
|
icon: 'ph-clipboard-text',
|
|
color: type == 'activities' ? 'success' : 'info'
|
|
})
|
|
} catch (err) {
|
|
console.error('Failed to copy: ', err)
|
|
}
|
|
}
|
|
|
|
/* Function to copy url with search parameters into clipboard */
|
|
export function copyParagraphToUrl(id: string) {
|
|
console.log('Encoding id', id)
|
|
|
|
const highlights = {
|
|
highlights: [
|
|
{
|
|
id: id,
|
|
color: '#f90'
|
|
}
|
|
]
|
|
}
|
|
|
|
const blob = encodeObjectToBase64Url(highlights)
|
|
|
|
console.log('Encoded highlights', blob)
|
|
|
|
console.log('Decoded highlights object', base64UrlDecode(blob))
|
|
}
|
|
|
|
/* Encode JS object to base64Url compatible string */
|
|
function encodeObjectToBase64Url(obj: object) {
|
|
// 1. Convert object to JSON string
|
|
const jsonString = JSON.stringify(obj)
|
|
|
|
// 2. Base64 encode the JSON string
|
|
const base64 = btoa(jsonString)
|
|
|
|
// 3. Make it URL-safe and remove padding
|
|
return base64
|
|
.replace(/\+/g, '-')
|
|
.replace(/\//g, '_')
|
|
.replace(/=+$/, '')
|
|
}
|
|
|
|
/* Decode base64URL String to json object */
|
|
function base64UrlDecode(base64Url: string) {
|
|
// Replace URL-safe characters and add padding
|
|
let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
|
|
while (base64.length % 4 !== 0) {
|
|
base64 += '='
|
|
}
|
|
return decodeURIComponent(atob(base64).split('').map(function (c) {
|
|
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
|
|
}).join(''))
|
|
}
|