Upload files to "renderer"
This commit is contained in:
@@ -0,0 +1,484 @@
|
||||
// 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, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
function escAttr(s) {
|
||||
return s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
function unamp(s) {
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/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(/<(\/?)(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*(\/?)>/gi,
|
||||
(m, slash, tag, attrs, self) => {
|
||||
tag = tag.toLowerCase();
|
||||
if (slash) return '</' + tag + '>';
|
||||
return '<' + tag + sanitizeAttrs(attrs) + (self ? '/' : '') + '>';
|
||||
});
|
||||
s = s.replace(/<br\s*\/?>/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, '"') + '">' + 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);
|
||||
@@ -0,0 +1,431 @@
|
||||
// Formatting toolbar for the wikitext editor.
|
||||
// Every action edits the textarea through execCommand where possible so Ctrl+Z keeps working.
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const PALETTE = [
|
||||
['#000000', '#434343', '#666666', '#999999', '#b7b7b7', '#cccccc', '#d9d9d9', '#efefef', '#f3f3f3', '#ffffff'],
|
||||
['#980000', '#ff0000', '#ff9900', '#ffff00', '#00ff00', '#00ffff', '#4a86e8', '#0000ff', '#9900ff', '#ff00ff'],
|
||||
['#e6b8af', '#f4cccc', '#fce5cd', '#fff2cc', '#d9ead3', '#d0e0e3', '#c9daf8', '#cfe2f3', '#d9d2e9', '#ead1dc'],
|
||||
['#dd7e6b', '#ea9999', '#f9cb9c', '#ffe599', '#b6d7a8', '#a2c4c9', '#a4c2f4', '#9fc5e8', '#b4a7d6', '#d5a6bd'],
|
||||
['#cc4125', '#e06666', '#f6b26b', '#ffd966', '#93c47d', '#76a5af', '#6d9eeb', '#6fa8dc', '#8e7cc3', '#c27ba0'],
|
||||
['#a61c00', '#cc0000', '#e69138', '#f1c232', '#6aa84f', '#45818e', '#3c78d8', '#3d85c6', '#674ea7', '#a64d79']
|
||||
];
|
||||
|
||||
function init(opts) {
|
||||
const ed = opts.editor;
|
||||
const onEdit = opts.onEdit;
|
||||
|
||||
/* ---------- editing primitives ---------- */
|
||||
|
||||
function sel() { return [ed.selectionStart, ed.selectionEnd]; }
|
||||
|
||||
function insert(text) {
|
||||
ed.focus();
|
||||
let ok = false;
|
||||
try {
|
||||
ok = text === '' ? document.execCommand('delete') : document.execCommand('insertText', false, text);
|
||||
} catch (e) { ok = false; }
|
||||
if (!ok) {
|
||||
ed.setRangeText(text, ed.selectionStart, ed.selectionEnd, 'end');
|
||||
onEdit();
|
||||
}
|
||||
}
|
||||
|
||||
// Replace [a, b) with text, then select [selA, selB).
|
||||
function replaceRange(a, b, text, selA, selB) {
|
||||
ed.focus();
|
||||
ed.setSelectionRange(a, b);
|
||||
insert(text);
|
||||
if (selA !== undefined) ed.setSelectionRange(selA, selB);
|
||||
}
|
||||
|
||||
function lineRange() {
|
||||
const v = ed.value;
|
||||
const s = v.lastIndexOf('\n', ed.selectionStart - 1) + 1;
|
||||
let e = v.indexOf('\n', ed.selectionEnd);
|
||||
if (e < 0) e = v.length;
|
||||
return { s, e };
|
||||
}
|
||||
|
||||
/* ---------- wrap and unwrap ---------- */
|
||||
|
||||
function defaultDetect(v, s, e, before, after) {
|
||||
const text = v.slice(s, e);
|
||||
if (text.length >= before.length + after.length && text.startsWith(before) && text.endsWith(after)) return 'inside';
|
||||
if (v.slice(s - before.length, s) === before && v.slice(e, e + after.length) === after) return 'around';
|
||||
return null;
|
||||
}
|
||||
|
||||
function italicDetect(v, s, e) {
|
||||
const text = v.slice(s, e);
|
||||
const q = "'";
|
||||
if (text.length >= 4 && text.startsWith(q + q) && text.endsWith(q + q)) {
|
||||
const bothStart = text.startsWith(q.repeat(5));
|
||||
const bothEnd = text.endsWith(q.repeat(5));
|
||||
if ((bothStart && bothEnd) || (!text.startsWith(q.repeat(3)) && !text.endsWith(q.repeat(3)))) return 'inside';
|
||||
}
|
||||
if (v.slice(s - 2, s) === q + q && v.slice(e, e + 2) === q + q) {
|
||||
const bothBefore = v.slice(s - 5, s) === q.repeat(5);
|
||||
const bothAfter = v.slice(e, e + 5) === q.repeat(5);
|
||||
if ((bothBefore && bothAfter) || (v.slice(s - 3, s) !== q.repeat(3) && v.slice(e, e + 3) !== q.repeat(3))) return 'around';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toggleWrap(before, after, placeholder, detect) {
|
||||
const [s, e] = sel();
|
||||
const v = ed.value;
|
||||
const text = v.slice(s, e);
|
||||
const found = detect ? detect(v, s, e, before, after) : defaultDetect(v, s, e, before, after);
|
||||
if (found === 'inside') {
|
||||
const inner = text.slice(before.length, text.length - after.length);
|
||||
replaceRange(s, e, inner, s, s + inner.length);
|
||||
} else if (found === 'around') {
|
||||
replaceRange(s - before.length, e + after.length, text, s - before.length, s - before.length + text.length);
|
||||
} else {
|
||||
const inner = text || placeholder;
|
||||
replaceRange(s, e, before + inner + after, s + before.length, s + before.length + inner.length);
|
||||
}
|
||||
}
|
||||
|
||||
function bold() { toggleWrap("'''", "'''", 'bold text'); }
|
||||
function italic() { toggleWrap("''", "''", 'italic text', italicDetect); }
|
||||
|
||||
// Wrap in a span with one style property, or change or remove it when one is already there.
|
||||
function applySpan(prop, value) {
|
||||
const [s, e] = sel();
|
||||
const v = ed.value;
|
||||
const text = v.slice(s, e);
|
||||
const openAt = '<span style="' + prop + ':\\s*[^";]*;?">';
|
||||
const reStart = new RegExp('^' + openAt);
|
||||
const reEnd = new RegExp(openAt + '$');
|
||||
let a = s;
|
||||
let b = e;
|
||||
let inner = text;
|
||||
const m = reStart.exec(text);
|
||||
if (m && text.endsWith('</span>') && text.length > m[0].length + 6) {
|
||||
inner = text.slice(m[0].length, text.length - 7);
|
||||
} else {
|
||||
const pm = reEnd.exec(v.slice(0, s));
|
||||
if (pm && v.slice(e, e + 7) === '</span>') {
|
||||
a = s - pm[0].length;
|
||||
b = e + 7;
|
||||
}
|
||||
}
|
||||
if (!value) {
|
||||
replaceRange(a, b, inner, a, a + inner.length);
|
||||
return;
|
||||
}
|
||||
const open = '<span style="' + prop + ':' + value + '">';
|
||||
const body = inner || 'text';
|
||||
replaceRange(a, b, open + body + '</span>', a + open.length, a + open.length + body.length);
|
||||
}
|
||||
|
||||
// Block styles (alignment, size) live in one <div style="..."> around whole lines.
|
||||
const DIV_RE = /^<div style="([^"]*)">\n?([\s\S]*?)\n?<\/div>$/;
|
||||
|
||||
function parseStyle(str) {
|
||||
const map = {};
|
||||
str.split(';').forEach((p) => {
|
||||
const i = p.indexOf(':');
|
||||
if (i > 0) map[p.slice(0, i).trim().toLowerCase()] = p.slice(i + 1).trim();
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
function applyDivStyle(prop, value, toggle) {
|
||||
const r = lineRange();
|
||||
const text = ed.value.slice(r.s, r.e);
|
||||
const m = DIV_RE.exec(text);
|
||||
let inner = text;
|
||||
let props = {};
|
||||
if (m) { props = parseStyle(m[1]); inner = m[2]; }
|
||||
if (!value || (toggle && props[prop] === value)) delete props[prop];
|
||||
else props[prop] = value;
|
||||
const keys = Object.keys(props);
|
||||
let out;
|
||||
if (!keys.length) {
|
||||
out = inner;
|
||||
} else {
|
||||
const body = inner.trim() === '' ? 'Text' : inner;
|
||||
const style = keys.map((k) => k + ':' + props[k]).join(';');
|
||||
out = body.indexOf('\n') >= 0
|
||||
? '<div style="' + style + '">\n' + body + '\n</div>'
|
||||
: '<div style="' + style + '">' + body + '</div>';
|
||||
}
|
||||
replaceRange(r.s, r.e, out, r.s, r.s + out.length);
|
||||
}
|
||||
|
||||
function align(kind) {
|
||||
if (kind === 'left') applyDivStyle('text-align', '', false);
|
||||
else applyDivStyle('text-align', kind, true);
|
||||
}
|
||||
|
||||
/* ---------- lines: headings and lists ---------- */
|
||||
|
||||
function mapLines(fn) {
|
||||
const r = lineRange();
|
||||
const lines = ed.value.slice(r.s, r.e).split('\n');
|
||||
const out = fn(lines).join('\n');
|
||||
replaceRange(r.s, r.e, out, r.s, r.s + out.length);
|
||||
}
|
||||
|
||||
function heading(level) {
|
||||
mapLines((lines) => lines.map((l) => {
|
||||
const bare = l.replace(/^\s*=+\s*/, '').replace(/\s*=+\s*$/, '').trim();
|
||||
if (!level) return bare;
|
||||
const mark = '='.repeat(level);
|
||||
return mark + ' ' + (bare || 'Heading') + ' ' + mark;
|
||||
}));
|
||||
}
|
||||
|
||||
// Bullets and numbers keep the nesting depth: "** x" becomes "## x" instead of "# ** x".
|
||||
const LIST_RE = /^([*#:;]+)\s?/;
|
||||
|
||||
function toList(ch) {
|
||||
mapLines((lines) => {
|
||||
const real = lines.filter((l) => l.trim() !== '');
|
||||
const all = real.length > 0 && real.every((l) => {
|
||||
const m = LIST_RE.exec(l);
|
||||
return m && m[1].split('').every((c) => c === ch);
|
||||
});
|
||||
return lines.map((l) => {
|
||||
if (l.trim() === '') return l;
|
||||
const m = LIST_RE.exec(l);
|
||||
if (all) return l.slice(m[0].length);
|
||||
if (m) return ch.repeat(m[1].length) + ' ' + l.slice(m[0].length);
|
||||
return ch + ' ' + l;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function indent() {
|
||||
mapLines((lines) => lines.map((l) => {
|
||||
if (l.trim() === '') return l;
|
||||
const m = /^([*#]+)/.exec(l);
|
||||
if (m) return m[1].charAt(m[1].length - 1) + l;
|
||||
return ':' + l;
|
||||
}));
|
||||
}
|
||||
|
||||
function outdent() {
|
||||
mapLines((lines) => lines.map((l) => {
|
||||
const m = /^([*#:]+)(\s?)/.exec(l);
|
||||
if (!m) return l;
|
||||
if (m[1].length === 1) return l.slice(m[0].length);
|
||||
return l.slice(1);
|
||||
}));
|
||||
}
|
||||
|
||||
/* ---------- inserts ---------- */
|
||||
|
||||
function insertBlock(block) {
|
||||
const [s, e] = sel();
|
||||
const v = ed.value;
|
||||
const lead = s > 0 && v.charAt(s - 1) !== '\n' ? '\n' : '';
|
||||
const trail = e < v.length && v.charAt(e) !== '\n' ? '\n' : '';
|
||||
replaceRange(s, e, lead + block + trail);
|
||||
}
|
||||
|
||||
function extLink() {
|
||||
const [s, e] = sel();
|
||||
const text = ed.value.slice(s, e);
|
||||
let out;
|
||||
let a;
|
||||
let b;
|
||||
if (/^(https?|ftp):\/\/\S+$/i.test(text)) {
|
||||
out = '[' + text + ' link text]';
|
||||
a = s + text.length + 2;
|
||||
b = a + 9;
|
||||
} else {
|
||||
const label = text || 'link text';
|
||||
out = '[https://example.com ' + label + ']';
|
||||
a = s + 1;
|
||||
b = a + 19;
|
||||
}
|
||||
replaceRange(s, e, out, a, b);
|
||||
}
|
||||
|
||||
function clearFormatting() {
|
||||
let [s, e] = sel();
|
||||
if (s === e) { const r = lineRange(); s = r.s; e = r.e; }
|
||||
const text = ed.value.slice(s, e);
|
||||
const out = text
|
||||
.replace(/'{2,5}/g, '')
|
||||
.replace(/<\/?(b|i|u|s|sub|sup|small|big|code|span|div|center|font|strike|del|ins|blockquote)(\s[^>]*)?>/gi, '');
|
||||
replaceRange(s, e, out, s, s + out.length);
|
||||
}
|
||||
|
||||
/* ---------- color grid ---------- */
|
||||
|
||||
const pop = document.createElement('div');
|
||||
pop.className = 'pop';
|
||||
pop.hidden = true;
|
||||
document.body.appendChild(pop);
|
||||
let popMode = 'color';
|
||||
let popAnchor = null;
|
||||
|
||||
function colorValue() { return popMode === 'color' ? 'color' : 'background-color'; }
|
||||
|
||||
function applyColor(c) {
|
||||
closePop();
|
||||
applySpan(colorValue(), c);
|
||||
}
|
||||
|
||||
function closePop() {
|
||||
pop.hidden = true;
|
||||
popAnchor = null;
|
||||
}
|
||||
|
||||
function buildPop() {
|
||||
pop.innerHTML = '';
|
||||
const title = document.createElement('div');
|
||||
title.className = 'popTitle';
|
||||
title.textContent = popMode === 'color' ? 'Text color' : 'Highlight color';
|
||||
pop.appendChild(title);
|
||||
|
||||
const grid = document.createElement('div');
|
||||
grid.className = 'grid';
|
||||
PALETTE.forEach((row) => row.forEach((c) => {
|
||||
const b = document.createElement('button');
|
||||
b.className = 'sw';
|
||||
b.style.background = c;
|
||||
b.title = c;
|
||||
b.addEventListener('mousedown', (ev) => ev.preventDefault());
|
||||
b.addEventListener('click', () => applyColor(c));
|
||||
grid.appendChild(b);
|
||||
}));
|
||||
pop.appendChild(grid);
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.className = 'popRow';
|
||||
const hex = document.createElement('input');
|
||||
hex.placeholder = '#rrggbb or name';
|
||||
hex.spellcheck = false;
|
||||
const go = document.createElement('button');
|
||||
go.textContent = 'Apply';
|
||||
const doApply = () => {
|
||||
const val = hex.value.trim();
|
||||
if (/^#[0-9a-f]{3}([0-9a-f]{3})?$/i.test(val) || /^[a-z]{3,20}$/i.test(val)) applyColor(val);
|
||||
else hex.select();
|
||||
};
|
||||
go.addEventListener('mousedown', (ev) => ev.preventDefault());
|
||||
go.addEventListener('click', doApply);
|
||||
hex.addEventListener('keydown', (ev) => {
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); doApply(); }
|
||||
else if (ev.key === 'Escape') { ev.preventDefault(); closePop(); ed.focus(); }
|
||||
});
|
||||
row.appendChild(hex);
|
||||
row.appendChild(go);
|
||||
pop.appendChild(row);
|
||||
|
||||
const clear = document.createElement('button');
|
||||
clear.className = 'popClear';
|
||||
clear.textContent = popMode === 'color' ? 'Remove text color' : 'Remove highlight';
|
||||
clear.addEventListener('mousedown', (ev) => ev.preventDefault());
|
||||
clear.addEventListener('click', () => applyColor(''));
|
||||
pop.appendChild(clear);
|
||||
}
|
||||
|
||||
function openPop(mode, anchor) {
|
||||
if (!pop.hidden && popMode === mode && popAnchor === anchor) { closePop(); return; }
|
||||
popMode = mode;
|
||||
popAnchor = anchor;
|
||||
buildPop();
|
||||
pop.hidden = false;
|
||||
const r = anchor.getBoundingClientRect();
|
||||
const left = Math.max(6, Math.min(r.left, window.innerWidth - pop.offsetWidth - 8));
|
||||
pop.style.left = left + 'px';
|
||||
pop.style.top = (r.bottom + 4) + 'px';
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', (ev) => {
|
||||
if (!pop.hidden && !pop.contains(ev.target) && ev.target !== popAnchor && !(popAnchor && popAnchor.contains(ev.target))) closePop();
|
||||
});
|
||||
document.addEventListener('keydown', (ev) => {
|
||||
if (ev.key === 'Escape' && !pop.hidden) closePop();
|
||||
});
|
||||
|
||||
/* ---------- wiring ---------- */
|
||||
|
||||
const actions = {
|
||||
bold,
|
||||
italic,
|
||||
underline: () => toggleWrap('<u>', '</u>', 'underlined text'),
|
||||
strike: () => toggleWrap('<s>', '</s>', 'struck text'),
|
||||
sub: () => toggleWrap('<sub>', '</sub>', 'sub'),
|
||||
sup: () => toggleWrap('<sup>', '</sup>', 'sup'),
|
||||
code: () => toggleWrap('<code>', '</code>', 'code'),
|
||||
nowiki: () => toggleWrap('<nowiki>', '</nowiki>', 'plain text'),
|
||||
quote: () => toggleWrap('<blockquote>', '</blockquote>', 'Quote'),
|
||||
link: () => toggleWrap('[[', ']]', 'Page name'),
|
||||
template: () => toggleWrap('{{', '}}', 'Template name'),
|
||||
ref: () => toggleWrap('<ref>', '</ref>', 'Reference text'),
|
||||
extlink: extLink,
|
||||
hr: () => insertBlock('----'),
|
||||
ul: () => toList('*'),
|
||||
ol: () => toList('#'),
|
||||
indent,
|
||||
outdent,
|
||||
'align-left': () => align('left'),
|
||||
'align-center': () => align('center'),
|
||||
'align-right': () => align('right'),
|
||||
'align-justify': () => align('justify'),
|
||||
clear: clearFormatting
|
||||
};
|
||||
|
||||
document.querySelectorAll('[data-fmt]').forEach((b) => {
|
||||
b.addEventListener('mousedown', (ev) => ev.preventDefault());
|
||||
b.addEventListener('click', () => {
|
||||
const k = b.dataset.fmt;
|
||||
if (k === 'color' || k === 'highlight') { openPop(k, b); return; }
|
||||
if (actions[k]) actions[k]();
|
||||
});
|
||||
});
|
||||
|
||||
const sizeSel = document.getElementById('sizeSel');
|
||||
if (sizeSel) {
|
||||
sizeSel.addEventListener('change', () => {
|
||||
const v = sizeSel.value;
|
||||
sizeSel.value = '';
|
||||
if (!v) return;
|
||||
applySpan('font-size', v === 'normal' ? '' : v + '%');
|
||||
});
|
||||
}
|
||||
|
||||
const blockSizeSel = document.getElementById('blockSizeSel');
|
||||
if (blockSizeSel) {
|
||||
blockSizeSel.addEventListener('change', () => {
|
||||
const v = blockSizeSel.value;
|
||||
blockSizeSel.value = '';
|
||||
if (!v) return;
|
||||
applyDivStyle('font-size', v === 'normal' ? '' : v + '%', false);
|
||||
});
|
||||
}
|
||||
|
||||
const headSel = document.getElementById('headSel');
|
||||
if (headSel) {
|
||||
headSel.addEventListener('change', () => {
|
||||
const v = headSel.value;
|
||||
headSel.value = '';
|
||||
if (!v) return;
|
||||
heading(v === 'p' ? 0 : parseInt(v, 10));
|
||||
});
|
||||
}
|
||||
|
||||
ed.addEventListener('keydown', (ev) => {
|
||||
if (!(ev.ctrlKey || ev.metaKey) || ev.shiftKey || ev.altKey) return;
|
||||
const k = ev.key.toLowerCase();
|
||||
if (k === 'b') { ev.preventDefault(); bold(); }
|
||||
else if (k === 'i') { ev.preventDefault(); italic(); }
|
||||
else if (k === 'u') { ev.preventDefault(); actions.underline(); }
|
||||
else if (k === 'k') { ev.preventDefault(); actions.link(); }
|
||||
});
|
||||
|
||||
const api = { replaceRange, insert, lineRange, toggleWrap, insertBlock, sel, applySpan, applyDivStyle };
|
||||
return { actions, applySpan, align, heading, api };
|
||||
}
|
||||
|
||||
window.SwiftFormat = { init };
|
||||
})();
|
||||
@@ -0,0 +1,148 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Swiftmark</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<header id="topbar">
|
||||
<button id="btnSidebar" title="Show or hide the note list">Notes</button>
|
||||
<select id="wikiSelect" title="Which wiki to preview against"></select>
|
||||
<button id="btnSettings" title="Add, edit or remove wikis">Wikis...</button>
|
||||
<span class="sep"></span>
|
||||
<button id="btnCssLoad" title="Load a CSS file over the preview to try a stylesheet before saving it on your wiki">Load CSS...</button>
|
||||
<button id="btnCssToggle" title="Turn the loaded CSS on or off" disabled>CSS off</button>
|
||||
<button id="btnCssClear" title="Forget the loaded CSS file" hidden>Clear CSS</button>
|
||||
<span id="cssName"></span>
|
||||
<span class="spacer"></span>
|
||||
<label id="splitWrap" title="Drag to change how wide the editor is. Double click the divider to reset."><span>Editor width</span><input id="splitRange" type="range" min="15" max="85" value="50"></label>
|
||||
<button id="modeBadge" class="badge" title="Preview status"></button>
|
||||
<button id="btnSwap" title="Swap the editor and preview sides (Ctrl+Shift+F)">Swap sides</button>
|
||||
</header>
|
||||
|
||||
<div id="main">
|
||||
<aside id="sidebar">
|
||||
<div class="sbTop">
|
||||
<input id="search" type="search" placeholder="Search notes" spellcheck="false">
|
||||
<button id="btnNew" title="New note (Ctrl+N)">New</button>
|
||||
</div>
|
||||
<ul id="noteList"></ul>
|
||||
<div id="folderLabel" title=""></div>
|
||||
</aside>
|
||||
|
||||
<section id="panes">
|
||||
<div class="pane" id="paneEditor">
|
||||
<div class="paneHead">
|
||||
<input id="titleInput" title="Note title (press Enter to rename)" spellcheck="false">
|
||||
<button id="btnExport" title="Export as PDF, Word or wikitext">Export...</button>
|
||||
<button id="btnDelete" title="Delete this note">Delete</button>
|
||||
</div>
|
||||
<div class="fmtbar" id="fmtbar">
|
||||
<span class="grp">
|
||||
<button data-fmt="bold" title="Bold (Ctrl+B)"><b>B</b></button>
|
||||
<button data-fmt="italic" title="Italic (Ctrl+I)"><i>I</i></button>
|
||||
<button data-fmt="underline" title="Underline (Ctrl+U)"><u>U</u></button>
|
||||
<button data-fmt="strike" title="Strikethrough"><s>S</s></button>
|
||||
<button data-fmt="sub" title="Subscript">x<sub>2</sub></button>
|
||||
<button data-fmt="sup" title="Superscript">x<sup>2</sup></button>
|
||||
<button data-fmt="code" title="Code"></></button>
|
||||
</span>
|
||||
<span class="grp">
|
||||
<button data-fmt="color" title="Text color"><span class="swA" id="swText">A</span></button>
|
||||
<button data-fmt="highlight" title="Highlight color"><span class="swH">ab</span></button>
|
||||
<select id="sizeSel" title="Text size">
|
||||
<option value="">Size</option>
|
||||
<option value="70">Tiny 70%</option>
|
||||
<option value="85">Small 85%</option>
|
||||
<option value="120">Large 120%</option>
|
||||
<option value="150">Larger 150%</option>
|
||||
<option value="200">Huge 200%</option>
|
||||
<option value="300">Giant 300%</option>
|
||||
<option value="normal">Normal (remove size)</option>
|
||||
</select>
|
||||
<select id="blockSizeSel" title="Size for the whole line or block, wrapped in a div">
|
||||
<option value="">Block size</option>
|
||||
<option value="70">Block 70%</option>
|
||||
<option value="85">Block 85%</option>
|
||||
<option value="120">Block 120%</option>
|
||||
<option value="150">Block 150%</option>
|
||||
<option value="200">Block 200%</option>
|
||||
<option value="300">Block 300%</option>
|
||||
<option value="normal">Normal (remove block size)</option>
|
||||
</select>
|
||||
</span>
|
||||
<span class="grp">
|
||||
<button data-fmt="align-left" title="Align left (removes other alignment)"><svg width="14" height="12" viewBox="0 0 14 12"><path d="M1 1h12M1 4h8M1 7h12M1 10h8" stroke="currentColor" stroke-width="1.5" fill="none"/></svg></button>
|
||||
<button data-fmt="align-center" title="Center"><svg width="14" height="12" viewBox="0 0 14 12"><path d="M1 1h12M3 4h8M1 7h12M3 10h8" stroke="currentColor" stroke-width="1.5" fill="none"/></svg></button>
|
||||
<button data-fmt="align-right" title="Align right"><svg width="14" height="12" viewBox="0 0 14 12"><path d="M1 1h12M5 4h8M1 7h12M5 10h8" stroke="currentColor" stroke-width="1.5" fill="none"/></svg></button>
|
||||
<button data-fmt="align-justify" title="Justify"><svg width="14" height="12" viewBox="0 0 14 12"><path d="M1 1h12M1 4h12M1 7h12M1 10h12" stroke="currentColor" stroke-width="1.5" fill="none"/></svg></button>
|
||||
</span>
|
||||
<span class="grp">
|
||||
<select id="headSel" title="Heading level for the selected lines">
|
||||
<option value="">Heading</option>
|
||||
<option value="p">Normal text</option>
|
||||
<option value="2">Heading 2</option>
|
||||
<option value="3">Heading 3</option>
|
||||
<option value="4">Heading 4</option>
|
||||
<option value="5">Heading 5</option>
|
||||
</select>
|
||||
<button data-fmt="ul" title="Bulleted list. Keeps nesting levels; click again to remove.">Bullets</button>
|
||||
<button data-fmt="ol" title="Numbered list. Keeps nesting levels; click again to remove.">Numbers</button>
|
||||
<button data-fmt="indent" title="Indent (nests list items one level deeper)">Indent</button>
|
||||
<button data-fmt="outdent" title="Outdent (one level shallower)">Outdent</button>
|
||||
</span>
|
||||
<span class="grp">
|
||||
<button data-fmt="link" title="Wiki link (Ctrl+K)">[[ ]]</button>
|
||||
<button data-fmt="extlink" title="External link">Ext link</button>
|
||||
<button id="btnMedia" title="Picture, thumbnail, video and sound place-marker code">Media...</button>
|
||||
<button id="btnTable" title="Insert a table: pick the size on the grid">Table</button>
|
||||
<button id="btnTableTools" title="Row and column tools for the table at the cursor">Table tools</button>
|
||||
<button data-fmt="hr" title="Horizontal rule">Rule</button>
|
||||
<button data-fmt="quote" title="Block quote">Quote</button>
|
||||
<button data-fmt="template" title="Template call">{{ }}</button>
|
||||
<button data-fmt="ref" title="Reference">Ref</button>
|
||||
<button data-fmt="nowiki" title="Show text without wiki markup">nowiki</button>
|
||||
<button id="btnSpell" title="Check spelling, offline">Spelling</button>
|
||||
<button id="btnThes" title="Find synonyms for the selected word, offline">Thesaurus</button>
|
||||
<button id="btnSnippets" title="Common snippets: nowiki, ref, comments, categories, magic words and more">Snippets</button>
|
||||
<button data-fmt="clear" title="Remove bold, italic and tag formatting from the selection or line">Clear</button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="paneBody">
|
||||
<textarea id="editor" spellcheck="true" wrap="soft" placeholder="Write wikitext here"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="splitter" role="separator" aria-orientation="vertical" tabindex="0" title="Drag to resize. Double click to reset. Arrow keys nudge."></div>
|
||||
|
||||
<div class="pane" id="panePreview">
|
||||
<div class="paneHead"><span class="paneTitle">Preview</span><span id="previewSource"></span></div>
|
||||
<div class="paneBody">
|
||||
<iframe id="preview" sandbox="allow-same-origin" title="Preview"></iframe>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer id="statusbar">
|
||||
<span id="noteStatus"></span>
|
||||
<span class="spacer"></span>
|
||||
<span id="countStatus"></span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<div id="toast" hidden></div>
|
||||
|
||||
<script src="fallback.js"></script>
|
||||
<script src="format.js"></script>
|
||||
<script src="tables.js"></script>
|
||||
<script src="snippets.js"></script>
|
||||
<script src="media.js"></script>
|
||||
<script src="proof.js"></script>
|
||||
<script src="export.js"></script>
|
||||
<script src="renderer.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,829 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const wn = window.wn;
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const ed = $('editor');
|
||||
|
||||
const state = {
|
||||
cfg: null,
|
||||
file: null,
|
||||
mode: 'fallback', // 'live' or 'fallback'
|
||||
api: null,
|
||||
siteName: '',
|
||||
reason: null, // why we are in fallback: {kind, detail}
|
||||
connecting: false,
|
||||
connectSeq: 0,
|
||||
renderSeq: 0,
|
||||
renderTimer: null,
|
||||
saveTimer: null,
|
||||
searchTimer: null,
|
||||
dirty: false,
|
||||
dialogKey: null,
|
||||
cssWarned: false,
|
||||
tables: null,
|
||||
notes: []
|
||||
};
|
||||
|
||||
/* ---------- small helpers ---------- */
|
||||
|
||||
function el(tag, text, cls) {
|
||||
const e = document.createElement(tag);
|
||||
if (text !== undefined && text !== null) e.textContent = text;
|
||||
if (cls) e.className = cls;
|
||||
return e;
|
||||
}
|
||||
|
||||
let toastTimer = null;
|
||||
function toast(msg, ms) {
|
||||
const t = $('toast');
|
||||
t.textContent = msg;
|
||||
t.hidden = false;
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => { t.hidden = true; }, ms || 3500);
|
||||
}
|
||||
|
||||
function hostOf(url) {
|
||||
try {
|
||||
return new URL(/^https?:\/\//i.test(url) ? url : 'https://' + url).host;
|
||||
} catch (e) { return url || ''; }
|
||||
}
|
||||
|
||||
function baseName(p) { return String(p || '').split(/[\\/]/).pop(); }
|
||||
|
||||
function uid() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 6); }
|
||||
|
||||
function openModal(opts) {
|
||||
const ov = el('div', null, 'overlay');
|
||||
const dlg = el('div', null, 'dialog' + (opts.wide ? ' wide' : ''));
|
||||
dlg.appendChild(el('h2', opts.title));
|
||||
const body = el('div', null, 'dialogBody');
|
||||
if (opts.content) body.appendChild(opts.content);
|
||||
dlg.appendChild(body);
|
||||
const bar = el('div', null, 'dialogButtons');
|
||||
let done = null;
|
||||
const promise = new Promise((resolve) => { done = resolve; });
|
||||
|
||||
function topOverlay() {
|
||||
const all = document.querySelectorAll('.overlay');
|
||||
return all[all.length - 1];
|
||||
}
|
||||
function close(v) {
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
ov.remove();
|
||||
done(v);
|
||||
}
|
||||
function onKey(e) {
|
||||
if (e.key === 'Escape' && topOverlay() === ov) {
|
||||
e.stopPropagation();
|
||||
close(null);
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
|
||||
(opts.buttons || [{ label: 'OK', value: 'ok', primary: true }]).forEach((b) => {
|
||||
const btn = el('button', b.label);
|
||||
if (b.primary) btn.classList.add('primary');
|
||||
btn.addEventListener('click', () => close(b.value));
|
||||
bar.appendChild(btn);
|
||||
});
|
||||
dlg.appendChild(bar);
|
||||
ov.appendChild(dlg);
|
||||
document.body.appendChild(ov);
|
||||
const first = bar.querySelector('.primary') || bar.querySelector('button');
|
||||
if (first && !opts.noFocus) first.focus();
|
||||
return { promise, close, body };
|
||||
}
|
||||
|
||||
/* ---------- config helpers ---------- */
|
||||
|
||||
function activeProfile() {
|
||||
return state.cfg.profiles.find((p) => p.id === state.cfg.active) || null;
|
||||
}
|
||||
function cssKey() { return state.cfg.active || 'none'; }
|
||||
function cssInfo() { return state.cfg.css[cssKey()] || { path: '', on: false }; }
|
||||
function setCssInfo(v) {
|
||||
const css = Object.assign({}, state.cfg.css);
|
||||
css[cssKey()] = v;
|
||||
state.cfg.css = css;
|
||||
wn.setConfig({ css });
|
||||
state.cssWarned = false;
|
||||
updateCssUi();
|
||||
schedulePreview(0);
|
||||
}
|
||||
|
||||
function applyLayout() {
|
||||
$('panes').classList.toggle('swapped', !!state.cfg.swapped);
|
||||
$('sidebar').classList.toggle('hidden', !state.cfg.sidebar);
|
||||
$('btnSidebar').classList.toggle('on', !!state.cfg.sidebar);
|
||||
}
|
||||
|
||||
function fillWikiSelect() {
|
||||
const sel = $('wikiSelect');
|
||||
sel.innerHTML = '';
|
||||
const none = el('option', 'No wiki (rough preview)');
|
||||
none.value = '';
|
||||
sel.appendChild(none);
|
||||
state.cfg.profiles.forEach((p) => {
|
||||
const o = el('option', p.name || hostOf(p.url));
|
||||
o.value = p.id;
|
||||
sel.appendChild(o);
|
||||
});
|
||||
sel.value = state.cfg.active || '';
|
||||
}
|
||||
|
||||
function updateCssUi() {
|
||||
const info = cssInfo();
|
||||
const has = !!info.path;
|
||||
$('btnCssToggle').disabled = !has;
|
||||
$('btnCssToggle').textContent = info.on && has ? 'CSS on' : 'CSS off';
|
||||
$('btnCssToggle').classList.toggle('on', info.on && has);
|
||||
$('btnCssClear').hidden = !has;
|
||||
$('cssName').textContent = has ? baseName(info.path) : '';
|
||||
$('cssName').title = info.path || '';
|
||||
}
|
||||
|
||||
function updateBadge() {
|
||||
const b = $('modeBadge');
|
||||
b.className = 'badge';
|
||||
if (state.connecting) {
|
||||
b.textContent = 'Connecting...';
|
||||
b.classList.add('busy');
|
||||
$('previewSource').textContent = '';
|
||||
} else if (state.mode === 'live') {
|
||||
b.textContent = 'Live preview';
|
||||
b.classList.add('live');
|
||||
b.title = 'Rendered by ' + (state.siteName || 'your wiki') + '. Click for details.';
|
||||
$('previewSource').textContent = state.siteName ? 'from ' + state.siteName : '';
|
||||
} else {
|
||||
b.textContent = 'Rough preview';
|
||||
b.classList.add('rough');
|
||||
b.title = 'Click to see why this is a rough preview and how to get a live one.';
|
||||
$('previewSource').textContent = 'local approximation';
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- preview ---------- */
|
||||
|
||||
async function getCssText() {
|
||||
const info = cssInfo();
|
||||
if (!info.on || !info.path) return '';
|
||||
const r = await wn.readCss(info.path);
|
||||
if (r.ok) return r.text;
|
||||
if (!state.cssWarned) {
|
||||
state.cssWarned = true;
|
||||
toast('Could not read the CSS file: ' + r.error, 5000);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function injectCss(doc, css) {
|
||||
if (!css) return doc;
|
||||
const tag = '<style id="wn-user-css">' + css.replace(/<\/style/gi, '<\\/style') + '</style>';
|
||||
if (/<\/head>/i.test(doc)) return doc.replace(/<\/head>/i, () => tag + '</head>');
|
||||
return tag + doc;
|
||||
}
|
||||
|
||||
function currentTitle() {
|
||||
return $('titleInput').value.trim() || 'Untitled';
|
||||
}
|
||||
|
||||
function setPreview(doc) {
|
||||
const frame = $('preview');
|
||||
let sy = 0;
|
||||
try { sy = frame.contentWindow.scrollY || 0; } catch (e) { sy = 0; }
|
||||
return new Promise((resolve) => {
|
||||
const guard = setTimeout(resolve, 5000);
|
||||
frame.onload = () => {
|
||||
clearTimeout(guard);
|
||||
try { frame.contentWindow.scrollTo(0, sy); } catch (e) { /* ignore */ }
|
||||
if (state.tables) state.tables.attachPreview(frame);
|
||||
resolve();
|
||||
};
|
||||
frame.srcdoc = doc;
|
||||
});
|
||||
}
|
||||
|
||||
async function render() {
|
||||
const seq = ++state.renderSeq;
|
||||
const text = state.tables ? state.tables.annotate(ed.value) : ed.value;
|
||||
const title = currentTitle();
|
||||
let doc = null;
|
||||
|
||||
if (state.mode === 'live' && state.api) {
|
||||
const r = await wn.parse({ api: state.api, text, title });
|
||||
if (seq !== state.renderSeq) return;
|
||||
if (r.ok) {
|
||||
doc = r.doc;
|
||||
} else {
|
||||
state.mode = 'fallback';
|
||||
state.api = null;
|
||||
state.reason = { kind: r.kind, detail: r.detail };
|
||||
updateBadge();
|
||||
maybeShowDialog();
|
||||
}
|
||||
}
|
||||
if (!doc) doc = window.WikiFallback.buildDocument(text, title);
|
||||
|
||||
const css = await getCssText();
|
||||
if (seq !== state.renderSeq) return;
|
||||
await setPreview(injectCss(doc, css));
|
||||
}
|
||||
|
||||
// For export: make sure the preview is current, then hand over its document.
|
||||
async function snapshotPreview() {
|
||||
clearTimeout(state.renderTimer);
|
||||
await render();
|
||||
try { return $('preview').contentDocument; } catch (e) { return null; }
|
||||
}
|
||||
|
||||
function schedulePreview(ms) {
|
||||
clearTimeout(state.renderTimer);
|
||||
const wait = ms !== undefined ? ms : (state.mode === 'live' ? 500 : 150);
|
||||
state.renderTimer = setTimeout(render, wait);
|
||||
}
|
||||
|
||||
function syncScroll() {
|
||||
const frame = $('preview');
|
||||
try {
|
||||
const max = ed.scrollHeight - ed.clientHeight;
|
||||
const ratio = max > 0 ? ed.scrollTop / max : 0;
|
||||
const w = frame.contentWindow;
|
||||
const h = w.document.documentElement.scrollHeight - w.innerHeight;
|
||||
if (h > 0) w.scrollTo(0, ratio * h);
|
||||
} catch (e) { /* preview not ready */ }
|
||||
}
|
||||
|
||||
/* ---------- the "rough preview" dialog ---------- */
|
||||
|
||||
function maybeShowDialog(force) {
|
||||
const key = (state.cfg.active || 'none') + ':' + (state.reason ? state.reason.kind : '');
|
||||
if (!force && state.dialogKey === key) return;
|
||||
state.dialogKey = key;
|
||||
showFallbackDialog();
|
||||
}
|
||||
|
||||
async function showFallbackDialog() {
|
||||
const r = state.reason || { kind: 'nowiki' };
|
||||
const p = activeProfile();
|
||||
const host = p ? hostOf(p.url) : '';
|
||||
const wrap = el('div');
|
||||
|
||||
if (state.mode === 'live') {
|
||||
wrap.appendChild(el('p', 'You are getting a live preview from ' + (state.siteName || host) +
|
||||
'. The preview is produced by the wiki itself, with its real styling.'));
|
||||
const m = openModal({ title: 'Live preview', content: wrap, buttons: [{ label: 'OK', value: 'ok', primary: true }] });
|
||||
await m.promise;
|
||||
return;
|
||||
}
|
||||
|
||||
if (r.kind === 'nowiki') {
|
||||
wrap.appendChild(el('p', 'No wiki is set up yet, so you are looking at a rough local preview. It is only a guess at how your page would look and will not match any particular wiki.'));
|
||||
} else {
|
||||
wrap.appendChild(el('p', 'Swiftmark could not get a live preview from ' + (host || 'your wiki') + '. ' + (r.detail || '')));
|
||||
}
|
||||
wrap.appendChild(el('p', 'Until that is fixed the preview is rough. It handles headings, bold and italic, links, lists, tables and references. Templates, infoboxes, parser functions and your wiki\'s own styling are not rendered, so expect differences.'));
|
||||
|
||||
const strong = el('p');
|
||||
strong.appendChild(el('b', 'To get a live preview that looks exactly like your wiki, unlock its API:'));
|
||||
wrap.appendChild(strong);
|
||||
|
||||
const ol = el('ol');
|
||||
const li1 = el('li', 'Make sure api.php can be reached. Open an address like ');
|
||||
li1.appendChild(el('code', 'https://yourwiki.example.org/w/api.php'));
|
||||
li1.appendChild(document.createTextNode(' in a browser. You should see an API help page, not an error.'));
|
||||
ol.appendChild(li1);
|
||||
const li2 = el('li', 'If your wiki hides pages from logged out visitors, the API refuses them too. To allow reading without a login, an admin sets ');
|
||||
li2.appendChild(el('code', "$wgGroupPermissions['*']['read'] = true;"));
|
||||
li2.appendChild(document.createTextNode(' in LocalSettings.php. This makes the whole wiki public. Swiftmark does not log in to wikis yet.'));
|
||||
ol.appendChild(li2);
|
||||
ol.appendChild(el('li', 'If a firewall, security plugin or CDN bot protection is blocking api.php, allow requests to it. Swiftmark identifies itself as Swiftmark/1.0.'));
|
||||
ol.appendChild(el('li', 'If the address is wrong, enter the wiki\'s main page address under Wikis. Swiftmark finds api.php from there.'));
|
||||
wrap.appendChild(ol);
|
||||
|
||||
const buttons = r.kind === 'nowiki'
|
||||
? [{ label: 'Keep rough preview', value: 'keep' }, { label: 'Add a wiki', value: 'settings', primary: true }]
|
||||
: [{ label: 'Keep rough preview', value: 'keep' }, { label: 'Wiki settings', value: 'settings' }, { label: 'Retry', value: 'retry', primary: true }];
|
||||
|
||||
const m = openModal({ title: 'Rough local preview', content: wrap, buttons, wide: true });
|
||||
const choice = await m.promise;
|
||||
if (choice === 'settings') openSettings();
|
||||
else if (choice === 'retry') connectActive({ force: true });
|
||||
}
|
||||
|
||||
/* ---------- connecting to the wiki ---------- */
|
||||
|
||||
async function connectActive(opts) {
|
||||
opts = opts || {};
|
||||
const seq = ++state.connectSeq;
|
||||
const p = activeProfile();
|
||||
state.api = null;
|
||||
state.mode = 'fallback';
|
||||
|
||||
if (!p) {
|
||||
state.connecting = false;
|
||||
state.reason = { kind: 'nowiki' };
|
||||
updateBadge();
|
||||
schedulePreview(0);
|
||||
if (opts.dialog !== false) maybeShowDialog(opts.force);
|
||||
return { ok: false, kind: 'nowiki' };
|
||||
}
|
||||
|
||||
state.connecting = true;
|
||||
updateBadge();
|
||||
const r = await wn.connect(p.url);
|
||||
if (seq !== state.connectSeq) return r;
|
||||
state.connecting = false;
|
||||
|
||||
if (r.ok) {
|
||||
state.mode = 'live';
|
||||
state.api = r.api;
|
||||
state.siteName = r.siteName;
|
||||
state.reason = null;
|
||||
state.dialogKey = null;
|
||||
} else {
|
||||
state.reason = { kind: r.kind, detail: r.detail };
|
||||
}
|
||||
updateBadge();
|
||||
schedulePreview(0);
|
||||
if (!r.ok && opts.dialog !== false) maybeShowDialog(opts.force);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ---------- wiki settings ---------- */
|
||||
|
||||
function openSettings() {
|
||||
const wrap = el('div');
|
||||
let working = null; // profile being edited, id null when new
|
||||
|
||||
// notes folder
|
||||
const rowFolder = el('div', null, 'formRow');
|
||||
rowFolder.appendChild(el('label', 'Notes folder'));
|
||||
const folderCode = el('code', state.cfg.notesDir);
|
||||
rowFolder.appendChild(folderCode);
|
||||
const btnFolder = el('button', 'Change...');
|
||||
rowFolder.appendChild(btnFolder);
|
||||
wrap.appendChild(rowFolder);
|
||||
wrap.appendChild(el('hr', null, 'divider'));
|
||||
|
||||
// wiki profile form
|
||||
const rowSel = el('div', null, 'formRow');
|
||||
rowSel.appendChild(el('label', 'Saved wikis'));
|
||||
const sel = el('select');
|
||||
rowSel.appendChild(sel);
|
||||
wrap.appendChild(rowSel);
|
||||
|
||||
const rowName = el('div', null, 'formRow');
|
||||
rowName.appendChild(el('label', 'Name'));
|
||||
const inName = el('input');
|
||||
inName.placeholder = 'My wiki';
|
||||
rowName.appendChild(inName);
|
||||
wrap.appendChild(rowName);
|
||||
|
||||
const rowUrl = el('div', null, 'formRow');
|
||||
rowUrl.appendChild(el('label', 'Address'));
|
||||
const inUrl = el('input');
|
||||
inUrl.placeholder = 'https://yourwiki.example.org';
|
||||
inUrl.spellcheck = false;
|
||||
rowUrl.appendChild(inUrl);
|
||||
wrap.appendChild(rowUrl);
|
||||
|
||||
const actions = el('div', null, 'formActions');
|
||||
const btnTest = el('button', 'Test connection');
|
||||
const btnSave = el('button', 'Save and use');
|
||||
btnSave.classList.add('primary');
|
||||
const btnDel = el('button', 'Delete');
|
||||
actions.appendChild(btnTest);
|
||||
actions.appendChild(btnSave);
|
||||
actions.appendChild(btnDel);
|
||||
wrap.appendChild(actions);
|
||||
|
||||
const result = el('div', null, 'formResult');
|
||||
wrap.appendChild(result);
|
||||
|
||||
function showResult(msg, good) {
|
||||
result.textContent = msg;
|
||||
result.className = 'formResult ' + (good ? 'good' : 'bad');
|
||||
}
|
||||
|
||||
function refillSelect(selectId) {
|
||||
sel.innerHTML = '';
|
||||
state.cfg.profiles.forEach((p) => {
|
||||
const o = el('option', p.name || hostOf(p.url));
|
||||
o.value = p.id;
|
||||
sel.appendChild(o);
|
||||
});
|
||||
const n = el('option', '(add a new wiki)');
|
||||
n.value = '';
|
||||
sel.appendChild(n);
|
||||
sel.value = selectId !== undefined ? selectId : '';
|
||||
}
|
||||
|
||||
function loadWorking() {
|
||||
const p = state.cfg.profiles.find((x) => x.id === sel.value);
|
||||
working = p ? Object.assign({}, p) : { id: null, name: '', url: '' };
|
||||
inName.value = working.name;
|
||||
inUrl.value = working.url;
|
||||
btnDel.disabled = !p;
|
||||
result.textContent = '';
|
||||
}
|
||||
|
||||
refillSelect(state.cfg.active || (state.cfg.profiles[0] ? state.cfg.profiles[0].id : ''));
|
||||
loadWorking();
|
||||
sel.addEventListener('change', loadWorking);
|
||||
|
||||
btnFolder.addEventListener('click', async () => {
|
||||
const dir = await wn.pickFolder();
|
||||
if (!dir) return;
|
||||
await wn.setConfig({ notesDir: dir });
|
||||
state.cfg.notesDir = dir;
|
||||
folderCode.textContent = dir;
|
||||
$('folderLabel').textContent = dir;
|
||||
$('folderLabel').title = dir;
|
||||
state.file = null;
|
||||
await refreshNotes();
|
||||
if (state.notes.length) await openNote(state.notes[0].file);
|
||||
else await newNote(true);
|
||||
toast('Now using ' + dir);
|
||||
});
|
||||
|
||||
btnTest.addEventListener('click', async () => {
|
||||
const url = inUrl.value.trim();
|
||||
if (!url) { showResult('Enter the wiki address first.', false); return; }
|
||||
showResult('Testing...', true);
|
||||
const r = await wn.connect(url);
|
||||
if (r.ok) showResult('Connected to ' + r.siteName + '. Live preview will work.', true);
|
||||
else showResult(r.detail || 'Could not connect.', false);
|
||||
});
|
||||
|
||||
btnSave.addEventListener('click', async () => {
|
||||
const url = inUrl.value.trim();
|
||||
if (!url) { showResult('Enter the wiki address first.', false); return; }
|
||||
const name = inName.value.trim() || hostOf(url);
|
||||
const profiles = state.cfg.profiles.slice();
|
||||
let id = working.id;
|
||||
if (id) {
|
||||
const i = profiles.findIndex((x) => x.id === id);
|
||||
if (i >= 0) profiles[i] = { id, name, url };
|
||||
} else {
|
||||
id = uid();
|
||||
profiles.push({ id, name, url });
|
||||
}
|
||||
await wn.setConfig({ profiles, active: id });
|
||||
state.cfg.profiles = profiles;
|
||||
state.cfg.active = id;
|
||||
fillWikiSelect();
|
||||
updateCssUi();
|
||||
refillSelect(id);
|
||||
loadWorking();
|
||||
showResult('Saved. Connecting...', true);
|
||||
const r = await connectActive({ dialog: false });
|
||||
if (r && r.ok) showResult('Saved. Connected to ' + r.siteName + '. Live preview is on.', true);
|
||||
else showResult('Saved, but no live preview yet. ' + ((r && r.detail) || ''), false);
|
||||
});
|
||||
|
||||
btnDel.addEventListener('click', async () => {
|
||||
if (!working || !working.id) return;
|
||||
const profiles = state.cfg.profiles.filter((x) => x.id !== working.id);
|
||||
let active = state.cfg.active;
|
||||
const deletedActive = active === working.id;
|
||||
if (deletedActive) active = null;
|
||||
await wn.setConfig({ profiles, active });
|
||||
state.cfg.profiles = profiles;
|
||||
state.cfg.active = active;
|
||||
fillWikiSelect();
|
||||
updateCssUi();
|
||||
refillSelect(active || '');
|
||||
loadWorking();
|
||||
if (deletedActive) await connectActive({ dialog: false });
|
||||
showResult('Deleted.', true);
|
||||
});
|
||||
|
||||
openModal({ title: 'Wikis and notes folder', content: wrap, wide: true, noFocus: true, buttons: [{ label: 'Close', value: 'close', primary: true }] });
|
||||
}
|
||||
|
||||
/* ---------- notes ---------- */
|
||||
|
||||
function fmtDate(ms) {
|
||||
const d = new Date(ms);
|
||||
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ' ' +
|
||||
d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function renderNoteList() {
|
||||
const ul = $('noteList');
|
||||
ul.innerHTML = '';
|
||||
if (!state.notes.length) {
|
||||
ul.appendChild(el('li', $('search').value ? 'No notes match.' : 'No notes yet.', 'none'));
|
||||
return;
|
||||
}
|
||||
state.notes.forEach((n) => {
|
||||
const li = el('li');
|
||||
li.dataset.file = n.file;
|
||||
if (n.file === state.file) li.classList.add('active');
|
||||
li.appendChild(el('span', n.title, 't'));
|
||||
li.appendChild(el('span', fmtDate(n.mtime), 'd'));
|
||||
li.title = n.title;
|
||||
li.addEventListener('click', () => { if (n.file !== state.file) openNote(n.file); });
|
||||
ul.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshNotes() {
|
||||
state.notes = await wn.listNotes($('search').value);
|
||||
renderNoteList();
|
||||
}
|
||||
|
||||
function setStatus(msg) { $('noteStatus').textContent = msg; }
|
||||
|
||||
function updateCount() {
|
||||
const t = ed.value;
|
||||
const words = (t.trim().match(/\S+/g) || []).length;
|
||||
$('countStatus').textContent = words + (words === 1 ? ' word, ' : ' words, ') + t.length + ' characters';
|
||||
}
|
||||
|
||||
async function saveNow() {
|
||||
clearTimeout(state.saveTimer);
|
||||
if (!state.file || !state.dirty) return;
|
||||
const file = state.file;
|
||||
const text = ed.value;
|
||||
state.dirty = false;
|
||||
setStatus('Saving...');
|
||||
try {
|
||||
await wn.writeNote(file, text);
|
||||
setStatus('Saved');
|
||||
if (!state.dirty) refreshNotes();
|
||||
} catch (e) {
|
||||
state.dirty = true;
|
||||
setStatus('Could not save: ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function openNote(file) {
|
||||
await saveNow();
|
||||
let text = '';
|
||||
try { text = await wn.readNote(file); } catch (e) { toast('Could not open that note.'); await refreshNotes(); return; }
|
||||
state.file = file;
|
||||
ed.value = text;
|
||||
$('titleInput').value = file.replace(/\.(wiki|mediawiki|txt)$/i, '');
|
||||
state.dirty = false;
|
||||
setStatus('Saved');
|
||||
updateCount();
|
||||
renderNoteList();
|
||||
wn.setConfig({ lastNote: file });
|
||||
schedulePreview(0);
|
||||
ed.scrollTop = 0;
|
||||
}
|
||||
|
||||
async function newNote(silent) {
|
||||
await saveNow();
|
||||
const r = await wn.createNote('Untitled');
|
||||
$('search').value = '';
|
||||
await refreshNotes();
|
||||
await openNote(r.file);
|
||||
if (!silent) {
|
||||
$('titleInput').focus();
|
||||
$('titleInput').select();
|
||||
}
|
||||
}
|
||||
|
||||
async function renameCurrent() {
|
||||
if (!state.file) return;
|
||||
const input = $('titleInput');
|
||||
const old = state.file.replace(/\.(wiki|mediawiki|txt)$/i, '');
|
||||
const wanted = input.value.trim();
|
||||
if (!wanted || wanted === old) { input.value = old; return; }
|
||||
await saveNow();
|
||||
const r = await wn.renameNote(state.file, wanted);
|
||||
if (!r.ok) {
|
||||
toast(r.error === 'exists' ? 'A note with that title already exists.' : 'That title cannot be used.');
|
||||
input.value = old;
|
||||
return;
|
||||
}
|
||||
state.file = r.file;
|
||||
input.value = r.file.replace(/\.(wiki|mediawiki|txt)$/i, '');
|
||||
wn.setConfig({ lastNote: r.file });
|
||||
await refreshNotes();
|
||||
schedulePreview(0);
|
||||
}
|
||||
|
||||
async function deleteCurrent() {
|
||||
if (!state.file) return;
|
||||
const name = $('titleInput').value;
|
||||
const wrap = el('div');
|
||||
wrap.appendChild(el('p', 'Delete "' + name + '"? This removes the file from your notes folder and cannot be undone.'));
|
||||
const m = openModal({
|
||||
title: 'Delete note',
|
||||
content: wrap,
|
||||
buttons: [{ label: 'Cancel', value: 'no', primary: true }, { label: 'Delete', value: 'yes' }]
|
||||
});
|
||||
if ((await m.promise) !== 'yes') return;
|
||||
const file = state.file;
|
||||
state.file = null;
|
||||
state.dirty = false;
|
||||
clearTimeout(state.saveTimer);
|
||||
try { await wn.deleteNote(file); } catch (e) { toast('Could not delete: ' + e.message); }
|
||||
await refreshNotes();
|
||||
if (state.notes.length) await openNote(state.notes[0].file);
|
||||
else await newNote(true);
|
||||
}
|
||||
|
||||
const WELCOME = [
|
||||
"== Welcome to Swiftmark ==",
|
||||
"Type wikitext on one side and watch it render on the other. Use '''Swap sides''' at the top right to put the editor on whichever side you like.",
|
||||
"",
|
||||
"=== Try some markup ===",
|
||||
"* A bullet with ''italic'' and '''bold''' text",
|
||||
"* A link to [[Another page]] and one to [https://example.org an outside site]",
|
||||
"# A numbered item",
|
||||
"# Another one",
|
||||
"",
|
||||
"{| class=\"wikitable\"",
|
||||
"! Thing !! Count",
|
||||
"|-",
|
||||
"| Notes || 1",
|
||||
"|}",
|
||||
"",
|
||||
"=== Formatting toolbar ===",
|
||||
"Select some text and use the bar above the editor: <u>underline</u>, <s>strikethrough</s>, H<sub>2</sub>O, x<sup>2</sup>, <span style=\"color:#cc0000\">colors</span>, <span style=\"background-color:#ffe599\">highlights</span>, <span style=\"font-size:150%\">sizes</span> and alignment.",
|
||||
"<div style=\"text-align:center\">Centered text</div>",
|
||||
"",
|
||||
"=== Real wiki styling ===",
|
||||
"Add your wiki under '''Wikis...''' to preview with your wiki's own engine and stylesheets.",
|
||||
"Use '''Load CSS...''' to try a stylesheet on the preview before you save it on your wiki.",
|
||||
""
|
||||
].join('\n');
|
||||
|
||||
async function createWelcome() {
|
||||
const r = await wn.createNote('Welcome');
|
||||
await wn.writeNote(r.file, WELCOME);
|
||||
return r.file;
|
||||
}
|
||||
|
||||
/* ---------- editing helpers ---------- */
|
||||
|
||||
function onEdit() {
|
||||
state.dirty = true;
|
||||
setStatus('Editing...');
|
||||
updateCount();
|
||||
clearTimeout(state.saveTimer);
|
||||
state.saveTimer = setTimeout(saveNow, 500);
|
||||
schedulePreview();
|
||||
}
|
||||
|
||||
/* ---------- resizable panes ---------- */
|
||||
|
||||
function setSplit(f, save) {
|
||||
f = Math.max(0.15, Math.min(0.85, f));
|
||||
state.cfg.split = f;
|
||||
$('panes').style.setProperty('--ef', String(f));
|
||||
$('splitRange').value = String(Math.round(f * 100));
|
||||
if (save) wn.setConfig({ split: f });
|
||||
}
|
||||
|
||||
function wireSplitter() {
|
||||
const panes = $('panes');
|
||||
const sp = $('splitter');
|
||||
setSplit(typeof state.cfg.split === 'number' ? state.cfg.split : 0.5, false);
|
||||
let drag = false;
|
||||
|
||||
function fromX(x) {
|
||||
const r = panes.getBoundingClientRect();
|
||||
let f = (x - r.left) / (r.width - 9);
|
||||
if (state.cfg.swapped) f = 1 - f;
|
||||
return f;
|
||||
}
|
||||
sp.addEventListener('mousedown', (e) => {
|
||||
e.preventDefault();
|
||||
drag = true;
|
||||
panes.classList.add('dragging');
|
||||
});
|
||||
window.addEventListener('mousemove', (e) => { if (drag) setSplit(fromX(e.clientX), false); });
|
||||
window.addEventListener('mouseup', () => {
|
||||
if (!drag) return;
|
||||
drag = false;
|
||||
panes.classList.remove('dragging');
|
||||
wn.setConfig({ split: state.cfg.split });
|
||||
});
|
||||
sp.addEventListener('dblclick', () => setSplit(0.5, true));
|
||||
sp.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||
e.preventDefault();
|
||||
let d = e.key === 'ArrowRight' ? 0.02 : -0.02;
|
||||
if (state.cfg.swapped) d = -d;
|
||||
setSplit(state.cfg.split + d, true);
|
||||
});
|
||||
$('splitRange').addEventListener('input', (e) => setSplit(parseInt(e.target.value, 10) / 100, false));
|
||||
$('splitRange').addEventListener('change', () => wn.setConfig({ split: state.cfg.split }));
|
||||
$('splitWrap').addEventListener('dblclick', () => setSplit(0.5, true));
|
||||
}
|
||||
|
||||
/* ---------- wiring ---------- */
|
||||
|
||||
function wire() {
|
||||
ed.addEventListener('input', onEdit);
|
||||
ed.addEventListener('scroll', () => requestAnimationFrame(syncScroll));
|
||||
ed.addEventListener('blur', saveNow);
|
||||
|
||||
// The formatting toolbar and the Ctrl+B, I, U, K shortcuts live in format.js.
|
||||
const fmt = window.SwiftFormat.init({ editor: ed, onEdit });
|
||||
state.tables = window.SwiftTables.init({ editor: ed, api: fmt.api, toast, getFrame: () => $('preview') });
|
||||
window.SwiftSnippets.init({ api: fmt.api, toast });
|
||||
window.SwiftMedia.init({ api: fmt.api, toast, openModal });
|
||||
window.SwiftProof.init({ editor: ed, api: fmt.api, toast, getConfig: () => state.cfg });
|
||||
window.SwiftExport.init({ toast, openModal, getTitle: currentTitle, getText: () => ed.value, snapshot: snapshotPreview });
|
||||
wireSplitter();
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
const mod = e.ctrlKey || e.metaKey;
|
||||
if (mod && e.shiftKey && e.key.toLowerCase() === 'f') { e.preventDefault(); $('btnSwap').click(); }
|
||||
else if (mod && !e.shiftKey && e.key.toLowerCase() === 'n') { e.preventDefault(); newNote(); }
|
||||
});
|
||||
|
||||
$('btnSwap').addEventListener('click', () => {
|
||||
state.cfg.swapped = !state.cfg.swapped;
|
||||
applyLayout();
|
||||
wn.setConfig({ swapped: state.cfg.swapped });
|
||||
ed.focus();
|
||||
});
|
||||
|
||||
$('btnSidebar').addEventListener('click', () => {
|
||||
state.cfg.sidebar = !state.cfg.sidebar;
|
||||
applyLayout();
|
||||
wn.setConfig({ sidebar: state.cfg.sidebar });
|
||||
});
|
||||
|
||||
$('btnNew').addEventListener('click', () => newNote());
|
||||
$('btnDelete').addEventListener('click', deleteCurrent);
|
||||
|
||||
$('search').addEventListener('input', () => {
|
||||
clearTimeout(state.searchTimer);
|
||||
state.searchTimer = setTimeout(refreshNotes, 200);
|
||||
});
|
||||
|
||||
const title = $('titleInput');
|
||||
title.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); title.blur(); ed.focus(); }
|
||||
else if (e.key === 'Escape') {
|
||||
title.value = (state.file || '').replace(/\.(wiki|mediawiki|txt)$/i, '');
|
||||
ed.focus();
|
||||
}
|
||||
});
|
||||
title.addEventListener('change', renameCurrent);
|
||||
|
||||
$('wikiSelect').addEventListener('change', async (e) => {
|
||||
state.cfg.active = e.target.value || null;
|
||||
await wn.setConfig({ active: state.cfg.active });
|
||||
updateCssUi();
|
||||
connectActive({ dialog: true });
|
||||
});
|
||||
|
||||
$('btnSettings').addEventListener('click', openSettings);
|
||||
$('modeBadge').addEventListener('click', () => showFallbackDialog());
|
||||
|
||||
$('btnCssLoad').addEventListener('click', async () => {
|
||||
const p = await wn.pickCss();
|
||||
if (p) setCssInfo({ path: p, on: true });
|
||||
});
|
||||
$('btnCssToggle').addEventListener('click', () => {
|
||||
const info = cssInfo();
|
||||
setCssInfo({ path: info.path, on: !info.on });
|
||||
});
|
||||
$('btnCssClear').addEventListener('click', () => setCssInfo({ path: '', on: false }));
|
||||
|
||||
window.addEventListener('beforeunload', () => {
|
||||
if (state.dirty && state.file) wn.writeNoteSync(state.file, ed.value);
|
||||
});
|
||||
window.addEventListener('blur', saveNow);
|
||||
}
|
||||
|
||||
/* ---------- start ---------- */
|
||||
|
||||
async function init() {
|
||||
state.cfg = await wn.getConfig();
|
||||
if (!state.cfg.css) state.cfg.css = {};
|
||||
if (state.cfg.active && !state.cfg.profiles.some((p) => p.id === state.cfg.active)) state.cfg.active = null;
|
||||
|
||||
applyLayout();
|
||||
fillWikiSelect();
|
||||
updateCssUi();
|
||||
updateBadge();
|
||||
$('folderLabel').textContent = state.cfg.notesDir;
|
||||
$('folderLabel').title = state.cfg.notesDir;
|
||||
wire();
|
||||
|
||||
await refreshNotes();
|
||||
if (!state.notes.length) {
|
||||
await createWelcome();
|
||||
await refreshNotes();
|
||||
}
|
||||
const last = state.notes.find((n) => n.file === state.cfg.lastNote);
|
||||
await openNote((last || state.notes[0]).file);
|
||||
|
||||
connectActive({ dialog: true });
|
||||
}
|
||||
|
||||
init().catch((e) => {
|
||||
document.body.textContent = 'Swiftmark could not start: ' + e.message;
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,399 @@
|
||||
:root {
|
||||
--bg: #f3f3f3;
|
||||
--panel: #ffffff;
|
||||
--text: #1f2328;
|
||||
--muted: #656d76;
|
||||
--line: #d0d7de;
|
||||
--accent: #0b6bcb;
|
||||
--accentText: #ffffff;
|
||||
--btn: #f6f8fa;
|
||||
--btnHover: #eaeef2;
|
||||
--warn: #7d4e00;
|
||||
--warnBg: #fff1c2;
|
||||
--ok: #116329;
|
||||
--okBg: #d8f5df;
|
||||
--sel: #ddf4ff;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #1b1c1f;
|
||||
--panel: #24262a;
|
||||
--text: #e6e8eb;
|
||||
--muted: #9aa0a6;
|
||||
--line: #3a3d42;
|
||||
--accent: #4c9ffe;
|
||||
--accentText: #0b1220;
|
||||
--btn: #2e3136;
|
||||
--btnHover: #3a3e44;
|
||||
--warn: #f0c75e;
|
||||
--warnBg: #3b2f0b;
|
||||
--ok: #6fdc84;
|
||||
--okBg: #12351c;
|
||||
--sel: #16314f;
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; border-radius: 0 !important; }
|
||||
|
||||
html, body { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 13px/1.4 "Segoe UI", system-ui, sans-serif;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#app { display: flex; flex-direction: column; height: 100%; }
|
||||
|
||||
button, select, input {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--btn);
|
||||
border: 1px solid var(--line);
|
||||
padding: 4px 10px;
|
||||
height: 28px;
|
||||
}
|
||||
button { cursor: pointer; }
|
||||
button:hover:not(:disabled) { background: var(--btnHover); }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button.primary { background: var(--accent); color: var(--accentText); border-color: var(--accent); }
|
||||
button.primary:hover:not(:disabled) { filter: brightness(1.1); background: var(--accent); }
|
||||
button.on { background: var(--sel); border-color: var(--accent); }
|
||||
button[hidden] { display: none; }
|
||||
input[type="search"], input[type="text"], input:not([type]) { background: var(--panel); }
|
||||
|
||||
#topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
background: var(--bg);
|
||||
border-bottom: 1px solid var(--line);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
#topbar .sep { width: 1px; height: 20px; background: var(--line); margin: 0 4px; }
|
||||
.spacer { flex: 1 1 auto; }
|
||||
#cssName { color: var(--muted); font-size: 12px; max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#wikiSelect { max-width: 220px; }
|
||||
|
||||
.badge { font-weight: 600; }
|
||||
.badge.live { background: var(--okBg); color: var(--ok); border-color: var(--ok); }
|
||||
.badge.rough { background: var(--warnBg); color: var(--warn); border-color: var(--warn); }
|
||||
.badge.busy { color: var(--muted); }
|
||||
|
||||
#main { display: flex; flex: 1 1 auto; min-height: 0; }
|
||||
|
||||
#sidebar {
|
||||
flex: 0 0 230px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--panel);
|
||||
border-right: 1px solid var(--line);
|
||||
min-height: 0;
|
||||
}
|
||||
#sidebar.hidden { display: none; }
|
||||
.sbTop { display: flex; gap: 6px; padding: 8px; border-bottom: 1px solid var(--line); }
|
||||
.sbTop input { flex: 1 1 auto; min-width: 0; }
|
||||
#noteList { list-style: none; margin: 0; padding: 0; overflow-y: auto; flex: 1 1 auto; }
|
||||
#noteList li {
|
||||
padding: 7px 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
cursor: pointer;
|
||||
}
|
||||
#noteList li:hover { background: var(--btnHover); }
|
||||
#noteList li.active { background: var(--sel); }
|
||||
#noteList .t { display: block; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#noteList .d { display: block; color: var(--muted); font-size: 11px; }
|
||||
#noteList .none { color: var(--muted); cursor: default; }
|
||||
#folderLabel {
|
||||
padding: 6px 10px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
border-top: 1px solid var(--line);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#panes {
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
gap: 1px;
|
||||
background: var(--line);
|
||||
min-width: 0;
|
||||
}
|
||||
#panes.swapped { flex-direction: row-reverse; }
|
||||
|
||||
.pane {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--panel);
|
||||
}
|
||||
.paneHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--bg);
|
||||
flex: 0 0 auto;
|
||||
min-height: 41px;
|
||||
}
|
||||
.paneTitle { font-weight: 600; }
|
||||
#previewSource { color: var(--muted); font-size: 12px; }
|
||||
#titleInput { flex: 1 1 auto; min-width: 60px; font-weight: 600; background: var(--panel); }
|
||||
.fmtbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--panel);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.fmtbar .grp { display: flex; align-items: center; gap: 2px; }
|
||||
.fmtbar button { height: 26px; min-width: 28px; padding: 2px 7px; display: inline-flex; align-items: center; justify-content: center; white-space: nowrap; }
|
||||
.fmtbar select { height: 26px; padding: 2px 4px; max-width: 110px; }
|
||||
.fmtbar svg { display: block; }
|
||||
.swA { font-weight: 700; border-bottom: 3px solid #d00000; line-height: 1; padding: 0 1px; }
|
||||
.swH { background: #ffe94d; color: #000; padding: 0 3px; line-height: 1.2; }
|
||||
|
||||
.pop {
|
||||
position: fixed;
|
||||
z-index: 60;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
padding: 8px;
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, .3);
|
||||
width: 244px;
|
||||
}
|
||||
.pop[hidden] { display: none; }
|
||||
.popTitle { font-weight: 600; margin-bottom: 6px; }
|
||||
.pop .grid { display: grid; grid-template-columns: repeat(10, 20px); gap: 2px; }
|
||||
.pop .sw { width: 20px; height: 20px; padding: 0; min-width: 0; border: 1px solid rgba(128, 128, 128, .55); }
|
||||
.pop .sw:hover { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
.popRow { display: flex; gap: 6px; margin-top: 8px; }
|
||||
.popRow input { flex: 1 1 auto; min-width: 0; height: 26px; }
|
||||
.popRow button { height: 26px; }
|
||||
.popClear { margin-top: 8px; width: 100%; height: 26px; }
|
||||
.paneBody { flex: 1 1 auto; min-height: 0; position: relative; }
|
||||
|
||||
#editor {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
resize: none;
|
||||
outline: none;
|
||||
padding: 12px 14px;
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
font: 14px/1.5 Consolas, "Cascadia Mono", Menlo, monospace;
|
||||
tab-size: 4;
|
||||
}
|
||||
|
||||
#preview { display: block; width: 100%; height: 100%; border: 0; background: #fff; }
|
||||
|
||||
#statusbar {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding: 3px 10px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
background: var(--bg);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, .45);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 50;
|
||||
}
|
||||
.dialog {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
width: min(560px, 92vw);
|
||||
max-height: 88vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 8px 30px rgba(0, 0, 0, .35);
|
||||
}
|
||||
.dialog.wide { width: min(680px, 94vw); }
|
||||
.dialog h2 { margin: 0; padding: 12px 16px; font-size: 15px; border-bottom: 1px solid var(--line); }
|
||||
.dialogBody { padding: 12px 16px; overflow-y: auto; }
|
||||
.dialogBody p { margin: 0 0 10px; }
|
||||
.dialogBody ol { margin: 0 0 6px 20px; padding: 0; }
|
||||
.dialogBody li { margin-bottom: 6px; }
|
||||
.dialogBody code {
|
||||
background: var(--btn);
|
||||
border: 1px solid var(--line);
|
||||
padding: 0 4px;
|
||||
font: 12px Consolas, monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
.dialogButtons {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 10px 16px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.formRow { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
||||
.formRow label { flex: 0 0 90px; color: var(--muted); }
|
||||
.formRow input, .formRow select { flex: 1 1 auto; min-width: 0; }
|
||||
.formRow code { flex: 1 1 auto; }
|
||||
.formActions { display: flex; gap: 8px; margin: 10px 0 6px; flex-wrap: wrap; }
|
||||
.formResult { min-height: 20px; margin-top: 6px; }
|
||||
.formResult.good { color: var(--ok); }
|
||||
.formResult.bad { color: var(--warn); }
|
||||
.divider { border: 0; border-top: 1px solid var(--line); margin: 14px 0; }
|
||||
|
||||
#toast {
|
||||
position: fixed;
|
||||
right: 14px;
|
||||
bottom: 34px;
|
||||
background: var(--text);
|
||||
color: var(--bg);
|
||||
padding: 8px 12px;
|
||||
max-width: 420px;
|
||||
z-index: 80;
|
||||
}
|
||||
#toast[hidden] { display: none; }
|
||||
|
||||
/* ---------- 1.2: splitter, table menu, snippets, media ---------- */
|
||||
|
||||
#splitWrap { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; }
|
||||
#splitRange { width: 110px; height: 20px; padding: 0; background: transparent; border: 0; }
|
||||
#topbar { flex-wrap: wrap; }
|
||||
|
||||
#panes { gap: 0; --ef: 0.5; }
|
||||
#paneEditor { flex: 0 0 calc((100% - 9px) * var(--ef)); }
|
||||
#panePreview { flex: 1 1 0; }
|
||||
#splitter {
|
||||
flex: 0 0 9px;
|
||||
cursor: col-resize;
|
||||
background: var(--line);
|
||||
position: relative;
|
||||
}
|
||||
#splitter::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 3px; top: 50%;
|
||||
width: 3px; height: 36px; margin-top: -18px;
|
||||
background: var(--muted);
|
||||
opacity: .6;
|
||||
}
|
||||
#splitter:hover, #splitter:focus, #panes.dragging #splitter { background: var(--accent); outline: none; }
|
||||
#panes.dragging { cursor: col-resize; user-select: none; }
|
||||
#panes.dragging iframe { pointer-events: none; }
|
||||
|
||||
.tmenu {
|
||||
position: fixed;
|
||||
z-index: 70;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, .3);
|
||||
width: 380px;
|
||||
max-height: calc(100vh - 12px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
.tmenu[hidden], .gridpop[hidden] { display: none; }
|
||||
.tHead { padding: 6px 10px; font-weight: 600; background: var(--bg); border-bottom: 1px solid var(--line); }
|
||||
.tclip { display: flex; gap: 2px; padding: 4px; border-bottom: 1px solid var(--line); }
|
||||
.tclip .tm { flex: 1 1 0; text-align: center; }
|
||||
.tbody { display: grid; grid-template-columns: 1fr 1fr; gap: 0; }
|
||||
.tsec { padding: 4px; border-bottom: 1px solid var(--line); }
|
||||
.tsec:nth-child(odd) { border-right: 1px solid var(--line); }
|
||||
.tsecTitle { font-size: 11px; text-transform: uppercase; color: var(--muted); padding: 2px 6px; }
|
||||
button.tm {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 26px;
|
||||
text-align: left;
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
padding: 2px 6px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
button.tm:hover:not(:disabled) { background: var(--sel); border-color: var(--accent); }
|
||||
|
||||
.gridpop { width: auto; }
|
||||
.tgrid { display: grid; grid-template-columns: repeat(8, 20px); gap: 2px; }
|
||||
button.tg { width: 20px; height: 20px; padding: 0; min-width: 0; }
|
||||
button.tg.hot { background: var(--accent); border-color: var(--accent); }
|
||||
.tlabel { margin: 6px 0; color: var(--muted); min-height: 18px; }
|
||||
.tchk { display: block; margin-top: 3px; }
|
||||
.tchk input { height: auto; padding: 0; }
|
||||
|
||||
.pop.snippets { width: 300px; }
|
||||
.snFilter { width: 100%; margin-bottom: 6px; height: 26px; }
|
||||
.snList { max-height: 340px; overflow-y: auto; }
|
||||
.snGroup { font-size: 11px; text-transform: uppercase; color: var(--muted); padding: 6px 6px 2px; }
|
||||
.snNote { margin-top: 8px; font-size: 12px; color: var(--warn); background: var(--warnBg); padding: 6px 8px; }
|
||||
|
||||
.mTabs { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 10px; }
|
||||
.mNote { color: var(--muted); font-size: 12px; background: var(--btn); padding: 6px 8px; border: 1px solid var(--line); }
|
||||
.mCodeLabel { margin-top: 6px; color: var(--muted); font-size: 12px; }
|
||||
.mCode { width: 100%; resize: none; font: 13px/1.4 Consolas, monospace; background: var(--panel); color: var(--text); border: 1px solid var(--line); padding: 6px; }
|
||||
.mCopy { margin-top: 6px; }
|
||||
|
||||
/* ---------- 1.3: spelling, thesaurus, export ---------- */
|
||||
|
||||
.proof {
|
||||
position: fixed;
|
||||
right: 14px;
|
||||
bottom: 38px;
|
||||
z-index: 55;
|
||||
width: 340px;
|
||||
max-height: 70vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, .3);
|
||||
}
|
||||
.proof[hidden] { display: none; }
|
||||
.proofHead { display: flex; justify-content: space-between; align-items: center; padding: 6px; border-bottom: 1px solid var(--line); background: var(--bg); }
|
||||
.proofTabs { display: flex; gap: 4px; }
|
||||
.proofX { height: 26px; }
|
||||
.proofBody { padding: 10px; overflow-y: auto; }
|
||||
.proofRow { display: flex; gap: 6px; align-items: center; margin-bottom: 8px; }
|
||||
.proofRow input:not([type="checkbox"]), .proofRow select { flex: 1 1 auto; min-width: 0; height: 26px; }
|
||||
.proofChk { white-space: nowrap; font-size: 12px; color: var(--muted); }
|
||||
.proofChk input { height: auto; padding: 0; }
|
||||
.proofLabel { color: var(--muted); font-size: 12px; }
|
||||
.badWord { font-size: 20px; font-weight: 700; color: #c0281c; margin: 2px 0 4px; word-break: break-all; }
|
||||
.proofCtx { font-size: 12px; color: var(--muted); margin-bottom: 8px; word-break: break-word; }
|
||||
.proofCtx b { color: var(--text); }
|
||||
.proofInput { width: 100%; height: 28px; margin-bottom: 6px; }
|
||||
.sugList { max-height: 150px; overflow-y: auto; border: 1px solid var(--line); margin-bottom: 8px; }
|
||||
.sugList .tm { height: 24px; }
|
||||
.proofActs { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
|
||||
.proofActs button { height: 26px; padding: 2px 6px; }
|
||||
.proofHint { font-size: 12px; color: var(--muted); margin: 6px 0; }
|
||||
.proofDone { padding: 10px; background: var(--okBg); color: var(--ok); }
|
||||
.thesRes { max-height: 46vh; overflow-y: auto; }
|
||||
.thesPos { font-weight: 700; margin: 8px 0 2px; border-bottom: 1px solid var(--line); }
|
||||
.thesSense { margin: 6px 0 8px; }
|
||||
.thesGloss { font-size: 12px; color: var(--muted); margin-bottom: 3px; }
|
||||
.thesChips { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
button.chip { height: 24px; padding: 1px 8px; }
|
||||
button.chip:hover { background: var(--sel); border-color: var(--accent); }
|
||||
|
||||
.expGroup { margin-bottom: 12px; }
|
||||
.expGroup.dim { opacity: .45; }
|
||||
.expTitle { font-weight: 600; margin-bottom: 4px; }
|
||||
.expOpt { display: flex; gap: 8px; align-items: flex-start; padding: 4px 0; cursor: pointer; }
|
||||
.expOpt input { height: auto; margin-top: 3px; padding: 0; }
|
||||
.expOpt small { display: block; color: var(--muted); }
|
||||
.fmtbar .grp { flex-wrap: wrap; }
|
||||
Reference in New Issue
Block a user