]> BookStack Code Mirror - bookstack/blob - resources/js/services/clipboard.ts
JS: Converted a few extra services to TS
[bookstack] / resources / js / services / clipboard.ts
1 export class Clipboard {
2
3     protected data: DataTransfer;
4
5     constructor(clipboardData: DataTransfer) {
6         this.data = clipboardData;
7     }
8
9     /**
10      * Check if the clipboard has any items.
11      */
12     hasItems(): boolean {
13         return Boolean(this.data) && Boolean(this.data.types) && this.data.types.length > 0;
14     }
15
16     /**
17      * Check if the given event has tabular-looking data in the clipboard.
18      */
19     containsTabularData(): boolean {
20         const rtfData = this.data.getData('text/rtf');
21         return !!rtfData && rtfData.includes('\\trowd');
22     }
23
24     /**
25      * Get the images that are in the clipboard data.
26      */
27     getImages(): File[] {
28         return this.getFiles().filter(f => f.type.includes('image'));
29     }
30
31     /**
32      * Get the files included in the clipboard data.
33      */
34     getFiles(): File[] {
35         const {files} = this.data;
36         return [...files];
37     }
38 }
39
40 export async function copyTextToClipboard(text: string) {
41     if (window.isSecureContext && navigator.clipboard) {
42         await navigator.clipboard.writeText(text);
43         return;
44     }
45
46     // Backup option where we can't use the navigator.clipboard API
47     const tempInput = document.createElement('textarea');
48     tempInput.setAttribute('style', 'position: absolute; left: -1000px; top: -1000px;');
49     tempInput.value = text;
50     document.body.appendChild(tempInput);
51     tempInput.select();
52     document.execCommand('copy');
53     document.body.removeChild(tempInput);
54 }