2019-01-23 22:22:38 +01:00
|
|
|
import {
|
|
|
|
Directive,
|
|
|
|
ElementRef,
|
|
|
|
HostListener,
|
|
|
|
} from '@angular/core';
|
|
|
|
|
|
|
|
import { PlatformUtilsService } from '../../abstractions/platformUtils.service';
|
|
|
|
|
|
|
|
@Directive({
|
2019-04-01 19:16:37 +02:00
|
|
|
selector: '[appSelectCopy]',
|
2019-01-23 22:22:38 +01:00
|
|
|
})
|
2019-04-01 19:16:37 +02:00
|
|
|
export class SelectCopyDirective {
|
2019-01-23 22:22:38 +01:00
|
|
|
constructor(private el: ElementRef, private platformUtilsService: PlatformUtilsService) { }
|
|
|
|
|
|
|
|
@HostListener('copy') onCopy() {
|
|
|
|
if (window == null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let copyText = '';
|
|
|
|
const selection = window.getSelection();
|
|
|
|
for (let i = 0; i < selection.rangeCount; i++) {
|
|
|
|
const range = selection.getRangeAt(i);
|
|
|
|
const text = range.toString();
|
2019-03-21 14:51:37 +01:00
|
|
|
|
|
|
|
// The selection should only contain one line of text. In some cases however, the
|
2019-03-21 14:55:45 +01:00
|
|
|
// selection contains newlines and space characters from the indentation of following
|
2019-03-21 14:51:37 +01:00
|
|
|
// sibling nodes. To avoid copying passwords containing trailing newlines and spaces
|
2019-03-21 14:55:45 +01:00
|
|
|
// that aren't part of the password, the selection has to be trimmed.
|
|
|
|
let stringEndPos = text.length;
|
|
|
|
const newLinePos = text.search(/(?:\r\n|\r|\n)/);
|
|
|
|
if (newLinePos > -1) {
|
2019-03-21 15:05:31 +01:00
|
|
|
const otherPart = text.substr(newLinePos).trim();
|
|
|
|
if (otherPart === '') {
|
|
|
|
stringEndPos = newLinePos;
|
|
|
|
}
|
2019-03-21 14:55:45 +01:00
|
|
|
}
|
2019-03-21 14:51:37 +01:00
|
|
|
copyText += text.substring(0, stringEndPos);
|
2019-01-23 22:22:38 +01:00
|
|
|
}
|
|
|
|
this.platformUtilsService.copyToClipboard(copyText, { window: window });
|
|
|
|
}
|
|
|
|
}
|