// Formatting toolbar for the wikitext editor. // Every action edits the textarea through execCommand where possible so Ctrl+Z keeps working. (function () { 'use strict'; const PALETTE = [ ['#000000', '#434343', '#666666', '#999999', '#b7b7b7', '#cccccc', '#d9d9d9', '#efefef', '#f3f3f3', '#ffffff'], ['#980000', '#ff0000', '#ff9900', '#ffff00', '#00ff00', '#00ffff', '#4a86e8', '#0000ff', '#9900ff', '#ff00ff'], ['#e6b8af', '#f4cccc', '#fce5cd', '#fff2cc', '#d9ead3', '#d0e0e3', '#c9daf8', '#cfe2f3', '#d9d2e9', '#ead1dc'], ['#dd7e6b', '#ea9999', '#f9cb9c', '#ffe599', '#b6d7a8', '#a2c4c9', '#a4c2f4', '#9fc5e8', '#b4a7d6', '#d5a6bd'], ['#cc4125', '#e06666', '#f6b26b', '#ffd966', '#93c47d', '#76a5af', '#6d9eeb', '#6fa8dc', '#8e7cc3', '#c27ba0'], ['#a61c00', '#cc0000', '#e69138', '#f1c232', '#6aa84f', '#45818e', '#3c78d8', '#3d85c6', '#674ea7', '#a64d79'] ]; function init(opts) { const ed = opts.editor; const onEdit = opts.onEdit; /* ---------- editing primitives ---------- */ function sel() { return [ed.selectionStart, ed.selectionEnd]; } function insert(text) { ed.focus(); let ok = false; try { ok = text === '' ? document.execCommand('delete') : document.execCommand('insertText', false, text); } catch (e) { ok = false; } if (!ok) { ed.setRangeText(text, ed.selectionStart, ed.selectionEnd, 'end'); onEdit(); } } // Replace [a, b) with text, then select [selA, selB). function replaceRange(a, b, text, selA, selB) { ed.focus(); ed.setSelectionRange(a, b); insert(text); if (selA !== undefined) ed.setSelectionRange(selA, selB); } function lineRange() { const v = ed.value; const s = v.lastIndexOf('\n', ed.selectionStart - 1) + 1; let e = v.indexOf('\n', ed.selectionEnd); if (e < 0) e = v.length; return { s, e }; } /* ---------- wrap and unwrap ---------- */ function defaultDetect(v, s, e, before, after) { const text = v.slice(s, e); if (text.length >= before.length + after.length && text.startsWith(before) && text.endsWith(after)) return 'inside'; if (v.slice(s - before.length, s) === before && v.slice(e, e + after.length) === after) return 'around'; return null; } function italicDetect(v, s, e) { const text = v.slice(s, e); const q = "'"; if (text.length >= 4 && text.startsWith(q + q) && text.endsWith(q + q)) { const bothStart = text.startsWith(q.repeat(5)); const bothEnd = text.endsWith(q.repeat(5)); if ((bothStart && bothEnd) || (!text.startsWith(q.repeat(3)) && !text.endsWith(q.repeat(3)))) return 'inside'; } if (v.slice(s - 2, s) === q + q && v.slice(e, e + 2) === q + q) { const bothBefore = v.slice(s - 5, s) === q.repeat(5); const bothAfter = v.slice(e, e + 5) === q.repeat(5); if ((bothBefore && bothAfter) || (v.slice(s - 3, s) !== q.repeat(3) && v.slice(e, e + 3) !== q.repeat(3))) return 'around'; } return null; } function toggleWrap(before, after, placeholder, detect) { const [s, e] = sel(); const v = ed.value; const text = v.slice(s, e); const found = detect ? detect(v, s, e, before, after) : defaultDetect(v, s, e, before, after); if (found === 'inside') { const inner = text.slice(before.length, text.length - after.length); replaceRange(s, e, inner, s, s + inner.length); } else if (found === 'around') { replaceRange(s - before.length, e + after.length, text, s - before.length, s - before.length + text.length); } else { const inner = text || placeholder; replaceRange(s, e, before + inner + after, s + before.length, s + before.length + inner.length); } } function bold() { toggleWrap("'''", "'''", 'bold text'); } function italic() { toggleWrap("''", "''", 'italic text', italicDetect); } // Wrap in a span with one style property, or change or remove it when one is already there. function applySpan(prop, value) { const [s, e] = sel(); const v = ed.value; const text = v.slice(s, e); const openAt = ''; const reStart = new RegExp('^' + openAt); const reEnd = new RegExp(openAt + '$'); let a = s; let b = e; let inner = text; const m = reStart.exec(text); if (m && text.endsWith('') && text.length > m[0].length + 6) { inner = text.slice(m[0].length, text.length - 7); } else { const pm = reEnd.exec(v.slice(0, s)); if (pm && v.slice(e, e + 7) === '') { a = s - pm[0].length; b = e + 7; } } if (!value) { replaceRange(a, b, inner, a, a + inner.length); return; } const open = ''; const body = inner || 'text'; replaceRange(a, b, open + body + '', a + open.length, a + open.length + body.length); } // Block styles (alignment, size) live in one
around whole lines. const DIV_RE = /^
\n?([\s\S]*?)\n?<\/div>$/; function parseStyle(str) { const map = {}; str.split(';').forEach((p) => { const i = p.indexOf(':'); if (i > 0) map[p.slice(0, i).trim().toLowerCase()] = p.slice(i + 1).trim(); }); return map; } function applyDivStyle(prop, value, toggle) { const r = lineRange(); const text = ed.value.slice(r.s, r.e); const m = DIV_RE.exec(text); let inner = text; let props = {}; if (m) { props = parseStyle(m[1]); inner = m[2]; } if (!value || (toggle && props[prop] === value)) delete props[prop]; else props[prop] = value; const keys = Object.keys(props); let out; if (!keys.length) { out = inner; } else { const body = inner.trim() === '' ? 'Text' : inner; const style = keys.map((k) => k + ':' + props[k]).join(';'); out = body.indexOf('\n') >= 0 ? '
\n' + body + '\n
' : '
' + body + '
'; } replaceRange(r.s, r.e, out, r.s, r.s + out.length); } function align(kind) { if (kind === 'left') applyDivStyle('text-align', '', false); else applyDivStyle('text-align', kind, true); } /* ---------- lines: headings and lists ---------- */ function mapLines(fn) { const r = lineRange(); const lines = ed.value.slice(r.s, r.e).split('\n'); const out = fn(lines).join('\n'); replaceRange(r.s, r.e, out, r.s, r.s + out.length); } function heading(level) { mapLines((lines) => lines.map((l) => { const bare = l.replace(/^\s*=+\s*/, '').replace(/\s*=+\s*$/, '').trim(); if (!level) return bare; const mark = '='.repeat(level); return mark + ' ' + (bare || 'Heading') + ' ' + mark; })); } // Bullets and numbers keep the nesting depth: "** x" becomes "## x" instead of "# ** x". const LIST_RE = /^([*#:;]+)\s?/; function toList(ch) { mapLines((lines) => { const real = lines.filter((l) => l.trim() !== ''); const all = real.length > 0 && real.every((l) => { const m = LIST_RE.exec(l); return m && m[1].split('').every((c) => c === ch); }); return lines.map((l) => { if (l.trim() === '') return l; const m = LIST_RE.exec(l); if (all) return l.slice(m[0].length); if (m) return ch.repeat(m[1].length) + ' ' + l.slice(m[0].length); return ch + ' ' + l; }); }); } function indent() { mapLines((lines) => lines.map((l) => { if (l.trim() === '') return l; const m = /^([*#]+)/.exec(l); if (m) return m[1].charAt(m[1].length - 1) + l; return ':' + l; })); } function outdent() { mapLines((lines) => lines.map((l) => { const m = /^([*#:]+)(\s?)/.exec(l); if (!m) return l; if (m[1].length === 1) return l.slice(m[0].length); return l.slice(1); })); } /* ---------- inserts ---------- */ function insertBlock(block) { const [s, e] = sel(); const v = ed.value; const lead = s > 0 && v.charAt(s - 1) !== '\n' ? '\n' : ''; const trail = e < v.length && v.charAt(e) !== '\n' ? '\n' : ''; replaceRange(s, e, lead + block + trail); } function extLink() { const [s, e] = sel(); const text = ed.value.slice(s, e); let out; let a; let b; if (/^(https?|ftp):\/\/\S+$/i.test(text)) { out = '[' + text + ' link text]'; a = s + text.length + 2; b = a + 9; } else { const label = text || 'link text'; out = '[https://example.com ' + label + ']'; a = s + 1; b = a + 19; } replaceRange(s, e, out, a, b); } function clearFormatting() { let [s, e] = sel(); if (s === e) { const r = lineRange(); s = r.s; e = r.e; } const text = ed.value.slice(s, e); const out = text .replace(/'{2,5}/g, '') .replace(/<\/?(b|i|u|s|sub|sup|small|big|code|span|div|center|font|strike|del|ins|blockquote)(\s[^>]*)?>/gi, ''); replaceRange(s, e, out, s, s + out.length); } /* ---------- color grid ---------- */ const pop = document.createElement('div'); pop.className = 'pop'; pop.hidden = true; document.body.appendChild(pop); let popMode = 'color'; let popAnchor = null; function colorValue() { return popMode === 'color' ? 'color' : 'background-color'; } function applyColor(c) { closePop(); applySpan(colorValue(), c); } function closePop() { pop.hidden = true; popAnchor = null; } function buildPop() { pop.innerHTML = ''; const title = document.createElement('div'); title.className = 'popTitle'; title.textContent = popMode === 'color' ? 'Text color' : 'Highlight color'; pop.appendChild(title); const grid = document.createElement('div'); grid.className = 'grid'; PALETTE.forEach((row) => row.forEach((c) => { const b = document.createElement('button'); b.className = 'sw'; b.style.background = c; b.title = c; b.addEventListener('mousedown', (ev) => ev.preventDefault()); b.addEventListener('click', () => applyColor(c)); grid.appendChild(b); })); pop.appendChild(grid); const row = document.createElement('div'); row.className = 'popRow'; const hex = document.createElement('input'); hex.placeholder = '#rrggbb or name'; hex.spellcheck = false; const go = document.createElement('button'); go.textContent = 'Apply'; const doApply = () => { const val = hex.value.trim(); if (/^#[0-9a-f]{3}([0-9a-f]{3})?$/i.test(val) || /^[a-z]{3,20}$/i.test(val)) applyColor(val); else hex.select(); }; go.addEventListener('mousedown', (ev) => ev.preventDefault()); go.addEventListener('click', doApply); hex.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); doApply(); } else if (ev.key === 'Escape') { ev.preventDefault(); closePop(); ed.focus(); } }); row.appendChild(hex); row.appendChild(go); pop.appendChild(row); const clear = document.createElement('button'); clear.className = 'popClear'; clear.textContent = popMode === 'color' ? 'Remove text color' : 'Remove highlight'; clear.addEventListener('mousedown', (ev) => ev.preventDefault()); clear.addEventListener('click', () => applyColor('')); pop.appendChild(clear); } function openPop(mode, anchor) { if (!pop.hidden && popMode === mode && popAnchor === anchor) { closePop(); return; } popMode = mode; popAnchor = anchor; buildPop(); pop.hidden = false; const r = anchor.getBoundingClientRect(); const left = Math.max(6, Math.min(r.left, window.innerWidth - pop.offsetWidth - 8)); pop.style.left = left + 'px'; pop.style.top = (r.bottom + 4) + 'px'; } document.addEventListener('mousedown', (ev) => { if (!pop.hidden && !pop.contains(ev.target) && ev.target !== popAnchor && !(popAnchor && popAnchor.contains(ev.target))) closePop(); }); document.addEventListener('keydown', (ev) => { if (ev.key === 'Escape' && !pop.hidden) closePop(); }); /* ---------- wiring ---------- */ const actions = { bold, italic, underline: () => toggleWrap('', '', 'underlined text'), strike: () => toggleWrap('', '', 'struck text'), sub: () => toggleWrap('', '', 'sub'), sup: () => toggleWrap('', '', 'sup'), code: () => toggleWrap('', '', 'code'), nowiki: () => toggleWrap('', '', 'plain text'), quote: () => toggleWrap('
', '
', 'Quote'), link: () => toggleWrap('[[', ']]', 'Page name'), template: () => toggleWrap('{{', '}}', 'Template name'), ref: () => toggleWrap('', '', 'Reference text'), extlink: extLink, hr: () => insertBlock('----'), ul: () => toList('*'), ol: () => toList('#'), indent, outdent, 'align-left': () => align('left'), 'align-center': () => align('center'), 'align-right': () => align('right'), 'align-justify': () => align('justify'), clear: clearFormatting }; document.querySelectorAll('[data-fmt]').forEach((b) => { b.addEventListener('mousedown', (ev) => ev.preventDefault()); b.addEventListener('click', () => { const k = b.dataset.fmt; if (k === 'color' || k === 'highlight') { openPop(k, b); return; } if (actions[k]) actions[k](); }); }); const sizeSel = document.getElementById('sizeSel'); if (sizeSel) { sizeSel.addEventListener('change', () => { const v = sizeSel.value; sizeSel.value = ''; if (!v) return; applySpan('font-size', v === 'normal' ? '' : v + '%'); }); } const blockSizeSel = document.getElementById('blockSizeSel'); if (blockSizeSel) { blockSizeSel.addEventListener('change', () => { const v = blockSizeSel.value; blockSizeSel.value = ''; if (!v) return; applyDivStyle('font-size', v === 'normal' ? '' : v + '%', false); }); } const headSel = document.getElementById('headSel'); if (headSel) { headSel.addEventListener('change', () => { const v = headSel.value; headSel.value = ''; if (!v) return; heading(v === 'p' ? 0 : parseInt(v, 10)); }); } ed.addEventListener('keydown', (ev) => { if (!(ev.ctrlKey || ev.metaKey) || ev.shiftKey || ev.altKey) return; const k = ev.key.toLowerCase(); if (k === 'b') { ev.preventDefault(); bold(); } else if (k === 'i') { ev.preventDefault(); italic(); } else if (k === 'u') { ev.preventDefault(); actions.underline(); } else if (k === 'k') { ev.preventDefault(); actions.link(); } }); const api = { replaceRange, insert, lineRange, toggleWrap, insertBlock, sel, applySpan, applyDivStyle }; return { actions, applySpan, align, heading, api }; } window.SwiftFormat = { init }; })();