(function () {
'use strict';
const wn = window.wn;
const $ = (id) => document.getElementById(id);
const ed = $('editor');
const state = {
cfg: null,
file: null,
mode: 'fallback', // 'live' or 'fallback'
api: null,
siteName: '',
reason: null, // why we are in fallback: {kind, detail}
connecting: false,
connectSeq: 0,
renderSeq: 0,
renderTimer: null,
saveTimer: null,
searchTimer: null,
dirty: false,
dialogKey: null,
cssWarned: false,
tables: null,
notes: []
};
/* ---------- small helpers ---------- */
function el(tag, text, cls) {
const e = document.createElement(tag);
if (text !== undefined && text !== null) e.textContent = text;
if (cls) e.className = cls;
return e;
}
let toastTimer = null;
function toast(msg, ms) {
const t = $('toast');
t.textContent = msg;
t.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { t.hidden = true; }, ms || 3500);
}
function hostOf(url) {
try {
return new URL(/^https?:\/\//i.test(url) ? url : 'https://' + url).host;
} catch (e) { return url || ''; }
}
function baseName(p) { return String(p || '').split(/[\\/]/).pop(); }
function uid() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 6); }
function openModal(opts) {
const ov = el('div', null, 'overlay');
const dlg = el('div', null, 'dialog' + (opts.wide ? ' wide' : ''));
dlg.appendChild(el('h2', opts.title));
const body = el('div', null, 'dialogBody');
if (opts.content) body.appendChild(opts.content);
dlg.appendChild(body);
const bar = el('div', null, 'dialogButtons');
let done = null;
const promise = new Promise((resolve) => { done = resolve; });
function topOverlay() {
const all = document.querySelectorAll('.overlay');
return all[all.length - 1];
}
function close(v) {
document.removeEventListener('keydown', onKey, true);
ov.remove();
done(v);
}
function onKey(e) {
if (e.key === 'Escape' && topOverlay() === ov) {
e.stopPropagation();
close(null);
}
}
document.addEventListener('keydown', onKey, true);
(opts.buttons || [{ label: 'OK', value: 'ok', primary: true }]).forEach((b) => {
const btn = el('button', b.label);
if (b.primary) btn.classList.add('primary');
btn.addEventListener('click', () => close(b.value));
bar.appendChild(btn);
});
dlg.appendChild(bar);
ov.appendChild(dlg);
document.body.appendChild(ov);
const first = bar.querySelector('.primary') || bar.querySelector('button');
if (first && !opts.noFocus) first.focus();
return { promise, close, body };
}
/* ---------- config helpers ---------- */
function activeProfile() {
return state.cfg.profiles.find((p) => p.id === state.cfg.active) || null;
}
function cssKey() { return state.cfg.active || 'none'; }
function cssInfo() { return state.cfg.css[cssKey()] || { path: '', on: false }; }
function setCssInfo(v) {
const css = Object.assign({}, state.cfg.css);
css[cssKey()] = v;
state.cfg.css = css;
wn.setConfig({ css });
state.cssWarned = false;
updateCssUi();
schedulePreview(0);
}
function applyLayout() {
$('panes').classList.toggle('swapped', !!state.cfg.swapped);
$('sidebar').classList.toggle('hidden', !state.cfg.sidebar);
$('btnSidebar').classList.toggle('on', !!state.cfg.sidebar);
}
function fillWikiSelect() {
const sel = $('wikiSelect');
sel.innerHTML = '';
const none = el('option', 'No wiki (rough preview)');
none.value = '';
sel.appendChild(none);
state.cfg.profiles.forEach((p) => {
const o = el('option', p.name || hostOf(p.url));
o.value = p.id;
sel.appendChild(o);
});
sel.value = state.cfg.active || '';
}
function updateCssUi() {
const info = cssInfo();
const has = !!info.path;
$('btnCssToggle').disabled = !has;
$('btnCssToggle').textContent = info.on && has ? 'CSS on' : 'CSS off';
$('btnCssToggle').classList.toggle('on', info.on && has);
$('btnCssClear').hidden = !has;
$('cssName').textContent = has ? baseName(info.path) : '';
$('cssName').title = info.path || '';
}
function updateBadge() {
const b = $('modeBadge');
b.className = 'badge';
if (state.connecting) {
b.textContent = 'Connecting...';
b.classList.add('busy');
$('previewSource').textContent = '';
} else if (state.mode === 'live') {
b.textContent = 'Live preview';
b.classList.add('live');
b.title = 'Rendered by ' + (state.siteName || 'your wiki') + '. Click for details.';
$('previewSource').textContent = state.siteName ? 'from ' + state.siteName : '';
} else {
b.textContent = 'Rough preview';
b.classList.add('rough');
b.title = 'Click to see why this is a rough preview and how to get a live one.';
$('previewSource').textContent = 'local approximation';
}
}
/* ---------- preview ---------- */
async function getCssText() {
const info = cssInfo();
if (!info.on || !info.path) return '';
const r = await wn.readCss(info.path);
if (r.ok) return r.text;
if (!state.cssWarned) {
state.cssWarned = true;
toast('Could not read the CSS file: ' + r.error, 5000);
}
return '';
}
function injectCss(doc, css) {
if (!css) return doc;
const tag = '';
if (/<\/head>/i.test(doc)) return doc.replace(/<\/head>/i, () => tag + '');
return tag + doc;
}
function currentTitle() {
return $('titleInput').value.trim() || 'Untitled';
}
function setPreview(doc) {
const frame = $('preview');
let sy = 0;
try { sy = frame.contentWindow.scrollY || 0; } catch (e) { sy = 0; }
return new Promise((resolve) => {
const guard = setTimeout(resolve, 5000);
frame.onload = () => {
clearTimeout(guard);
try { frame.contentWindow.scrollTo(0, sy); } catch (e) { /* ignore */ }
if (state.tables) state.tables.attachPreview(frame);
resolve();
};
frame.srcdoc = doc;
});
}
async function render() {
const seq = ++state.renderSeq;
const text = state.tables ? state.tables.annotate(ed.value) : ed.value;
const title = currentTitle();
let doc = null;
if (state.mode === 'live' && state.api) {
const r = await wn.parse({ api: state.api, text, title });
if (seq !== state.renderSeq) return;
if (r.ok) {
doc = r.doc;
} else {
state.mode = 'fallback';
state.api = null;
state.reason = { kind: r.kind, detail: r.detail };
updateBadge();
maybeShowDialog();
}
}
if (!doc) doc = window.WikiFallback.buildDocument(text, title);
const css = await getCssText();
if (seq !== state.renderSeq) return;
await setPreview(injectCss(doc, css));
}
// For export: make sure the preview is current, then hand over its document.
async function snapshotPreview() {
clearTimeout(state.renderTimer);
await render();
try { return $('preview').contentDocument; } catch (e) { return null; }
}
function schedulePreview(ms) {
clearTimeout(state.renderTimer);
const wait = ms !== undefined ? ms : (state.mode === 'live' ? 500 : 150);
state.renderTimer = setTimeout(render, wait);
}
function syncScroll() {
const frame = $('preview');
try {
const max = ed.scrollHeight - ed.clientHeight;
const ratio = max > 0 ? ed.scrollTop / max : 0;
const w = frame.contentWindow;
const h = w.document.documentElement.scrollHeight - w.innerHeight;
if (h > 0) w.scrollTo(0, ratio * h);
} catch (e) { /* preview not ready */ }
}
/* ---------- the "rough preview" dialog ---------- */
function maybeShowDialog(force) {
const key = (state.cfg.active || 'none') + ':' + (state.reason ? state.reason.kind : '');
if (!force && state.dialogKey === key) return;
state.dialogKey = key;
showFallbackDialog();
}
async function showFallbackDialog() {
const r = state.reason || { kind: 'nowiki' };
const p = activeProfile();
const host = p ? hostOf(p.url) : '';
const wrap = el('div');
if (state.mode === 'live') {
wrap.appendChild(el('p', 'You are getting a live preview from ' + (state.siteName || host) +
'. The preview is produced by the wiki itself, with its real styling.'));
const m = openModal({ title: 'Live preview', content: wrap, buttons: [{ label: 'OK', value: 'ok', primary: true }] });
await m.promise;
return;
}
if (r.kind === 'nowiki') {
wrap.appendChild(el('p', 'No wiki is set up yet, so you are looking at a rough local preview. It is only a guess at how your page would look and will not match any particular wiki.'));
} else {
wrap.appendChild(el('p', 'Swiftmark could not get a live preview from ' + (host || 'your wiki') + '. ' + (r.detail || '')));
}
wrap.appendChild(el('p', 'Until that is fixed the preview is rough. It handles headings, bold and italic, links, lists, tables and references. Templates, infoboxes, parser functions and your wiki\'s own styling are not rendered, so expect differences.'));
const strong = el('p');
strong.appendChild(el('b', 'To get a live preview that looks exactly like your wiki, unlock its API:'));
wrap.appendChild(strong);
const ol = el('ol');
const li1 = el('li', 'Make sure api.php can be reached. Open an address like ');
li1.appendChild(el('code', 'https://yourwiki.example.org/w/api.php'));
li1.appendChild(document.createTextNode(' in a browser. You should see an API help page, not an error.'));
ol.appendChild(li1);
const li2 = el('li', 'If your wiki hides pages from logged out visitors, the API refuses them too. To allow reading without a login, an admin sets ');
li2.appendChild(el('code', "$wgGroupPermissions['*']['read'] = true;"));
li2.appendChild(document.createTextNode(' in LocalSettings.php. This makes the whole wiki public. Swiftmark does not log in to wikis yet.'));
ol.appendChild(li2);
ol.appendChild(el('li', 'If a firewall, security plugin or CDN bot protection is blocking api.php, allow requests to it. Swiftmark identifies itself as Swiftmark/1.0.'));
ol.appendChild(el('li', 'If the address is wrong, enter the wiki\'s main page address under Wikis. Swiftmark finds api.php from there.'));
wrap.appendChild(ol);
const buttons = r.kind === 'nowiki'
? [{ label: 'Keep rough preview', value: 'keep' }, { label: 'Add a wiki', value: 'settings', primary: true }]
: [{ label: 'Keep rough preview', value: 'keep' }, { label: 'Wiki settings', value: 'settings' }, { label: 'Retry', value: 'retry', primary: true }];
const m = openModal({ title: 'Rough local preview', content: wrap, buttons, wide: true });
const choice = await m.promise;
if (choice === 'settings') openSettings();
else if (choice === 'retry') connectActive({ force: true });
}
/* ---------- connecting to the wiki ---------- */
async function connectActive(opts) {
opts = opts || {};
const seq = ++state.connectSeq;
const p = activeProfile();
state.api = null;
state.mode = 'fallback';
if (!p) {
state.connecting = false;
state.reason = { kind: 'nowiki' };
updateBadge();
schedulePreview(0);
if (opts.dialog !== false) maybeShowDialog(opts.force);
return { ok: false, kind: 'nowiki' };
}
state.connecting = true;
updateBadge();
const r = await wn.connect(p.url);
if (seq !== state.connectSeq) return r;
state.connecting = false;
if (r.ok) {
state.mode = 'live';
state.api = r.api;
state.siteName = r.siteName;
state.reason = null;
state.dialogKey = null;
} else {
state.reason = { kind: r.kind, detail: r.detail };
}
updateBadge();
schedulePreview(0);
if (!r.ok && opts.dialog !== false) maybeShowDialog(opts.force);
return r;
}
/* ---------- wiki settings ---------- */
function openSettings() {
const wrap = el('div');
let working = null; // profile being edited, id null when new
// notes folder
const rowFolder = el('div', null, 'formRow');
rowFolder.appendChild(el('label', 'Notes folder'));
const folderCode = el('code', state.cfg.notesDir);
rowFolder.appendChild(folderCode);
const btnFolder = el('button', 'Change...');
rowFolder.appendChild(btnFolder);
wrap.appendChild(rowFolder);
wrap.appendChild(el('hr', null, 'divider'));
// wiki profile form
const rowSel = el('div', null, 'formRow');
rowSel.appendChild(el('label', 'Saved wikis'));
const sel = el('select');
rowSel.appendChild(sel);
wrap.appendChild(rowSel);
const rowName = el('div', null, 'formRow');
rowName.appendChild(el('label', 'Name'));
const inName = el('input');
inName.placeholder = 'My wiki';
rowName.appendChild(inName);
wrap.appendChild(rowName);
const rowUrl = el('div', null, 'formRow');
rowUrl.appendChild(el('label', 'Address'));
const inUrl = el('input');
inUrl.placeholder = 'https://yourwiki.example.org';
inUrl.spellcheck = false;
rowUrl.appendChild(inUrl);
wrap.appendChild(rowUrl);
const actions = el('div', null, 'formActions');
const btnTest = el('button', 'Test connection');
const btnSave = el('button', 'Save and use');
btnSave.classList.add('primary');
const btnDel = el('button', 'Delete');
actions.appendChild(btnTest);
actions.appendChild(btnSave);
actions.appendChild(btnDel);
wrap.appendChild(actions);
const result = el('div', null, 'formResult');
wrap.appendChild(result);
function showResult(msg, good) {
result.textContent = msg;
result.className = 'formResult ' + (good ? 'good' : 'bad');
}
function refillSelect(selectId) {
sel.innerHTML = '';
state.cfg.profiles.forEach((p) => {
const o = el('option', p.name || hostOf(p.url));
o.value = p.id;
sel.appendChild(o);
});
const n = el('option', '(add a new wiki)');
n.value = '';
sel.appendChild(n);
sel.value = selectId !== undefined ? selectId : '';
}
function loadWorking() {
const p = state.cfg.profiles.find((x) => x.id === sel.value);
working = p ? Object.assign({}, p) : { id: null, name: '', url: '' };
inName.value = working.name;
inUrl.value = working.url;
btnDel.disabled = !p;
result.textContent = '';
}
refillSelect(state.cfg.active || (state.cfg.profiles[0] ? state.cfg.profiles[0].id : ''));
loadWorking();
sel.addEventListener('change', loadWorking);
btnFolder.addEventListener('click', async () => {
const dir = await wn.pickFolder();
if (!dir) return;
await wn.setConfig({ notesDir: dir });
state.cfg.notesDir = dir;
folderCode.textContent = dir;
$('folderLabel').textContent = dir;
$('folderLabel').title = dir;
state.file = null;
await refreshNotes();
if (state.notes.length) await openNote(state.notes[0].file);
else await newNote(true);
toast('Now using ' + dir);
});
btnTest.addEventListener('click', async () => {
const url = inUrl.value.trim();
if (!url) { showResult('Enter the wiki address first.', false); return; }
showResult('Testing...', true);
const r = await wn.connect(url);
if (r.ok) showResult('Connected to ' + r.siteName + '. Live preview will work.', true);
else showResult(r.detail || 'Could not connect.', false);
});
btnSave.addEventListener('click', async () => {
const url = inUrl.value.trim();
if (!url) { showResult('Enter the wiki address first.', false); return; }
const name = inName.value.trim() || hostOf(url);
const profiles = state.cfg.profiles.slice();
let id = working.id;
if (id) {
const i = profiles.findIndex((x) => x.id === id);
if (i >= 0) profiles[i] = { id, name, url };
} else {
id = uid();
profiles.push({ id, name, url });
}
await wn.setConfig({ profiles, active: id });
state.cfg.profiles = profiles;
state.cfg.active = id;
fillWikiSelect();
updateCssUi();
refillSelect(id);
loadWorking();
showResult('Saved. Connecting...', true);
const r = await connectActive({ dialog: false });
if (r && r.ok) showResult('Saved. Connected to ' + r.siteName + '. Live preview is on.', true);
else showResult('Saved, but no live preview yet. ' + ((r && r.detail) || ''), false);
});
btnDel.addEventListener('click', async () => {
if (!working || !working.id) return;
const profiles = state.cfg.profiles.filter((x) => x.id !== working.id);
let active = state.cfg.active;
const deletedActive = active === working.id;
if (deletedActive) active = null;
await wn.setConfig({ profiles, active });
state.cfg.profiles = profiles;
state.cfg.active = active;
fillWikiSelect();
updateCssUi();
refillSelect(active || '');
loadWorking();
if (deletedActive) await connectActive({ dialog: false });
showResult('Deleted.', true);
});
openModal({ title: 'Wikis and notes folder', content: wrap, wide: true, noFocus: true, buttons: [{ label: 'Close', value: 'close', primary: true }] });
}
/* ---------- notes ---------- */
function fmtDate(ms) {
const d = new Date(ms);
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ' ' +
d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
}
function renderNoteList() {
const ul = $('noteList');
ul.innerHTML = '';
if (!state.notes.length) {
ul.appendChild(el('li', $('search').value ? 'No notes match.' : 'No notes yet.', 'none'));
return;
}
state.notes.forEach((n) => {
const li = el('li');
li.dataset.file = n.file;
if (n.file === state.file) li.classList.add('active');
li.appendChild(el('span', n.title, 't'));
li.appendChild(el('span', fmtDate(n.mtime), 'd'));
li.title = n.title;
li.addEventListener('click', () => { if (n.file !== state.file) openNote(n.file); });
ul.appendChild(li);
});
}
async function refreshNotes() {
state.notes = await wn.listNotes($('search').value);
renderNoteList();
}
function setStatus(msg) { $('noteStatus').textContent = msg; }
function updateCount() {
const t = ed.value;
const words = (t.trim().match(/\S+/g) || []).length;
$('countStatus').textContent = words + (words === 1 ? ' word, ' : ' words, ') + t.length + ' characters';
}
async function saveNow() {
clearTimeout(state.saveTimer);
if (!state.file || !state.dirty) return;
const file = state.file;
const text = ed.value;
state.dirty = false;
setStatus('Saving...');
try {
await wn.writeNote(file, text);
setStatus('Saved');
if (!state.dirty) refreshNotes();
} catch (e) {
state.dirty = true;
setStatus('Could not save: ' + e.message);
}
}
async function openNote(file) {
await saveNow();
let text = '';
try { text = await wn.readNote(file); } catch (e) { toast('Could not open that note.'); await refreshNotes(); return; }
state.file = file;
ed.value = text;
$('titleInput').value = file.replace(/\.(wiki|mediawiki|txt)$/i, '');
state.dirty = false;
setStatus('Saved');
updateCount();
renderNoteList();
wn.setConfig({ lastNote: file });
schedulePreview(0);
ed.scrollTop = 0;
}
async function newNote(silent) {
await saveNow();
const r = await wn.createNote('Untitled');
$('search').value = '';
await refreshNotes();
await openNote(r.file);
if (!silent) {
$('titleInput').focus();
$('titleInput').select();
}
}
async function renameCurrent() {
if (!state.file) return;
const input = $('titleInput');
const old = state.file.replace(/\.(wiki|mediawiki|txt)$/i, '');
const wanted = input.value.trim();
if (!wanted || wanted === old) { input.value = old; return; }
await saveNow();
const r = await wn.renameNote(state.file, wanted);
if (!r.ok) {
toast(r.error === 'exists' ? 'A note with that title already exists.' : 'That title cannot be used.');
input.value = old;
return;
}
state.file = r.file;
input.value = r.file.replace(/\.(wiki|mediawiki|txt)$/i, '');
wn.setConfig({ lastNote: r.file });
await refreshNotes();
schedulePreview(0);
}
async function deleteCurrent() {
if (!state.file) return;
const name = $('titleInput').value;
const wrap = el('div');
wrap.appendChild(el('p', 'Delete "' + name + '"? This removes the file from your notes folder and cannot be undone.'));
const m = openModal({
title: 'Delete note',
content: wrap,
buttons: [{ label: 'Cancel', value: 'no', primary: true }, { label: 'Delete', value: 'yes' }]
});
if ((await m.promise) !== 'yes') return;
const file = state.file;
state.file = null;
state.dirty = false;
clearTimeout(state.saveTimer);
try { await wn.deleteNote(file); } catch (e) { toast('Could not delete: ' + e.message); }
await refreshNotes();
if (state.notes.length) await openNote(state.notes[0].file);
else await newNote(true);
}
const WELCOME = [
"== Welcome to Swiftmark ==",
"Type wikitext on one side and watch it render on the other. Use '''Swap sides''' at the top right to put the editor on whichever side you like.",
"",
"=== Try some markup ===",
"* A bullet with ''italic'' and '''bold''' text",
"* A link to [[Another page]] and one to [https://example.org an outside site]",
"# A numbered item",
"# Another one",
"",
"{| class=\"wikitable\"",
"! Thing !! Count",
"|-",
"| Notes || 1",
"|}",
"",
"=== Formatting toolbar ===",
"Select some text and use the bar above the editor: underline, strikethrough, H2O, x2, colors, highlights, sizes and alignment.",
"