69 lines
1.9 KiB
JavaScript
69 lines
1.9 KiB
JavaScript
/**
|
|
* Writes a text string to the system clipboard.
|
|
*
|
|
* @async
|
|
* @param {string} data text to be written to the clipboard
|
|
* @throws {Error} unable to copy text to clipboard
|
|
*/
|
|
export const copyTextToClipboard = async data => {
|
|
const text =
|
|
typeof data === 'object' && data !== null
|
|
? JSON.stringify(data, null, 2)
|
|
: String(data ?? '');
|
|
|
|
let clipboardError;
|
|
|
|
try {
|
|
if (!navigator.clipboard?.writeText) {
|
|
throw new Error('Clipboard API is unavailable');
|
|
}
|
|
|
|
await navigator.clipboard.writeText(text);
|
|
return;
|
|
} catch (error) {
|
|
clipboardError = error;
|
|
}
|
|
|
|
const textarea = document.createElement('textarea');
|
|
textarea.value = text;
|
|
textarea.setAttribute('readonly', '');
|
|
textarea.style.position = 'fixed';
|
|
textarea.style.opacity = '0';
|
|
textarea.style.pointerEvents = 'none';
|
|
document.body.appendChild(textarea);
|
|
|
|
try {
|
|
textarea.select();
|
|
textarea.setSelectionRange(0, textarea.value.length);
|
|
|
|
if (!document.execCommand?.('copy')) {
|
|
throw new Error('Fallback copy command failed');
|
|
}
|
|
} catch {
|
|
throw new Error(
|
|
`Unable to copy text to clipboard: ${clipboardError.message}`
|
|
);
|
|
} finally {
|
|
textarea.remove();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Handles OTP paste events by extracting numeric digits from clipboard data.
|
|
*
|
|
* @param {ClipboardEvent} event - The paste event from the clipboard
|
|
* @param {number} maxLength - Maximum number of digits to extract (default: 6)
|
|
* @returns {string|null} - Extracted numeric string or null if invalid
|
|
*/
|
|
export const handleOtpPaste = (event, maxLength = 6) => {
|
|
if (!event?.clipboardData) return null;
|
|
|
|
const pastedData = event.clipboardData
|
|
.getData('text')
|
|
.replace(/\D/g, '') // Remove all non-digit characters
|
|
.slice(0, maxLength); // Limit to maxLength digits
|
|
|
|
// Only return if we have the exact expected length
|
|
return pastedData.length === maxLength ? pastedData : null;
|
|
};
|