@sv-use/core
Version:
A collection of Svelte 5 utilities.
77 lines (76 loc) • 2.67 kB
JavaScript
import { onDestroy } from 'svelte';
import { BROWSER } from 'esm-env';
import { getPermission } from '../get-permission/index.svelte.js';
import { handleEventListener } from '../handle-event-listener/index.svelte.js';
import { noop } from '../__internal__/utils.svelte.js';
/**
* Provides write (and optionally read) access to the text clipboard.
* @param options Additional options to customize the behavior.
* @see https://svelte-librarian.github.io/sv-use/docs/core/get-clipboard-text
*/
export function getClipboardText(options = {}) {
const { autoCleanup = true, allowRead = false, copyDuration = 2000, legacyCopy = false } = options;
const _isClipboardAPISupported = $derived.by(() => navigator && 'clipboard' in navigator);
const _isSupported = $derived.by(() => _isClipboardAPISupported || legacyCopy);
const _readPermission = getPermission('clipboard-read', { exposeControls: true });
const _writePermission = getPermission('clipboard-write');
let _isCopied = $state(false);
let _text = $state('');
let cleanup = noop;
if (BROWSER && _isSupported && allowRead) {
cleanup = handleEventListener(['copy', 'cut'], readText);
}
if (autoCleanup) {
onDestroy(() => {
cleanup();
});
}
function copyText(value) {
if (!_isSupported)
return;
if (_isClipboardAPISupported && _writePermission) {
navigator.clipboard.writeText(value).then(() => {
_isCopied = true;
setTimeout(() => {
_isCopied = false;
}, copyDuration);
});
}
else {
legacyCopyText(value);
}
_text = value;
}
async function readText() {
if (!_isClipboardAPISupported)
return;
_text =
_readPermission.isSupported && _readPermission.current !== 'denied'
? await navigator.clipboard.readText()
: legacyReadText();
}
function legacyCopyText(value) {
const textArea = document.createElement('textarea');
textArea.value = value;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
function legacyReadText() {
return document?.getSelection?.()?.toString() ?? '';
}
return {
get isSupported() {
return _isClipboardAPISupported;
},
get isCopied() {
return _isCopied;
},
get text() {
return _text;
},
copyText,
cleanup
};
}