Added base64 encoding / decoding code

This commit is contained in:
Julio Ruiz 2026-05-24 06:04:50 -05:00
parent b12c31099c
commit f963c48e75
1 changed files with 49 additions and 2 deletions

View File

@ -1,5 +1,5 @@
/* Copy to Clipboard */
export async function copyToClipboard(textToCopy: string, type: string) {
export async function copyToClipboard(textToCopy: string, type: string, id: string) {
const toast = useToast()
try {
@ -13,4 +13,51 @@ export async function copyToClipboard(textToCopy: string, type: string) {
} 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(''))
}