Files
final-wishes/src/ops.js
Eric Bell 673560a249 Capture walkthroughs online in a separate tool, merge them in offline (Fixes #28)
build.js now also writes capture.html: no document, no payload, no storage.
It captures walkthroughs and exports an encrypted .fwcapture bundle (magic
FC, own passphrase). The main app's Import captures... opens a bundle and
places each walkthrough in a chosen section or sub-tab; nothing is written
until Save and the bundle is never modified.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 15:41:19 -05:00

396 lines
14 KiB
JavaScript

import { defaultHeaderFields, isSequence, GENERAL_TITLE } from './model.js';
// 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.subsections || []).forEach((t) => ids.add(t.id));
(s.records || []).forEach((r) => ids.add(r.id));
(s.items || []).forEach((i) => ids.add(i.id));
(s.sequences || []).forEach((q) => ids.add(q.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, tabId = '') {
const r = { id: newId(doc, 'rec'), title: 'New record', status: 'tbd', updated: today(), fields: [] };
if (tabId) r.subsection = tabId;
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;
}
// final-wishes-YYYYMMDD.html (local date)
export function backupName(date) {
const p = (n) => String(n).padStart(2, '0');
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;
}
// ---- image fields ----
export function addImageField(record, label, value) {
const f = { kind: 'image', label: label || 'Image', value };
record.fields.push(f);
return f;
}
// ---- revert to the last saved state (Cancel) ----
// A baseline is a deep copy of the document taken at open / save.
export function snapshotDoc(doc) {
return JSON.parse(JSON.stringify(doc));
}
// The date stamp changes on every edit, so it never counts as a difference.
const stable = (doc) => JSON.stringify({ ...doc, meta: { ...doc.meta, lastUpdated: '' } });
const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
export function docDiffers(doc, baseline) {
return stable(doc) !== stable(baseline);
}
// A section the baseline doesn't have was added since: that counts as changed.
export function sectionDiffers(doc, baseline, id) {
const cur = doc.sections.find((s) => s.id === id);
const old = baseline.sections.find((s) => s.id === id);
if (!cur) return false;
return !old || !sameJson(cur, old);
}
export function headerDiffers(doc, baseline) {
return !sameJson(doc.header, baseline.header);
}
// Put the section back as it was in the baseline (in its current position),
// or remove it if it was added since. Returns the id of the section to show
// next (the same one, or a neighbour after a removal; undefined if none left).
export function revertSection(doc, baseline, id) {
const i = doc.sections.findIndex((s) => s.id === id);
if (i < 0) return undefined;
const old = baseline.sections.find((s) => s.id === id);
if (old) {
doc.sections[i] = snapshotDoc(old);
syncDate(doc, baseline);
return id;
}
doc.sections.splice(i, 1);
syncDate(doc, baseline);
const next = doc.sections[i] || doc.sections[i - 1];
return next && next.id;
}
export function revertHeader(doc, baseline) {
if (baseline.header === undefined) delete doc.header;
else doc.header = snapshotDoc(baseline.header);
syncDate(doc, baseline);
}
// If nothing differs any more, the "last updated" date goes back too.
function syncDate(doc, baseline) {
if (!docDiffers(doc, baseline)) doc.meta.lastUpdated = baseline.meta.lastUpdated;
}
// ---- visual sequences ----
// Every sequence in the document, wherever it lives.
export function allSequences(doc) {
const out = [];
for (const s of doc.sections) {
for (const e of s.records || []) if (isSequence(e)) out.push(e);
for (const e of s.items || []) if (isSequence(e)) out.push(e);
for (const e of s.sequences || []) out.push(e);
}
return out;
}
// Erase the content of every secret field and secret frame (labels, structure
// and the secret flags stay). Returns how many values were erased.
export function clearSecrets(doc) {
let n = 0;
const frames = (q) => { for (const f of q.frames) if (f.secret && (f.image || String(f.text || '').trim() || String(f.ifStuck || '').trim())) { f.image = ''; delete f.marks; f.text = ''; if (f.ifStuck) f.ifStuck = ''; n++; } };
for (const s of doc.sections) {
for (const r of s.records || []) {
if (isSequence(r)) frames(r);
else for (const f of r.fields) if (f.secret && f.value) { f.value = ''; n++; }
}
for (const it of s.items || []) if (isSequence(it)) frames(it);
for (const q of s.sequences || []) frames(q);
}
return n;
}
// The ordered list a new sequence goes into for this kind of section.
export function sequenceList(section) {
if (section.kind === 'records') return section.records;
if (section.kind === 'text') return section.sequences || (section.sequences = []);
return section.items;
}
export function addSequence(doc, section, tabId = '') {
const q = { id: newId(doc, 'seq'), kind: 'sequence', title: 'New visual sequence', updated: today(), frames: [] };
if (tabId && section.kind === 'records') q.subsection = tabId;
sequenceList(section).push(q);
touch(doc, q);
return q;
}
export function addFrame(seq, image = '', layout = 'under') {
const f = { image, text: '', layout };
seq.frames.push(f);
return f;
}
// ---- credential references from steps (issue #24) ----
// Every record in the document, wherever it sits (sequences are not records).
export function allRecordsIn(doc) {
return doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r)));
}
// A field gets an id the first time something references it. Returns it.
export function ensureFieldId(record, field) {
if (field.id) return field.id;
const taken = new Set(record.fields.map((f) => f.id).filter(Boolean));
let n = record.fields.length + 1;
while (taken.has('f' + n)) n++;
field.id = 'f' + n;
return field.id;
}
// { record, field } for a reference, or null if either is gone or the field is an image.
export function findFieldRef(doc, ref) {
const record = allRecordsIn(doc).find((r) => r.id === ref.record);
const field = record && record.fields.find((f) => f.id === ref.field && f.kind !== 'image');
return field ? { record, field } : null;
}
// Add a reference to `frame` for `field` of `record`; no duplicates. Returns true if added.
export function addUse(frame, record, field) {
const ref = { record: record.id, field: ensureFieldId(record, field) };
frame.uses = frame.uses || [];
if (frame.uses.some((u) => u.record === ref.record && u.field === ref.field)) return false;
frame.uses.push(ref);
return true;
}
export function removeUse(frame, i) {
frame.uses.splice(i, 1);
if (!frame.uses.length) delete frame.uses;
}
// A step captured from the screen: a new frame, and the sequence remembers when,
// so the reader can be told the site may have changed since.
export function addCapture(seq, image) {
const f = addFrame(seq, image);
seq.captured = today();
return f;
}
// Merge a captured walkthrough ({ title, captured, frames: [{ image }] }) from a capture
// bundle (issue #28) into `section`, as a new visual sequence. Returns the sequence.
export function importWalkthrough(doc, section, wt, tabId = '') {
const q = addSequence(doc, section, tabId);
q.title = String(wt.title || '').trim() || 'Captured walkthrough';
q.captured = wt.captured;
for (const f of wt.frames) addFrame(q, f.image);
return q;
}
// ---- what a section holds (for the delete confirmation) ----
export function sectionContents(section) {
const c = { records: 0, items: 0, sequences: 0, images: 0, text: false };
const countFrames = (q) => { for (const f of q.frames) if (f.image) c.images++; };
for (const r of section.records || []) {
if (isSequence(r)) { c.sequences++; countFrames(r); } else {
c.records++;
for (const f of r.fields) if (f.kind === 'image' && f.value) c.images++;
}
}
for (const it of section.items || []) { if (isSequence(it)) { c.sequences++; countFrames(it); } else c.items++; }
for (const q of section.sequences || []) { c.sequences++; countFrames(q); }
c.text = section.kind === 'text' && !!String(section.body || '').trim();
return c;
}
export function deleteSectionMessage(section) {
const c = sectionContents(section);
const n = (k, one, many) => (k ? [k + ' ' + (k === 1 ? one : many)] : []);
const parts = [...n(c.records, 'record', 'records'), ...n(c.items, 'item', 'items'),
...n(c.sequences, 'visual sequence', 'visual sequences'), ...n(c.images, 'image', 'images'), ...(c.text ? ['its text'] : [])];
const name = '"' + section.title + '"';
if (!parts.length) return 'Delete the empty section ' + name + '?';
return 'Delete the section ' + name + ' and everything in it (' + parts.join(', ') + ')? This cannot be undone with Cancel.';
}
// ---- sub-tabs of a records section ----
// A tab id of '' is the General catch-all; the rest are section.subsections ids.
export const hasTabs = (section) => !!(section.subsections && section.subsections.length);
// [{id, title}] in display order, General first; [] when the section has no sub-tabs.
export function tabsOf(section) {
if (!hasTabs(section)) return [];
return [{ id: '', title: section.generalTitle || GENERAL_TITLE }, ...section.subsections.map((t) => ({ id: t.id, title: t.title }))];
}
// Which tab an entry (record or sequence) is in. A missing or dangling id means General.
export function entryTab(section, e) {
return e.subsection && (section.subsections || []).some((t) => t.id === e.subsection) ? e.subsection : '';
}
// The tab to show: `wanted` if it still exists, else General.
export function validTab(section, wanted) {
return wanted && (section.subsections || []).some((t) => t.id === wanted) ? wanted : '';
}
// Entries of the section's list that are in a tab, as [{e, i}] (i = index in the list).
export function entriesInTab(section, tabId) {
const out = [];
section.records.forEach((e, i) => { if (entryTab(section, e) === tabId) out.push({ e, i }); });
return out;
}
// Index of the nearest element before (dir -1) / after (+1) arr[i] satisfying `same`, or -1.
export function siblingIndex(arr, i, dir, same = () => true) {
for (let j = i + dir; j >= 0 && j < arr.length; j += dir) if (same(arr[j])) return j;
return -1;
}
// Move arr[i] past its nearest neighbour for which `same` holds. Returns true if it moved.
export function moveWithin(arr, i, dir, same) {
const j = siblingIndex(arr, i, dir, same);
if (j < 0) return false;
[arr[i], arr[j]] = [arr[j], arr[i]];
return true;
}
export function addSubsection(doc, section, title) {
const t = { id: newId(doc, 'sub'), title: String(title).trim() };
(section.subsections || (section.subsections = [])).push(t);
touch(doc);
return t;
}
export function moveSubsection(section, id, dir) {
const i = (section.subsections || []).findIndex((t) => t.id === id);
return i < 0 ? false : move(section.subsections, i, dir);
}
// Rename a tab; '' is the General tab. Refuses an empty name.
export function renameTab(section, id, title) {
const name = String(title).trim();
if (!name) return false;
if (id === '') section.generalTitle = name;
else { const t = (section.subsections || []).find((x) => x.id === id); if (!t) return false; t.title = name; }
return true;
}
// Put a record or sequence in a tab ('' = General).
export function moveToTab(section, e, tabId) {
if (tabId && !(section.subsections || []).some((t) => t.id === tabId)) return false;
if (tabId) e.subsection = tabId; else delete e.subsection;
return true;
}
// Delete a tab. Its records and sequences fall back to General (nothing is lost).
// With no sub-tabs left, the section goes back to a plain list.
export function removeSubsection(section, id) {
const i = (section.subsections || []).findIndex((t) => t.id === id);
if (i < 0) return false;
for (const e of section.records) if (e.subsection === id) delete e.subsection;
section.subsections.splice(i, 1);
if (!section.subsections.length) { delete section.subsections; delete section.generalTitle; }
return true;
}
export function deleteSubsectionMessage(section, id) {
const t = section.subsections.find((x) => x.id === id);
const n = entriesInTab(section, id).length;
const where = '"' + (section.generalTitle || GENERAL_TITLE) + '"';
return 'Delete the sub-tab "' + t.title + '"?' + (n ? ' Its ' + n + (n === 1 ? ' entry moves' : ' entries move') + ' to ' + where + '.' : '');
}
// What to print for a records section: [{title, entries}]. Without sub-tabs one group with
// a null title; with them, one group per tab that has entries.
export function printGroups(section) {
if (!hasTabs(section)) return [{ title: null, entries: section.records }];
return tabsOf(section)
.map((t) => ({ title: t.title, entries: entriesInTab(section, t.id).map((x) => x.e) }))
.filter((g) => g.entries.length);
}