clipboard.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. /*!
  2. * clipboard.js v1.5.5
  3. * https://zenorocha.github.io/clipboard.js
  4. *
  5. * Licensed MIT © Zeno Rocha
  6. */
  7. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Clipboard = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  8. var matches = require('matches-selector')
  9. module.exports = function (element, selector, checkYoSelf) {
  10. var parent = checkYoSelf ? element : element.parentNode
  11. while (parent && parent !== document) {
  12. if (matches(parent, selector)) return parent;
  13. parent = parent.parentNode
  14. }
  15. }
  16. },{"matches-selector":2}],2:[function(require,module,exports){
  17. /**
  18. * Element prototype.
  19. */
  20. var proto = Element.prototype;
  21. /**
  22. * Vendor function.
  23. */
  24. var vendor = proto.matchesSelector
  25. || proto.webkitMatchesSelector
  26. || proto.mozMatchesSelector
  27. || proto.msMatchesSelector
  28. || proto.oMatchesSelector;
  29. /**
  30. * Expose `match()`.
  31. */
  32. module.exports = match;
  33. /**
  34. * Match `el` to `selector`.
  35. *
  36. * @param {Element} el
  37. * @param {String} selector
  38. * @return {Boolean}
  39. * @api public
  40. */
  41. function match(el, selector) {
  42. if (vendor) return vendor.call(el, selector);
  43. var nodes = el.parentNode.querySelectorAll(selector);
  44. for (var i = 0; i < nodes.length; ++i) {
  45. if (nodes[i] == el) return true;
  46. }
  47. return false;
  48. }
  49. },{}],3:[function(require,module,exports){
  50. var closest = require('closest');
  51. /**
  52. * Delegates event to a selector.
  53. *
  54. * @param {Element} element
  55. * @param {String} selector
  56. * @param {String} type
  57. * @param {Function} callback
  58. * @return {Object}
  59. */
  60. function delegate(element, selector, type, callback) {
  61. var listenerFn = listener.apply(this, arguments);
  62. element.addEventListener(type, listenerFn);
  63. return {
  64. destroy: function() {
  65. element.removeEventListener(type, listenerFn);
  66. }
  67. }
  68. }
  69. /**
  70. * Finds closest match and invokes callback.
  71. *
  72. * @param {Element} element
  73. * @param {String} selector
  74. * @param {String} type
  75. * @param {Function} callback
  76. * @return {Function}
  77. */
  78. function listener(element, selector, type, callback) {
  79. return function(e) {
  80. e.delegateTarget = closest(e.target, selector, true);
  81. if (e.delegateTarget) {
  82. callback.call(element, e);
  83. }
  84. }
  85. }
  86. module.exports = delegate;
  87. },{"closest":1}],4:[function(require,module,exports){
  88. /**
  89. * Check if argument is a HTML element.
  90. *
  91. * @param {Object} value
  92. * @return {Boolean}
  93. */
  94. exports.node = function(value) {
  95. return value !== undefined
  96. && value instanceof HTMLElement
  97. && value.nodeType === 1;
  98. };
  99. /**
  100. * Check if argument is a list of HTML elements.
  101. *
  102. * @param {Object} value
  103. * @return {Boolean}
  104. */
  105. exports.nodeList = function(value) {
  106. var type = Object.prototype.toString.call(value);
  107. return value !== undefined
  108. && (type === '[object NodeList]' || type === '[object HTMLCollection]')
  109. && ('length' in value)
  110. && (value.length === 0 || exports.node(value[0]));
  111. };
  112. /**
  113. * Check if argument is a string.
  114. *
  115. * @param {Object} value
  116. * @return {Boolean}
  117. */
  118. exports.string = function(value) {
  119. return typeof value === 'string'
  120. || value instanceof String;
  121. };
  122. /**
  123. * Check if argument is a function.
  124. *
  125. * @param {Object} value
  126. * @return {Boolean}
  127. */
  128. exports.function = function(value) {
  129. var type = Object.prototype.toString.call(value);
  130. return type === '[object Function]';
  131. };
  132. },{}],5:[function(require,module,exports){
  133. var is = require('./is');
  134. var delegate = require('delegate');
  135. /**
  136. * Validates all params and calls the right
  137. * listener function based on its target type.
  138. *
  139. * @param {String|HTMLElement|HTMLCollection|NodeList} target
  140. * @param {String} type
  141. * @param {Function} callback
  142. * @return {Object}
  143. */
  144. function listen(target, type, callback) {
  145. if (!target && !type && !callback) {
  146. throw new Error('Missing required arguments');
  147. }
  148. if (!is.string(type)) {
  149. throw new TypeError('Second argument must be a String');
  150. }
  151. if (!is.function(callback)) {
  152. throw new TypeError('Third argument must be a Function');
  153. }
  154. if (is.node(target)) {
  155. return listenNode(target, type, callback);
  156. }
  157. else if (is.nodeList(target)) {
  158. return listenNodeList(target, type, callback);
  159. }
  160. else if (is.string(target)) {
  161. return listenSelector(target, type, callback);
  162. }
  163. else {
  164. throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');
  165. }
  166. }
  167. /**
  168. * Adds an event listener to a HTML element
  169. * and returns a remove listener function.
  170. *
  171. * @param {HTMLElement} node
  172. * @param {String} type
  173. * @param {Function} callback
  174. * @return {Object}
  175. */
  176. function listenNode(node, type, callback) {
  177. node.addEventListener(type, callback);
  178. return {
  179. destroy: function() {
  180. node.removeEventListener(type, callback);
  181. }
  182. }
  183. }
  184. /**
  185. * Add an event listener to a list of HTML elements
  186. * and returns a remove listener function.
  187. *
  188. * @param {NodeList|HTMLCollection} nodeList
  189. * @param {String} type
  190. * @param {Function} callback
  191. * @return {Object}
  192. */
  193. function listenNodeList(nodeList, type, callback) {
  194. Array.prototype.forEach.call(nodeList, function(node) {
  195. node.addEventListener(type, callback);
  196. });
  197. return {
  198. destroy: function() {
  199. Array.prototype.forEach.call(nodeList, function(node) {
  200. node.removeEventListener(type, callback);
  201. });
  202. }
  203. }
  204. }
  205. /**
  206. * Add an event listener to a selector
  207. * and returns a remove listener function.
  208. *
  209. * @param {String} selector
  210. * @param {String} type
  211. * @param {Function} callback
  212. * @return {Object}
  213. */
  214. function listenSelector(selector, type, callback) {
  215. return delegate(document.body, selector, type, callback);
  216. }
  217. module.exports = listen;
  218. },{"./is":4,"delegate":3}],6:[function(require,module,exports){
  219. function select(element) {
  220. var selectedText;
  221. if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
  222. element.focus();
  223. element.setSelectionRange(0, element.value.length);
  224. selectedText = element.value;
  225. }
  226. else {
  227. if (element.hasAttribute('contenteditable')) {
  228. element.focus();
  229. }
  230. var selection = window.getSelection();
  231. var range = document.createRange();
  232. range.selectNodeContents(element);
  233. selection.removeAllRanges();
  234. selection.addRange(range);
  235. selectedText = selection.toString();
  236. }
  237. return selectedText;
  238. }
  239. module.exports = select;
  240. },{}],7:[function(require,module,exports){
  241. function E () {
  242. // Keep this empty so it's easier to inherit from
  243. // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
  244. }
  245. E.prototype = {
  246. on: function (name, callback, ctx) {
  247. var e = this.e || (this.e = {});
  248. (e[name] || (e[name] = [])).push({
  249. fn: callback,
  250. ctx: ctx
  251. });
  252. return this;
  253. },
  254. once: function (name, callback, ctx) {
  255. var self = this;
  256. function listener () {
  257. self.off(name, listener);
  258. callback.apply(ctx, arguments);
  259. };
  260. listener._ = callback
  261. return this.on(name, listener, ctx);
  262. },
  263. emit: function (name) {
  264. var data = [].slice.call(arguments, 1);
  265. var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
  266. var i = 0;
  267. var len = evtArr.length;
  268. for (i; i < len; i++) {
  269. evtArr[i].fn.apply(evtArr[i].ctx, data);
  270. }
  271. return this;
  272. },
  273. off: function (name, callback) {
  274. var e = this.e || (this.e = {});
  275. var evts = e[name];
  276. var liveEvents = [];
  277. if (evts && callback) {
  278. for (var i = 0, len = evts.length; i < len; i++) {
  279. if (evts[i].fn !== callback && evts[i].fn._ !== callback)
  280. liveEvents.push(evts[i]);
  281. }
  282. }
  283. // Remove event from queue to prevent memory leak
  284. // Suggested by https://github.com/lazd
  285. // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
  286. (liveEvents.length)
  287. ? e[name] = liveEvents
  288. : delete e[name];
  289. return this;
  290. }
  291. };
  292. module.exports = E;
  293. },{}],8:[function(require,module,exports){
  294. 'use strict';
  295. exports.__esModule = true;
  296. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  297. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  298. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  299. var _select = require('select');
  300. var _select2 = _interopRequireDefault(_select);
  301. /**
  302. * Inner class which performs selection from either `text` or `target`
  303. * properties and then executes copy or cut operations.
  304. */
  305. var ClipboardAction = (function () {
  306. /**
  307. * @param {Object} options
  308. */
  309. function ClipboardAction(options) {
  310. _classCallCheck(this, ClipboardAction);
  311. this.resolveOptions(options);
  312. this.initSelection();
  313. }
  314. /**
  315. * Defines base properties passed from constructor.
  316. * @param {Object} options
  317. */
  318. ClipboardAction.prototype.resolveOptions = function resolveOptions() {
  319. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  320. this.action = options.action;
  321. this.emitter = options.emitter;
  322. this.target = options.target;
  323. this.text = options.text;
  324. this.trigger = options.trigger;
  325. this.selectedText = '';
  326. };
  327. /**
  328. * Decides which selection strategy is going to be applied based
  329. * on the existence of `text` and `target` properties.
  330. */
  331. ClipboardAction.prototype.initSelection = function initSelection() {
  332. if (this.text && this.target) {
  333. throw new Error('Multiple attributes declared, use either "target" or "text"');
  334. } else if (this.text) {
  335. this.selectFake();
  336. } else if (this.target) {
  337. this.selectTarget();
  338. } else {
  339. throw new Error('Missing required attributes, use either "target" or "text"');
  340. }
  341. };
  342. /**
  343. * Creates a fake textarea element, sets its value from `text` property,
  344. * and makes a selection on it.
  345. */
  346. ClipboardAction.prototype.selectFake = function selectFake() {
  347. var _this = this;
  348. this.removeFake();
  349. this.fakeHandler = document.body.addEventListener('click', function () {
  350. return _this.removeFake();
  351. });
  352. this.fakeElem = document.createElement('textarea');
  353. this.fakeElem.style.position = 'absolute';
  354. this.fakeElem.style.left = '-9999px';
  355. this.fakeElem.style.top = (window.pageYOffset || document.documentElement.scrollTop) + 'px';
  356. this.fakeElem.setAttribute('readonly', '');
  357. this.fakeElem.value = this.text;
  358. document.body.appendChild(this.fakeElem);
  359. this.selectedText = _select2['default'](this.fakeElem);
  360. this.copyText();
  361. };
  362. /**
  363. * Only removes the fake element after another click event, that way
  364. * a user can hit `Ctrl+C` to copy because selection still exists.
  365. */
  366. ClipboardAction.prototype.removeFake = function removeFake() {
  367. if (this.fakeHandler) {
  368. document.body.removeEventListener('click');
  369. this.fakeHandler = null;
  370. }
  371. if (this.fakeElem) {
  372. document.body.removeChild(this.fakeElem);
  373. this.fakeElem = null;
  374. }
  375. };
  376. /**
  377. * Selects the content from element passed on `target` property.
  378. */
  379. ClipboardAction.prototype.selectTarget = function selectTarget() {
  380. this.selectedText = _select2['default'](this.target);
  381. this.copyText();
  382. };
  383. /**
  384. * Executes the copy operation based on the current selection.
  385. */
  386. ClipboardAction.prototype.copyText = function copyText() {
  387. var succeeded = undefined;
  388. try {
  389. succeeded = document.execCommand(this.action);
  390. } catch (err) {
  391. succeeded = false;
  392. }
  393. this.handleResult(succeeded);
  394. };
  395. /**
  396. * Fires an event based on the copy operation result.
  397. * @param {Boolean} succeeded
  398. */
  399. ClipboardAction.prototype.handleResult = function handleResult(succeeded) {
  400. if (succeeded) {
  401. this.emitter.emit('success', {
  402. action: this.action,
  403. text: this.selectedText,
  404. trigger: this.trigger,
  405. clearSelection: this.clearSelection.bind(this)
  406. });
  407. } else {
  408. this.emitter.emit('error', {
  409. action: this.action,
  410. trigger: this.trigger,
  411. clearSelection: this.clearSelection.bind(this)
  412. });
  413. }
  414. };
  415. /**
  416. * Removes current selection and focus from `target` element.
  417. */
  418. ClipboardAction.prototype.clearSelection = function clearSelection() {
  419. if (this.target) {
  420. this.target.blur();
  421. }
  422. window.getSelection().removeAllRanges();
  423. };
  424. /**
  425. * Sets the `action` to be performed which can be either 'copy' or 'cut'.
  426. * @param {String} action
  427. */
  428. /**
  429. * Destroy lifecycle.
  430. */
  431. ClipboardAction.prototype.destroy = function destroy() {
  432. this.removeFake();
  433. };
  434. _createClass(ClipboardAction, [{
  435. key: 'action',
  436. set: function set() {
  437. var action = arguments.length <= 0 || arguments[0] === undefined ? 'copy' : arguments[0];
  438. this._action = action;
  439. if (this._action !== 'copy' && this._action !== 'cut') {
  440. throw new Error('Invalid "action" value, use either "copy" or "cut"');
  441. }
  442. },
  443. /**
  444. * Gets the `action` property.
  445. * @return {String}
  446. */
  447. get: function get() {
  448. return this._action;
  449. }
  450. /**
  451. * Sets the `target` property using an element
  452. * that will be have its content copied.
  453. * @param {Element} target
  454. */
  455. }, {
  456. key: 'target',
  457. set: function set(target) {
  458. if (target !== undefined) {
  459. if (target && typeof target === 'object' && target.nodeType === 1) {
  460. this._target = target;
  461. } else {
  462. throw new Error('Invalid "target" value, use a valid Element');
  463. }
  464. }
  465. },
  466. /**
  467. * Gets the `target` property.
  468. * @return {String|HTMLElement}
  469. */
  470. get: function get() {
  471. return this._target;
  472. }
  473. }]);
  474. return ClipboardAction;
  475. })();
  476. exports['default'] = ClipboardAction;
  477. module.exports = exports['default'];
  478. },{"select":6}],9:[function(require,module,exports){
  479. 'use strict';
  480. exports.__esModule = true;
  481. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  482. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  483. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  484. var _clipboardAction = require('./clipboard-action');
  485. var _clipboardAction2 = _interopRequireDefault(_clipboardAction);
  486. var _tinyEmitter = require('tiny-emitter');
  487. var _tinyEmitter2 = _interopRequireDefault(_tinyEmitter);
  488. var _goodListener = require('good-listener');
  489. var _goodListener2 = _interopRequireDefault(_goodListener);
  490. /**
  491. * Base class which takes one or more elements, adds event listeners to them,
  492. * and instantiates a new `ClipboardAction` on each click.
  493. */
  494. var Clipboard = (function (_Emitter) {
  495. _inherits(Clipboard, _Emitter);
  496. /**
  497. * @param {String|HTMLElement|HTMLCollection|NodeList} trigger
  498. * @param {Object} options
  499. */
  500. function Clipboard(trigger, options) {
  501. _classCallCheck(this, Clipboard);
  502. _Emitter.call(this);
  503. this.resolveOptions(options);
  504. this.listenClick(trigger);
  505. }
  506. /**
  507. * Helper function to retrieve attribute value.
  508. * @param {String} suffix
  509. * @param {Element} element
  510. */
  511. /**
  512. * Defines if attributes would be resolved using internal setter functions
  513. * or custom functions that were passed in the constructor.
  514. * @param {Object} options
  515. */
  516. Clipboard.prototype.resolveOptions = function resolveOptions() {
  517. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  518. this.action = typeof options.action === 'function' ? options.action : this.defaultAction;
  519. this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;
  520. this.text = typeof options.text === 'function' ? options.text : this.defaultText;
  521. };
  522. /**
  523. * Adds a click event listener to the passed trigger.
  524. * @param {String|HTMLElement|HTMLCollection|NodeList} trigger
  525. */
  526. Clipboard.prototype.listenClick = function listenClick(trigger) {
  527. var _this = this;
  528. this.listener = _goodListener2['default'](trigger, 'click', function (e) {
  529. return _this.onClick(e);
  530. });
  531. };
  532. /**
  533. * Defines a new `ClipboardAction` on each click event.
  534. * @param {Event} e
  535. */
  536. Clipboard.prototype.onClick = function onClick(e) {
  537. var trigger = e.delegateTarget || e.currentTarget;
  538. if (this.clipboardAction) {
  539. this.clipboardAction = null;
  540. }
  541. this.clipboardAction = new _clipboardAction2['default']({
  542. action: this.action(trigger),
  543. target: this.target(trigger),
  544. text: this.text(trigger),
  545. trigger: trigger,
  546. emitter: this
  547. });
  548. };
  549. /**
  550. * Default `action` lookup function.
  551. * @param {Element} trigger
  552. */
  553. Clipboard.prototype.defaultAction = function defaultAction(trigger) {
  554. return getAttributeValue('action', trigger);
  555. };
  556. /**
  557. * Default `target` lookup function.
  558. * @param {Element} trigger
  559. */
  560. Clipboard.prototype.defaultTarget = function defaultTarget(trigger) {
  561. var selector = getAttributeValue('target', trigger);
  562. if (selector) {
  563. return document.querySelector(selector);
  564. }
  565. };
  566. /**
  567. * Default `text` lookup function.
  568. * @param {Element} trigger
  569. */
  570. Clipboard.prototype.defaultText = function defaultText(trigger) {
  571. return getAttributeValue('text', trigger);
  572. };
  573. /**
  574. * Destroy lifecycle.
  575. */
  576. Clipboard.prototype.destroy = function destroy() {
  577. this.listener.destroy();
  578. if (this.clipboardAction) {
  579. this.clipboardAction.destroy();
  580. this.clipboardAction = null;
  581. }
  582. };
  583. return Clipboard;
  584. })(_tinyEmitter2['default']);
  585. function getAttributeValue(suffix, element) {
  586. var attribute = 'data-clipboard-' + suffix;
  587. if (!element.hasAttribute(attribute)) {
  588. return;
  589. }
  590. return element.getAttribute(attribute);
  591. }
  592. exports['default'] = Clipboard;
  593. module.exports = exports['default'];
  594. },{"./clipboard-action":8,"good-listener":5,"tiny-emitter":7}]},{},[9])(9)
  595. });