Handle pasted HTML document

This commit is contained in:
morethanwords 2022-01-14 05:29:38 +04:00
parent 318aaf6f4e
commit 7c67d80dab
2 changed files with 24 additions and 7 deletions

View File

@ -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(/<body>([\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 <p>asd</p>\n<p>zxc</p>
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;

View File

@ -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;
}