]> BookStack Code Mirror - bookstack/blob - resources/js/services/clipboard.js
Editors: Properly aligned edit area border radius
[bookstack] / resources / js / services / clipboard.js
1 export class Clipboard {
2
3     /**
4      * Constructor
5      * @param {DataTransfer} clipboardData
6      */
7     constructor(clipboardData) {
8         this.data = clipboardData;
9     }
10
11     /**
12      * Check if the clipboard has any items.
13      */
14     hasItems() {
15         return Boolean(this.data) && Boolean(this.data.types) && this.data.types.length > 0;
16     }
17
18     /**
19      * Check if the given event has tabular-looking data in the clipboard.
20      * @return {boolean}
21      */
22     containsTabularData() {
23         const rtfData = this.data.getData('text/rtf');
24         return rtfData && rtfData.includes('\\trowd');
25     }
26
27     /**
28      * Get the images that are in the clipboard data.
29      * @return {Array<File>}
30      */
31     getImages() {
32         const {types} = this.data;
33         const images = [];
34
35         for (const type of types) {
36             if (type.includes('image')) {
37                 const item = this.data.getData(type);
38                 images.push(item.getAsFile());
39             }
40         }
41
42         const imageFiles = this.getFiles().filter(f => f.type.includes('image'));
43         images.push(...imageFiles);
44
45         return images;
46     }
47
48     /**
49      * Get the files included in the clipboard data.
50      * @return {File[]}
51      */
52     getFiles() {
53         const {files} = this.data;
54         return [...files];
55     }
56
57 }
58
59 export async function copyTextToClipboard(text) {
60     if (window.isSecureContext && navigator.clipboard) {
61         await navigator.clipboard.writeText(text);
62         return;
63     }
64
65     // Backup option where we can't use the navigator.clipboard API
66     const tempInput = document.createElement('textarea');
67     tempInput.style = 'position: absolute; left: -1000px; top: -1000px;';
68     tempInput.value = text;
69     document.body.appendChild(tempInput);
70     tempInput.select();
71     document.execCommand('copy');
72     document.body.removeChild(tempInput);
73 }