search/app/utils/textUtilities.ts

64 lines
1.6 KiB
TypeScript

/* Copy to Clipboard */
export async function copyToClipboard(textToCopy: string, type: string, id: string) {
const toast = useToast()
try {
await navigator.clipboard.writeText(textToCopy)
toast.add({
title: 'Texto copiado!',
description: `${textToCopy}`,
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(''))
}