Add Core.js
This commit is contained in:
parent
2074cc3eed
commit
796bc0d450
1 changed files with 380 additions and 0 deletions
380
Core.js
Normal file
380
Core.js
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
/**
|
||||
* SimonUp Core Compiler (Core.js)
|
||||
* Eine moderne, fluss- und blockorientierte Auszeichnungssprache.
|
||||
*/
|
||||
class SimonUp {
|
||||
constructor() {
|
||||
this.plugins = [];
|
||||
this.headings = []; // Speichert alle gefundenen Überschriften für das TOC
|
||||
this.counters = [0, 0, 0, 0, 0, 0]; // Zähler für die hierarchischen Ebenen 1 bis 6
|
||||
}
|
||||
|
||||
/**
|
||||
* Registriert eine Erweiterung (Plugin)
|
||||
* @param {Object} plugin - Ein Objekt mit optionalen 'before'- und 'after'-Hooks
|
||||
*/
|
||||
use(plugin) {
|
||||
this.plugins.push(plugin);
|
||||
return this; // Ermöglicht Method Chaining
|
||||
}
|
||||
|
||||
/**
|
||||
* Hauptfunktion: Wandelt SimonUp-Text (.up) in valides HTML um
|
||||
* @param {string} text - Der rohe SimonUp-Text
|
||||
* @returns {string} Das gerenderte HTML
|
||||
*/
|
||||
parse(text) {
|
||||
// Zustand bei jedem Parse-Vorgang zurücksetzen
|
||||
this.headings = [];
|
||||
this.counters = [0, 0, 0, 0, 0, 0];
|
||||
|
||||
let html = text;
|
||||
|
||||
// 1. Vorverarbeitung durch Plugins
|
||||
for (const plugin of this.plugins) {
|
||||
if (plugin.before) html = plugin.before(html);
|
||||
}
|
||||
|
||||
// 2. Block-Parsing (Strukturelle Blöcke wie &t, &toc, &-, etc.)
|
||||
html = this._parseBlocks(html);
|
||||
|
||||
// 3. Nachverarbeitung des Gesamtergebnisses & TOC-Injektion
|
||||
html = this._injectTOC(html);
|
||||
|
||||
// 4. Nachverarbeitung durch Plugins
|
||||
for (const plugin of this.plugins) {
|
||||
if (plugin.after) html = plugin.after(html);
|
||||
}
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERN: Verarbeitet strukturelle Blöcke zeilenweise
|
||||
*/
|
||||
_parseBlocks(text) {
|
||||
// Normalisiere Zeilenumbrüche und teile den Text auf
|
||||
const lines = text.replace(/\r\n/g, '\n').split('\n');
|
||||
let result = [];
|
||||
let inBlock = false;
|
||||
let blockType = null;
|
||||
let blockMeta = ""; // Für zusätzliche Infos in der Startzeile (z.B. "3x" oder "Titel")
|
||||
let blockBuffer = [];
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
let line = lines[i];
|
||||
|
||||
// Block-Start erkennen (Zeile beginnt mit '&' und hat danach Inhalt)
|
||||
if (!inBlock && line.startsWith('&') && line.trim().length > 1) {
|
||||
inBlock = true;
|
||||
const fullHeader = line.substring(1).trim();
|
||||
const spaceIndex = fullHeader.indexOf(' ');
|
||||
|
||||
if (spaceIndex !== -1) {
|
||||
blockType = fullHeader.substring(0, spaceIndex).toLowerCase();
|
||||
blockMeta = fullHeader.substring(spaceIndex).trim();
|
||||
} else {
|
||||
blockType = fullHeader.toLowerCase();
|
||||
blockMeta = "";
|
||||
}
|
||||
blockBuffer = [];
|
||||
continue;
|
||||
}
|
||||
|
||||
// Block-Ende erkennen (Ein einzelnes '&' auf einer eigenen Zeile)
|
||||
if (inBlock && line.trim() === '&') {
|
||||
result.push(this._renderBlock(blockType, blockMeta, blockBuffer));
|
||||
inBlock = false;
|
||||
blockType = null;
|
||||
blockMeta = "";
|
||||
continue;
|
||||
}
|
||||
|
||||
// Inhalt sammeln oder normalen Fließtext verarbeiten
|
||||
if (inBlock) {
|
||||
blockBuffer.push(line);
|
||||
} else {
|
||||
// Horizontale Linie als blockfreie Ausnahme abfangen
|
||||
if (line.trim() === '___') {
|
||||
result.push('<hr>');
|
||||
} else {
|
||||
// Normaler Fließtext außerhalb von Blöcken wandert in den Inline-Parser
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERN: Erzeugt das HTML für einen geschlossenen Block
|
||||
*/
|
||||
_renderBlock(type, meta, lines) {
|
||||
const content = lines.join('\n');
|
||||
|
||||
switch (type) {
|
||||
case 'toc':
|
||||
// Unser neuer, intelligenter TOC-Block
|
||||
let tocHtml = `<div class="simonup-toc-wrapper">\n`;
|
||||
if (meta) tocHtml += `<h2>${meta}</h2>\n`;
|
||||
if (content.trim()) {
|
||||
const intro = lines.map(l => this._parseInline(l)).join('<br>');
|
||||
tocHtml += `<p class="toc-intro">${intro}</p>\n`;
|
||||
}
|
||||
// Ein eindeutiger HTML-Kommentar als Platzhalter für die spätere Injektion
|
||||
tocHtml += `\n</div>`;
|
||||
return tocHtml;
|
||||
|
||||
case '-': // Unsortierte Liste
|
||||
return '<ul>\n' + lines.filter(l => l.trim()).map(l => `<li>${this._parseInline(l)}</li>`).join('\n') + '\n</ul>';
|
||||
|
||||
case '+': // Nummerierte Liste
|
||||
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)
|
||||
const langClass = meta ? ` class="language-${meta}"` : '';
|
||||
// Escaping für HTML-Sonderzeichen im Code-Block
|
||||
const escapedCode = content.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
return `<pre><code${langClass}>${escapedCode}</code></pre>`;
|
||||
|
||||
case 'q': // Zitatblock
|
||||
return `<blockquote>${lines.map(l => this._parseInline(l)).join('<br>')}</blockquote>`;
|
||||
|
||||
case 'b': // Bibeltext
|
||||
return `<div class="bible-block">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`;
|
||||
|
||||
case 'f': // Spoiler / Fold
|
||||
return `<details>\n<summary>${meta || 'Details'}</summary>\n<p>${lines.map(l => this._parseInline(l)).join('<br>')}</p>\n</details>`;
|
||||
|
||||
case 'i': // Infobox
|
||||
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
|
||||
return this._renderTable(meta, lines);
|
||||
|
||||
default:
|
||||
// Fallback für unbekannte Blocktypen
|
||||
return `<div class="block-${type}">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERN: Hilfsfunktion zum Rendern von Multi-line-Tabellen und Galerien
|
||||
*/
|
||||
_renderTable(meta, lines) {
|
||||
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 cellBuffer = [];
|
||||
|
||||
for (let line of lines) {
|
||||
if (line.trim() === '') continue;
|
||||
|
||||
// Zerlege die Zeile anhand des Spaltenrenners '|'
|
||||
// Achtung: Ein escaped '|' (falls vorhanden) müsste beachtet werden
|
||||
let parts = line.split('|');
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
let part = parts[i];
|
||||
if (i === parts.length - 1 && part.trim() === '') {
|
||||
// Zeile wurde mit einem | sauber beendet
|
||||
if (cellBuffer.length > 0 || part !== '') {
|
||||
cellBuffer.push(part);
|
||||
}
|
||||
if (cellBuffer.length > 0) {
|
||||
currentCells.push(cellBuffer.join('\n'));
|
||||
cellBuffer = [];
|
||||
}
|
||||
// Zeile ist komplett!
|
||||
tableHtml += '<tr>\n' + currentCells.map(c => `<td>${this._parseInline(c.trim())}</td>`).join('\n') + '\n</tr>\n';
|
||||
currentCells = [];
|
||||
} else {
|
||||
cellBuffer.push(part);
|
||||
if (i < parts.length - 1) {
|
||||
currentCells.push(cellBuffer.join('\n'));
|
||||
cellBuffer = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tableHtml += '</table>';
|
||||
return tableHtml;
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERN: Verarbeitet Fluss-Formatierungen (Inline) mittels RegEx
|
||||
*/
|
||||
_parseInline(text) {
|
||||
if (!text) return '';
|
||||
let html = text;
|
||||
|
||||
// 1. ESCAPE: Temporär schützen, damit Formatierungen sie nicht überschreiben
|
||||
html = html.replace(/\\(.)/g, (match, char) => ``);
|
||||
|
||||
// 2. ÜBERSCHRIFTEN (Exakt nach unseren neuen Regeln verarbeitet)
|
||||
|
||||
// Regel A: Automatische Nummerierung (3#x Titel 3#x)
|
||||
html = html.replace(/([1-6])#x\s*(.*?)\s*\1#x/g, (match, level, title) => {
|
||||
const lvl = parseInt(level);
|
||||
const numStr = this._getAutoNumber(lvl);
|
||||
const fullTitle = `${numStr} ${title}`;
|
||||
const id = this._slugify(fullTitle);
|
||||
|
||||
// Für das TOC erfassen
|
||||
this.headings.push({ level: lvl, text: fullTitle, id: id });
|
||||
return `<h${lvl} id="${id}">${fullTitle}</h${lvl}>`;
|
||||
});
|
||||
|
||||
// Regel B: Vom TOC ausgeschlossene Titel (3#- Titel 3#-)
|
||||
html = html.replace(/([1-6])#-\s*(.*?)\s*\1#-/g, (match, level, title) => {
|
||||
const lvl = parseInt(level);
|
||||
return `<h${lvl}>${title}</h${lvl}>`; // Wird NICHT in this.headings gespeichert
|
||||
});
|
||||
|
||||
// Regel C: Manuelle Nummerierung (3# Titel 3#)
|
||||
html = html.replace(/([1-6])#\s*(.*?)\s*\1#/g, (match, level, title) => {
|
||||
const lvl = parseInt(level);
|
||||
const id = this._slugify(title);
|
||||
|
||||
this.headings.push({ level: lvl, text: title, id: id });
|
||||
return `<h${lvl} id="${id}">${title}</h${lvl}>`;
|
||||
});
|
||||
|
||||
// Regel D: Das schnelle, solitäre # für H1 (# Titel #)
|
||||
html = html.replace(/#([^#]+)#/g, (match, title) => {
|
||||
const id = this._slugify(title);
|
||||
this.headings.push({ level: 1, text: title, id: id });
|
||||
return `<h1 id="${id}">${title}</h1>`;
|
||||
});
|
||||
|
||||
// 3. STANDARD FLUSS-FORMATIERUNGEN
|
||||
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, '<u>$1</u>'); // Unterstrichen
|
||||
html = html.replace(/~([^~]+)~/g, '<del>$1</del>'); // Durchgestrichen
|
||||
html = html.replace(/=([^=]+)=/g, '<mark>$1</mark>'); // Highlight
|
||||
html = html.replace(/\^([^^]+)\^/g, '<sup>$1</sup>'); // Hochgestellt
|
||||
html = html.replace(/°([^°]+)°/g, '<sub>$1</sub>'); // Tiefgestellt
|
||||
html = html.replace(/`([^`]+)`/g, '<code>$1</code>'); // Inline-Code
|
||||
|
||||
// 4. AUSRICHTUNG & EINRÜCKUNG (Basiszeichen '>')
|
||||
html = html.replace(/>l ([^>]+)>/g, '<div style="text-align: left;">$1</div>');
|
||||
html = html.replace(/>r ([^>]+)>/g, '<div style="text-align: right;">$1</div>');
|
||||
html = html.replace(/>c ([^>]+)>/g, '<div style="text-align: center;">$1</div>');
|
||||
html = html.replace(/>j ([^>]+)>/g, '<div style="text-align: justify;">$1</div>');
|
||||
html = html.replace(/>tt ([^>]+)>/g, '<div style="margin-left: 4em;">$1</div>');
|
||||
html = html.replace(/>t ([^>]+)>/g, '<div style="margin-left: 2em;">$1</div>');
|
||||
|
||||
// 5. LINKS & MEDIEN
|
||||
// Bilder mit definierter Breite: 
|
||||
html = html.replace(/!\[([^\]]+)\s+w:(\d+)\]\(([^)]+)\)/g, '<img src="$3" alt="$1" style="width: $2px; height: auto;">');
|
||||
// Standard Bilder: 
|
||||
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>');
|
||||
// Standard-Links: [Text](URL)
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
|
||||
|
||||
// 6. FUSSNOTEN (Manuell ^1[...]^ und Automatisch ^x[...]^)
|
||||
html = html.replace(/\^x\[([^\]]+)\]\^/g, '<span class="footnote-auto" title="$1">[*]</span>'); // Logik für Fußnoten-Endleiste optional
|
||||
html = html.replace(/\^(\d+)\[([^\]]+)\]\^/g, '<sup class="footnote-manual" title="$2">[$1]</sup>');
|
||||
|
||||
// 7. ESCAPE ZURÜCKWANDELN
|
||||
html = html.replace(//g, (match, code) => String.fromCharCode(parseInt(code)));
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERN: Errechnet die nächste fortlaufende Kapitelnummer (z.B. "1.2.1.")
|
||||
*/
|
||||
_getAutoNumber(level) {
|
||||
let idx = level - 1;
|
||||
this.counters[idx]++;
|
||||
// Alle untergeordneten Ebenen radikal auf 0 zurücksetzen
|
||||
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);
|
||||
return activeParts.join('.') + '.';
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERN: Macht aus Text eine URL-konforme ID (Anker für das TOC)
|
||||
*/
|
||||
_slugify(text) {
|
||||
return text.toLowerCase()
|
||||
.replace(/[^a-z0-9\s-]/g, '') // Entferne Sonderzeichen
|
||||
.replace(/\s+/g, '-'); // Ersetze Leerzeichen durch Bindestriche
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERN: Erzeugt die fertige HTML-Liste des TOC und injiziert sie in den Platzhalter
|
||||
*/
|
||||
_injectTOC(html) {
|
||||
// Falls kein TOC-Block deklariert wurde oder keine Überschriften da sind, Platzhalter entfernen
|
||||
if (this.headings.length === 0) {
|
||||
return html.replace('', '');
|
||||
}
|
||||
|
||||
let tocListHtml = '<div class="simonup-toc">\n<ul>\n';
|
||||
let currentLevel = 1;
|
||||
|
||||
for (const heading of this.headings) {
|
||||
if (heading.level > currentLevel) {
|
||||
tocListHtml += '<ul>\n'.repeat(heading.level - currentLevel);
|
||||
} else if (heading.level < currentLevel) {
|
||||
tocListHtml += '</ul>\n'.repeat(currentLevel - heading.level);
|
||||
}
|
||||
currentLevel = heading.level;
|
||||
|
||||
tocListHtml += `<li><a href="#${heading.id}">${heading.text}</a></li>\n`;
|
||||
}
|
||||
|
||||
if (currentLevel > 1) {
|
||||
tocListHtml += '</ul>\n'.repeat(currentLevel - 1);
|
||||
}
|
||||
tocListHtml += '</ul>\n</div>';
|
||||
|
||||
return html.replace('', tocListHtml);
|
||||
}
|
||||
|
||||
/**
|
||||
* INTERN: Analysiert leere Zeilen, um Absätze (<p>) und Zeilenumbrüche (<br>) zu trennen
|
||||
*/
|
||||
_processParagraphs(elements) {
|
||||
let processed = [];
|
||||
let paragraphBuffer = [];
|
||||
|
||||
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')) {
|
||||
if (paragraphBuffer.length > 0) {
|
||||
processed.push(`<p>${paragraphBuffer.join('<br>')}</p>`);
|
||||
paragraphBuffer = [];
|
||||
}
|
||||
processed.push(element);
|
||||
} else if (element.trim() === '') {
|
||||
// Bei einer echten Leerzeile (2x Enter) wird der Absatz gebunden
|
||||
if (paragraphBuffer.length > 0) {
|
||||
processed.push(`<p>${paragraphBuffer.join('<br>')}</p>`);
|
||||
paragraphBuffer = [];
|
||||
}
|
||||
} else {
|
||||
paragraphBuffer.push(element);
|
||||
}
|
||||
}
|
||||
|
||||
if (paragraphBuffer.length > 0) {
|
||||
processed.push(`<p>${paragraphBuffer.join('<br>')}</p>`);
|
||||
}
|
||||
|
||||
return processed.join('\n');
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue