Compare commits

...

6 Commits

12 changed files with 585 additions and 19 deletions

View File

@@ -65,6 +65,9 @@ A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text wit
- **Sub-tabs:** `ops.js` holds the pure logic (`tabsOf`, `entriesInTab`, `moveToTab`, `moveWithin`, `removeSubsection`, `printGroups`). The records stay in one array, and the tab bar filters them. The shown tab is in `state.tabs` (not saved). Up/down moves a record past its nearest neighbour in the same tab. Deleting a tab sends its records to General. Print writes one sub-heading per non-empty tab.
- **Images:** drag and drop, clipboard paste and file picker all feed `importFiles()`. Files are sniffed by their first bytes, downscaled to at most 1600 px and re-encoded, which strips metadata, and stored as data URLs with a limit of about 3 MB each.
- **Walkthroughs (issue #23):** a sequence frame may carry `ifStuck` text and a `stop` flag, and a sequence a `captured` date. In Edit, "Capture from screen…" uses `getDisplayMedia` (`startScreenCapture`, `grabScreenFrame`, `stopScreenCapture` in `images.js`; the stream lives in a closure variable in `app.js`, ended when leaving edit mode) and adds frames via `addCapture()` in `ops.js`. In view mode `state.walk` (`{id, k}`, not saved) shows a sequence one step at a time (`walkSequence`).
- **Credential references (issue #24):** a frame's `uses: [{record, field}]` points at record fields by id. A field gets an `id` the first time it is referenced (`ensureFieldId`, `addUse`, `findFieldRef`, `allRecordsIn` in `ops.js`). A dangling reference is shown as removed, never a validation error. `viewUses` and `copyValue` (30 s clipboard wipe) are in `app.js`; `usesView` in `print.js` does the masked/included print text.
- **Annotation (issue #25):** a frame's `marks` are `{type:'marker',x,y}` or `{type:'box',x,y,w,h}` as fractions of the picture (`isMark`, `normRect` in `images.js`). `markedImage()` in `app.js` wraps a step's `<img>` in a `.marked` box and lays CSS overlays over it, so the same marks work in the list, player, lightbox and print. `openAnnotator()` is a canvas dialog; Blur out runs `pixelateRegion()` (pure, in `images.js`) on the pixels and `Apply` re-encodes the picture, so no unblurred copy is stored. Marks are dropped when the picture is replaced, removed or erased by `clearSecrets`.
- **Reset (`?reset=1`):** opening the file with `?reset=1` or `#reset=1` shows a banner after unlock offering to erase every secret-flagged field value and secret frame (`clearSecrets()` in `ops.js`, count from `countSecrets`). Labels, structure and flags stay. It is read live (`resetRequested()`), with a `hashchange` listener to re-offer, and `state.resetOffered` dismisses it. Nothing is written until Save, so make a Backup copy first. It's meant for working on layout on a less safe machine.
**Save.** Uses the File System Access API (`showSaveFilePicker`, handle reused) where available, otherwise a Blob download. `assemble()` rebuilds the full HTML from the page's own CSS and JS plus a fresh encrypted payload. "Backup copy" downloads `final-wishes-YYYYMMDD.html`.

View File

@@ -160,6 +160,41 @@ not part of a record or item, so it sits exactly where you put it.
- **Secret** (per step) hides both the picture and the text behind Show/Hide
and withholds it from a masked print. Steps are numbered 1, 2, 3… in view
and in print, and a step is kept on one page.
- **Capture from the screen:** in Edit, **Capture from screen…** asks the
browser to share a window or tab (nothing is recorded or sent anywhere).
Log in to the site yourself, get to the screen you want, come back to this
page and click **Capture step**. Each click adds one step with that picture;
repeat for each screen, then **Stop sharing** (it also stops when you leave
Edit). Account numbers and balances in a screenshot are real data: mark the
step **secret**, or capture a screen before they appear. Works in Chrome,
Edge and Firefox opened from a file. Pasting a screenshot still works too.
- **If it looks different or fails:** each step has an optional note for what
to do when the screen is not what the picture shows (who to call, what to
say). Tick **Stop here** to tell the reader not to go further without help.
Both show in the list, the walkthrough and print, and are hidden with a
secret step.
- **Mark up a picture:** in Edit, **Mark up picture…** under a step's image
opens an editor. **Marker** (click) drops a numbered circle where the reader
should click; **Box** (drag) outlines something to look at; **Blur out**
(drag) pixelates anything private, such as account numbers and balances.
**Undo** steps back, **Apply** keeps it. Markers and boxes are overlays you can
change later (they show in the list, walkthrough, enlarged view and print).
**Blur is different: it is baked into the picture when you Apply**, so no
readable copy is kept, and it cannot be undone after you Save. Replacing or
removing a step's picture drops its markers and boxes, since they would no
longer line up.
- **Credentials a step needs:** in Edit, each step has **+ Use a field from a
record…**. Pick the login fields (say Santander's username and password) and
the step shows them beside the picture, live from the record, so there is one
copy to keep current. A secret stays masked until **Show**; **Copy** puts the
value on the clipboard without showing it (the clipboard is wiped after 30
seconds, which also replaces anything else copied in that time). Print shows
them too, masked unless you choose "Include secrets". If the record or field is
later deleted the step says the credential was removed. Renaming or
reordering fields is safe: the link is to the field itself.
- **Walkthrough:** in view mode, **Walk through, one step at a time** shows one
step with Back / Next. A sequence made from captures shows its capture date
and a reminder that the site may have changed since.
- Files saved with sequences cannot be opened by older builds; opening an
older file in a newer build (see below) still works. **Cancel** and the
other editing rules work the same as for records.

View File

@@ -13,6 +13,7 @@
pwChanged: false, // passphrase changed since the last save
tabs: {}, // section id -> id of the sub-tab being shown ('' = General); not saved
collapsed: new Set(), // ids of records folded to just their title (view mode only)
walk: null, // { id, k }: the visual sequence shown as a one-step-at-a-time walkthrough (not saved)
revealed: new WeakSet(), // secret field objects currently shown
blob: null, // encrypted payload taken from a file the user chose to open
handle: null, // File System Access handle once the user picked a save location
@@ -157,6 +158,49 @@
const allRecords = () => state.doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r)));
const addFrameFrom = (seq) => (name, url) => addFrame(seq, url);
// Copy a credential for the reader, then wipe the clipboard after 30 seconds
// (this overwrites whatever is on the clipboard by then, whether or not it is ours).
let clipTimer = null;
async function copyValue(fld) {
try {
await navigator.clipboard.writeText(fld.value);
clearTimeout(clipTimer);
clipTimer = setTimeout(() => { navigator.clipboard.writeText('').catch(() => {}); }, 30000);
setStatus('Copied ' + fld.label + '. The clipboard is cleared in 30 seconds.');
} catch {
setStatus('Could not copy ' + fld.label + '. Show it and copy it by hand.');
}
}
// Screen capture while editing a visual sequence. The stream lives here, not in
// the DOM, so it survives render(). { stream, video, seqId } or null.
let capture = null;
function endCapture() { stopScreenCapture(capture); capture = null; }
async function beginCapture(q) {
endCapture();
try {
const cap = await startScreenCapture();
cap.seqId = q.id;
cap.stream.getVideoTracks()[0].onended = () => { if (capture === cap) { capture = null; setStatus('Screen sharing ended.'); render(); } };
capture = cap;
setStatus('Sharing. Get the site to the screen you want, come back here and click Capture step.');
} catch (err) {
setStatus(err.message);
}
render();
}
async function captureStep(q) {
try {
const url = await processImageFile(await grabScreenFrame(capture));
addCapture(q, url);
changed(q); // clears the status, so set it afterwards
setStatus('Step ' + q.frames.length + ' captured.');
} catch (err) {
setStatus(err.message);
}
render();
}
// Add each file as a new image field on `rec`, or put the first into
// `opts.replace` (an existing image field). Per-file problems are reported
// together; the files that worked are still kept.
@@ -170,7 +214,7 @@
for (const file of files) {
try {
const url = await processImageFile(file);
if (opts.replace && !added) opts.replace[key] = url;
if (opts.replace && !added) { opts.replace[key] = url; if (key === 'image') delete opts.replace.marks; }
else add(file.name, url);
added++;
} catch (err) {
@@ -211,9 +255,117 @@
importFiles(rec, files, { replace: field && field.kind === 'image' ? field : null, pasted: true });
});
function openLightbox(label, src) {
// A step's picture with its markers and boxes laid over it. Positions are fractions
// of the picture, so they stay put at any size, in print too.
function markedImage(img, marks) {
if (!marks || !marks.length) return img;
let n = 0;
return h('div', { class: 'marked' }, img, marks.map((m) => (m.type === 'box'
? h('span', { class: 'mbox', 'aria-hidden': 'true', style: 'left:' + m.x * 100 + '%;top:' + m.y * 100 + '%;width:' + m.w * 100 + '%;height:' + m.h * 100 + '%' })
: h('span', { class: 'mpin', 'aria-hidden': 'true', style: 'left:' + m.x * 100 + '%;top:' + m.y * 100 + '%' }, String(++n)))));
}
// Mark up a step's picture: numbered markers and highlight boxes (kept as overlays, editable
// later) and Blur out (burned into the pixels on Apply, so no readable copy is kept).
async function openAnnotator(q, f) {
const img = new Image();
img.src = f.image;
try { await img.decode(); } catch { return setStatus('That image could not be opened.'); }
const W = img.naturalWidth, H = img.naturalHeight;
const base = document.createElement('canvas');
base.width = W; base.height = H;
const bctx = base.getContext('2d', { willReadFrequently: true });
bctx.drawImage(img, 0, 0);
const marks = structuredClone(f.marks || []);
const undo = [];
let tool = 'marker', blurs = 0, drag = null;
const view = h('canvas', { class: 'annot', width: W, height: H, 'aria-label': 'Picture to mark up' });
const vctx = view.getContext('2d');
const lw = Math.max(3, Math.round(W / 300)), pr = Math.max(14, Math.round(W / 60));
function draw() {
vctx.drawImage(base, 0, 0);
let n = 0;
for (const m of marks) {
if (m.type === 'box') {
vctx.strokeStyle = '#e11'; vctx.lineWidth = lw;
vctx.strokeRect(m.x * W, m.y * H, m.w * W, m.h * H);
} else {
vctx.beginPath(); vctx.arc(m.x * W, m.y * H, pr, 0, 2 * Math.PI);
vctx.fillStyle = '#e11'; vctx.fill(); vctx.lineWidth = 2; vctx.strokeStyle = '#fff'; vctx.stroke();
vctx.fillStyle = '#fff'; vctx.font = '700 ' + Math.round(pr * 1.2) + 'px system-ui, sans-serif';
vctx.textAlign = 'center'; vctx.textBaseline = 'middle'; vctx.fillText(String(++n), m.x * W, m.y * H + 1);
}
}
if (drag) {
const r = normRect(drag.x0, drag.y0, drag.x1, drag.y1, 0);
if (r) {
vctx.setLineDash([8, 6]); vctx.lineWidth = lw; vctx.strokeStyle = tool === 'blur' ? '#000' : '#e11';
vctx.strokeRect(r.x * W, r.y * H, r.w * W, r.h * H); vctx.setLineDash([]);
}
}
}
const at = (e) => {
const b = view.getBoundingClientRect();
return { x: Math.min(1, Math.max(0, (e.clientX - b.left) / b.width)), y: Math.min(1, Math.max(0, (e.clientY - b.top) / b.height)) };
};
view.addEventListener('pointerdown', (e) => {
const p = at(e);
if (tool === 'marker') { marks.push({ type: 'marker', x: p.x, y: p.y }); undo.push(() => marks.pop()); draw(); return; }
view.setPointerCapture(e.pointerId);
drag = { x0: p.x, y0: p.y, x1: p.x, y1: p.y };
});
view.addEventListener('pointermove', (e) => { if (drag) { const p = at(e); drag.x1 = p.x; drag.y1 = p.y; draw(); } });
view.addEventListener('pointerup', (e) => {
if (!drag) return;
const p = at(e);
const r = normRect(drag.x0, drag.y0, p.x, p.y);
drag = null;
if (r && tool === 'box') {
marks.push({ type: 'box', x: r.x, y: r.y, w: r.w, h: r.h }); undo.push(() => marks.pop());
} else if (r && tool === 'blur') {
const snap = bctx.getImageData(0, 0, W, H);
const id = bctx.getImageData(0, 0, W, H);
pixelateRegion(id.data, W, H, { x: r.x * W, y: r.y * H, w: r.w * W, h: r.h * H });
bctx.putImageData(id, 0, 0);
blurs++; undo.push(() => { bctx.putImageData(snap, 0, 0); blurs--; });
}
draw();
});
const tools = [['marker', 'Marker (click)'], ['box', 'Box (drag)'], ['blur', 'Blur out (drag)']];
const radios = tools.map(([v, t]) => h('label', { class: 'radio' },
h('input', { type: 'radio', name: 'annot-tool', value: v, checked: v === tool, onchange: () => { tool = v; } }), ' ' + t));
const dlg = h('dialog', { class: 'card annotator', 'aria-label': 'Mark up picture' },
h('h3', {}, 'Mark up this picture'),
h('p', { class: 'muted small' }, 'Marker: click where the reader should click. Box: drag around something to point at. Blur out: drag over anything private, such as account numbers or balances. Blur is permanent once you Apply and Save; markers and boxes can be changed later.'),
h('div', { class: 'row' }, radios,
btn('Undo', () => { const u = undo.pop(); if (u) { u(); draw(); } }, 'small'),
btn('Clear markers and boxes', () => { if (!marks.length) return; const copy = marks.splice(0); undo.push(() => marks.push(...copy)); draw(); }, 'small')),
view,
h('div', { class: 'row' },
btn('Cancel', () => dlg.close()),
btn('Apply', () => {
if (blurs > 0) {
let url = base.toDataURL(f.image.startsWith('data:image/png') ? 'image/png' : 'image/jpeg', JPEG_QUALITY);
if (!isImageDataUrl(url)) url = base.toDataURL('image/jpeg', JPEG_QUALITY);
if (!isImageDataUrl(url)) return setStatus('The blurred picture is too large to keep.');
f.image = url;
}
if (marks.length) f.marks = marks; else delete f.marks;
changed(q); // clears the status, so set it afterwards
setStatus(blurs > 0 ? 'Picture marked up and blurred. Save to keep it.' : 'Markers and boxes updated.');
dlg.close(); render();
}, 'primary')));
dlg.addEventListener('close', () => dlg.remove());
document.body.append(dlg);
dlg.showModal();
draw();
}
function openLightbox(label, src, marks) {
const dlg = h('dialog', { class: 'card lightbox', 'aria-label': label },
h('h3', {}, label), h('img', { class: 'bigimg', src, alt: label }),
h('h3', {}, label), markedImage(h('img', { class: 'bigimg', src, alt: label }), marks),
h('div', { class: 'row' }, btn('Close', () => dlg.close(), 'primary')));
dlg.addEventListener('close', () => dlg.remove());
document.body.append(dlg);
@@ -304,18 +456,59 @@
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); } })
f.image ? markedImage(h('img', { class: 'fimg', src: f.image, alt: label, tabIndex: 0, title: 'Click to enlarge',
onclick: () => openLightbox(label, f.image, f.marks), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(label, f.image, f.marks); } }), f.marks)
: h('span', { class: 'muted' }, '(no image)'),
layout !== 'none' ? h('p', { class: 'ftext' }, f.text) : null,
viewUses(f),
f.stop || String(f.ifStuck || '').trim() ? h('div', { class: 'fnotes' },
f.stop ? h('p', { class: 'fstop' }, h('strong', {}, 'Stop here. Do not go further.')) : null,
String(f.ifStuck || '').trim() ? h('p', { class: 'fstuck' }, h('strong', {}, 'If it looks different or fails: '), f.ifStuck) : null) : null,
f.secret ? btn('Hide', toggle, 'link', { 'aria-label': 'Hide ' + label }) : null]);
}
// The credentials a step needs, live from their records: secrets stay masked until shown.
function viewUses(f) {
if (!f.uses || !f.uses.length) return null;
return h('div', { class: 'fuses' }, h('strong', {}, 'You will need:'), f.uses.map((u) => {
const hit = findFieldRef(state.doc, u);
if (!hit) return h('p', { class: 'muted' }, '(a credential this step used has been removed)');
const fld = hit.field;
const shown = !fld.secret || state.revealed.has(fld);
const toggle = () => { state.revealed[shown ? 'delete' : 'add'](fld); render(); };
return h('div', { class: 'row fuse' },
h('span', {}, hit.record.title + ' \u203A ' + fld.label + ': '),
h('span', { class: fld.secret ? 'secret' : '' }, !fld.value ? '(not set)' : shown ? fld.value : '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022'),
fld.secret ? btn(shown ? 'Hide' : 'Show', toggle, 'link', { 'aria-label': (shown ? 'Hide ' : 'Show ') + fld.label }) : null,
fld.value ? btn('Copy', () => copyValue(fld), 'small', { 'aria-label': 'Copy ' + fld.label }) : null);
}));
}
const capturedNote = (q) => (q.captured ? ' Captured ' + q.captured + '. The site may have changed since.' : '');
// One step at a time, with Back/Next. A secret step stays hidden until shown, as in the list.
function walkSequence(q) {
const n = q.frames.length;
const k = Math.max(0, Math.min(state.walk.k, n - 1));
const go = (to) => () => { state.walk = { id: q.id, k: to }; render(); };
return h('article', { class: 'card seq walk', 'data-seq': q.id },
h('h3', {}, q.title),
viewFrame(q, q.frames[k], k),
h('div', { class: 'row walknav' },
btn('\u2190 Back', go(k - 1), '', { disabled: k === 0 }),
h('span', { class: 'muted', role: 'status' }, 'Step ' + (k + 1) + ' of ' + n),
btn('Next \u2192', go(k + 1), 'primary', { disabled: k === n - 1 }),
btn('Show all steps', () => { state.walk = null; render(); }, 'link')),
h('p', { class: 'muted small' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
}
function viewSequence(q) {
if (state.walk && state.walk.id === q.id && q.frames.length) return walkSequence(q);
return h('article', { class: 'card seq' },
h('h3', {}, q.title),
q.frames.length ? btn('Walk through, one step at a time', () => { state.walk = { id: q.id, k: 0 }; render(); }, 'small') : null,
q.frames.length ? h('div', { class: 'frames' }, q.frames.map((f, k) => viewFrame(q, f, k))) : h('p', { class: 'muted' }, '(no steps yet)'),
h('p', { class: 'muted small' }, 'Updated ' + q.updated));
h('p', { class: 'muted small' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
}
const seqItem = (q) => h('li', { class: 'seqitem' }, viewSequence(q));
@@ -376,7 +569,7 @@
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,
obj[key] ? markedImage(h('img', { class: 'fimg', src: obj[key], alt: label }), key === 'image' ? obj.marks : null) : null,
h('p', { class: 'muted small' }, obj[key]
? formatBytes(dataUrlBytes(obj[key])) + '. Drop, paste or choose a file to replace it.'
: 'Drop an image here, paste one while this box is selected, or choose a file.'),
@@ -464,16 +657,46 @@
const LAYOUT_LABELS = [['right', 'Text right of image'], ['under', 'Text under image'], ['none', 'No text']];
// Pick the record fields this step needs; the reader sees them beside the step.
function useEditor(q, f, k) {
const recs = allRecords().filter((r) => r.fields.some((x) => x.kind !== 'image'));
const pick = h('select', { 'aria-label': 'Add a credential to step ' + (k + 1), onchange: () => {
if (!pick.value) return;
const [rid, idx] = pick.value.split('|');
const rec = recs.find((r) => r.id === rid);
if (rec && addUse(f, rec, rec.fields[Number(idx)])) { changed(q); render(); }
} },
h('option', { value: '' }, '+ Use a field from a record\u2026'),
recs.map((r) => h('optgroup', { label: r.title }, r.fields.map((x, i) => (x.kind === 'image' ? null
: h('option', { value: r.id + '|' + i }, x.label + (x.secret ? ' (secret)' : '')))))));
return h('div', {},
h('strong', {}, 'Credentials this step needs'),
(f.uses || []).map((u, i) => {
const hit = findFieldRef(state.doc, u);
return h('div', { class: 'row' },
h('span', {}, hit ? hit.record.title + ' \u203A ' + hit.field.label : '(removed)'),
btn('\u2715', () => { removeUse(f, i); changed(q); render(); }, 'icon danger', { 'aria-label': 'Remove credential from step ' + (k + 1) }));
}),
pick);
}
function editFrame(q, f, k) {
const secret = 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 stop = h('input', { type: 'checkbox', checked: !!f.stop, 'aria-label': 'Stop here, step ' + (k + 1),
onchange: () => { f.stop = stop.checked || undefined; if (!f.stop) delete f.stop; changed(q); } });
const layout = h('select', { 'aria-label': 'Text position for step ' + (k + 1), onchange: () => { f.layout = layout.value; changed(q); render(); } },
LAYOUT_LABELS.map(([v, t]) => h('option', { value: v, selected: f.layout === v }, t)));
return h('div', { class: 'field imagefield frameedit' },
h('div', { class: 'row' }, h('strong', {}, 'Step ' + (k + 1)), layout, 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)));
(files) => importFiles(q, files, { key: 'image', replace: f, add: addFrameFrom(q) }), () => { if (!f.image) delete f.marks; changed(q); }),
f.image ? h('div', { class: 'row' }, btn('Mark up picture\u2026', () => openAnnotator(q, f), 'small', { 'aria-label': 'Mark up the picture for step ' + (k + 1) }),
f.marks && f.marks.length ? h('span', { class: 'muted small' }, f.marks.length + (f.marks.length === 1 ? ' marker or box' : ' markers and boxes')) : null) : null,
f.layout === 'none' ? null : h('label', {}, 'Text', input(f, 'text', { multiline: true, label: 'Text for step ' + (k + 1) }, q)),
useEditor(q, f, k),
h('label', {}, 'If it looks different or fails', input(f, 'ifStuck', { multiline: true, label: 'If step ' + (k + 1) + ' looks different or fails' }, q)),
h('label', { class: 'check' }, stop, ' Stop here: the reader must not go further without help'));
}
function editSequence(list, q, i, s) {
@@ -487,7 +710,10 @@
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));
btn('+ Add images\u2026', () => picker.click(), 'small'), picker,
capture && capture.seqId === q.id
? [btn('Capture step', () => captureStep(q), 'primary small'), btn('Stop sharing', () => { endCapture(); setStatus('Stopped sharing.'); render(); }, 'small')]
: btn('Capture from screen\u2026', () => beginCapture(q), 'small', { title: 'Share the window with the site, then capture each screen you want as a step' })));
}
const addSeqBtn = (s) => btn('+ Add visual sequence', () => { addSequence(state.doc, s, s.kind === 'records' ? currentTab(s) : ''); markDirty(); render(); }, 'primary');
@@ -570,14 +796,19 @@
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) })
: v.image ? markedImage(h('img', { class: 'pimg', src: v.image, alt: 'Step ' + (k + 1) }), f.marks)
: h('p', {}, '(no image)'),
v.layout !== 'none' ? h('p', { class: 'pftext' }, v.text) : null);
v.layout !== 'none' ? h('p', { class: 'pftext' }, v.text) : null,
v.withheld ? null : usesView(state.doc, f, includeSecrets).map((u) => h('p', { class: 'pftext' },
u.missing ? '(a credential this step used has been removed)' : 'You will need: ' + u.record + ' \u203A ' + u.label + ': ' + u.value)),
v.stop ? h('p', { class: 'pstop' }, h('strong', {}, 'STOP HERE. Do not go further.')) : null,
v.ifStuck ? h('p', { class: 'pftext' }, h('strong', {}, 'If it looks different or fails: '), v.ifStuck) : null);
}
function printSequence(q, includeSecrets) {
return h('div', { class: 'pseq' },
h('h3', {}, q.title),
q.captured ? h('p', { class: 'pftext' }, 'Captured ' + q.captured + '. The site may have changed since.') : null,
q.frames.map((f, k) => printFrame(f, k, includeSecrets)));
}
@@ -782,6 +1013,7 @@
}
function render() {
if (capture && !state.editing) endCapture(); // sharing only lasts while editing
root.replaceChildren();
if (!state.doc) return root.append(renderStart());
const onHeader = state.current === HEADER_ID;

View File

@@ -85,3 +85,92 @@ export async function processImageFile(blob) {
if (bmp.close) bmp.close();
}
}
// Browser only. Screen capture for building a walkthrough: the user shares a
// window or tab, then each grab is one frame. Nothing is recorded or sent anywhere.
export async function startScreenCapture() {
if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
throw new Error('This browser cannot capture the screen. Take a screenshot and paste it instead.');
}
let stream;
try {
stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false });
} catch (err) {
throw new Error(err && err.name === 'NotAllowedError' ? 'Screen sharing was cancelled.' : 'Screen sharing could not start.');
}
const video = document.createElement('video');
video.srcObject = stream;
video.muted = true;
await video.play();
return { stream, video };
}
export function stopScreenCapture(cap) {
if (cap && cap.stream) cap.stream.getTracks().forEach((t) => t.stop());
}
// The current picture of a started capture, as a PNG blob.
export function grabScreenFrame(cap) {
const v = cap.video;
if (!v.videoWidth || !v.videoHeight) return Promise.reject(new Error('The shared window has no picture yet. Try again in a moment.'));
const canvas = document.createElement('canvas');
canvas.width = v.videoWidth;
canvas.height = v.videoHeight;
canvas.getContext('2d').drawImage(v, 0, 0);
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('Could not grab the picture.'))), 'image/png'));
}
// ---- annotation helpers (issue #25), pure ----
// Marks sit on a frame's picture as fractions of its width and height (0..1), so they
// stay in place however the picture is scaled:
// { type: 'marker', x, y } a numbered circle centred on the point
// { type: 'box', x, y, w, h } a highlight rectangle (x, y = top-left)
// Blur is NOT a mark: it is burned into the picture's pixels (pixelateRegion), so no
// unblurred copy is kept.
export const MARK_TYPES = ['marker', 'box'];
const clamp01 = (v) => Math.min(1, Math.max(0, v));
// A rectangle from two corners (any order), clamped to the picture. null if it is
// too small to mean anything (a stray click).
export function normRect(x0, y0, x1, y1, min = 0.01) {
const ax = clamp01(Math.min(x0, x1)), ay = clamp01(Math.min(y0, y1));
const bx = clamp01(Math.max(x0, x1)), by = clamp01(Math.max(y0, y1));
const w = bx - ax, h = by - ay;
return w < min || h < min ? null : { x: ax, y: ay, w, h };
}
export function isMark(m) {
if (!m || typeof m !== 'object' || !MARK_TYPES.includes(m.type)) return false;
const frac = (v) => typeof v === 'number' && v >= 0 && v <= 1;
if (!frac(m.x) || !frac(m.y)) return false;
if (m.type === 'marker') return true;
return frac(m.w) && frac(m.h) && m.w > 0 && m.h > 0 && m.x + m.w <= 1.0001 && m.y + m.h <= 1.0001;
}
// Block size for blurring a region: coarse enough that small text cannot be read back.
export function blurBlock(w, h) {
return Math.max(12, Math.round(Math.min(w, h) / 3));
}
// Replace each block of rect {x,y,w,h} (pixels) in RGBA `data` (width x height) with its
// average colour, in place. Pixels outside the rectangle are untouched.
export function pixelateRegion(data, width, height, rect, block = blurBlock(rect.w, rect.h)) {
const x0 = Math.max(0, Math.floor(rect.x)), y0 = Math.max(0, Math.floor(rect.y));
const x1 = Math.min(width, Math.ceil(rect.x + rect.w)), y1 = Math.min(height, Math.ceil(rect.y + rect.h));
for (let by = y0; by < y1; by += block) {
for (let bx = x0; bx < x1; bx += block) {
const ex = Math.min(bx + block, x1), ey = Math.min(by + block, y1);
let r = 0, g = 0, b = 0, a = 0, n = 0;
for (let y = by; y < ey; y++) for (let x = bx; x < ex; x++) {
const i = (y * width + x) * 4;
r += data[i]; g += data[i + 1]; b += data[i + 2]; a += data[i + 3]; n++;
}
if (!n) continue;
r = Math.round(r / n); g = Math.round(g / n); b = Math.round(b / n); a = Math.round(a / n);
for (let y = by; y < ey; y++) for (let x = bx; x < ex; x++) {
const i = (y * width + x) * 4;
data[i] = r; data[i + 1] = g; data[i + 2] = b; data[i + 3] = a;
}
}
}
}

View File

@@ -1,4 +1,4 @@
import { isImageDataUrl, MAX_IMAGE_DATA_CHARS } from './images.js';
import { isImageDataUrl, MAX_IMAGE_DATA_CHARS, isMark } from './images.js';
// Data model for the document (plaintext JSON before encryption).
// Pure functions, no DOM; runs in browsers and Node. build.js strips `export`.
@@ -29,7 +29,17 @@ import { isImageDataUrl, MAX_IMAGE_DATA_CHARS } from './images.js';
// Item: { id, text, status: 'open'|'done'|'tbd', detail?: string }
// Sequence (visual sequence): { id, kind: 'sequence', title, updated: 'YYYY-MM-DD',
// frames: [Frame] } -- a numbered series of pictures with optional text.
// Frame: { image: PNG/JPEG data URL or '', text, layout: 'right'|'under'|'none', secret?: boolean }
// Frame: { image: PNG/JPEG data URL or '', text, layout: 'right'|'under'|'none', secret?: boolean,
// ifStuck?: string, what to do if the screen looks different or the step fails
// stop?: boolean, "stop here and call someone" marker; ifStuck says who/why
// marks?: [Mark] overlay on the picture: { type:'marker', x, y } or
// { type:'box', x, y, w, h }, all fractions 0..1 of the picture
// uses?: [{ record: <record id>, field: <field id> }] credentials this step needs,
// shown beside the step with Show/Hide and Copy. A reference
// that no longer resolves is shown as missing, never an error.
// A record Field may carry `id` (unique within its record): assigned the first time a step
// references it, so the reference survives reordering and renaming the field.
// A sequence may also carry `captured: 'YYYY-MM-DD'`, set when a step is captured from the screen.
// A sequence lives in the same ordered list as the records (records sections) or
// items (steps / checklist sections), so it sits wherever the user puts it, but it
// is not a record or an item (no number, no tick box). A 'text' section keeps its
@@ -165,12 +175,18 @@ export function validate(doc) {
if (!DATE_RE.test(r.updated ?? '')) errs.push(`${where}: updated must be YYYY-MM-DD`);
if (r.notes !== undefined && !isStr(r.notes)) errs.push(`${where}: notes must be a string`);
if (!Array.isArray(r.fields)) return errs.push(`${where}: fields must be an array`);
const fieldIds = new Set();
r.fields.forEach((f, k) => {
const fw = `${where}.fields[${k}]`;
if (!isObj(f)) return errs.push(`${fw}: must be an object`);
if (!isStr(f.label) || !f.label) errs.push(`${fw}: missing label`);
if (!isStr(f.value)) errs.push(`${fw}: value must be a string`);
if (f.secret !== undefined && typeof f.secret !== 'boolean') errs.push(`${fw}: secret must be a boolean`);
if (f.id !== undefined) {
if (!isStr(f.id) || !f.id) errs.push(`${fw}: id must be a non-empty string`);
else if (fieldIds.has(f.id)) errs.push(`${fw}: duplicate field id "${f.id}"`);
else fieldIds.add(f.id);
}
if (f.kind !== undefined && !FIELD_KINDS.includes(f.kind)) errs.push(`${fw}: unknown kind "${f.kind}"`);
if (f.kind === 'image' && isStr(f.value) && f.value !== '' && !isImageDataUrl(f.value)) {
errs.push(`${fw}: image must be a PNG or JPEG under ${Math.round(MAX_IMAGE_DATA_CHARS / 1e6)} MB`);
@@ -184,6 +200,7 @@ export function validate(doc) {
if (q.kind !== 'sequence') errs.push(`${where}: kind must be "sequence"`);
if (!isStr(q.title) || !q.title) errs.push(`${where}: missing title`);
if (!DATE_RE.test(q.updated ?? '')) errs.push(`${where}: updated must be YYYY-MM-DD`);
if (q.captured !== undefined && !DATE_RE.test(q.captured)) errs.push(`${where}: captured must be YYYY-MM-DD`);
if (!Array.isArray(q.frames)) return errs.push(`${where}: frames must be an array`);
q.frames.forEach((f, k) => {
const fw = `${where}.frames[${k}]`;
@@ -193,6 +210,18 @@ export function validate(doc) {
if (!isStr(f.text)) errs.push(`${fw}: text must be a string`);
if (!FRAME_LAYOUTS.includes(f.layout)) errs.push(`${fw}: bad layout "${f.layout}"`);
if (f.secret !== undefined && typeof f.secret !== 'boolean') errs.push(`${fw}: secret must be a boolean`);
if (f.ifStuck !== undefined && !isStr(f.ifStuck)) errs.push(`${fw}: ifStuck must be a string`);
if (f.stop !== undefined && typeof f.stop !== 'boolean') errs.push(`${fw}: stop must be a boolean`);
if (f.marks !== undefined) {
if (!Array.isArray(f.marks)) errs.push(`${fw}: marks must be an array`);
else f.marks.forEach((m, n) => { if (!isMark(m)) errs.push(`${fw}.marks[${n}]: not a valid marker or box`); });
}
if (f.uses !== undefined) {
if (!Array.isArray(f.uses)) errs.push(`${fw}: uses must be an array`);
else f.uses.forEach((u, m) => {
if (!isObj(u) || !isStr(u.record) || !u.record || !isStr(u.field) || !u.field) errs.push(`${fw}.uses[${m}]: needs record and field ids`);
});
}
});
}

View File

@@ -184,7 +184,7 @@ export function allSequences(doc) {
// 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())) { f.image = ''; f.text = ''; n++; } };
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);
@@ -217,6 +217,51 @@ export function addFrame(seq, image = '', layout = 'under') {
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;
}
// ---- what a section holds (for the delete confirmation) ----
export function sectionContents(section) {
const c = { records: 0, items: 0, sequences: 0, images: 0, text: false };

View File

@@ -46,19 +46,33 @@ export function frameLayout(frame) {
// What to show for a frame. A secret frame (picture and text) is withheld
// unless secrets are included; a frame with nothing in it is never "withheld".
export function frameView(frame, includeSecrets) {
const hasContent = !!(frame.image || String(frame.text || '').trim());
const hasContent = !!(frame.image || String(frame.text || '').trim() || String(frame.ifStuck || '').trim());
const withheld = !!frame.secret && !includeSecrets && hasContent;
return {
withheld,
image: withheld ? '' : frame.image,
text: withheld ? '' : frame.text,
ifStuck: withheld ? '' : String(frame.ifStuck || '').trim(),
stop: withheld ? false : !!frame.stop,
layout: withheld ? 'none' : frameLayout(frame),
};
}
// What a step's credential references show: [{ label, record, value, secret, missing }].
// A secret value is a placeholder unless includeSecrets; a reference that no longer
// resolves is marked missing. Uses displayValue so masking matches the rest of print.
export function usesView(doc, frame, includeSecrets) {
return (frame.uses || []).map((u) => {
const rec = doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r))).find((r) => r.id === u.record);
const f = rec && rec.fields.find((x) => x.id === u.field && x.kind !== 'image');
return f ? { label: f.label, record: rec.title, value: displayValue(f, includeSecrets), secret: !!f.secret, missing: false }
: { label: '', record: '', value: '', secret: false, missing: true };
});
}
export function countSecrets(doc) {
let n = 0;
const frames = (q) => { for (const f of q.frames) if (f.secret && (f.image || String(f.text || '').trim())) n++; };
const frames = (q) => { for (const f of q.frames) if (f.secret && (f.image || String(f.text || '').trim() || String(f.ifStuck || '').trim())) n++; };
for (const s of doc.sections) {
for (const r of s.records || []) {
if (isSequence(r)) frames(r);

View File

@@ -58,6 +58,15 @@ textarea { width: 100%; display: block; } label { display: block; margin-top: .5
.frame.right { grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); } .frame .fimg { margin: 0; }
.fnum { font-weight: 700; color: var(--accent); } .ftext { white-space: pre-wrap; margin: 0; }
li.seqitem { display: block; list-style: none; margin-left: -1.4rem; } .frameedit { border-top: 1px dashed var(--line); padding-top: .5rem; }
.fnotes { grid-column: 1 / -1; display: grid; gap: .35rem; } .fnotes p { margin: 0; }
.marked { position: relative; display: block; width: fit-content; max-width: 100%; line-height: 0; }
.mbox { position: absolute; box-sizing: border-box; border: 3px solid #e11; box-shadow: 0 0 0 1px #fff; border-radius: 3px; pointer-events: none; }
.mpin { position: absolute; box-sizing: border-box; transform: translate(-50%, -50%); width: 1.6rem; height: 1.6rem; border-radius: 50%; background: #e11; color: #fff; border: 2px solid #fff; font: 700 .85rem/1.2rem system-ui, sans-serif; text-align: center; pointer-events: none; }
.annotator { max-width: min(95vw, 70rem); } .annot { display: block; max-width: 100%; max-height: 65vh; margin: .5rem auto; cursor: crosshair; touch-action: none; border: 1px solid var(--line); }
.fuses { grid-column: 1 / -1; } .fuse { align-items: center; margin: .25rem 0; }
.fstop { border: 2px solid var(--danger); color: var(--danger); border-radius: .35rem; padding: .35rem .6rem; }
.fstuck { background: var(--warn-bg); color: var(--warn-fg); border-radius: .35rem; padding: .35rem .6rem; white-space: pre-wrap; }
.walk .fimg { max-height: 28rem; } .walknav { align-items: center; margin-top: .75rem; }
@media (max-width: 700px) { .frame.right { grid-template-columns: minmax(0, 1fr); } }
dialog.lightbox { max-width: 92vw; max-height: 92vh; overflow: auto; } .bigimg { display: block; max-width: 100%; max-height: 75vh; margin: 0 auto .75rem; background: #fff; }
@@ -101,6 +110,8 @@ dialog.lightbox { max-width: 92vw; max-height: 92vh; overflow: auto; } .bigimg {
.pframe { break-inside: avoid; display: grid; grid-template-columns: minmax(0, 1fr); gap: 3pt 12pt; align-items: start; margin: 0 0 10pt; }
.pframe.right { grid-template-columns: 3.9in minmax(0, 1fr); } .pframe.right .pimg { max-height: 3.4in; }
.pfnum { grid-column: 1 / -1; font: 700 9.5pt system-ui, sans-serif; break-after: avoid; } .pframe p { margin: 0; } .pftext { white-space: pre-wrap; }
.marked { break-inside: avoid; } .mbox { border: 2pt solid #e11; box-shadow: none; } .mpin { width: 14pt; height: 14pt; font: 700 8pt/10pt system-ui, sans-serif; background: #e11; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
.pstop { grid-column: 1 / -1; border: 1.5pt solid #000; padding: 2pt 5pt; }
.psecret { font-family: ui-monospace, Consolas, monospace; }
.ptag { font: 700 8pt system-ui, sans-serif; border: 1pt solid #000; padding: 0 4pt; margin-left: 8pt; border-radius: 2pt; vertical-align: middle; }
.pnotes, .pbody, .pintro { white-space: pre-wrap; margin: 4pt 0 0; }

View File

@@ -2,7 +2,7 @@
// YYMMDD is the date, X the iteration that day (A first, B second, ...).
// Bump with `npm run bump` (see bump-version.js). build.js strips `export`.
export const APP_VERSION = '261123A';
export const APP_VERSION = '261124F';
const VERSION_RE = /^(\d{6})([A-Z])$/;
export const isVersion = (v) => typeof v === 'string' && VERSION_RE.test(v);

View File

@@ -86,3 +86,41 @@ test('displayValue for images: masked when secret, never the data itself', () =>
assert.equal(displayValue({ ...img, value: '' }, false), '(no image)');
assert.equal(countSecrets(docWithField({ ...img, secret: true })), 1);
});
import { normRect, isMark, blurBlock, pixelateRegion } from '../src/images.js';
test('normRect orders corners, clamps to the picture, drops stray clicks', () => {
assert.deepEqual(normRect(0.5, 0.6, 0.2, 0.1), { x: 0.2, y: 0.1, w: 0.3, h: 0.5 });
const c = normRect(-1, -1, 2, 0.5);
assert.deepEqual([c.x, c.y, c.w, c.h], [0, 0, 1, 0.5]);
assert.equal(normRect(0.5, 0.5, 0.503, 0.9), null);
});
test('isMark accepts markers and boxes inside the picture only', () => {
assert.equal(isMark({ type: 'marker', x: 0.5, y: 0.5 }), true);
assert.equal(isMark({ type: 'box', x: 0.1, y: 0.1, w: 0.5, h: 0.5 }), true);
assert.equal(isMark({ type: 'box', x: 0.6, y: 0.1, w: 0.5, h: 0.5 }), false); // runs off the right edge
assert.equal(isMark({ type: 'box', x: 0.1, y: 0.1, w: 0, h: 0.5 }), false);
assert.equal(isMark({ type: 'marker', x: 2, y: 0.5 }), false);
assert.equal(isMark({ type: 'blur', x: 0.1, y: 0.1, w: 0.2, h: 0.2 }), false);
assert.equal(isMark(null), false);
});
test('pixelateRegion averages blocks inside the rectangle and leaves the rest alone', () => {
const W = 40, H = 30;
const data = new Uint8ClampedArray(W * H * 4);
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { // a pattern with detail in every pixel
const i = (y * W + x) * 4; data[i] = (x * 37 + y * 11) % 256; data[i + 1] = (x * 5) % 256; data[i + 2] = (y * 9) % 256; data[i + 3] = 255;
}
const before = Uint8ClampedArray.from(data);
pixelateRegion(data, W, H, { x: 10, y: 5, w: 24, h: 20 }, 12);
const px = (a, x, y) => [...a.slice((y * W + x) * 4, (y * W + x) * 4 + 4)].join();
assert.equal(px(data, 10, 5), px(data, 21, 16)); // same 12x12 block, same colour
assert.notEqual(px(data, 10, 5), px(data, 22, 5)); // next block differs
assert.notEqual(px(data, 12, 7), px(before, 12, 7)); // detail is gone
assert.equal(px(data, 9, 5), px(before, 9, 5)); // left of the rectangle: untouched
assert.equal(px(data, 34, 5), px(before, 34, 5)); // right of it
assert.equal(px(data, 15, 25), px(before, 15, 25)); // below it
// total of each channel inside a block is preserved up to rounding (it is an average)
assert.ok(blurBlock(300, 14) >= 12 && blurBlock(900, 600) === 200);
});

View File

@@ -104,6 +104,13 @@ test('sequence validation: layout, image, text, secret, id, title', () => {
bad((x) => { x.frames[0].image = 5; }, /image must be a string/);
bad((x) => { x.frames[0].text = null; }, /text must be a string/);
bad((x) => { x.frames[0].secret = 'yes'; }, /secret must be a boolean/);
bad((x) => { x.frames[0].marks = 'no'; }, /marks must be an array/);
bad((x) => { x.frames[0].marks = [{ type: 'box', x: 0.9, y: 0, w: 0.5, h: 0.5 }]; }, /not a valid marker or box/);
const okm = structuredClone(d); okm.sections[0].records[1].frames[0].marks = [{ type: 'marker', x: 0.3, y: 0.4 }, { type: 'box', x: 0.1, y: 0.1, w: 0.2, h: 0.2 }];
assert.deepEqual(validate(okm), []);
bad((x) => { x.frames[0].ifStuck = 5; }, /ifStuck must be a string/);
bad((x) => { x.frames[0].stop = 'yes'; }, /stop must be a boolean/);
bad((x) => { x.captured = 'yesterday'; }, /captured must be YYYY-MM-DD/);
bad((x) => { x.title = ''; }, /missing title/);
bad((x) => { x.id = d.sections[0].records[0].id; }, /duplicate id/);
bad((x) => { delete x.frames; }, /frames must be an array/);
@@ -116,8 +123,11 @@ test('frameLayout hides empty text; frameView withholds secret frames only when
assert.equal(frameLayout({ layout: 'right', text: 'x' }), 'right');
assert.equal(frameLayout({ layout: 'none', text: 'x' }), 'none');
const f = { image: PNG, text: 'pw is hunter2', layout: 'under', secret: true };
assert.deepEqual(frameView(f, false), { withheld: true, image: '', text: '', layout: 'none' });
assert.deepEqual(frameView(f, false), { withheld: true, image: '', text: '', ifStuck: '', stop: false, layout: 'none' });
assert.equal(frameView(f, true).text, 'pw is hunter2');
const g = { image: PNG, text: '', layout: 'none', ifStuck: ' call 555-0100 ', stop: true };
assert.deepEqual([frameView(g, false).ifStuck, frameView(g, false).stop], ['call 555-0100', true]);
assert.deepEqual([frameView({ ...g, secret: true }, false).ifStuck, frameView({ ...g, secret: true }, false).stop], ['', false]);
assert.equal(frameView({ image: '', text: '', layout: 'under', secret: true }, false).withheld, false);
});

View File

@@ -345,3 +345,63 @@ test('clearSecrets erases secret fields and frames, keeps the rest, returns the
assert.deepEqual(validate(doc), []);
assert.equal(clearSecrets(doc), 0);
});
test('addCapture adds a frame and stamps the sequence captured date; clearSecrets clears ifStuck on secret steps', async () => {
const { addCapture, clearSecrets, addSequence } = await import('../src/ops.js');
const doc = emptyDocument('x');
const s = addSection(doc, 'records', 'Banking');
const q = addSequence(doc, s);
assert.equal(q.captured, undefined);
const f = addCapture(q, '');
assert.equal(q.frames.length, 1);
assert.equal(f.layout, 'under');
assert.match(q.captured, /^\d{4}-\d{2}-\d{2}$/);
f.secret = true; f.ifStuck = 'call 555-0100'; f.stop = true; f.image = 'data:image/png;base64,AAAA'; f.marks = [{ type: 'marker', x: 0.5, y: 0.5 }];
assert.equal(clearSecrets(doc), 1);
assert.equal(f.marks, undefined);
assert.equal(f.ifStuck, '');
assert.equal(f.stop, true);
assert.deepEqual(validate(doc), []);
});
test('credential references: field ids are stable, refs resolve, missing ones are detected', async () => {
const { addUse, removeUse, findFieldRef, ensureFieldId, addSequence, addFrame } = await import('../src/ops.js');
const { usesView } = await import('../src/print.js');
const doc = emptyDocument('x');
const s = addSection(doc, 'records', 'Banking');
const r = addRecord(doc, s);
addField(r); addField(r);
r.fields[0].label = 'User'; r.fields[0].value = 'bob';
r.fields[1].label = 'Password'; r.fields[1].value = 'hunter2'; r.fields[1].secret = true;
const q = addSequence(doc, s);
const fr = addFrame(q);
assert.equal(addUse(fr, r, r.fields[1]), true);
assert.equal(addUse(fr, r, r.fields[1]), false); // no duplicates
addUse(fr, r, r.fields[0]);
assert.equal(ensureFieldId(r, r.fields[1]), r.fields[1].id); // stable
assert.notEqual(r.fields[0].id, r.fields[1].id);
assert.deepEqual(validate(doc), []);
const moved = r.fields.reverse(); // reorder: references still resolve
assert.equal(findFieldRef(doc, fr.uses[0]).field.label, 'Password');
assert.deepEqual(usesView(doc, fr, false).map((u) => [u.label, u.value]), [['Password', '[withheld]'], ['User', 'bob']]);
assert.equal(usesView(doc, fr, true)[0].value, 'hunter2');
r.fields.splice(0, 1); // delete the password field
assert.equal(findFieldRef(doc, fr.uses[0]), null);
assert.equal(usesView(doc, fr, true)[0].missing, true);
assert.deepEqual(validate(doc), []); // a dangling reference is not an error
removeUse(fr, 0); removeUse(fr, 0);
assert.equal(fr.uses, undefined);
});
test('validation: uses and field ids', async () => {
const { addSequence, addFrame } = await import('../src/ops.js');
const doc = emptyDocument('x');
const s = addSection(doc, 'records', 'B');
const r = addRecord(doc, s); addField(r); addField(r);
const q = addSequence(doc, s); const fr = addFrame(q);
const bad = (mut, re) => { const c = structuredClone(doc); mut(c.sections[0]); assert.match(validate(c).join('|'), re); };
bad((x) => { x.records[1].frames[0].uses = 'no'; }, /uses must be an array/);
bad((x) => { x.records[1].frames[0].uses = [{ record: 'a' }]; }, /needs record and field ids/);
bad((x) => { x.records[0].fields[0].id = 'f1'; x.records[0].fields[1].id = 'f1'; }, /duplicate field id/);
bad((x) => { x.records[0].fields[0].id = ''; }, /id must be a non-empty string/);
});