diff --git a/OVERVIEW.md b/OVERVIEW.md index 4124e90..3d0baea 100644 --- a/OVERVIEW.md +++ b/OVERVIEW.md @@ -54,7 +54,7 @@ Git-ignored on purpose: `*.pdf`, `data/` (plaintext working copies with real sec **Document model** (`src/model.js`, `schemaVersion 1`): `meta {owner, title, lastUpdated}`; optional `header {fields}` for the running print header; `sections`. Section kinds: - `text` (a `body`, plus optional `sequences`) -- `records` (records with labeled `fields`; a field is text or an image) +- `records` (records with labeled `fields`; a field is text or an image). It can optionally have sub-tabs: `subsections: [{id, title}]`, a `generalTitle` for the catch-all first tab (default "General"), and a `subsection` id on each record or sequence. No `subsection`, or one that matches no tab, means General. - `steps` and `checklist` (ordered `items`) A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text with a layout of right / under / none) is an entry in the same ordered list as a section's records or items, or in a text section's `sequences` array. It is not a record or an item: no step number and no tick box. Ids are unique across the whole document. `secret` flags exist on fields and frames. Validation is `validate()` / `assertValid()`; the save path refuses an invalid document. @@ -62,6 +62,7 @@ A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text wit **UI** (`src/app.js`, a single IIFE): state lives in one `state` object (including `collapsed`, the folded record ids). Edits mutate `state.doc` in place and then call `markDirty()` or `changed(record)` (which also stamps `updated` and `meta.lastUpdated`). `render()` rebuilds the page. `changed` clears `state.status`, so set the status afterwards. - **Editing and Cancel:** edit mode is global. **Cancel** reverts the section (or the print header) on screen to a deep-copy baseline taken at open and at each save, then leaves edit mode. - **Collapsing records:** in view mode each record card has a Collapse/Expand button, and records sections have "Collapse all" / "Expand all". Folded ids live in `state.collapsed` (a `Set`, view-only, never saved, cleared on reload). A collapsed card shows only its title and gets ↑/↓ buttons that reorder it via `move()` and `changed()`, so moving stamps `updated` and marks the document dirty. +- **Sub-tabs:** `ops.js` holds the pure logic (`tabsOf`, `entriesInTab`, `moveToTab`, `moveWithin`, `removeSubsection`, `printGroups`). The records stay in one array, and the tab bar filters them. The shown tab is in `state.tabs` (not saved). Up/down moves a record past its nearest neighbour in the same tab. Deleting a tab sends its records to General. Print writes one sub-heading per non-empty tab. - **Images:** drag and drop, clipboard paste and file picker all feed `importFiles()`. Files are sniffed by their first bytes, downscaled to at most 1600 px and re-encoded, which strips metadata, and stored as data URLs with a limit of about 3 MB each. **Save.** Uses the File System Access API (`showSaveFilePicker`, handle reused) where available, otherwise a Blob download. `assemble()` rebuilds the full HTML from the page's own CSS and JS plus a fresh encrypted payload. "Backup copy" downloads `final-wishes-YYYYMMDD.html`. @@ -100,7 +101,7 @@ No database. The document is a JSON object, encrypted and embedded in the HTML f - **Bundle scope:** all modules share one scope after the build. Don't add a top-level name that already exists elsewhere, and don't use `import`/`export` forms other than line-start `import ` and `export `, because the stripper is regex-based. - **`h()` children:** it flattens with `flat(Infinity)`, but `replaceChildren` needs an explicit `.flat()`. Use `textContent`, never `innerHTML`. - **Dirty and status:** `markDirty()` clears the status text, so set `state.status` after calling `changed()`. -- **Older builds:** files saved with images or visual sequences can't be opened by builds that predate them. The upgrade path only goes forward. +- **Older builds:** files saved with images, visual sequences or sub-tabs can't be opened by builds that predate them. The upgrade path only goes forward. - **Blob size:** images are embedded in the encrypted payload and make the file bigger and saves slower. - **Skipped test:** one test in `test/model.test.js` is skipped unless the gitignored `data/seed.json` exists. - **Browser coverage:** features were verified in headless Chromium only; Firefox and Safari drop and paste are untested. diff --git a/docs/MAINTENANCE.md b/docs/MAINTENANCE.md index a53487f..eaadb84 100644 --- a/docs/MAINTENANCE.md +++ b/docs/MAINTENANCE.md @@ -54,6 +54,29 @@ 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* one until you save and replace it. +## Sub-tabs +A *records* section (Banking, say) can be split into **sub-tabs** such as +Standard, Online and Credit Union. Other kinds of section don't have them. + +- **Create:** choose Edit, type a name under **Sub-tabs** and press + **+ Add sub-tab**. The first one makes a tab bar appear, with a catch-all + **General** tab first. Records you already had are in General. A section + with no sub-tabs looks exactly as before. +- **Add into a tab:** **+ Add record** and **+ Add visual sequence** add to the + tab you are on. +- **Fix a misplaced record:** each record (and visual sequence) has a + **Sub-tab** drop-down in edit mode. Pick the right tab and it moves there. +- **Order:** the up/down arrows reorder within the tab you are on. The + name box under Sub-tabs renames the selected tab (General too), and its + arrows move the tab left or right. +- **Delete a tab:** the ✕ asks first. Its records move to General, so + nothing is lost. Deleting the last tab turns the section back into a plain list. +- **Collapse all / Expand all** work on the tab you are on. +- **Print:** each tab prints as a sub-heading inside the section (tabs + with nothing in them are left out). +- **Older copies:** a file saved with sub-tabs can't be opened by an older + build of the app. Upgrade the app first (see *Upgrading*). + ## 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 diff --git a/src/app.js b/src/app.js index d45de7f..15b60ac 100644 --- a/src/app.js +++ b/src/app.js @@ -11,6 +11,7 @@ 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) revealed: new WeakSet(), // secret field objects currently shown blob: null, // encrypted payload taken from a file the user chose to open @@ -230,16 +231,32 @@ return [h('dt', {}, f.label), h('dd', {}, value)]; } - function viewRecord(r, arr, i) { + 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.collapsed.has(r.id); const toggle = () => { state.collapsed[closed ? 'delete' : 'add'](r.id); render(); }; - const shift = (dir) => { move(arr, i, dir); changed(r); render(); }; + const shift = (dir) => { moveWithin(arr, i, dir, same); changed(r); render(); }; return h('article', { class: 'card' + (closed ? ' collapsed' : '') }, h('div', { class: 'rechead' }, h('h3', {}, r.title, ' ', statusBadge(r.status)), h('span', { class: 'tools' }, - closed && i > 0 ? btn('↑', () => shift(-1), 'icon', { 'aria-label': 'Move ' + r.title + ' up' }) : null, - closed && i < arr.length - 1 ? btn('↓', () => shift(1), 'icon', { 'aria-label': 'Move ' + r.title + ' down' }) : null, + 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, @@ -247,8 +264,8 @@ h('p', { class: 'muted small' }, 'Updated ' + r.updated)]); } - function foldBar(s) { - const recs = s.records.filter((r) => !isSequence(r)); + 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' }, @@ -285,11 +302,19 @@ it.detail ? h('p', { class: 'notes' }, it.detail) : null); } + function viewRecords(s) { + const entries = entriesInTab(s, currentTab(s)); + return [tabBar(s), + hasTabs(s) && !entries.length ? h('p', { class: 'muted' }, 'Nothing in this sub-tab yet. Choose Edit to add or move records here.') : 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' ? [foldBar(s), s.records.map((r, i) => (isSequence(r) ? viewSequence(r) : viewRecord(r, s.records, i)))] : 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, ]; @@ -309,12 +334,13 @@ } // Up / down / delete controls for element i of arr. // `message` (string or function) replaces the default delete confirmation. - function rowTools(arr, i, what, record, quiet = false, message = null) { + // `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(() => move(arr, i, -1)), 'icon', { 'aria-label': 'Move ' + what + ' up', disabled: i === 0 }), - btn('↓', act(() => move(arr, i, 1)), 'icon', { 'aria-label': 'Move ' + what + ' down', disabled: i === arr.length - 1 }), + btn('↑', act(() => 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 })); } @@ -356,13 +382,56 @@ 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')), + 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'), @@ -384,19 +453,20 @@ f.layout === 'none' ? null : h('label', {}, 'Text', input(f, 'text', { multiline: true, label: 'Text for step ' + (k + 1) }, q))); } - function editSequence(list, q, i) { + 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)), + 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)); } - const addSeqBtn = (s) => btn('+ Add visual sequence', () => { addSequence(state.doc, s); markDirty(); render(); }, 'primary'); + 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' }, @@ -412,8 +482,9 @@ 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' ? [s.records.map((r, i) => (isSequence(r) ? editSequence(s.records, r, i) : editRecord(s, r, i))), - h('div', { class: 'row' }, btn('+ Add record', () => { addRecord(state.doc, s); markDirty(); render(); }, 'primary'), 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, @@ -518,7 +589,8 @@ 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' ? s.records.map((r) => (isSequence(r) ? printSequence(r, includeSecrets) : printRecord(r, 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(); diff --git a/src/model.js b/src/model.js index bbe12c0..a903366 100644 --- a/src/model.js +++ b/src/model.js @@ -15,6 +15,12 @@ import { isImageDataUrl, MAX_IMAGE_DATA_CHARS } from './images.js'; // '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: `. +// 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 } @@ -38,6 +44,7 @@ import { isImageDataUrl, MAX_IMAGE_DATA_CHARS } from './images.js'; // in the UI and optionally in print output. export const SCHEMA_VERSION = 1; +export const GENERAL_TITLE = 'General'; export const SECTION_KINDS = ['text', 'records', 'steps', 'checklist']; export const RECORD_STATUSES = ['ok', 'tbd']; export const ITEM_STATUSES = ['open', 'done', 'tbd']; @@ -117,6 +124,7 @@ export function validate(doc) { 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`); @@ -126,7 +134,23 @@ export function validate(doc) { } } else if (s.kind === 'records') { if (!Array.isArray(s.records)) return errs.push(`${where}: records must be an array`); - s.records.forEach((r, j) => (isSequence(r) ? checkSequence : checkRecord)(r, `${where}.records[${j}]`)); + 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}]`)); diff --git a/src/ops.js b/src/ops.js index 97580a0..da8356a 100644 --- a/src/ops.js +++ b/src/ops.js @@ -1,4 +1,4 @@ -import { defaultHeaderFields, isSequence } from './model.js'; +import { defaultHeaderFields, isSequence, GENERAL_TITLE } from './model.js'; // Pure editing operations on the document model. No DOM; tested in Node. // build.js strips `export` when bundling. @@ -9,6 +9,7 @@ export function allIds(doc) { const ids = new Set(); for (const s of doc.sections) { ids.add(s.id); + (s.subsections || []).forEach((t) => ids.add(t.id)); (s.records || []).forEach((r) => ids.add(r.id)); (s.items || []).forEach((i) => ids.add(i.id)); (s.sequences || []).forEach((q) => ids.add(q.id)); @@ -51,8 +52,9 @@ export function addSection(doc, kind, title) { return s; } -export function addRecord(doc, section) { +export function addRecord(doc, section, tabId = '') { const r = { id: newId(doc, 'rec'), title: 'New record', status: 'tbd', updated: today(), fields: [] }; + if (tabId) r.subsection = tabId; section.records.push(r); touch(doc, r); return r; @@ -185,8 +187,9 @@ export function sequenceList(section) { return section.items; } -export function addSequence(doc, section) { +export function addSequence(doc, section, tabId = '') { const q = { id: newId(doc, 'seq'), kind: 'sequence', title: 'New visual sequence', updated: today(), frames: [] }; + if (tabId && section.kind === 'records') q.subsection = tabId; sequenceList(section).push(q); touch(doc, q); return q; @@ -223,3 +226,99 @@ export function deleteSectionMessage(section) { if (!parts.length) return 'Delete the empty section ' + name + '?'; return 'Delete the section ' + name + ' and everything in it (' + parts.join(', ') + ')? This cannot be undone with Cancel.'; } + +// ---- sub-tabs of a records section ---- +// A tab id of '' is the General catch-all; the rest are section.subsections ids. +export const hasTabs = (section) => !!(section.subsections && section.subsections.length); + +// [{id, title}] in display order, General first; [] when the section has no sub-tabs. +export function tabsOf(section) { + if (!hasTabs(section)) return []; + return [{ id: '', title: section.generalTitle || GENERAL_TITLE }, ...section.subsections.map((t) => ({ id: t.id, title: t.title }))]; +} + +// Which tab an entry (record or sequence) is in. A missing or dangling id means General. +export function entryTab(section, e) { + return e.subsection && (section.subsections || []).some((t) => t.id === e.subsection) ? e.subsection : ''; +} + +// The tab to show: `wanted` if it still exists, else General. +export function validTab(section, wanted) { + return wanted && (section.subsections || []).some((t) => t.id === wanted) ? wanted : ''; +} + +// Entries of the section's list that are in a tab, as [{e, i}] (i = index in the list). +export function entriesInTab(section, tabId) { + const out = []; + section.records.forEach((e, i) => { if (entryTab(section, e) === tabId) out.push({ e, i }); }); + return out; +} + +// Index of the nearest element before (dir -1) / after (+1) arr[i] satisfying `same`, or -1. +export function siblingIndex(arr, i, dir, same = () => true) { + for (let j = i + dir; j >= 0 && j < arr.length; j += dir) if (same(arr[j])) return j; + return -1; +} + +// Move arr[i] past its nearest neighbour for which `same` holds. Returns true if it moved. +export function moveWithin(arr, i, dir, same) { + const j = siblingIndex(arr, i, dir, same); + if (j < 0) return false; + [arr[i], arr[j]] = [arr[j], arr[i]]; + return true; +} + +export function addSubsection(doc, section, title) { + const t = { id: newId(doc, 'sub'), title: String(title).trim() }; + (section.subsections || (section.subsections = [])).push(t); + touch(doc); + return t; +} + +export function moveSubsection(section, id, dir) { + const i = (section.subsections || []).findIndex((t) => t.id === id); + return i < 0 ? false : move(section.subsections, i, dir); +} + +// Rename a tab; '' is the General tab. Refuses an empty name. +export function renameTab(section, id, title) { + const name = String(title).trim(); + if (!name) return false; + if (id === '') section.generalTitle = name; + else { const t = (section.subsections || []).find((x) => x.id === id); if (!t) return false; t.title = name; } + return true; +} + +// Put a record or sequence in a tab ('' = General). +export function moveToTab(section, e, tabId) { + if (tabId && !(section.subsections || []).some((t) => t.id === tabId)) return false; + if (tabId) e.subsection = tabId; else delete e.subsection; + return true; +} + +// Delete a tab. Its records and sequences fall back to General (nothing is lost). +// With no sub-tabs left, the section goes back to a plain list. +export function removeSubsection(section, id) { + const i = (section.subsections || []).findIndex((t) => t.id === id); + if (i < 0) return false; + for (const e of section.records) if (e.subsection === id) delete e.subsection; + section.subsections.splice(i, 1); + if (!section.subsections.length) { delete section.subsections; delete section.generalTitle; } + return true; +} + +export function deleteSubsectionMessage(section, id) { + const t = section.subsections.find((x) => x.id === id); + const n = entriesInTab(section, id).length; + const where = '"' + (section.generalTitle || GENERAL_TITLE) + '"'; + return 'Delete the sub-tab "' + t.title + '"?' + (n ? ' Its ' + n + (n === 1 ? ' entry moves' : ' entries move') + ' to ' + where + '.' : ''); +} + +// What to print for a records section: [{title, entries}]. Without sub-tabs one group with +// a null title; with them, one group per tab that has entries. +export function printGroups(section) { + if (!hasTabs(section)) return [{ title: null, entries: section.records }]; + return tabsOf(section) + .map((t) => ({ title: t.title, entries: entriesInTab(section, t.id).map((x) => x.e) })) + .filter((g) => g.entries.length); +} diff --git a/src/style.css b/src/style.css index 23ce8d9..e460e62 100644 --- a/src/style.css +++ b/src/style.css @@ -41,6 +41,11 @@ 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; } :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); } @@ -85,6 +90,7 @@ dialog.lightbox { max-width: 92vw; max-height: 92vh; overflow: auto; } .bigimg { .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; } diff --git a/src/version.js b/src/version.js index c30eb2b..bfd75ce 100644 --- a/src/version.js +++ b/src/version.js @@ -2,7 +2,7 @@ // YYMMDD is the date, X the iteration that day (A first, B second, ...). // Bump with `npm run bump` (see bump-version.js). build.js strips `export`. -export const APP_VERSION = '261121A'; +export const APP_VERSION = '261121B'; const VERSION_RE = /^(\d{6})([A-Z])$/; export const isVersion = (v) => typeof v === 'string' && VERSION_RE.test(v); diff --git a/test/model.test.js b/test/model.test.js index eae2b14..053454d 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -127,3 +127,36 @@ test('countSecrets counts secret frames in all places and ignores sequences as r rs.records[1].frames[0].secret = true; st.items[1].frames[1].secret = true; tx.sequences[0].frames[0].secret = true; assert.equal(countSecrets(d), 3); }); + +test('sub-tabs: valid shapes pass, bad ones are reported', () => { + const withTabs = () => { + const d = good(); + const s = d.sections[1]; + s.subsections = [{ id: 'sub1', title: 'Online' }]; + s.generalTitle = 'Everyday'; + s.records[0].subsection = 'sub1'; + return d; + }; + assert.deepEqual(validate(withTabs()), []); + + let d = withTabs(); d.sections[1].records[0].subsection = 'nope'; + assert.match(validate(d).join('\n'), /not one of this section's sub-tabs/); + + d = withTabs(); d.sections[1].subsections[0].title = ' '; + assert.match(validate(d).join('\n'), /missing title/); + + d = withTabs(); d.sections[1].subsections.push({ id: 'sub1', title: 'Dup' }); + assert.match(validate(d).join('\n'), /duplicate id "sub1"/); + + d = withTabs(); d.sections[1].subsections = {}; + assert.match(validate(d).join('\n'), /subsections must be an array/); + + d = withTabs(); d.sections[1].generalTitle = ''; + assert.match(validate(d).join('\n'), /generalTitle/); + + d = good(); d.sections[2].subsections = []; + assert.match(validate(d).join('\n'), /only records sections can have sub-tabs/); + + d = good(); d.sections[1].records[0].subsection = 'x'; + assert.match(validate(d).join('\n'), /not one of this section's sub-tabs/); +}); diff --git a/test/ops.test.js b/test/ops.test.js index 7ddbdfe..c6931fd 100644 --- a/test/ops.test.js +++ b/test/ops.test.js @@ -191,3 +191,132 @@ test('deleteSectionMessage: items, singular forms, and text sections', () => { addSequence(d, t); assert.match(deleteSectionMessage(t), /\(1 visual sequence, its text\)/); }); + +// ---- sub-tabs ---- +import { hasTabs, tabsOf, entryTab, validTab, entriesInTab, siblingIndex, moveWithin, addSubsection, moveSubsection, renameTab, moveToTab, removeSubsection, deleteSubsectionMessage, printGroups } from '../src/ops.js'; + +function bank() { + const doc = emptyDocument('Me'); + const s = addSection(doc, 'records', 'Banking'); + const a = addRecord(doc, s); a.title = 'A'; + const b = addRecord(doc, s); b.title = 'B'; + const c = addRecord(doc, s); c.title = 'C'; + return { doc, s, a, b, c }; +} + +test('a section has no tabs until one is added; then General comes first', () => { + const { doc, s } = bank(); + assert.equal(hasTabs(s), false); + assert.deepEqual(tabsOf(s), []); + const t = addSubsection(doc, s, ' Online '); + assert.equal(t.title, 'Online'); + assert.deepEqual(tabsOf(s), [{ id: '', title: 'General' }, { id: t.id, title: 'Online' }]); + assert.deepEqual(validate(doc), []); +}); + +test('records without a sub-tab, or with a dangling one, are in General', () => { + const { doc, s, a, b } = bank(); + const t = addSubsection(doc, s, 'Online'); + moveToTab(s, b, t.id); + assert.equal(entryTab(s, a), ''); + assert.equal(entryTab(s, b), t.id); + b.subsection = 'gone'; + assert.equal(entryTab(s, b), ''); + assert.equal(validTab(s, 'gone'), ''); + assert.equal(validTab(s, t.id), t.id); +}); + +test('moveToTab changes the tab, refuses an unknown one, and General clears it', () => { + const { doc, s, a } = bank(); + const t = addSubsection(doc, s, 'Online'); + assert.equal(moveToTab(s, a, t.id), true); + assert.equal(a.subsection, t.id); + assert.equal(moveToTab(s, a, 'nope'), false); + assert.equal(a.subsection, t.id); + assert.equal(moveToTab(s, a, ''), true); + assert.equal('subsection' in a, false); + assert.deepEqual(validate(doc), []); +}); + +test('up/down moves within a tab, stepping over records in other tabs', () => { + const { doc, s, a, b, c } = bank(); + const t = addSubsection(doc, s, 'Online'); + moveToTab(s, b, t.id); // list: A(General) B(Online) C(General) + const same = (e) => entryTab(s, e) === ''; + assert.equal(siblingIndex(s.records, 0, 1, same), 2); + assert.equal(moveWithin(s.records, 0, 1, same), true); + assert.deepEqual(s.records.map((r) => r.title), ['C', 'B', 'A']); + assert.equal(moveWithin(s.records, 2, 1, same), false); + assert.deepEqual(entriesInTab(s, '').map((x) => x.e.title), ['C', 'A']); + assert.deepEqual(entriesInTab(s, t.id).map((x) => x.i), [1]); +}); + +test('new records and sequences go into the given tab', () => { + const { doc, s } = bank(); + const t = addSubsection(doc, s, 'Online'); + const r = addRecord(doc, s, t.id); + const q = addSequence(doc, s, t.id); + assert.equal(r.subsection, t.id); + assert.equal(q.subsection, t.id); + assert.equal('subsection' in addRecord(doc, s), false); + assert.deepEqual(validate(doc), []); +}); + +test('renameTab renames General or a tab, and refuses an empty name', () => { + const { doc, s } = bank(); + const t = addSubsection(doc, s, 'Online'); + assert.equal(renameTab(s, '', 'Everyday'), true); + assert.equal(renameTab(s, t.id, 'Web'), true); + assert.deepEqual(tabsOf(s).map((x) => x.title), ['Everyday', 'Web']); + assert.equal(renameTab(s, t.id, ' '), false); + assert.equal(renameTab(s, 'nope', 'x'), false); + assert.deepEqual(validate(doc), []); +}); + +test('moveSubsection reorders tabs', () => { + const { doc, s } = bank(); + const x = addSubsection(doc, s, 'X'); + const y = addSubsection(doc, s, 'Y'); + assert.equal(moveSubsection(s, y.id, -1), true); + assert.deepEqual(s.subsections.map((t) => t.title), ['Y', 'X']); + assert.equal(moveSubsection(s, y.id, -1), false); + assert.equal(moveSubsection(s, 'nope', 1), false); + void x; +}); + +test('removing a tab sends its records to General; removing the last tab restores a plain section', () => { + const { doc, s, a, b } = bank(); + const t = addSubsection(doc, s, 'Online'); + renameTab(s, '', 'Everyday'); + moveToTab(s, a, t.id); + assert.match(deleteSubsectionMessage(s, t.id), /Delete the sub-tab "Online"\? Its 1 entry moves to "Everyday"\./); + assert.equal(removeSubsection(s, t.id), true); + assert.equal('subsection' in a, false); + assert.equal(s.records.length, 3); + assert.equal(hasTabs(s), false); + assert.equal('subsections' in s, false); + assert.equal('generalTitle' in s, false); + assert.equal(removeSubsection(s, t.id), false); + void b; + assert.deepEqual(validate(doc), []); +}); + +test('printGroups: one untitled group without tabs, else one per non-empty tab', () => { + const { doc, s, a, b } = bank(); + assert.equal(printGroups(s).length, 1); + assert.equal(printGroups(s)[0].title, null); + const t = addSubsection(doc, s, 'Online'); + addSubsection(doc, s, 'Empty'); + moveToTab(s, b, t.id); + const g = printGroups(s); + assert.deepEqual(g.map((x) => x.title), ['General', 'Online']); + assert.deepEqual(g[1].entries, [b]); + void a; +}); + +test('sub-tab ids are unique across the document', () => { + const { doc, s } = bank(); + const t = addSubsection(doc, s, 'Online'); + const ids = new Set([t.id, ...s.records.map((r) => r.id), s.id]); + assert.equal(ids.size, 5); +});