1303 lines
71 KiB
JavaScript
1303 lines
71 KiB
JavaScript
// UI: unlock / load, section navigation, read-only view, edit mode.
|
|
// All DOM is built with h() + textContent, never innerHTML, so document
|
|
// content can't inject markup.
|
|
(function () {
|
|
const root = document.getElementById('app');
|
|
const state = {
|
|
doc: null,
|
|
passphrase: null, // kept in memory for saving (issue #6)
|
|
current: null, // current section id
|
|
editing: false,
|
|
dirty: false,
|
|
baseline: null, // deep copy of the document at open/save; Cancel reverts to it
|
|
pwChanged: false, // passphrase changed since the last save
|
|
tabs: {}, // section id -> id of the sub-tab being shown ('' = General); not saved
|
|
collapsed: new Set(), // ids of records folded to just their title (view mode only)
|
|
searchOpen: false, // the search controls are showing in place of the toolbar buttons
|
|
search: null, // { q, hits: [{sid, eid, n}], i, scroll }: the active search (not saved)
|
|
searchAll: false, // true only while building the hidden copy the search counts matches in
|
|
walk: null, // { id, k }: the visual sequence shown as a one-step-at-a-time walkthrough (not saved)
|
|
revealed: new WeakSet(), // secret field objects currently shown
|
|
blob: null, // encrypted payload taken from a file the user chose to open
|
|
handle: null, // File System Access handle once the user picked a save location
|
|
status: '',
|
|
error: '',
|
|
};
|
|
|
|
// ?reset=1 (or #reset=1): after unlock, offer to erase every secret value.
|
|
// Read live: typing #reset=1 into an already-open page only fires hashchange, it does not reload.
|
|
const resetRequested = () => /[?#&]reset=1(?![0-9])/.test(location.search + location.hash);
|
|
const resetBanner = () => {
|
|
const n = countSecrets(state.doc);
|
|
const done = () => { state.resetOffered = true; render(); };
|
|
return h('div', { class: 'card', role: 'alert' },
|
|
h('h2', {}, 'Reset: erase secret values'),
|
|
h('p', {}, n ? 'This will erase ' + n + ' secret value' + (n === 1 ? '' : 's') + ' (passwords, PINs, secret images and steps) from this document in memory. Labels and everything else stay.'
|
|
: 'This document has no secret values to erase.'),
|
|
h('p', {}, 'Nothing is written until you Save. Make a Backup copy first if you may need the secrets again, because saving over this file removes them for good.'),
|
|
h('div', { class: 'row' },
|
|
n ? btn('Erase ' + n + ' secret value' + (n === 1 ? '' : 's'), () => {
|
|
const erased = clearSecrets(state.doc);
|
|
state.revealed = new WeakSet();
|
|
state.resetOffered = true;
|
|
markDirty();
|
|
state.status = 'Erased ' + erased + ' secret value' + (erased === 1 ? '' : 's') + '. Save to keep this.';
|
|
render();
|
|
}, 'primary') : null,
|
|
btn(n ? 'Keep them' : 'Dismiss', done)));
|
|
};
|
|
|
|
function h(tag, attrs, ...kids) {
|
|
const el = document.createElement(tag);
|
|
for (const [k, v] of Object.entries(attrs || {})) {
|
|
if (v === false || v == null) continue;
|
|
if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
|
|
else if (k === 'class') el.className = v;
|
|
else if (k in el && k !== 'list') el[k] = v;
|
|
else el.setAttribute(k, v === true ? '' : v);
|
|
}
|
|
for (const kid of kids.flat(Infinity)) {
|
|
if (kid == null || kid === false) continue;
|
|
el.append(kid.nodeType ? kid : document.createTextNode(String(kid)));
|
|
}
|
|
return el;
|
|
}
|
|
const btn = (label, onclick, cls = '', extra = {}) =>
|
|
h('button', Object.assign({ type: 'button', class: 'btn ' + cls, onclick }, extra), label);
|
|
|
|
function markDirty() {
|
|
state.dirty = true;
|
|
const d = document.getElementById('dirty');
|
|
if (d) d.hidden = false;
|
|
state.status = '';
|
|
const st = document.getElementById('status');
|
|
if (st) st.textContent = '';
|
|
}
|
|
function changed(record) {
|
|
touch(state.doc, record);
|
|
markDirty();
|
|
}
|
|
function snapshot() {
|
|
state.baseline = snapshotDoc(state.doc);
|
|
state.pwChanged = false;
|
|
}
|
|
window.addEventListener('beforeunload', (e) => {
|
|
if (state.dirty) { e.preventDefault(); e.returnValue = ''; }
|
|
});
|
|
|
|
// ---------- start / unlock ----------
|
|
function payloadText() {
|
|
const p = document.getElementById('payload');
|
|
return p ? p.textContent.trim() : '';
|
|
}
|
|
|
|
function renderStart() {
|
|
const blob = state.blob || payloadText();
|
|
const msg = h('p', { class: 'error', role: 'alert' }, state.error);
|
|
if (blob) {
|
|
const pw = h('input', { type: 'password', autocomplete: 'current-password', autofocus: true, 'aria-label': 'Passphrase' });
|
|
const form = h('form', { class: 'card start', onsubmit: async (e) => {
|
|
e.preventDefault();
|
|
state.error = '';
|
|
try {
|
|
const doc = JSON.parse(await decrypt(blob, pw.value));
|
|
assertValid(doc);
|
|
state.doc = doc;
|
|
snapshot();
|
|
state.passphrase = pw.value;
|
|
state.blob = null;
|
|
state.current = doc.sections[0] && doc.sections[0].id;
|
|
} catch (err) {
|
|
state.error = err instanceof DecryptError ? err.message : 'Could not open the file: ' + err.message;
|
|
}
|
|
render();
|
|
} },
|
|
h('h1', {}, 'Final Wishes'),
|
|
h('p', {}, 'Enter the passphrase to open this document.'),
|
|
pw, msg, btn('Open', null, 'primary', { type: 'submit' }),
|
|
state.blob ? btn('Choose a different file', () => { state.blob = null; state.error = ''; render(); }, 'small') : null);
|
|
return form;
|
|
}
|
|
// No encrypted data embedded yet (development / first use).
|
|
const file = h('input', { type: 'file', accept: '.json,application/json', 'aria-label': 'Open a JSON file', onchange: async () => {
|
|
try {
|
|
const doc = JSON.parse(await file.files[0].text());
|
|
assertValid(doc);
|
|
state.doc = doc;
|
|
snapshot();
|
|
state.current = doc.sections[0] && doc.sections[0].id;
|
|
state.error = '';
|
|
} catch (err) { state.error = 'Could not open that file: ' + err.message; }
|
|
render();
|
|
} });
|
|
const existing = h('input', { type: 'file', accept: '.html,text/html', 'aria-label': 'Open an existing Final Wishes file', onchange: async () => {
|
|
const m = (await existing.files[0].text()).match(/<script id="payload"[^>]*>([^<]*)<\/script>/);
|
|
if (m && m[1].trim()) { state.blob = m[1].trim(); state.error = ''; }
|
|
else state.error = 'That file has no encrypted Final Wishes data in it.';
|
|
render();
|
|
} });
|
|
return h('div', { class: 'card start' },
|
|
h('h1', {}, 'Final Wishes'),
|
|
h('p', {}, 'No encrypted data is built into this file yet.'),
|
|
h('p', {}, 'Open your existing Final Wishes file (your data is carried into this newer version; the old file is not changed until you save over it):'), existing,
|
|
h('p', {}, 'Import a plain JSON file (you will choose a passphrase when you save):'), file, msg,
|
|
h('p', {}, 'or'),
|
|
btn('Start a new document', () => {
|
|
state.doc = emptyDocument('');
|
|
snapshot();
|
|
state.editing = true;
|
|
render();
|
|
}, 'primary'));
|
|
}
|
|
|
|
// ---------- images ----------
|
|
function setStatus(msg) {
|
|
state.status = msg;
|
|
const st = document.getElementById('status');
|
|
if (st) st.textContent = msg;
|
|
}
|
|
const hasFiles = (e) => !!(e.dataTransfer && [...(e.dataTransfer.types || [])].includes('Files'));
|
|
const isImageFile = (f) => /^image\//.test(f.type) || /\.(png|jpe?g)$/i.test(f.name || '');
|
|
const allRecords = () => state.doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r)));
|
|
const addFrameFrom = (seq) => (name, url) => addFrame(seq, url);
|
|
|
|
// Copy a credential for the reader, then wipe the clipboard after 30 seconds
|
|
// (this overwrites whatever is on the clipboard by then, whether or not it is ours).
|
|
let clipTimer = null;
|
|
async function copyValue(fld) {
|
|
try {
|
|
await navigator.clipboard.writeText(fld.value);
|
|
clearTimeout(clipTimer);
|
|
clipTimer = setTimeout(() => { navigator.clipboard.writeText('').catch(() => {}); }, 30000);
|
|
setStatus('Copied ' + fld.label + '. The clipboard is cleared in 30 seconds.');
|
|
} catch {
|
|
setStatus('Could not copy ' + fld.label + '. Show it and copy it by hand.');
|
|
}
|
|
}
|
|
|
|
// Screen capture while editing a visual sequence. The stream lives here, not in
|
|
// the DOM, so it survives render(). { stream, video, seqId } or null.
|
|
let capture = null;
|
|
function endCapture() { stopScreenCapture(capture); capture = null; }
|
|
async function beginCapture(q) {
|
|
endCapture();
|
|
try {
|
|
const cap = await startScreenCapture();
|
|
cap.seqId = q.id;
|
|
cap.stream.getVideoTracks()[0].onended = () => { if (capture === cap) { capture = null; setStatus('Screen sharing ended.'); render(); } };
|
|
capture = cap;
|
|
setStatus('Sharing. Get the site to the screen you want, come back here and click Capture step.');
|
|
} catch (err) {
|
|
setStatus(err.message);
|
|
}
|
|
render();
|
|
}
|
|
async function captureStep(q) {
|
|
try {
|
|
const url = await processImageFile(await grabScreenFrame(capture));
|
|
addCapture(q, url);
|
|
changed(q); // clears the status, so set it afterwards
|
|
setStatus('Step ' + q.frames.length + ' captured.');
|
|
} catch (err) {
|
|
setStatus(err.message);
|
|
}
|
|
render();
|
|
}
|
|
|
|
// Add each file as a new image field on `rec`, or put the first into
|
|
// `opts.replace` (an existing image field). Per-file problems are reported
|
|
// together; the files that worked are still kept.
|
|
// opts.replace: an existing object whose opts.key (default 'value') takes the first file.
|
|
// opts.add(name, url): how a new image is added (default: a new image field on `rec`).
|
|
async function importFiles(rec, files, opts = {}) {
|
|
const key = opts.key || 'value';
|
|
const add = opts.add || ((name, url) => addImageField(rec, opts.pasted ? 'Pasted image' : labelFromFilename(name), url));
|
|
let added = 0;
|
|
const errors = [];
|
|
for (const file of files) {
|
|
try {
|
|
const url = await processImageFile(file);
|
|
if (opts.replace && !added) { opts.replace[key] = url; if (key === 'image') delete opts.replace.marks; }
|
|
else add(file.name, url);
|
|
added++;
|
|
} catch (err) {
|
|
errors.push((file.name ? file.name + ': ' : '') + err.message);
|
|
}
|
|
}
|
|
if (added) changed(rec); // clears the status, so set it afterwards
|
|
setStatus(errors.length ? errors.join(' ') : added + (added === 1 ? ' image added.' : ' images added.'));
|
|
render();
|
|
}
|
|
|
|
// Dropping a file on the page must never navigate away from unsaved work.
|
|
window.addEventListener('dragover', (e) => { if (hasFiles(e)) e.preventDefault(); });
|
|
window.addEventListener('drop', (e) => { if (hasFiles(e)) e.preventDefault(); });
|
|
|
|
// Paste an image: into an image field replaces it, anywhere else in a record adds a new field.
|
|
document.addEventListener('paste', (e) => {
|
|
if (!state.doc) return;
|
|
const files = [...(e.clipboardData ? e.clipboardData.files : [])].filter(isImageFile);
|
|
if (!files.length) return; // ordinary text paste is left alone
|
|
const t = e.target;
|
|
if (t && /^(INPUT|TEXTAREA)$/.test(t.tagName) && e.clipboardData.getData('text/plain')) return;
|
|
if (!state.editing) return setStatus('Choose Edit, then paste into a record or visual sequence.');
|
|
const seqEl = t && t.closest ? t.closest('[data-seq]') : null;
|
|
const seq = seqEl && allSequences(state.doc).find((q) => q.id === seqEl.dataset.seq);
|
|
if (seq) {
|
|
e.preventDefault();
|
|
const fz = t.closest('[data-frame]');
|
|
const frame = fz ? seq.frames[Number(fz.dataset.frame)] : null;
|
|
return importFiles(seq, files, { key: 'image', replace: frame, add: addFrameFrom(seq) });
|
|
}
|
|
const recEl = t && t.closest ? t.closest('[data-rec]') : null;
|
|
const rec = recEl && allRecords().find((r) => r.id === recEl.dataset.rec);
|
|
if (!rec) return setStatus('Click inside a record or visual sequence first, then paste.');
|
|
e.preventDefault();
|
|
const zone = t.closest('[data-field]');
|
|
const field = zone ? rec.fields[Number(zone.dataset.field)] : null;
|
|
importFiles(rec, files, { replace: field && field.kind === 'image' ? field : null, pasted: true });
|
|
});
|
|
|
|
// A step's picture with its markers and boxes laid over it. Positions are fractions
|
|
// of the picture, so they stay put at any size, in print too.
|
|
function markedImage(img, marks) {
|
|
if (!marks || !marks.length) return img;
|
|
let n = 0;
|
|
return h('div', { class: 'marked' }, img, marks.map((m) => (m.type === 'box'
|
|
? h('span', { class: 'mbox', 'aria-hidden': 'true', style: 'left:' + m.x * 100 + '%;top:' + m.y * 100 + '%;width:' + m.w * 100 + '%;height:' + m.h * 100 + '%' })
|
|
: h('span', { class: 'mpin', 'aria-hidden': 'true', style: 'left:' + m.x * 100 + '%;top:' + m.y * 100 + '%' }, String(++n)))));
|
|
}
|
|
|
|
// Mark up a step's picture: numbered markers and highlight boxes (kept as overlays, editable
|
|
// later) and Blur out (burned into the pixels on Apply, so no readable copy is kept).
|
|
async function openAnnotator(q, f) {
|
|
const img = new Image();
|
|
img.src = f.image;
|
|
try { await img.decode(); } catch { return setStatus('That image could not be opened.'); }
|
|
const W = img.naturalWidth, H = img.naturalHeight;
|
|
const base = document.createElement('canvas');
|
|
base.width = W; base.height = H;
|
|
const bctx = base.getContext('2d', { willReadFrequently: true });
|
|
bctx.drawImage(img, 0, 0);
|
|
const marks = structuredClone(f.marks || []);
|
|
const undo = [];
|
|
let tool = 'marker', blurs = 0, drag = null;
|
|
const view = h('canvas', { class: 'annot', width: W, height: H, 'aria-label': 'Picture to mark up' });
|
|
const vctx = view.getContext('2d');
|
|
const lw = Math.max(3, Math.round(W / 300)), pr = Math.max(14, Math.round(W / 60));
|
|
|
|
function draw() {
|
|
vctx.drawImage(base, 0, 0);
|
|
let n = 0;
|
|
for (const m of marks) {
|
|
if (m.type === 'box') {
|
|
vctx.strokeStyle = '#e11'; vctx.lineWidth = lw;
|
|
vctx.strokeRect(m.x * W, m.y * H, m.w * W, m.h * H);
|
|
} else {
|
|
vctx.beginPath(); vctx.arc(m.x * W, m.y * H, pr, 0, 2 * Math.PI);
|
|
vctx.fillStyle = '#e11'; vctx.fill(); vctx.lineWidth = 2; vctx.strokeStyle = '#fff'; vctx.stroke();
|
|
vctx.fillStyle = '#fff'; vctx.font = '700 ' + Math.round(pr * 1.2) + 'px system-ui, sans-serif';
|
|
vctx.textAlign = 'center'; vctx.textBaseline = 'middle'; vctx.fillText(String(++n), m.x * W, m.y * H + 1);
|
|
}
|
|
}
|
|
if (drag) {
|
|
const r = normRect(drag.x0, drag.y0, drag.x1, drag.y1, 0);
|
|
if (r) {
|
|
vctx.setLineDash([8, 6]); vctx.lineWidth = lw; vctx.strokeStyle = tool === 'blur' ? '#000' : '#e11';
|
|
vctx.strokeRect(r.x * W, r.y * H, r.w * W, r.h * H); vctx.setLineDash([]);
|
|
}
|
|
}
|
|
}
|
|
const at = (e) => {
|
|
const b = view.getBoundingClientRect();
|
|
return { x: Math.min(1, Math.max(0, (e.clientX - b.left) / b.width)), y: Math.min(1, Math.max(0, (e.clientY - b.top) / b.height)) };
|
|
};
|
|
view.addEventListener('pointerdown', (e) => {
|
|
const p = at(e);
|
|
if (tool === 'marker') { marks.push({ type: 'marker', x: p.x, y: p.y }); undo.push(() => marks.pop()); draw(); return; }
|
|
view.setPointerCapture(e.pointerId);
|
|
drag = { x0: p.x, y0: p.y, x1: p.x, y1: p.y };
|
|
});
|
|
view.addEventListener('pointermove', (e) => { if (drag) { const p = at(e); drag.x1 = p.x; drag.y1 = p.y; draw(); } });
|
|
view.addEventListener('pointerup', (e) => {
|
|
if (!drag) return;
|
|
const p = at(e);
|
|
const r = normRect(drag.x0, drag.y0, p.x, p.y);
|
|
drag = null;
|
|
if (r && tool === 'box') {
|
|
marks.push({ type: 'box', x: r.x, y: r.y, w: r.w, h: r.h }); undo.push(() => marks.pop());
|
|
} else if (r && tool === 'blur') {
|
|
const snap = bctx.getImageData(0, 0, W, H);
|
|
const id = bctx.getImageData(0, 0, W, H);
|
|
pixelateRegion(id.data, W, H, { x: r.x * W, y: r.y * H, w: r.w * W, h: r.h * H });
|
|
bctx.putImageData(id, 0, 0);
|
|
blurs++; undo.push(() => { bctx.putImageData(snap, 0, 0); blurs--; });
|
|
}
|
|
draw();
|
|
});
|
|
|
|
const tools = [['marker', 'Marker (click)'], ['box', 'Box (drag)'], ['blur', 'Blur out (drag)']];
|
|
const radios = tools.map(([v, t]) => h('label', { class: 'radio' },
|
|
h('input', { type: 'radio', name: 'annot-tool', value: v, checked: v === tool, onchange: () => { tool = v; } }), ' ' + t));
|
|
const dlg = h('dialog', { class: 'card annotator', 'aria-label': 'Mark up picture' },
|
|
h('h3', {}, 'Mark up this picture'),
|
|
h('p', { class: 'muted small' }, 'Marker: click where the reader should click. Box: drag around something to point at. Blur out: drag over anything private, such as account numbers or balances. Blur is permanent once you Apply and Save; markers and boxes can be changed later.'),
|
|
h('div', { class: 'row' }, radios,
|
|
btn('Undo', () => { const u = undo.pop(); if (u) { u(); draw(); } }, 'small'),
|
|
btn('Clear markers and boxes', () => { if (!marks.length) return; const copy = marks.splice(0); undo.push(() => marks.push(...copy)); draw(); }, 'small')),
|
|
view,
|
|
h('div', { class: 'row' },
|
|
btn('Cancel', () => dlg.close()),
|
|
btn('Apply', () => {
|
|
if (blurs > 0) {
|
|
let url = base.toDataURL(f.image.startsWith('data:image/png') ? 'image/png' : 'image/jpeg', JPEG_QUALITY);
|
|
if (!isImageDataUrl(url)) url = base.toDataURL('image/jpeg', JPEG_QUALITY);
|
|
if (!isImageDataUrl(url)) return setStatus('The blurred picture is too large to keep.');
|
|
f.image = url;
|
|
}
|
|
if (marks.length) f.marks = marks; else delete f.marks;
|
|
changed(q); // clears the status, so set it afterwards
|
|
setStatus(blurs > 0 ? 'Picture marked up and blurred. Save to keep it.' : 'Markers and boxes updated.');
|
|
dlg.close(); render();
|
|
}, 'primary')));
|
|
dlg.addEventListener('close', () => dlg.remove());
|
|
document.body.append(dlg);
|
|
dlg.showModal();
|
|
draw();
|
|
}
|
|
|
|
function openLightbox(label, src, marks) {
|
|
const dlg = h('dialog', { class: 'card lightbox', 'aria-label': label },
|
|
h('h3', {}, label), markedImage(h('img', { class: 'bigimg', src, alt: label }), marks),
|
|
h('div', { class: 'row' }, btn('Close', () => dlg.close(), 'primary')));
|
|
dlg.addEventListener('close', () => dlg.remove());
|
|
document.body.append(dlg);
|
|
dlg.showModal();
|
|
}
|
|
|
|
// ---------- read-only view ----------
|
|
function statusBadge(status) {
|
|
return status === 'tbd' ? h('span', { class: 'badge tbd nosearch' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done nosearch' }, 'Done') : null;
|
|
}
|
|
|
|
function viewImageField(f) {
|
|
const hidden = f.secret && !state.revealed.has(f);
|
|
const toggle = () => { state.revealed[hidden ? 'add' : 'delete'](f); render(); };
|
|
let value;
|
|
if (!f.value) value = h('span', { class: 'muted' }, '(no image)');
|
|
else if (hidden) value = h('span', {}, h('span', { class: 'secret' }, '(hidden image)'), btn('Show', toggle, 'link', { 'aria-label': 'Show ' + f.label }));
|
|
else value = h('span', {},
|
|
h('img', { class: 'fimg', src: f.value, alt: f.label, tabIndex: 0, title: 'Click to enlarge',
|
|
onclick: () => openLightbox(f.label, f.value), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(f.label, f.value); } }),
|
|
f.secret ? btn('Hide', toggle, 'link', { 'aria-label': 'Hide ' + f.label }) : null);
|
|
return [h('dt', {}, f.label), h('dd', {}, value)];
|
|
}
|
|
|
|
function viewField(f) {
|
|
if (f.kind === 'image') return viewImageField(f);
|
|
let value;
|
|
if (f.secret) {
|
|
const shown = state.revealed.has(f);
|
|
const span = h('span', { class: 'secret' }, !f.value ? '(not set)' : shown ? f.value : '••••••••');
|
|
value = h('span', {}, span, f.value && btn(shown ? 'Hide' : 'Show', () => {
|
|
state.revealed[shown ? 'delete' : 'add'](f);
|
|
render();
|
|
}, 'link', { 'aria-label': (shown ? 'Hide ' : 'Show ') + f.label }));
|
|
} else {
|
|
value = f.value || h('span', { class: 'muted' }, '(blank)');
|
|
}
|
|
return [h('dt', {}, f.label), h('dd', {}, value)];
|
|
}
|
|
|
|
const currentTab = (s) => validTab(s, state.tabs[s.id]);
|
|
const sameTab = (s) => { const t = currentTab(s); return (e) => entryTab(s, e) === t; };
|
|
|
|
// The row of sub-tab buttons (nothing when the section has no sub-tabs).
|
|
function tabBar(s) {
|
|
const tabs = tabsOf(s);
|
|
if (!tabs.length) return null;
|
|
const cur = currentTab(s);
|
|
return h('div', { class: 'tabs', role: 'tablist', 'aria-label': s.title + ' sub-tabs' }, tabs.map((t) => h('button',
|
|
{ type: 'button', role: 'tab', class: 'tab' + (t.id === cur ? ' on' : ''), 'aria-selected': String(t.id === cur),
|
|
onclick: () => { state.tabs[s.id] = t.id; render(); } },
|
|
t.title, ' ', h('span', { class: 'muted small' }, '(' + entriesInTab(s, t.id).length + ')'))));
|
|
}
|
|
|
|
function viewRecord(s, r, i) {
|
|
const arr = s.records;
|
|
const same = sameTab(s);
|
|
const closed = !state.searchAll && state.collapsed.has(r.id);
|
|
const toggle = () => { state.collapsed[closed ? 'delete' : 'add'](r.id); render(); };
|
|
const shift = (dir) => { moveWithin(arr, i, dir, same); changed(r); render(); };
|
|
return h('article', { class: 'card' + (closed ? ' collapsed' : ''), 'data-eid': r.id },
|
|
h('div', { class: 'rechead' },
|
|
h('h3', {}, r.title, ' ', statusBadge(r.status)),
|
|
h('span', { class: 'tools' },
|
|
closed && siblingIndex(arr, i, -1, same) >= 0 ? btn('↑', () => shift(-1), 'icon', { 'aria-label': 'Move ' + r.title + ' up' }) : null,
|
|
closed && siblingIndex(arr, i, 1, same) >= 0 ? btn('↓', () => shift(1), 'icon', { 'aria-label': 'Move ' + r.title + ' down' }) : null,
|
|
btn(closed ? 'Expand' : 'Collapse', toggle, 'small', { 'aria-expanded': String(!closed), 'aria-label': (closed ? 'Expand ' : 'Collapse ') + r.title }))),
|
|
closed ? null : [
|
|
r.fields.length ? h('dl', {}, r.fields.map(viewField)) : null,
|
|
r.notes ? h('p', { class: 'notes' }, r.notes) : null,
|
|
h('p', { class: 'muted small nosearch' }, 'Updated ' + r.updated)]);
|
|
}
|
|
|
|
function foldBar(entries) {
|
|
const recs = entries.filter((r) => !isSequence(r));
|
|
if (!recs.length) return null;
|
|
const setAll = (fold) => { recs.forEach((r) => state.collapsed[fold ? 'add' : 'delete'](r.id)); render(); };
|
|
return h('div', { class: 'row foldbar' },
|
|
btn('Collapse all', () => setAll(true), 'small'), btn('Expand all', () => setAll(false), 'small'));
|
|
}
|
|
|
|
// A frame is hidden (picture and text) if marked secret and not revealed.
|
|
function viewFrame(q, f, k) {
|
|
const hidden = f.secret && !state.revealed.has(f);
|
|
const toggle = () => { state.revealed[hidden ? 'add' : 'delete'](f); render(); };
|
|
const label = q.title + ', step ' + (k + 1);
|
|
const layout = hidden ? 'none' : frameLayout(f);
|
|
return h('div', { class: 'frame ' + layout },
|
|
h('div', { class: 'fnum nosearch' }, 'Step ' + (k + 1)),
|
|
hidden ? h('div', {}, h('span', { class: 'secret' }, '(hidden step)'), btn('Show', toggle, 'link', { 'aria-label': 'Show ' + label })) : [
|
|
f.image ? markedImage(h('img', { class: 'fimg', src: f.image, alt: label, tabIndex: 0, title: 'Click to enlarge',
|
|
onclick: () => openLightbox(label, f.image, f.marks), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(label, f.image, f.marks); } }), f.marks)
|
|
: h('span', { class: 'muted' }, '(no image)'),
|
|
layout !== 'none' ? h('p', { class: 'ftext' }, f.text) : null,
|
|
viewUses(f),
|
|
f.stop || String(f.ifStuck || '').trim() ? h('div', { class: 'fnotes' },
|
|
f.stop ? h('p', { class: 'fstop' }, h('strong', {}, 'Stop here. Do not go further.')) : null,
|
|
String(f.ifStuck || '').trim() ? h('p', { class: 'fstuck' }, h('strong', {}, 'If it looks different or fails: '), f.ifStuck) : null) : null,
|
|
f.secret ? btn('Hide', toggle, 'link', { 'aria-label': 'Hide ' + label }) : null]);
|
|
}
|
|
|
|
// The credentials a step needs, live from their records: secrets stay masked until shown.
|
|
function viewUses(f) {
|
|
if (!f.uses || !f.uses.length) return null;
|
|
return h('div', { class: 'fuses nosearch' }, h('strong', {}, 'You will need:'), f.uses.map((u) => {
|
|
const hit = findFieldRef(state.doc, u);
|
|
if (!hit) return h('p', { class: 'muted' }, '(a credential this step used has been removed)');
|
|
const fld = hit.field;
|
|
const shown = !fld.secret || state.revealed.has(fld);
|
|
const toggle = () => { state.revealed[shown ? 'delete' : 'add'](fld); render(); };
|
|
return h('div', { class: 'row fuse' },
|
|
h('span', {}, hit.record.title + ' \u203A ' + fld.label + ': '),
|
|
h('span', { class: fld.secret ? 'secret' : '' }, !fld.value ? '(not set)' : shown ? fld.value : '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022'),
|
|
fld.secret ? btn(shown ? 'Hide' : 'Show', toggle, 'link', { 'aria-label': (shown ? 'Hide ' : 'Show ') + fld.label }) : null,
|
|
fld.value ? btn('Copy', () => copyValue(fld), 'small', { 'aria-label': 'Copy ' + fld.label }) : null);
|
|
}));
|
|
}
|
|
|
|
const capturedNote = (q) => (q.captured ? ' Captured ' + q.captured + '. The site may have changed since.' : '');
|
|
|
|
// One step at a time, with Back/Next. A secret step stays hidden until shown, as in the list.
|
|
function walkSequence(q) {
|
|
const n = q.frames.length;
|
|
const k = Math.max(0, Math.min(state.walk.k, n - 1));
|
|
const go = (to) => () => { state.walk = { id: q.id, k: to }; render(); };
|
|
return h('article', { class: 'card seq walk', 'data-seq': q.id, 'data-eid': q.id },
|
|
h('h3', {}, q.title),
|
|
viewFrame(q, q.frames[k], k),
|
|
h('div', { class: 'row walknav nosearch' },
|
|
btn('\u2190 Back', go(k - 1), '', { disabled: k === 0 }),
|
|
h('span', { class: 'muted', role: 'status' }, 'Step ' + (k + 1) + ' of ' + n),
|
|
btn('Next \u2192', go(k + 1), 'primary', { disabled: k === n - 1 }),
|
|
btn('Show all steps', () => { state.walk = null; render(); }, 'link')),
|
|
h('p', { class: 'muted small nosearch' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
|
|
}
|
|
|
|
function viewSequence(q) {
|
|
if (!state.searchAll && state.walk && state.walk.id === q.id && q.frames.length) return walkSequence(q);
|
|
return h('article', { class: 'card seq', 'data-eid': q.id },
|
|
h('h3', {}, q.title),
|
|
q.frames.length ? btn('Walk through, one step at a time', () => { state.walk = { id: q.id, k: 0 }; render(); }, 'small') : null,
|
|
q.frames.length ? h('div', { class: 'frames' }, q.frames.map((f, k) => viewFrame(q, f, k))) : h('p', { class: 'muted nosearch' }, '(no steps yet)'),
|
|
h('p', { class: 'muted small nosearch' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
|
|
}
|
|
const seqItem = (q) => h('li', { class: 'seqitem' }, viewSequence(q));
|
|
|
|
function viewItem(it, ordered) {
|
|
return h('li', { class: 'item ' + it.status, 'data-eid': it.id },
|
|
h('div', {}, h('strong', {}, it.text), ' ', statusBadge(it.status)),
|
|
it.detail ? h('p', { class: 'notes' }, it.detail) : null);
|
|
}
|
|
|
|
function viewRecords(s) {
|
|
const entries = state.searchAll ? s.records.map((e, i) => ({ e, i })) : entriesInTab(s, currentTab(s));
|
|
return [state.searchAll ? null : tabBar(s),
|
|
hasTabs(s) && !entries.length ? h('p', { class: 'muted nosearch' }, 'Nothing in this sub-tab yet. Choose Edit to add or move records here.') : null,
|
|
state.searchAll ? null : foldBar(entries.map((x) => x.e)),
|
|
entries.map(({ e, i }) => (isSequence(e) ? viewSequence(e) : viewRecord(s, e, i)))];
|
|
}
|
|
|
|
function viewSection(s) {
|
|
return [
|
|
s.intro ? h('p', { class: 'intro' }, s.intro) : null,
|
|
s.kind === 'text' ? [h('p', { class: 'body' }, s.body), (s.sequences || []).map(viewSequence)] : null,
|
|
s.kind === 'records' ? viewRecords(s) : null,
|
|
s.kind === 'steps' ? h('ol', { class: 'items' }, s.items.map((i) => (isSequence(i) ? seqItem(i) : viewItem(i)))) : null,
|
|
s.kind === 'checklist' ? h('ul', { class: 'items' }, s.items.map((i) => (isSequence(i) ? seqItem(i) : viewItem(i)))) : null,
|
|
];
|
|
}
|
|
|
|
// ---------- edit mode ----------
|
|
function input(obj, key, opts = {}, record) {
|
|
const tag = opts.multiline ? 'textarea' : 'input';
|
|
const el = h(tag, { value: obj[key] ?? '', 'aria-label': opts.label || key, rows: opts.multiline ? 3 : undefined,
|
|
oninput: () => { obj[key] = el.value; changed(record); } });
|
|
return el;
|
|
}
|
|
function select(obj, key, values, label, record) {
|
|
const el = h('select', { 'aria-label': label, onchange: () => { obj[key] = el.value; changed(record); } },
|
|
values.map((v) => h('option', { value: v, selected: obj[key] === v }, v)));
|
|
return el;
|
|
}
|
|
// Up / down / delete controls for element i of arr.
|
|
// `message` (string or function) replaces the default delete confirmation.
|
|
// `same` (optional) limits up/down to elements it accepts, e.g. the ones in the same sub-tab.
|
|
function rowTools(arr, i, what, record, quiet = false, message = null, same = () => true) {
|
|
const note = () => (quiet ? markDirty() : changed(record));
|
|
const act = (fn) => () => { fn(); note(); render(); };
|
|
return h('span', { class: 'tools' },
|
|
btn('↑', act(() => moveWithin(arr, i, -1, same)), 'icon', { 'aria-label': 'Move ' + what + ' up', disabled: siblingIndex(arr, i, -1, same) < 0 }),
|
|
btn('↓', act(() => moveWithin(arr, i, 1, same)), 'icon', { 'aria-label': 'Move ' + what + ' down', disabled: siblingIndex(arr, i, 1, same) < 0 }),
|
|
btn('✕', () => { if (confirm(typeof message === 'function' ? message() : message || 'Delete this ' + what + '?')) { removeAt(arr, i); note(); render(); } }, 'icon danger', { 'aria-label': 'Delete ' + what }));
|
|
}
|
|
|
|
// The drop / paste / choose-a-file box for the picture stored at obj[key].
|
|
// onFiles(files) receives the dropped or chosen files; onChange() runs after Remove.
|
|
function imageZone(obj, key, label, attrs, onFiles, onChange) {
|
|
const picker = h('input', { type: 'file', accept: 'image/png,image/jpeg', hidden: true, 'aria-label': 'Choose an image file',
|
|
onchange: () => { onFiles([...picker.files]); picker.value = ''; } });
|
|
const zone = h('div', Object.assign({ class: 'dropzone', tabIndex: 0, 'aria-label': 'Image for ' + label + ': drop, paste or choose a file',
|
|
ondragover: (e) => { if (hasFiles(e)) { e.preventDefault(); zone.classList.add('over'); } },
|
|
ondragleave: () => zone.classList.remove('over'),
|
|
ondrop: (e) => { e.preventDefault(); e.stopPropagation(); zone.classList.remove('over'); onFiles([...e.dataTransfer.files]); } }, attrs),
|
|
obj[key] ? markedImage(h('img', { class: 'fimg', src: obj[key], alt: label }), key === 'image' ? obj.marks : null) : null,
|
|
h('p', { class: 'muted small' }, obj[key]
|
|
? formatBytes(dataUrlBytes(obj[key])) + '. Drop, paste or choose a file to replace it.'
|
|
: 'Drop an image here, paste one while this box is selected, or choose a file.'),
|
|
h('div', { class: 'row' },
|
|
btn('Choose file\u2026', () => picker.click(), 'small'),
|
|
obj[key] ? btn('Remove image', () => { obj[key] = ''; onChange(); render(); }, 'small') : null),
|
|
picker);
|
|
return zone;
|
|
}
|
|
|
|
// Normal / Lawyer / Secret chooser for a field or step (replaces the old "secret" checkbox).
|
|
const LEVELS = [['normal', 'Normal'], ['lawyer', 'Lawyer'], ['secret', 'Secret']];
|
|
function levelSelect(x, label, onChange) {
|
|
const sel = h('select', { 'aria-label': label, onchange: () => { setLevel(x, sel.value); onChange(); } },
|
|
LEVELS.map(([v, t]) => h('option', { value: v, selected: levelOf(x) === v }, t)));
|
|
return h('label', { class: 'check' }, sel);
|
|
}
|
|
|
|
function editImageField(r, f, i) {
|
|
const secret = levelSelect(f, 'Visibility of ' + (f.label || 'image field'), () => changed(r));
|
|
const zone = imageZone(f, 'value', f.label, { 'data-field': String(i) }, (files) => importFiles(r, files, { replace: f }), () => changed(r));
|
|
return h('div', { class: 'field imagefield' },
|
|
h('div', { class: 'row' }, input(f, 'label', { label: 'Field label' }, r), secret, rowTools(r.fields, i, 'image field', r)),
|
|
zone);
|
|
}
|
|
|
|
function editField(r, f, i) {
|
|
if (f.kind === 'image') return editImageField(r, f, i);
|
|
const secret = levelSelect(f, 'Visibility of ' + (f.label || 'field'), () => changed(r));
|
|
return h('div', { class: 'row field' },
|
|
input(f, 'label', { label: 'Field label' }, r), input(f, 'value', { label: 'Field value' }, r),
|
|
secret, rowTools(r.fields, i, 'field', r));
|
|
}
|
|
|
|
// "Sub-tab: [select]" for a record or sequence; changing it moves the entry to that tab.
|
|
function moveToRow(s, e) {
|
|
if (!hasTabs(s)) return null;
|
|
const sel = h('select', { 'aria-label': 'Sub-tab of ' + e.title, onchange: () => {
|
|
const t = tabsOf(s).find((x) => x.id === sel.value);
|
|
moveToTab(s, e, sel.value); changed(e);
|
|
render(); setStatus('Moved "' + e.title + '" to ' + t.title + '.');
|
|
} }, tabsOf(s).map((t) => h('option', { value: t.id, selected: t.id === entryTab(s, e) }, t.title)));
|
|
return h('div', { class: 'row' }, h('label', { class: 'check' }, 'Sub-tab ', sel));
|
|
}
|
|
|
|
// Add, rename, reorder and delete the sub-tabs of a records section.
|
|
function tabPanel(s) {
|
|
const cur = currentTab(s);
|
|
const name = h('input', { placeholder: 'New sub-tab name (e.g. Online)', 'aria-label': 'New sub-tab name',
|
|
onkeydown: (e) => { if (e.key === 'Enter') { e.preventDefault(); add(); } } });
|
|
const add = () => {
|
|
if (!name.value.trim()) return name.focus();
|
|
state.tabs[s.id] = addSubsection(state.doc, s, name.value).id;
|
|
markDirty(); render();
|
|
};
|
|
let manage = null;
|
|
if (hasTabs(s)) {
|
|
const tab = tabsOf(s).find((t) => t.id === cur);
|
|
const idx = s.subsections.findIndex((t) => t.id === cur);
|
|
const rename = h('input', { value: tab.title, 'aria-label': 'Name of the selected sub-tab',
|
|
onchange: () => { if (renameTab(s, cur, rename.value)) { changed(); render(); } else rename.value = tab.title; } });
|
|
const shift = (dir) => () => { moveSubsection(s, cur, dir); changed(); render(); };
|
|
manage = h('div', { class: 'row' }, rename, cur ? h('span', { class: 'tools' },
|
|
btn('←', shift(-1), 'icon', { 'aria-label': 'Move sub-tab left', disabled: idx <= 0 }),
|
|
btn('→', shift(1), 'icon', { 'aria-label': 'Move sub-tab right', disabled: idx >= s.subsections.length - 1 }),
|
|
btn('✕', () => {
|
|
if (!confirm(deleteSubsectionMessage(s, cur))) return;
|
|
removeSubsection(s, cur); state.tabs[s.id] = ''; changed(); render();
|
|
}, 'icon danger', { 'aria-label': 'Delete sub-tab' })) : h('span', { class: 'muted small' }, 'Catch-all for records not placed in a sub-tab'));
|
|
}
|
|
return h('div', { class: 'card editing' },
|
|
h('strong', {}, 'Sub-tabs'),
|
|
h('div', { class: 'row' }, name, btn('+ Add sub-tab', add, 'small')),
|
|
manage);
|
|
}
|
|
|
|
function editRecord(s, r, i) {
|
|
const picker = h('input', { type: 'file', multiple: true, accept: 'image/png,image/jpeg', hidden: true, 'aria-label': 'Choose images to add',
|
|
onchange: () => { importFiles(r, [...picker.files]); picker.value = ''; } });
|
|
return h('article', { class: 'card editing', 'data-rec': r.id,
|
|
ondragover: (e) => { if (hasFiles(e)) e.preventDefault(); },
|
|
ondrop: (e) => { e.preventDefault(); importFiles(r, [...e.dataTransfer.files]); } },
|
|
h('div', { class: 'row' }, input(r, 'title', { label: 'Record title' }, r), select(r, 'status', ['ok', 'tbd'], 'Record status', r), rowTools(s.records, i, 'record', undefined, false, null, sameTab(s))),
|
|
moveToRow(s, r),
|
|
r.fields.map((f, k) => editField(r, f, k)),
|
|
h('div', { class: 'row' },
|
|
btn('+ Add field', () => { addField(r); changed(r); render(); }, 'small'),
|
|
btn('+ Add image\u2026', () => picker.click(), 'small'), picker),
|
|
h('label', {}, 'Notes', input(r, 'notes', { multiline: true, label: 'Notes' }, r)));
|
|
}
|
|
|
|
const LAYOUT_LABELS = [['right', 'Text right of image'], ['under', 'Text under image'], ['none', 'No text']];
|
|
|
|
// Pick the record fields this step needs; the reader sees them beside the step.
|
|
function useEditor(q, f, k) {
|
|
const recs = allRecords().filter((r) => r.fields.some((x) => x.kind !== 'image'));
|
|
const pick = h('select', { 'aria-label': 'Add a credential to step ' + (k + 1), onchange: () => {
|
|
if (!pick.value) return;
|
|
const [rid, idx] = pick.value.split('|');
|
|
const rec = recs.find((r) => r.id === rid);
|
|
if (rec && addUse(f, rec, rec.fields[Number(idx)])) { changed(q); render(); }
|
|
} },
|
|
h('option', { value: '' }, '+ Use a field from a record\u2026'),
|
|
recs.map((r) => h('optgroup', { label: r.title }, r.fields.map((x, i) => (x.kind === 'image' ? null
|
|
: h('option', { value: r.id + '|' + i }, x.label + (x.secret ? ' (secret)' : '')))))));
|
|
return h('div', {},
|
|
h('strong', {}, 'Credentials this step needs'),
|
|
(f.uses || []).map((u, i) => {
|
|
const hit = findFieldRef(state.doc, u);
|
|
return h('div', { class: 'row' },
|
|
h('span', {}, hit ? hit.record.title + ' \u203A ' + hit.field.label : '(removed)'),
|
|
btn('\u2715', () => { removeUse(f, i); changed(q); render(); }, 'icon danger', { 'aria-label': 'Remove credential from step ' + (k + 1) }));
|
|
}),
|
|
pick);
|
|
}
|
|
|
|
function editFrame(q, f, k) {
|
|
const secret = levelSelect(f, 'Visibility of step ' + (k + 1), () => changed(q));
|
|
const stop = h('input', { type: 'checkbox', checked: !!f.stop, 'aria-label': 'Stop here, step ' + (k + 1),
|
|
onchange: () => { f.stop = stop.checked || undefined; if (!f.stop) delete f.stop; changed(q); } });
|
|
const layout = h('select', { 'aria-label': 'Text position for step ' + (k + 1), onchange: () => { f.layout = layout.value; changed(q); render(); } },
|
|
LAYOUT_LABELS.map(([v, t]) => h('option', { value: v, selected: f.layout === v }, t)));
|
|
return h('div', { class: 'field imagefield frameedit' },
|
|
h('div', { class: 'row' }, h('strong', {}, 'Step ' + (k + 1)), layout, secret, rowTools(q.frames, k, 'step', q)),
|
|
imageZone(f, 'image', q.title + ', step ' + (k + 1), { 'data-frame': String(k) },
|
|
(files) => importFiles(q, files, { key: 'image', replace: f, add: addFrameFrom(q) }), () => { if (!f.image) delete f.marks; changed(q); }),
|
|
f.image ? h('div', { class: 'row' }, btn('Mark up picture\u2026', () => openAnnotator(q, f), 'small', { 'aria-label': 'Mark up the picture for step ' + (k + 1) }),
|
|
f.marks && f.marks.length ? h('span', { class: 'muted small' }, f.marks.length + (f.marks.length === 1 ? ' marker or box' : ' markers and boxes')) : null) : null,
|
|
f.layout === 'none' ? null : h('label', {}, 'Text', input(f, 'text', { multiline: true, label: 'Text for step ' + (k + 1) }, q)),
|
|
useEditor(q, f, k),
|
|
h('label', {}, 'If it looks different or fails', input(f, 'ifStuck', { multiline: true, label: 'If step ' + (k + 1) + ' looks different or fails' }, q)),
|
|
h('label', { class: 'check' }, stop, ' Stop here: the reader must not go further without help'));
|
|
}
|
|
|
|
function editSequence(list, q, i, s) {
|
|
const picker = h('input', { type: 'file', multiple: true, accept: 'image/png,image/jpeg', hidden: true, 'aria-label': 'Choose images for new steps',
|
|
onchange: () => { importFiles(q, [...picker.files], { add: addFrameFrom(q) }); picker.value = ''; } });
|
|
return h('article', { class: 'card editing seq', 'data-seq': q.id,
|
|
ondragover: (e) => { if (hasFiles(e)) e.preventDefault(); },
|
|
ondrop: (e) => { e.preventDefault(); importFiles(q, [...e.dataTransfer.files], { add: addFrameFrom(q) }); } },
|
|
h('div', { class: 'row' }, input(q, 'title', { label: 'Visual sequence title' }, q), rowTools(list, i, 'visual sequence', q, false, null, s ? sameTab(s) : undefined)),
|
|
s ? moveToRow(s, q) : null,
|
|
q.frames.map((f, k) => editFrame(q, f, k)),
|
|
h('div', { class: 'row' },
|
|
btn('+ Add step', () => { addFrame(q); changed(q); render(); }, 'small'),
|
|
btn('+ Add images\u2026', () => picker.click(), 'small'), picker,
|
|
capture && capture.seqId === q.id
|
|
? [btn('Capture step', () => captureStep(q), 'primary small'), btn('Stop sharing', () => { endCapture(); setStatus('Stopped sharing.'); render(); }, 'small')]
|
|
: btn('Capture from screen\u2026', () => beginCapture(q), 'small', { title: 'Share the window with the site, then capture each screen you want as a step' })));
|
|
}
|
|
const addSeqBtn = (s) => btn('+ Add visual sequence', () => { addSequence(state.doc, s, s.kind === 'records' ? currentTab(s) : ''); markDirty(); render(); }, 'primary');
|
|
|
|
function editItem(s, it, i) {
|
|
return h('li', { class: 'card editing' },
|
|
h('div', { class: 'row' }, input(it, 'text', { label: 'Item text' }), select(it, 'status', ['open', 'done', 'tbd'], 'Item status'), rowTools(s.items, i, 'item')),
|
|
h('label', {}, 'Detail', input(it, 'detail', { multiline: true, label: 'Detail' })));
|
|
}
|
|
|
|
function editSection(s) {
|
|
const secIdx = state.doc.sections.indexOf(s);
|
|
return [
|
|
h('div', { class: 'card editing' },
|
|
h('div', { class: 'row' }, input(s, 'title', { label: 'Section title' }), rowTools(state.doc.sections, secIdx, 'section', undefined, false, () => deleteSectionMessage(s))),
|
|
h('label', {}, 'Intro', input(s, 'intro', { multiline: true, label: 'Section intro' }))),
|
|
s.kind === 'text' ? [h('label', {}, 'Text', input(s, 'body', { multiline: true, label: 'Body' })),
|
|
(s.sequences || []).map((q, i) => editSequence(s.sequences, q, i)), h('div', { class: 'row' }, addSeqBtn(s))] : null,
|
|
s.kind === 'records' ? [tabPanel(s), tabBar(s),
|
|
entriesInTab(s, currentTab(s)).map(({ e, i }) => (isSequence(e) ? editSequence(s.records, e, i, s) : editRecord(s, e, i))),
|
|
h('div', { class: 'row' }, btn('+ Add record', () => { addRecord(state.doc, s, currentTab(s)); markDirty(); render(); }, 'primary'), addSeqBtn(s))] : null,
|
|
s.kind === 'steps' || s.kind === 'checklist' ? [h('ol', { class: 'items' }, s.items.map((it, i) => (isSequence(it)
|
|
? h('li', { class: 'seqitem' }, editSequence(s.items, it, i)) : editItem(s, it, i)))),
|
|
h('div', { class: 'row' }, btn('+ Add item', () => { addItem(state.doc, s); markDirty(); render(); }, 'primary'), addSeqBtn(s))] : null,
|
|
];
|
|
}
|
|
|
|
// ---------- print header ----------
|
|
const HEADER_ID = '__header';
|
|
|
|
// The running header line, laid out left | unaligned... | right.
|
|
function headerEl(doc) {
|
|
const L = headerLayout(doc);
|
|
return h('div', { class: 'phead' },
|
|
L.left ? h('span', { class: 'ph-left' }, L.left) : null,
|
|
h('span', { class: 'ph-mid' }, L.middle.map((t) => h('span', {}, t))),
|
|
L.right ? h('span', { class: 'ph-right' }, L.right) : null);
|
|
}
|
|
|
|
function headerPanel() {
|
|
const doc = state.doc;
|
|
const preview = h('div', { class: 'card hpreview', 'aria-label': 'Header preview' });
|
|
const refresh = () => preview.replaceChildren(headerEl(doc));
|
|
refresh();
|
|
const intro = h('p', { class: 'intro' }, 'This line is printed at the top of every page. Left-aligned text comes first, unaligned fields sit in the middle, and the right-aligned field comes last. Only one field can be left aligned and one right aligned.');
|
|
if (!state.editing) return [intro, preview, h('p', { class: 'muted' }, 'Choose Edit to change it.')];
|
|
|
|
const fields = ensureHeader(doc).fields;
|
|
return [intro, preview,
|
|
fields.map((f, i) => {
|
|
const taken = takenAligns(fields, f);
|
|
const kind = h('select', { 'aria-label': 'Field type', onchange: () => { f.kind = kind.value; markDirty(); render(); } },
|
|
[['text', 'Text'], ['lastUpdated', 'Last updated']].map(([v, l]) => h('option', { value: v, selected: f.kind === v }, l)));
|
|
const text = h('input', { value: f.text, 'aria-label': f.kind === 'lastUpdated' ? 'Label before the date' : 'Header text',
|
|
placeholder: f.kind === 'lastUpdated' ? 'Label before the date (optional)' : 'Text',
|
|
oninput: () => { f.text = text.value; markDirty(); refresh(); } });
|
|
const align = h('select', { 'aria-label': 'Alignment', onchange: () => {
|
|
if (!setAlign(fields, f, align.value)) return;
|
|
markDirty(); render();
|
|
} }, [['', 'Not aligned'], ['left', 'Left'], ['right', 'Right']].map(([v, l]) =>
|
|
h('option', { value: v, selected: (f.align || '') === v, disabled: !!v && taken.has(v) }, l + (v && taken.has(v) ? ' (in use)' : ''))));
|
|
return h('div', { class: 'card editing' }, h('div', { class: 'row' }, kind, text, align, rowTools(fields, i, 'header field', null, true)));
|
|
}),
|
|
h('div', { class: 'row' },
|
|
btn('+ Add field', () => { addHeaderField(doc); markDirty(); render(); }, 'primary'),
|
|
btn('Reset to default', () => { delete doc.header; markDirty(); render(); }, 'small'))];
|
|
}
|
|
|
|
// ---------- print ----------
|
|
const printRoot = document.getElementById('printdoc');
|
|
const box = (status) => h('span', { class: 'cb ' + status, 'aria-hidden': 'true' }, status === 'done' ? '✓' : '');
|
|
|
|
// Text, or the picture itself for a visible image field.
|
|
function printCell(f, mode) {
|
|
if (f.kind === 'image' && f.value && !isHidden(f, mode)) return h('img', { class: 'pimg', src: f.value, alt: f.label });
|
|
return displayValue(f, mode);
|
|
}
|
|
|
|
function printFrame(f, k, mode) {
|
|
const v = frameView(f, mode);
|
|
return h('div', { class: 'pframe ' + v.layout },
|
|
h('div', { class: 'pfnum' }, 'Step ' + (k + 1)),
|
|
v.withheld ? h('p', { class: 'psecret' }, '[withheld]')
|
|
: v.image ? markedImage(h('img', { class: 'pimg', src: v.image, alt: 'Step ' + (k + 1) }), f.marks)
|
|
: h('p', {}, '(no image)'),
|
|
v.layout !== 'none' ? h('p', { class: 'pftext' }, v.text) : null,
|
|
v.withheld ? null : usesView(state.doc, f, mode).map((u) => h('p', { class: 'pftext' },
|
|
u.missing ? '(a credential this step used has been removed)' : 'You will need: ' + u.record + ' \u203A ' + u.label + ': ' + u.value)),
|
|
v.stop ? h('p', { class: 'pstop' }, h('strong', {}, 'STOP HERE. Do not go further.')) : null,
|
|
v.ifStuck ? h('p', { class: 'pftext' }, h('strong', {}, 'If it looks different or fails: '), v.ifStuck) : null);
|
|
}
|
|
|
|
function printSequence(q, mode) {
|
|
return h('div', { class: 'pseq' },
|
|
h('h3', {}, q.title),
|
|
q.captured ? h('p', { class: 'pftext' }, 'Captured ' + q.captured + '. The site may have changed since.') : null,
|
|
q.frames.map((f, k) => printFrame(f, k, mode)));
|
|
}
|
|
|
|
function printRecord(r, mode) {
|
|
return h('div', { class: 'prec' + (r.status === 'tbd' ? ' tbd' : '') },
|
|
h('h3', {}, r.title, r.status === 'tbd' ? h('span', { class: 'ptag' }, 'TBD') : null),
|
|
r.fields.length ? h('table', {}, h('tbody', {}, r.fields.map((f) => h('tr', {},
|
|
h('th', {}, f.label), h('td', { class: f.secret ? 'psecret' : '' }, printCell(f, mode)))))) : null,
|
|
r.notes ? h('p', { class: 'pnotes' }, r.notes) : null);
|
|
}
|
|
|
|
// The lawyer's summary: just the records with lawyer-level fields, as one compact list.
|
|
function printSummary(doc) {
|
|
const groups = summaryGroups(doc);
|
|
const list = groups.length ? groups.map((s) => h('section', { class: 'psumsec' },
|
|
h('h2', {}, s.section),
|
|
s.groups.map((g) => [g.title == null ? null : h('h3', { class: 'psubhead' }, g.title),
|
|
g.records.map((r) => h('div', { class: 'prec' }, h('h3', {}, r.title),
|
|
h('table', {}, h('tbody', {}, r.fields.map((f) => h('tr', {}, h('th', {}, f.label), h('td', { class: 'psecret' }, f.value || '(not set)')))))))])))
|
|
: h('p', {}, 'Nothing to list: no record has a lawyer-level field.');
|
|
printRoot.replaceChildren(h('table', { class: 'ptable' },
|
|
h('thead', {}, h('tr', {}, h('td', {}, headerEl(doc)))),
|
|
h('tbody', {}, h('tr', {}, h('td', {},
|
|
h('section', { class: 'pcover psumcover' },
|
|
h('h1', {}, (doc.meta.title || 'Final Wishes') + ": lawyer's summary"),
|
|
doc.meta.owner ? h('p', { class: 'powner' }, 'Prepared by ' + doc.meta.owner) : null,
|
|
h('p', {}, 'Last update: ' + doc.meta.lastUpdated),
|
|
h('p', { class: 'pnote warn' }, "This is the LAWYER'S SUMMARY. It lists only the accounts and details a lawyer needs, in clear text. Keep it locked away.")),
|
|
list)))));
|
|
}
|
|
|
|
function printItem(it, numbered) {
|
|
return h('li', { class: 'pitem ' + it.status },
|
|
box(it.status), h('strong', {}, it.text), it.status === 'tbd' ? h('span', { class: 'ptag' }, 'TBD') : null,
|
|
it.detail ? h('p', { class: 'pnotes' }, it.detail) : null);
|
|
}
|
|
|
|
function buildPrintDoc(rawMode) {
|
|
const mode = normalizeMode(rawMode);
|
|
if (mode === 'summary') return printSummary(state.doc);
|
|
const doc = state.doc;
|
|
const kept = mode === 'complete' ? 'This copy INCLUDES passwords, PINs and other secrets. Keep it locked away (fire safe or sealed envelope).'
|
|
: mode === 'obscured' ? 'This is the MASKED copy. Secrets are shown, but every digit in them is replaced by \u2022. Pictures marked secret are withheld. Keep it locked away.'
|
|
: mode === 'lawyer' ? "This is the LAWYER'S VIEW. It includes account numbers and other details a lawyer needs, but the most private secrets (passwords, PINs, balances) are WITHHELD. Keep it locked away."
|
|
: 'Secrets (passwords, PINs, security answers) are WITHHELD from this copy. They are stored in the encrypted file.';
|
|
const content = [
|
|
h('section', { class: 'pcover' },
|
|
h('h1', {}, doc.meta.title || 'Final Wishes'),
|
|
doc.meta.owner ? h('p', { class: 'powner' }, 'Prepared by ' + doc.meta.owner) : null,
|
|
h('p', {}, 'Last update: ' + doc.meta.lastUpdated),
|
|
h('p', { class: 'pnote' + (mode !== 'masked' ? ' warn' : '') }, kept),
|
|
h('p', {}, 'Items marked TBD are not yet filled in. A box beside an instruction is for ticking it off as it is done.'),
|
|
h('h2', {}, 'Contents'),
|
|
h('ol', { class: 'ptoc' }, doc.sections.map((s) => h('li', {}, s.title)))),
|
|
doc.sections.map((s) => h('section', { class: 'psec' },
|
|
h('h2', {}, s.title),
|
|
s.intro ? h('p', { class: 'pintro' }, s.intro) : null,
|
|
s.kind === 'text' ? [h('p', { class: 'pbody' }, s.body), (s.sequences || []).map((q) => printSequence(q, mode))] : null,
|
|
s.kind === 'records' ? printGroups(s).map((g) => [g.title == null ? null : h('h3', { class: 'psubhead' }, g.title),
|
|
g.entries.map((r) => (isSequence(r) ? printSequence(r, mode) : printRecord(r, mode)))]) : null,
|
|
s.kind === 'steps' ? h('ol', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, mode)) : printItem(i)))) : null,
|
|
s.kind === 'checklist' ? h('ul', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, mode)) : printItem(i)))) : null)),
|
|
].flat();
|
|
// The header sits in <thead> so the browser repeats it, in flow, at the top of every page.
|
|
printRoot.replaceChildren(h('table', { class: 'ptable' },
|
|
h('thead', {}, h('tr', {}, h('td', {}, headerEl(doc)))),
|
|
h('tbody', {}, h('tr', {}, h('td', {}, content)))));
|
|
}
|
|
window.addEventListener('afterprint', () => printRoot.replaceChildren()); // don't leave secrets lingering in the DOM
|
|
|
|
function openPrintDialog() {
|
|
const n = countByLevel(state.doc);
|
|
const sum = summaryCounts(state.doc);
|
|
const plural = (c) => c + ' secret value' + (c === 1 ? '' : 's');
|
|
const radio = (value, checked, text) => h('label', { class: 'radio' }, h('input', { type: 'radio', name: 'mode', value, checked }), ' ' + text);
|
|
const dlg = h('dialog', { class: 'card', 'aria-label': 'Print options' },
|
|
h('h3', {}, 'Print'),
|
|
radio('masked', true, 'Withhold secrets (safe overview; ' + plural(n.lawyer + n.secret) + ' hidden)'),
|
|
radio('lawyer', false, "Lawyer's view (shows " + n.lawyer + ' lawyer-level value' + (n.lawyer === 1 ? '' : 's') + '; ' + plural(n.secret) + ' hidden)'),
|
|
radio('summary', false, "Lawyer's summary (a short list of " + sum.records + ' record' + (sum.records === 1 ? '' : 's') + ' with lawyer-level values, ' + sum.values + ' value' + (sum.values === 1 ? '' : 's') + ')'),
|
|
radio('obscured', false, 'Masked (shows ' + plural(n.lawyer + n.secret) + ' with every number hidden)'),
|
|
radio('complete', false, 'Include secrets (full copy: store it securely)'),
|
|
h('div', { class: 'row' },
|
|
btn('Cancel', () => { dlg.close(); dlg.remove(); }),
|
|
btn('Print', async () => {
|
|
const chosen = dlg.querySelector('input[name=mode]:checked').value;
|
|
dlg.close(); dlg.remove();
|
|
buildPrintDoc(chosen);
|
|
// Pictures must be decoded before the browser lays out the pages.
|
|
await Promise.all([...printRoot.querySelectorAll('img')].map((img) => img.decode().catch(() => {})));
|
|
window.print();
|
|
}, 'primary')));
|
|
document.body.append(dlg);
|
|
dlg.showModal();
|
|
}
|
|
|
|
// ---------- save ----------
|
|
const byId = (id) => document.getElementById(id);
|
|
|
|
function downloadFile(html, name) {
|
|
const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
|
|
const a = h('a', { href: url, download: name });
|
|
document.body.append(a);
|
|
a.click();
|
|
a.remove();
|
|
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
|
}
|
|
|
|
// Resolves to the chosen passphrase, or null if cancelled.
|
|
function askPassphrase(title, intro) {
|
|
return new Promise((resolve) => {
|
|
const p1 = h('input', { type: 'password', autocomplete: 'new-password', 'aria-label': 'New passphrase' });
|
|
const p2 = h('input', { type: 'password', autocomplete: 'new-password', 'aria-label': 'Repeat passphrase' });
|
|
const err = h('p', { class: 'error', role: 'alert' });
|
|
const finish = (v) => { dlg.close(); dlg.remove(); resolve(v); };
|
|
const dlg = h('dialog', { class: 'card', 'aria-label': title },
|
|
h('form', { onsubmit: (e) => {
|
|
e.preventDefault();
|
|
const problem = passphraseProblem(p1.value);
|
|
if (problem) err.textContent = problem;
|
|
else if (p1.value !== p2.value) err.textContent = 'The two entries do not match.';
|
|
else finish(p1.value);
|
|
} },
|
|
h('h3', {}, title), h('p', {}, intro), p1, p2, err,
|
|
h('div', { class: 'row' }, btn('Cancel', () => finish(null)), btn('Set passphrase', null, 'primary', { type: 'submit' }))));
|
|
dlg.addEventListener('cancel', () => resolve(null));
|
|
document.body.append(dlg);
|
|
dlg.showModal();
|
|
p1.focus();
|
|
});
|
|
}
|
|
|
|
// ---------- import captured walkthroughs (issue #28) ----------
|
|
// Open a bundle made by capture.html, then choose where each walkthrough goes. All or
|
|
// nothing per bundle: a wrong passphrase or damaged file imports nothing. The bundle file is
|
|
// never changed, so walkthroughs you skip can be imported from it later.
|
|
function importCaptures() {
|
|
const dests = destinations(state.doc);
|
|
const file = h('input', { type: 'file', accept: '.fwcapture,text/plain', 'aria-label': 'Capture bundle file' });
|
|
const pw = h('input', { type: 'password', autocomplete: 'off', placeholder: 'Bundle passphrase', 'aria-label': 'Bundle passphrase' });
|
|
const msg = h('p', { class: 'error', role: 'alert' });
|
|
const list = h('div', {});
|
|
const go = btn('Import selected', null, 'primary', { type: 'button', hidden: true });
|
|
let rows = [];
|
|
const close = () => { dlg.close(); dlg.remove(); };
|
|
const open = async () => {
|
|
msg.textContent = '';
|
|
try {
|
|
if (!file.files[0]) throw new Error('Choose the bundle file first.');
|
|
const bundle = await openBundle(await file.files[0].text(), pw.value);
|
|
if (!bundle.walkthroughs.length) throw new Error('That bundle has no walkthroughs.');
|
|
rows = bundle.walkthroughs.map((w) => {
|
|
const use = h('input', { type: 'checkbox', checked: true, 'aria-label': 'Import this walkthrough' });
|
|
const title = h('input', { value: w.title, 'aria-label': 'Walkthrough name' });
|
|
const where = h('select', { 'aria-label': 'Where to put it' }, dests.map((d) => h('option', { value: d.key }, d.label)));
|
|
const cur = state.doc.sections.find((x) => x.id === state.current);
|
|
if (cur) where.value = cur.id + '|';
|
|
return { w, use, title, where, el: h('div', { class: 'importrow' },
|
|
h('label', { class: 'check' }, use, ' ' + w.frames.length + ' step' + (w.frames.length === 1 ? '' : 's') + ', captured ' + w.captured),
|
|
h('div', { class: 'row' }, title, where)) };
|
|
});
|
|
list.replaceChildren(...rows.map((r) => r.el));
|
|
go.hidden = false;
|
|
if (!dests.length) msg.textContent = 'The document has no sections to put them in. Add one first.';
|
|
} catch (err) {
|
|
msg.textContent = err instanceof DecryptError ? err.message : err.message || 'Could not open that file.';
|
|
}
|
|
};
|
|
go.onclick = () => {
|
|
const picked = rows.filter((r) => r.use.checked);
|
|
if (!picked.length) { msg.textContent = 'Tick at least one walkthrough, or Cancel.'; return; }
|
|
for (const r of picked) {
|
|
const d = dests.find((x) => x.key === r.where.value);
|
|
const sec = state.doc.sections.find((x) => x.id === d.sid);
|
|
importWalkthrough(state.doc, sec, Object.assign({}, r.w, { title: r.title.value }), d.tab);
|
|
}
|
|
close();
|
|
markDirty();
|
|
state.status = 'Imported ' + picked.length + ' walkthrough' + (picked.length === 1 ? '' : 's') + '. Save to keep them, then delete the bundle file.';
|
|
render();
|
|
};
|
|
const dlg = h('dialog', { class: 'card', 'aria-label': 'Import captured walkthroughs' },
|
|
h('h3', {}, 'Import captured walkthroughs'),
|
|
h('p', {}, 'Choose the bundle file made by the capture tool and enter its passphrase. Nothing is saved until you Save.'),
|
|
file, pw, btn('Open bundle', open, 'small'), msg, list,
|
|
h('div', { class: 'row' }, btn('Cancel', close), go));
|
|
dlg.addEventListener('cancel', () => dlg.remove());
|
|
document.body.append(dlg);
|
|
dlg.showModal();
|
|
}
|
|
|
|
// backup=true downloads final-wishes-YYYYMMDD.html; otherwise writes the main file.
|
|
async function save({ backup = false } = {}) {
|
|
try {
|
|
if (!state.passphrase) {
|
|
const p = await askPassphrase('Choose a passphrase', 'This passphrase encrypts the document. Without it nobody can open it, so store it where your executor can find it.');
|
|
if (!p) return;
|
|
state.passphrase = p;
|
|
}
|
|
assertValid(state.doc);
|
|
const html = assemble({
|
|
css: byId('fw-css').textContent,
|
|
js: byId('fw-js').textContent,
|
|
payload: await encrypt(JSON.stringify(state.doc), state.passphrase),
|
|
});
|
|
if (backup) {
|
|
const name = backupName(new Date());
|
|
downloadFile(html, name);
|
|
state.status = 'Backup copy downloaded as ' + name + '.';
|
|
} else if (window.showSaveFilePicker) {
|
|
if (!state.handle) {
|
|
state.handle = await window.showSaveFilePicker({ suggestedName: 'final-wishes.html', types: [{ description: 'Final Wishes', accept: { 'text/html': ['.html'] } }] });
|
|
}
|
|
try {
|
|
const w = await state.handle.createWritable();
|
|
await w.write(html);
|
|
await w.close();
|
|
state.status = 'Saved to ' + state.handle.name + '.';
|
|
} catch (e) {
|
|
if (!e || (e.name !== 'NotAllowedError' && e.name !== 'SecurityError')) throw e;
|
|
// Chrome created the (empty) file but refuses to write it, e.g. a protected folder.
|
|
// Forget the handle so the next Save asks again, and hand over a download instead.
|
|
state.handle = null;
|
|
downloadFile(html, 'final-wishes.html');
|
|
state.status = 'Chrome would not let this page write to the chosen location, so final-wishes.html was downloaded instead. Delete the empty file it left behind and replace your old copy with the download.';
|
|
}
|
|
state.dirty = false;
|
|
snapshot();
|
|
} else {
|
|
downloadFile(html, 'final-wishes.html');
|
|
state.status = 'Downloaded final-wishes.html. Replace the old copy on the thumbdrive with it.';
|
|
state.dirty = false;
|
|
snapshot();
|
|
}
|
|
} catch (e) {
|
|
if (e && e.name === 'AbortError') return; // user closed the file picker
|
|
state.status = 'Save failed: ' + (e && e.message ? e.message : e);
|
|
}
|
|
render();
|
|
}
|
|
|
|
// Cancel: throw away unsaved edits to the section (or print header) on
|
|
// screen, back to how it was at the last open/save, then leave edit mode.
|
|
function cancelEdit() {
|
|
const onHeader = state.current === HEADER_ID;
|
|
const id = state.current;
|
|
const differs = onHeader ? headerDiffers(state.doc, state.baseline) : sectionDiffers(state.doc, state.baseline, id);
|
|
if (differs) {
|
|
if (!confirm('Discard your unsaved changes to this ' + (onHeader ? 'print header' : 'section') + '?')) return;
|
|
if (onHeader) revertHeader(state.doc, state.baseline);
|
|
else state.current = revertSection(state.doc, state.baseline, id);
|
|
state.dirty = state.pwChanged || docDiffers(state.doc, state.baseline);
|
|
state.status = 'Changes discarded.';
|
|
}
|
|
state.editing = false;
|
|
render();
|
|
}
|
|
|
|
async function changePassphrase() {
|
|
const p = await askPassphrase('Change passphrase', 'The new passphrase takes effect when you next save. Until then the saved file still opens with the old one.');
|
|
if (!p) return;
|
|
state.passphrase = p;
|
|
state.pwChanged = true;
|
|
markDirty();
|
|
state.status = 'Passphrase changed. Save to apply it.';
|
|
render();
|
|
}
|
|
|
|
document.addEventListener('keydown', (e) => {
|
|
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's' && state.doc) { e.preventDefault(); save(); }
|
|
});
|
|
|
|
// ---------- shell ----------
|
|
function renderNav() {
|
|
const nav = h('nav', { 'aria-label': 'Sections' },
|
|
h('ul', {}, state.doc.sections.map((s) => h('li', {},
|
|
h('a', { href: '#' + s.id, class: s.id === state.current ? 'current' : '', onclick: (e) => { e.preventDefault(); state.current = s.id; render(); } }, s.title)))),
|
|
h('ul', { class: 'navextra' }, h('li', {},
|
|
h('a', { href: '#header', class: state.current === HEADER_ID ? 'current' : '', onclick: (e) => { e.preventDefault(); state.current = HEADER_ID; render(); } }, 'Print header'))));
|
|
if (state.editing) {
|
|
const kind = h('select', { 'aria-label': 'New section type' }, SECTION_KINDS.map((k) => h('option', { value: k }, k)));
|
|
const title = h('input', { placeholder: 'New section title', 'aria-label': 'New section title' });
|
|
nav.append(h('div', { class: 'addsec' }, title, kind, btn('+ Add section', () => {
|
|
if (!title.value.trim()) return title.focus();
|
|
state.current = addSection(state.doc, kind.value, title.value.trim()).id;
|
|
markDirty(); render();
|
|
}, 'small')));
|
|
}
|
|
return nav;
|
|
}
|
|
|
|
function render() {
|
|
if (capture && !state.editing) endCapture(); // sharing only lasts while editing
|
|
if (state.editing) { state.search = null; state.searchOpen = false; } // search is for reading; Edit clears it
|
|
const keepFocus = searchEl && searchEl.contains(document.activeElement) ? document.activeElement : null;
|
|
root.replaceChildren();
|
|
if (!state.doc) return root.append(renderStart());
|
|
const onHeader = state.current === HEADER_ID;
|
|
const sec = onHeader ? null : state.doc.sections.find((s) => s.id === state.current) || state.doc.sections[0];
|
|
if (sec) state.current = sec.id;
|
|
root.append(
|
|
h('header', { class: 'top' },
|
|
h('div', { class: 'titlerow' },
|
|
h('h1', {}, state.doc.meta.title || 'Final Wishes'),
|
|
h('span', { class: 'muted' }, 'Last update: ' + state.doc.meta.lastUpdated),
|
|
h('span', { class: 'muted', id: 'version', title: 'Version of this app' }, 'Ver ' + APP_VERSION),
|
|
h('span', { id: 'dirty', class: 'badge tbd', hidden: !state.dirty }, 'Unsaved changes'),
|
|
h('span', { id: 'status', class: 'muted', role: 'status' }, state.status)),
|
|
// While searching, the search controls take the toolbar's place; Cancel brings the buttons back.
|
|
h('div', { class: 'toolbar' }, state.searchOpen ? searchBarEl() : [
|
|
btn('Save', () => save(), state.dirty ? 'primary' : ''),
|
|
state.editing ? btn('Cancel', cancelEdit, '', { title: 'Discard unsaved changes to this section and stop editing' }) : null,
|
|
btn('Backup copy', () => save({ backup: true })),
|
|
btn('Change passphrase', changePassphrase),
|
|
btn('Print…', openPrintDialog),
|
|
state.editing ? null : btn('Import captures…', importCaptures, '', { title: 'Merge walkthroughs captured with the separate capture tool' }),
|
|
state.editing ? null : btn('Search', openSearch, '', { id: 'searchopen', title: 'Find a word in the document' }),
|
|
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : '')])),
|
|
...(resetRequested() && !state.resetOffered ? [resetBanner()] : []), // never pass null: append() would print "null"
|
|
h('div', { class: 'layout' }, renderNav(),
|
|
h('main', {}, onHeader ? [h('h2', {}, 'Print header'), headerPanel()]
|
|
: sec ? [h('h2', {}, sec.title), state.editing ? editSection(sec) : viewSection(sec)]
|
|
: h('p', { class: 'muted' }, 'No sections yet. Choose Edit to add one.'))));
|
|
if (state.searchOpen) updateSearchUi();
|
|
if (keepFocus) keepFocus.focus();
|
|
highlightSearch();
|
|
}
|
|
|
|
// ---------- search (issue #27) ----------
|
|
// The search bar is built once and re-attached on every render(), so what was typed survives.
|
|
// Matches are counted in a hidden copy of every section (all sub-tabs, nothing folded) built by
|
|
// the same view functions as the page, so the count agrees with what is shown. Secret values,
|
|
// buttons, form fields and page furniture are never searched (see SEARCH_SKIP).
|
|
const SEARCH_SKIP = 'button,textarea,input,select,script,style,.secret,.nosearch,[hidden]';
|
|
let searchEl = null, searchInput = null, searchNote = null, searchBtns = {};
|
|
|
|
function searchBarEl() {
|
|
if (searchEl) return searchEl;
|
|
searchInput = h('input', { type: 'search', class: 'searchbox', 'aria-label': 'Search the document', placeholder: 'Search', autocomplete: 'off',
|
|
oninput: () => { if (state.search) { state.search = null; clearHighlights(); updateSearchUi(); } },
|
|
onkeydown: (e) => {
|
|
const found = state.search && state.search.hits.length;
|
|
if (e.key === 'Tab' && found) { e.preventDefault(); stepSearch(e.shiftKey ? -1 : 1); }
|
|
else if (e.key === 'Enter') {
|
|
e.preventDefault();
|
|
if (found && state.search.q === searchInput.value.trim()) stepSearch(e.shiftKey ? -1 : 1); else runSearch();
|
|
} else if (e.key === 'Escape') cancelSearch();
|
|
} });
|
|
searchNote = h('span', { class: 'muted small searchnote', role: 'status' });
|
|
searchBtns = {
|
|
search: btn('Search', runSearch, 'primary'),
|
|
prev: btn('\u2190 Previous', () => stepSearch(-1), '', { 'aria-label': 'Previous match' }),
|
|
next: btn('Next \u2192', () => stepSearch(1), '', { 'aria-label': 'Next match' }),
|
|
cancel: btn('Cancel', cancelSearch),
|
|
};
|
|
searchEl = h('div', { class: 'searchbar', role: 'search' }, searchInput, searchNote,
|
|
searchBtns.search, searchBtns.prev, searchBtns.next, searchBtns.cancel);
|
|
return searchEl;
|
|
}
|
|
|
|
function openSearch() {
|
|
state.searchOpen = true;
|
|
render();
|
|
searchInput.focus();
|
|
}
|
|
|
|
function updateSearchUi() {
|
|
if (!searchEl) return;
|
|
const s = state.search;
|
|
const n = s ? s.hits.length : 0;
|
|
searchNote.textContent = !s ? '' : n ? (s.i + 1) + ' of ' + n : 'Not found';
|
|
searchBtns.prev.disabled = searchBtns.next.disabled = n === 0;
|
|
}
|
|
|
|
// Every text node under `container` that the search may look at.
|
|
function searchableText(container) {
|
|
const out = [];
|
|
const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, {
|
|
acceptNode: (n) => (n.parentElement && !n.parentElement.closest(SEARCH_SKIP) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT) });
|
|
while (walker.nextNode()) out.push(walker.currentNode);
|
|
return out;
|
|
}
|
|
|
|
// Matches under `container`, in order, each labelled with the entry (record, item or
|
|
// sequence) it sits in and its count within that entry. '' means section-level text.
|
|
function matchesIn(container, q) {
|
|
const seen = {};
|
|
const out = [];
|
|
for (const node of searchableText(container)) {
|
|
const ranges = searchRanges(node.nodeValue, q);
|
|
if (!ranges.length) continue;
|
|
const entry = node.parentElement.closest('[data-eid]');
|
|
const eid = entry ? entry.dataset.eid : '';
|
|
for (const r of ranges) out.push({ node, start: r.start, end: r.end, eid, n: (seen[eid] = (seen[eid] || 0) + 1) - 1 });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function findAllHits(q) {
|
|
let host;
|
|
state.searchAll = true;
|
|
try {
|
|
host = h('div', {}, state.doc.sections.map((s) => h('section', { 'data-sid': s.id }, h('h2', {}, s.title), viewSection(s))));
|
|
} finally {
|
|
state.searchAll = false;
|
|
}
|
|
const hits = [];
|
|
for (const sec of host.querySelectorAll('section[data-sid]')) {
|
|
for (const m of matchesIn(sec, q)) hits.push({ sid: sec.dataset.sid, eid: m.eid, n: m.n });
|
|
}
|
|
return hits;
|
|
}
|
|
|
|
function runSearch() {
|
|
const q = searchInput.value.trim();
|
|
if (!q) { state.search = null; return render(); }
|
|
state.search = { q, hits: findAllHits(q), i: -1 };
|
|
if (state.search.hits.length) stepSearch(1); else render();
|
|
}
|
|
|
|
// Cancel: forget the search and put the toolbar buttons back.
|
|
function cancelSearch() {
|
|
searchInput.value = '';
|
|
state.search = null;
|
|
state.searchOpen = false;
|
|
render();
|
|
const again = document.getElementById('searchopen');
|
|
if (again) again.focus();
|
|
}
|
|
|
|
// Go to match i: its section, its sub-tab, unfolded, then highlight and scroll to it.
|
|
function stepSearch(dir) {
|
|
const s = state.search;
|
|
if (!s || !s.hits.length) return;
|
|
s.i = stepSearchIndex(s.i, dir, s.hits.length);
|
|
const hit = s.hits[s.i];
|
|
const sec = state.doc.sections.find((x) => x.id === hit.sid);
|
|
state.current = hit.sid;
|
|
state.walk = null;
|
|
if (hit.eid && sec) {
|
|
state.collapsed.delete(hit.eid);
|
|
const list = [...(sec.records || []), ...(sec.items || []), ...(sec.sequences || [])];
|
|
const entry = list.find((x) => x.id === hit.eid);
|
|
if (entry && sec.kind === 'records') state.tabs[sec.id] = entryTab(sec, entry);
|
|
}
|
|
s.scroll = true;
|
|
render();
|
|
}
|
|
|
|
function clearHighlights() {
|
|
for (const m of root.querySelectorAll('mark.hit')) {
|
|
const parent = m.parentNode;
|
|
m.replaceWith(...m.childNodes);
|
|
parent.normalize();
|
|
}
|
|
}
|
|
|
|
// After each render: wrap every match on screen in <mark>, the current one stronger.
|
|
function highlightSearch() {
|
|
const s = state.search;
|
|
if (!s || !s.hits.length || state.current === HEADER_ID) return;
|
|
const main = root.querySelector('main');
|
|
if (!main) return;
|
|
const cur = s.hits[s.i];
|
|
const found = matchesIn(main, s.q);
|
|
let current = null;
|
|
for (let k = found.length - 1; k >= 0; k--) { // last first, so earlier offsets stay valid
|
|
const f = found[k];
|
|
const range = document.createRange();
|
|
range.setStart(f.node, f.start);
|
|
range.setEnd(f.node, f.end);
|
|
const mark = document.createElement('mark');
|
|
mark.className = 'hit' + (cur && state.current === cur.sid && f.eid === cur.eid && f.n === cur.n ? ' cur' : '');
|
|
range.surroundContents(mark);
|
|
if (mark.classList.contains('cur')) current = mark;
|
|
}
|
|
if (current && s.scroll) current.scrollIntoView({ block: 'center' });
|
|
s.scroll = false;
|
|
}
|
|
|
|
window.addEventListener('hashchange', () => { state.resetOffered = false; render(); });
|
|
render();
|
|
})();
|