707 lines
38 KiB
JavaScript
707 lines
38 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
|
|
collapsed: new Set(), // ids of records folded to just their title (view mode only)
|
|
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: '',
|
|
};
|
|
|
|
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);
|
|
|
|
// 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;
|
|
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 });
|
|
});
|
|
|
|
function openLightbox(label, src) {
|
|
const dlg = h('dialog', { class: 'card lightbox', 'aria-label': label },
|
|
h('h3', {}, label), h('img', { class: 'bigimg', src, alt: label }),
|
|
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' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done' }, '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)];
|
|
}
|
|
|
|
function viewRecord(r, arr, i) {
|
|
const closed = state.collapsed.has(r.id);
|
|
const toggle = () => { state.collapsed[closed ? 'delete' : 'add'](r.id); render(); };
|
|
const shift = (dir) => { move(arr, i, dir); changed(r); render(); };
|
|
return h('article', { class: 'card' + (closed ? ' collapsed' : '') },
|
|
h('div', { class: 'rechead' },
|
|
h('h3', {}, r.title, ' ', statusBadge(r.status)),
|
|
h('span', { class: 'tools' },
|
|
closed && i > 0 ? btn('↑', () => shift(-1), 'icon', { 'aria-label': 'Move ' + r.title + ' up' }) : null,
|
|
closed && i < arr.length - 1 ? 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' }, 'Updated ' + r.updated)]);
|
|
}
|
|
|
|
function foldBar(s) {
|
|
const recs = s.records.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' }, 'Step ' + (k + 1)),
|
|
hidden ? h('div', {}, h('span', { class: 'secret' }, '(hidden step)'), btn('Show', toggle, 'link', { 'aria-label': 'Show ' + label })) : [
|
|
f.image ? h('img', { class: 'fimg', src: f.image, alt: label, tabIndex: 0, title: 'Click to enlarge',
|
|
onclick: () => openLightbox(label, f.image), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(label, f.image); } })
|
|
: h('span', { class: 'muted' }, '(no image)'),
|
|
layout !== 'none' ? h('p', { class: 'ftext' }, f.text) : null,
|
|
f.secret ? btn('Hide', toggle, 'link', { 'aria-label': 'Hide ' + label }) : null]);
|
|
}
|
|
|
|
function viewSequence(q) {
|
|
return h('article', { class: 'card seq' },
|
|
h('h3', {}, q.title),
|
|
q.frames.length ? h('div', { class: 'frames' }, q.frames.map((f, k) => viewFrame(q, f, k))) : h('p', { class: 'muted' }, '(no steps yet)'),
|
|
h('p', { class: 'muted small' }, 'Updated ' + q.updated));
|
|
}
|
|
const seqItem = (q) => h('li', { class: 'seqitem' }, viewSequence(q));
|
|
|
|
function viewItem(it, ordered) {
|
|
return h('li', { class: 'item ' + it.status },
|
|
h('div', {}, h('strong', {}, it.text), ' ', statusBadge(it.status)),
|
|
it.detail ? h('p', { class: 'notes' }, it.detail) : null);
|
|
}
|
|
|
|
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' ? [foldBar(s), s.records.map((r, i) => (isSequence(r) ? viewSequence(r) : viewRecord(r, s.records, i)))] : 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.
|
|
function rowTools(arr, i, what, record, quiet = false, message = null) {
|
|
const note = () => (quiet ? markDirty() : changed(record));
|
|
const act = (fn) => () => { fn(); note(); render(); };
|
|
return h('span', { class: 'tools' },
|
|
btn('↑', act(() => move(arr, i, -1)), 'icon', { 'aria-label': 'Move ' + what + ' up', disabled: i === 0 }),
|
|
btn('↓', act(() => move(arr, i, 1)), 'icon', { 'aria-label': 'Move ' + what + ' down', disabled: i === arr.length - 1 }),
|
|
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] ? h('img', { class: 'fimg', src: obj[key], alt: label }) : 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;
|
|
}
|
|
|
|
function editImageField(r, f, i) {
|
|
const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret',
|
|
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; 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), h('label', { class: 'check' }, secret, ' 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 = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret',
|
|
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(r); } });
|
|
return h('div', { class: 'row field' },
|
|
input(f, 'label', { label: 'Field label' }, r), input(f, 'value', { label: 'Field value' }, r),
|
|
h('label', { class: 'check' }, secret, ' secret'), rowTools(r.fields, i, 'field', r));
|
|
}
|
|
|
|
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')),
|
|
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']];
|
|
|
|
function editFrame(q, f, k) {
|
|
const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret step',
|
|
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; 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, h('label', { class: 'check' }, secret, ' 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) }), () => changed(q)),
|
|
f.layout === 'none' ? null : h('label', {}, 'Text', input(f, 'text', { multiline: true, label: 'Text for step ' + (k + 1) }, q)));
|
|
}
|
|
|
|
function editSequence(list, q, i) {
|
|
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)),
|
|
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));
|
|
}
|
|
const addSeqBtn = (s) => btn('+ Add visual sequence', () => { addSequence(state.doc, 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' ? [s.records.map((r, i) => (isSequence(r) ? editSequence(s.records, r, i) : editRecord(s, r, i))),
|
|
h('div', { class: 'row' }, btn('+ Add record', () => { addRecord(state.doc, 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, includeSecrets) {
|
|
if (f.kind === 'image' && f.value && (!f.secret || includeSecrets)) return h('img', { class: 'pimg', src: f.value, alt: f.label });
|
|
return displayValue(f, includeSecrets);
|
|
}
|
|
|
|
function printFrame(f, k, includeSecrets) {
|
|
const v = frameView(f, includeSecrets);
|
|
return h('div', { class: 'pframe ' + v.layout },
|
|
h('div', { class: 'pfnum' }, 'Step ' + (k + 1)),
|
|
v.withheld ? h('p', { class: 'psecret' }, '[withheld]')
|
|
: v.image ? h('img', { class: 'pimg', src: v.image, alt: 'Step ' + (k + 1) })
|
|
: h('p', {}, '(no image)'),
|
|
v.layout !== 'none' ? h('p', { class: 'pftext' }, v.text) : null);
|
|
}
|
|
|
|
function printSequence(q, includeSecrets) {
|
|
return h('div', { class: 'pseq' },
|
|
h('h3', {}, q.title),
|
|
q.frames.map((f, k) => printFrame(f, k, includeSecrets)));
|
|
}
|
|
|
|
function printRecord(r, includeSecrets) {
|
|
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, includeSecrets)))))) : null,
|
|
r.notes ? h('p', { class: 'pnotes' }, r.notes) : null);
|
|
}
|
|
|
|
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(includeSecrets) {
|
|
const doc = state.doc;
|
|
const kept = includeSecrets ? 'This copy INCLUDES passwords, PINs and other secrets. Keep it locked away (fire safe or sealed envelope).'
|
|
: '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' + (includeSecrets ? ' 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, includeSecrets))] : null,
|
|
s.kind === 'records' ? s.records.map((r) => (isSequence(r) ? printSequence(r, includeSecrets) : printRecord(r, includeSecrets))) : null,
|
|
s.kind === 'steps' ? h('ol', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, includeSecrets)) : printItem(i)))) : null,
|
|
s.kind === 'checklist' ? h('ul', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, includeSecrets)) : 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 = countSecrets(state.doc);
|
|
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('mask', true, 'Withhold secrets (safe overview; ' + n + ' secret value' + (n === 1 ? '' : 's') + ' hidden)'),
|
|
radio('include', false, 'Include secrets (full copy: store it securely)'),
|
|
h('div', { class: 'row' },
|
|
btn('Cancel', () => { dlg.close(); dlg.remove(); }),
|
|
btn('Print', async () => {
|
|
const include = dlg.querySelector('input[name=mode]:checked').value === 'include';
|
|
dlg.close(); dlg.remove();
|
|
buildPrintDoc(include);
|
|
// 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();
|
|
});
|
|
}
|
|
|
|
// 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'] } }] });
|
|
}
|
|
const w = await state.handle.createWritable();
|
|
await w.write(html);
|
|
await w.close();
|
|
state.status = 'Saved to ' + state.handle.name + '.';
|
|
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() {
|
|
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('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),
|
|
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),
|
|
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : '')),
|
|
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.'))));
|
|
}
|
|
|
|
render();
|
|
})();
|