UNPKG

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