2020-11-06 20:11:18 +00:00
|
|
|
// Copyright 2020 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2021-10-26 19:15:33 +00:00
|
|
|
import type Quill from 'quill';
|
2020-11-12 01:01:45 +00:00
|
|
|
import Delta from 'quill-delta';
|
|
|
|
|
2020-11-19 17:38:25 +00:00
|
|
|
const replaceAngleBrackets = (text: string) => {
|
|
|
|
const entities: Array<[RegExp, string]> = [
|
|
|
|
[/&/g, '&'],
|
|
|
|
[/</g, '<'],
|
|
|
|
[/>/g, '>'],
|
|
|
|
];
|
|
|
|
|
|
|
|
return entities.reduce(
|
|
|
|
(acc, [re, replaceValue]) => acc.replace(re, replaceValue),
|
|
|
|
text
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2020-11-06 20:11:18 +00:00
|
|
|
export class SignalClipboard {
|
|
|
|
quill: Quill;
|
|
|
|
|
|
|
|
constructor(quill: Quill) {
|
|
|
|
this.quill = quill;
|
|
|
|
|
2020-11-12 01:01:45 +00:00
|
|
|
this.quill.root.addEventListener('paste', e => this.onCapturePaste(e));
|
2020-11-06 20:11:18 +00:00
|
|
|
|
2023-05-10 00:40:19 +00:00
|
|
|
const clipboard = this.quill.getModule('clipboard');
|
2023-05-11 19:48:34 +00:00
|
|
|
|
|
|
|
// We keep just the first few matchers (for spacing) then drop the rest!
|
|
|
|
clipboard.matchers = clipboard.matchers
|
|
|
|
.slice(0, 4)
|
|
|
|
.concat(clipboard.matchers.slice(11));
|
2020-11-06 20:11:18 +00:00
|
|
|
}
|
2020-11-12 01:01:45 +00:00
|
|
|
|
|
|
|
onCapturePaste(event: ClipboardEvent): void {
|
2023-05-17 16:58:32 +00:00
|
|
|
event.preventDefault();
|
|
|
|
event.stopPropagation();
|
|
|
|
|
2022-09-14 21:40:44 +00:00
|
|
|
if (event.clipboardData == null) {
|
2020-11-12 01:01:45 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.quill.focus();
|
|
|
|
|
|
|
|
const clipboard = this.quill.getModule('clipboard');
|
|
|
|
const selection = this.quill.getSelection();
|
|
|
|
|
2022-09-14 21:40:44 +00:00
|
|
|
if (selection == null) {
|
2020-11-12 01:01:45 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const text = event.clipboardData.getData('text/plain');
|
2023-05-10 00:40:19 +00:00
|
|
|
const html = event.clipboardData.getData('text/html');
|
2020-11-12 01:01:45 +00:00
|
|
|
|
2020-11-19 17:38:25 +00:00
|
|
|
const clipboardDelta = html
|
|
|
|
? clipboard.convert(html)
|
|
|
|
: clipboard.convert(replaceAngleBrackets(text));
|
|
|
|
|
2020-11-12 01:01:45 +00:00
|
|
|
const { scrollTop } = this.quill.scrollingContainer;
|
|
|
|
|
|
|
|
this.quill.selection.update('silent');
|
|
|
|
|
|
|
|
if (selection) {
|
|
|
|
setTimeout(() => {
|
|
|
|
const delta = new Delta()
|
|
|
|
.retain(selection.index)
|
2023-05-17 16:58:32 +00:00
|
|
|
.delete(selection.length)
|
2020-11-19 17:38:25 +00:00
|
|
|
.concat(clipboardDelta);
|
2020-11-12 01:01:45 +00:00
|
|
|
this.quill.updateContents(delta, 'user');
|
|
|
|
this.quill.setSelection(delta.length(), 0, 'silent');
|
|
|
|
this.quill.scrollingContainer.scrollTop = scrollTop;
|
|
|
|
}, 1);
|
|
|
|
}
|
|
|
|
}
|
2020-11-06 20:11:18 +00:00
|
|
|
}
|