Add configurable running print header
The line printed on every page is now a header stored in the document as header.fields: any number of Text / Last updated fields, each optionally aligned left or right (at most one of each). Printed order is left, unaligned, right. Edited from a Print header panel with live preview; documents without a header use the previous title/last-update default. The header is a repeating table header so it sits in flow and cannot overlap body text, replacing the fixed-position footer. Also add "Open your existing Final Wishes file" to the start screen so data in an older encrypted file can be carried into a newer build. Closes #9 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
4
build.js
4
build.js
@@ -16,10 +16,10 @@ import { assertValid } from './src/model.js';
|
|||||||
const root = dirname(fileURLToPath(import.meta.url));
|
const root = dirname(fileURLToPath(import.meta.url));
|
||||||
const read = (p) => readFileSync(join(root, 'src', p), 'utf8');
|
const read = (p) => readFileSync(join(root, 'src', p), 'utf8');
|
||||||
|
|
||||||
// Modules are concatenated (ES `export` dropped) ahead of app.js into one scope.
|
// Modules are concatenated (ES `import` lines and `export` keywords dropped) ahead of app.js into one scope.
|
||||||
const MODULES = ['crypto.js', 'model.js', 'ops.js', 'print.js', 'template.js'];
|
const MODULES = ['crypto.js', 'model.js', 'ops.js', 'print.js', 'template.js'];
|
||||||
export function bundleJs() {
|
export function bundleJs() {
|
||||||
return MODULES.map((f) => read(f).replace(/^export /gm, '')).concat(read('app.js')).join('\n');
|
return MODULES.map((f) => read(f).replace(/^import .*$/gm, '').replace(/^export /gm, '')).concat(read('app.js')).join('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseArgs(argv) {
|
function parseArgs(argv) {
|
||||||
|
|||||||
81
src/app.js
81
src/app.js
@@ -10,6 +10,7 @@
|
|||||||
editing: false,
|
editing: false,
|
||||||
dirty: false,
|
dirty: false,
|
||||||
revealed: new WeakSet(), // secret field objects currently shown
|
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
|
handle: null, // File System Access handle once the user picked a save location
|
||||||
status: '',
|
status: '',
|
||||||
error: '',
|
error: '',
|
||||||
@@ -56,7 +57,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderStart() {
|
function renderStart() {
|
||||||
const blob = payloadText();
|
const blob = state.blob || payloadText();
|
||||||
const msg = h('p', { class: 'error', role: 'alert' }, state.error);
|
const msg = h('p', { class: 'error', role: 'alert' }, state.error);
|
||||||
if (blob) {
|
if (blob) {
|
||||||
const pw = h('input', { type: 'password', autocomplete: 'current-password', autofocus: true, 'aria-label': 'Passphrase' });
|
const pw = h('input', { type: 'password', autocomplete: 'current-password', autofocus: true, 'aria-label': 'Passphrase' });
|
||||||
@@ -68,6 +69,7 @@
|
|||||||
assertValid(doc);
|
assertValid(doc);
|
||||||
state.doc = doc;
|
state.doc = doc;
|
||||||
state.passphrase = pw.value;
|
state.passphrase = pw.value;
|
||||||
|
state.blob = null;
|
||||||
state.current = doc.sections[0] && doc.sections[0].id;
|
state.current = doc.sections[0] && doc.sections[0].id;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
state.error = err instanceof DecryptError ? err.message : 'Could not open the file: ' + err.message;
|
state.error = err instanceof DecryptError ? err.message : 'Could not open the file: ' + err.message;
|
||||||
@@ -76,7 +78,8 @@
|
|||||||
} },
|
} },
|
||||||
h('h1', {}, 'Final Wishes'),
|
h('h1', {}, 'Final Wishes'),
|
||||||
h('p', {}, 'Enter the passphrase to open this document.'),
|
h('p', {}, 'Enter the passphrase to open this document.'),
|
||||||
pw, msg, btn('Open', null, 'primary', { type: 'submit' }));
|
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;
|
return form;
|
||||||
}
|
}
|
||||||
// No encrypted data embedded yet (development / first use).
|
// No encrypted data embedded yet (development / first use).
|
||||||
@@ -90,9 +93,16 @@
|
|||||||
} catch (err) { state.error = 'Could not open that file: ' + err.message; }
|
} catch (err) { state.error = 'Could not open that file: ' + err.message; }
|
||||||
render();
|
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' },
|
return h('div', { class: 'card start' },
|
||||||
h('h1', {}, 'Final Wishes'),
|
h('h1', {}, 'Final Wishes'),
|
||||||
h('p', {}, 'No encrypted data is built into this file yet.'),
|
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', {}, 'Import a plain JSON file (you will choose a passphrase when you save):'), file, msg,
|
||||||
h('p', {}, 'or'),
|
h('p', {}, 'or'),
|
||||||
btn('Start a new document', () => {
|
btn('Start a new document', () => {
|
||||||
@@ -159,12 +169,13 @@
|
|||||||
return el;
|
return el;
|
||||||
}
|
}
|
||||||
// Up / down / delete controls for element i of arr.
|
// Up / down / delete controls for element i of arr.
|
||||||
function rowTools(arr, i, what, record) {
|
function rowTools(arr, i, what, record, quiet = false) {
|
||||||
const act = (fn) => () => { fn(); changed(record); render(); };
|
const note = () => (quiet ? markDirty() : changed(record));
|
||||||
|
const act = (fn) => () => { fn(); note(); render(); };
|
||||||
return h('span', { class: 'tools' },
|
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 + ' up', disabled: i === 0 }),
|
||||||
btn('↓', act(() => move(arr, i, 1)), 'icon', { 'aria-label': 'Move ' + what + ' down', disabled: i === arr.length - 1 }),
|
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 }));
|
btn('✕', () => { if (confirm('Delete this ' + what + '?')) { removeAt(arr, i); note(); render(); } }, 'icon danger', { 'aria-label': 'Delete ' + what }));
|
||||||
}
|
}
|
||||||
|
|
||||||
function editField(r, f, i) {
|
function editField(r, f, i) {
|
||||||
@@ -201,6 +212,47 @@
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- 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 ----------
|
// ---------- print ----------
|
||||||
const printRoot = document.getElementById('printdoc');
|
const printRoot = document.getElementById('printdoc');
|
||||||
const box = (status) => h('span', { class: 'cb ' + status, 'aria-hidden': 'true' }, status === 'done' ? '✓' : '');
|
const box = (status) => h('span', { class: 'cb ' + status, 'aria-hidden': 'true' }, status === 'done' ? '✓' : '');
|
||||||
@@ -223,8 +275,7 @@
|
|||||||
const doc = state.doc;
|
const doc = state.doc;
|
||||||
const kept = includeSecrets ? 'This copy INCLUDES passwords, PINs and other secrets. Keep it locked away (fire safe or sealed envelope).'
|
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.';
|
: 'Secrets (passwords, PINs, security answers) are WITHHELD from this copy. They are stored in the encrypted file.';
|
||||||
printRoot.replaceChildren(...[
|
const content = [
|
||||||
h('div', { class: 'pfooter' }, footerText(doc)),
|
|
||||||
h('section', { class: 'pcover' },
|
h('section', { class: 'pcover' },
|
||||||
h('h1', {}, doc.meta.title || 'Final Wishes'),
|
h('h1', {}, doc.meta.title || 'Final Wishes'),
|
||||||
doc.meta.owner ? h('p', { class: 'powner' }, 'Prepared by ' + doc.meta.owner) : null,
|
doc.meta.owner ? h('p', { class: 'powner' }, 'Prepared by ' + doc.meta.owner) : null,
|
||||||
@@ -240,7 +291,11 @@
|
|||||||
s.kind === 'records' ? s.records.map((r) => printRecord(r, includeSecrets)) : null,
|
s.kind === 'records' ? s.records.map((r) => printRecord(r, includeSecrets)) : null,
|
||||||
s.kind === 'steps' ? h('ol', { class: 'pitems' }, s.items.map((i) => printItem(i))) : null,
|
s.kind === 'steps' ? h('ol', { class: 'pitems' }, s.items.map((i) => printItem(i))) : null,
|
||||||
s.kind === 'checklist' ? h('ul', { class: 'pitems' }, s.items.map((i) => printItem(i))) : null)),
|
s.kind === 'checklist' ? h('ul', { class: 'pitems' }, s.items.map((i) => printItem(i))) : null)),
|
||||||
].flat());
|
].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
|
window.addEventListener('afterprint', () => printRoot.replaceChildren()); // don't leave secrets lingering in the DOM
|
||||||
|
|
||||||
@@ -355,7 +410,9 @@
|
|||||||
function renderNav() {
|
function renderNav() {
|
||||||
const nav = h('nav', { 'aria-label': 'Sections' },
|
const nav = h('nav', { 'aria-label': 'Sections' },
|
||||||
h('ul', {}, state.doc.sections.map((s) => h('li', {},
|
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('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) {
|
if (state.editing) {
|
||||||
const kind = h('select', { 'aria-label': 'New section type' }, SECTION_KINDS.map((k) => h('option', { value: k }, k)));
|
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' });
|
const title = h('input', { placeholder: 'New section title', 'aria-label': 'New section title' });
|
||||||
@@ -371,7 +428,8 @@
|
|||||||
function render() {
|
function render() {
|
||||||
root.replaceChildren();
|
root.replaceChildren();
|
||||||
if (!state.doc) return root.append(renderStart());
|
if (!state.doc) return root.append(renderStart());
|
||||||
const sec = state.doc.sections.find((s) => s.id === state.current) || state.doc.sections[0];
|
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;
|
if (sec) state.current = sec.id;
|
||||||
root.append(
|
root.append(
|
||||||
h('header', { class: 'top' },
|
h('header', { class: 'top' },
|
||||||
@@ -385,7 +443,8 @@
|
|||||||
btn('Print…', openPrintDialog),
|
btn('Print…', openPrintDialog),
|
||||||
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : '')),
|
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : '')),
|
||||||
h('div', { class: 'layout' }, renderNav(),
|
h('div', { class: 'layout' }, renderNav(),
|
||||||
h('main', {}, sec ? [h('h2', {}, sec.title), state.editing ? editSection(sec) : viewSection(sec)]
|
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.'))));
|
: h('p', { class: 'muted' }, 'No sections yet. Choose Edit to add one.'))));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
37
src/model.js
37
src/model.js
@@ -4,6 +4,7 @@
|
|||||||
// Document:
|
// Document:
|
||||||
// { schemaVersion: 1,
|
// { schemaVersion: 1,
|
||||||
// meta: { owner, title, lastUpdated: 'YYYY-MM-DD' },
|
// meta: { owner, title, lastUpdated: 'YYYY-MM-DD' },
|
||||||
|
// header?: { fields: [HeaderField] }, // running print header; absent = defaults
|
||||||
// sections: [ Section ] }
|
// sections: [ Section ] }
|
||||||
//
|
//
|
||||||
// Section (ordered). `kind` decides which body it has:
|
// Section (ordered). `kind` decides which body it has:
|
||||||
@@ -17,6 +18,11 @@
|
|||||||
// fields: [{ label, value, secret?: boolean }], notes?: string }
|
// fields: [{ label, value, secret?: boolean }], notes?: string }
|
||||||
// Item: { id, text, status: 'open'|'done'|'tbd', detail?: string }
|
// Item: { id, text, status: 'open'|'done'|'tbd', detail?: string }
|
||||||
//
|
//
|
||||||
|
// HeaderField: { kind: 'text'|'lastUpdated', text, align?: 'left'|'right' }
|
||||||
|
// kind 'text' prints `text`; 'lastUpdated' prints `text` (a label) + meta.lastUpdated.
|
||||||
|
// At most one field is 'left' and one 'right'. Printed order: the left field,
|
||||||
|
// then unaligned fields in list order, then the right field.
|
||||||
|
//
|
||||||
// Ids are unique across the whole document. `secret` fields are masked
|
// Ids are unique across the whole document. `secret` fields are masked
|
||||||
// in the UI and optionally in print output.
|
// in the UI and optionally in print output.
|
||||||
|
|
||||||
@@ -24,6 +30,16 @@ export const SCHEMA_VERSION = 1;
|
|||||||
export const SECTION_KINDS = ['text', 'records', 'steps', 'checklist'];
|
export const SECTION_KINDS = ['text', 'records', 'steps', 'checklist'];
|
||||||
export const RECORD_STATUSES = ['ok', 'tbd'];
|
export const RECORD_STATUSES = ['ok', 'tbd'];
|
||||||
export const ITEM_STATUSES = ['open', 'done', 'tbd'];
|
export const ITEM_STATUSES = ['open', 'done', 'tbd'];
|
||||||
|
export const HEADER_KINDS = ['text', 'lastUpdated'];
|
||||||
|
export const HEADER_ALIGNS = ['left', 'right'];
|
||||||
|
|
||||||
|
// What the header is when the document doesn't define one.
|
||||||
|
export function defaultHeaderFields(doc) {
|
||||||
|
return [
|
||||||
|
{ kind: 'text', text: (doc.meta && doc.meta.title) || 'Final Wishes', align: 'left' },
|
||||||
|
{ kind: 'lastUpdated', text: 'Last update: ', align: 'right' },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
const isStr = (v) => typeof v === 'string';
|
const isStr = (v) => typeof v === 'string';
|
||||||
@@ -57,6 +73,27 @@ export function validate(doc) {
|
|||||||
if (!DATE_RE.test(doc.meta.lastUpdated ?? '')) errs.push('meta.lastUpdated must be YYYY-MM-DD');
|
if (!DATE_RE.test(doc.meta.lastUpdated ?? '')) errs.push('meta.lastUpdated must be YYYY-MM-DD');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (doc.header !== undefined) {
|
||||||
|
if (!isObj(doc.header) || !Array.isArray(doc.header.fields)) errs.push('header.fields must be an array');
|
||||||
|
else {
|
||||||
|
let left = 0;
|
||||||
|
let right = 0;
|
||||||
|
doc.header.fields.forEach((f, i) => {
|
||||||
|
const w = `header.fields[${i}]`;
|
||||||
|
if (!isObj(f)) return errs.push(`${w}: must be an object`);
|
||||||
|
if (!HEADER_KINDS.includes(f.kind)) errs.push(`${w}: unknown kind "${f.kind}"`);
|
||||||
|
if (!isStr(f.text)) errs.push(`${w}: text must be a string`);
|
||||||
|
if (f.align !== undefined) {
|
||||||
|
if (!HEADER_ALIGNS.includes(f.align)) errs.push(`${w}: bad align "${f.align}"`);
|
||||||
|
else if (f.align === 'left') left++;
|
||||||
|
else right++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (left > 1) errs.push('header: only one field can be left aligned');
|
||||||
|
if (right > 1) errs.push('header: only one field can be right aligned');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!Array.isArray(doc.sections)) return [...errs, 'sections must be an array'];
|
if (!Array.isArray(doc.sections)) return [...errs, 'sections must be an array'];
|
||||||
|
|
||||||
doc.sections.forEach((s, i) => {
|
doc.sections.forEach((s, i) => {
|
||||||
|
|||||||
29
src/ops.js
29
src/ops.js
@@ -1,3 +1,5 @@
|
|||||||
|
import { defaultHeaderFields } from './model.js';
|
||||||
|
|
||||||
// Pure editing operations on the document model. No DOM; tested in Node.
|
// Pure editing operations on the document model. No DOM; tested in Node.
|
||||||
// build.js strips `export` when bundling.
|
// build.js strips `export` when bundling.
|
||||||
|
|
||||||
@@ -73,3 +75,30 @@ export function backupName(date) {
|
|||||||
const p = (n) => String(n).padStart(2, '0');
|
const p = (n) => String(n).padStart(2, '0');
|
||||||
return `final-wishes-${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}.html`;
|
return `final-wishes-${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}.html`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- print header ----
|
||||||
|
// Materialize the default header into the document the first time it is edited.
|
||||||
|
export function ensureHeader(doc) {
|
||||||
|
if (!doc.header) doc.header = { fields: defaultHeaderFields(doc) };
|
||||||
|
return doc.header;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addHeaderField(doc) {
|
||||||
|
const f = { kind: 'text', text: 'New text' };
|
||||||
|
ensureHeader(doc).fields.push(f);
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alignments ('left' / 'right') already used by fields other than `field`.
|
||||||
|
export function takenAligns(fields, field) {
|
||||||
|
return new Set(fields.filter((f) => f !== field && f.align).map((f) => f.align));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set a field's alignment ('left' | 'right' | '' for none). Refuses a second
|
||||||
|
// left or right field; returns whether it was applied.
|
||||||
|
export function setAlign(fields, field, align) {
|
||||||
|
if (align && takenAligns(fields, field).has(align)) return false;
|
||||||
|
if (align) field.align = align;
|
||||||
|
else delete field.align;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|||||||
23
src/print.js
23
src/print.js
@@ -1,3 +1,5 @@
|
|||||||
|
import { defaultHeaderFields } from './model.js';
|
||||||
|
|
||||||
// Pure helpers for the printed document. No DOM; tested in Node.
|
// Pure helpers for the printed document. No DOM; tested in Node.
|
||||||
// build.js strips `export` when bundling.
|
// build.js strips `export` when bundling.
|
||||||
|
|
||||||
@@ -11,8 +13,25 @@ export function displayValue(field, includeSecrets) {
|
|||||||
return field.value || '(blank)';
|
return field.value || '(blank)';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function footerText(doc) {
|
export function headerFields(doc) {
|
||||||
return `${doc.meta.title || 'Final Wishes'} — Last update: ${doc.meta.lastUpdated}`;
|
return doc.header ? doc.header.fields : defaultHeaderFields(doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function headerText(field, doc) {
|
||||||
|
return field.kind === 'lastUpdated' ? (field.text || '') + doc.meta.lastUpdated : field.text;
|
||||||
|
}
|
||||||
|
|
||||||
|
// { left, middle: [..], right } in printed order: the left-aligned field, then
|
||||||
|
// unaligned fields in list order, then the right-aligned field. Empty text is dropped.
|
||||||
|
export function headerLayout(doc) {
|
||||||
|
const fields = headerFields(doc);
|
||||||
|
const left = fields.find((f) => f.align === 'left');
|
||||||
|
const right = fields.find((f) => f.align === 'right');
|
||||||
|
return {
|
||||||
|
left: left ? headerText(left, doc) : '',
|
||||||
|
middle: fields.filter((f) => f.align !== 'left' && f.align !== 'right').map((f) => headerText(f, doc)).filter(Boolean),
|
||||||
|
right: right ? headerText(right, doc) : '',
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function countSecrets(doc) {
|
export function countSecrets(doc) {
|
||||||
|
|||||||
@@ -40,15 +40,25 @@ textarea { width: 100%; display: block; } label { display: block; margin-top: .5
|
|||||||
.tools { display: inline-flex; gap: .2rem; } .addsec { display: grid; gap: .4rem; margin-top: 1rem; }
|
.tools { display: inline-flex; gap: .2rem; } .addsec { display: grid; gap: .4rem; margin-top: 1rem; }
|
||||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
|
||||||
|
/* ---------- print header (screen preview and printed running header) ---------- */
|
||||||
|
.phead { display: flex; align-items: baseline; gap: 14px; font: 700 1.15rem system-ui, sans-serif; border-bottom: 2px solid currentColor; padding-bottom: 5px; }
|
||||||
|
.ph-left { flex: 0 1 auto; text-align: left; min-width: 0; } /* the left field wraps first */
|
||||||
|
.ph-right { flex: 0 0 auto; text-align: right; margin-left: auto; white-space: nowrap; }
|
||||||
|
.ph-mid { flex: 1 1 auto; display: flex; justify-content: center; gap: 14px; } .ph-mid > span { white-space: nowrap; }
|
||||||
|
.hpreview { padding: .75rem 1rem; } .navextra { margin-top: 1rem; border-top: 1px solid var(--line); padding-top: .5rem; }
|
||||||
|
|
||||||
/* ---------- print ---------- */
|
/* ---------- print ---------- */
|
||||||
@media screen { #printdoc { display: none; } .radio { display: block; margin: .5rem 0; } dialog.card { max-width: 30rem; } dialog::backdrop { background: rgba(0,0,0,.45); } }
|
@media screen { #printdoc { display: none; } .radio { display: block; margin: .5rem 0; } dialog.card { max-width: 30rem; } dialog::backdrop { background: rgba(0,0,0,.45); } }
|
||||||
@page { size: letter; margin: 0.8in 0.8in 1in; }
|
@page { size: letter; margin: 0.7in 0.8in 0.8in; }
|
||||||
@media print {
|
@media print {
|
||||||
:root { color-scheme: light; }
|
:root { color-scheme: light; }
|
||||||
html, body { background: #fff !important; color: #000 !important; font-size: 11pt; }
|
html, body { background: #fff !important; color: #000 !important; font-size: 11pt; }
|
||||||
#app, dialog { display: none !important; }
|
#app, dialog { display: none !important; }
|
||||||
#printdoc { display: block; font-family: Georgia, "Times New Roman", serif; line-height: 1.35; }
|
#printdoc { display: block; font-family: Georgia, "Times New Roman", serif; line-height: 1.35; }
|
||||||
.pfooter { position: fixed; bottom: -0.6in; left: 0; right: 0; text-align: center; font: 9pt system-ui, sans-serif; color: #444; border-top: 0.5pt solid #999; padding-top: 3pt; }
|
.ptable { width: 100%; border-collapse: collapse; }
|
||||||
|
.ptable > thead > tr > td, .ptable > tbody > tr > td { padding: 0; }
|
||||||
|
.ptable > thead { display: table-header-group; }
|
||||||
|
.phead { color: #000; border-bottom-color: #000; margin-bottom: 14pt; }
|
||||||
.pcover { break-after: page; }
|
.pcover { break-after: page; }
|
||||||
.pcover h1 { font-size: 26pt; margin: 1.2in 0 .2in; }
|
.pcover h1 { font-size: 26pt; margin: 1.2in 0 .2in; }
|
||||||
.powner { font-size: 14pt; }
|
.powner { font-size: 14pt; }
|
||||||
|
|||||||
@@ -46,6 +46,23 @@ test('rejects structural problems', () => {
|
|||||||
assert.deepEqual(validate(null), ['document must be an object']);
|
assert.deepEqual(validate(null), ['document must be an object']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('header validation: kinds, aligns, and one left / one right at most', () => {
|
||||||
|
const withHeader = (fields) => ({ ...good(), header: { fields } });
|
||||||
|
const ok = [{ kind: 'text', text: 'T', align: 'left' }, { kind: 'text', text: 'm' }, { kind: 'lastUpdated', text: '', align: 'right' }];
|
||||||
|
assert.deepEqual(validate(withHeader(ok)), []);
|
||||||
|
assert.deepEqual(validate(withHeader([])), []);
|
||||||
|
assert.deepEqual(validate(good()), []); // header is optional
|
||||||
|
const bad = [
|
||||||
|
[[{ kind: 'x', text: 'a' }], /unknown kind/],
|
||||||
|
[[{ kind: 'text', text: 5 }], /text must be a string/],
|
||||||
|
[[{ kind: 'text', text: 'a', align: 'center' }], /bad align/],
|
||||||
|
[[{ kind: 'text', text: 'a', align: 'left' }, { kind: 'text', text: 'b', align: 'left' }], /only one field can be left/],
|
||||||
|
[[{ kind: 'text', text: 'a', align: 'right' }, { kind: 'text', text: 'b', align: 'right' }], /only one field can be right/],
|
||||||
|
];
|
||||||
|
for (const [fields, re] of bad) assert.match(validate(withHeader(fields)).join('\n'), re);
|
||||||
|
assert.match(validate({ ...good(), header: {} }).join('\n'), /header.fields must be an array/);
|
||||||
|
});
|
||||||
|
|
||||||
// data/ is gitignored (private), so this only runs on a machine that has the seed.
|
// data/ is gitignored (private), so this only runs on a machine that has the seed.
|
||||||
test('data/seed.json, when present, is valid', { skip: !existsSync('data/seed.json') }, () => {
|
test('data/seed.json, when present, is valid', { skip: !existsSync('data/seed.json') }, () => {
|
||||||
const seed = JSON.parse(readFileSync('data/seed.json', 'utf8'));
|
const seed = JSON.parse(readFileSync('data/seed.json', 'utf8'));
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { emptyDocument, validate } from '../src/model.js';
|
import { emptyDocument, validate } from '../src/model.js';
|
||||||
import { move, removeAt, newId, addSection, addRecord, addField, addItem, touch } from '../src/ops.js';
|
import { move, removeAt, newId, addSection, addRecord, addField, addItem, touch, ensureHeader, addHeaderField, setAlign, takenAligns } from '../src/ops.js';
|
||||||
|
|
||||||
test('move swaps neighbors and refuses out of range', () => {
|
test('move swaps neighbors and refuses out of range', () => {
|
||||||
const a = [1, 2, 3];
|
const a = [1, 2, 3];
|
||||||
@@ -56,3 +56,28 @@ test('touch stamps record and document dates', () => {
|
|||||||
assert.match(doc.meta.lastUpdated, /^\d{4}-\d{2}-\d{2}$/);
|
assert.match(doc.meta.lastUpdated, /^\d{4}-\d{2}-\d{2}$/);
|
||||||
assert.notEqual(rec.updated, '2000-01-01');
|
assert.notEqual(rec.updated, '2000-01-01');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('ensureHeader materializes defaults once; addHeaderField keeps document valid', () => {
|
||||||
|
const doc = emptyDocument('Me', 'My Title');
|
||||||
|
assert.equal(doc.header, undefined);
|
||||||
|
const h = ensureHeader(doc);
|
||||||
|
assert.equal(ensureHeader(doc), h);
|
||||||
|
assert.equal(h.fields[0].text, 'My Title');
|
||||||
|
addHeaderField(doc);
|
||||||
|
assert.equal(doc.header.fields.length, 3);
|
||||||
|
assert.deepEqual(validate(doc), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('setAlign enforces one left and one right', () => {
|
||||||
|
const fields = [{ kind: 'text', text: 'a' }, { kind: 'text', text: 'b' }, { kind: 'text', text: 'c' }];
|
||||||
|
assert.equal(setAlign(fields, fields[0], 'left'), true);
|
||||||
|
assert.equal(setAlign(fields, fields[1], 'left'), false);
|
||||||
|
assert.equal(fields[1].align, undefined);
|
||||||
|
assert.equal(setAlign(fields, fields[1], 'right'), true);
|
||||||
|
assert.equal(setAlign(fields, fields[2], 'right'), false);
|
||||||
|
assert.deepEqual([...takenAligns(fields, fields[2])].sort(), ['left', 'right']);
|
||||||
|
assert.equal(setAlign(fields, fields[0], 'left'), true); // re-selecting its own value is fine
|
||||||
|
assert.equal(setAlign(fields, fields[0], ''), true);
|
||||||
|
assert.equal('align' in fields[0], false);
|
||||||
|
assert.equal(setAlign(fields, fields[2], 'left'), true); // freed
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { displayValue, footerText, countSecrets } from '../src/print.js';
|
import { displayValue, headerLayout, countSecrets } from '../src/print.js';
|
||||||
|
|
||||||
test('displayValue shows or withholds secrets, never confuses empty with hidden', () => {
|
test('displayValue shows or withholds secrets, never confuses empty with hidden', () => {
|
||||||
assert.equal(displayValue({ label: 'a', value: 'x' }, false), 'x');
|
assert.equal(displayValue({ label: 'a', value: 'x' }, false), 'x');
|
||||||
@@ -16,10 +16,31 @@ test('masked output never contains the secret text', () => {
|
|||||||
assert.ok(!out.includes('hunter2'));
|
assert.ok(!out.includes('hunter2'));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('footerText and countSecrets', () => {
|
test('countSecrets counts only filled secret fields', () => {
|
||||||
const doc = { meta: { title: 'T', lastUpdated: '2022-04-14' }, sections: [
|
const doc = { meta: { title: 'T', lastUpdated: '2022-04-14' }, sections: [
|
||||||
{ records: [{ fields: [{ label: 'a', value: 'x', secret: true }, { label: 'b', value: '', secret: true }, { label: 'c', value: 'y' }] }] },
|
{ records: [{ fields: [{ label: 'a', value: 'x', secret: true }, { label: 'b', value: '', secret: true }, { label: 'c', value: 'y' }] }] },
|
||||||
{ items: [] } ] };
|
{ items: [] } ] };
|
||||||
assert.equal(footerText(doc), 'T — Last update: 2022-04-14');
|
|
||||||
assert.equal(countSecrets(doc), 1);
|
assert.equal(countSecrets(doc), 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const D = (header) => ({ meta: { title: 'My Title', lastUpdated: '2026-11-09' }, header, sections: [] });
|
||||||
|
|
||||||
|
test('header defaults: title left, last update right', () => {
|
||||||
|
assert.deepEqual(headerLayout(D(undefined)), { left: 'My Title', middle: [], right: 'Last update: 2026-11-09' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('header layout order is left, unaligned in list order, right, regardless of field order', () => {
|
||||||
|
const doc = D({ fields: [
|
||||||
|
{ kind: 'lastUpdated', text: 'Updated ', align: 'right' },
|
||||||
|
{ kind: 'text', text: 'Middle A' },
|
||||||
|
{ kind: 'text', text: 'Left one', align: 'left' },
|
||||||
|
{ kind: 'text', text: 'Middle B' },
|
||||||
|
] });
|
||||||
|
assert.deepEqual(headerLayout(doc), { left: 'Left one', middle: ['Middle A', 'Middle B'], right: 'Updated 2026-11-09' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('header with only unaligned fields, and empty text dropped', () => {
|
||||||
|
const doc = D({ fields: [{ kind: 'text', text: 'A' }, { kind: 'text', text: '' }, { kind: 'lastUpdated', text: '' }] });
|
||||||
|
assert.deepEqual(headerLayout(doc), { left: '', middle: ['A', '2026-11-09'], right: '' });
|
||||||
|
assert.deepEqual(headerLayout(D({ fields: [] })), { left: '', middle: [], right: '' });
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user