From 82de74d5459cad7b67e35018f344739c2a442e65 Mon Sep 17 00:00:00 2001 From: weishaupt <1+weishaupt@noreply.localhost> Date: Wed, 11 Nov 2026 00:09:12 +0000 Subject: [PATCH] Upload files to "renderer" --- renderer/export.js | 146 ++++++++++ renderer/media.js | 247 +++++++++++++++++ renderer/proof.js | 297 +++++++++++++++++++++ renderer/snippets.js | 160 +++++++++++ renderer/tables.js | 615 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 1465 insertions(+) create mode 100644 renderer/export.js create mode 100644 renderer/media.js create mode 100644 renderer/proof.js create mode 100644 renderer/snippets.js create mode 100644 renderer/tables.js 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', '', '', 'plain text'), + W('Escaping', 'pre (preformatted)', '
', '
', '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', '
'), + T('Escaping', 'Clear floats', '
'), + + W('References', 'ref (footnote)', '', '', 'Reference text', { needs: 'Cite' }), + W('References', 'Named ref', '', '', 'Reference text', { needs: 'Cite' }), + T('References', 'Reuse a named ref', '', { needs: 'Cite' }), + W('References', 'Grouped ref', '', '', 'Note text', { needs: 'Cite' }), + B('References', 'references list', '', { needs: 'Cite' }), + B('References', 'references for a group', '', { needs: 'Cite' }), + B('References', 'Reflist template', '{{Reflist}}', { needs: 'Cite', hint: 'Needs the Reflist template as well.' }), + + W('Page control', 'noinclude', '', '', 'only on this page'), + W('Page control', 'includeonly', '', '', 'only where transcluded'), + W('Page control', 'onlyinclude', '', '', 'the part that is transcluded'), + B('Page control', '#REDIRECT', '#REDIRECT [[Target page]]'), + B('Page control', 'Category', '[[Category:Name]]'), + T('Page control', 'Link to a category', '[[:Category:Name]]'), + B('Page control', 'DEFAULTSORT', '{{DEFAULTSORT:Sort key}}'), + B('Page control', '__TOC__', '__TOC__'), + B('Page control', '__NOTOC__', '__NOTOC__'), + B('Page control', '__FORCETOC__', '__FORCETOC__'), + B('Page control', '__NOEDITSECTION__', '__NOEDITSECTION__'), + + T('Magic words', 'Signature and date', '~~~~'), + T('Magic words', 'PAGENAME', '{{PAGENAME}}'), + T('Magic words', 'SITENAME', '{{SITENAME}}'), + T('Magic words', 'CURRENTYEAR', '{{CURRENTYEAR}}'), + T('Magic words', 'Anchor', ''), + T('Magic words', 'Link to a section', '[[#Section name|link text]]'), + T('Magic words', 'Link to a page section', '[[Page name#Section name|link text]]'), + + B('Layout', 'Definition list', '; Term\n: Definition'), + B('Layout', 'Collapsible box', '{| class="wikitable mw-collapsible mw-collapsed"\n! Click to expand\n|-\n| Hidden content\n|}'), + B('Layout', 'Gallery', '\nFile:Example1.jpg|Caption one\nFile:Example2.jpg|Caption two\n', { needs: 'Gallery' }), + B('Layout', 'Two columns', '{| style="width:100%"\n| style="width:50%; vertical-align:top" |\nLeft column\n| style="width:50%; vertical-align:top" |\nRight column\n|}'), + B('Layout', 'Side box (floats right)', '
\nSide box text\n
'), + B('Layout', 'Note box', '
\n\'\'\'Note:\'\'\' Text of the note.\n
'), + B('Layout', 'Warning box', '
\n\'\'\'Warning:\'\'\' Text of the warning.\n
'), + + W('Extensions', 'syntaxhighlight', '', '', 'code', { needs: 'SyntaxHighlight' }), + W('Extensions', 'math', '', '', 'x^2 + y^2 = z^2', { needs: 'Math' }), + W('Extensions', 'poem', '', '', 'Line one\nLine two', { needs: 'Poem' }), + T('Extensions', '#if', '{{#if: condition | then | else }}', { needs: 'ParserFunctions' }), + T('Extensions', '#switch', '{{#switch: value\n | a = result a\n | b = result b\n | #default = other\n}}', { needs: 'ParserFunctions' }), + T('Extensions', '#expr', '{{#expr: 1 + 2 }}', { needs: 'ParserFunctions' }) + ]; + + function init(opts) { + const api = opts.api; + const toast = opts.toast; + const btn = document.getElementById('btnSnippets'); + if (!btn) return; + + const pop = document.createElement('div'); + pop.className = 'pop snippets'; + pop.hidden = true; + document.body.appendChild(pop); + + function close() { pop.hidden = true; } + + function insertItem(it) { + close(); + if (it.kind === 'wrap') api.toggleWrap(it.a, it.b, it.ph); + else if (it.kind === 'block') api.insertBlock(it.text); + else api.insert(it.text); + if (it.needs) toast(NEEDS[it.needs], 7000); + } + + function build(filter) { + const list = pop.querySelector('.snList'); + list.innerHTML = ''; + const f = filter.trim().toLowerCase(); + let group = null; + ITEMS.forEach((it) => { + const hay = (it.label + ' ' + it.g + ' ' + (it.needs || '') + ' ' + (it.text || it.a || '')).toLowerCase(); + if (f && hay.indexOf(f) < 0) return; + if (it.g !== group) { + group = it.g; + const h = document.createElement('div'); + h.className = 'snGroup'; + h.textContent = group; + list.appendChild(h); + } + const b = document.createElement('button'); + b.className = 'tm'; + b.textContent = it.label + (it.needs ? ' *' : ''); + b.title = it.needs ? NEEDS[it.needs] : (it.hint || ''); + b.addEventListener('mousedown', (e) => { if (e.target === b) e.preventDefault(); }); + b.addEventListener('click', () => insertItem(it)); + list.appendChild(b); + }); + if (!list.children.length) { + const n = document.createElement('div'); + n.className = 'snGroup'; + n.textContent = 'Nothing matches.'; + list.appendChild(n); + } + } + + function open() { + pop.innerHTML = ''; + const t = document.createElement('div'); + t.className = 'popTitle'; + t.textContent = 'Snippets'; + pop.appendChild(t); + const q = document.createElement('input'); + q.type = 'search'; + q.placeholder = 'Filter snippets'; + q.className = 'snFilter'; + q.addEventListener('input', () => build(q.value)); + pop.appendChild(q); + const list = document.createElement('div'); + list.className = 'snList'; + pop.appendChild(list); + const note = document.createElement('div'); + note.className = 'snNote'; + note.textContent = '* Needs an extension on your wiki. Footnotes ( and ) need the Cite extension, the references app. If your wiki does not have it installed, they will not work and show as plain text.'; + pop.appendChild(note); + build(''); + pop.hidden = false; + const r = btn.getBoundingClientRect(); + pop.style.left = Math.max(6, Math.min(r.left, window.innerWidth - pop.offsetWidth - 8)) + 'px'; + pop.style.top = (r.bottom + 4) + 'px'; + q.focus(); + } + + btn.addEventListener('mousedown', (e) => e.preventDefault()); + btn.addEventListener('click', () => { if (pop.hidden) open(); else close(); }); + document.addEventListener('mousedown', (e) => { + if (!pop.hidden && !pop.contains(e.target) && e.target !== btn) close(); + }); + document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !pop.hidden) close(); }); + } + + window.SwiftSnippets = { init, ITEMS }; +})(); diff --git a/renderer/tables.js b/renderer/tables.js new file mode 100644 index 0000000..2cfe522 --- /dev/null +++ b/renderer/tables.js @@ -0,0 +1,615 @@ +// Table editor for MediaWiki tables. +// The pure part (parse, serialize, annotate, ops) also runs under Node for tests. +(function (root) { + 'use strict'; + + /* ---------- parsing ---------- */ + + // A copy of the text where things that must not be read as table syntax are blanked + // out (same length, same newlines): comments, nowiki-like tags and templates. + function maskText(text) { + const out = text.split(''); + const blank = (a, b) => { for (let i = a; i < b; i++) if (out[i] !== '\n') out[i] = ' '; }; + let m; + const reC = /|$)/g; + while ((m = reC.exec(text))) blank(m.index, m.index + m[0].length); + const reT = /<(nowiki|pre|source|syntaxhighlight|math|score)\b[^>]*>[\s\S]*?<\/\1>/gi; + while ((m = reT.exec(text))) blank(m.index, m.index + m[0].length); + const s = out.join(''); + let depth = 0; + let start = 0; + for (let i = 0; i < s.length; i++) { + if (s[i] === '{' && s[i + 1] === '{') { + if (depth === 0) start = i; + depth++; i++; + } else if (s[i] === '}' && s[i + 1] === '}' && depth > 0) { + depth--; i++; + if (depth === 0) blank(start, i + 1); + } + } + if (depth > 0) blank(start, out.length); + return out.join(''); + } + + // Same again, but characters inside [[links]] are made harmless so their pipes do not split cells. + function maskLinks(masked) { + return masked.replace(/\[\[[^\]\n]*\]\]/g, (x) => 'x'.repeat(x.length)); + } + + function parseTables(text) { + const m1 = maskText(text); + const m2 = maskLinks(m1); + const tables = []; + let depth = 0; + let t = null; + let row = null; + let cur = null; + let pos = 0; + + function closeRow() { + if (row && row.cells.length) t.rows.push(row); + } + function finishCell() { + if (cur) { + cur.content = text.slice(cur.cStart, cur.cEnd).replace(/^\s+|\s+$/g, ''); + cur = null; + } + } + function endTable(endPos) { + finishCell(); + closeRow(); + t.end = endPos; + tables.push(t); + t = null; row = null; cur = null; + } + + const lines = text.split('\n'); + for (let li = 0; li < lines.length; li++) { + const ls = pos; + const le = pos + lines[li].length; + pos = le + 1; + const lm = m1.slice(ls, le); + const lead = lm.length - lm.replace(/^\s+/, '').length; + const tl = lm.slice(lead); + + if (tl.startsWith('{|')) { + if (depth === 0) { + t = { start: ls, end: le, attrs: text.slice(ls + lead + 2, le).trim(), caption: null, rows: [] }; + row = { attrs: '', cells: [] }; + cur = null; + } else if (cur) { + cur.cEnd = le; + } + depth++; + continue; + } + if (depth === 0) continue; + if (tl.startsWith('|}')) { + depth--; + if (depth === 0) endTable(le); + else if (cur) cur.cEnd = le; + continue; + } + if (depth > 1) { if (cur) cur.cEnd = le; continue; } + + const base = ls + lead; + if (tl.startsWith('|+')) { + finishCell(); + t.caption = text.slice(base + 2, le).trim(); + continue; + } + if (tl.startsWith('|-')) { + finishCell(); + closeRow(); + row = { attrs: text.slice(base, le).replace(/^\|-+/, '').trim(), cells: [] }; + continue; + } + if (tl.charAt(0) === '|' || tl.charAt(0) === '!') { + finishCell(); + const hdrLine = tl.charAt(0) === '!'; + const lm2 = m2.slice(ls, le); + const seps = []; + const re = hdrLine ? /\|\||!!/g : /\|\|/g; + let mm; + const body = lm2.slice(lead + 1); + while ((mm = re.exec(body))) seps.push(mm.index + lead + 1); + const bounds = []; + let a = lead + 1; + let from = lead; + seps.forEach((sp) => { bounds.push([a, sp, from]); a = sp + 2; from = sp; }); + bounds.push([a, lm.length, from]); + bounds.forEach((bd) => { + finishCell(); + const seg = lm2.slice(bd[0], bd[1]); + const pi = seg.indexOf('|'); + const cell = { hdr: hdrLine, attrs: '', content: '', from: ls + bd[2], markerEnd: ls + bd[0], hasAttrs: false, cStart: ls + bd[0], cEnd: ls + bd[1] }; + if (pi >= 0) { + cell.hasAttrs = true; + cell.attrs = text.slice(ls + bd[0], ls + bd[0] + pi).trim(); + cell.markerEnd = ls + bd[0] + pi; + cell.cStart = ls + bd[0] + pi + 1; + } + row.cells.push(cell); + cur = cell; + }); + continue; + } + // continuation line of the current cell + if (cur) cur.cEnd = le; + } + if (t) endTable(text.length); + return tables; + } + + /* ---------- writing back ---------- */ + + function cellParts(c) { + return { pre: c.attrs ? c.attrs + ' | ' : '', body: c.content }; + } + + // Returns {text, pos[r][c]} where pos is the offset of each cell's content in the text. + function serialize(t) { + let out = '{|' + (t.attrs ? ' ' + t.attrs : ''); + const pos = []; + if (t.caption) out += '\n|+ ' + t.caption; + t.rows.forEach((row, ri) => { + out += '\n'; + if (ri > 0 || row.attrs) out += '|-' + (row.attrs ? ' ' + row.attrs : '') + '\n'; + pos[ri] = []; + const oneLine = row.cells.every((c) => c.content.indexOf('\n') < 0); + const allHdr = row.cells.every((c) => c.hdr); + const allData = row.cells.every((c) => !c.hdr); + if (oneLine && (allHdr || allData)) { + const mark = allHdr ? '! ' : '| '; + const sep = allHdr ? ' !! ' : ' || '; + out += mark; + row.cells.forEach((c, ci) => { + const p = cellParts(c); + if (ci > 0) out += sep; + out += p.pre; + pos[ri][ci] = out.length; + out += p.body; + }); + } else { + row.cells.forEach((c, ci) => { + const p = cellParts(c); + if (ci > 0) out += '\n'; + out += (c.hdr ? '! ' : '| ') + p.pre; + pos[ri][ci] = out.length; + out += p.body; + }); + } + }); + out += '\n|}'; + return { text: out, pos }; + } + + /* ---------- marking cells for the preview ---------- */ + + function annotate(text) { + if (text.indexOf('{|') < 0) return text; + const tabs = parseTables(text); + const ins = []; + tabs.forEach((t, ti) => t.rows.forEach((row, ri) => row.cells.forEach((c, ci) => { + const tag = ' data-swm="' + ti + ':' + ri + ':' + ci + '"'; + ins.push([c.markerEnd, c.hasAttrs ? tag + ' ' : tag + ' |']); + }))); + ins.sort((a, b) => b[0] - a[0]); + let out = text; + ins.forEach((p) => { out = out.slice(0, p[0]) + p[1] + out.slice(p[0]); }); + return out; + } + + /* ---------- finding the table and cell at a text offset ---------- */ + + function locate(text, p) { + const tabs = parseTables(text); + for (let ti = 0; ti < tabs.length; ti++) { + const t = tabs[ti]; + if (p < t.start || p > t.end) continue; + let best = null; + t.rows.forEach((row, ri) => row.cells.forEach((c, ci) => { if (c.from <= p) best = { r: ri, c: ci }; })); + if (!best) best = { r: 0, c: 0 }; + return { ti, r: best.r, c: best.c, table: t }; + } + return null; + } + + /* ---------- operations ---------- */ + + function blankCell(hdr) { return { hdr: !!hdr, attrs: '', content: '', hasAttrs: false }; } + function maxCols(t) { return t.rows.reduce((m, r) => Math.max(m, r.cells.length), 0); } + function cloneRow(row) { + return { attrs: row.attrs, cells: row.cells.map((c) => ({ hdr: c.hdr, attrs: c.attrs, content: c.content, hasAttrs: c.hasAttrs })) }; + } + + function hasClass(t, cls) { + const m = /class\s*=\s*"([^"]*)"/i.exec(t.attrs); + return !!m && m[1].split(/\s+/).indexOf(cls) >= 0; + } + function toggleClass(t, cls) { + const re = /class\s*=\s*"([^"]*)"/i; + const m = re.exec(t.attrs); + if (!m) { t.attrs = ('class="' + cls + '" ' + t.attrs).trim(); return; } + const list = m[1].split(/\s+/).filter(Boolean); + const i = list.indexOf(cls); + if (i >= 0) list.splice(i, 1); else list.push(cls); + t.attrs = (list.length ? t.attrs.replace(re, 'class="' + list.join(' ') + '"') : t.attrs.replace(re, '')).replace(/\s+/g, ' ').trim(); + } + + function cmpValues(a, b) { + const na = parseFloat(a.replace(/,/g, '')); + const nb = parseFloat(b.replace(/,/g, '')); + if (!isNaN(na) && !isNaN(nb) && /^[-+]?[\d.,]+%?$/.test(a.trim()) && /^[-+]?[\d.,]+%?$/.test(b.trim())) return na - nb; + return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }); + } + + function sortRows(t, c, dir) { + let skip = 0; + while (skip < t.rows.length && t.rows[skip].cells.length && t.rows[skip].cells.every((x) => x.hdr)) skip++; + const head = t.rows.slice(0, skip); + const body = t.rows.slice(skip).map((r, i) => ({ r, i })); + body.sort((x, y) => { + const a = x.r.cells[c] ? x.r.cells[c].content : ''; + const b = y.r.cells[c] ? y.r.cells[c].content : ''; + return (cmpValues(a, b) * dir) || (x.i - y.i); + }); + t.rows = head.concat(body.map((x) => x.r)); + } + + // Each op changes t in place and returns the new {r, c}, or 'delete' to remove the whole table. + const OPS = { + rowAbove(t, r, c) { t.rows.splice(r, 0, { attrs: '', cells: t.rows[r].cells.map((x) => blankCell(x.hdr)) }); return { r, c }; }, + rowBelow(t, r, c) { t.rows.splice(r + 1, 0, { attrs: '', cells: t.rows[r].cells.map(() => blankCell(false)) }); return { r: r + 1, c }; }, + rowDup(t, r, c) { t.rows.splice(r + 1, 0, cloneRow(t.rows[r])); return { r: r + 1, c }; }, + rowDel(t, r, c) { + t.rows.splice(r, 1); + if (!t.rows.length) return 'delete'; + return { r: Math.min(r, t.rows.length - 1), c }; + }, + rowUp(t, r, c) { if (r > 0) { const x = t.rows[r]; t.rows[r] = t.rows[r - 1]; t.rows[r - 1] = x; return { r: r - 1, c }; } return { r, c }; }, + rowDown(t, r, c) { if (r < t.rows.length - 1) { const x = t.rows[r]; t.rows[r] = t.rows[r + 1]; t.rows[r + 1] = x; return { r: r + 1, c }; } return { r, c }; }, + hdrRow(t, r, c) { const to = !t.rows[r].cells.every((x) => x.hdr); t.rows[r].cells.forEach((x) => { x.hdr = to; }); return { r, c }; }, + colLeft(t, r, c) { t.rows.forEach((row) => { const at = Math.min(c, row.cells.length); row.cells.splice(at, 0, blankCell(row.cells[c] && row.cells[c].hdr)); }); return { r, c }; }, + colRight(t, r, c) { t.rows.forEach((row) => { const at = Math.min(c + 1, row.cells.length); row.cells.splice(at, 0, blankCell(row.cells[c] && row.cells[c].hdr)); }); return { r, c: c + 1 }; }, + colMoveL(t, r, c) { + if (c === 0) return { r, c }; + t.rows.forEach((row) => { if (row.cells[c]) { const x = row.cells[c]; row.cells[c] = row.cells[c - 1]; row.cells[c - 1] = x; } }); + return { r, c: c - 1 }; + }, + colMoveR(t, r, c) { + t.rows.forEach((row) => { if (row.cells[c + 1]) { const x = row.cells[c]; row.cells[c] = row.cells[c + 1]; row.cells[c + 1] = x; } }); + return { r, c: Math.min(c + 1, maxCols(t) - 1) }; + }, + colDel(t, r, c) { + t.rows.forEach((row) => { if (c < row.cells.length) row.cells.splice(c, 1); }); + t.rows = t.rows.filter((row) => row.cells.length); + if (!t.rows.length) return 'delete'; + return { r: Math.min(r, t.rows.length - 1), c: Math.min(c, maxCols(t) - 1) }; + }, + sortAsc(t, r, c) { sortRows(t, c, 1); return { r: 0, c }; }, + sortDesc(t, r, c) { sortRows(t, c, -1); return { r: 0, c }; }, + hdrCell(t, r, c) { const x = t.rows[r].cells[c]; if (x) x.hdr = !x.hdr; return { r, c }; }, + clearCell(t, r, c) { const x = t.rows[r].cells[c]; if (x) x.content = ''; return { r, c }; }, + clsWikitable(t, r, c) { toggleClass(t, 'wikitable'); return { r, c }; }, + clsSortable(t, r, c) { toggleClass(t, 'sortable'); return { r, c }; }, + clsCollapsible(t, r, c) { toggleClass(t, 'mw-collapsible'); return { r, c }; }, + delTable() { return 'delete'; } + }; + + function makeTable(rows, cols, o) { + o = o || {}; + const cls = []; + if (o.wikitable !== false) cls.push('wikitable'); + if (o.sortable) cls.push('sortable'); + const t = { attrs: cls.length ? 'class="' + cls.join(' ') + '"' : '', caption: null, rows: [] }; + for (let r = 0; r < rows; r++) { + const hdr = !!o.header && r === 0; + const cells = []; + for (let c = 0; c < cols; c++) cells.push({ hdr, attrs: '', content: hdr ? 'Header ' + (c + 1) : 'Cell', hasAttrs: false }); + t.rows.push({ attrs: '', cells }); + } + return serialize(t).text; + } + + const pure = { maskText, parseTables, serialize, annotate, locate, OPS, makeTable, hasClass }; + if (typeof module !== 'undefined' && module.exports) module.exports = pure; + if (typeof window === 'undefined') return; + + /* ---------- the app side: menus and the preview hook ---------- */ + + function init(opts) { + const ed = opts.editor; + const api = opts.api; + const toast = opts.toast; + const getFrame = opts.getFrame; + + const menu = document.createElement('div'); + menu.className = 'tmenu'; + menu.hidden = true; + document.body.appendChild(menu); + + const grid = document.createElement('div'); + grid.className = 'pop gridpop'; + grid.hidden = true; + document.body.appendChild(grid); + + let ctx = null; // {ti, r, c} + let lastCell = null; // cell to outline after the next render + + function el(tag, text, cls) { + const e = document.createElement(tag); + if (text) e.textContent = text; + if (cls) e.className = cls; + return e; + } + + function closeMenu() { + menu.hidden = true; + grid.hidden = true; + ctx = null; + clearOutline(); + } + + function cellEl(ti, r, c) { + const f = getFrame(); + try { + return f.contentDocument.querySelector('[data-swm="' + ti + ':' + r + ':' + c + '"]'); + } catch (e) { return null; } + } + + function clearOutline() { + const f = getFrame(); + try { + f.contentDocument.querySelectorAll('[data-swm]').forEach((x) => { x.style.outline = ''; x.style.outlineOffset = ''; }); + } catch (e) { /* no preview yet */ } + } + + function outline(ti, r, c) { + clearOutline(); + const x = cellEl(ti, r, c); + if (x) { x.style.outline = '2px solid #0b6bcb'; x.style.outlineOffset = '-2px'; } + } + + function position(node, x, y) { + node.style.left = '0px'; + node.style.top = '0px'; + const w = node.offsetWidth; + const h = node.offsetHeight; + node.style.left = Math.max(4, Math.min(x, window.innerWidth - w - 6)) + 'px'; + node.style.top = Math.max(4, Math.min(y, window.innerHeight - h - 6)) + 'px'; + } + + function run(op) { + if (!ctx) return; + const text = ed.value; + const tabs = parseTables(text); + const t = tabs[ctx.ti]; + if (!t) { toast('That table has changed. Click it again.'); closeMenu(); return; } + const r = Math.min(ctx.r, t.rows.length - 1); + const c = Math.min(ctx.c, Math.max(0, t.rows[r].cells.length - 1)); + const res = OPS[op](t, r, c); + const ti = ctx.ti; + menu.hidden = true; + ctx = null; + if (res === 'delete') { + api.replaceRange(t.start, t.end, ''); + clearOutline(); + return; + } + const s = serialize(t); + const rr = Math.min(res.r, s.pos.length - 1); + const cc = Math.min(res.c, s.pos[rr].length - 1); + const caret = t.start + s.pos[rr][cc]; + api.replaceRange(t.start, t.end, s.text, caret, caret); + lastCell = { ti, r: rr, c: cc }; + } + + function item(label, op, on, disabled) { + const b = el('button', label, 'tm'); + if (on !== undefined) b.classList.toggle('chk', !!on); + if (on !== undefined) b.textContent = (on ? '✓ ' : ' ') + label; + b.disabled = !!disabled; + b.addEventListener('mousedown', (e) => e.preventDefault()); + b.addEventListener('click', () => run(op)); + return b; + } + + function section(title, items) { + const d = el('div', null, 'tsec'); + d.appendChild(el('div', title, 'tsecTitle')); + items.forEach((i) => d.appendChild(i)); + return d; + } + + function clipRow() { + const d = el('div', null, 'tclip'); + [['Cut', 'cut'], ['Copy', 'copy'], ['Paste', 'paste'], ['Select all', 'all']].forEach((p) => { + const b = el('button', p[0], 'tm'); + b.addEventListener('mousedown', (e) => e.preventDefault()); + b.addEventListener('click', () => { closeMenu(); clipboard(p[1]); }); + d.appendChild(b); + }); + return d; + } + + async function clipboard(kind) { + ed.focus(); + if (kind === 'all') { ed.select(); return; } + if (kind === 'paste') { + let ok = false; + try { ok = document.execCommand('paste'); } catch (e) { ok = false; } + if (!ok) { + try { api.insert(await navigator.clipboard.readText()); } catch (e) { toast('Paste is blocked here. Use Ctrl+V.'); } + } + return; + } + let ok = false; + try { ok = document.execCommand(kind); } catch (e) { ok = false; } + if (!ok) toast('Use Ctrl+' + (kind === 'cut' ? 'X' : 'C') + ' for that.'); + } + + function openMenu(x, y, c0, withClip) { + ctx = { ti: c0.ti, r: c0.r, c: c0.c }; + const t = parseTables(ed.value)[c0.ti]; + if (!t) return; + const rows = t.rows.length; + const cols = maxCols(t); + menu.innerHTML = ''; + menu.appendChild(el('div', 'Table ' + (c0.ti + 1) + ', row ' + (c0.r + 1) + ' of ' + rows + ', column ' + (c0.c + 1) + ' of ' + cols, 'tHead')); + if (withClip) menu.appendChild(clipRow()); + const body = el('div', null, 'tbody'); + body.appendChild(section('Row', [ + item('Insert above', 'rowAbove'), + item('Insert below', 'rowBelow'), + item('Duplicate', 'rowDup'), + item('Move up', 'rowUp', undefined, c0.r === 0), + item('Move down', 'rowDown', undefined, c0.r >= rows - 1), + item('Header row on/off', 'hdrRow'), + item('Delete row', 'rowDel') + ])); + body.appendChild(section('Column', [ + item('Insert left', 'colLeft'), + item('Insert right', 'colRight'), + item('Move left', 'colMoveL', undefined, c0.c === 0), + item('Move right', 'colMoveR', undefined, c0.c >= cols - 1), + item('Sort A to Z', 'sortAsc'), + item('Sort Z to A', 'sortDesc'), + item('Delete column', 'colDel') + ])); + body.appendChild(section('Cell', [ + item('Header cell on/off', 'hdrCell'), + item('Clear cell', 'clearCell') + ])); + body.appendChild(section('Table', [ + item('Wikitable look', 'clsWikitable', hasClass(t, 'wikitable')), + item('Sortable', 'clsSortable', hasClass(t, 'sortable')), + item('Collapsible', 'clsCollapsible', hasClass(t, 'mw-collapsible')), + item('Delete table', 'delTable') + ])); + menu.appendChild(body); + menu.hidden = false; + grid.hidden = true; + position(menu, x, y); + outline(c0.ti, c0.r, c0.c); + } + + /* preview clicks */ + + function onPreviewClick(ev) { + const target = ev.target; + const cell = target && target.closest ? target.closest('[data-swm]') : null; + const a = target && target.closest ? target.closest('a') : null; + if (a && cell) { + const h = a.getAttribute('href') || ''; + if (h.charAt(0) !== '#') ev.preventDefault(); + } + if (!cell) { if (!menu.hidden) closeMenu(); return; } + const w = ev.view || (cell.ownerDocument && cell.ownerDocument.defaultView); + try { if (w && String(w.getSelection()).length) return; } catch (e) { /* ignore */ } + const p = cell.getAttribute('data-swm').split(':').map(Number); + const f = getFrame().getBoundingClientRect(); + openMenu(f.left + ev.clientX + 2, f.top + ev.clientY + 2, { ti: p[0], r: p[1], c: p[2] }, false); + } + + function attachPreview(frame) { + let doc = null; + try { doc = frame.contentDocument; } catch (e) { doc = null; } + if (!doc) return; + doc.addEventListener('click', onPreviewClick, true); + doc.addEventListener('scroll', () => { if (!menu.hidden) closeMenu(); }, true); + if (lastCell) { + const x = lastCell; + lastCell = null; + outline(x.ti, x.r, x.c); + setTimeout(clearOutline, 1800); + } + } + + /* editor: right click and the toolbar button */ + + function here() { return locate(ed.value, ed.selectionStart); } + + ed.addEventListener('contextmenu', (ev) => { + const h = here(); + if (!h) return; + ev.preventDefault(); + openMenu(ev.clientX, ev.clientY, h, true); + }); + + const tools = document.getElementById('btnTableTools'); + if (tools) { + tools.addEventListener('mousedown', (ev) => ev.preventDefault()); + tools.addEventListener('click', () => { + const h = here(); + if (!h) { toast('Put the cursor inside a table first, or use Table to insert one.'); return; } + const r = tools.getBoundingClientRect(); + openMenu(r.left, r.bottom + 4, h, false); + }); + } + + /* new table grid */ + + function openGrid(anchor) { + const N = 8; + grid.innerHTML = ''; + grid.appendChild(el('div', 'Insert a table', 'popTitle')); + const g = el('div', null, 'tgrid'); + const label = el('div', 'Pick a size', 'tlabel'); + const cells = []; + for (let r = 1; r <= N; r++) for (let c = 1; c <= N; c++) { + const b = el('button', null, 'tg'); + b.dataset.r = r; b.dataset.c = c; + b.addEventListener('mousedown', (e) => e.preventDefault()); + b.addEventListener('mouseenter', () => { + cells.forEach((x) => x.classList.toggle('hot', +x.dataset.r <= r && +x.dataset.c <= c)); + label.textContent = r + ' rows by ' + c + ' columns'; + }); + b.addEventListener('click', () => { + const o = { header: hdr.checked, wikitable: wk.checked, sortable: so.checked }; + grid.hidden = true; + api.insertBlock(makeTable(r, c, o)); + }); + cells.push(b); + g.appendChild(b); + } + grid.appendChild(g); + grid.appendChild(label); + function chk(text, on) { + const l = el('label', null, 'tchk'); + const i = document.createElement('input'); + i.type = 'checkbox'; i.checked = on; + l.appendChild(i); l.appendChild(document.createTextNode(' ' + text)); + grid.appendChild(l); + return i; + } + const hdr = chk('Header row', true); + const wk = chk('Wikitable look', true); + const so = chk('Sortable', false); + menu.hidden = true; + grid.hidden = false; + const r = anchor.getBoundingClientRect(); + position(grid, r.left, r.bottom + 4); + } + + const btn = document.getElementById('btnTable'); + if (btn) { + btn.addEventListener('mousedown', (ev) => ev.preventDefault()); + btn.addEventListener('click', () => { if (grid.hidden) openGrid(btn); else grid.hidden = true; }); + } + + document.addEventListener('mousedown', (ev) => { + if (!menu.hidden && !menu.contains(ev.target)) closeMenu(); + if (!grid.hidden && !grid.contains(ev.target) && ev.target !== btn) grid.hidden = true; + }); + document.addEventListener('keydown', (ev) => { + if (ev.key === 'Escape') { if (!menu.hidden) closeMenu(); grid.hidden = true; } + }); + window.addEventListener('blur', () => { if (!menu.hidden) closeMenu(); }); + + return { annotate, attachPreview, openMenu, openGrid, closeMenu }; + } + + window.SwiftTables = Object.assign({ init }, pure); +})(this); +