|
| 1 | +import {insertText} from './text' |
| 2 | + |
| 3 | +export function install(el: HTMLElement): void { |
| 4 | + el.addEventListener('paste', onPaste) |
| 5 | +} |
| 6 | + |
| 7 | +export function uninstall(el: HTMLElement): void { |
| 8 | + el.removeEventListener('paste', onPaste) |
| 9 | +} |
| 10 | + |
| 11 | +function onPaste(event: ClipboardEvent) { |
| 12 | + const transfer = event.clipboardData |
| 13 | + if (!transfer || !hasPlainText(transfer)) return |
| 14 | + |
| 15 | + const field = event.currentTarget |
| 16 | + if (!(field instanceof HTMLTextAreaElement)) return |
| 17 | + |
| 18 | + const text = transfer.getData('text/plain') |
| 19 | + if (!text) return |
| 20 | + |
| 21 | + if (isWithinLink(field)) return |
| 22 | + |
| 23 | + event.stopPropagation() |
| 24 | + event.preventDefault() |
| 25 | + |
| 26 | + const selectedText = field.value.substring(field.selectionStart, field.selectionEnd) |
| 27 | + |
| 28 | + insertText(field, linkify(selectedText, text), {addNewline: false}) |
| 29 | +} |
| 30 | + |
| 31 | +function hasPlainText(transfer: DataTransfer): boolean { |
| 32 | + return Array.from(transfer.types).includes('text/plain') |
| 33 | +} |
| 34 | + |
| 35 | +function isWithinLink(textarea: HTMLTextAreaElement): boolean { |
| 36 | + const selectionStart = textarea.selectionStart || 0 |
| 37 | + |
| 38 | + if (selectionStart > 1) { |
| 39 | + const previousChars = textarea.value.substring(selectionStart - 2, selectionStart) |
| 40 | + return previousChars === '](' |
| 41 | + } else { |
| 42 | + return false |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +function linkify(selectedText: string, text: string): string { |
| 47 | + return selectedText.length && isURL(text) ? `[${selectedText}](${text})` : text |
| 48 | +} |
| 49 | + |
| 50 | +function isURL(url: string): boolean { |
| 51 | + return /^https?:\/\//i.test(url) |
| 52 | +} |
0 commit comments