2592 lines
152 KiB
HTML
2592 lines
152 KiB
HTML
<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>Final Wishes</title>
|
|
<style id="fw-css">:root {
|
|
color-scheme: light dark;
|
|
--bg: #fafaf7; --fg: #1d1d1b; --muted: #6b6b66; --card: #fff; --line: #d9d9d2;
|
|
--accent: #1f5f8b; --warn-bg: #fff1c9; --warn-fg: #6a4b00; --ok-bg: #dcefdc; --ok-fg: #1d4d1d; --danger: #a12a2a;
|
|
font-family: system-ui, -apple-system, "Segoe UI", sans-serif; line-height: 1.45;
|
|
}
|
|
@media (prefers-color-scheme: dark) {
|
|
:root { --bg: #17181a; --fg: #e8e8e4; --muted: #a0a09a; --card: #212326; --line: #3a3c40;
|
|
--accent: #7ab8e6; --warn-bg: #4a3a0c; --warn-fg: #ffe08a; --ok-bg: #1f3a1f; --ok-fg: #b6e3b6; --danger: #ff8a8a; }
|
|
}
|
|
* { box-sizing: border-box; }
|
|
body { margin: 0; background: var(--bg); color: var(--fg); }
|
|
#app { max-width: 70rem; margin: 0 auto; padding: 1rem; }
|
|
h1 { font-size: 1.4rem; margin: 0; } h2 { margin: 0 0 .75rem; } h3 { margin: 0 0 .5rem; font-size: 1.05rem; }
|
|
.top { display: flex; flex-direction: column; gap: .75rem; padding-bottom: .75rem; border-bottom: 1px solid var(--line); margin-bottom: 1rem; }
|
|
.top .titlerow, .top .toolbar { display: flex; flex-wrap: wrap; gap: .75rem; align-items: center; } .top h1 { flex: 1 1 auto; }
|
|
.layout { display: grid; grid-template-columns: 15rem 1fr; gap: 1.5rem; align-items: start; }
|
|
@media (max-width: 700px) { .layout { grid-template-columns: 1fr; } }
|
|
nav ul { list-style: none; margin: 0; padding: 0; }
|
|
nav a { display: block; padding: .4rem .6rem; border-radius: .4rem; color: inherit; text-decoration: none; }
|
|
nav a:hover { background: var(--line); } nav a.current { background: var(--accent); color: var(--bg); font-weight: 600; }
|
|
.card { background: var(--card); border: 1px solid var(--line); border-radius: .6rem; padding: .85rem 1rem; margin: 0 0 .85rem; }
|
|
.start { max-width: 26rem; margin: 15vh auto 0; display: grid; gap: .75rem; }
|
|
dl { display: grid; grid-template-columns: minmax(8rem, 14rem) 1fr; gap: .25rem 1rem; margin: 0; }
|
|
dt { color: var(--muted); } dd { margin: 0; overflow-wrap: anywhere; }
|
|
.secret { font-family: ui-monospace, monospace; }
|
|
.notes, .body, .intro { white-space: pre-wrap; } .intro { color: var(--muted); }
|
|
.muted { color: var(--muted); } .small { font-size: .8rem; margin: .5rem 0 0; }
|
|
.badge { font-size: .7rem; font-weight: 700; padding: .1rem .45rem; border-radius: 1rem; vertical-align: middle; }
|
|
.badge.tbd { background: var(--warn-bg); color: var(--warn-fg); } .badge.done { background: var(--ok-bg); color: var(--ok-fg); }
|
|
ol.items, ul.items { padding-left: 1.4rem; } .item { margin-bottom: .75rem; } .item.done strong { text-decoration: line-through; }
|
|
.error { color: var(--danger); margin: 0; min-height: 1.2em; }
|
|
input, select, textarea { font: inherit; color: inherit; background: var(--bg); border: 1px solid var(--line); border-radius: .35rem; padding: .35rem .5rem; min-width: 0; }
|
|
textarea { width: 100%; display: block; } label { display: block; margin-top: .5rem; } label.check { display: inline-flex; gap: .25rem; margin: 0; align-items: center; white-space: nowrap; }
|
|
.row { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; margin-bottom: .5rem; } .row input:not([type=checkbox]) { flex: 1 1 10rem; }
|
|
.rechead { display: flex; justify-content: space-between; align-items: center; gap: .75rem; } .rechead h3 { margin: 0; } .rechead .tools { display: flex; gap: .35rem; flex: none; } .card.collapsed { padding-top: .5rem; padding-bottom: .5rem; }
|
|
.btn { font: inherit; padding: .35rem .8rem; border-radius: .4rem; border: 1px solid var(--line); background: var(--card); color: inherit; cursor: pointer; }
|
|
.btn.primary { background: var(--accent); color: var(--bg); border-color: var(--accent); }
|
|
.btn.link { border: 0; background: none; color: var(--accent); padding: 0 .5rem; text-decoration: underline; }
|
|
.btn.icon { padding: .2rem .5rem; } .btn.danger { color: var(--danger); } .btn.small { font-size: .85rem; } .btn:disabled { opacity: .35; cursor: default; }
|
|
.tools { display: inline-flex; gap: .2rem; } .addsec { display: grid; gap: .4rem; margin-top: 1rem; }
|
|
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
|
|
|
/* ---------- sub-tabs ---------- */
|
|
.tabs { display: flex; flex-wrap: wrap; gap: .25rem; border-bottom: 1px solid var(--line); margin: 0 0 1rem; }
|
|
.tab { font: inherit; color: inherit; background: none; border: 1px solid transparent; border-bottom: 0; border-radius: .4rem .4rem 0 0; padding: .4rem .9rem; cursor: pointer; margin-bottom: -1px; }
|
|
.tab.on { background: var(--card); border-color: var(--line); font-weight: 600; box-shadow: inset 0 -2px 0 var(--accent); }
|
|
|
|
/* ---------- image fields ---------- */
|
|
.fimg { display: block; max-width: 100%; max-height: 18rem; border: 1px solid var(--line); border-radius: .35rem; background: #fff; cursor: zoom-in; margin: .25rem 0; }
|
|
.dropzone { border: 2px dashed var(--line); border-radius: .5rem; padding: .75rem; text-align: center; background: var(--bg); }
|
|
.dropzone.over, .dropzone:focus-visible { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, var(--bg)); }
|
|
.dropzone .row { justify-content: center; margin: .25rem 0 0; } .dropzone .fimg { margin: .25rem auto; cursor: default; } .imagefield { margin: 0 0 .75rem; }
|
|
/* ---------- visual sequences ---------- */
|
|
.seq { border-left: 3px solid var(--accent); } .frames { display: grid; gap: 1rem; }
|
|
.frame { display: grid; grid-template-columns: minmax(0, 1fr); gap: .35rem 1rem; align-items: start; padding-bottom: .75rem; border-bottom: 1px dashed var(--line); }
|
|
.frame:last-child { border-bottom: 0; padding-bottom: 0; } .frame .fnum { grid-column: 1 / -1; }
|
|
.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); }
|
|
.searchbar { display: flex; flex: 1 1 100%; flex-wrap: wrap; gap: .5rem; align-items: center; }
|
|
.searchbox { flex: 1 1 14rem; min-width: 8rem; font: inherit; padding: .4rem .6rem; line-height: 1.2; border: 1px solid var(--line); border-radius: .4rem; background: var(--card); color: var(--fg); }
|
|
.searchnote { min-width: 4.5rem; text-align: right; }
|
|
mark.hit { background: var(--warn-bg); color: var(--warn-fg); border-radius: .2rem; padding: 0 .1em; }
|
|
mark.hit.cur { background: var(--accent); color: var(--bg); outline: 2px solid var(--accent); }
|
|
.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; }
|
|
|
|
/* ---------- 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 ---------- */
|
|
@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.7in 0.8in 0.8in; }
|
|
@media print {
|
|
:root { color-scheme: light; }
|
|
html, body { background: #fff !important; color: #000 !important; font-size: 11pt; }
|
|
#app, dialog { display: none !important; }
|
|
#printdoc { display: block; font-family: Georgia, "Times New Roman", serif; line-height: 1.35; }
|
|
.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 h1 { font-size: 26pt; margin: 1.2in 0 .2in; }
|
|
.powner { font-size: 14pt; }
|
|
.pnote { border: 1.5pt solid #000; padding: 8pt 10pt; font: 600 10.5pt system-ui, sans-serif; }
|
|
.pnote.warn { border-width: 3pt; }
|
|
.ptoc { columns: 2; padding-left: 1.2em; }
|
|
.psec { break-before: page; }
|
|
.psec:first-of-type { break-before: auto; }
|
|
h2 { font-size: 17pt; border-bottom: 1pt solid #000; padding-bottom: 3pt; margin: 0 0 10pt; break-after: avoid; }
|
|
h3 { font-size: 12.5pt; margin: 0 0 4pt; break-after: avoid; }
|
|
h3.psubhead { font-size: 14pt; margin: 12pt 0 6pt; padding-bottom: 2pt; border-bottom: 0.5pt solid #666; font-family: system-ui, sans-serif; }
|
|
.prec { break-inside: avoid; margin: 0 0 12pt; padding: 6pt 8pt; border: 0.75pt solid #888; border-left-width: 3pt; }
|
|
.prec.tbd { border-left-color: #000; background: #eee; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
|
.prec table { border-collapse: collapse; width: 100%; font-size: 10.5pt; }
|
|
.prec th { text-align: left; font-weight: 600; width: 30%; vertical-align: top; padding: 1.5pt 8pt 1.5pt 0; font-family: system-ui, sans-serif; font-size: 9.5pt; color: #333; }
|
|
.prec td { padding: 1.5pt 0; overflow-wrap: anywhere; }
|
|
.pimg { display: block; max-width: 100%; max-height: 4.2in; object-fit: contain; border: 0.5pt solid #999; margin: 2pt 0; }
|
|
.pseq { margin: 0 0 12pt; } li.pseqitem { display: block; list-style: none; }
|
|
.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; }
|
|
.pintro { font-style: italic; margin-bottom: 10pt; }
|
|
.pitems { padding-left: 0; list-style-position: inside; }
|
|
.pitem { break-inside: avoid; margin: 0 0 9pt; }
|
|
.pitem .pnotes { margin-left: 2.2em; }
|
|
.cb { display: inline-block; width: 11pt; height: 11pt; border: 1.2pt solid #000; margin: 0 7pt 0 4pt; vertical-align: -1.5pt; text-align: center; line-height: 10pt; font: 700 9pt system-ui, sans-serif; }
|
|
}
|
|
|
|
/* capture tool (issue #28) */
|
|
.capwalks { display: flex; flex-wrap: wrap; gap: .4rem; margin: 0 0 .75rem; }
|
|
.capthumbs { display: grid; grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr)); gap: .75rem; margin: .75rem 0; }
|
|
.capthumb { border: 1px solid var(--line); border-radius: .4rem; padding: .4rem; }
|
|
.capthumb img { width: 100%; display: block; border-radius: .25rem; }
|
|
.capthumb .row { margin: .4rem 0 0; }
|
|
.importrow { border-top: 1px solid var(--line); padding: .6rem 0; }
|
|
.importrow:first-of-type { border-top: 0; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div id="printdoc" aria-hidden="true"></div>
|
|
<main id="app"><noscript>This document needs JavaScript enabled.</noscript></main>
|
|
<script id="payload" type="application/octet-stream">RlcBAAknwLnNQMwG+m1/FUjGDTC8VgqqoCsJIenPTuxwk9DTwDrH9e3+h2AWgXpq1nCY6hVzjJmB/GOM0ZspFYiKwSWlZmrG7h0yn2AVBSMXkp2MtaEE/u2OTSMbjcpCxhSwNsHwnWknl5L9uCb3M7xnd2A1FGD6SpSzFQIgn4KaSQ5aSNqQLXK9d1wDheR8fQbFSnVJWOG90IrpH1cC2PTrK2103wGUWiIC2ngpWSlM98ah5VheUg8oyc0HYKgy1+hYwI6tNofZDJV+poQT61lmX0rHSzA20x+WSMYriOOJocp3Uz2WT4HEityuJteOf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YGdqWVu9HKklX2tKUhfOvVv2WXlQt3GtuyS+fIbUFz73sJRPreHu501qjbQmMdpCXY1+wl3xoRyPftuwTXkl9O7XBWZ3CyNgvBt2N6f4hQ8druIFtwCf76A2WM4ZHj1FzKtwYWnBHdBHCrlrsROrhqIdtLI8x/R61tgQzQO8+NBFi/J10+3QnQiVCZ550gyh5LLbFxhGVh47sGMOA0qO7fG3wh92GnHpFwVA3PWIgVRfc62fX4I7OcUYthA/t6plxmjE3MP5HgFJxcMnCU9iarxC3MR1BMwc6+UVqLaw9s3B4oIG2gdFBTjMNFm6Y7iLY/8JwIRioUd8BzyyGYaxucb80TWyLz9clJTnFuomKNsP0m1JVjeFxYzwGZxO4kVQETeoFrOS9sL8WX6Hy/MhrJ5VwmuYGVZsz21l1RwPcpqz+uhnSrcwBp3gsr5U99FitLmNrboyWlUy0YEyGhOshWWbwdo69hP9p/BDIDGi/l3gPOnA26YSaHsvOmLi3omr0c/wRzXprA9YM1jDzxRPp4oXPC9SCO/pDpRrMyl0cHp58lZcWOlaY2xl2GULD66w3kgd7e12bGGHnfiMTe3Y+tJzhu83XugGaeDgDZR+lyakPOSsS5DB6zG6xEbywE=</script>
|
|
<script id="fw-js">// Passphrase encryption: PBKDF2-SHA256 -> AES-256-GCM, WebCrypto only.
|
|
// Runs unchanged in browsers and Node 20+. build.js strips the `export`
|
|
// keywords when inlining this into the single-file bundle.
|
|
//
|
|
// Blob layout (base64 of): "FW" 0x01 | iterations u32be | salt 16 | iv 12 | ciphertext+tag
|
|
// The 7-byte header + salt + iv are bound in as GCM additional data, so any
|
|
// tampering with them fails authentication just like tampering with the ciphertext.
|
|
|
|
const MAGIC = [0x46, 0x57, 0x01]; // "FW" version 1
|
|
const CAPTURE_MAGIC = [0x46, 0x43, 0x01]; // "FC" version 1: a capture bundle (issue #28)
|
|
const SALT_LEN = 16;
|
|
const IV_LEN = 12;
|
|
const HEADER_LEN = MAGIC.length + 4;
|
|
const DEFAULT_ITERATIONS = 600000; // OWASP 2023 guidance for PBKDF2-SHA256
|
|
const MAX_ITERATIONS = 10000000; // refuse absurd values from a hostile blob
|
|
|
|
class DecryptError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
this.name = 'DecryptError';
|
|
}
|
|
}
|
|
|
|
function toBase64(bytes) {
|
|
let s = '';
|
|
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
}
|
|
return btoa(s);
|
|
}
|
|
|
|
function fromBase64(str) {
|
|
try {
|
|
const s = atob(str.trim());
|
|
const out = new Uint8Array(s.length);
|
|
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
|
return out;
|
|
} catch {
|
|
throw new DecryptError('Not a valid encrypted file.');
|
|
}
|
|
}
|
|
|
|
async function deriveKey(passphrase, salt, iterations) {
|
|
const base = await crypto.subtle.importKey(
|
|
'raw', new TextEncoder().encode(passphrase), 'PBKDF2', false, ['deriveKey']);
|
|
return crypto.subtle.deriveKey(
|
|
{ name: 'PBKDF2', hash: 'SHA-256', salt, iterations },
|
|
base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
}
|
|
|
|
// Returns a base64 string. `iterations` is overridable for fast tests only.
|
|
async function encrypt(plaintext, passphrase, iterations = DEFAULT_ITERATIONS, magic = MAGIC) {
|
|
if (!passphrase) throw new Error('A passphrase is required.');
|
|
const salt = crypto.getRandomValues(new Uint8Array(SALT_LEN));
|
|
const iv = crypto.getRandomValues(new Uint8Array(IV_LEN));
|
|
const head = new Uint8Array(HEADER_LEN + SALT_LEN + IV_LEN);
|
|
head.set(magic, 0);
|
|
new DataView(head.buffer).setUint32(magic.length, iterations);
|
|
head.set(salt, HEADER_LEN);
|
|
head.set(iv, HEADER_LEN + SALT_LEN);
|
|
|
|
const key = await deriveKey(passphrase, salt, iterations);
|
|
const ct = new Uint8Array(await crypto.subtle.encrypt(
|
|
{ name: 'AES-GCM', iv, additionalData: head }, key, new TextEncoder().encode(plaintext)));
|
|
|
|
const out = new Uint8Array(head.length + ct.length);
|
|
out.set(head, 0);
|
|
out.set(ct, head.length);
|
|
return toBase64(out);
|
|
}
|
|
|
|
// Throws DecryptError for a wrong passphrase, corruption, or tampering
|
|
// (these are deliberately indistinguishable).
|
|
async function decrypt(blob, passphrase, magic = MAGIC) {
|
|
const bytes = fromBase64(blob);
|
|
const preamble = HEADER_LEN + SALT_LEN + IV_LEN;
|
|
if (bytes.length < preamble + 16 || magic.some((b, i) => bytes[i] !== b)) {
|
|
throw new DecryptError('Not a valid encrypted file.');
|
|
}
|
|
const iterations = new DataView(bytes.buffer, bytes.byteOffset).getUint32(magic.length);
|
|
if (iterations < 1 || iterations > MAX_ITERATIONS) {
|
|
throw new DecryptError('Not a valid encrypted file.');
|
|
}
|
|
const head = bytes.slice(0, preamble);
|
|
const salt = bytes.slice(HEADER_LEN, HEADER_LEN + SALT_LEN);
|
|
const iv = bytes.slice(HEADER_LEN + SALT_LEN, preamble);
|
|
try {
|
|
const key = await deriveKey(passphrase || '', salt, iterations);
|
|
const pt = await crypto.subtle.decrypt(
|
|
{ name: 'AES-GCM', iv, additionalData: head }, key, bytes.slice(preamble));
|
|
return new TextDecoder().decode(pt);
|
|
} catch {
|
|
throw new DecryptError('Wrong passphrase, or the file is damaged.');
|
|
}
|
|
}
|
|
|
|
const MIN_PASSPHRASE_LENGTH = 12;
|
|
|
|
// Returns '' when acceptable, otherwise a message for the user.
|
|
function passphraseProblem(p) {
|
|
if (!p || p.length < MIN_PASSPHRASE_LENGTH) {
|
|
return `Use at least ${MIN_PASSPHRASE_LENGTH} characters (a few random words works well).`;
|
|
}
|
|
return '';
|
|
}
|
|
|
|
// Image fields: pure helpers (tested in Node) plus the browser-only import
|
|
// pipeline processImageFile(). build.js strips `export` / `import` lines.
|
|
//
|
|
// Stored form: a record field { kind: 'image', label, value: 'data:image/png|jpeg;base64,...' }
|
|
// with value '' meaning "no image yet". Only PNG and JPEG are accepted.
|
|
|
|
const MAX_DIMENSION = 1600; // longest side after import
|
|
const PNG_KEEP_LIMIT = 700 * 1024; // a PNG larger than this is re-encoded as JPEG
|
|
const JPEG_QUALITY = 0.85;
|
|
const MAX_IMAGE_DATA_CHARS = 4000000; // ~3 MB of image per field
|
|
|
|
const IMAGE_DATA_URL_RE = /^data:image\/(png|jpeg);base64,[A-Za-z0-9+/]+={0,2}$/;
|
|
|
|
// Identify an image by its first bytes (never trust the file name or MIME type).
|
|
function sniffType(bytes) {
|
|
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png';
|
|
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
|
|
return '';
|
|
}
|
|
|
|
// Scale (w, h) down so the longest side is at most `max`; never scales up.
|
|
function fitSize(w, h, max = MAX_DIMENSION) {
|
|
const longest = Math.max(w, h);
|
|
if (longest <= max) return { width: w, height: h };
|
|
const s = max / longest;
|
|
return { width: Math.max(1, Math.round(w * s)), height: Math.max(1, Math.round(h * s)) };
|
|
}
|
|
|
|
function isImageDataUrl(v) {
|
|
return typeof v === 'string' && v.length <= MAX_IMAGE_DATA_CHARS && IMAGE_DATA_URL_RE.test(v);
|
|
}
|
|
|
|
// Decoded size in bytes of a base64 data URL.
|
|
function dataUrlBytes(v) {
|
|
const b64 = v.slice(v.indexOf(',') + 1);
|
|
const pad = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0;
|
|
return Math.floor((b64.length * 3) / 4) - pad;
|
|
}
|
|
|
|
function formatBytes(n) {
|
|
return n < 1024 ? n + ' B' : n < 1048576 ? Math.round(n / 1024) + ' KB' : (n / 1048576).toFixed(1) + ' MB';
|
|
}
|
|
|
|
// "drivers_license-front.png" -> "drivers license front"
|
|
function labelFromFilename(name) {
|
|
const base = String(name || '').replace(/^.*[\\/]/, '').replace(/\.[^.]*$/, '').replace(/[_-]+/g, ' ').trim();
|
|
return base || 'Image';
|
|
}
|
|
|
|
// Browser only. Decode, shrink, strip metadata (by redrawing on a canvas) and
|
|
// re-encode. Returns a data URL that passes isImageDataUrl, or throws an Error
|
|
// with a message fit to show the user.
|
|
async function processImageFile(blob) {
|
|
const bytes = new Uint8Array(await blob.arrayBuffer());
|
|
const type = sniffType(bytes);
|
|
if (!type) throw new Error('Only PNG and JPEG images can be added.');
|
|
let bmp;
|
|
try {
|
|
bmp = await createImageBitmap(blob); // applies the EXIF orientation
|
|
} catch {
|
|
throw new Error('That image could not be read.');
|
|
}
|
|
try {
|
|
const draw = (scale, fill) => {
|
|
const fit = fitSize(bmp.width, bmp.height);
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = Math.max(1, Math.round(fit.width * scale));
|
|
canvas.height = Math.max(1, Math.round(fit.height * scale));
|
|
const ctx = canvas.getContext('2d');
|
|
if (fill) { ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, canvas.width, canvas.height); }
|
|
ctx.drawImage(bmp, 0, 0, canvas.width, canvas.height);
|
|
return canvas;
|
|
};
|
|
if (type === 'image/png') {
|
|
const png = draw(1, false).toDataURL('image/png');
|
|
if (dataUrlBytes(png) <= PNG_KEEP_LIMIT && isImageDataUrl(png)) return png;
|
|
}
|
|
// JPEG, or a PNG too big to keep: try progressively smaller until it fits.
|
|
for (const [scale, q] of [[1, JPEG_QUALITY], [1, 0.7], [0.7, 0.7], [0.5, 0.7]]) {
|
|
const jpg = draw(scale, true).toDataURL('image/jpeg', q);
|
|
if (isImageDataUrl(jpg)) return jpg;
|
|
}
|
|
throw new Error('That image is too large, even after shrinking it.');
|
|
} finally {
|
|
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.
|
|
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 };
|
|
}
|
|
|
|
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.
|
|
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.
|
|
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).
|
|
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 };
|
|
}
|
|
|
|
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.
|
|
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.
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// Data model for the document (plaintext JSON before encryption).
|
|
// Pure functions, no DOM; runs in browsers and Node. build.js strips `export`.
|
|
//
|
|
// Document:
|
|
// { schemaVersion: 1,
|
|
// meta: { owner, title, lastUpdated: 'YYYY-MM-DD' },
|
|
// header?: { fields: [HeaderField] }, // running print header; absent = defaults
|
|
// sections: [ Section ] }
|
|
//
|
|
// Section (ordered). `kind` decides which body it has:
|
|
// 'text' -> { body: string } free narrative ("Start here")
|
|
// 'records' -> { records: [Record] } accounts, people, places, items
|
|
// 'steps' -> { items: [Item] } ordered instructions (wind-down)
|
|
// 'checklist' -> { items: [Item] } things still to add/do
|
|
// Every section has { id, title, kind } and may have { intro: string }.
|
|
// A 'records' section may also have sub-tabs:
|
|
// subsections?: [{ id, title }] user-defined tabs, in display order
|
|
// generalTitle?: string name of the catch-all first tab (default 'General')
|
|
// Each record or sequence in its list may carry `subsection: <a subsections id>`.
|
|
// No `subsection` (or one that matches no tab) means the General tab. With no
|
|
// subsections the section shows no tabs at all.
|
|
//
|
|
// Record: { id, title, status: 'ok'|'tbd', updated: 'YYYY-MM-DD',
|
|
// fields: [Field], notes?: string }
|
|
// Field: { label, value, secret?: boolean, kind?: 'text'|'image' } (kind defaults to text)
|
|
// An image field's value is a PNG/JPEG data URL, or '' when no image is set yet.
|
|
// 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,
|
|
// 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
|
|
// sequences in an optional `sequences` array, printed after the body.
|
|
//
|
|
// 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
|
|
// in the UI and optionally in print output.
|
|
|
|
const SCHEMA_VERSION = 1;
|
|
const GENERAL_TITLE = 'General';
|
|
const SECTION_KINDS = ['text', 'records', 'steps', 'checklist'];
|
|
const RECORD_STATUSES = ['ok', 'tbd'];
|
|
const ITEM_STATUSES = ['open', 'done', 'tbd'];
|
|
const FIELD_KINDS = ['text', 'image'];
|
|
const FRAME_LAYOUTS = ['right', 'under', 'none'];
|
|
const isSequence = (e) => !!e && typeof e === 'object' && e.kind === 'sequence';
|
|
const HEADER_KINDS = ['text', 'lastUpdated'];
|
|
const HEADER_ALIGNS = ['left', 'right'];
|
|
|
|
// What the header is when the document doesn't define one.
|
|
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 isStr = (v) => typeof v === 'string';
|
|
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
|
|
function emptyDocument(owner = '', title = 'In the event of my death or incapacity') {
|
|
return {
|
|
schemaVersion: SCHEMA_VERSION,
|
|
meta: { owner, title, lastUpdated: new Date().toISOString().slice(0, 10) },
|
|
sections: [],
|
|
};
|
|
}
|
|
|
|
// Returns a list of human-readable problems; empty means valid.
|
|
function validate(doc) {
|
|
const errs = [];
|
|
const seen = new Set();
|
|
const checkId = (id, where) => {
|
|
if (!isStr(id) || !id) errs.push(`${where}: missing id`);
|
|
else if (seen.has(id)) errs.push(`${where}: duplicate id "${id}"`);
|
|
else seen.add(id);
|
|
};
|
|
|
|
if (!isObj(doc)) return ['document must be an object'];
|
|
if (doc.schemaVersion !== SCHEMA_VERSION) errs.push(`schemaVersion must be ${SCHEMA_VERSION}`);
|
|
|
|
if (!isObj(doc.meta)) errs.push('meta must be an object');
|
|
else {
|
|
if (!isStr(doc.meta.owner)) errs.push('meta.owner must be a string');
|
|
if (!isStr(doc.meta.title)) errs.push('meta.title must be a string');
|
|
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'];
|
|
|
|
doc.sections.forEach((s, i) => {
|
|
const where = `sections[${i}]`;
|
|
if (!isObj(s)) return errs.push(`${where}: must be an object`);
|
|
checkId(s.id, where);
|
|
if (!isStr(s.title) || !s.title) errs.push(`${where}: missing title`);
|
|
if (s.intro !== undefined && !isStr(s.intro)) errs.push(`${where}: intro must be a string`);
|
|
if (!SECTION_KINDS.includes(s.kind)) return errs.push(`${where}: unknown kind "${s.kind}"`);
|
|
if (s.kind !== 'records' && (s.subsections !== undefined || s.generalTitle !== undefined)) errs.push(`${where}: only records sections can have sub-tabs`);
|
|
|
|
if (s.kind === 'text') {
|
|
if (!isStr(s.body)) errs.push(`${where}: text section needs a body string`);
|
|
if (s.sequences !== undefined) {
|
|
if (!Array.isArray(s.sequences)) errs.push(`${where}: sequences must be an array`);
|
|
else s.sequences.forEach((q, j) => checkSequence(q, `${where}.sequences[${j}]`));
|
|
}
|
|
} else if (s.kind === 'records') {
|
|
if (!Array.isArray(s.records)) return errs.push(`${where}: records must be an array`);
|
|
const tabIds = new Set();
|
|
if (s.generalTitle !== undefined && (!isStr(s.generalTitle) || !s.generalTitle.trim())) errs.push(`${where}: generalTitle must be a non-empty string`);
|
|
if (s.subsections !== undefined) {
|
|
if (!Array.isArray(s.subsections)) errs.push(`${where}: subsections must be an array`);
|
|
else s.subsections.forEach((t, j) => {
|
|
const tw = `${where}.subsections[${j}]`;
|
|
if (!isObj(t)) return errs.push(`${tw}: must be an object`);
|
|
checkId(t.id, tw);
|
|
if (isStr(t.id)) tabIds.add(t.id);
|
|
if (!isStr(t.title) || !t.title.trim()) errs.push(`${tw}: missing title`);
|
|
});
|
|
}
|
|
s.records.forEach((r, j) => {
|
|
const rw = `${where}.records[${j}]`;
|
|
(isSequence(r) ? checkSequence : checkRecord)(r, rw);
|
|
if (isObj(r) && r.subsection !== undefined && !tabIds.has(r.subsection)) errs.push(`${rw}: subsection "${r.subsection}" is not one of this section's sub-tabs`);
|
|
});
|
|
} else {
|
|
if (!Array.isArray(s.items)) return errs.push(`${where}: items must be an array`);
|
|
s.items.forEach((it, j) => (isSequence(it) ? checkSequence : checkItem)(it, `${where}.items[${j}]`));
|
|
}
|
|
});
|
|
|
|
function checkRecord(r, where) {
|
|
if (!isObj(r)) return errs.push(`${where}: must be an object`);
|
|
checkId(r.id, where);
|
|
if (!isStr(r.title) || !r.title) errs.push(`${where}: missing title`);
|
|
if (!RECORD_STATUSES.includes(r.status)) errs.push(`${where}: bad status "${r.status}"`);
|
|
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`);
|
|
}
|
|
});
|
|
}
|
|
|
|
function checkSequence(q, where) {
|
|
if (!isObj(q)) return errs.push(`${where}: must be an object`);
|
|
checkId(q.id, where);
|
|
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}]`;
|
|
if (!isObj(f)) return errs.push(`${fw}: must be an object`);
|
|
if (!isStr(f.image)) errs.push(`${fw}: image must be a string`);
|
|
else if (f.image !== '' && !isImageDataUrl(f.image)) errs.push(`${fw}: image must be a PNG or JPEG under ${Math.round(MAX_IMAGE_DATA_CHARS / 1e6)} MB`);
|
|
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`);
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
function checkItem(it, where) {
|
|
if (!isObj(it)) return errs.push(`${where}: must be an object`);
|
|
checkId(it.id, where);
|
|
if (!isStr(it.text) || !it.text) errs.push(`${where}: missing text`);
|
|
if (!ITEM_STATUSES.includes(it.status)) errs.push(`${where}: bad status "${it.status}"`);
|
|
if (it.detail !== undefined && !isStr(it.detail)) errs.push(`${where}: detail must be a string`);
|
|
}
|
|
|
|
return errs;
|
|
}
|
|
|
|
function assertValid(doc) {
|
|
const errs = validate(doc);
|
|
if (errs.length) throw new Error('Invalid document:\n- ' + errs.join('\n- '));
|
|
return doc;
|
|
}
|
|
|
|
|
|
|
|
// 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);
|
|
|
|
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;
|
|
}
|
|
|
|
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.
|
|
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;
|
|
}
|
|
|
|
function removeAt(arr, i) {
|
|
return i >= 0 && i < arr.length ? arr.splice(i, 1)[0] : undefined;
|
|
}
|
|
|
|
function touch(doc, record) {
|
|
const d = today();
|
|
doc.meta.lastUpdated = d;
|
|
if (record) record.updated = d;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
function addField(record) {
|
|
const f = { label: 'Label', value: '' };
|
|
record.fields.push(f);
|
|
return f;
|
|
}
|
|
|
|
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)
|
|
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.
|
|
function ensureHeader(doc) {
|
|
if (!doc.header) doc.header = { fields: defaultHeaderFields(doc) };
|
|
return doc.header;
|
|
}
|
|
|
|
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`.
|
|
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.
|
|
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 ----
|
|
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.
|
|
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);
|
|
|
|
function docDiffers(doc, baseline) {
|
|
return stable(doc) !== stable(baseline);
|
|
}
|
|
|
|
// A section the baseline doesn't have was added since: that counts as changed.
|
|
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);
|
|
}
|
|
|
|
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).
|
|
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;
|
|
}
|
|
|
|
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.
|
|
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.
|
|
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.
|
|
function sequenceList(section) {
|
|
if (section.kind === 'records') return section.records;
|
|
if (section.kind === 'text') return section.sequences || (section.sequences = []);
|
|
return section.items;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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).
|
|
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.
|
|
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.
|
|
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.
|
|
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;
|
|
}
|
|
|
|
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.
|
|
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.
|
|
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) ----
|
|
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;
|
|
}
|
|
|
|
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.
|
|
const hasTabs = (section) => !!(section.subsections && section.subsections.length);
|
|
|
|
// [{id, title}] in display order, General first; [] when the section has no sub-tabs.
|
|
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.
|
|
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.
|
|
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).
|
|
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.
|
|
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.
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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.
|
|
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).
|
|
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.
|
|
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;
|
|
}
|
|
|
|
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.
|
|
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);
|
|
}
|
|
|
|
|
|
|
|
|
|
// Capture bundles (issue #28): walkthroughs captured in the separate, online capture.html
|
|
// and carried to the offline main app. A bundle is JSON sealed like the main document
|
|
// (PBKDF2 -> AES-GCM) but with the "FC" magic bytes, so the two can never be mixed up.
|
|
//
|
|
// { format: 'fw-capture', version: 1, created: 'YYYY-MM-DD',
|
|
// walkthroughs: [{ title, captured: 'YYYY-MM-DD', frames: [{ image: <PNG/JPEG data URL> }] }] }
|
|
//
|
|
// Pure functions, no DOM. build.js strips `export` / `import` lines.
|
|
|
|
const BUNDLE_FORMAT = 'fw-capture';
|
|
const BUNDLE_VERSION = 1;
|
|
const MAX_WALKTHROUGHS = 100;
|
|
const MAX_FRAMES = 200;
|
|
const BUNDLE_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
|
|
function newWalkthrough(title = '', date = new Date().toISOString().slice(0, 10)) {
|
|
return { title, captured: date, frames: [] };
|
|
}
|
|
|
|
// Problems with a bundle's contents, as strings; [] when it is fine to import.
|
|
function validateBundle(b) {
|
|
const errs = [];
|
|
if (!b || typeof b !== 'object' || b.format !== BUNDLE_FORMAT) return ['This is not a capture bundle.'];
|
|
if (b.version !== BUNDLE_VERSION) return ['This bundle is from a different version of the capture tool (' + b.version + ').'];
|
|
if (!Array.isArray(b.walkthroughs) || b.walkthroughs.length > MAX_WALKTHROUGHS) return ['The bundle has no walkthroughs list.'];
|
|
b.walkthroughs.forEach((w, i) => {
|
|
const where = 'Walkthrough ' + (i + 1);
|
|
if (!w || typeof w !== 'object') return errs.push(where + ' is not valid.');
|
|
if (typeof w.title !== 'string') errs.push(where + ' has no title.');
|
|
if (typeof w.captured !== 'string' || !BUNDLE_DATE_RE.test(w.captured)) errs.push(where + ' has no capture date.');
|
|
if (!Array.isArray(w.frames) || w.frames.length > MAX_FRAMES) return errs.push(where + ' has no steps list.');
|
|
w.frames.forEach((f, j) => { if (!f || !isImageDataUrl(f.image)) errs.push(where + ', step ' + (j + 1) + ' has no valid picture.'); });
|
|
});
|
|
return errs;
|
|
}
|
|
|
|
// Walkthroughs with no steps are left out: there is nothing to carry over.
|
|
async function sealBundle(walkthroughs, passphrase, iterations, date = new Date().toISOString().slice(0, 10)) {
|
|
const bundle = { format: BUNDLE_FORMAT, version: BUNDLE_VERSION, created: date, walkthroughs: walkthroughs.filter((w) => w.frames.length) };
|
|
const errs = validateBundle(bundle);
|
|
if (errs.length) throw new Error(errs[0]);
|
|
return encrypt(JSON.stringify(bundle), passphrase, iterations, CAPTURE_MAGIC);
|
|
}
|
|
|
|
// Returns the bundle; throws DecryptError (wrong passphrase / damaged / not a bundle) or Error (bad contents).
|
|
// Nothing is returned unless the whole bundle is valid, so a merge is all or nothing.
|
|
async function openBundle(blob, passphrase) {
|
|
const bundle = JSON.parse(await decrypt(blob, passphrase, CAPTURE_MAGIC));
|
|
const errs = validateBundle(bundle);
|
|
if (errs.length) throw new Error(errs[0]);
|
|
return bundle;
|
|
}
|
|
|
|
// ---- where a walkthrough can go in the document ----
|
|
// [{ key, sid, tab, label }]: every section a sequence can live in, with one entry per sub-tab.
|
|
function destinations(doc) {
|
|
const out = [];
|
|
for (const s of doc.sections) {
|
|
out.push({ key: s.id + '|', sid: s.id, tab: '', label: s.title });
|
|
if (s.kind === 'records') {
|
|
for (const t of s.subsections || []) out.push({ key: s.id + '|' + t.id, sid: s.id, tab: t.id, label: s.title + ' \u203a ' + t.title });
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
|
|
|
|
// Pure helpers for the printed document. No DOM; tested in Node.
|
|
// build.js strips `export` when bundling.
|
|
|
|
// What to print for a field. Secrets are either shown or withheld; an empty
|
|
// secret is always "(not set)" so a blank is never mistaken for a hidden value.
|
|
function displayValue(field, includeSecrets) {
|
|
if (field.kind === 'image') {
|
|
if (!field.value) return '(no image)';
|
|
return field.secret && !includeSecrets ? '[withheld]' : '[image]';
|
|
}
|
|
if (field.secret) {
|
|
if (!field.value) return '(not set)';
|
|
return includeSecrets ? field.value : '[withheld]';
|
|
}
|
|
return field.value || '(blank)';
|
|
}
|
|
|
|
function headerFields(doc) {
|
|
return doc.header ? doc.header.fields : defaultHeaderFields(doc);
|
|
}
|
|
|
|
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.
|
|
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) : '',
|
|
};
|
|
}
|
|
|
|
// Where a frame's text goes: empty text never takes room, whatever the layout says.
|
|
function frameLayout(frame) {
|
|
return frame.layout === 'none' || !String(frame.text || '').trim() ? 'none' : frame.layout;
|
|
}
|
|
|
|
// 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".
|
|
function frameView(frame, includeSecrets) {
|
|
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.
|
|
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 };
|
|
});
|
|
}
|
|
|
|
function countSecrets(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())) 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) n++;
|
|
}
|
|
for (const it of s.items || []) if (isSequence(it)) frames(it);
|
|
for (const q of s.sequences || []) frames(q);
|
|
}
|
|
return n;
|
|
}
|
|
|
|
// Pure helpers for the search bar (issue #27). No DOM; tested in Node.
|
|
// build.js strips `export` when bundling, so names here must not collide with other modules.
|
|
|
|
// Where `query` occurs in `text`, ignoring case: [{ start, end }], left to right, not overlapping.
|
|
// A blank query matches nothing.
|
|
function searchRanges(text, query) {
|
|
const q = String(query || '').trim();
|
|
if (!q) return [];
|
|
const re = new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
|
|
const out = [];
|
|
let m;
|
|
while ((m = re.exec(String(text))) !== null) {
|
|
out.push({ start: m.index, end: m.index + m[0].length });
|
|
if (m[0].length === 0) re.lastIndex++; // cannot happen for a non-empty query; never loop forever
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// The next index when stepping `dir` (+1 or -1) through `count` places, wrapping round.
|
|
// -1 when there is nowhere to go.
|
|
function stepSearchIndex(i, dir, count) {
|
|
if (count <= 0) return -1;
|
|
return (((i + dir) % count) + count) % count;
|
|
}
|
|
|
|
// The single-file HTML skeleton. Used by build.js (Node) and by Save in the
|
|
// browser, so a built file and a saved file are produced by the same code.
|
|
// NOTE: the closing script tag is written <\/script> inside the template
|
|
// literal so this source can itself be inlined into a <script> element.
|
|
function assemble({ css, js, payload }) {
|
|
return `<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>Final Wishes</title>
|
|
<style id="fw-css">${css}</style>
|
|
</head>
|
|
<body>
|
|
<div id="printdoc" aria-hidden="true"></div>
|
|
<main id="app"><noscript>This document needs JavaScript enabled.</noscript></main>
|
|
<script id="payload" type="application/octet-stream">${payload}<\/script>
|
|
<script id="fw-js">${js}<\/script>
|
|
</body>
|
|
</html>
|
|
`;
|
|
}
|
|
|
|
// The capture tool (issue #28): a separate page with no document, no payload and no
|
|
// way to read the main file. Built by build.js into capture.html.
|
|
function assembleCapture({ css, js }) {
|
|
return `<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>Final Wishes: capture walkthroughs</title>
|
|
<style id="fw-css">${css}</style>
|
|
</head>
|
|
<body>
|
|
<main id="app"><noscript>This tool needs JavaScript enabled.</noscript></main>
|
|
<script id="fw-js">${js}<\/script>
|
|
</body>
|
|
</html>
|
|
`;
|
|
}
|
|
|
|
// The version of the app code, shown at the top of the page: "Ver YYMMDDX".
|
|
// 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`.
|
|
|
|
const APP_VERSION = '261127A';
|
|
|
|
const VERSION_RE = /^(\d{6})([A-Z])$/;
|
|
const isVersion = (v) => typeof v === 'string' && VERSION_RE.test(v);
|
|
|
|
// YYMMDD for a Date, in local time.
|
|
function versionDate(date) {
|
|
const p = (n) => String(n).padStart(2, '0');
|
|
return p(date.getFullYear() % 100) + p(date.getMonth() + 1) + p(date.getDate());
|
|
}
|
|
|
|
// The version that follows `current` when released on `date`: the next letter
|
|
// on the same day, or A on a new day.
|
|
function nextVersion(current, date) {
|
|
if (!isVersion(current)) throw new Error('Not a version: ' + current);
|
|
const day = versionDate(date);
|
|
if (!current.startsWith(day)) return day + 'A';
|
|
const letter = current[6];
|
|
if (letter === 'Z') throw new Error('Already 26 versions on ' + day + '; wait until tomorrow.');
|
|
return day + String.fromCharCode(letter.charCodeAt(0) + 1);
|
|
}
|
|
|
|
// UI: unlock / load, section navigation, read-only view, edit mode.
|
|
// All DOM is built with h() + textContent, never innerHTML, so document
|
|
// content can't inject markup.
|
|
(function () {
|
|
const root = document.getElementById('app');
|
|
const state = {
|
|
doc: null,
|
|
passphrase: null, // kept in memory for saving (issue #6)
|
|
current: null, // current section id
|
|
editing: false,
|
|
dirty: false,
|
|
baseline: null, // deep copy of the document at open/save; Cancel reverts to it
|
|
pwChanged: false, // passphrase changed since the last save
|
|
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)
|
|
searchOpen: false, // the search controls are showing in place of the toolbar buttons
|
|
search: null, // { q, hits: [{sid, eid, n}], i, scroll }: the active search (not saved)
|
|
searchAll: false, // true only while building the hidden copy the search counts matches in
|
|
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
|
|
status: '',
|
|
error: '',
|
|
};
|
|
|
|
// ?reset=1 (or #reset=1): after unlock, offer to erase every secret value.
|
|
// Read live: typing #reset=1 into an already-open page only fires hashchange, it does not reload.
|
|
const resetRequested = () => /[?#&]reset=1(?![0-9])/.test(location.search + location.hash);
|
|
const resetBanner = () => {
|
|
const n = countSecrets(state.doc);
|
|
const done = () => { state.resetOffered = true; render(); };
|
|
return h('div', { class: 'card', role: 'alert' },
|
|
h('h2', {}, 'Reset: erase secret values'),
|
|
h('p', {}, n ? 'This will erase ' + n + ' secret value' + (n === 1 ? '' : 's') + ' (passwords, PINs, secret images and steps) from this document in memory. Labels and everything else stay.'
|
|
: 'This document has no secret values to erase.'),
|
|
h('p', {}, 'Nothing is written until you Save. Make a Backup copy first if you may need the secrets again, because saving over this file removes them for good.'),
|
|
h('div', { class: 'row' },
|
|
n ? btn('Erase ' + n + ' secret value' + (n === 1 ? '' : 's'), () => {
|
|
const erased = clearSecrets(state.doc);
|
|
state.revealed = new WeakSet();
|
|
state.resetOffered = true;
|
|
markDirty();
|
|
state.status = 'Erased ' + erased + ' secret value' + (erased === 1 ? '' : 's') + '. Save to keep this.';
|
|
render();
|
|
}, 'primary') : null,
|
|
btn(n ? 'Keep them' : 'Dismiss', done)));
|
|
};
|
|
|
|
function h(tag, attrs, ...kids) {
|
|
const el = document.createElement(tag);
|
|
for (const [k, v] of Object.entries(attrs || {})) {
|
|
if (v === false || v == null) continue;
|
|
if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
|
|
else if (k === 'class') el.className = v;
|
|
else if (k in el && k !== 'list') el[k] = v;
|
|
else el.setAttribute(k, v === true ? '' : v);
|
|
}
|
|
for (const kid of kids.flat(Infinity)) {
|
|
if (kid == null || kid === false) continue;
|
|
el.append(kid.nodeType ? kid : document.createTextNode(String(kid)));
|
|
}
|
|
return el;
|
|
}
|
|
const btn = (label, onclick, cls = '', extra = {}) =>
|
|
h('button', Object.assign({ type: 'button', class: 'btn ' + cls, onclick }, extra), label);
|
|
|
|
function markDirty() {
|
|
state.dirty = true;
|
|
const d = document.getElementById('dirty');
|
|
if (d) d.hidden = false;
|
|
state.status = '';
|
|
const st = document.getElementById('status');
|
|
if (st) st.textContent = '';
|
|
}
|
|
function changed(record) {
|
|
touch(state.doc, record);
|
|
markDirty();
|
|
}
|
|
function snapshot() {
|
|
state.baseline = snapshotDoc(state.doc);
|
|
state.pwChanged = false;
|
|
}
|
|
window.addEventListener('beforeunload', (e) => {
|
|
if (state.dirty) { e.preventDefault(); e.returnValue = ''; }
|
|
});
|
|
|
|
// ---------- start / unlock ----------
|
|
function payloadText() {
|
|
const p = document.getElementById('payload');
|
|
return p ? p.textContent.trim() : '';
|
|
}
|
|
|
|
function renderStart() {
|
|
const blob = state.blob || payloadText();
|
|
const msg = h('p', { class: 'error', role: 'alert' }, state.error);
|
|
if (blob) {
|
|
const pw = h('input', { type: 'password', autocomplete: 'current-password', autofocus: true, 'aria-label': 'Passphrase' });
|
|
const form = h('form', { class: 'card start', onsubmit: async (e) => {
|
|
e.preventDefault();
|
|
state.error = '';
|
|
try {
|
|
const doc = JSON.parse(await decrypt(blob, pw.value));
|
|
assertValid(doc);
|
|
state.doc = doc;
|
|
snapshot();
|
|
state.passphrase = pw.value;
|
|
state.blob = null;
|
|
state.current = doc.sections[0] && doc.sections[0].id;
|
|
} catch (err) {
|
|
state.error = err instanceof DecryptError ? err.message : 'Could not open the file: ' + err.message;
|
|
}
|
|
render();
|
|
} },
|
|
h('h1', {}, 'Final Wishes'),
|
|
h('p', {}, 'Enter the passphrase to open this document.'),
|
|
pw, msg, btn('Open', null, 'primary', { type: 'submit' }),
|
|
state.blob ? btn('Choose a different file', () => { state.blob = null; state.error = ''; render(); }, 'small') : null);
|
|
return form;
|
|
}
|
|
// No encrypted data embedded yet (development / first use).
|
|
const file = h('input', { type: 'file', accept: '.json,application/json', 'aria-label': 'Open a JSON file', onchange: async () => {
|
|
try {
|
|
const doc = JSON.parse(await file.files[0].text());
|
|
assertValid(doc);
|
|
state.doc = doc;
|
|
snapshot();
|
|
state.current = doc.sections[0] && doc.sections[0].id;
|
|
state.error = '';
|
|
} catch (err) { state.error = 'Could not open that file: ' + err.message; }
|
|
render();
|
|
} });
|
|
const existing = h('input', { type: 'file', accept: '.html,text/html', 'aria-label': 'Open an existing Final Wishes file', onchange: async () => {
|
|
const m = (await existing.files[0].text()).match(/<script id="payload"[^>]*>([^<]*)<\/script>/);
|
|
if (m && m[1].trim()) { state.blob = m[1].trim(); state.error = ''; }
|
|
else state.error = 'That file has no encrypted Final Wishes data in it.';
|
|
render();
|
|
} });
|
|
return h('div', { class: 'card start' },
|
|
h('h1', {}, 'Final Wishes'),
|
|
h('p', {}, 'No encrypted data is built into this file yet.'),
|
|
h('p', {}, 'Open your existing Final Wishes file (your data is carried into this newer version; the old file is not changed until you save over it):'), existing,
|
|
h('p', {}, 'Import a plain JSON file (you will choose a passphrase when you save):'), file, msg,
|
|
h('p', {}, 'or'),
|
|
btn('Start a new document', () => {
|
|
state.doc = emptyDocument('');
|
|
snapshot();
|
|
state.editing = true;
|
|
render();
|
|
}, 'primary'));
|
|
}
|
|
|
|
// ---------- images ----------
|
|
function setStatus(msg) {
|
|
state.status = msg;
|
|
const st = document.getElementById('status');
|
|
if (st) st.textContent = msg;
|
|
}
|
|
const hasFiles = (e) => !!(e.dataTransfer && [...(e.dataTransfer.types || [])].includes('Files'));
|
|
const isImageFile = (f) => /^image\//.test(f.type) || /\.(png|jpe?g)$/i.test(f.name || '');
|
|
const allRecords = () => state.doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r)));
|
|
const addFrameFrom = (seq) => (name, url) => addFrame(seq, url);
|
|
|
|
// 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.
|
|
// opts.replace: an existing object whose opts.key (default 'value') takes the first file.
|
|
// opts.add(name, url): how a new image is added (default: a new image field on `rec`).
|
|
async function importFiles(rec, files, opts = {}) {
|
|
const key = opts.key || 'value';
|
|
const add = opts.add || ((name, url) => addImageField(rec, opts.pasted ? 'Pasted image' : labelFromFilename(name), url));
|
|
let added = 0;
|
|
const errors = [];
|
|
for (const file of files) {
|
|
try {
|
|
const url = await processImageFile(file);
|
|
if (opts.replace && !added) { opts.replace[key] = url; if (key === 'image') delete opts.replace.marks; }
|
|
else add(file.name, url);
|
|
added++;
|
|
} catch (err) {
|
|
errors.push((file.name ? file.name + ': ' : '') + err.message);
|
|
}
|
|
}
|
|
if (added) changed(rec); // clears the status, so set it afterwards
|
|
setStatus(errors.length ? errors.join(' ') : added + (added === 1 ? ' image added.' : ' images added.'));
|
|
render();
|
|
}
|
|
|
|
// Dropping a file on the page must never navigate away from unsaved work.
|
|
window.addEventListener('dragover', (e) => { if (hasFiles(e)) e.preventDefault(); });
|
|
window.addEventListener('drop', (e) => { if (hasFiles(e)) e.preventDefault(); });
|
|
|
|
// Paste an image: into an image field replaces it, anywhere else in a record adds a new field.
|
|
document.addEventListener('paste', (e) => {
|
|
if (!state.doc) return;
|
|
const files = [...(e.clipboardData ? e.clipboardData.files : [])].filter(isImageFile);
|
|
if (!files.length) return; // ordinary text paste is left alone
|
|
const t = e.target;
|
|
if (t && /^(INPUT|TEXTAREA)$/.test(t.tagName) && e.clipboardData.getData('text/plain')) return;
|
|
if (!state.editing) return setStatus('Choose Edit, then paste into a record or visual sequence.');
|
|
const seqEl = t && t.closest ? t.closest('[data-seq]') : null;
|
|
const seq = seqEl && allSequences(state.doc).find((q) => q.id === seqEl.dataset.seq);
|
|
if (seq) {
|
|
e.preventDefault();
|
|
const fz = t.closest('[data-frame]');
|
|
const frame = fz ? seq.frames[Number(fz.dataset.frame)] : null;
|
|
return importFiles(seq, files, { key: 'image', replace: frame, add: addFrameFrom(seq) });
|
|
}
|
|
const recEl = t && t.closest ? t.closest('[data-rec]') : null;
|
|
const rec = recEl && allRecords().find((r) => r.id === recEl.dataset.rec);
|
|
if (!rec) return setStatus('Click inside a record or visual sequence first, then paste.');
|
|
e.preventDefault();
|
|
const zone = t.closest('[data-field]');
|
|
const field = zone ? rec.fields[Number(zone.dataset.field)] : null;
|
|
importFiles(rec, files, { replace: field && field.kind === 'image' ? field : null, pasted: true });
|
|
});
|
|
|
|
// 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), 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);
|
|
dlg.showModal();
|
|
}
|
|
|
|
// ---------- read-only view ----------
|
|
function statusBadge(status) {
|
|
return status === 'tbd' ? h('span', { class: 'badge tbd nosearch' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done nosearch' }, 'Done') : null;
|
|
}
|
|
|
|
function viewImageField(f) {
|
|
const hidden = f.secret && !state.revealed.has(f);
|
|
const toggle = () => { state.revealed[hidden ? 'add' : 'delete'](f); render(); };
|
|
let value;
|
|
if (!f.value) value = h('span', { class: 'muted' }, '(no image)');
|
|
else if (hidden) value = h('span', {}, h('span', { class: 'secret' }, '(hidden image)'), btn('Show', toggle, 'link', { 'aria-label': 'Show ' + f.label }));
|
|
else value = h('span', {},
|
|
h('img', { class: 'fimg', src: f.value, alt: f.label, tabIndex: 0, title: 'Click to enlarge',
|
|
onclick: () => openLightbox(f.label, f.value), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(f.label, f.value); } }),
|
|
f.secret ? btn('Hide', toggle, 'link', { 'aria-label': 'Hide ' + f.label }) : null);
|
|
return [h('dt', {}, f.label), h('dd', {}, value)];
|
|
}
|
|
|
|
function viewField(f) {
|
|
if (f.kind === 'image') return viewImageField(f);
|
|
let value;
|
|
if (f.secret) {
|
|
const shown = state.revealed.has(f);
|
|
const span = h('span', { class: 'secret' }, !f.value ? '(not set)' : shown ? f.value : '••••••••');
|
|
value = h('span', {}, span, f.value && btn(shown ? 'Hide' : 'Show', () => {
|
|
state.revealed[shown ? 'delete' : 'add'](f);
|
|
render();
|
|
}, 'link', { 'aria-label': (shown ? 'Hide ' : 'Show ') + f.label }));
|
|
} else {
|
|
value = f.value || h('span', { class: 'muted' }, '(blank)');
|
|
}
|
|
return [h('dt', {}, f.label), h('dd', {}, value)];
|
|
}
|
|
|
|
const currentTab = (s) => validTab(s, state.tabs[s.id]);
|
|
const sameTab = (s) => { const t = currentTab(s); return (e) => entryTab(s, e) === t; };
|
|
|
|
// The row of sub-tab buttons (nothing when the section has no sub-tabs).
|
|
function tabBar(s) {
|
|
const tabs = tabsOf(s);
|
|
if (!tabs.length) return null;
|
|
const cur = currentTab(s);
|
|
return h('div', { class: 'tabs', role: 'tablist', 'aria-label': s.title + ' sub-tabs' }, tabs.map((t) => h('button',
|
|
{ type: 'button', role: 'tab', class: 'tab' + (t.id === cur ? ' on' : ''), 'aria-selected': String(t.id === cur),
|
|
onclick: () => { state.tabs[s.id] = t.id; render(); } },
|
|
t.title, ' ', h('span', { class: 'muted small' }, '(' + entriesInTab(s, t.id).length + ')'))));
|
|
}
|
|
|
|
function viewRecord(s, r, i) {
|
|
const arr = s.records;
|
|
const same = sameTab(s);
|
|
const closed = !state.searchAll && state.collapsed.has(r.id);
|
|
const toggle = () => { state.collapsed[closed ? 'delete' : 'add'](r.id); render(); };
|
|
const shift = (dir) => { moveWithin(arr, i, dir, same); changed(r); render(); };
|
|
return h('article', { class: 'card' + (closed ? ' collapsed' : ''), 'data-eid': r.id },
|
|
h('div', { class: 'rechead' },
|
|
h('h3', {}, r.title, ' ', statusBadge(r.status)),
|
|
h('span', { class: 'tools' },
|
|
closed && siblingIndex(arr, i, -1, same) >= 0 ? btn('↑', () => shift(-1), 'icon', { 'aria-label': 'Move ' + r.title + ' up' }) : null,
|
|
closed && siblingIndex(arr, i, 1, same) >= 0 ? btn('↓', () => shift(1), 'icon', { 'aria-label': 'Move ' + r.title + ' down' }) : null,
|
|
btn(closed ? 'Expand' : 'Collapse', toggle, 'small', { 'aria-expanded': String(!closed), 'aria-label': (closed ? 'Expand ' : 'Collapse ') + r.title }))),
|
|
closed ? null : [
|
|
r.fields.length ? h('dl', {}, r.fields.map(viewField)) : null,
|
|
r.notes ? h('p', { class: 'notes' }, r.notes) : null,
|
|
h('p', { class: 'muted small nosearch' }, 'Updated ' + r.updated)]);
|
|
}
|
|
|
|
function foldBar(entries) {
|
|
const recs = entries.filter((r) => !isSequence(r));
|
|
if (!recs.length) return null;
|
|
const setAll = (fold) => { recs.forEach((r) => state.collapsed[fold ? 'add' : 'delete'](r.id)); render(); };
|
|
return h('div', { class: 'row foldbar' },
|
|
btn('Collapse all', () => setAll(true), 'small'), btn('Expand all', () => setAll(false), 'small'));
|
|
}
|
|
|
|
// A frame is hidden (picture and text) if marked secret and not revealed.
|
|
function viewFrame(q, f, k) {
|
|
const hidden = f.secret && !state.revealed.has(f);
|
|
const toggle = () => { state.revealed[hidden ? 'add' : 'delete'](f); render(); };
|
|
const label = q.title + ', step ' + (k + 1);
|
|
const layout = hidden ? 'none' : frameLayout(f);
|
|
return h('div', { class: 'frame ' + layout },
|
|
h('div', { class: 'fnum nosearch' }, 'Step ' + (k + 1)),
|
|
hidden ? h('div', {}, h('span', { class: 'secret' }, '(hidden step)'), btn('Show', toggle, 'link', { 'aria-label': 'Show ' + label })) : [
|
|
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 nosearch' }, 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, 'data-eid': q.id },
|
|
h('h3', {}, q.title),
|
|
viewFrame(q, q.frames[k], k),
|
|
h('div', { class: 'row walknav nosearch' },
|
|
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 nosearch' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
|
|
}
|
|
|
|
function viewSequence(q) {
|
|
if (!state.searchAll && state.walk && state.walk.id === q.id && q.frames.length) return walkSequence(q);
|
|
return h('article', { class: 'card seq', 'data-eid': q.id },
|
|
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 nosearch' }, '(no steps yet)'),
|
|
h('p', { class: 'muted small nosearch' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
|
|
}
|
|
const seqItem = (q) => h('li', { class: 'seqitem' }, viewSequence(q));
|
|
|
|
function viewItem(it, ordered) {
|
|
return h('li', { class: 'item ' + it.status, 'data-eid': it.id },
|
|
h('div', {}, h('strong', {}, it.text), ' ', statusBadge(it.status)),
|
|
it.detail ? h('p', { class: 'notes' }, it.detail) : null);
|
|
}
|
|
|
|
function viewRecords(s) {
|
|
const entries = state.searchAll ? s.records.map((e, i) => ({ e, i })) : entriesInTab(s, currentTab(s));
|
|
return [state.searchAll ? null : tabBar(s),
|
|
hasTabs(s) && !entries.length ? h('p', { class: 'muted nosearch' }, 'Nothing in this sub-tab yet. Choose Edit to add or move records here.') : null,
|
|
state.searchAll ? null : foldBar(entries.map((x) => x.e)),
|
|
entries.map(({ e, i }) => (isSequence(e) ? viewSequence(e) : viewRecord(s, e, i)))];
|
|
}
|
|
|
|
function viewSection(s) {
|
|
return [
|
|
s.intro ? h('p', { class: 'intro' }, s.intro) : null,
|
|
s.kind === 'text' ? [h('p', { class: 'body' }, s.body), (s.sequences || []).map(viewSequence)] : null,
|
|
s.kind === 'records' ? viewRecords(s) : null,
|
|
s.kind === 'steps' ? h('ol', { class: 'items' }, s.items.map((i) => (isSequence(i) ? seqItem(i) : viewItem(i)))) : null,
|
|
s.kind === 'checklist' ? h('ul', { class: 'items' }, s.items.map((i) => (isSequence(i) ? seqItem(i) : viewItem(i)))) : null,
|
|
];
|
|
}
|
|
|
|
// ---------- edit mode ----------
|
|
function input(obj, key, opts = {}, record) {
|
|
const tag = opts.multiline ? 'textarea' : 'input';
|
|
const el = h(tag, { value: obj[key] ?? '', 'aria-label': opts.label || key, rows: opts.multiline ? 3 : undefined,
|
|
oninput: () => { obj[key] = el.value; changed(record); } });
|
|
return el;
|
|
}
|
|
function select(obj, key, values, label, record) {
|
|
const el = h('select', { 'aria-label': label, onchange: () => { obj[key] = el.value; changed(record); } },
|
|
values.map((v) => h('option', { value: v, selected: obj[key] === v }, v)));
|
|
return el;
|
|
}
|
|
// Up / down / delete controls for element i of arr.
|
|
// `message` (string or function) replaces the default delete confirmation.
|
|
// `same` (optional) limits up/down to elements it accepts, e.g. the ones in the same sub-tab.
|
|
function rowTools(arr, i, what, record, quiet = false, message = null, same = () => true) {
|
|
const note = () => (quiet ? markDirty() : changed(record));
|
|
const act = (fn) => () => { fn(); note(); render(); };
|
|
return h('span', { class: 'tools' },
|
|
btn('↑', act(() => moveWithin(arr, i, -1, same)), 'icon', { 'aria-label': 'Move ' + what + ' up', disabled: siblingIndex(arr, i, -1, same) < 0 }),
|
|
btn('↓', act(() => moveWithin(arr, i, 1, same)), 'icon', { 'aria-label': 'Move ' + what + ' down', disabled: siblingIndex(arr, i, 1, same) < 0 }),
|
|
btn('✕', () => { if (confirm(typeof message === 'function' ? message() : message || 'Delete this ' + what + '?')) { removeAt(arr, i); note(); render(); } }, 'icon danger', { 'aria-label': 'Delete ' + what }));
|
|
}
|
|
|
|
// The drop / paste / choose-a-file box for the picture stored at obj[key].
|
|
// onFiles(files) receives the dropped or chosen files; onChange() runs after Remove.
|
|
function imageZone(obj, key, label, attrs, onFiles, onChange) {
|
|
const picker = h('input', { type: 'file', accept: 'image/png,image/jpeg', hidden: true, 'aria-label': 'Choose an image file',
|
|
onchange: () => { onFiles([...picker.files]); picker.value = ''; } });
|
|
const zone = h('div', Object.assign({ class: 'dropzone', tabIndex: 0, 'aria-label': 'Image for ' + label + ': drop, paste or choose a file',
|
|
ondragover: (e) => { if (hasFiles(e)) { e.preventDefault(); zone.classList.add('over'); } },
|
|
ondragleave: () => zone.classList.remove('over'),
|
|
ondrop: (e) => { e.preventDefault(); e.stopPropagation(); zone.classList.remove('over'); onFiles([...e.dataTransfer.files]); } }, attrs),
|
|
obj[key] ? 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.'),
|
|
h('div', { class: 'row' },
|
|
btn('Choose file\u2026', () => picker.click(), 'small'),
|
|
obj[key] ? btn('Remove image', () => { obj[key] = ''; onChange(); render(); }, 'small') : null),
|
|
picker);
|
|
return zone;
|
|
}
|
|
|
|
function editImageField(r, f, i) {
|
|
const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret',
|
|
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(r); } });
|
|
const zone = imageZone(f, 'value', f.label, { 'data-field': String(i) }, (files) => importFiles(r, files, { replace: f }), () => changed(r));
|
|
return h('div', { class: 'field imagefield' },
|
|
h('div', { class: 'row' }, input(f, 'label', { label: 'Field label' }, r), h('label', { class: 'check' }, secret, ' secret'), rowTools(r.fields, i, 'image field', r)),
|
|
zone);
|
|
}
|
|
|
|
function editField(r, f, i) {
|
|
if (f.kind === 'image') return editImageField(r, f, i);
|
|
const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret',
|
|
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(r); } });
|
|
return h('div', { class: 'row field' },
|
|
input(f, 'label', { label: 'Field label' }, r), input(f, 'value', { label: 'Field value' }, r),
|
|
h('label', { class: 'check' }, secret, ' secret'), rowTools(r.fields, i, 'field', r));
|
|
}
|
|
|
|
// "Sub-tab: [select]" for a record or sequence; changing it moves the entry to that tab.
|
|
function moveToRow(s, e) {
|
|
if (!hasTabs(s)) return null;
|
|
const sel = h('select', { 'aria-label': 'Sub-tab of ' + e.title, onchange: () => {
|
|
const t = tabsOf(s).find((x) => x.id === sel.value);
|
|
moveToTab(s, e, sel.value); changed(e);
|
|
render(); setStatus('Moved "' + e.title + '" to ' + t.title + '.');
|
|
} }, tabsOf(s).map((t) => h('option', { value: t.id, selected: t.id === entryTab(s, e) }, t.title)));
|
|
return h('div', { class: 'row' }, h('label', { class: 'check' }, 'Sub-tab ', sel));
|
|
}
|
|
|
|
// Add, rename, reorder and delete the sub-tabs of a records section.
|
|
function tabPanel(s) {
|
|
const cur = currentTab(s);
|
|
const name = h('input', { placeholder: 'New sub-tab name (e.g. Online)', 'aria-label': 'New sub-tab name',
|
|
onkeydown: (e) => { if (e.key === 'Enter') { e.preventDefault(); add(); } } });
|
|
const add = () => {
|
|
if (!name.value.trim()) return name.focus();
|
|
state.tabs[s.id] = addSubsection(state.doc, s, name.value).id;
|
|
markDirty(); render();
|
|
};
|
|
let manage = null;
|
|
if (hasTabs(s)) {
|
|
const tab = tabsOf(s).find((t) => t.id === cur);
|
|
const idx = s.subsections.findIndex((t) => t.id === cur);
|
|
const rename = h('input', { value: tab.title, 'aria-label': 'Name of the selected sub-tab',
|
|
onchange: () => { if (renameTab(s, cur, rename.value)) { changed(); render(); } else rename.value = tab.title; } });
|
|
const shift = (dir) => () => { moveSubsection(s, cur, dir); changed(); render(); };
|
|
manage = h('div', { class: 'row' }, rename, cur ? h('span', { class: 'tools' },
|
|
btn('←', shift(-1), 'icon', { 'aria-label': 'Move sub-tab left', disabled: idx <= 0 }),
|
|
btn('→', shift(1), 'icon', { 'aria-label': 'Move sub-tab right', disabled: idx >= s.subsections.length - 1 }),
|
|
btn('✕', () => {
|
|
if (!confirm(deleteSubsectionMessage(s, cur))) return;
|
|
removeSubsection(s, cur); state.tabs[s.id] = ''; changed(); render();
|
|
}, 'icon danger', { 'aria-label': 'Delete sub-tab' })) : h('span', { class: 'muted small' }, 'Catch-all for records not placed in a sub-tab'));
|
|
}
|
|
return h('div', { class: 'card editing' },
|
|
h('strong', {}, 'Sub-tabs'),
|
|
h('div', { class: 'row' }, name, btn('+ Add sub-tab', add, 'small')),
|
|
manage);
|
|
}
|
|
|
|
function editRecord(s, r, i) {
|
|
const picker = h('input', { type: 'file', multiple: true, accept: 'image/png,image/jpeg', hidden: true, 'aria-label': 'Choose images to add',
|
|
onchange: () => { importFiles(r, [...picker.files]); picker.value = ''; } });
|
|
return h('article', { class: 'card editing', 'data-rec': r.id,
|
|
ondragover: (e) => { if (hasFiles(e)) e.preventDefault(); },
|
|
ondrop: (e) => { e.preventDefault(); importFiles(r, [...e.dataTransfer.files]); } },
|
|
h('div', { class: 'row' }, input(r, 'title', { label: 'Record title' }, r), select(r, 'status', ['ok', 'tbd'], 'Record status', r), rowTools(s.records, i, 'record', undefined, false, null, sameTab(s))),
|
|
moveToRow(s, r),
|
|
r.fields.map((f, k) => editField(r, f, k)),
|
|
h('div', { class: 'row' },
|
|
btn('+ Add field', () => { addField(r); changed(r); render(); }, 'small'),
|
|
btn('+ Add image\u2026', () => picker.click(), 'small'), picker),
|
|
h('label', {}, 'Notes', input(r, 'notes', { multiline: true, label: 'Notes' }, r)));
|
|
}
|
|
|
|
const LAYOUT_LABELS = [['right', 'Text right of image'], ['under', 'Text under image'], ['none', 'No text']];
|
|
|
|
// 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) }), () => { 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) {
|
|
const picker = h('input', { type: 'file', multiple: true, accept: 'image/png,image/jpeg', hidden: true, 'aria-label': 'Choose images for new steps',
|
|
onchange: () => { importFiles(q, [...picker.files], { add: addFrameFrom(q) }); picker.value = ''; } });
|
|
return h('article', { class: 'card editing seq', 'data-seq': q.id,
|
|
ondragover: (e) => { if (hasFiles(e)) e.preventDefault(); },
|
|
ondrop: (e) => { e.preventDefault(); importFiles(q, [...e.dataTransfer.files], { add: addFrameFrom(q) }); } },
|
|
h('div', { class: 'row' }, input(q, 'title', { label: 'Visual sequence title' }, q), rowTools(list, i, 'visual sequence', q, false, null, s ? sameTab(s) : undefined)),
|
|
s ? moveToRow(s, q) : null,
|
|
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,
|
|
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');
|
|
|
|
function editItem(s, it, i) {
|
|
return h('li', { class: 'card editing' },
|
|
h('div', { class: 'row' }, input(it, 'text', { label: 'Item text' }), select(it, 'status', ['open', 'done', 'tbd'], 'Item status'), rowTools(s.items, i, 'item')),
|
|
h('label', {}, 'Detail', input(it, 'detail', { multiline: true, label: 'Detail' })));
|
|
}
|
|
|
|
function editSection(s) {
|
|
const secIdx = state.doc.sections.indexOf(s);
|
|
return [
|
|
h('div', { class: 'card editing' },
|
|
h('div', { class: 'row' }, input(s, 'title', { label: 'Section title' }), rowTools(state.doc.sections, secIdx, 'section', undefined, false, () => deleteSectionMessage(s))),
|
|
h('label', {}, 'Intro', input(s, 'intro', { multiline: true, label: 'Section intro' }))),
|
|
s.kind === 'text' ? [h('label', {}, 'Text', input(s, 'body', { multiline: true, label: 'Body' })),
|
|
(s.sequences || []).map((q, i) => editSequence(s.sequences, q, i)), h('div', { class: 'row' }, addSeqBtn(s))] : null,
|
|
s.kind === 'records' ? [tabPanel(s), tabBar(s),
|
|
entriesInTab(s, currentTab(s)).map(({ e, i }) => (isSequence(e) ? editSequence(s.records, e, i, s) : editRecord(s, e, i))),
|
|
h('div', { class: 'row' }, btn('+ Add record', () => { addRecord(state.doc, s, currentTab(s)); markDirty(); render(); }, 'primary'), addSeqBtn(s))] : null,
|
|
s.kind === 'steps' || s.kind === 'checklist' ? [h('ol', { class: 'items' }, s.items.map((it, i) => (isSequence(it)
|
|
? h('li', { class: 'seqitem' }, editSequence(s.items, it, i)) : editItem(s, it, i)))),
|
|
h('div', { class: 'row' }, btn('+ Add item', () => { addItem(state.doc, s); markDirty(); render(); }, 'primary'), addSeqBtn(s))] : null,
|
|
];
|
|
}
|
|
|
|
// ---------- print header ----------
|
|
const HEADER_ID = '__header';
|
|
|
|
// The running header line, laid out left | unaligned... | right.
|
|
function headerEl(doc) {
|
|
const L = headerLayout(doc);
|
|
return h('div', { class: 'phead' },
|
|
L.left ? h('span', { class: 'ph-left' }, L.left) : null,
|
|
h('span', { class: 'ph-mid' }, L.middle.map((t) => h('span', {}, t))),
|
|
L.right ? h('span', { class: 'ph-right' }, L.right) : null);
|
|
}
|
|
|
|
function headerPanel() {
|
|
const doc = state.doc;
|
|
const preview = h('div', { class: 'card hpreview', 'aria-label': 'Header preview' });
|
|
const refresh = () => preview.replaceChildren(headerEl(doc));
|
|
refresh();
|
|
const intro = h('p', { class: 'intro' }, 'This line is printed at the top of every page. Left-aligned text comes first, unaligned fields sit in the middle, and the right-aligned field comes last. Only one field can be left aligned and one right aligned.');
|
|
if (!state.editing) return [intro, preview, h('p', { class: 'muted' }, 'Choose Edit to change it.')];
|
|
|
|
const fields = ensureHeader(doc).fields;
|
|
return [intro, preview,
|
|
fields.map((f, i) => {
|
|
const taken = takenAligns(fields, f);
|
|
const kind = h('select', { 'aria-label': 'Field type', onchange: () => { f.kind = kind.value; markDirty(); render(); } },
|
|
[['text', 'Text'], ['lastUpdated', 'Last updated']].map(([v, l]) => h('option', { value: v, selected: f.kind === v }, l)));
|
|
const text = h('input', { value: f.text, 'aria-label': f.kind === 'lastUpdated' ? 'Label before the date' : 'Header text',
|
|
placeholder: f.kind === 'lastUpdated' ? 'Label before the date (optional)' : 'Text',
|
|
oninput: () => { f.text = text.value; markDirty(); refresh(); } });
|
|
const align = h('select', { 'aria-label': 'Alignment', onchange: () => {
|
|
if (!setAlign(fields, f, align.value)) return;
|
|
markDirty(); render();
|
|
} }, [['', 'Not aligned'], ['left', 'Left'], ['right', 'Right']].map(([v, l]) =>
|
|
h('option', { value: v, selected: (f.align || '') === v, disabled: !!v && taken.has(v) }, l + (v && taken.has(v) ? ' (in use)' : ''))));
|
|
return h('div', { class: 'card editing' }, h('div', { class: 'row' }, kind, text, align, rowTools(fields, i, 'header field', null, true)));
|
|
}),
|
|
h('div', { class: 'row' },
|
|
btn('+ Add field', () => { addHeaderField(doc); markDirty(); render(); }, 'primary'),
|
|
btn('Reset to default', () => { delete doc.header; markDirty(); render(); }, 'small'))];
|
|
}
|
|
|
|
// ---------- print ----------
|
|
const printRoot = document.getElementById('printdoc');
|
|
const box = (status) => h('span', { class: 'cb ' + status, 'aria-hidden': 'true' }, status === 'done' ? '✓' : '');
|
|
|
|
// Text, or the picture itself for a visible image field.
|
|
function printCell(f, includeSecrets) {
|
|
if (f.kind === 'image' && f.value && (!f.secret || includeSecrets)) return h('img', { class: 'pimg', src: f.value, alt: f.label });
|
|
return displayValue(f, includeSecrets);
|
|
}
|
|
|
|
function printFrame(f, k, includeSecrets) {
|
|
const v = frameView(f, includeSecrets);
|
|
return h('div', { class: 'pframe ' + v.layout },
|
|
h('div', { class: 'pfnum' }, 'Step ' + (k + 1)),
|
|
v.withheld ? h('p', { class: 'psecret' }, '[withheld]')
|
|
: v.image ? 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.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)));
|
|
}
|
|
|
|
function printRecord(r, includeSecrets) {
|
|
return h('div', { class: 'prec' + (r.status === 'tbd' ? ' tbd' : '') },
|
|
h('h3', {}, r.title, r.status === 'tbd' ? h('span', { class: 'ptag' }, 'TBD') : null),
|
|
r.fields.length ? h('table', {}, h('tbody', {}, r.fields.map((f) => h('tr', {},
|
|
h('th', {}, f.label), h('td', { class: f.secret ? 'psecret' : '' }, printCell(f, includeSecrets)))))) : null,
|
|
r.notes ? h('p', { class: 'pnotes' }, r.notes) : null);
|
|
}
|
|
|
|
function printItem(it, numbered) {
|
|
return h('li', { class: 'pitem ' + it.status },
|
|
box(it.status), h('strong', {}, it.text), it.status === 'tbd' ? h('span', { class: 'ptag' }, 'TBD') : null,
|
|
it.detail ? h('p', { class: 'pnotes' }, it.detail) : null);
|
|
}
|
|
|
|
function buildPrintDoc(includeSecrets) {
|
|
const doc = state.doc;
|
|
const kept = includeSecrets ? 'This copy INCLUDES passwords, PINs and other secrets. Keep it locked away (fire safe or sealed envelope).'
|
|
: 'Secrets (passwords, PINs, security answers) are WITHHELD from this copy. They are stored in the encrypted file.';
|
|
const content = [
|
|
h('section', { class: 'pcover' },
|
|
h('h1', {}, doc.meta.title || 'Final Wishes'),
|
|
doc.meta.owner ? h('p', { class: 'powner' }, 'Prepared by ' + doc.meta.owner) : null,
|
|
h('p', {}, 'Last update: ' + doc.meta.lastUpdated),
|
|
h('p', { class: 'pnote' + (includeSecrets ? ' warn' : '') }, kept),
|
|
h('p', {}, 'Items marked TBD are not yet filled in. A box beside an instruction is for ticking it off as it is done.'),
|
|
h('h2', {}, 'Contents'),
|
|
h('ol', { class: 'ptoc' }, doc.sections.map((s) => h('li', {}, s.title)))),
|
|
doc.sections.map((s) => h('section', { class: 'psec' },
|
|
h('h2', {}, s.title),
|
|
s.intro ? h('p', { class: 'pintro' }, s.intro) : null,
|
|
s.kind === 'text' ? [h('p', { class: 'pbody' }, s.body), (s.sequences || []).map((q) => printSequence(q, includeSecrets))] : null,
|
|
s.kind === 'records' ? printGroups(s).map((g) => [g.title == null ? null : h('h3', { class: 'psubhead' }, g.title),
|
|
g.entries.map((r) => (isSequence(r) ? printSequence(r, includeSecrets) : printRecord(r, includeSecrets)))]) : null,
|
|
s.kind === 'steps' ? h('ol', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, includeSecrets)) : printItem(i)))) : null,
|
|
s.kind === 'checklist' ? h('ul', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, includeSecrets)) : printItem(i)))) : null)),
|
|
].flat();
|
|
// The header sits in <thead> so the browser repeats it, in flow, at the top of every page.
|
|
printRoot.replaceChildren(h('table', { class: 'ptable' },
|
|
h('thead', {}, h('tr', {}, h('td', {}, headerEl(doc)))),
|
|
h('tbody', {}, h('tr', {}, h('td', {}, content)))));
|
|
}
|
|
window.addEventListener('afterprint', () => printRoot.replaceChildren()); // don't leave secrets lingering in the DOM
|
|
|
|
function openPrintDialog() {
|
|
const n = countSecrets(state.doc);
|
|
const radio = (value, checked, text) => h('label', { class: 'radio' }, h('input', { type: 'radio', name: 'mode', value, checked }), ' ' + text);
|
|
const dlg = h('dialog', { class: 'card', 'aria-label': 'Print options' },
|
|
h('h3', {}, 'Print'),
|
|
radio('mask', true, 'Withhold secrets (safe overview; ' + n + ' secret value' + (n === 1 ? '' : 's') + ' hidden)'),
|
|
radio('include', false, 'Include secrets (full copy: store it securely)'),
|
|
h('div', { class: 'row' },
|
|
btn('Cancel', () => { dlg.close(); dlg.remove(); }),
|
|
btn('Print', async () => {
|
|
const include = dlg.querySelector('input[name=mode]:checked').value === 'include';
|
|
dlg.close(); dlg.remove();
|
|
buildPrintDoc(include);
|
|
// Pictures must be decoded before the browser lays out the pages.
|
|
await Promise.all([...printRoot.querySelectorAll('img')].map((img) => img.decode().catch(() => {})));
|
|
window.print();
|
|
}, 'primary')));
|
|
document.body.append(dlg);
|
|
dlg.showModal();
|
|
}
|
|
|
|
// ---------- save ----------
|
|
const byId = (id) => document.getElementById(id);
|
|
|
|
function downloadFile(html, name) {
|
|
const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
|
|
const a = h('a', { href: url, download: name });
|
|
document.body.append(a);
|
|
a.click();
|
|
a.remove();
|
|
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
|
}
|
|
|
|
// Resolves to the chosen passphrase, or null if cancelled.
|
|
function askPassphrase(title, intro) {
|
|
return new Promise((resolve) => {
|
|
const p1 = h('input', { type: 'password', autocomplete: 'new-password', 'aria-label': 'New passphrase' });
|
|
const p2 = h('input', { type: 'password', autocomplete: 'new-password', 'aria-label': 'Repeat passphrase' });
|
|
const err = h('p', { class: 'error', role: 'alert' });
|
|
const finish = (v) => { dlg.close(); dlg.remove(); resolve(v); };
|
|
const dlg = h('dialog', { class: 'card', 'aria-label': title },
|
|
h('form', { onsubmit: (e) => {
|
|
e.preventDefault();
|
|
const problem = passphraseProblem(p1.value);
|
|
if (problem) err.textContent = problem;
|
|
else if (p1.value !== p2.value) err.textContent = 'The two entries do not match.';
|
|
else finish(p1.value);
|
|
} },
|
|
h('h3', {}, title), h('p', {}, intro), p1, p2, err,
|
|
h('div', { class: 'row' }, btn('Cancel', () => finish(null)), btn('Set passphrase', null, 'primary', { type: 'submit' }))));
|
|
dlg.addEventListener('cancel', () => resolve(null));
|
|
document.body.append(dlg);
|
|
dlg.showModal();
|
|
p1.focus();
|
|
});
|
|
}
|
|
|
|
// ---------- import captured walkthroughs (issue #28) ----------
|
|
// Open a bundle made by capture.html, then choose where each walkthrough goes. All or
|
|
// nothing per bundle: a wrong passphrase or damaged file imports nothing. The bundle file is
|
|
// never changed, so walkthroughs you skip can be imported from it later.
|
|
function importCaptures() {
|
|
const dests = destinations(state.doc);
|
|
const file = h('input', { type: 'file', accept: '.fwcapture,text/plain', 'aria-label': 'Capture bundle file' });
|
|
const pw = h('input', { type: 'password', autocomplete: 'off', placeholder: 'Bundle passphrase', 'aria-label': 'Bundle passphrase' });
|
|
const msg = h('p', { class: 'error', role: 'alert' });
|
|
const list = h('div', {});
|
|
const go = btn('Import selected', null, 'primary', { type: 'button', hidden: true });
|
|
let rows = [];
|
|
const close = () => { dlg.close(); dlg.remove(); };
|
|
const open = async () => {
|
|
msg.textContent = '';
|
|
try {
|
|
if (!file.files[0]) throw new Error('Choose the bundle file first.');
|
|
const bundle = await openBundle(await file.files[0].text(), pw.value);
|
|
if (!bundle.walkthroughs.length) throw new Error('That bundle has no walkthroughs.');
|
|
rows = bundle.walkthroughs.map((w) => {
|
|
const use = h('input', { type: 'checkbox', checked: true, 'aria-label': 'Import this walkthrough' });
|
|
const title = h('input', { value: w.title, 'aria-label': 'Walkthrough name' });
|
|
const where = h('select', { 'aria-label': 'Where to put it' }, dests.map((d) => h('option', { value: d.key }, d.label)));
|
|
const cur = state.doc.sections.find((x) => x.id === state.current);
|
|
if (cur) where.value = cur.id + '|';
|
|
return { w, use, title, where, el: h('div', { class: 'importrow' },
|
|
h('label', { class: 'check' }, use, ' ' + w.frames.length + ' step' + (w.frames.length === 1 ? '' : 's') + ', captured ' + w.captured),
|
|
h('div', { class: 'row' }, title, where)) };
|
|
});
|
|
list.replaceChildren(...rows.map((r) => r.el));
|
|
go.hidden = false;
|
|
if (!dests.length) msg.textContent = 'The document has no sections to put them in. Add one first.';
|
|
} catch (err) {
|
|
msg.textContent = err instanceof DecryptError ? err.message : err.message || 'Could not open that file.';
|
|
}
|
|
};
|
|
go.onclick = () => {
|
|
const picked = rows.filter((r) => r.use.checked);
|
|
if (!picked.length) { msg.textContent = 'Tick at least one walkthrough, or Cancel.'; return; }
|
|
for (const r of picked) {
|
|
const d = dests.find((x) => x.key === r.where.value);
|
|
const sec = state.doc.sections.find((x) => x.id === d.sid);
|
|
importWalkthrough(state.doc, sec, Object.assign({}, r.w, { title: r.title.value }), d.tab);
|
|
}
|
|
close();
|
|
markDirty();
|
|
state.status = 'Imported ' + picked.length + ' walkthrough' + (picked.length === 1 ? '' : 's') + '. Save to keep them, then delete the bundle file.';
|
|
render();
|
|
};
|
|
const dlg = h('dialog', { class: 'card', 'aria-label': 'Import captured walkthroughs' },
|
|
h('h3', {}, 'Import captured walkthroughs'),
|
|
h('p', {}, 'Choose the bundle file made by the capture tool and enter its passphrase. Nothing is saved until you Save.'),
|
|
file, pw, btn('Open bundle', open, 'small'), msg, list,
|
|
h('div', { class: 'row' }, btn('Cancel', close), go));
|
|
dlg.addEventListener('cancel', () => dlg.remove());
|
|
document.body.append(dlg);
|
|
dlg.showModal();
|
|
}
|
|
|
|
// backup=true downloads final-wishes-YYYYMMDD.html; otherwise writes the main file.
|
|
async function save({ backup = false } = {}) {
|
|
try {
|
|
if (!state.passphrase) {
|
|
const p = await askPassphrase('Choose a passphrase', 'This passphrase encrypts the document. Without it nobody can open it, so store it where your executor can find it.');
|
|
if (!p) return;
|
|
state.passphrase = p;
|
|
}
|
|
assertValid(state.doc);
|
|
const html = assemble({
|
|
css: byId('fw-css').textContent,
|
|
js: byId('fw-js').textContent,
|
|
payload: await encrypt(JSON.stringify(state.doc), state.passphrase),
|
|
});
|
|
if (backup) {
|
|
const name = backupName(new Date());
|
|
downloadFile(html, name);
|
|
state.status = 'Backup copy downloaded as ' + name + '.';
|
|
} else if (window.showSaveFilePicker) {
|
|
if (!state.handle) {
|
|
state.handle = await window.showSaveFilePicker({ suggestedName: 'final-wishes.html', types: [{ description: 'Final Wishes', accept: { 'text/html': ['.html'] } }] });
|
|
}
|
|
try {
|
|
const w = await state.handle.createWritable();
|
|
await w.write(html);
|
|
await w.close();
|
|
state.status = 'Saved to ' + state.handle.name + '.';
|
|
} catch (e) {
|
|
if (!e || (e.name !== 'NotAllowedError' && e.name !== 'SecurityError')) throw e;
|
|
// Chrome created the (empty) file but refuses to write it, e.g. a protected folder.
|
|
// Forget the handle so the next Save asks again, and hand over a download instead.
|
|
state.handle = null;
|
|
downloadFile(html, 'final-wishes.html');
|
|
state.status = 'Chrome would not let this page write to the chosen location, so final-wishes.html was downloaded instead. Delete the empty file it left behind and replace your old copy with the download.';
|
|
}
|
|
state.dirty = false;
|
|
snapshot();
|
|
} else {
|
|
downloadFile(html, 'final-wishes.html');
|
|
state.status = 'Downloaded final-wishes.html. Replace the old copy on the thumbdrive with it.';
|
|
state.dirty = false;
|
|
snapshot();
|
|
}
|
|
} catch (e) {
|
|
if (e && e.name === 'AbortError') return; // user closed the file picker
|
|
state.status = 'Save failed: ' + (e && e.message ? e.message : e);
|
|
}
|
|
render();
|
|
}
|
|
|
|
// Cancel: throw away unsaved edits to the section (or print header) on
|
|
// screen, back to how it was at the last open/save, then leave edit mode.
|
|
function cancelEdit() {
|
|
const onHeader = state.current === HEADER_ID;
|
|
const id = state.current;
|
|
const differs = onHeader ? headerDiffers(state.doc, state.baseline) : sectionDiffers(state.doc, state.baseline, id);
|
|
if (differs) {
|
|
if (!confirm('Discard your unsaved changes to this ' + (onHeader ? 'print header' : 'section') + '?')) return;
|
|
if (onHeader) revertHeader(state.doc, state.baseline);
|
|
else state.current = revertSection(state.doc, state.baseline, id);
|
|
state.dirty = state.pwChanged || docDiffers(state.doc, state.baseline);
|
|
state.status = 'Changes discarded.';
|
|
}
|
|
state.editing = false;
|
|
render();
|
|
}
|
|
|
|
async function changePassphrase() {
|
|
const p = await askPassphrase('Change passphrase', 'The new passphrase takes effect when you next save. Until then the saved file still opens with the old one.');
|
|
if (!p) return;
|
|
state.passphrase = p;
|
|
state.pwChanged = true;
|
|
markDirty();
|
|
state.status = 'Passphrase changed. Save to apply it.';
|
|
render();
|
|
}
|
|
|
|
document.addEventListener('keydown', (e) => {
|
|
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's' && state.doc) { e.preventDefault(); save(); }
|
|
});
|
|
|
|
// ---------- shell ----------
|
|
function renderNav() {
|
|
const nav = h('nav', { 'aria-label': 'Sections' },
|
|
h('ul', {}, state.doc.sections.map((s) => h('li', {},
|
|
h('a', { href: '#' + s.id, class: s.id === state.current ? 'current' : '', onclick: (e) => { e.preventDefault(); state.current = s.id; render(); } }, s.title)))),
|
|
h('ul', { class: 'navextra' }, h('li', {},
|
|
h('a', { href: '#header', class: state.current === HEADER_ID ? 'current' : '', onclick: (e) => { e.preventDefault(); state.current = HEADER_ID; render(); } }, 'Print header'))));
|
|
if (state.editing) {
|
|
const kind = h('select', { 'aria-label': 'New section type' }, SECTION_KINDS.map((k) => h('option', { value: k }, k)));
|
|
const title = h('input', { placeholder: 'New section title', 'aria-label': 'New section title' });
|
|
nav.append(h('div', { class: 'addsec' }, title, kind, btn('+ Add section', () => {
|
|
if (!title.value.trim()) return title.focus();
|
|
state.current = addSection(state.doc, kind.value, title.value.trim()).id;
|
|
markDirty(); render();
|
|
}, 'small')));
|
|
}
|
|
return nav;
|
|
}
|
|
|
|
function render() {
|
|
if (capture && !state.editing) endCapture(); // sharing only lasts while editing
|
|
if (state.editing) { state.search = null; state.searchOpen = false; } // search is for reading; Edit clears it
|
|
const keepFocus = searchEl && searchEl.contains(document.activeElement) ? document.activeElement : null;
|
|
root.replaceChildren();
|
|
if (!state.doc) return root.append(renderStart());
|
|
const onHeader = state.current === HEADER_ID;
|
|
const sec = onHeader ? null : state.doc.sections.find((s) => s.id === state.current) || state.doc.sections[0];
|
|
if (sec) state.current = sec.id;
|
|
root.append(
|
|
h('header', { class: 'top' },
|
|
h('div', { class: 'titlerow' },
|
|
h('h1', {}, state.doc.meta.title || 'Final Wishes'),
|
|
h('span', { class: 'muted' }, 'Last update: ' + state.doc.meta.lastUpdated),
|
|
h('span', { class: 'muted', id: 'version', title: 'Version of this app' }, 'Ver ' + APP_VERSION),
|
|
h('span', { id: 'dirty', class: 'badge tbd', hidden: !state.dirty }, 'Unsaved changes'),
|
|
h('span', { id: 'status', class: 'muted', role: 'status' }, state.status)),
|
|
// While searching, the search controls take the toolbar's place; Cancel brings the buttons back.
|
|
h('div', { class: 'toolbar' }, state.searchOpen ? searchBarEl() : [
|
|
btn('Save', () => save(), state.dirty ? 'primary' : ''),
|
|
state.editing ? btn('Cancel', cancelEdit, '', { title: 'Discard unsaved changes to this section and stop editing' }) : null,
|
|
btn('Backup copy', () => save({ backup: true })),
|
|
btn('Change passphrase', changePassphrase),
|
|
btn('Print…', openPrintDialog),
|
|
state.editing ? null : btn('Import captures…', importCaptures, '', { title: 'Merge walkthroughs captured with the separate capture tool' }),
|
|
state.editing ? null : btn('Search', openSearch, '', { id: 'searchopen', title: 'Find a word in the document' }),
|
|
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : '')])),
|
|
...(resetRequested() && !state.resetOffered ? [resetBanner()] : []), // never pass null: append() would print "null"
|
|
h('div', { class: 'layout' }, renderNav(),
|
|
h('main', {}, onHeader ? [h('h2', {}, 'Print header'), headerPanel()]
|
|
: sec ? [h('h2', {}, sec.title), state.editing ? editSection(sec) : viewSection(sec)]
|
|
: h('p', { class: 'muted' }, 'No sections yet. Choose Edit to add one.'))));
|
|
if (state.searchOpen) updateSearchUi();
|
|
if (keepFocus) keepFocus.focus();
|
|
highlightSearch();
|
|
}
|
|
|
|
// ---------- search (issue #27) ----------
|
|
// The search bar is built once and re-attached on every render(), so what was typed survives.
|
|
// Matches are counted in a hidden copy of every section (all sub-tabs, nothing folded) built by
|
|
// the same view functions as the page, so the count agrees with what is shown. Secret values,
|
|
// buttons, form fields and page furniture are never searched (see SEARCH_SKIP).
|
|
const SEARCH_SKIP = 'button,textarea,input,select,script,style,.secret,.nosearch,[hidden]';
|
|
let searchEl = null, searchInput = null, searchNote = null, searchBtns = {};
|
|
|
|
function searchBarEl() {
|
|
if (searchEl) return searchEl;
|
|
searchInput = h('input', { type: 'search', class: 'searchbox', 'aria-label': 'Search the document', placeholder: 'Search', autocomplete: 'off',
|
|
oninput: () => { if (state.search) { state.search = null; clearHighlights(); updateSearchUi(); } },
|
|
onkeydown: (e) => {
|
|
const found = state.search && state.search.hits.length;
|
|
if (e.key === 'Tab' && found) { e.preventDefault(); stepSearch(e.shiftKey ? -1 : 1); }
|
|
else if (e.key === 'Enter') {
|
|
e.preventDefault();
|
|
if (found && state.search.q === searchInput.value.trim()) stepSearch(e.shiftKey ? -1 : 1); else runSearch();
|
|
} else if (e.key === 'Escape') cancelSearch();
|
|
} });
|
|
searchNote = h('span', { class: 'muted small searchnote', role: 'status' });
|
|
searchBtns = {
|
|
search: btn('Search', runSearch, 'primary'),
|
|
prev: btn('\u2190 Previous', () => stepSearch(-1), '', { 'aria-label': 'Previous match' }),
|
|
next: btn('Next \u2192', () => stepSearch(1), '', { 'aria-label': 'Next match' }),
|
|
cancel: btn('Cancel', cancelSearch),
|
|
};
|
|
searchEl = h('div', { class: 'searchbar', role: 'search' }, searchInput, searchNote,
|
|
searchBtns.search, searchBtns.prev, searchBtns.next, searchBtns.cancel);
|
|
return searchEl;
|
|
}
|
|
|
|
function openSearch() {
|
|
state.searchOpen = true;
|
|
render();
|
|
searchInput.focus();
|
|
}
|
|
|
|
function updateSearchUi() {
|
|
if (!searchEl) return;
|
|
const s = state.search;
|
|
const n = s ? s.hits.length : 0;
|
|
searchNote.textContent = !s ? '' : n ? (s.i + 1) + ' of ' + n : 'Not found';
|
|
searchBtns.prev.disabled = searchBtns.next.disabled = n === 0;
|
|
}
|
|
|
|
// Every text node under `container` that the search may look at.
|
|
function searchableText(container) {
|
|
const out = [];
|
|
const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, {
|
|
acceptNode: (n) => (n.parentElement && !n.parentElement.closest(SEARCH_SKIP) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT) });
|
|
while (walker.nextNode()) out.push(walker.currentNode);
|
|
return out;
|
|
}
|
|
|
|
// Matches under `container`, in order, each labelled with the entry (record, item or
|
|
// sequence) it sits in and its count within that entry. '' means section-level text.
|
|
function matchesIn(container, q) {
|
|
const seen = {};
|
|
const out = [];
|
|
for (const node of searchableText(container)) {
|
|
const ranges = searchRanges(node.nodeValue, q);
|
|
if (!ranges.length) continue;
|
|
const entry = node.parentElement.closest('[data-eid]');
|
|
const eid = entry ? entry.dataset.eid : '';
|
|
for (const r of ranges) out.push({ node, start: r.start, end: r.end, eid, n: (seen[eid] = (seen[eid] || 0) + 1) - 1 });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function findAllHits(q) {
|
|
let host;
|
|
state.searchAll = true;
|
|
try {
|
|
host = h('div', {}, state.doc.sections.map((s) => h('section', { 'data-sid': s.id }, h('h2', {}, s.title), viewSection(s))));
|
|
} finally {
|
|
state.searchAll = false;
|
|
}
|
|
const hits = [];
|
|
for (const sec of host.querySelectorAll('section[data-sid]')) {
|
|
for (const m of matchesIn(sec, q)) hits.push({ sid: sec.dataset.sid, eid: m.eid, n: m.n });
|
|
}
|
|
return hits;
|
|
}
|
|
|
|
function runSearch() {
|
|
const q = searchInput.value.trim();
|
|
if (!q) { state.search = null; return render(); }
|
|
state.search = { q, hits: findAllHits(q), i: -1 };
|
|
if (state.search.hits.length) stepSearch(1); else render();
|
|
}
|
|
|
|
// Cancel: forget the search and put the toolbar buttons back.
|
|
function cancelSearch() {
|
|
searchInput.value = '';
|
|
state.search = null;
|
|
state.searchOpen = false;
|
|
render();
|
|
const again = document.getElementById('searchopen');
|
|
if (again) again.focus();
|
|
}
|
|
|
|
// Go to match i: its section, its sub-tab, unfolded, then highlight and scroll to it.
|
|
function stepSearch(dir) {
|
|
const s = state.search;
|
|
if (!s || !s.hits.length) return;
|
|
s.i = stepSearchIndex(s.i, dir, s.hits.length);
|
|
const hit = s.hits[s.i];
|
|
const sec = state.doc.sections.find((x) => x.id === hit.sid);
|
|
state.current = hit.sid;
|
|
state.walk = null;
|
|
if (hit.eid && sec) {
|
|
state.collapsed.delete(hit.eid);
|
|
const list = [...(sec.records || []), ...(sec.items || []), ...(sec.sequences || [])];
|
|
const entry = list.find((x) => x.id === hit.eid);
|
|
if (entry && sec.kind === 'records') state.tabs[sec.id] = entryTab(sec, entry);
|
|
}
|
|
s.scroll = true;
|
|
render();
|
|
}
|
|
|
|
function clearHighlights() {
|
|
for (const m of root.querySelectorAll('mark.hit')) {
|
|
const parent = m.parentNode;
|
|
m.replaceWith(...m.childNodes);
|
|
parent.normalize();
|
|
}
|
|
}
|
|
|
|
// After each render: wrap every match on screen in <mark>, the current one stronger.
|
|
function highlightSearch() {
|
|
const s = state.search;
|
|
if (!s || !s.hits.length || state.current === HEADER_ID) return;
|
|
const main = root.querySelector('main');
|
|
if (!main) return;
|
|
const cur = s.hits[s.i];
|
|
const found = matchesIn(main, s.q);
|
|
let current = null;
|
|
for (let k = found.length - 1; k >= 0; k--) { // last first, so earlier offsets stay valid
|
|
const f = found[k];
|
|
const range = document.createRange();
|
|
range.setStart(f.node, f.start);
|
|
range.setEnd(f.node, f.end);
|
|
const mark = document.createElement('mark');
|
|
mark.className = 'hit' + (cur && state.current === cur.sid && f.eid === cur.eid && f.n === cur.n ? ' cur' : '');
|
|
range.surroundContents(mark);
|
|
if (mark.classList.contains('cur')) current = mark;
|
|
}
|
|
if (current && s.scroll) current.scrollIntoView({ block: 'center' });
|
|
s.scroll = false;
|
|
}
|
|
|
|
window.addEventListener('hashchange', () => { state.resetOffered = false; render(); });
|
|
render();
|
|
})();
|
|
</script>
|
|
</body>
|
|
</html>
|