Files
Swiftmark/renderer/tables.js
T
2026-11-11 00:09:12 +00:00

616 lines
23 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 = /<!--[\s\S]*?(-->|$)/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);