Implement removeAloneBRs function to clean up <br> tags and enhance HTML rendering

This commit is contained in:
mic 2025-06-18 23:11:38 +02:00
parent 72428d8ee5
commit c90ee66fb4

View file

@ -338,10 +338,10 @@ class MessagesArea extends HTMLElement {
if(promptData.mailMessageId == -1) { // we are using the reply from the compose window!
promptData.action = "2"; // replace text
}
let finalText = fullTextHTMLAtAssignment;
let finalText = removeAloneBRs(fullTextHTMLAtAssignment);
const selectedHTML = this.getCurrentSelectionHTML();
if(selectedHTML != "") {
finalText = selectedHTML;
finalText = removeAloneBRs(selectedHTML);
}
switch(promptData.action) {
@ -522,9 +522,11 @@ class MessagesArea extends HTMLElement {
// Convert Markdown to DOM nodes using the markdown-it library
const md = window.markdownit();
const html = md.render(fullText);
const html = convertNewlinesToBr(md.render(fullText));
this.fullTextHTML += html;
// console.log(">>>>>>>>>>>>>>>> flushAccumulatingMessage this.fullTextHTML: " + this.fullTextHTML);
// Create a new DOM parser
const parser = new DOMParser();
@ -562,12 +564,42 @@ customElements.define('messages-area', MessagesArea);
function htmlStringToFragment(htmlString) {
console.log(">>>>>>>>>>>>>>>> htmlStringToFragment htmlString: " + htmlString);
// console.log(">>>>>>>>>>>>>>>> htmlStringToFragment htmlString: " + htmlString);
const normalizedHtml = htmlString.replace(/\n/g, '<br>');
console.log(">>>>>>>>>>>>>>>> htmlStringToFragment normalizedHtml: " + normalizedHtml);
// console.log(">>>>>>>>>>>>>>>> htmlStringToFragment normalizedHtml: " + normalizedHtml);
const parser = new DOMParser();
const doc = parser.parseFromString(normalizedHtml, 'text/html');
const fragment = document.createDocumentFragment();
Array.from(doc.body.childNodes).forEach(node => fragment.appendChild(node));
return fragment;
}
function convertNewlinesToBr(text) {
return text.replace(/\n/g, '<br>');
}
function removeAloneBRs(htmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
const brElements = Array.from(doc.querySelectorAll('br'));
brElements.forEach(br => {
let current = br;
let isInsideP = false;
while (current.parentElement) {
if (current.parentElement.tagName.toLowerCase() === 'p') {
isInsideP = true;
break;
}
current = current.parentElement;
}
if (!isInsideP) {
br.remove();
}
});
return doc.body.innerHTML;
}