Files
Swiftmark/renderer/fallback.js
T
2026-11-11 00:08:55 +00:00

485 lines
20 KiB
JavaScript

// Rough local wikitext renderer. Used only when a wiki's own API is not available.
// It covers common markup. It does not expand templates or run parser functions.
(function (root) {
'use strict';
const DEFAULT_CSS = [
'html{background:#fff}',
'body{margin:0;color:#202122;font:14px/1.6 "Segoe UI",system-ui,sans-serif;background:#fff}',
'.wn-page{padding:16px 24px;max-width:960px}',
'h1.firstHeading{font:normal 1.8em/1.3 Georgia,"Times New Roman",serif;margin:0 0 .6em;padding:0;border-bottom:1px solid #a2a9b1}',
'.wn-page h1,.wn-page h2{font-family:Georgia,"Times New Roman",serif;font-weight:normal;border-bottom:1px solid #a2a9b1;margin:1em 0 .25em;padding:0}',
'.wn-page h1{font-size:1.8em}.wn-page h2{font-size:1.5em}',
'.wn-page h3,.wn-page h4,.wn-page h5,.wn-page h6{font-weight:bold;margin:.8em 0 .2em;border:0}',
'.wn-page h3{font-size:1.2em}.wn-page h4{font-size:1.05em}.wn-page h5,.wn-page h6{font-size:1em}',
'p{margin:.5em 0}',
'ul,ol{margin:.3em 0 .5em 1.6em;padding:0}',
'dl{margin:.3em 0}dd{margin-left:1.6em}',
'a.wn-link{color:#36c;cursor:pointer;text-decoration:none}a.wn-link:hover{text-decoration:underline}',
'a.wn-ext{color:#36c}',
'.wikitable{background:#f8f9fa;color:#202122;margin:1em 0;border:1px solid #a2a9b1;border-collapse:collapse}',
'.wikitable>tbody>tr>th,.wikitable>tbody>tr>td,.wikitable>tr>th,.wikitable>tr>td{border:1px solid #a2a9b1;padding:.2em .4em}',
'.wikitable>tbody>tr>th,.wikitable>tr>th{background:#eaecf0;text-align:center}',
'caption{font-weight:bold;padding:.3em}',
'.wn-tmpl{background:#fef6e7;border:1px dashed #c8a24a;padding:0 .3em;font-size:.9em;color:#6b4e00}',
'.wn-fig{display:inline-block;vertical-align:top;max-width:100%;background:#eaecf0;border:1px dashed #a2a9b1;color:#54595d;font-size:.85em;line-height:1.35}',
'.wn-fig .wn-box{display:flex;align-items:center;justify-content:center;min-height:90px;padding:.4em;text-align:center;background:repeating-linear-gradient(45deg,#f3f4f6,#f3f4f6 8px,#eaecf0 8px,#eaecf0 16px)}',
'.wn-fig.wn-video .wn-box{min-height:140px;background:#2b2e33;color:#dde}',
'.wn-fig.wn-audio .wn-box{min-height:34px;background:#eef1f6}',
'.wn-fig.wn-framed{background:#f8f9fa;border:1px solid #c8ccd1;padding:3px}',
'.wn-fig .wn-cap{display:block;padding:.3em .5em;color:#202122;background:#f8f9fa;border-top:1px solid #c8ccd1;font-size:.95em;text-align:left}',
'.wn-l{float:left;margin:.3em 1em .5em 0}.wn-r{float:right;margin:.3em 0 .5em 1em}.wn-c{display:block;margin:.5em auto}',
'.wn-img{background:#eaecf0;border:1px dashed #a2a9b1;padding:0 .3em;font-size:.9em;color:#54595d}',
'sup.wn-ref a{color:#36c;cursor:pointer;text-decoration:none}',
'.wn-refs ol{font-size:.9em}',
'.wn-cats{margin-top:2em;padding:6px 10px;border:1px solid #a2a9b1;background:#f8f9fa;font-size:.9em}',
'pre{background:#f8f9fa;border:1px solid #eaecf0;padding:.5em;white-space:pre-wrap;font:13px/1.4 Consolas,monospace}',
'hr{border:0;border-top:1px solid #a2a9b1;margin:.8em 0}',
'blockquote{margin:.8em 0 .8em 1.6em;padding-left:.8em;border-left:3px solid #c8ccd1}'
].join('\n');
const ALLOWED_ATTR = new Set(['class', 'style', 'colspan', 'rowspan', 'align', 'valign', 'width', 'height',
'border', 'cellpadding', 'cellspacing', 'bgcolor', 'title', 'id', 'dir', 'lang', 'data-swm']);
function esc(s) {
return s.replace(/&(?!#?\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function escAttr(s) {
return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function unamp(s) {
return s.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"');
}
function sanitizeAttrs(str) {
if (!str) return '';
let out = '';
const re = /([A-Za-z][\w-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g;
let m;
while ((m = re.exec(str))) {
const name = m[1].toLowerCase();
if (!ALLOWED_ATTR.has(name)) continue;
const val = unamp(m[2] !== undefined ? m[2] : (m[3] !== undefined ? m[3] : (m[4] || '')));
if (/url\s*\(|expression|javascript:|behavior|-moz-binding/i.test(val)) continue;
out += ' ' + name + '="' + escAttr(val) + '"';
}
return out;
}
function stash(ctx, html) {
ctx.stash.push(html);
return '' + (ctx.stash.length - 1) + '';
}
function unstash(ctx, s) {
let prev;
let n = 0;
do {
prev = s;
s = s.replace(/(\d+)/g, (m, i) => ctx.stash[+i]);
} while (s !== prev && ++n < 25);
return s;
}
function quotes(s) {
s = s.replace(/'''''(.+?)'''''/g, '<b><i>$1</i></b>');
s = s.replace(/'''(.+?)'''/g, '<b>$1</b>');
s = s.replace(/''(.+?)''/g, '<i>$1</i>');
return s;
}
const AUDIO_EXT = /\.(ogg|oga|mp3|wav|flac|opus|m4a|mid)$/i;
const VIDEO_EXT = /\.(webm|ogv|mp4|mov|mpg|mpeg)$/i;
// A grey place-marker for a File: link that honours alignment, size, thumb/frame and caption.
function mediaBox(ctx, target, opts, quotes) {
const name = target.replace(/^[^:]+:/, '').trim();
let type = '';
let align = '';
let width = '';
let cap = '';
opts.forEach((raw) => {
const p = raw.trim();
const l = p.toLowerCase();
let m;
if (l === 'thumb' || l === 'thumbnail' || l === 'frame' || l === 'frameless') type = l === 'thumbnail' ? 'thumb' : l;
else if (l === 'left' || l === 'right' || l === 'center' || l === 'none') align = l;
else if ((m = /^(\d+)px$/.exec(l))) width = m[1];
else if ((m = /^(\d+)x\d+px$/.exec(l))) width = m[1];
else if (/^(border|upright|link=|alt=|page=|start=|end=|class=|lang=|loop|muted|autoplay|nocontrols|baseline|sub|super|top|text-top|middle|bottom|text-bottom)/i.test(p)) { /* ignored */ }
else if (p) cap = p;
});
const kind = AUDIO_EXT.test(name) ? 'audio' : (VIDEO_EXT.test(name) ? 'video' : 'picture');
const framed = type === 'thumb' || type === 'frame';
const label = (kind === 'audio' ? 'Sound: ' : (kind === 'video' ? 'Video: ' : 'Picture: ')) + esc(name) + (width && type !== 'frame' ? ' (' + width + 'px)' : '');
const cls = ['wn-fig', 'wn-' + kind];
if (framed) cls.push('wn-framed');
if (align === 'left') cls.push('wn-l');
else if (align === 'right' || (framed && align !== 'none' && align !== 'center' && align !== 'left')) cls.push('wn-r');
else if (align === 'center') cls.push('wn-c');
let w = width;
if (!w && framed) w = kind === 'audio' ? '300' : '220';
const style = w && type !== 'frame' ? ' style="width:' + w + 'px"' : '';
const capHtml = framed && cap ? '<span class="wn-cap">' + quotes(esc(cap)) + '</span>' : '';
return '<span class="' + cls.join(' ') + '"' + style + '><span class="wn-box">' + label + '</span>' + capHtml + '</span>';
}
// EmbedVideo style embeds: {{#ev:service|id|width|align|caption}} and {{#evu:url|alignment=..}}
function embedBox(ctx, name, params, quotes) {
const isUrl = /^#evu$/i.test(name);
let align = '';
let cap = '';
let dims = '';
let what = '';
if (isUrl) {
what = (params[0] || '').trim();
params.slice(1).forEach((p) => {
const m = /^\s*([a-z]+)\s*=\s*([\s\S]*)$/i.exec(p);
if (!m) return;
const k = m[1].toLowerCase();
if (k === 'alignment' || k === 'align') align = m[2].trim().toLowerCase();
else if (k === 'dimensions') dims = m[2].trim();
else if (k === 'description') cap = m[2].trim();
});
} else {
what = (params[0] || '').trim() + ' ' + (params[1] || '').trim();
dims = (params[2] || '').trim();
align = (params[3] || '').trim().toLowerCase();
cap = (params[4] || '').trim();
}
const audio = /soundcloud|bandcamp|spotify/i.test(what) || AUDIO_EXT.test(what);
const cls = ['wn-fig', 'wn-embed', audio ? 'wn-audio' : 'wn-video'];
if (cap) cls.push('wn-framed');
if (align === 'left') cls.push('wn-l'); else if (align === 'right') cls.push('wn-r'); else if (align === 'center') cls.push('wn-c');
const w = (/^(\d+)/.exec(dims) || [])[1] || (audio ? '300' : '320');
return '<span class="' + cls.join(' ') + '" style="width:' + Math.min(+w, 640) + 'px"><span class="wn-box">' +
(audio ? 'Sound embed: ' : 'Video embed: ') + esc(what.length > 60 ? what.slice(0, 57) + '...' : what) + '</span>' +
(cap ? '<span class="wn-cap">' + quotes(esc(cap)) + '</span>' : '') + '</span>';
}
function inline(ctx, raw) {
let s = esc(raw);
s = s.replace(/&lt;(\/?)(b|i|u|s|em|strong|sup|sub|small|big|code|tt|del|ins|strike|center|span|div|p|blockquote|abbr|cite|kbd|var|samp|font|mark|q)((?:\s[^<>]*?)?)\s*(\/?)&gt;/gi,
(m, slash, tag, attrs, self) => {
tag = tag.toLowerCase();
if (slash) return '</' + tag + '>';
return '<' + tag + sanitizeAttrs(attrs) + (self ? '/' : '') + '>';
});
s = s.replace(/&lt;br\s*\/?&gt;/gi, '<br>');
// internal links, images, categories
s = s.replace(/\[\[([^\[\]]+?)\]\]([A-Za-z]*)/g, (m, inner, trail) => {
const parts = inner.split('|');
let target = parts[0].trim();
const lead = target.charAt(0) === ':';
if (lead) target = target.slice(1);
const nsm = /^([^:]+):/.exec(target);
const ns = nsm ? nsm[1].toLowerCase() : '';
if (!lead && ns === 'category') {
ctx.cats.push(target.replace(/^[^:]+:/, '').trim());
return '';
}
if (!lead && (ns === 'file' || ns === 'image')) {
return stash(ctx, mediaBox(ctx, target, parts.slice(1), quotes));
}
let text;
if (parts.length > 1 && parts[1].trim() !== '') text = parts.slice(1).join('|');
else if (parts.length > 1) text = target.replace(/^[^:]+:/, '');
else text = target;
return stash(ctx, '<a class="wn-link" title="' + target.replace(/"/g, '&quot;') + '">' + quotes(text) + trail + '</a>');
});
// external links with and without labels
s = s.replace(/\[((?:https?|ftp):\/\/[^\s\]]+)(?:\s+([^\]]*))?\]/gi, (m, url, label) => {
if (label === undefined || label === '') {
ctx.extN++;
label = '[' + ctx.extN + ']';
}
return stash(ctx, '<a class="wn-ext" href="' + url.replace(/"/g, '%22') + '">' + quotes(label) + '</a>');
});
// bare urls
s = s.replace(/(^|[^\w"'=>])((?:https?|ftp):\/\/[^\s<>"]+)/gi, (m, pre, url) => {
let tail = '';
const t = /[.,;:!?)]+$/.exec(url);
if (t) { tail = t[0]; url = url.slice(0, url.length - tail.length); }
return pre + stash(ctx, '<a class="wn-ext" href="' + url.replace(/"/g, '%22') + '">' + url + '</a>') + tail;
});
s = s.replace(/__[A-Z]+__/g, '');
return quotes(s);
}
function splitCell(part) {
const m = /^([^|\[\]{}]*?)\|(?!\|)([\s\S]*)$/.exec(part);
if (m && /^\s*(?:[A-Za-z][\w-]*\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"']+)\s*)+$/.test(m[1])) {
return { attrs: m[1], content: m[2] };
}
return { attrs: '', content: part };
}
function renderTable(ctx, lines) {
let html = '<table' + sanitizeAttrs(lines[0].trim().slice(2)) + '>';
let rowOpen = false;
let cur = null;
let depth = 0;
const flushCell = () => {
if (cur) {
let inner = renderBlocks(ctx, cur.buf.join('\n').trim());
const single = /^<p>([\s\S]*)<\/p>$/.exec(inner);
if (single && single[1].indexOf('<p>') < 0) inner = single[1];
html += '<' + cur.tag + sanitizeAttrs(cur.attrs) + '>' + inner + '</' + cur.tag + '>';
cur = null;
}
};
const openRow = (attrs) => {
flushCell();
if (rowOpen) html += '</tr>';
html += '<tr' + sanitizeAttrs(attrs) + '>';
rowOpen = true;
};
for (let k = 1; k < lines.length; k++) {
const ln = lines[k];
const t = ln.trim();
if (/^\{\|/.test(t)) { depth++; if (cur) cur.buf.push(t); continue; }
if (/^\|\}/.test(t)) {
if (depth > 0) { depth--; if (cur) cur.buf.push(t); continue; }
break;
}
if (depth > 0) { if (cur) cur.buf.push(t); continue; }
if (/^\|\+/.test(t)) {
flushCell();
html += '<caption>' + inline(ctx, t.slice(2).trim()) + '</caption>';
continue;
}
if (/^\|-/.test(t)) { openRow(t.replace(/^\|-+/, '')); continue; }
if (t.charAt(0) === '!' || t.charAt(0) === '|') {
if (!rowOpen) openRow('');
flushCell();
const isHead = t.charAt(0) === '!';
const body = t.slice(1);
const parts = isHead ? body.split(/!!|\|\|/) : body.split('||');
parts.forEach((p, idx) => {
const c = splitCell(p);
cur = { tag: isHead ? 'th' : 'td', attrs: c.attrs, buf: [c.content] };
if (idx < parts.length - 1) flushCell();
});
continue;
}
if (cur) cur.buf.push(t);
}
flushCell();
if (rowOpen) html += '</tr>';
return html + '</table>';
}
function tagOf(ch) { return ch === '*' ? 'ul' : (ch === '#' ? 'ol' : 'dl'); }
function renderList(ctx, items, depth) {
let html = '';
let i = 0;
while (i < items.length) {
const tag = tagOf(items[i].prefix.charAt(depth));
const run = [];
let j = i;
while (j < items.length && tagOf(items[j].prefix.charAt(depth)) === tag) { run.push(items[j]); j++; }
html += '<' + tag + '>' + renderRun(ctx, run, depth) + '</' + tag + '>';
i = j;
}
return html;
}
function renderRun(ctx, run, depth) {
let html = '';
let i = 0;
while (i < run.length) {
const it = run[i];
const child = [];
let j = i + 1;
while (j < run.length && run[j].prefix.length > depth + 1) { child.push(run[j]); j++; }
const ch = it.prefix.charAt(depth);
const itemTag = (ch === '*' || ch === '#') ? 'li' : (ch === ';' ? 'dt' : 'dd');
const direct = it.prefix.length === depth + 1;
const nested = direct ? child : [it].concat(child);
if (direct && ch === ';' && / : /.test(it.text)) {
const idx = it.text.indexOf(' : ');
html += '<dt>' + inline(ctx, it.text.slice(0, idx)) + '</dt><dd>' + inline(ctx, it.text.slice(idx + 3)) +
(nested.length ? renderList(ctx, nested, depth + 1) : '') + '</dd>';
} else {
html += '<' + itemTag + '>' + (direct ? inline(ctx, it.text) : '') +
(nested.length ? renderList(ctx, nested, depth + 1) : '') + '</' + itemTag + '>';
}
i = j;
}
return html;
}
function renderBlocks(ctx, text) {
const lines = text.split('\n');
const out = [];
let para = [];
let i = 0;
const flush = () => {
if (!para.length) return;
const h = inline(ctx, para.join('\n'));
const only = /^(\d+)$/.exec(h.trim());
if (only && /^<(pre|blockquote|div|table|ul|ol|h\d)/i.test(ctx.stash[+only[1]])) out.push(h.trim());
else out.push('<p>' + h + '</p>');
para = [];
};
while (i < lines.length) {
const line = lines[i];
const tl = line.trim();
if (/^\{\|/.test(tl)) {
flush();
let depth = 0;
let j = i;
const collected = [];
do {
const t = lines[j].trim();
if (/^\{\|/.test(t)) depth++;
if (/^\|\}/.test(t)) depth--;
collected.push(lines[j]);
j++;
} while (j < lines.length && depth > 0);
out.push(renderTable(ctx, collected));
i = j;
continue;
}
const hm = /^(={1,6})\s*(.*?)\s*\1\s*$/.exec(tl);
if (hm && hm[2]) {
flush();
const lv = hm[1].length;
out.push('<h' + lv + '>' + inline(ctx, hm[2]) + '</h' + lv + '>');
i++;
continue;
}
if (/^-{4,}\s*$/.test(tl)) { flush(); out.push('<hr>'); i++; continue; }
if (/^[*#:;]/.test(line)) {
flush();
const items = [];
while (i < lines.length && /^[*#:;]/.test(lines[i])) {
const m = /^([*#:;]+)\s*(.*)$/.exec(lines[i]);
items.push({ prefix: m[1], text: m[2] });
i++;
}
out.push(renderList(ctx, items, 0));
continue;
}
if (/^ /.test(line) && tl !== '') {
flush();
const pre = [];
while (i < lines.length && /^ /.test(lines[i]) && lines[i].trim() !== '') { pre.push(lines[i].slice(1)); i++; }
out.push('<pre>' + inline(ctx, pre.join('\n')) + '</pre>');
continue;
}
if (tl === '') { flush(); i++; continue; }
if (/^<\/?(div|center|blockquote)[\s>]/i.test(tl)) {
flush();
out.push(inline(ctx, tl));
i++;
continue;
}
const lone = /^(\d+)$/.exec(tl);
if (lone && /^(<(pre|blockquote|div|table|ul|ol|h\d)|@@REFS@@)/i.test(ctx.stash[+lone[1]])) {
flush();
out.push(tl);
i++;
continue;
}
para.push(line);
i++;
}
flush();
return out.join('\n');
}
function refToken(ctx, attrs, content) {
const nm = attrs ? /name\s*=\s*"?([^"\s\/>]+)/i.exec(attrs) : null;
const name = nm ? nm[1] : '';
let idx = -1;
if (name && ctx.refNames[name] !== undefined) {
idx = ctx.refNames[name];
if (content && !ctx.refs[idx].content) ctx.refs[idx].content = content;
} else {
ctx.refs.push({ name, content: content || '' });
idx = ctx.refs.length - 1;
if (name) ctx.refNames[name] = idx;
}
return stash(ctx, '<sup class="wn-ref"><a>[' + (idx + 1) + ']</a></sup>');
}
function renderWikitext(src, title) {
const ctx = { stash: [], refs: [], refNames: {}, cats: [], extN: 0 };
let t = String(src || '').replace(/\r\n?/g, '\n').replace(/[]/g, '');
t = t.replace(/<!--[\s\S]*?-->/g, '');
t = t.replace(/<nowiki>([\s\S]*?)<\/nowiki>/gi, (m, c) => stash(ctx, esc(c)));
t = t.replace(/<nowiki\s*\/>/gi, '');
t = t.replace(/<(pre|source|syntaxhighlight)(?:\s[^>]*)?>([\s\S]*?)<\/\1>/gi,
(m, tag, c) => stash(ctx, '<pre>' + esc(c.replace(/^\n/, '')) + '</pre>'));
let guard = 0;
while (/\{\{[^{}]*\}\}/.test(t) && guard++ < 60) {
t = t.replace(/\{\{([^{}]*)\}\}/g, (m, c) => {
const name = c.split('|')[0].trim();
const up = name.toUpperCase();
if (up === 'PAGENAME' || up === 'FULLPAGENAME' || up === 'BASEPAGENAME') return stash(ctx, esc(title || ''));
if (/^DEFAULTSORT:/i.test(name)) return '';
if (/^#evu?$/i.test(name.replace(/:$/, '')) || /^#evu?:/i.test(name)) {
const nm = /^#evu?/i.exec(name)[0];
const first = name.replace(/^#evu?:/i, '');
const ps = c.split('|');
ps[0] = first;
return stash(ctx, embedBox(ctx, nm, ps, quotes));
}
return stash(ctx, '<span class="wn-tmpl" title="Templates are not expanded in the rough preview">{{' + esc(name) + '}}</span>');
});
}
t = t.replace(/<ref(\s[^>]*?)?\/>/gi, (m, attrs) => refToken(ctx, attrs, null));
t = t.replace(/<ref(\s[^>]*)?>([\s\S]*?)<\/ref>/gi, (m, attrs, c) => refToken(ctx, attrs, c));
let hasRefsTag = false;
t = t.replace(/<references\s*\/?>(?:\s*<\/references>)?/gi, () => { hasRefsTag = true; return stash(ctx, '@@REFS@@'); });
let html = unstash(ctx, renderBlocks(ctx, t));
let refsHtml = '';
if (ctx.refs.length) {
const lis = ctx.refs.map((r) => '<li>' + unstash(ctx, inline(ctx, r.content.trim())) + '</li>').join('');
refsHtml = '<ol class="references">' + lis + '</ol>';
}
if (hasRefsTag) html = html.replace('@@REFS@@', refsHtml);
else if (refsHtml) html += '<div class="wn-refs"><h2>References</h2>' + refsHtml + '</div>';
const seen = {};
const cats = ctx.cats.filter((c) => (seen[c] ? false : (seen[c] = true)));
if (cats.length) html += '<div class="wn-cats">Categories: ' + cats.map(esc).join(' | ') + '</div>';
return html;
}
function buildDocument(text, title) {
return '<!DOCTYPE html><html><head><meta charset="utf-8"><style>' + DEFAULT_CSS + '</style></head><body>' +
'<div class="wn-page mw-body-content"><h1 class="firstHeading">' + esc(title || '') + '</h1>' +
'<div class="mw-parser-output">' + renderWikitext(text, title) + '</div></div></body></html>';
}
const api = { buildDocument, renderWikitext };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.WikiFallback = api;
})(typeof window !== 'undefined' ? window : this);