blob: fae189f5d7e1b21ab8fe6d6c4252e34f47869c10 [file] [log] [blame]
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-icons/iron-icons.html">
<link rel="import" href="chops-button.html">
<dom-module id="chops-copy-to-clipboard">
<template>
<chops-button id="button" title$="copy '[[content]]' to the clipboard" on-click="_copyToClipboard">
<iron-icon icon="[[icon]]"></iron-icon>
</chops-button>
<textarea hidden id="contentDiv">[[content]]</textarea>
</template>
<script>
'use strict';
/**
* `<chops-copy-to-clipboard>`
*
* ChopsCopyToClipboard adds a button to copy some data to the clipboard.
*
* @customElement
* @polymer
* @demo /demo/chops-copy-to-clipboard_demo.html
*/
class ChopsCopyToClipboard extends Polymer.Element {
static get is() { return 'chops-copy-to-clipboard'; }
static get properties() {
return {
content: {
type: String,
value: '',
},
icon: {
type: String,
value: 'content-copy'
}
}
}
_copyToClipboard() {
// First, preserve any existing selection the user has made.
const ranges = [];
const sel = window.getSelection();
for (let i = 0; i < sel.rangeCount; i++) {
ranges.push(sel.getRangeAt(0));
}
// Copy data to the clipboard.
// TODO(seanmccullough): Look for a less hacky way to do this.
// It doesn't cause any visual flickering, just based on manual
// testing though. The Clipboard API is cleaner but requires
// prompting the user for special permissions.
this.$.contentDiv.hidden = false;
this.$.contentDiv.select();
document.execCommand('copy');
this.$.contentDiv.hidden = true;
// Restore any existing selection the user has made.
sel.removeAllRanges();
ranges.forEach((range) => {
sel.addRange(range);
});
}
}
customElements.define(ChopsCopyToClipboard.is, ChopsCopyToClipboard);
</script>
<dom-module>