refactor: DRY Markdown post-processing logic

This commit is contained in:
Aleksander Grygier 2025-12-16 10:14:36 +01:00
parent c05da389ba
commit 0e7e5db661
1 changed files with 91 additions and 81 deletions

View File

@ -76,15 +76,29 @@
html: string; html: string;
}; };
function enhanceLinks(html: string): string { /**
if (!browser || !html.includes('<a')) { * Helper to process HTML with a temporary DOM element.
* Returns original HTML if not in browser or tag not found.
*/
function processHtml(
html: string,
tagCheck: string,
processor: (tempDiv: HTMLDivElement) => boolean
): string {
if (!browser || !html.includes(tagCheck)) {
return html; return html;
} }
const tempDiv = document.createElement('div'); const tempDiv = document.createElement('div');
tempDiv.innerHTML = html; tempDiv.innerHTML = html;
// Make all links open in new tabs const mutated = processor(tempDiv);
return mutated ? tempDiv.innerHTML : html;
}
function enhanceLinks(html: string): string {
return processHtml(html, '<a', (tempDiv) => {
const linkElements = tempDiv.querySelectorAll('a[href]'); const linkElements = tempDiv.querySelectorAll('a[href]');
let mutated = false; let mutated = false;
@ -100,17 +114,12 @@
link.setAttribute('rel', 'noopener noreferrer'); link.setAttribute('rel', 'noopener noreferrer');
} }
return mutated ? tempDiv.innerHTML : html; return mutated;
});
} }
function enhanceCodeBlocks(html: string): string { function enhanceCodeBlocks(html: string): string {
if (!browser || !html.includes('<pre')) { return processHtml(html, '<pre', (tempDiv) => {
return html;
}
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
const preElements = tempDiv.querySelectorAll('pre'); const preElements = tempDiv.querySelectorAll('pre');
let mutated = false; let mutated = false;
@ -187,7 +196,8 @@
pre.parentNode?.replaceChild(wrapper, pre); pre.parentNode?.replaceChild(wrapper, pre);
} }
return mutated ? tempDiv.innerHTML : html; return mutated;
});
} }
function getCodeInfoFromTarget(target: HTMLElement) { function getCodeInfoFromTarget(target: HTMLElement) {