clipboard.mjs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import { DOCUMENT } from '@angular/common';
  2. import * as i0 from '@angular/core';
  3. import { inject, Injectable, InjectionToken, NgZone, EventEmitter, Directive, Input, Output, NgModule } from '@angular/core';
  4. /**
  5. * A pending copy-to-clipboard operation.
  6. *
  7. * The implementation of copying text to the clipboard modifies the DOM and
  8. * forces a re-layout. This re-layout can take too long if the string is large,
  9. * causing the execCommand('copy') to happen too long after the user clicked.
  10. * This results in the browser refusing to copy. This object lets the
  11. * re-layout happen in a separate tick from copying by providing a copy function
  12. * that can be called later.
  13. *
  14. * Destroy must be called when no longer in use, regardless of whether `copy` is
  15. * called.
  16. */
  17. class PendingCopy {
  18. _document;
  19. _textarea;
  20. constructor(text, _document) {
  21. this._document = _document;
  22. const textarea = (this._textarea = this._document.createElement('textarea'));
  23. const styles = textarea.style;
  24. // Hide the element for display and accessibility. Set a fixed position so the page layout
  25. // isn't affected. We use `fixed` with `top: 0`, because focus is moved into the textarea
  26. // for a split second and if it's off-screen, some browsers will attempt to scroll it into view.
  27. styles.position = 'fixed';
  28. styles.top = styles.opacity = '0';
  29. styles.left = '-999em';
  30. textarea.setAttribute('aria-hidden', 'true');
  31. textarea.value = text;
  32. // Making the textarea `readonly` prevents the screen from jumping on iOS Safari (see #25169).
  33. textarea.readOnly = true;
  34. // The element needs to be inserted into the fullscreen container, if the page
  35. // is in fullscreen mode, otherwise the browser won't execute the copy command.
  36. (this._document.fullscreenElement || this._document.body).appendChild(textarea);
  37. }
  38. /** Finishes copying the text. */
  39. copy() {
  40. const textarea = this._textarea;
  41. let successful = false;
  42. try {
  43. // Older browsers could throw if copy is not supported.
  44. if (textarea) {
  45. const currentFocus = this._document.activeElement;
  46. textarea.select();
  47. textarea.setSelectionRange(0, textarea.value.length);
  48. successful = this._document.execCommand('copy');
  49. if (currentFocus) {
  50. currentFocus.focus();
  51. }
  52. }
  53. }
  54. catch {
  55. // Discard error.
  56. // Initial setting of {@code successful} will represent failure here.
  57. }
  58. return successful;
  59. }
  60. /** Cleans up DOM changes used to perform the copy operation. */
  61. destroy() {
  62. const textarea = this._textarea;
  63. if (textarea) {
  64. textarea.remove();
  65. this._textarea = undefined;
  66. }
  67. }
  68. }
  69. /**
  70. * A service for copying text to the clipboard.
  71. */
  72. class Clipboard {
  73. _document = inject(DOCUMENT);
  74. constructor() { }
  75. /**
  76. * Copies the provided text into the user's clipboard.
  77. *
  78. * @param text The string to copy.
  79. * @returns Whether the operation was successful.
  80. */
  81. copy(text) {
  82. const pendingCopy = this.beginCopy(text);
  83. const successful = pendingCopy.copy();
  84. pendingCopy.destroy();
  85. return successful;
  86. }
  87. /**
  88. * Prepares a string to be copied later. This is useful for large strings
  89. * which take too long to successfully render and be copied in the same tick.
  90. *
  91. * The caller must call `destroy` on the returned `PendingCopy`.
  92. *
  93. * @param text The string to copy.
  94. * @returns the pending copy operation.
  95. */
  96. beginCopy(text) {
  97. return new PendingCopy(text, this._document);
  98. }
  99. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: Clipboard, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
  100. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: Clipboard, providedIn: 'root' });
  101. }
  102. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: Clipboard, decorators: [{
  103. type: Injectable,
  104. args: [{ providedIn: 'root' }]
  105. }], ctorParameters: () => [] });
  106. /** Injection token that can be used to provide the default options to `CdkCopyToClipboard`. */
  107. const CDK_COPY_TO_CLIPBOARD_CONFIG = new InjectionToken('CDK_COPY_TO_CLIPBOARD_CONFIG');
  108. /**
  109. * Provides behavior for a button that when clicked copies content into user's
  110. * clipboard.
  111. */
  112. class CdkCopyToClipboard {
  113. _clipboard = inject(Clipboard);
  114. _ngZone = inject(NgZone);
  115. /** Content to be copied. */
  116. text = '';
  117. /**
  118. * How many times to attempt to copy the text. This may be necessary for longer text, because
  119. * the browser needs time to fill an intermediate textarea element and copy the content.
  120. */
  121. attempts = 1;
  122. /**
  123. * Emits when some text is copied to the clipboard. The
  124. * emitted value indicates whether copying was successful.
  125. */
  126. copied = new EventEmitter();
  127. /** Copies that are currently being attempted. */
  128. _pending = new Set();
  129. /** Whether the directive has been destroyed. */
  130. _destroyed;
  131. /** Timeout for the current copy attempt. */
  132. _currentTimeout;
  133. constructor() {
  134. const config = inject(CDK_COPY_TO_CLIPBOARD_CONFIG, { optional: true });
  135. if (config && config.attempts != null) {
  136. this.attempts = config.attempts;
  137. }
  138. }
  139. /** Copies the current text to the clipboard. */
  140. copy(attempts = this.attempts) {
  141. if (attempts > 1) {
  142. let remainingAttempts = attempts;
  143. const pending = this._clipboard.beginCopy(this.text);
  144. this._pending.add(pending);
  145. const attempt = () => {
  146. const successful = pending.copy();
  147. if (!successful && --remainingAttempts && !this._destroyed) {
  148. // We use 1 for the timeout since it's more predictable when flushing in unit tests.
  149. this._currentTimeout = this._ngZone.runOutsideAngular(() => setTimeout(attempt, 1));
  150. }
  151. else {
  152. this._currentTimeout = null;
  153. this._pending.delete(pending);
  154. pending.destroy();
  155. this.copied.emit(successful);
  156. }
  157. };
  158. attempt();
  159. }
  160. else {
  161. this.copied.emit(this._clipboard.copy(this.text));
  162. }
  163. }
  164. ngOnDestroy() {
  165. if (this._currentTimeout) {
  166. clearTimeout(this._currentTimeout);
  167. }
  168. this._pending.forEach(copy => copy.destroy());
  169. this._pending.clear();
  170. this._destroyed = true;
  171. }
  172. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: CdkCopyToClipboard, deps: [], target: i0.ɵɵFactoryTarget.Directive });
  173. static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.6", type: CdkCopyToClipboard, isStandalone: true, selector: "[cdkCopyToClipboard]", inputs: { text: ["cdkCopyToClipboard", "text"], attempts: ["cdkCopyToClipboardAttempts", "attempts"] }, outputs: { copied: "cdkCopyToClipboardCopied" }, host: { listeners: { "click": "copy()" } }, ngImport: i0 });
  174. }
  175. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: CdkCopyToClipboard, decorators: [{
  176. type: Directive,
  177. args: [{
  178. selector: '[cdkCopyToClipboard]',
  179. host: {
  180. '(click)': 'copy()',
  181. },
  182. }]
  183. }], ctorParameters: () => [], propDecorators: { text: [{
  184. type: Input,
  185. args: ['cdkCopyToClipboard']
  186. }], attempts: [{
  187. type: Input,
  188. args: ['cdkCopyToClipboardAttempts']
  189. }], copied: [{
  190. type: Output,
  191. args: ['cdkCopyToClipboardCopied']
  192. }] } });
  193. class ClipboardModule {
  194. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: ClipboardModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
  195. static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.6", ngImport: i0, type: ClipboardModule, imports: [CdkCopyToClipboard], exports: [CdkCopyToClipboard] });
  196. static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: ClipboardModule });
  197. }
  198. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: ClipboardModule, decorators: [{
  199. type: NgModule,
  200. args: [{
  201. imports: [CdkCopyToClipboard],
  202. exports: [CdkCopyToClipboard],
  203. }]
  204. }] });
  205. export { CDK_COPY_TO_CLIPBOARD_CONFIG, CdkCopyToClipboard, Clipboard, ClipboardModule, PendingCopy };
  206. //# sourceMappingURL=clipboard.mjs.map