-
Notifications
You must be signed in to change notification settings - Fork 6.8k
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
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b472fe3
Clipboard: add clipboard service and directive
a9c4469
Merge branch 'master' of github.com:xkxx/components
4e0979f
Clipboard: fix lint and ci errors
4121654
Clipboard: fix lint and CI errors.
a6fdc7b
Merge branch 'master' of github.com:xkxx/components
548807b
Clipboard: address review feedback
1e9131a
Clipboard: rename [copyToClipboard] to [cdkCopytoClipboard]
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"], | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
})); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.