import { RangeStatic, Sources } from 'quill'; import Delta from './quill-delta/Delta'; interface IQuill { selection: any; root: HTMLDivElement; addContainer(classNameOrDomNode: string | Node, refNode?: Node): HTMLDivElement; isEnabled(): boolean; getSelection(focus: true): RangeStatic; updateContents(delta: Delta, source: Sources): Delta; setSelection(index: number, name: string): void; focus(): void; } const SILENT = 'silent'; const USER = 'user'; export default class Clipboard { private container: HTMLDivElement; constructor(private quill: IQuill, _options = {}) { this.quill.root.addEventListener('paste', this.onPaste.bind(this)); this.container = this.quill.addContainer('ql-clipboard'); this.container.setAttribute('contenteditable', 'true'); this.container.setAttribute('tabindex', '-1'); } public onPaste(e: ClipboardEvent) { this.container.focus(); this.quill.selection.update(SILENT); const clipboardData = e.clipboardData; if (clipboardData) { const len = clipboardData.types.length; if (len > 0) { // 1 or 2 const data_index = len - 1; const type = clipboardData.types[data_index]; const data = clipboardData.items[data_index]; if (/^Files$/i.test(type)) { if (data && data.type.match('image/*')) { const fileClipboard = data.getAsFile(); if (fileClipboard) { setTimeout(() => { const reader = new FileReader(); reader.onload = (ee) => { const range = this.quill.getSelection(true); this.quill.updateContents(new Delta().retain(range.index).delete(range.length).insert({ image: (ee.target as FileReader).result }), USER); this.quill.setSelection(range.index + 1, SILENT); // (fileClipboard as unknown as { value: string; }).value = ''; }; reader.readAsDataURL(fileClipboard); }, 1); } } } if (/text/.test(type)) { const str_data = clipboardData.items[0]; str_data.getAsString((str) => { // window.console.log(type, '1111111', str.replace(/]*>?/, '')); window.console.log(type, '1111111', str); setTimeout(() => { const range = this.quill.getSelection(true); const delta = new Delta(); delta.retain(range.index); delta.delete(range.length); delta.insert({ text: str }); this.quill.updateContents(delta, USER); this.quill.setSelection(delta.length() - range.length + 1, SILENT); this.quill.focus(); }, 1); }); } } } if (e.defaultPrevented || !this.quill.isEnabled()) { return; } } }