SimonUp/Core.js
2026-07-09 18:00:25 +02:00

414 lines
No EOL
16 KiB
JavaScript

/**
* SimonUp Core Compiler (Core.js) - Version 1.2
* 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)
*/
use(plugin) {
this.plugins.push(plugin);
return this;
}
/**
* Hauptfunktion: Wandelt SimonUp-Text (.up) in valides HTML um
*/
parse(text) {
this.headings = [];
this.counters = [0, 0, 0, 0, 0, 0];
let html = text;
// "Before"-Plugins ausführen
for (const plugin of this.plugins) {
if (plugin.before) html = plugin.before(html);
}
html = this._parseBlocks(html);
html = this._injectTOC(html);
// "After"-Plugins ausführen
for (const plugin of this.plugins) {
if (plugin.after) html = plugin.after(html);
}
return html;
}
/**
* INTERN: Verarbeitet strukturelle Blöcke und freie Strukturen zeilenweise
*/
_parseBlocks(text) {
const lines = text.replace(/\r\n/g, '\n').split('\n');
let result = [];
let inBlock = false;
let blockType = null;
let blockMeta = "";
let blockBuffer = [];
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
// 1. Block-Start erkennen (&typ meta)
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;
}
// 2. Block-Ende erkennen (einzelnes &)
if (inBlock && line.trim() === '&') {
result.push(this._renderBlock(blockType, blockMeta, blockBuffer));
inBlock = false;
blockType = null;
blockMeta = "";
continue;
}
// 3. Inhalt sammeln oder freie Zeilen verarbeiten
if (inBlock) {
blockBuffer.push(line);
} else {
let trimmed = line.trim();
if (trimmed === '___') {
// Horizontale Linie
result.push('<hr>');
} else if (trimmed.startsWith('- ')) {
// Freier Listenpunkt (Ungeordnet)
result.push(`<ul-item>${this._parseInline(line.replace(/^\s*-\s+/, ''))}</ul-item>`);
} else if (/^\d+\.\s+/.test(trimmed)) {
// Freier Listenpunkt (Nummeriert)
let cleanLine = line.replace(/^\s*\d+\.\s+/, '');
result.push(`<ol-item>${this._parseInline(cleanLine)}</ol-item>`);
} else {
// Normaler Fließtext
result.push(this._parseInline(line));
}
}
}
// Freie Listenpunkte zusammenfassen und Absätze bauen
return this._processParagraphsAndLists(result);
}
/**
* INTERN: Erzeugt das HTML für einen geschlossenen Block
*/
_renderBlock(type, meta, lines) {
const content = lines.join('\n');
switch (type) {
case 'toc':
// Platzhalter für das spätere Injektions-Verfahren hinterlassen
let tocWrapper = ``;
if (meta || content.trim()) {
tocWrapper = `<div class="simonup-toc-wrapper">\n`;
if (meta) tocWrapper += `<h2>${meta}</h2>\n`;
if (content.trim()) {
const intro = lines.map(l => this._parseInline(l)).join('<br>');
tocWrapper += `<p class="toc-intro">${intro}</p>\n`;
}
tocWrapper += `\n</div>`;
}
return tocWrapper;
case 'c':
const langClass = meta ? ` class="language-${meta}"` : '';
const escapedCode = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return `<pre><code${langClass}>${escapedCode}</code></pre>`;
case 'q':
return `<blockquote>${lines.map(l => this._parseInline(l)).join('<br>')}</blockquote>`;
case 'b':
return `<div class="bible-block">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`;
case 'f':
return `<details>\n<summary>${meta || 'Details'}</summary>\n<p>${lines.map(l => this._parseInline(l)).join('<br>')}</p>\n</details>`;
case 'i':
return `<div class="infobox" style="border-left: 4px solid ${meta || '#ff6347'}; padding: 10px; margin: 10px 0; background: #f8f9fa;">\n${lines.map(l => this._parseInline(l)).join('<br>')}\n</div>`;
case 't':
return this._renderTable(meta, lines);
case '>':
return `<div style="margin-left: 2em;">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`;
case '>>':
return `<div style="margin-left: 4em;">${lines.map(l => this._parseInline(l)).join('<br>')}</div>`;
default:
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';
let currentCells = [];
let cellBuffer = [];
// Parsing-Logik für Multi-line-Zellen via Pipe (|)
for (let line of lines) {
let parts = line.split('|');
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
if (i === parts.length - 1) {
if (part.trim() !== '') {
cellBuffer.push(part);
}
if (line.endsWith('|') && cellBuffer.length > 0) {
currentCells.push(cellBuffer.join('\n'));
cellBuffer = [];
}
} else {
cellBuffer.push(part);
currentCells.push(cellBuffer.join('\n'));
cellBuffer = [];
}
}
if (line.endsWith('|') && currentCells.length > 0) {
tableHtml += '<tr>\n' + currentCells.map(c => `<td>${this._parseInline(c.trim()).replace(/\n/g, '<br>')}</td>`).join('\n') + '\n</tr>\n';
currentCells = [];
}
}
tableHtml += '</table>';
return tableHtml;
}
/**
* INTERN: Verarbeitet Fluss-Formatierungen (Inline) mittels V1.2-RegEx
*/
_parseInline(text) {
if (!text) return '';
let html = text;
// 1. ESCAPE: Steuerzeichen sichern (Schutz vor doppelter Evaluierung)
const escapes = [];
html = html.replace(/\\(.)/g, (match, char) => {
escapes.push(char);
return ``;
});
// 2. UNIVERSAL-RESET: Verarbeitet den "//"-Reset im Satz
html = html.replace(/\/\/(\s|$)/g, '$1');
// 3. ÜBERSCHRIFTEN (V1.2 konform: Startet mit X#, schließt optional mit /# oder Zeilenende)
const processHeading = (pattern, callback) => {
let match;
while ((match = pattern.exec(html)) !== null) {
const fullMatch = match[0];
const level = parseInt(match[1]);
const titleAndRest = match[2];
// Schließzeichen /# suchen, sonst bis Zeilenende parsen
let title = titleAndRest;
let rest = "";
const closeIdx = titleAndRest.indexOf('/#');
if (closeIdx !== -1) {
title = titleAndRest.substring(0, closeIdx);
rest = titleAndRest.substring(closeIdx + 2);
}
const result = callback(level, title.trim(), rest);
html = html.substring(0, match.index) + result + html.substring(match.index + fullMatch.length);
}
};
// 3a. Automatische Nummerierung (1x# bis 6x#)
processHeading(/^([1-6])x#\s*(.*)/g, (level, title, rest) => {
const numStr = this._getAutoNumber(level);
const fullTitle = `${numStr} ${title}`;
const id = this._slugify(fullTitle);
this.headings.push({ level, text: fullTitle, id });
return `<h${level} id="${id}">${fullTitle}</h${level}>${rest}`;
});
// 3b. Nicht im TOC erwünscht (1-# bis 6-#)
processHeading(/^([1-6])-#\s*(.*)/g, (level, title, rest) => {
return `<h${level}>${title}</h${level}>${rest}`;
});
// 3c. Standard-Überschrift (1# bis 6#)
processHeading(/^([1-6])#\s*(.*)/g, (level, title, rest) => {
const id = this._slugify(title);
this.headings.push({ level, text: title, id });
return `<h${level} id="${id}">${title}</h${level}>${rest}`;
});
// 4. INLINE SCHLIESS-LOGIK (V1.2: ZeichenText/Zeichen)
const inlineRules = [
{ tag: 'strong', symbol: '\\*\\*' }, // Fett (**Text/**)
{ tag: 'span style="font-weight: 500;"', symbol: '\\*' }, // Medium (*Text/*)
{ tag: 'em', symbol: '%' }, // Kursiv (%Text/%)
{ tag: 'u', symbol: '_' }, // Unterstrichen (_Text/_)
{ tag: 'del', symbol: '~' }, // Durchgestrichen (~Text/~)
{ tag: 'mark', symbol: '=' }, // Highlight (=Text/=)
{ tag: 'sup', symbol: '\\^' }, // Hochgestellt (^Text/^)
{ tag: 'sub', symbol: '°' }, // Tiefgestellt (°Text/°)
{ tag: 'code', symbol: '`' } // Inline-Code (`Text/`)
];
inlineRules.forEach(rule => {
// Regulärer Match: Symbol -> Text -> /Symbol
let regex = new RegExp(`${rule.symbol}(.+?)\/${rule.symbol}`, 'g');
html = html.replace(regex, `<${rule.tag}>$1</${rule.tag.split(' ')[0]}>`);
// Fallback für Universal-Reset: Offenes Symbol bis zum let resetRegex = new RegExp(`${rule.symbol}(.+?)(?=)`, 'g');
html = html.replace(resetRegex, `<${rule.tag}>$1</${rule.tag.split(' ')[0]}>`);
});
html = html.replace(//g, ''); // Aufgeräumte Reset-Tags
// 5. AUSRICHTUNG IM FLUSS (>c Text />)
const alignMap = { l: 'left', r: 'right', c: 'center', j: 'justify' };
html = html.replace(/>([lrcj])\s+(.+?)\s*\/>/g, (m, dir, content) => {
return `<div style="text-align: ${alignMap[dir]};">${content}</div>`;
});
// 6. LINKS & MEDIEN
html = html.replace(/!\[([^\]]+)\s+w:(\d+)\]\(([^)]+)\)/g, '<img src="$3" alt="$1" style="width: $2px; height: auto;">');
html = html.replace(/!\[([^\]]+)\]\(([^)]+)\)/g, '<img src="$2" alt="$1">');
html = html.replace(/\[([^\]]+)\]\{([^}]+)\}/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
// 7. FUSSNOTEN
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>');
// 8. ESCAPES wiederherstellen
html = html.replace(//g, (match, idx) => escapes[idx]);
return html;
}
/**
* INTERN: Errechnet die nächste fortlaufende Kapitelnummer
*/
_getAutoNumber(level) {
let idx = level - 1;
this.counters[idx]++;
for (let i = idx + 1; i < 6; i++) this.counters[i] = 0;
let activeParts = this.counters.slice(0, level);
return activeParts.join('.') + '.';
}
/**
* INTERN: Macht aus Text eine URL-konforme ID
*/
_slugify(text) {
return text.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-');
}
/**
* INTERN: Erzeugt die fertige HTML-Liste des TOC und injiziert sie in den Block
*/
_injectTOC(html) {
if (!html.includes('')) return html;
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: Fasst freie Listen-Elemente zusammen und generiert Absätze (<p>)
*/
_processParagraphsAndLists(elements) {
let processed = [];
let paragraphBuffer = [];
let listBuffer = [];
let currentListType = null; // 'ul' oder 'ol'
const flushList = () => {
if (listBuffer.length > 0) {
processed.push(`<${currentListType}>\n` + listBuffer.map(item => ` <li>${item}</li>`).join('\n') + `\n</${currentListType}>`);
listBuffer = [];
currentListType = null;
}
};
const flushParagraph = () => {
if (paragraphBuffer.length > 0) {
processed.push(`<p>${paragraphBuffer.join('<br>')}</p>`);
paragraphBuffer = [];
}
};
for (let element of elements) {
let isUlItem = element.startsWith('<ul-item>');
let isOlItem = element.startsWith('<ol-item>');
if (isUlItem || isOlItem) {
flushParagraph();
let type = isUlItem ? 'ul' : 'ol';
let content = isUlItem ? element.replace(/<\/?ul-item>/g, '') : element.replace(/<\/?ol-item>/g, '');
if (currentListType && currentListType !== type) {
flushList();
}
currentListType = type;
listBuffer.push(content);
} else if (element.startsWith('<') && !/^(<a>|<strong>|<em>|<u>|<del>|<mark>|<sup>|<sub>|<span>|<code>|<img>|<h\d>)/i.test(element)) {
// Strukturelles Block-Element (z.B. <table>, <blockquote>)
flushList();
flushParagraph();
processed.push(element);
} else if (element.trim() === '') {
// Leerzeile bricht Listen und Absätze auf
flushList();
flushParagraph();
} else {
// Fließtext mündet im Absatz-Buffer
flushList();
paragraphBuffer.push(element);
}
}
flushList();
flushParagraph();
return processed.join('\n');
}
}