Add images as a record field (drop, paste, import)
Images are downscaled, re-encoded and stored inside the encrypted document. Closes #10 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -18,6 +18,8 @@ The passphrase is prompted for (hidden) or read from `FW_PASSPHRASE`.
|
|||||||
- `src/crypto.js` passphrase encryption (PBKDF2 -> AES-256-GCM)
|
- `src/crypto.js` passphrase encryption (PBKDF2 -> AES-256-GCM)
|
||||||
- `src/model.js` document schema and validation (sections, records, and the
|
- `src/model.js` document schema and validation (sections, records, and the
|
||||||
optional print `header`); `src/ops.js` edit helpers
|
optional print `header`); `src/ops.js` edit helpers
|
||||||
|
- `src/images.js` image-field helpers and the import pipeline (PNG/JPEG only,
|
||||||
|
downscaled and re-encoded in the browser)
|
||||||
- `src/print.js` print helpers (secret masking, header layout)
|
- `src/print.js` print helpers (secret masking, header layout)
|
||||||
- `src/app.js` + `src/style.css` the UI, including the Print header panel
|
- `src/app.js` + `src/style.css` the UI, including the Print header panel
|
||||||
- `src/template.js` the HTML skeleton shared by `build.js` and in-page Save
|
- `src/template.js` the HTML skeleton shared by `build.js` and in-page Save
|
||||||
|
|||||||
2
build.js
2
build.js
@@ -17,7 +17,7 @@ const root = dirname(fileURLToPath(import.meta.url));
|
|||||||
const read = (p) => readFileSync(join(root, 'src', p), 'utf8');
|
const read = (p) => readFileSync(join(root, 'src', p), 'utf8');
|
||||||
|
|
||||||
// Modules are concatenated (ES `import` lines and `export` keywords dropped) ahead of app.js into one scope.
|
// Modules are concatenated (ES `import` lines and `export` keywords dropped) ahead of app.js into one scope.
|
||||||
const MODULES = ['crypto.js', 'model.js', 'ops.js', 'print.js', 'template.js'];
|
const MODULES = ['crypto.js', 'images.js', 'model.js', 'ops.js', 'print.js', 'template.js'];
|
||||||
export function bundleJs() {
|
export function bundleJs() {
|
||||||
return MODULES.map((f) => read(f).replace(/^import .*$/gm, '').replace(/^export /gm, '')).concat(read('app.js')).join('\n');
|
return MODULES.map((f) => read(f).replace(/^import .*$/gm, '').replace(/^export /gm, '')).concat(read('app.js')).join('\n');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,36 @@ After sealing, `data/seed.json` is still plaintext. Delete it (and see
|
|||||||
4. If you changed the passphrase, the old file still opens with the *old*
|
4. If you changed the passphrase, the old file still opens with the *old*
|
||||||
one until you save and replace it.
|
one until you save and replace it.
|
||||||
|
|
||||||
|
## Images
|
||||||
|
Any record can hold pictures (scans of documents, photos of a safe's
|
||||||
|
contents, a screenshot of where to click). They are another kind of field, so
|
||||||
|
they have a label, a **secret** checkbox, reorder arrows and a delete button
|
||||||
|
like any other field. In **Edit** mode, add one of three ways:
|
||||||
|
|
||||||
|
- **+ Add image...** in the record, then choose one or more files.
|
||||||
|
- **Drag and drop** a file onto the record (adds a new field) or onto an
|
||||||
|
existing image box (replaces that image).
|
||||||
|
- **Paste** (Ctrl/Cmd+V) with the cursor inside the record (adds a new field),
|
||||||
|
or with an image box selected (replaces it). Text pastes are unaffected.
|
||||||
|
|
||||||
|
What to expect:
|
||||||
|
- Only **PNG and JPEG** are accepted. The type is checked from the file's
|
||||||
|
contents, not its name. Anything else is refused with a message.
|
||||||
|
- Images are **shrunk** so the longest side is at most 1600 px and re-encoded.
|
||||||
|
This also removes camera metadata such as GPS location. A large PNG becomes a
|
||||||
|
JPEG (transparency is lost); small PNGs stay PNG so screenshots stay sharp.
|
||||||
|
Photos usually end up well under 1 MB; there is a hard limit of about 3 MB
|
||||||
|
per image.
|
||||||
|
- Pictures are stored inside the encrypted document, so they are protected by
|
||||||
|
the passphrase like everything else, but they make `final-wishes.html` bigger
|
||||||
|
and each save slower. Add what the executor needs, not everything you have.
|
||||||
|
- **Secret** images are hidden in the viewer behind **Show/Hide** and are
|
||||||
|
withheld ("[withheld]") from a masked print. A photo of an ID card is as
|
||||||
|
sensitive as a password: a full "Include secrets" print contains it.
|
||||||
|
- Click an image in the viewer to enlarge it. In print each image is scaled to
|
||||||
|
fit the page (at most about 4 inches tall).
|
||||||
|
- Dropping a file anywhere on the page never navigates away from unsaved work.
|
||||||
|
|
||||||
## Upgrading the app (new version, same data)
|
## Upgrading the app (new version, same data)
|
||||||
Your data is stored encrypted inside each `final-wishes.html`; the app code
|
Your data is stored encrypted inside each `final-wishes.html`; the app code
|
||||||
sits beside it in the same file. A file therefore keeps running the version it
|
sits beside it in the same file. A file therefore keeps running the version it
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ TO OPEN IT
|
|||||||
4. Start with the "Start here" section, then read the section titled
|
4. Start with the "Start here" section, then read the section titled
|
||||||
"What to do with PC" (my business) when you are ready for it.
|
"What to do with PC" (my business) when you are ready for it.
|
||||||
|
|
||||||
|
Entries may contain pictures (for example scans of documents). Click a
|
||||||
|
picture to enlarge it. Secret pictures stay hidden until you click Show.
|
||||||
|
|
||||||
You do not need internet access, and nothing you do here is sent anywhere.
|
You do not need internet access, and nothing you do here is sent anywhere.
|
||||||
|
|
||||||
TO PRINT IT
|
TO PRINT IT
|
||||||
|
|||||||
122
src/app.js
122
src/app.js
@@ -112,12 +112,87 @@
|
|||||||
}, 'primary'));
|
}, '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 || []);
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
async function importFiles(rec, files, opts = {}) {
|
||||||
|
let added = 0;
|
||||||
|
const errors = [];
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
const url = await processImageFile(file);
|
||||||
|
if (opts.replace && !added) opts.replace.value = url;
|
||||||
|
else addImageField(rec, opts.pasted ? 'Pasted image' : labelFromFilename(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.');
|
||||||
|
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 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 });
|
||||||
|
});
|
||||||
|
|
||||||
|
function openLightbox(f) {
|
||||||
|
const dlg = h('dialog', { class: 'card lightbox', 'aria-label': f.label },
|
||||||
|
h('h3', {}, f.label), h('img', { class: 'bigimg', src: f.value, alt: f.label }),
|
||||||
|
h('div', { class: 'row' }, btn('Close', () => dlg.close(), 'primary')));
|
||||||
|
dlg.addEventListener('close', () => dlg.remove());
|
||||||
|
document.body.append(dlg);
|
||||||
|
dlg.showModal();
|
||||||
|
}
|
||||||
|
|
||||||
// ---------- read-only view ----------
|
// ---------- read-only view ----------
|
||||||
function statusBadge(status) {
|
function statusBadge(status) {
|
||||||
return status === 'tbd' ? h('span', { class: 'badge tbd' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done' }, 'Done') : null;
|
return status === 'tbd' ? h('span', { class: 'badge tbd' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done' }, '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), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(f); } }),
|
||||||
|
f.secret ? btn('Hide', toggle, 'link', { 'aria-label': 'Hide ' + f.label }) : null);
|
||||||
|
return [h('dt', {}, f.label), h('dd', {}, value)];
|
||||||
|
}
|
||||||
|
|
||||||
function viewField(f) {
|
function viewField(f) {
|
||||||
|
if (f.kind === 'image') return viewImageField(f);
|
||||||
let value;
|
let value;
|
||||||
if (f.secret) {
|
if (f.secret) {
|
||||||
const shown = state.revealed.has(f);
|
const shown = state.revealed.has(f);
|
||||||
@@ -178,7 +253,30 @@
|
|||||||
btn('✕', () => { if (confirm('Delete this ' + what + '?')) { removeAt(arr, i); note(); render(); } }, 'icon danger', { 'aria-label': 'Delete ' + what }));
|
btn('✕', () => { if (confirm('Delete this ' + what + '?')) { removeAt(arr, i); note(); render(); } }, 'icon danger', { 'aria-label': 'Delete ' + what }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function 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 picker = h('input', { type: 'file', accept: 'image/png,image/jpeg', hidden: true, 'aria-label': 'Choose an image file',
|
||||||
|
onchange: () => { importFiles(r, [...picker.files], { replace: f }); picker.value = ''; } });
|
||||||
|
const zone = h('div', { class: 'dropzone', tabIndex: 0, 'data-field': String(i), 'aria-label': 'Image for ' + f.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'); importFiles(r, [...e.dataTransfer.files], { replace: f }); } },
|
||||||
|
f.value ? h('img', { class: 'fimg', src: f.value, alt: f.label }) : null,
|
||||||
|
h('p', { class: 'muted small' }, f.value
|
||||||
|
? formatBytes(dataUrlBytes(f.value)) + '. 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'),
|
||||||
|
f.value ? btn('Remove image', () => { f.value = ''; changed(r); render(); }, 'small') : null),
|
||||||
|
picker);
|
||||||
|
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) {
|
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',
|
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); } });
|
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(r); } });
|
||||||
return h('div', { class: 'row field' },
|
return h('div', { class: 'row field' },
|
||||||
@@ -187,10 +285,16 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function editRecord(s, r, i) {
|
function editRecord(s, r, i) {
|
||||||
return h('article', { class: 'card editing' },
|
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')),
|
h('div', { class: 'row' }, input(r, 'title', { label: 'Record title' }, r), select(r, 'status', ['ok', 'tbd'], 'Record status', r), rowTools(s.records, i, 'record')),
|
||||||
r.fields.map((f, k) => editField(r, f, k)),
|
r.fields.map((f, k) => editField(r, f, k)),
|
||||||
btn('+ Add field', () => { addField(r); changed(r); render(); }, 'small'),
|
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)));
|
h('label', {}, 'Notes', input(r, 'notes', { multiline: true, label: 'Notes' }, r)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,11 +361,17 @@
|
|||||||
const printRoot = document.getElementById('printdoc');
|
const printRoot = document.getElementById('printdoc');
|
||||||
const box = (status) => h('span', { class: 'cb ' + status, 'aria-hidden': 'true' }, status === 'done' ? '✓' : '');
|
const box = (status) => h('span', { class: 'cb ' + status, 'aria-hidden': 'true' }, status === 'done' ? '✓' : '');
|
||||||
|
|
||||||
|
// 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 printRecord(r, includeSecrets) {
|
function printRecord(r, includeSecrets) {
|
||||||
return h('div', { class: 'prec' + (r.status === 'tbd' ? ' tbd' : '') },
|
return h('div', { class: 'prec' + (r.status === 'tbd' ? ' tbd' : '') },
|
||||||
h('h3', {}, r.title, r.status === 'tbd' ? h('span', { class: 'ptag' }, 'TBD') : null),
|
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', {},
|
r.fields.length ? h('table', {}, h('tbody', {}, r.fields.map((f) => h('tr', {},
|
||||||
h('th', {}, f.label), h('td', { class: f.secret ? 'psecret' : '' }, displayValue(f, includeSecrets)))))) : null,
|
h('th', {}, f.label), h('td', { class: f.secret ? 'psecret' : '' }, printCell(f, includeSecrets)))))) : null,
|
||||||
r.notes ? h('p', { class: 'pnotes' }, r.notes) : null);
|
r.notes ? h('p', { class: 'pnotes' }, r.notes) : null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,11 +418,13 @@
|
|||||||
radio('include', false, 'Include secrets (full copy: store it securely)'),
|
radio('include', false, 'Include secrets (full copy: store it securely)'),
|
||||||
h('div', { class: 'row' },
|
h('div', { class: 'row' },
|
||||||
btn('Cancel', () => { dlg.close(); dlg.remove(); }),
|
btn('Cancel', () => { dlg.close(); dlg.remove(); }),
|
||||||
btn('Print', () => {
|
btn('Print', async () => {
|
||||||
const include = dlg.querySelector('input[name=mode]:checked').value === 'include';
|
const include = dlg.querySelector('input[name=mode]:checked').value === 'include';
|
||||||
dlg.close(); dlg.remove();
|
dlg.close(); dlg.remove();
|
||||||
buildPrintDoc(include);
|
buildPrintDoc(include);
|
||||||
setTimeout(() => window.print(), 50);
|
// 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')));
|
}, 'primary')));
|
||||||
document.body.append(dlg);
|
document.body.append(dlg);
|
||||||
dlg.showModal();
|
dlg.showModal();
|
||||||
|
|||||||
87
src/images.js
Normal file
87
src/images.js
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
// 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.
|
||||||
|
|
||||||
|
export const MAX_DIMENSION = 1600; // longest side after import
|
||||||
|
export const PNG_KEEP_LIMIT = 700 * 1024; // a PNG larger than this is re-encoded as JPEG
|
||||||
|
export const JPEG_QUALITY = 0.85;
|
||||||
|
export 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).
|
||||||
|
export 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.
|
||||||
|
export 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)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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.
|
||||||
|
export 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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"
|
||||||
|
export 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.
|
||||||
|
export 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
11
src/model.js
11
src/model.js
@@ -1,3 +1,5 @@
|
|||||||
|
import { isImageDataUrl, MAX_IMAGE_DATA_CHARS } from './images.js';
|
||||||
|
|
||||||
// Data model for the document (plaintext JSON before encryption).
|
// Data model for the document (plaintext JSON before encryption).
|
||||||
// Pure functions, no DOM; runs in browsers and Node. build.js strips `export`.
|
// Pure functions, no DOM; runs in browsers and Node. build.js strips `export`.
|
||||||
//
|
//
|
||||||
@@ -15,7 +17,9 @@
|
|||||||
// Every section has { id, title, kind } and may have { intro: string }.
|
// Every section has { id, title, kind } and may have { intro: string }.
|
||||||
//
|
//
|
||||||
// Record: { id, title, status: 'ok'|'tbd', updated: 'YYYY-MM-DD',
|
// Record: { id, title, status: 'ok'|'tbd', updated: 'YYYY-MM-DD',
|
||||||
// fields: [{ label, value, secret?: boolean }], notes?: string }
|
// 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 }
|
// Item: { id, text, status: 'open'|'done'|'tbd', detail?: string }
|
||||||
//
|
//
|
||||||
// HeaderField: { kind: 'text'|'lastUpdated', text, align?: 'left'|'right' }
|
// HeaderField: { kind: 'text'|'lastUpdated', text, align?: 'left'|'right' }
|
||||||
@@ -30,6 +34,7 @@ export const SCHEMA_VERSION = 1;
|
|||||||
export const SECTION_KINDS = ['text', 'records', 'steps', 'checklist'];
|
export const SECTION_KINDS = ['text', 'records', 'steps', 'checklist'];
|
||||||
export const RECORD_STATUSES = ['ok', 'tbd'];
|
export const RECORD_STATUSES = ['ok', 'tbd'];
|
||||||
export const ITEM_STATUSES = ['open', 'done', 'tbd'];
|
export const ITEM_STATUSES = ['open', 'done', 'tbd'];
|
||||||
|
export const FIELD_KINDS = ['text', 'image'];
|
||||||
export const HEADER_KINDS = ['text', 'lastUpdated'];
|
export const HEADER_KINDS = ['text', 'lastUpdated'];
|
||||||
export const HEADER_ALIGNS = ['left', 'right'];
|
export const HEADER_ALIGNS = ['left', 'right'];
|
||||||
|
|
||||||
@@ -129,6 +134,10 @@ export function validate(doc) {
|
|||||||
if (!isStr(f.label) || !f.label) errs.push(`${fw}: missing label`);
|
if (!isStr(f.label) || !f.label) errs.push(`${fw}: missing label`);
|
||||||
if (!isStr(f.value)) errs.push(`${fw}: value must be a string`);
|
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.secret !== undefined && typeof f.secret !== 'boolean') errs.push(`${fw}: secret must be a boolean`);
|
||||||
|
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`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -102,3 +102,10 @@ export function setAlign(fields, field, align) {
|
|||||||
else delete field.align;
|
else delete field.align;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- image fields ----
|
||||||
|
export function addImageField(record, label, value) {
|
||||||
|
const f = { kind: 'image', label: label || 'Image', value };
|
||||||
|
record.fields.push(f);
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,6 +6,10 @@ import { defaultHeaderFields } from './model.js';
|
|||||||
// What to print for a field. Secrets are either shown or withheld; an empty
|
// 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.
|
// secret is always "(not set)" so a blank is never mistaken for a hidden value.
|
||||||
export function displayValue(field, includeSecrets) {
|
export 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.secret) {
|
||||||
if (!field.value) return '(not set)';
|
if (!field.value) return '(not set)';
|
||||||
return includeSecrets ? field.value : '[withheld]';
|
return includeSecrets ? field.value : '[withheld]';
|
||||||
|
|||||||
@@ -40,6 +40,13 @@ textarea { width: 100%; display: block; } label { display: block; margin-top: .5
|
|||||||
.tools { display: inline-flex; gap: .2rem; } .addsec { display: grid; gap: .4rem; margin-top: 1rem; }
|
.tools { display: inline-flex; gap: .2rem; } .addsec { display: grid; gap: .4rem; margin-top: 1rem; }
|
||||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
|
||||||
|
/* ---------- 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; }
|
||||||
|
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) ---------- */
|
/* ---------- 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; }
|
.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-left { flex: 0 1 auto; text-align: left; min-width: 0; } /* the left field wraps first */
|
||||||
@@ -74,6 +81,7 @@ textarea { width: 100%; display: block; } label { display: block; margin-top: .5
|
|||||||
.prec table { border-collapse: collapse; width: 100%; font-size: 10.5pt; }
|
.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 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; }
|
.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; }
|
||||||
.psecret { font-family: ui-monospace, Consolas, monospace; }
|
.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; }
|
.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; }
|
.pnotes, .pbody, .pintro { white-space: pre-wrap; margin: 4pt 0 0; }
|
||||||
|
|||||||
88
test/images.test.js
Normal file
88
test/images.test.js
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { sniffType, fitSize, isImageDataUrl, dataUrlBytes, formatBytes, labelFromFilename, MAX_IMAGE_DATA_CHARS } from '../src/images.js';
|
||||||
|
import { validate } from '../src/model.js';
|
||||||
|
import { addImageField, addRecord, addSection } from '../src/ops.js';
|
||||||
|
import { displayValue, countSecrets } from '../src/print.js';
|
||||||
|
import { emptyDocument } from '../src/model.js';
|
||||||
|
|
||||||
|
const PNG = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0]);
|
||||||
|
const JPG = Uint8Array.from([0xff, 0xd8, 0xff, 0xe0, 0, 0]);
|
||||||
|
const TINY_PNG = 'data:image/png;base64,iVBORw0KGgo=';
|
||||||
|
const TINY_JPG = 'data:image/jpeg;base64,/9j/4AAQ';
|
||||||
|
|
||||||
|
test('sniffType goes by file signature, not name or claimed type', () => {
|
||||||
|
assert.equal(sniffType(PNG), 'image/png');
|
||||||
|
assert.equal(sniffType(JPG), 'image/jpeg');
|
||||||
|
assert.equal(sniffType(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>')), '');
|
||||||
|
assert.equal(sniffType(new TextEncoder().encode('GIF89a......')), '');
|
||||||
|
assert.equal(sniffType(new Uint8Array([0x89, 0x50])), '');
|
||||||
|
assert.equal(sniffType(new Uint8Array(0)), '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fitSize shrinks the long side to the limit, keeps ratio, never upscales', () => {
|
||||||
|
assert.deepEqual(fitSize(4000, 3000), { width: 1600, height: 1200 });
|
||||||
|
assert.deepEqual(fitSize(3000, 4000), { width: 1200, height: 1600 });
|
||||||
|
assert.deepEqual(fitSize(800, 600), { width: 800, height: 600 });
|
||||||
|
assert.deepEqual(fitSize(1600, 1600), { width: 1600, height: 1600 });
|
||||||
|
assert.deepEqual(fitSize(10000, 1), { width: 1600, height: 1 });
|
||||||
|
assert.deepEqual(fitSize(4000, 3000, 400), { width: 400, height: 300 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('isImageDataUrl accepts PNG/JPEG data URLs only', () => {
|
||||||
|
assert.ok(isImageDataUrl(TINY_PNG));
|
||||||
|
assert.ok(isImageDataUrl(TINY_JPG));
|
||||||
|
for (const bad of ['', 'data:image/gif;base64,R0lGOD', 'data:image/svg+xml;base64,PHN2Zz4=', 'data:text/html;base64,PGI+',
|
||||||
|
'data:image/png,rawtext', 'data:image/png;base64,', 'javascript:alert(1)', 'http://x/y.png', 'data:image/png;base64,AA"onerror="x', 5, null]) {
|
||||||
|
assert.equal(isImageDataUrl(bad), false, String(bad));
|
||||||
|
}
|
||||||
|
assert.equal(isImageDataUrl('data:image/png;base64,' + 'A'.repeat(MAX_IMAGE_DATA_CHARS)), false, 'oversize');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dataUrlBytes, formatBytes, labelFromFilename', () => {
|
||||||
|
assert.equal(dataUrlBytes('data:image/png;base64,QUJD'), 3);
|
||||||
|
assert.equal(dataUrlBytes('data:image/png;base64,QUI='), 2);
|
||||||
|
assert.equal(dataUrlBytes('data:image/png;base64,QQ=='), 1);
|
||||||
|
assert.equal(formatBytes(500), '500 B');
|
||||||
|
assert.equal(formatBytes(2048), '2 KB');
|
||||||
|
assert.equal(formatBytes(3 * 1048576), '3.0 MB');
|
||||||
|
assert.equal(labelFromFilename('drivers_license-front.PNG'), 'drivers license front');
|
||||||
|
assert.equal(labelFromFilename('C:\\scans\\passport.jpg'), 'passport');
|
||||||
|
assert.equal(labelFromFilename('.png'), 'Image');
|
||||||
|
assert.equal(labelFromFilename(''), 'Image');
|
||||||
|
});
|
||||||
|
|
||||||
|
function docWithField(field) {
|
||||||
|
const d = emptyDocument('Me');
|
||||||
|
const s = addSection(d, 'records', 'S');
|
||||||
|
const r = addRecord(d, s);
|
||||||
|
r.fields.push(field);
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('model validates image fields', () => {
|
||||||
|
assert.deepEqual(validate(docWithField({ kind: 'image', label: 'Front', value: TINY_PNG })), []);
|
||||||
|
assert.deepEqual(validate(docWithField({ kind: 'image', label: 'Front', value: '' })), []);
|
||||||
|
assert.deepEqual(validate(docWithField({ kind: 'text', label: 'a', value: 'x' })), []);
|
||||||
|
assert.match(validate(docWithField({ kind: 'image', label: 'F', value: 'data:image/gif;base64,R0lG' })).join('\n'), /PNG or JPEG/);
|
||||||
|
assert.match(validate(docWithField({ kind: 'image', label: 'F', value: 'not an image' })).join('\n'), /PNG or JPEG/);
|
||||||
|
assert.match(validate(docWithField({ kind: 'video', label: 'F', value: '' })).join('\n'), /unknown kind/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('addImageField appends a valid image field', () => {
|
||||||
|
const d = emptyDocument('Me');
|
||||||
|
const r = addRecord(d, addSection(d, 'records', 'S'));
|
||||||
|
const f = addImageField(r, '', TINY_JPG);
|
||||||
|
assert.equal(f.kind, 'image');
|
||||||
|
assert.equal(f.label, 'Image');
|
||||||
|
assert.deepEqual(validate(d), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('displayValue for images: masked when secret, never the data itself', () => {
|
||||||
|
const img = { kind: 'image', label: 'a', value: TINY_PNG };
|
||||||
|
assert.equal(displayValue(img, false), '[image]');
|
||||||
|
assert.equal(displayValue({ ...img, secret: true }, false), '[withheld]');
|
||||||
|
assert.equal(displayValue({ ...img, secret: true }, true), '[image]');
|
||||||
|
assert.equal(displayValue({ ...img, value: '' }, false), '(no image)');
|
||||||
|
assert.equal(countSecrets(docWithField({ ...img, secret: true })), 1);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user