clipboard.js
1 const crypto = require('crypto'); 2 const { clipboard } = require('electron'); 3 4 // Extended: Represents the clipboard used for copying and pasting in Atom. 5 // 6 // An instance of this class is always available as the `atom.clipboard` global. 7 // 8 // ## Examples 9 // 10 // ```js 11 // atom.clipboard.write('hello') 12 // 13 // console.log(atom.clipboard.read()) // 'hello' 14 // ``` 15 module.exports = class Clipboard { 16 constructor() { 17 this.reset(); 18 } 19 20 reset() { 21 this.metadata = null; 22 this.signatureForMetadata = null; 23 } 24 25 // Creates an `md5` hash of some text. 26 // 27 // * `text` A {String} to hash. 28 // 29 // Returns a hashed {String}. 30 md5(text) { 31 return crypto 32 .createHash('md5') 33 .update(text, 'utf8') 34 .digest('hex'); 35 } 36 37 // Public: Write the given text to the clipboard. 38 // 39 // The metadata associated with the text is available by calling 40 // {::readWithMetadata}. 41 // 42 // * `text` The {String} to store. 43 // * `metadata` (optional) The additional info to associate with the text. 44 write(text, metadata) { 45 this.signatureForMetadata = this.md5(text); 46 this.metadata = metadata; 47 clipboard.writeText(text); 48 } 49 50 // Public: Read the text from the clipboard. 51 // 52 // Returns a {String}. 53 read() { 54 return clipboard.readText(); 55 } 56 57 // Public: Read the text from the clipboard and return both the text and the 58 // associated metadata. 59 // 60 // Returns an {Object} with the following keys: 61 // * `text` The {String} clipboard text. 62 // * `metadata` The metadata stored by an earlier call to {::write}. 63 readWithMetadata() { 64 const text = this.read(); 65 if (this.signatureForMetadata === this.md5(text)) { 66 return { text, metadata: this.metadata }; 67 } else { 68 return { text }; 69 } 70 } 71 };