diff --git a/renderer/export.js b/renderer/export.js
new file mode 100644
index 0000000..3b09d64
--- /dev/null
+++ b/renderer/export.js
@@ -0,0 +1,146 @@
+// Export dialog: PDF, Word (.docx) or wikitext. PDF and Word can hold the rendered preview or the markup.
+(function () {
+ 'use strict';
+
+ const SKIP = { SCRIPT: 1, STYLE: 1, LINK: 1, NOSCRIPT: 1, META: 1, TITLE: 1 };
+
+ // Word cannot read stylesheets, so the look of the preview is copied onto each element as inline style.
+ function inlineBody(doc) {
+ const win = doc.defaultView;
+ const body = doc.body;
+ const clone = body.cloneNode(true);
+ const a = doc.createTreeWalker(body, NodeFilter.SHOW_ELEMENT);
+ const b = doc.createTreeWalker(clone, NodeFilter.SHOW_ELEMENT);
+ const kill = [];
+ let o = a.currentNode;
+ let c = b.currentNode;
+ do {
+ const tag = o.tagName;
+ const cs = win.getComputedStyle(o);
+ if (SKIP[tag] || cs.display === 'none' || /\b(mw-editsection|noprint|mw-empty-elt)\b/.test(o.className || '')) {
+ kill.push(c);
+ } else {
+ const st = [];
+ const col = cs.color;
+ if (col && col !== 'rgb(0, 0, 0)' && col !== 'rgb(32, 33, 34)') st.push('color:' + col);
+ const bg = cs.backgroundColor;
+ if (bg && bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent' && bg !== 'rgb(255, 255, 255)' && tag !== 'BODY') st.push('background-color:' + bg);
+ if (parseInt(cs.fontWeight, 10) >= 600 && !/^(H[1-6]|B|STRONG|TH)$/.test(tag)) st.push('font-weight:bold');
+ if (cs.fontStyle === 'italic' && !/^(I|EM|CITE)$/.test(tag)) st.push('font-style:italic');
+ if (/^(P|DIV|TD|TH|H[1-6]|LI|BLOCKQUOTE)$/.test(tag) && /^(center|right|justify)$/.test(cs.textAlign)) st.push('text-align:' + cs.textAlign);
+ if (/^(TABLE|TD|TH)$/.test(tag)) {
+ const w = parseFloat(cs.borderTopWidth);
+ if (w > 0 && cs.borderTopStyle !== 'none') st.push('border:1px solid ' + cs.borderTopColor);
+ }
+ if (st.length) c.setAttribute('style', (c.getAttribute('style') ? c.getAttribute('style') + ';' : '') + st.join(';'));
+ c.removeAttribute('data-swm');
+ }
+ o = a.nextNode();
+ c = b.nextNode();
+ } while (o && c);
+ kill.forEach((k) => { if (k.parentNode) k.parentNode.removeChild(k); });
+ return clone.innerHTML;
+ }
+
+ function cleanHtml(doc) {
+ return '' + doc.documentElement.outerHTML.replace(/\sdata-swm="[^"]*"/g, '');
+ }
+
+ function init(opts) {
+ const wn = window.wn;
+ const toast = opts.toast;
+ const btn = document.getElementById('btnExport');
+ if (!btn) return;
+ btn.addEventListener('click', openDialog);
+
+ function openDialog() {
+ const wrap = document.createElement('div');
+ const form = { format: 'pdf', content: 'preview', paper: 'Letter' };
+ const rows = [];
+
+ function group(title, name, choices, onchange) {
+ const g = document.createElement('div');
+ g.className = 'expGroup';
+ const t = document.createElement('div');
+ t.className = 'expTitle';
+ t.textContent = title;
+ g.appendChild(t);
+ const inputs = [];
+ choices.forEach((ch) => {
+ const l = document.createElement('label');
+ l.className = 'expOpt';
+ const i = document.createElement('input');
+ i.type = 'radio';
+ i.name = 'exp-' + name;
+ i.value = ch[0];
+ i.checked = form[name] === ch[0];
+ i.addEventListener('change', () => { form[name] = ch[0]; refresh(); });
+ l.appendChild(i);
+ const s = document.createElement('span');
+ const b = document.createElement('b');
+ b.textContent = ch[1];
+ s.appendChild(b);
+ if (ch[2]) { const d = document.createElement('small'); d.textContent = ch[2]; s.appendChild(d); }
+ l.appendChild(s);
+ g.appendChild(l);
+ inputs.push(i);
+ });
+ wrap.appendChild(g);
+ rows.push({ g, inputs });
+ return g;
+ }
+
+ group('Format', 'format', [
+ ['pdf', 'PDF', 'A print-ready document.'],
+ ['docx', 'Word document (.docx)', 'Opens in Word, LibreOffice and Google Docs.'],
+ ['wiki', 'Wikitext (.wiki)', 'The raw markup, ready to paste into a wiki.']
+ ]);
+ const contentG = group('What goes in the file', 'content', [
+ ['preview', 'The preview', 'The page as it looks rendered, with your wiki\'s styling when the preview is live.'],
+ ['markup', 'The wiki markup', 'The source text itself, in a monospace font.']
+ ]);
+ const paperRow = document.createElement('div');
+ paperRow.className = 'formRow';
+ const pl = document.createElement('label');
+ pl.textContent = 'Paper size';
+ const ps = document.createElement('select');
+ [['Letter', 'Letter (8.5 x 11 in)'], ['A4', 'A4']].forEach((p) => { const o = document.createElement('option'); o.value = p[0]; o.textContent = p[1]; ps.appendChild(o); });
+ ps.addEventListener('change', () => { form.paper = ps.value; });
+ paperRow.appendChild(pl);
+ paperRow.appendChild(ps);
+ wrap.appendChild(paperRow);
+
+ function refresh() {
+ const wiki = form.format === 'wiki';
+ contentG.classList.toggle('dim', wiki);
+ contentG.querySelectorAll('input').forEach((i) => { i.disabled = wiki; });
+ ps.disabled = wiki;
+ paperRow.classList.toggle('dim', wiki);
+ }
+ refresh();
+
+ const m = opts.openModal({
+ title: 'Export "' + opts.getTitle() + '"',
+ content: wrap,
+ buttons: [{ label: 'Cancel', value: null }, { label: 'Export...', value: 'go', primary: true }]
+ });
+ m.promise.then(async (v) => {
+ if (v !== 'go') return;
+ const req = { format: form.format, content: form.content, paper: form.paper, title: opts.getTitle(), text: opts.getText() };
+ if (form.format !== 'wiki' && form.content === 'preview') {
+ toast('Rendering the preview...');
+ const doc = await opts.snapshot();
+ if (!doc) { toast('The preview is not ready. Try again in a moment.'); return; }
+ if (form.format === 'pdf') req.html = cleanHtml(doc);
+ else req.body = inlineBody(doc);
+ }
+ toast('Exporting...', 8000);
+ const r = await wn.exportFile(req);
+ if (r.canceled) { toast('Export canceled.'); return; }
+ toast(r.ok ? 'Saved ' + r.path : 'Export failed: ' + r.error, r.ok ? 8000 : 8000);
+ });
+ }
+ }
+
+ window.SwiftExport = { init, inlineBody };
+})();
diff --git a/renderer/media.js b/renderer/media.js
new file mode 100644
index 0000000..34095b3
--- /dev/null
+++ b/renderer/media.js
@@ -0,0 +1,247 @@
+// Media place-marker code: pictures, thumbnails, video, sound. Nothing is uploaded.
+// buildCode() is pure and also runs under Node for tests.
+(function (root) {
+ 'use strict';
+
+ const KINDS = [
+ { id: 'picture', label: 'Picture' },
+ { id: 'thumb', label: 'Thumbnail' },
+ { id: 'video', label: 'Video file' },
+ { id: 'vembed', label: 'Video embed' },
+ { id: 'sound', label: 'Sound file' },
+ { id: 'sembed', label: 'Sound embed' }
+ ];
+
+ const DEFAULTS = {
+ picture: { file: 'Example.jpg', align: 'none', width: '300', alt: '' },
+ thumb: { file: 'Example.jpg', type: 'thumb', align: 'right', width: '250', caption: 'Caption' },
+ video: { file: 'Example.webm', type: 'thumb', align: 'right', width: '320', caption: 'Caption', start: '', end: '' },
+ vembed: { service: 'url', url: 'https://www.youtube.com/watch?v=VIDEOID', id: 'VIDEOID', align: 'right', width: '560', height: '315', caption: 'Caption' },
+ sound: { file: 'Example.ogg', mode: 'player', align: 'right', width: '', caption: 'Caption' },
+ sembed: { service: 'url', url: 'https://example.com/sound.mp3', id: '', align: 'right', caption: 'Caption' }
+ };
+
+ const clean = (s) => String(s === undefined || s === null ? '' : s).replace(/^\s*(File|Image|Media):/i, '').trim();
+ const px = (w) => (String(w || '').trim() ? String(w).trim().replace(/px$/i, '') + 'px' : '');
+ const cap = (s) => String(s || '').replace(/\|/g, '{{!}}').trim();
+
+ function buildCode(kind, o) {
+ o = Object.assign({}, DEFAULTS[kind], o || {});
+ const parts = [];
+ if (kind === 'picture') {
+ parts.push('File:' + clean(o.file));
+ if (o.align && o.align !== 'none') parts.push(o.align);
+ if (px(o.width)) parts.push(px(o.width));
+ if (o.alt) parts.push('alt=' + cap(o.alt));
+ return '[[' + parts.join('|') + ']]';
+ }
+ if (kind === 'thumb' || kind === 'video') {
+ parts.push('File:' + clean(o.file));
+ if (o.type && o.type !== 'none') parts.push(o.type);
+ if (o.align && o.align !== 'none') parts.push(o.align);
+ if (o.type !== 'frame' && px(o.width)) parts.push(px(o.width));
+ if (kind === 'video') {
+ if (String(o.start || '').trim()) parts.push('start=' + String(o.start).trim());
+ if (String(o.end || '').trim()) parts.push('end=' + String(o.end).trim());
+ }
+ if (cap(o.caption)) parts.push(cap(o.caption));
+ return '[[' + parts.join('|') + ']]';
+ }
+ if (kind === 'sound') {
+ if (o.mode === 'link') return '[[Media:' + clean(o.file) + '|' + (cap(o.caption) || 'Listen') + ']]';
+ parts.push('File:' + clean(o.file));
+ parts.push('thumb');
+ if (o.align && o.align !== 'none') parts.push(o.align);
+ if (px(o.width)) parts.push(px(o.width));
+ if (cap(o.caption)) parts.push(cap(o.caption));
+ return '[[' + parts.join('|') + ']]';
+ }
+ if (kind === 'vembed' || kind === 'sembed') {
+ if (o.service && o.service !== 'url') {
+ const a = ['{{#ev:' + o.service, String(o.id || '').trim()];
+ const extra = kind === 'vembed'
+ ? [String(o.width || '').trim(), o.align && o.align !== 'none' ? o.align : '', cap(o.caption)]
+ : ['', o.align && o.align !== 'none' ? o.align : '', cap(o.caption)];
+ while (extra.length && !extra[extra.length - 1]) extra.pop();
+ return a.concat(extra).join('|') + '}}';
+ }
+ const out = ['{{#evu:' + String(o.url || '').trim()];
+ if (o.align && o.align !== 'none') out.push('alignment=' + o.align);
+ if (kind === 'vembed') {
+ const w = String(o.width || '').trim();
+ const h = String(o.height || '').trim();
+ if (w && h) out.push('dimensions=' + w + 'x' + h);
+ else if (w) out.push('dimensions=' + w);
+ }
+ if (cap(o.caption)) { out.push('description=' + cap(o.caption)); out.push('container=frame'); }
+ return out.join('|') + '}}';
+ }
+ return '';
+ }
+
+ const pure = { buildCode, KINDS, DEFAULTS };
+ if (typeof module !== 'undefined' && module.exports) module.exports = pure;
+ if (typeof window === 'undefined') return;
+
+ /* ---------- dialog ---------- */
+
+ const NOTES = {
+ picture: 'Place-marker only. Nothing is uploaded: use the name of a file that is, or will be, on your wiki.',
+ thumb: 'Place-marker only. Nothing is uploaded. A thumbnail gets a border, the caption underneath and floats to the side you pick.',
+ video: 'Place-marker only. Playing video files in a page needs the TimedMediaHandler extension on your wiki (or video files allowed by your wiki\'s settings).',
+ vembed: 'Video embeds need an embed extension such as EmbedVideo on your wiki. Without it the code shows as plain text. Check which one your wiki uses.',
+ sound: 'Place-marker only. Nothing is uploaded. Playing sound files in a page needs the TimedMediaHandler extension on your wiki.',
+ sembed: 'Sound embeds need an embed extension such as EmbedVideo on your wiki. Without it the code shows as plain text.'
+ };
+
+ const WARN = {
+ video: 'Video files need the TimedMediaHandler extension on your wiki to play.',
+ vembed: 'Embeds need the EmbedVideo extension (or your wiki\'s equivalent).',
+ sound: 'Sound files need the TimedMediaHandler extension on your wiki to play.',
+ sembed: 'Embeds need the EmbedVideo extension (or your wiki\'s equivalent).'
+ };
+
+ function init(opts) {
+ const api = opts.api;
+ const toast = opts.toast;
+ const openModal = opts.openModal;
+ const btn = document.getElementById('btnMedia');
+ if (!btn) return;
+ btn.addEventListener('mousedown', (e) => e.preventDefault());
+ btn.addEventListener('click', () => open('picture'));
+
+ function open(start) {
+ let kind = start;
+ const vals = {};
+ Object.keys(DEFAULTS).forEach((k) => { vals[k] = Object.assign({}, DEFAULTS[k]); });
+
+ const wrap = document.createElement('div');
+ const tabs = document.createElement('div');
+ tabs.className = 'mTabs';
+ const form = document.createElement('div');
+ const note = document.createElement('p');
+ note.className = 'mNote';
+ const codeLabel = document.createElement('div');
+ codeLabel.className = 'mCodeLabel';
+ codeLabel.textContent = 'Code that will be inserted';
+ const code = document.createElement('textarea');
+ code.className = 'mCode';
+ code.readOnly = true;
+ code.rows = 3;
+ code.spellcheck = false;
+ const copy = document.createElement('button');
+ copy.textContent = 'Copy code';
+ copy.className = 'mCopy';
+ wrap.appendChild(tabs);
+ wrap.appendChild(note);
+ wrap.appendChild(form);
+ wrap.appendChild(codeLabel);
+ wrap.appendChild(code);
+ wrap.appendChild(copy);
+
+ const sel = (o, list) => {
+ const s = document.createElement('select');
+ list.forEach((p) => { const x = document.createElement('option'); x.value = p[0]; x.textContent = p[1]; s.appendChild(x); });
+ s.value = o;
+ return s;
+ };
+ const ALIGN = [['none', 'No alignment'], ['left', 'Left'], ['center', 'Center'], ['right', 'Right']];
+
+ function field(label, key, type, list, hint) {
+ const row = document.createElement('div');
+ row.className = 'formRow';
+ const l = document.createElement('label');
+ l.textContent = label;
+ row.appendChild(l);
+ let input;
+ if (type === 'select') input = sel(vals[kind][key], list);
+ else { input = document.createElement('input'); input.value = vals[kind][key]; input.spellcheck = false; if (hint) input.placeholder = hint; }
+ const upd = () => { vals[kind][key] = input.value; refresh(); };
+ input.addEventListener('input', upd);
+ input.addEventListener('change', () => { upd(); if (type === 'select') draw(); });
+ row.appendChild(input);
+ form.appendChild(row);
+ }
+
+ function draw() {
+ tabs.innerHTML = '';
+ KINDS.forEach((k) => {
+ const b = document.createElement('button');
+ b.textContent = k.label;
+ b.classList.toggle('on', k.id === kind);
+ b.addEventListener('click', () => { kind = k.id; draw(); });
+ tabs.appendChild(b);
+ });
+ note.textContent = NOTES[kind];
+ form.innerHTML = '';
+ const o = vals[kind];
+ if (kind === 'picture') {
+ field('File name', 'file', 'text', null, 'Example.jpg');
+ field('Alignment', 'align', 'select', ALIGN);
+ field('Width (px)', 'width', 'text', null, 'blank for full size');
+ field('Alt text', 'alt', 'text');
+ } else if (kind === 'thumb' || kind === 'video') {
+ field('File name', 'file', 'text', null, kind === 'video' ? 'Example.webm' : 'Example.jpg');
+ field('Style', 'type', 'select', [['thumb', 'Thumbnail (border and caption)'], ['frame', 'Frame (full size, caption)'], ['frameless', 'Frameless (no border)'], ['none', 'Plain']]);
+ field('Alignment', 'align', 'select', ALIGN);
+ if (o.type !== 'frame') field('Width (px)', 'width', 'text', null, 'e.g. 250');
+ if (kind === 'video') {
+ field('Start (sec)', 'start', 'text', null, 'optional');
+ field('End (sec)', 'end', 'text', null, 'optional');
+ }
+ field('Caption', 'caption', 'text');
+ } else if (kind === 'sound') {
+ field('File name', 'file', 'text', null, 'Example.ogg');
+ field('Form', 'mode', 'select', [['player', 'Player box'], ['link', 'Plain link to the file']]);
+ if (o.mode !== 'link') {
+ field('Alignment', 'align', 'select', ALIGN);
+ field('Width (px)', 'width', 'text', null, 'optional');
+ }
+ field('Caption', 'caption', 'text');
+ } else if (kind === 'vembed') {
+ field('Source', 'service', 'select', [['url', 'Full URL'], ['youtube', 'YouTube id'], ['vimeo', 'Vimeo id'], ['dailymotion', 'Dailymotion id']]);
+ if (o.service === 'url') field('Video URL', 'url', 'text'); else field('Video id', 'id', 'text');
+ field('Alignment', 'align', 'select', ALIGN);
+ field('Width (px)', 'width', 'text');
+ if (o.service === 'url') field('Height (px)', 'height', 'text');
+ field('Caption', 'caption', 'text');
+ } else if (kind === 'sembed') {
+ field('Source', 'service', 'select', [['url', 'Full URL'], ['soundcloud', 'SoundCloud id'], ['bandcamp', 'Bandcamp id']]);
+ if (o.service === 'url') field('Sound URL', 'url', 'text'); else field('Sound id', 'id', 'text');
+ field('Alignment', 'align', 'select', ALIGN);
+ field('Caption', 'caption', 'text');
+ }
+ refresh();
+ }
+
+ function refresh() { code.value = buildCode(kind, vals[kind]); }
+
+ copy.addEventListener('click', async () => {
+ code.select();
+ let ok = false;
+ try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
+ if (!ok) { try { await navigator.clipboard.writeText(code.value); ok = true; } catch (e) { ok = false; } }
+ toast(ok ? 'Code copied.' : 'Could not copy. Select the code and press Ctrl+C.');
+ });
+
+ draw();
+ const m = openModal({
+ title: 'Media place-marker code',
+ content: wrap,
+ wide: true,
+ noFocus: true,
+ buttons: [{ label: 'Cancel', value: null }, { label: 'Insert', value: 'ok', primary: true }]
+ });
+ m.promise.then((v) => {
+ if (v !== 'ok') return;
+ const text = buildCode(kind, vals[kind]);
+ api.insert(text);
+ if (WARN[kind]) toast(WARN[kind], 7000);
+ });
+ }
+
+ return { open };
+ }
+
+ window.SwiftMedia = Object.assign({ init }, pure);
+})(this);
diff --git a/renderer/proof.js b/renderer/proof.js
new file mode 100644
index 0000000..24f2b60
--- /dev/null
+++ b/renderer/proof.js
@@ -0,0 +1,297 @@
+// Spelling and thesaurus panel. The dictionaries live in the main process (offline).
+(function () {
+ 'use strict';
+
+ function init(opts) {
+ const ed = opts.editor;
+ const api = opts.api;
+ const toast = opts.toast;
+ const wn = window.wn;
+
+ const panel = document.createElement('div');
+ panel.className = 'proof';
+ panel.hidden = true;
+ document.body.appendChild(panel);
+
+ const state = { tab: 'spell', cur: null, pos: 0, ignore: new Set(), count: 0, target: null, lastWord: '', cfg: opts.getConfig() };
+
+ 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;
+ }
+ const noFocus = (b) => { b.addEventListener('mousedown', (e) => { if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT') e.preventDefault(); }); return b; };
+ function btn(label, fn, cls) { const b = noFocus(el('button', label, cls)); b.addEventListener('click', fn); return b; }
+
+ function reveal(a, b) {
+ ed.focus();
+ ed.setSelectionRange(a, b);
+ ed.blur();
+ ed.focus();
+ }
+
+ /* ---------- shell ---------- */
+
+ function close() { panel.hidden = true; }
+
+ function open(tab) {
+ state.tab = tab;
+ panel.hidden = false;
+ draw();
+ if (tab === 'spell') { state.pos = 0; scan(0); } else { startThesaurus(); }
+ }
+
+ function draw() {
+ panel.innerHTML = '';
+ const head = el('div', null, 'proofHead');
+ const tabs = el('div', null, 'proofTabs');
+ [['spell', 'Spelling'], ['thes', 'Thesaurus']].forEach((t) => {
+ const b = noFocus(el('button', t[1]));
+ b.classList.toggle('on', state.tab === t[0]);
+ b.addEventListener('click', () => open(t[0]));
+ tabs.appendChild(b);
+ });
+ head.appendChild(tabs);
+ head.appendChild(btn('Close', close, 'proofX'));
+ panel.appendChild(head);
+ const body = el('div', null, 'proofBody');
+ body.id = 'proofBody';
+ panel.appendChild(body);
+ if (state.tab === 'spell') drawSpellShell(body); else drawThesShell(body);
+ }
+
+ /* ---------- spelling ---------- */
+
+ function drawSpellShell(body) {
+ const opts1 = el('div', null, 'proofRow');
+ const lang = document.createElement('select');
+ [['en-US', 'English (US)'], ['en-GB', 'English (UK)']].forEach((p) => { const o = el('option', p[1]); o.value = p[0]; lang.appendChild(o); });
+ lang.value = state.cfg.spellLang || 'en-US';
+ lang.addEventListener('change', () => {
+ state.cfg.spellLang = lang.value;
+ wn.setConfig({ spellLang: lang.value });
+ state.ignore.clear();
+ state.pos = 0;
+ scan(0);
+ });
+ opts1.appendChild(lang);
+ const lab = el('label', null, 'proofChk');
+ const cb = document.createElement('input');
+ cb.type = 'checkbox';
+ cb.checked = state.cfg.underline !== false;
+ cb.addEventListener('change', () => {
+ state.cfg.underline = cb.checked;
+ ed.spellcheck = cb.checked;
+ wn.setConfig({ underline: cb.checked });
+ });
+ lab.appendChild(cb);
+ lab.appendChild(document.createTextNode(' Underline as I type'));
+ opts1.appendChild(lab);
+ body.appendChild(opts1);
+ const area = el('div', null, 'spellArea');
+ area.id = 'spellArea';
+ body.appendChild(area);
+ body.appendChild(el('div', 'Markup such as templates, link targets, tags and web addresses is skipped.', 'proofHint'));
+ }
+
+ async function scan(from) {
+ const area = document.getElementById('spellArea');
+ if (!area) return;
+ area.textContent = 'Checking...';
+ const r = await wn.spellCheck(ed.value);
+ if (!r.ok) { area.textContent = 'Spell check failed: ' + r.error; return; }
+ const list = r.list.filter((x) => !state.ignore.has(x.word.toLowerCase()));
+ state.count = list.length;
+ let next = list.find((x) => x.start >= from);
+ let wrapped = false;
+ if (!next && list.length) { next = list[0]; wrapped = true; }
+ if (!next) { state.cur = null; area.innerHTML = ''; area.appendChild(el('div', 'No spelling problems found.', 'proofDone')); return; }
+ state.cur = next;
+ showWord(area, next, wrapped);
+ }
+
+ async function showWord(area, item, wrapped) {
+ reveal(item.start, item.end);
+ area.innerHTML = '';
+ area.appendChild(el('div', 'Not in dictionary' + (state.count > 1 ? ' (' + state.count + ' left)' : '') + (wrapped ? ', back at the top' : ''), 'proofLabel'));
+ area.appendChild(el('div', item.word, 'badWord'));
+ const v = ed.value;
+ const ctx = v.slice(Math.max(0, item.start - 30), item.start).replace(/\s+/g, ' ');
+ const after = v.slice(item.end, item.end + 30).replace(/\s+/g, ' ');
+ const c = el('div', null, 'proofCtx');
+ c.appendChild(document.createTextNode('...' + ctx));
+ c.appendChild(el('b', item.word));
+ c.appendChild(document.createTextNode(after + '...'));
+ area.appendChild(c);
+ const input = document.createElement('input');
+ input.className = 'proofInput';
+ input.spellcheck = false;
+ input.placeholder = 'Type a correction or pick a suggestion';
+ area.appendChild(input);
+ const sug = el('div', null, 'sugList');
+ area.appendChild(sug);
+ const acts = el('div', null, 'proofActs');
+ const go = (fn) => () => { if (state.cur === item) fn(); };
+ acts.appendChild(btn('Replace', go(() => replaceCur(input.value.trim()))));
+ acts.appendChild(btn('Replace all', go(() => replaceAll(input.value.trim()))));
+ acts.appendChild(btn('Ignore', go(() => { state.pos = item.end; scan(state.pos); })));
+ acts.appendChild(btn('Ignore all', go(() => { state.ignore.add(item.word.toLowerCase()); state.pos = item.end; scan(state.pos); })));
+ acts.appendChild(btn('Add to dictionary', go(async () => { await wn.spellAdd(item.word); toast('Added "' + item.word + '" to your dictionary.'); state.pos = item.end; scan(state.pos); })));
+ area.appendChild(acts);
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); replaceCur(input.value.trim()); } });
+ const list = await wn.spellSuggest(item.word);
+ if (state.cur !== item) return;
+ if (!list.length) sug.appendChild(el('div', 'No suggestions.', 'proofHint'));
+ list.forEach((w, i) => {
+ const word = /^[A-Z]/.test(item.word) && !/^[A-Z]/.test(w) ? w.charAt(0).toUpperCase() + w.slice(1) : w;
+ const b = noFocus(el('button', word, 'tm'));
+ b.addEventListener('click', () => { input.value = word; });
+ b.addEventListener('dblclick', () => replaceCur(word));
+ sug.appendChild(b);
+ if (i === 0) input.value = word;
+ });
+ }
+
+ function replaceCur(word) {
+ const c = state.cur;
+ if (!c || !word) return;
+ api.replaceRange(c.start, c.end, word);
+ state.pos = c.start + word.length;
+ scan(state.pos);
+ }
+
+ async function replaceAll(word) {
+ const c = state.cur;
+ if (!c || !word) return;
+ const r = await wn.spellCheck(ed.value);
+ if (!r.ok) return;
+ const hits = r.list.filter((x) => x.word === c.word).sort((a, b) => b.start - a.start);
+ hits.forEach((h) => api.replaceRange(h.start, h.end, word));
+ toast('Replaced ' + hits.length + (hits.length === 1 ? ' word.' : ' words.'));
+ scan(0);
+ }
+
+ /* ---------- thesaurus ---------- */
+
+ function wordAtCaret() {
+ const v = ed.value;
+ let a = ed.selectionStart;
+ let b = ed.selectionEnd;
+ if (a === b) {
+ while (a > 0 && /[\p{L}'-]/u.test(v.charAt(a - 1))) a--;
+ while (b < v.length && /[\p{L}'-]/u.test(v.charAt(b))) b++;
+ }
+ const w = v.slice(a, b).trim();
+ if (!w || w.length > 40 || /\n/.test(w)) return null;
+ return { a, b, word: w };
+ }
+
+ function drawThesShell(body) {
+ const row = el('div', null, 'proofRow');
+ const input = document.createElement('input');
+ input.id = 'thesInput';
+ input.placeholder = 'Word to look up';
+ input.spellcheck = false;
+ input.value = state.lastWord;
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); lookup(input.value); } });
+ row.appendChild(input);
+ row.appendChild(btn('Look up', () => lookup(input.value)));
+ body.appendChild(row);
+ body.appendChild(el('div', 'Click a word to replace the selected word with it. Ctrl+click a word to look that one up instead.', 'proofHint'));
+ const res = el('div', null, 'thesRes');
+ res.id = 'thesRes';
+ body.appendChild(res);
+ body.appendChild(el('div', 'Offline thesaurus from Princeton WordNet.', 'proofHint'));
+ }
+
+ function startThesaurus() {
+ const w = wordAtCaret();
+ if (w) {
+ state.target = { a: w.a, b: w.b };
+ state.lastWord = w.word;
+ const i = document.getElementById('thesInput');
+ if (i) i.value = w.word;
+ lookup(w.word);
+ } else {
+ const i = document.getElementById('thesInput');
+ if (i) i.focus();
+ const r = document.getElementById('thesRes');
+ if (r) r.appendChild(el('div', 'Select a word in the editor, or type one above.', 'proofHint'));
+ }
+ }
+
+ function matchCase(orig, w) {
+ if (!orig) return w;
+ if (orig.length > 1 && orig === orig.toUpperCase() && /[A-Z]/.test(orig)) return w.toUpperCase();
+ if (/^[A-Z]/.test(orig)) return w.charAt(0).toUpperCase() + w.slice(1);
+ return w;
+ }
+
+ async function lookup(word) {
+ word = String(word || '').trim();
+ const res = document.getElementById('thesRes');
+ if (!res) return;
+ if (!word) return;
+ state.lastWord = word;
+ const i = document.getElementById('thesInput');
+ if (i) i.value = word;
+ res.textContent = 'Looking up...';
+ const r = await wn.thesaurus(word);
+ res.innerHTML = '';
+ if (!r.ok) { res.textContent = 'Lookup failed: ' + r.error; return; }
+ if (!r.groups.length) { res.appendChild(el('div', 'No synonyms found for "' + word + '".', 'proofDone')); return; }
+ if (r.lemma.toLowerCase() !== word.toLowerCase()) res.appendChild(el('div', 'Showing results for "' + r.lemma + '".', 'proofHint'));
+ r.groups.forEach((g) => {
+ res.appendChild(el('div', g.pos, 'thesPos'));
+ g.senses.forEach((s) => {
+ const box = el('div', null, 'thesSense');
+ box.appendChild(el('div', s.gloss, 'thesGloss'));
+ const chips = el('div', null, 'thesChips');
+ s.words.forEach((w) => {
+ const b = noFocus(el('button', w, 'chip'));
+ b.addEventListener('click', (ev) => {
+ if (ev.ctrlKey || ev.metaKey) { lookup(w); return; }
+ replaceTarget(w);
+ });
+ chips.appendChild(b);
+ });
+ box.appendChild(chips);
+ res.appendChild(box);
+ });
+ });
+ }
+
+ function replaceTarget(w) {
+ let t = state.target;
+ if (!t) {
+ const c = wordAtCaret();
+ if (!c) { toast('Select the word you want to replace first.'); return; }
+ t = { a: c.a, b: c.b };
+ }
+ const orig = ed.value.slice(t.a, t.b);
+ const nw = matchCase(orig, w);
+ api.replaceRange(t.a, t.b, nw, t.a, t.a + nw.length);
+ state.target = { a: t.a, b: t.a + nw.length };
+ }
+
+ /* ---------- buttons ---------- */
+
+ const bs = document.getElementById('btnSpell');
+ const bt = document.getElementById('btnThes');
+ [[bs, 'spell'], [bt, 'thes']].forEach((p) => {
+ if (!p[0]) return;
+ p[0].addEventListener('mousedown', (e) => e.preventDefault());
+ p[0].addEventListener('click', () => {
+ if (!panel.hidden && state.tab === p[1]) { close(); return; }
+ open(p[1]);
+ });
+ });
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !panel.hidden && !document.querySelector('.overlay')) close(); });
+
+ ed.spellcheck = state.cfg.underline !== false;
+ return { open, close };
+ }
+
+ window.SwiftProof = { init };
+})();
diff --git a/renderer/snippets.js b/renderer/snippets.js
new file mode 100644
index 0000000..c46d112
--- /dev/null
+++ b/renderer/snippets.js
@@ -0,0 +1,160 @@
+// Snippets menu: common wikitext pieces, grouped, with a filter box.
+(function () {
+ 'use strict';
+
+ const NEEDS = {
+ Cite: 'This needs the Cite extension (the references app). If your wiki does not have it installed, the tags will show up as plain text instead of working footnotes.',
+ SyntaxHighlight: 'This needs the SyntaxHighlight extension on your wiki.',
+ Math: 'This needs the Math extension on your wiki.',
+ Poem: 'This needs the Poem feature (built in on recent MediaWiki, an extension on old ones).',
+ ParserFunctions: 'This needs the ParserFunctions extension on your wiki.',
+ Gallery: 'Gallery tags are built in, but the files you list must exist on your wiki.'
+ };
+
+ const W = (g, label, a, b, ph, extra) => Object.assign({ g, label, kind: 'wrap', a, b, ph }, extra || {});
+ const T = (g, label, text, extra) => Object.assign({ g, label, kind: 'text', text }, extra || {});
+ const B = (g, label, text, extra) => Object.assign({ g, label, kind: 'block', text }, extra || {});
+
+ const ITEMS = [
+ W('Escaping', 'nowiki', '
', '', 'preformatted text'), + W('Escaping', 'Comment', '', 'a note only editors see'), + W('Escaping', 'kbd (keyboard key)', '', '', 'Ctrl'), + W('Escaping', 'code', '
', '', 'code'),
+ T('Escaping', 'Non-breaking space', ' '),
+ T('Escaping', 'Line break', '