Skip to content

feat(material-experimental): add Clipboard service and directive. #16704

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/cdk-experimental/clipboard/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package(default_visibility = ["//visibility:public"])

load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite")

ng_module(
name = "clipboard",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = glob(["**/*.html"]),
module_name = "@angular/cdk-experimental/clipboard",
deps = [
"@npm//@angular/common",
"@npm//@angular/core",
"@npm//rxjs",
],
)

ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":clipboard",
"//src/cdk/testing",
"@npm//@angular/common",
"@npm//@angular/platform-browser",
],
)

ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
20 changes: 20 additions & 0 deletions src/cdk-experimental/clipboard/clipboard-module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';

import {CdkCopyToClipboard} from './copy-to-clipboard';

@NgModule({
declarations: [CdkCopyToClipboard],
imports: [CommonModule],
exports: [CdkCopyToClipboard],
})
export class ClipboardModule {
}
88 changes: 88 additions & 0 deletions src/cdk-experimental/clipboard/clipboard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import {DOCUMENT} from '@angular/common';
import {TestBed} from '@angular/core/testing';

import {Clipboard, PendingCopy} from './clipboard';

const COPY_CONTENT = 'copy content';

describe('Clipboard', () => {
let clipboard: Clipboard;

let execCommand: jasmine.Spy;
let document: Document;
let body: HTMLElement;
let focusedInput: HTMLElement;

beforeEach(() => {
TestBed.configureTestingModule({});

clipboard = TestBed.get(Clipboard);
document = TestBed.get(DOCUMENT);
execCommand = spyOn(document, 'execCommand').and.returnValue(true);
body = document.body;

focusedInput = document.createElement('input');
body.appendChild(focusedInput);
focusedInput.focus();
});

afterEach(() => {
focusedInput.remove();
});

describe('#beginCopy', () => {
let pendingCopy: PendingCopy;

beforeEach(() => {
pendingCopy = clipboard.beginCopy(COPY_CONTENT);
});

afterEach(() => {
pendingCopy.destroy();
});

it('loads the copy content in textarea', () => {
expect(body.querySelector('textarea')!.value).toBe(COPY_CONTENT);
});

it('removes the textarea after destroy()', () => {
pendingCopy.destroy();

expect(body.querySelector('textarea')).toBeNull();
});
});

describe('#copy', () => {
it('returns true when execCommand succeeds', () => {
expect(clipboard.copy(COPY_CONTENT)).toBe(true);

expect(body.querySelector('textarea')).toBeNull();
});

it('does not move focus away from focused element', () => {
expect(clipboard.copy(COPY_CONTENT)).toBe(true);

expect(document.activeElement).toBe(focusedInput);
});

describe('when execCommand fails', () => {
beforeEach(() => {
execCommand.and.throwError('could not copy');
});

it('returns false', () => {
expect(clipboard.copy(COPY_CONTENT)).toBe(false);
});

it('removes the text area', () => {
expect(body.querySelector('textarea')).toBeNull();
});
});

it('returns false when execCommand returns false', () => {
execCommand.and.returnValue(false);

expect(clipboard.copy(COPY_CONTENT)).toBe(false);
});
});
});
113 changes: 113 additions & 0 deletions src/cdk-experimental/clipboard/clipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {DOCUMENT} from '@angular/common';
import {Inject, Injectable} from '@angular/core';

/**
* A service for copying text to the clipboard.
*
* Example usage:
*
* clipboard.copy("copy this text");
*/
@Injectable({providedIn: 'root'})
export class Clipboard {
private _document: Document;

constructor(@Inject(DOCUMENT) document: any) {
this._document = document;
}

/**
* Copies the provided text into the user's clipboard.
*
* @param text The string to copy.
* @returns Whether the operation was successful.
*/
copy(text: string): boolean {
const pendingCopy = this.beginCopy(text);
const successful = pendingCopy.copy();
pendingCopy.destroy();

return successful;
}

/**
* Prepares a string to be copied later. This is useful for large strings
* which take too long to successfully render and be copied in the same tick.
*
* The caller must call `destroy` on the returned `PendingCopy`.
*
* @param text The string to copy.
* @returns the pending copy operation.
*/
beginCopy(text: string): PendingCopy {
return new PendingCopy(text, this._document);
}
}

/**
* A pending copy-to-clipboard operation.
*
* The implementation of copying text to the clipboard modifies the DOM and
* forces a relayout. This relayout can take too long if the string is large,
* causing the execCommand('copy') to happen too long after the user clicked.
* This results in the browser refusing to copy. This object lets the
* relayout happen in a separate tick from copying by providing a copy function
* that can be called later.
*
* Destroy must be called when no longer in use, regardless of whether `copy` is
* called.
*/
export class PendingCopy {
private _textarea: HTMLTextAreaElement|undefined;

constructor(text: string, private readonly _document: Document) {
const textarea = this._textarea = this._document.createElement('textarea');

// Hide the element for display and accessibility.
textarea.setAttribute('style', 'opacity: 0;');
textarea.setAttribute('aria-hidden', 'true');

textarea.value = text;
this._document.body.appendChild(textarea);
}

/** Finishes copying the text. */
copy(): boolean {
const textarea = this._textarea;
let successful = false;

try { // Older browsers could throw if copy is not supported.
if (textarea) {
const currentFocus = document.activeElement;

textarea.select();
successful = this._document.execCommand('copy');

if (currentFocus instanceof HTMLElement) {
currentFocus.focus();
}
}
} catch {
// Discard error.
// Initial setting of {@code successful} will represent failure here.
}

return successful;
}

/** Cleans up DOM changes used to perform the copy operation. */
destroy() {
if (this._textarea) {
this._document.body.removeChild(this._textarea);
this._textarea = undefined;
}
}
}
64 changes: 64 additions & 0 deletions src/cdk-experimental/clipboard/copy-to-clipboard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';

import {Clipboard} from './clipboard';
import {ClipboardModule} from './clipboard-module';

const COPY_CONTENT = 'copy content';

@Component({
selector: 'copy-to-clipboard-host',
template: `<button [cdkCopyToClipboard]="content" (copied)="copied.emit($event)"></button>`,
})
class CopyToClipboardHost {
@Input() content = '';
@Output() copied = new EventEmitter<boolean>();
}

describe('CdkCopyToClipboard', () => {
let fixture: ComponentFixture<CopyToClipboardHost>;
let mockCopy: jasmine.Spy;
let copiedOutput: jasmine.Spy;

beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
declarations: [CopyToClipboardHost],
imports: [ClipboardModule],
});

TestBed.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(CopyToClipboardHost);

const host = fixture.componentInstance;
host.content = COPY_CONTENT;
copiedOutput = jasmine.createSpy('copied');
host.copied.subscribe(copiedOutput);
mockCopy = spyOn(TestBed.get(Clipboard), 'copy');

fixture.detectChanges();
});

it('copies content to clipboard upon click', () => {
fixture.nativeElement.querySelector('button')!.click();

expect(mockCopy).toHaveBeenCalledWith(COPY_CONTENT);
});

it('emits copied event true when copy succeeds', fakeAsync(() => {
mockCopy.and.returnValue(true);
fixture.nativeElement.querySelector('button')!.click();

expect(copiedOutput).toHaveBeenCalledWith(true);
}));

it('emits copied event false when copy fails', fakeAsync(() => {
mockCopy.and.returnValue(false);
fixture.nativeElement.querySelector('button')!.click();
tick();

expect(copiedOutput).toHaveBeenCalledWith(false);
}));
});
38 changes: 38 additions & 0 deletions src/cdk-experimental/clipboard/copy-to-clipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {Directive, EventEmitter, Input, Output} from '@angular/core';

import {Clipboard} from './clipboard';

/**
* Provides behavior for a button that when clicked copies content into user's
* clipboard.
*
* Example usage:
*
* `<button copyToClipboard="Content to be copied">Copy me!</button>`
*/
@Directive({
selector: '[cdkCopyToClipboard]',
host: {
'(click)': 'doCopy()',
}
})
export class CdkCopyToClipboard {
/** Content to be copied. */
@Input('cdkCopyToClipboard') text = '';

@Output() copied = new EventEmitter<boolean>();

constructor(private readonly clipboard: Clipboard) {}

doCopy() {
this.copied.emit(this.clipboard.copy(this.text));
}
}