Add viewer/editor UI

Passphrase unlock (or open a plain JSON file while no payload is
embedded), sectioned navigation, read-only cards with masked secret
fields and a reveal toggle, and an edit mode with add/remove/reorder for
sections, records, fields and items. Pure edit operations live in
ops.js with tests. DOM is built with textContent only.

Closes #4

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 08:10:21 -05:00
parent 2c713f3a9b
commit d882debb9b
5 changed files with 400 additions and 7 deletions

View File

@@ -10,7 +10,7 @@ const read = (p) => readFileSync(join(root, 'src', p), 'utf8');
const out = read('index.html') const out = read('index.html')
.replace('/*__CSS__*/', () => read('style.css')) .replace('/*__CSS__*/', () => read('style.css'))
// Plain-script bundle: drop ES `export` so modules concatenate into one scope. // Plain-script bundle: drop ES `export` so modules concatenate into one scope.
.replace('/*__JS__*/', () => ['crypto.js', 'model.js'].map((f) => read(f).replace(/^export /gm, '')).concat(read('app.js')).join('\n')) .replace('/*__JS__*/', () => ['crypto.js', 'model.js', 'ops.js'].map((f) => read(f).replace(/^export /gm, '')).concat(read('app.js')).join('\n'))
.replace('/*__PAYLOAD__*/', () => ''); .replace('/*__PAYLOAD__*/', () => '');
mkdirSync(join(root, 'dist'), { recursive: true }); mkdirSync(join(root, 'dist'), { recursive: true });

View File

@@ -1,5 +1,233 @@
// App entry point. Crypto (#2), data model (#3), UI (#4) and print (#5) land here. // 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 () { (function () {
const app = document.getElementById('app'); const root = document.getElementById('app');
app.textContent = 'Final Wishes: scaffold loaded.'; const state = {
doc: null,
passphrase: null, // kept in memory for saving (issue #6)
current: null, // current section id
editing: false,
dirty: false,
revealed: new WeakSet(), // secret field objects currently shown
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;
}
function changed(record) {
touch(state.doc, record);
markDirty();
}
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 = 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;
state.passphrase = pw.value;
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' }));
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;
state.current = doc.sections[0] && doc.sections[0].id;
state.error = '';
} catch (err) { state.error = 'Could not open that file: ' + err.message; }
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 a JSON file:'), file, msg,
h('p', {}, 'or'),
btn('Start a new document', () => {
state.doc = emptyDocument('');
state.editing = true;
render();
}, 'primary'));
}
// ---------- 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 viewField(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) {
return h('article', { class: 'card' },
h('h3', {}, r.title, ' ', statusBadge(r.status)),
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 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) : null,
s.kind === 'records' ? s.records.map(viewRecord) : null,
s.kind === 'steps' ? h('ol', { class: 'items' }, s.items.map((i) => viewItem(i))) : null,
s.kind === 'checklist' ? h('ul', { class: 'items' }, s.items.map((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.
function rowTools(arr, i, what, record) {
const act = (fn) => () => { fn(); changed(record); 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('Delete this ' + what + '?')) { removeAt(arr, i); changed(record); render(); } }, 'icon danger', { 'aria-label': 'Delete ' + what }));
}
function editField(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) {
return h('article', { class: 'card editing' },
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)),
btn('+ Add field', () => { addField(r); changed(r); render(); }, 'small'),
h('label', {}, 'Notes', input(r, 'notes', { multiline: true, label: 'Notes' }, r)));
}
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')),
h('label', {}, 'Intro', input(s, 'intro', { multiline: true, label: 'Section intro' }))),
s.kind === 'text' ? h('label', {}, 'Text', input(s, 'body', { multiline: true, label: 'Body' })) : null,
s.kind === 'records' ? [s.records.map((r, i) => editRecord(s, r, i)), btn('+ Add record', () => { addRecord(state.doc, s); markDirty(); render(); }, 'primary')] : null,
s.kind === 'steps' || s.kind === 'checklist' ? [h('ol', { class: 'items' }, s.items.map((it, i) => editItem(s, it, i))), btn('+ Add item', () => { addItem(state.doc, s); markDirty(); render(); }, 'primary')] : null,
];
}
// ---------- 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)))));
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 sec = 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', { id: 'dirty', class: 'badge tbd', hidden: !state.dirty }, 'Unsaved changes'),
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : '')),
h('div', { class: 'layout' }, renderNav(),
h('main', {}, sec ? [h('h2', {}, sec.title), state.editing ? editSection(sec) : viewSection(sec)]
: h('p', { class: 'muted' }, 'No sections yet. Choose Edit to add one.'))));
}
render();
})(); })();

69
src/ops.js Normal file
View File

@@ -0,0 +1,69 @@
// Pure editing operations on the document model. No DOM; tested in Node.
// build.js strips `export` when bundling.
const today = () => new Date().toISOString().slice(0, 10);
export function allIds(doc) {
const ids = new Set();
for (const s of doc.sections) {
ids.add(s.id);
(s.records || []).forEach((r) => ids.add(r.id));
(s.items || []).forEach((i) => ids.add(i.id));
}
return ids;
}
export function newId(doc, prefix) {
const ids = allIds(doc);
let n = ids.size + 1;
while (ids.has(`${prefix}-${n}`)) n++;
return `${prefix}-${n}`;
}
// Move arr[i] one place up (dir -1) or down (+1). Returns true if it moved.
export function move(arr, i, dir) {
const j = i + dir;
if (i < 0 || i >= arr.length || j < 0 || j >= arr.length) return false;
[arr[i], arr[j]] = [arr[j], arr[i]];
return true;
}
export function removeAt(arr, i) {
return i >= 0 && i < arr.length ? arr.splice(i, 1)[0] : undefined;
}
export function touch(doc, record) {
const d = today();
doc.meta.lastUpdated = d;
if (record) record.updated = d;
}
export function addSection(doc, kind, title) {
const s = { id: newId(doc, 'sec'), title, kind };
if (kind === 'text') s.body = '';
else if (kind === 'records') s.records = [];
else s.items = [];
doc.sections.push(s);
touch(doc);
return s;
}
export function addRecord(doc, section) {
const r = { id: newId(doc, 'rec'), title: 'New record', status: 'tbd', updated: today(), fields: [] };
section.records.push(r);
touch(doc, r);
return r;
}
export function addField(record) {
const f = { label: 'Label', value: '' };
record.fields.push(f);
return f;
}
export function addItem(doc, section) {
const it = { id: newId(doc, 'item'), text: 'New item', status: 'open' };
section.items.push(it);
touch(doc);
return it;
}

View File

@@ -1,3 +1,41 @@
:root { color-scheme: light dark; font-family: system-ui, sans-serif; } :root {
body { margin: 0; padding: 1rem; } color-scheme: light dark;
#app { max-width: 50rem; margin: 0 auto; } --bg: #fafaf7; --fg: #1d1d1b; --muted: #6b6b66; --card: #fff; --line: #d9d9d2;
--accent: #1f5f8b; --warn-bg: #fff1c9; --warn-fg: #6a4b00; --ok-bg: #dcefdc; --ok-fg: #1d4d1d; --danger: #a12a2a;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif; line-height: 1.45;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #17181a; --fg: #e8e8e4; --muted: #a0a09a; --card: #212326; --line: #3a3c40;
--accent: #7ab8e6; --warn-bg: #4a3a0c; --warn-fg: #ffe08a; --ok-bg: #1f3a1f; --ok-fg: #b6e3b6; --danger: #ff8a8a; }
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--fg); }
#app { max-width: 70rem; margin: 0 auto; padding: 1rem; }
h1 { font-size: 1.4rem; margin: 0; } h2 { margin: 0 0 .75rem; } h3 { margin: 0 0 .5rem; font-size: 1.05rem; }
.top { display: flex; flex-wrap: wrap; gap: .75rem; align-items: center; padding-bottom: .75rem; border-bottom: 1px solid var(--line); margin-bottom: 1rem; }
.top h1 { flex: 1 1 auto; }
.layout { display: grid; grid-template-columns: 15rem 1fr; gap: 1.5rem; align-items: start; }
@media (max-width: 700px) { .layout { grid-template-columns: 1fr; } }
nav ul { list-style: none; margin: 0; padding: 0; }
nav a { display: block; padding: .4rem .6rem; border-radius: .4rem; color: inherit; text-decoration: none; }
nav a:hover { background: var(--line); } nav a.current { background: var(--accent); color: var(--bg); font-weight: 600; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: .6rem; padding: .85rem 1rem; margin: 0 0 .85rem; }
.start { max-width: 26rem; margin: 15vh auto 0; display: grid; gap: .75rem; }
dl { display: grid; grid-template-columns: minmax(8rem, 14rem) 1fr; gap: .25rem 1rem; margin: 0; }
dt { color: var(--muted); } dd { margin: 0; overflow-wrap: anywhere; }
.secret { font-family: ui-monospace, monospace; }
.notes, .body, .intro { white-space: pre-wrap; } .intro { color: var(--muted); }
.muted { color: var(--muted); } .small { font-size: .8rem; margin: .5rem 0 0; }
.badge { font-size: .7rem; font-weight: 700; padding: .1rem .45rem; border-radius: 1rem; vertical-align: middle; }
.badge.tbd { background: var(--warn-bg); color: var(--warn-fg); } .badge.done { background: var(--ok-bg); color: var(--ok-fg); }
ol.items, ul.items { padding-left: 1.4rem; } .item { margin-bottom: .75rem; } .item.done strong { text-decoration: line-through; }
.error { color: var(--danger); margin: 0; min-height: 1.2em; }
input, select, textarea { font: inherit; color: inherit; background: var(--bg); border: 1px solid var(--line); border-radius: .35rem; padding: .35rem .5rem; min-width: 0; }
textarea { width: 100%; display: block; } label { display: block; margin-top: .5rem; } label.check { display: inline-flex; gap: .25rem; margin: 0; align-items: center; white-space: nowrap; }
.row { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; margin-bottom: .5rem; } .row input:not([type=checkbox]) { flex: 1 1 10rem; }
.btn { font: inherit; padding: .35rem .8rem; border-radius: .4rem; border: 1px solid var(--line); background: var(--card); color: inherit; cursor: pointer; }
.btn.primary { background: var(--accent); color: var(--bg); border-color: var(--accent); }
.btn.link { border: 0; background: none; color: var(--accent); padding: 0 .5rem; text-decoration: underline; }
.btn.icon { padding: .2rem .5rem; } .btn.danger { color: var(--danger); } .btn.small { font-size: .85rem; } .btn:disabled { opacity: .35; cursor: default; }
.tools { display: inline-flex; gap: .2rem; } .addsec { display: grid; gap: .4rem; margin-top: 1rem; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }

58
test/ops.test.js Normal file
View File

@@ -0,0 +1,58 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { emptyDocument, validate } from '../src/model.js';
import { move, removeAt, newId, addSection, addRecord, addField, addItem, touch } from '../src/ops.js';
test('move swaps neighbors and refuses out of range', () => {
const a = [1, 2, 3];
assert.equal(move(a, 0, 1), true);
assert.deepEqual(a, [2, 1, 3]);
assert.equal(move(a, 0, -1), false);
assert.equal(move(a, 2, 1), false);
assert.deepEqual(a, [2, 1, 3]);
});
test('removeAt removes one element, ignores bad index', () => {
const a = ['x', 'y'];
assert.equal(removeAt(a, 0), 'x');
assert.deepEqual(a, ['y']);
assert.equal(removeAt(a, 5), undefined);
});
test('added sections/records/items/fields keep the document valid with unique ids', () => {
const doc = emptyDocument('Me');
const rs = addSection(doc, 'records', 'Banks');
const ts = addSection(doc, 'text', 'Intro');
const ss = addSection(doc, 'steps', 'Steps');
const cs = addSection(doc, 'checklist', 'Todo');
const r1 = addRecord(doc, rs);
const r2 = addRecord(doc, rs);
addField(r1);
addItem(doc, ss);
addItem(doc, cs);
assert.deepEqual(validate(doc), []);
assert.notEqual(r1.id, r2.id);
assert.equal(ts.body, '');
const ids = [rs, ts, ss, cs, r1, r2].map((x) => x.id);
assert.equal(new Set(ids).size, ids.length);
});
test('newId never collides after deletions', () => {
const doc = emptyDocument('Me');
const s = addSection(doc, 'records', 'B');
const a = addRecord(doc, s);
const b = addRecord(doc, s);
removeAt(s.records, 0);
const c = addRecord(doc, s);
assert.notEqual(c.id, b.id);
assert.equal(new Set(s.records.map((r) => r.id)).size, 2);
});
test('touch stamps record and document dates', () => {
const doc = emptyDocument('Me');
doc.meta.lastUpdated = '2000-01-01';
const rec = { updated: '2000-01-01' };
touch(doc, rec);
assert.match(doc.meta.lastUpdated, /^\d{4}-\d{2}-\d{2}$/);
assert.notEqual(rec.updated, '2000-01-01');
});