From 7c67d80dab721792f16edc5f8138803c1e1625f7 Mon Sep 17 00:00:00 2001 From: morethanwords Date: Fri, 14 Jan 2022 05:29:38 +0400 Subject: [PATCH] Handle pasted HTML document --- src/components/inputField.ts | 23 ++++++++++++++++++++--- src/helpers/dom/getRichElementValue.ts | 8 ++++---- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/components/inputField.ts b/src/components/inputField.ts index cc591aac..c85998ad 100644 --- a/src/components/inputField.ts +++ b/src/components/inputField.ts @@ -24,11 +24,28 @@ let init = () => { let text: string, entities: MessageEntity[]; // @ts-ignore - const html: string = (e.originalEvent || e).clipboardData.getData('text/html'); + let html: string = (e.originalEvent || e).clipboardData.getData('text/html'); if(html.trim()) { - const span = document.createElement('span'); + const match = html.match(/([\s\S]*)<\/body>/); + if(match) { + html = match[1].trim(); + } + + let span: HTMLElement = document.createElement('span'); span.innerHTML = html; - + + let curChild = span.firstChild; + while(curChild) { // * fix whitespace between elements like

asd

\n

zxc

+ let nextSibling = curChild.nextSibling; + if(curChild.nodeType === 3) { + if(!curChild.nodeValue.trim()) { + curChild.remove(); + } + } + + curChild = nextSibling; + } + const richValue = getRichValue(span, true); text = richValue.value; entities = richValue.entities; diff --git a/src/helpers/dom/getRichElementValue.ts b/src/helpers/dom/getRichElementValue.ts index c0ba4c76..4bd7659f 100644 --- a/src/helpers/dom/getRichElementValue.ts +++ b/src/helpers/dom/getRichElementValue.ts @@ -138,7 +138,6 @@ export default function getRichElementValue(node: HTMLElement, lines: string[], } offset.offset += nodeValue.length; - return; } @@ -174,13 +173,14 @@ export default function getRichElementValue(node: HTMLElement, lines: string[], line.push('\x01'); } - if(isBlock && line.length) { + const wasLength = line.length; + if(isBlock && wasLength) { lines.push(line.join('')); - line.splice(0, line.length); + line.splice(0, wasLength); ++offset.offset; } - if(node.tagName === 'P') { + if(wasLength && node.tagName === 'P' && node.nextSibling) { lines.push(''); ++offset.offset; }