/** * Piccole utilità per l'HTML: escape e post-elaborazione dell'HTML generato dal Markdown. */ /** Escape dei caratteri speciali per testo e attributi tra virgolette doppie. */ export const escapeHtml = (s: string): string => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); function hostOf(href: string): string | null { try { return new URL(href).host; } catch { return null; } } /** * Applica `transform` solo al testo dell'HTML, non ai tag né agli attributi (URL, classi). * Per HTML generato dal sito (Markdown del repository): non è un parser completo. */ export function mapHtmlText(html: string, transform: (text: string) => string): string { return html .split(/(<[^>]*>)/) .map((part) => (part.startsWith('<') ? part : transform(part))) .join(''); } /** * Aggiunge `rel="noopener"` ai link verso altri siti (brief §4.7); i link si aprono nella stessa * scheda. `siteHost` è l'host del sito (i link interni assoluti restano invariati). */ export function externalLinksNoopener(html: string, siteHost: string): string { return html.replace( /]*)>/g, (match, href: string, rest: string) => { const host = hostOf(href); if (!host || host === siteHost || /\brel=/.test(rest)) return match; return ``; }, ); }