Update Core.js

This commit is contained in:
simonpipe 2026-07-07 21:16:38 +02:00
parent 7637dfb0c6
commit 9b27907b04

150
Core.js
View file

@ -11,37 +11,28 @@ class SimonUp {
/** /**
* Registriert eine Erweiterung (Plugin) * Registriert eine Erweiterung (Plugin)
* @param {Object} plugin - Ein Objekt mit optionalen 'before'- und 'after'-Hooks
*/ */
use(plugin) { use(plugin) {
this.plugins.push(plugin); this.plugins.push(plugin);
return this; // Ermöglicht Method Chaining return this;
} }
/** /**
* Hauptfunktion: Wandelt SimonUp-Text (.up) in valides HTML um * Hauptfunktion: Wandelt SimonUp-Text (.up) in valides HTML um
* @param {string} text - Der rohe SimonUp-Text
* @returns {string} Das gerenderte HTML
*/ */
parse(text) { parse(text) {
// Zustand bei jedem Parse-Vorgang zurücksetzen
this.headings = []; this.headings = [];
this.counters = [0, 0, 0, 0, 0, 0]; this.counters = [0, 0, 0, 0, 0, 0];
let html = text; let html = text;
// 1. Vorverarbeitung durch Plugins
for (const plugin of this.plugins) { for (const plugin of this.plugins) {
if (plugin.before) html = plugin.before(html); if (plugin.before) html = plugin.before(html);
} }
// 2. Block-Parsing (Strukturelle Blöcke wie &t, &toc, &-, etc.)
html = this._parseBlocks(html); html = this._parseBlocks(html);
// 3. Nachverarbeitung des Gesamtergebnisses & TOC-Injektion
html = this._injectTOC(html); html = this._injectTOC(html);
// 4. Nachverarbeitung durch Plugins
for (const plugin of this.plugins) { for (const plugin of this.plugins) {
if (plugin.after) html = plugin.after(html); if (plugin.after) html = plugin.after(html);
} }
@ -53,18 +44,16 @@ class SimonUp {
* INTERN: Verarbeitet strukturelle Blöcke zeilenweise * INTERN: Verarbeitet strukturelle Blöcke zeilenweise
*/ */
_parseBlocks(text) { _parseBlocks(text) {
// Normalisiere Zeilenumbrüche und teile den Text auf
const lines = text.replace(/\r\n/g, '\n').split('\n'); const lines = text.replace(/\r\n/g, '\n').split('\n');
let result = []; let result = [];
let inBlock = false; let inBlock = false;
let blockType = null; let blockType = null;
let blockMeta = ""; // Für zusätzliche Infos in der Startzeile (z.B. "3x" oder "Titel") let blockMeta = "";
let blockBuffer = []; let blockBuffer = [];
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
let line = lines[i]; let line = lines[i];
// Block-Start erkennen (Zeile beginnt mit '&' und hat danach Inhalt)
if (!inBlock && line.startsWith('&') && line.trim().length > 1) { if (!inBlock && line.startsWith('&') && line.trim().length > 1) {
inBlock = true; inBlock = true;
const fullHeader = line.substring(1).trim(); const fullHeader = line.substring(1).trim();
@ -81,7 +70,6 @@ class SimonUp {
continue; continue;
} }
// Block-Ende erkennen (Ein einzelnes '&' auf einer eigenen Zeile)
if (inBlock && line.trim() === '&') { if (inBlock && line.trim() === '&') {
result.push(this._renderBlock(blockType, blockMeta, blockBuffer)); result.push(this._renderBlock(blockType, blockMeta, blockBuffer));
inBlock = false; inBlock = false;
@ -90,22 +78,17 @@ class SimonUp {
continue; continue;
} }
// Inhalt sammeln oder normalen Fließtext verarbeiten
if (inBlock) { if (inBlock) {
blockBuffer.push(line); blockBuffer.push(line);
} else { } else {
// Horizontale Linie als blockfreie Ausnahme abfangen
if (line.trim() === '___') { if (line.trim() === '___') {
result.push('<hr>'); result.push('<hr>');
} else { } else {
// Normaler Fließtext außerhalb von Blöcken wandert in den Inline-Parser
result.push(this._parseInline(line)); result.push(this._parseInline(line));
} }
} }
} }
// Am Ende leere Zeilen (Soft Breaks vs. Hard Breaks) korrekt verknüpfen
// Zwei aufeinanderfolgende leere Absätze erzeugen <p>, einfache Zeilenumbrüche <br>
return this._processParagraphs(result); return this._processParagraphs(result);
} }
@ -117,46 +100,42 @@ class SimonUp {
switch (type) { switch (type) {
case 'toc': case 'toc':
// Unser neuer, intelligenter TOC-Block
let tocHtml = `<div class="simonup-toc-wrapper">\n`; let tocHtml = `<div class="simonup-toc-wrapper">\n`;
if (meta) tocHtml += `<h2>${meta}</h2>\n`; if (meta) tocHtml += `<h2>${meta}</h2>\n`;
if (content.trim()) { if (content.trim()) {
const intro = lines.map(l => this._parseInline(l)).join('<br>'); const intro = lines.map(l => this._parseInline(l)).join('<br>');
tocHtml += `<p class="toc-intro">${intro}</p>\n`; tocHtml += `<p class="toc-intro">${intro}</p>\n`;
} }
// Ein eindeutiger HTML-Kommentar als Platzhalter für die spätere Injektion
tocHtml += `\n</div>`; tocHtml += `\n</div>`;
return tocHtml; return tocHtml;
case '-': // Unsortierte Liste case '-':
return '<ul>\n' + lines.filter(l => l.trim()).map(l => `<li>${this._parseInline(l)}</li>`).join('\n') + '\n</ul>'; return '<ul>\n' + lines.filter(l => l.trim()).map(l => `<li>${this._parseInline(l)}</li>`).join('\n') + '\n</ul>';
case '+': // Nummerierte Liste case '+':
return '<ol>\n' + lines.filter(l => l.trim()).map(l => `<li>${this._parseInline(l)}</li>`).join('\n') + '\n</ol>'; return '<ol>\n' + lines.filter(l => l.trim()).map(l => `<li>${this._parseInline(l)}</li>`).join('\n') + '\n</ol>';
case 'c': // Code-Block (Ignoriert Fluss-Formatierungen) case 'c':
const langClass = meta ? ` class="language-${meta}"` : ''; const langClass = meta ? ` class="language-${meta}"` : '';
// Escaping für HTML-Sonderzeichen im Code-Block const poolCode = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const escapedCode = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); return `<pre><code${langClass}>${poolCode}</code></pre>`;
return `<pre><code${langClass}>${escapedCode}</code></pre>`;
case 'q': // Zitatblock case 'q':
return `<blockquote>${lines.map(l => this._parseInline(l)).join('<br>')}</blockquote>`; return `<blockquote>${lines.map(l => this._parseInline(l)).join('<br>')}</blockquote>`;
case 'b': // Bibeltext case 'b':
return `<div class="bible-block">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`; return `<div class="bible-block">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`;
case 'f': // Spoiler / Fold case 'f':
return `<details>\n<summary>${meta || 'Details'}</summary>\n<p>${lines.map(l => this._parseInline(l)).join('<br>')}</p>\n</details>`; return `<details>\n<summary>${meta || 'Details'}</summary>\n<p>${lines.map(l => this._parseInline(l)).join('<br>')}</p>\n</details>`;
case 'i': // Infobox case 'i':
return `<div class="infobox" style="border-left: 4px solid ${meta || '#007bff'}; padding: 10px; margin: 10px 0; background: #f8f9fa;">\n${lines.map(l => this._parseInline(l)).join('<br>')}\n</div>`; return `<div class="infobox" style="border-left: 4px solid ${meta || '#007bff'}; padding: 10px; margin: 10px 0; background: #f8f9fa;">\n${lines.map(l => this._parseInline(l)).join('<br>')}\n</div>`;
case 't': // Komplexe Multi-line-Tabellen-Logik & Galerien case 't':
return this._renderTable(meta, lines); return this._renderTable(meta, lines);
default: default:
// Fallback für unbekannte Blocktypen
return `<div class="block-${type}">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`; return `<div class="block-${type}">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`;
} }
} }
@ -166,23 +145,16 @@ class SimonUp {
*/ */
_renderTable(meta, lines) { _renderTable(meta, lines) {
let tableHtml = '<table>\n'; let tableHtml = '<table>\n';
// Einfache Breiten-Zuweisung über CSS (z.B. "3x" oder Prozentangaben) im Stylesheet spiegeln
// Der Kürze halber generieren wir hier das Grundgerüst:
let inRow = false;
let currentCells = []; let currentCells = [];
let cellBuffer = []; let cellBuffer = [];
for (let line of lines) { for (let line of lines) {
if (line.trim() === '') continue; if (line.trim() === '') continue;
// Zerlege die Zeile anhand des Spaltenrenners '|'
// Achtung: Ein escaped '|' (falls vorhanden) müsste beachtet werden
let parts = line.split('|'); let parts = line.split('|');
for (let i = 0; i < parts.length; i++) { for (let i = 0; i < parts.length; i++) {
let part = parts[i]; let part = parts[i];
if (i === parts.length - 1 && part.trim() === '') { if (i === parts.length - 1 && part.trim() === '') {
// Zeile wurde mit einem | sauber beendet
if (cellBuffer.length > 0 || part !== '') { if (cellBuffer.length > 0 || part !== '') {
cellBuffer.push(part); cellBuffer.push(part);
} }
@ -190,7 +162,6 @@ class SimonUp {
currentCells.push(cellBuffer.join('\n')); currentCells.push(cellBuffer.join('\n'));
cellBuffer = []; cellBuffer = [];
} }
// Zeile ist komplett!
tableHtml += '<tr>\n' + currentCells.map(c => `<td>${this._parseInline(c.trim())}</td>`).join('\n') + '\n</tr>\n'; tableHtml += '<tr>\n' + currentCells.map(c => `<td>${this._parseInline(c.trim())}</td>`).join('\n') + '\n</tr>\n';
currentCells = []; currentCells = [];
} else { } else {
@ -213,112 +184,105 @@ class SimonUp {
if (!text) return ''; if (!text) return '';
let html = text; let html = text;
// 1. ESCAPE: Temporär schützen, damit Formatierungen sie nicht überschreiben // 1. ESCAPE: Temporär schützen
html = html.replace(/\\(.)/g, (match, char) => ``); html = html.replace(/\\(.)/g, (match, char) => ``);
// 2. ÜBERSCHRIFTEN (Exakt nach unseren neuen Regeln verarbeitet) // 2. ÜBERSCHRIFTEN (Flusssicher angepasst)
// Regel A: Automatische Nummerierung (3#x Titel 3#x) // Regel A: Automatische Nummerierung (3#x Titel 3#x Restlicher Text)
html = html.replace(/([1-6])#x\s*(.*?)\s*\1#x/g, (match, level, title) => { html = html.replace(/([1-6])#x\s*([^#]+?)\s*\1#x(.*)/g, (match, level, title, rest) => {
const lvl = parseInt(level); const lvl = parseInt(level);
const numStr = this._getAutoNumber(lvl); const numStr = this._getAutoNumber(lvl);
const fullTitle = `${numStr} ${title}`; const fullTitle = `${numStr} ${title.trim()}`;
const id = this._slugify(fullTitle); const id = this._slugify(fullTitle);
// Für das TOC erfassen
this.headings.push({ level: lvl, text: fullTitle, id: id }); this.headings.push({ level: lvl, text: fullTitle, id: id });
return `<h${lvl} id="${id}">${fullTitle}</h${lvl}>`; return `<h${lvl} id="${id}" style="display:inline-block; margin-right:10px;">${fullTitle}</h${lvl}>${rest}`;
}); });
// Regel B: Vom TOC ausgeschlossene Titel (3#- Titel 3#-) // Regel B: Vom TOC ausgeschlossene Titel (3#- Titel 3#- Restlicher Text)
html = html.replace(/([1-6])#-\s*(.*?)\s*\1#-/g, (match, level, title) => { html = html.replace(/([1-6])#-\s*([^#]+?)\s*\1#-(.*)/g, (match, level, title, rest) => {
const lvl = parseInt(level); const lvl = parseInt(level);
return `<h${lvl}>${title}</h${lvl}>`; // Wird NICHT in this.headings gespeichert return `<h${lvl} style="display:inline-block; margin-right:10px;">${title.trim()}</h${lvl}>${rest}`;
}); });
// Regel C: Manuelle Nummerierung (3# Titel 3#) // Regel C: Manuelle Nummerierung (3# Titel 3# Restlicher Text)
html = html.replace(/([1-6])#\s*(.*?)\s*\1#/g, (match, level, title) => { html = html.replace(/([1-6])#\s*([^#]+?)\s*\1#(.*)/g, (match, level, title, rest) => {
const lvl = parseInt(level); const lvl = parseInt(level);
const id = this._slugify(title); const id = this._slugify(title.trim());
this.headings.push({ level: lvl, text: title, id: id }); this.headings.push({ level: lvl, text: title.trim(), id: id });
return `<h${lvl} id="${id}">${title}</h${lvl}>`; return `<h${lvl} id="${id}" style="display:inline-block; margin-right:10px;">${title.trim()}</h${lvl}>${rest}`;
}); });
// Regel D: Das schnelle, solitäre # für H1 (# Titel #) // Regel D: Das schnelle, solitäre # für H1 (# Titel # Restlicher Text)
html = html.replace(/#([^#]+)#/g, (match, title) => { html = html.replace(/#([^#]+)#(.*)/g, (match, title, rest) => {
const id = this._slugify(title); const id = this._slugify(title.trim());
this.headings.push({ level: 1, text: title, id: id }); this.headings.push({ level: 1, text: title.trim(), id: id });
return `<h1 id="${id}">${title}</h1>`; return `<h1 id="${id}" style="display:inline-block; margin-right:10px;">${title.trim()}</h1>${rest}`;
}); });
// 3. STANDARD FLUSS-FORMATIERUNGEN // 3. STANDARD FLUSS-FORMATIERUNGEN (In priorisierter Reihenfolge)
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>'); // Fett html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>'); // Fett
html = html.replace(/\*([^*]+)\*/g, '<span style="font-weight: 500;">$1</span>'); // Medium html = html.replace(/\/([^/]+)\//g, '<em>$1</em>'); // Kursiv
html = html.replace(/\/([^/]+)\//g, '<em>$1</em>'); // Kursiv html = html.replace(/_([^_]+)_/g, '<u>$1</u>'); // Unterstrichen
html = html.replace(/_([^_]+)_/g, '<u>$1</u>'); // Unterstrichen html = html.replace(/~([^~]+)~/g, '<del>$1</del>'); // Durchgestrichen
html = html.replace(/~([^~]+)~/g, '<del>$1</del>'); // Durchgestrichen html = html.replace(/=([^=]+)=/g, '<mark>$1</mark>'); // Highlight
html = html.replace(/=([^=]+)=/g, '<mark>$1</mark>'); // Highlight html = html.replace(/\^([^^]+)\^/g, '<sup>$1</sup>'); // Hochgestellt
html = html.replace(/\^([^^]+)\^/g, '<sup>$1</sup>'); // Hochgestellt html = html.replace(/°([^°]+)°/g, '<sub>$1</sub>'); // Tiefgestellt
html = html.replace(/°([^°]+)°/g, '<sub>$1</sub>'); // Tiefgestellt html = html.replace(/`([^`]+)`/g, '<code>$1</code>'); // Inline-Code
html = html.replace(/`([^`]+)`/g, '<code>$1</code>'); // Inline-Code
// 3.1 MEDIUM-FORMATIERUNG (Sucht nach *, ignoriert aber bereits generiertes HTML)
html = html.replace(/(?<!<[^>]*)\*([^*<\/>]+)\*(?![^<]*>)/g, '<span style="font-weight: 500;">$1</span>');
// 4. AUSRICHTUNG & EINRÜCKUNG (Basiszeichen '>') // 4. AUSRICHTUNG & EINRÜCKUNG (Basiszeichen '>')
html = html.replace(/>l ([^>]+)>/g, '<div style="text-align: left;">$1</div>'); html = html.replace(/>l ([^>]+)>/g, '<div style="text-align: left; display: inline-block; width: 100%;">$1</div>');
html = html.replace(/>r ([^>]+)>/g, '<div style="text-align: right;">$1</div>'); html = html.replace(/>r ([^>]+)>/g, '<div style="text-align: right; display: inline-block; width: 100%;">$1</div>');
html = html.replace(/>c ([^>]+)>/g, '<div style="text-align: center;">$1</div>'); html = html.replace(/>c ([^>]+)>/g, '<div style="text-align: center; display: inline-block; width: 100%;">$1</div>');
html = html.replace(/>j ([^>]+)>/g, '<div style="text-align: justify;">$1</div>'); html = html.replace(/>j ([^>]+)>/g, '<div style="text-align: justify; display: inline-block; width: 100%;">$1</div>');
html = html.replace(/>tt ([^>]+)>/g, '<div style="margin-left: 4em;">$1</div>'); html = html.replace(/>tt ([^>]+)>/g, '<div style="margin-left: 4em; display: inline-block;">$1</div>');
html = html.replace(/>t ([^>]+)>/g, '<div style="margin-left: 2em;">$1</div>'); html = html.replace(/>t ([^>]+)>/g, '<div style="margin-left: 2em; display: inline-block;">$1</div>');
// 5. LINKS & MEDIEN // 5. LINKS & MEDIEN
// Bilder mit definierter Breite: ![Alt w:300](URL)
html = html.replace(/!\[([^\]]+)\s+w:(\d+)\]\(([^)]+)\)/g, '<img src="$3" alt="$1" style="width: $2px; height: auto;">'); html = html.replace(/!\[([^\]]+)\s+w:(\d+)\]\(([^)]+)\)/g, '<img src="$3" alt="$1" style="width: $2px; height: auto;">');
// Standard Bilder: ![Alt](URL)
html = html.replace(/!\[([^\]]+)\]\(([^)]+)\)/g, '<img src="$2" alt="$1">'); html = html.replace(/!\[([^\]]+)\]\(([^)]+)\)/g, '<img src="$2" alt="$1">');
// Komfort-Links (Neuer Tab): [Text]{URL}
html = html.replace(/\[([^\]]+)\]\{([^}]+)\}/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'); html = html.replace(/\[([^\]]+)\]\{([^}]+)\}/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
// Standard-Links: [Text](URL)
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>'); html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
// 6. FUSSNOTEN (Manuell ^1[...]^ und Automatisch ^x[...]^) // 6. FUSSNOTEN
html = html.replace(/\^x\[([^\]]+)\]\^/g, '<span class="footnote-auto" title="$1">[*]</span>'); // Logik für Fußnoten-Endleiste optional html = html.replace(/\^x\[([^\]]+)\]\^/g, '<span class="footnote-auto" title="$1">[*]</span>');
html = html.replace(/\^(\d+)\[([^\]]+)\]\^/g, '<sup class="footnote-manual" title="$2">[$1]</sup>'); html = html.replace(/\^(\d+)\[([^\]]+)\]\^/g, '<sup class="footnote-manual" title="$2">[$1]</sup>');
// 7. ESCAPE ZURÜCKWANDELN // 7. ESCAPE ZURÜCKWANDELN
html = html.replace(/``/g, (match, code) => String.fromCharCode(parseInt(code))); html = html.replace(/<\!--SU_ESC_(\d+)-->/g, (match, code) => String.fromCharCode(parseInt(code)));
return html; return html;
} }
/** /**
* INTERN: Errechnet die nächste fortlaufende Kapitelnummer (z.B. "1.2.1.") * INTERN: Errechnet die nächste fortlaufende Kapitelnummer
*/ */
_getAutoNumber(level) { _getAutoNumber(level) {
let idx = level - 1; let idx = level - 1;
this.counters[idx]++; this.counters[idx]++;
// Alle untergeordneten Ebenen radikal auf 0 zurücksetzen
for (let i = idx + 1; i < 6; i++) this.counters[i] = 0; for (let i = idx + 1; i < 6; i++) this.counters[i] = 0;
// Array filtern, um nur die bis hierhin aktiven Nummernzähler zu extrahieren
let activeParts = this.counters.slice(0, level); let activeParts = this.counters.slice(0, level);
return activeParts.join('.') + '.'; return activeParts.join('.') + '.';
} }
/** /**
* INTERN: Macht aus Text eine URL-konforme ID (Anker für das TOC) * INTERN: Macht aus Text eine URL-konforme ID
*/ */
_slugify(text) { _slugify(text) {
return text.toLowerCase() return text.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '') // Entferne Sonderzeichen .replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-'); // Ersetze Leerzeichen durch Bindestriche .replace(/\s+/g, '-');
} }
/** /**
* INTERN: Erzeugt die fertige HTML-Liste des TOC und injiziert sie in den Platzhalter * INTERN: Erzeugt die fertige HTML-Liste des TOC und injiziert sie in den Platzhalter
*/ */
_injectTOC(html) { _injectTOC(html) {
// Falls kein TOC-Block deklariert wurde oder keine Überschriften da sind, Platzhalter entfernen
if (this.headings.length === 0) { if (this.headings.length === 0) {
return html.replace('', ''); return html.replace('', '');
} }
@ -353,15 +317,13 @@ class SimonUp {
let paragraphBuffer = []; let paragraphBuffer = [];
for (let element of elements) { for (let element of elements) {
// Wenn es ein fertiger HTML-Block (z.B. Table, List, H1) ist, schließe offenen Absatz ab if (element.startsWith('<') && !element.startsWith('<a>') && !element.startsWith('<strong>') && !element.startsWith('<em>') && !element.startsWith('<span>') && !element.startsWith('<code>') && !element.startsWith('<img') && !element.startsWith('<h')) {
if (element.startsWith('<') && !element.startsWith('<a>') && !element.startsWith('<strong>') && !element.startsWith('<em>') && !element.startsWith('<span>') && !element.startsWith('<code>') && !element.startsWith('<img')) {
if (paragraphBuffer.length > 0) { if (paragraphBuffer.length > 0) {
processed.push(`<p>${paragraphBuffer.join('<br>')}</p>`); processed.push(`<p>${paragraphBuffer.join('<br>')}</p>`);
paragraphBuffer = []; paragraphBuffer = [];
} }
processed.push(element); processed.push(element);
} else if (element.trim() === '') { } else if (element.trim() === '') {
// Bei einer echten Leerzeile (2x Enter) wird der Absatz gebunden
if (paragraphBuffer.length > 0) { if (paragraphBuffer.length > 0) {
processed.push(`<p>${paragraphBuffer.join('<br>')}</p>`); processed.push(`<p>${paragraphBuffer.join('<br>')}</p>`);
paragraphBuffer = []; paragraphBuffer = [];