From f05065215d8ac803a5f5ed59cffc7e20c36b5692 Mon Sep 17 00:00:00 2001 From: Maksim Kostromin Date: Thu, 3 Dec 2026 19:44:55 -0500 Subject: [PATCH] refactor(viewer): scope rules on a tree --- src/viewer/app/derive.ts | 44 +++---- src/viewer/app/scope-tree.test.ts | 147 +++++++++++++++++++++++ src/viewer/app/scope-tree.ts | 192 ++++++++++++++++++++++++++++++ 3 files changed, 361 insertions(+), 22 deletions(-) create mode 100644 src/viewer/app/scope-tree.test.ts create mode 100644 src/viewer/app/scope-tree.ts diff --git a/src/viewer/app/derive.ts b/src/viewer/app/derive.ts index 6d243fe..9283330 100644 --- a/src/viewer/app/derive.ts +++ b/src/viewer/app/derive.ts @@ -5,6 +5,7 @@ import type { Account, Dataset, Position } from '../../shared/model'; import { incomeReceived, isIncome, type TxnStore } from '../../shared/transactions'; import { incomeTax, type IncomeTax } from './income-tax'; import type { Scope } from './prefs'; +import { FIDELITY, buildTree, fidelityLeaf, framedNodes, groupAccounts, groupId, scopeOf as leavesShown, toggleLeaf, toggleNode, type ScopeNode } from './scope-tree'; import { addDays, addMonths } from '../../shared/dates'; import { perYear } from '../../shared/typed-columns'; @@ -12,18 +13,25 @@ export { addMonths }; export interface Group { name: string; accounts: Account[]; balance: number } -/** groups in the site's order (the order the accounts came in) */ +/** groups in the site's order (the order the accounts came in), as the scope tree groups them (app/scope-tree.ts) */ export function groupsOf(ds: Dataset): Group[] { - const out: Group[] = []; - ds.accounts.forEach((a) => { - let g = out.find((x) => x.name === a.group); - if (!g) { g = { name: a.group, accounts: [], balance: 0 }; out.push(g); } - g.accounts.push(a); - g.balance += a.balance ?? 0; - }); - return out; + return groupAccounts(ds.accounts).map((g) => ({ ...g, balance: g.accounts.reduce((s, a) => s + (a.balance ?? 0), 0) })); } +// The scope rules run on the scope tree (app/scope-tree.ts); until the 401k joins it the tree holds the Fidelity accounts +// alone, and the scope is kept in today's words ('all', 'group:', 'account:', 'set:'). One tree per dataset +const trees = new WeakMap(); +export function fidelityTree(ds: Dataset): ScopeNode { + let tree = trees.get(ds); + if (!tree) { tree = buildTree({ fidelity: ds.accounts }); trees.set(ds, tree); } + return tree; +} +const leafSet = (numbers: Iterable): Set => new Set(Array.from(numbers).map(fidelityLeaf)); +const numbersOf = (tree: ScopeNode, leaves: ReadonlySet): string[] => leavesShown(tree, leaves).map((id) => id.slice(fidelityLeaf('').length)); +// a node of the tree as the key of its chip in today's strip: all, group:, account: +const GROUP_KEY = groupId(FIDELITY, ''); +const chipKey = (id: string): string => (id.startsWith(GROUP_KEY) ? `group:${id.slice(GROUP_KEY.length)}` : id.startsWith(fidelityLeaf('')) ? `account:${id.slice(fidelityLeaf('').length)}` : id); + /** * The owner's own order (owner 2026-11-24): groups move as a whole with their accounts, accounts move inside their * group; accounts in `order` come by its index, the rest keep the site's order after them @@ -120,12 +128,7 @@ export function scopeOf(ds: Dataset, numbers: string[]): Scope { */ export function framedChips(ds: Dataset, shown: ReadonlySet): Set { const out = new Set(); - if (!ds.accounts.length || !ds.accounts.some((a) => shown.has(a.number))) return out; - if (ds.accounts.every((a) => shown.has(a.number))) return out.add('all'); - groupsOf(ds).forEach((g) => { - if (g.accounts.every((a) => shown.has(a.number))) out.add(`group:${g.name}`); - else g.accounts.filter((a) => shown.has(a.number)).forEach((a) => out.add(`account:${a.number}`)); - }); + framedNodes(fidelityTree(ds), leafSet(Array.from(shown))).forEach((id) => out.add(chipKey(id))); return out; } @@ -135,17 +138,14 @@ export function framedChips(ds: Dataset, shown: ReadonlySet): Set, group: string): Scope { - const mine = groupsOf(ds).find((g) => g.name === group)?.accounts.map((a) => a.number) ?? []; - if (!mine.length) return scopeOf(ds, Array.from(shown)); - if (ds.accounts.every((a) => shown.has(a.number))) return scopeOf(ds, mine); - const others = Array.from(shown).filter((n) => mine.indexOf(n) < 0); - return scopeOf(ds, mine.every((n) => shown.has(n)) ? others : others.concat(mine)); + const tree = fidelityTree(ds); + return scopeOf(ds, numbersOf(tree, toggleNode(tree, leafSet(Array.from(shown)), groupId(FIDELITY, group)))); } /** the account checkbox (owner 2026-11-23: "only Elena and Elena ROTH IRA"): adds or removes one account */ export function toggleAccount(ds: Dataset, scope: Scope, number: string): Scope { - const now = accountsIn(ds, scope).map((a) => a.number); - return scopeOf(ds, now.includes(number) ? now.filter((n) => n !== number) : now.concat(number)); + const tree = fidelityTree(ds); + return scopeOf(ds, numbersOf(tree, toggleLeaf(tree, leafSet(accountsIn(ds, scope).map((a) => a.number)), fidelityLeaf(number)))); } /** a scope that no longer exists (account closed, other data) falls back to all accounts */ diff --git a/src/viewer/app/scope-tree.test.ts b/src/viewer/app/scope-tree.test.ts new file mode 100644 index 0000000..7a00678 --- /dev/null +++ b/src/viewer/app/scope-tree.test.ts @@ -0,0 +1,147 @@ +/// +/// +/// +// The scope tree: the plan's traces (owner 2026-12-03) and the rules of the strip. Names and numbers are made up +import { expect, test } from 'bun:test'; +import { pageFacts, visiblePages } from './pages'; +import { ADP, FIDELITY, LEAF_401K, LEAF_PAY, ROOT, buildTree, checkState, chipKids, chipLabel, fidelityLeaf, framedNodes, groupAccounts, groupId, leavesOf, migrateFolded, migrateScope, nodeOf, onlyNode, pathTo, scopeOf, scopeTitle, shownLeaves, toggleLeaf, toggleNode, validScope, type ScopeNode } from './scope-tree'; + +const acct = (number: string, name: string, group: string, type?: string) => ({ number, name, group, type }); +// Fidelity = Investment {A1, A2}, Retirement {R1}; ADP = {K} (the plan's traces) +const FID = [acct('A1', 'Joint', 'Investment', 'Brokerage'), acct('A2', 'Kids', 'Investment', 'Brokerage'), acct('R1', 'Max ROTH IRA', 'Retirement', 'ROTH IRA')]; +const tree = buildTree({ fidelity: FID, k401: true }); +const [A1, A2, R1] = ['A1', 'A2', 'R1'].map(fidelityLeaf) as [string, string, string]; +const K = LEAF_401K; +const INV = groupId(FIDELITY, 'Investment'); +const RET = groupId(FIDELITY, 'Retirement'); +const set = (...ids: string[]) => new Set(ids); +const sorted = (s: ReadonlySet) => Array.from(s).sort(); +const ALL = [A1, A2, R1, K]; + +test('the tree: All -> source -> group -> account; a source with nothing read is left out', () => { + expect(tree.kids!.map((k) => k.id)).toEqual([FIDELITY, ADP]); + expect(nodeOf(tree, FIDELITY)!.kids!.map((g) => [g.id, g.kids!.map((a) => a.id)])).toEqual([[INV, [A1, A2]], [RET, [R1]]]); + expect(leavesOf(tree)).toEqual(ALL); + expect(nodeOf(tree, R1)!.shelter).toBe('free'); + expect(nodeOf(tree, A1)!.shelter).toBeNull(); + expect(buildTree({ fidelity: [] , k401: true }).kids!.map((k) => k.id)).toEqual([ADP]); + expect(buildTree({ fidelity: FID }).kids!.map((k) => k.id)).toEqual([FIDELITY]); + expect(leavesOf(buildTree({ fidelity: [] }))).toEqual([]); + expect(pathTo(tree, A2)!.map((n) => n.id)).toEqual([ROOT, FIDELITY, INV, A2]); + expect(pathTo(tree, 'nope')).toBeNull(); + expect(groupAccounts([acct('1', 'a', 'G'), acct('2', 'b', 'H'), acct('3', 'c', 'G')]).map((g) => [g.name, g.accounts.map((a) => a.number)])).toEqual([['G', ['1', '3']], ['H', ['2']]]); +}); + +test('leaf ids of the 401k and the pay, in tree-only use', () => { + const both = buildTree({ fidelity: FID, k401: true, pay: true }); + expect(nodeOf(both, ADP)!.kids!.map((k) => k.id)).toEqual(['adp:401k', 'adp:pay']); + expect(LEAF_PAY).toBe('adp:pay'); + // the pages of only the pay: Taxes and Salary + expect(visiblePages(pageFacts(shownLeaves(both, set(LEAF_PAY)).map((id) => ({ id, shelter: nodeOf(both, id)!.shelter }))))).toEqual(['taxes', 'salary']); + // the ADP source: the 401k pages and the salary and taxes pages + const adp = toggleNode(both, set(), ADP); + expect(sorted(adp)).toEqual(['adp:401k', 'adp:pay']); + expect(visiblePages(pageFacts(shownLeaves(both, adp).map((id) => ({ id, shelter: nodeOf(both, id)!.shelter }))))).toEqual(['summary', 'activity', 'taxes', 'salary']); +}); + +test('the five traces of the plan', () => { + // All + tick Investment -> {A1, A2} + expect(sorted(toggleNode(tree, set(...ALL), INV))).toEqual([A1, A2].sort()); + // Fidelity only + tick Investment -> {A1, A2} + expect(sorted(toggleNode(tree, set(A1, A2, R1), INV))).toEqual([A1, A2].sort()); + // {A1, A2, K} + tick Retirement -> {A1, A2, R1, K} + expect(sorted(toggleNode(tree, set(A1, A2, K), RET))).toEqual(ALL.slice().sort()); + // {A1, A2} + tick Investment -> none (= everything) + expect(sorted(toggleNode(tree, set(A1, A2), INV))).toEqual([]); + expect(shownLeaves(tree, set())).toEqual(ALL); + // All + tick ADP -> {K}, then tick Fidelity -> All + const adp = toggleNode(tree, set(...ALL), ADP); + expect(sorted(adp)).toEqual([K]); + const back = toggleNode(tree, adp, FIDELITY); + expect(sorted(back)).toEqual(ALL.slice().sort()); + expect(sorted(framedNodes(tree, back))).toEqual([ROOT]); +}); + +test('the All checkbox: everything ticked -> nothing, else everything; an unknown node changes nothing', () => { + expect(sorted(toggleNode(tree, set(...ALL), ROOT))).toEqual([]); + expect(sorted(toggleNode(tree, set(A1), ROOT))).toEqual(ALL.slice().sort()); + expect(sorted(toggleNode(tree, set(), ROOT))).toEqual(ALL.slice().sort()); + expect(sorted(toggleNode(tree, set(A1, 'gone'), 'nope'))).toEqual([A1]); +}); + +test('an account checkbox adds or removes only it; a click on a chip shows only its leaves', () => { + expect(sorted(toggleLeaf(tree, set(A1), K))).toEqual([A1, K].sort()); + expect(sorted(toggleLeaf(tree, set(A1, K), A1))).toEqual([K]); + expect(sorted(toggleLeaf(tree, set(A1), 'fidelity:gone'))).toEqual([A1]); + expect(sorted(onlyNode(tree, INV))).toEqual([A1, A2].sort()); + expect(sorted(onlyNode(tree, K))).toEqual([K]); + expect(sorted(onlyNode(tree, 'nope'))).toEqual([]); +}); + +test('the frame: the highest node chosen whole whose parent is not', () => { + expect(sorted(framedNodes(tree, set(...ALL)))).toEqual([ROOT]); + expect(sorted(framedNodes(tree, set(A1, A2, R1)))).toEqual([FIDELITY]); + expect(sorted(framedNodes(tree, set(A1, A2, K)))).toEqual([ADP, INV].sort()); + expect(sorted(framedNodes(tree, set(A1, R1)))).toEqual([A1, RET].sort()); + expect(sorted(framedNodes(tree, set()))).toEqual([]); + expect(sorted(framedNodes(tree, set('gone')))).toEqual([]); +}); + +test('checkbox states: ticked, partly, clear', () => { + expect(checkState(tree, set(...ALL))).toEqual({ checked: true, mixed: false }); + expect(checkState(tree, set(A1))).toEqual({ checked: false, mixed: true }); + expect(checkState(nodeOf(tree, INV)!, set(R1))).toEqual({ checked: false, mixed: false }); + expect(checkState(nodeOf(tree, K)!, set(K))).toEqual({ checked: true, mixed: false }); + expect(checkState(buildTree({ fidelity: [] }), set())).toEqual({ checked: false, mixed: false }); +}); + +test('the title: All, one account, a whole source or group, up to three names, else a count', () => { + const count = (n: number) => `${n} accounts`; + expect(scopeTitle(tree, set(), count)).toBe('All accounts'); + expect(scopeTitle(tree, set(...ALL), count)).toBe('All accounts'); + expect(scopeTitle(tree, set(R1), count)).toBe('Max ROTH IRA'); + expect(scopeTitle(tree, set(A1, A2), count)).toBe('Investment'); + expect(scopeTitle(tree, set(A1, A2, R1), count)).toBe('Fidelity'); + expect(scopeTitle(tree, set(A1, R1), count)).toBe('Joint + Max ROTH IRA'); + expect(scopeTitle(tree, set(A1, A2, K), count)).toBe('Joint + Kids + ADP mykplan 401k'); + const five = buildTree({ fidelity: FID.concat(acct('A3', 'Three', 'Investment'), acct('A4', 'Four', 'Investment')), k401: true }); + expect(scopeTitle(five, set(fidelityLeaf('A3'), fidelityLeaf('A4'), A1, R1), count)).toBe('4 accounts'); +}); + +test('a level with one child is one chip: the 401k alone in ADP is drawn as "ADP 401k"; with the pay, ADP -> 401k, Work', () => { + const kids = (t: ScopeNode, id: string) => chipKids(t, nodeOf(t, id)!).map((k) => k.id); + // All with Fidelity and ADP: the sources; ADP with the 401k alone is drawn as the 401k + expect(kids(tree, ROOT)).toEqual([FIDELITY, K]); + expect(chipLabel(tree, K)).toBe('ADP 401k'); + const both = buildTree({ fidelity: FID, k401: true, pay: true }); + expect(kids(both, ROOT)).toEqual([FIDELITY, ADP]); + expect(kids(both, ADP)).toEqual([K, LEAF_PAY]); + expect([chipLabel(both, K), chipLabel(both, LEAF_PAY), chipLabel(both, ADP)]).toEqual(['401k', 'Work', 'ADP']); + // Fidelity alone (today's strip): All draws the groups itself, as today + const fid = buildTree({ fidelity: FID }); + expect(kids(fid, ROOT)).toEqual([INV, RET]); + expect(kids(fid, INV)).toEqual([A1, A2]); + expect([chipLabel(fid, ROOT), chipLabel(fid, INV), chipLabel(fid, A1)]).toEqual(['All accounts', 'Investment', 'Joint']); + expect(chipLabel(fid, 'nope')).toBe('nope'); +}); + +test('a kept scope: only the leaves still there; the scope of before the tree as leaves', () => { + expect(sorted(validScope(tree, set(A1, 'fidelity:closed')))).toEqual([A1]); + expect(sorted(validScope(tree, set('fidelity:closed')))).toEqual([]); + expect(scopeOf(tree, set(K, A2, A1))).toEqual([A1, A2, K]); + expect(sorted(migrateScope(tree, 'all'))).toEqual(ALL.slice().sort()); + expect(sorted(migrateScope(tree, 'none'))).toEqual([]); + expect(sorted(migrateScope(tree, 'group:Investment'))).toEqual([A1, A2].sort()); + expect(sorted(migrateScope(tree, 'group:Gone'))).toEqual([]); + expect(sorted(migrateScope(tree, 'account:R1'))).toEqual([R1]); + expect(sorted(migrateScope(tree, 'set:A2,R1,closed'))).toEqual([A2, R1].sort()); + expect(migrateFolded(['*', 'Retirement'])).toEqual([ROOT, RET]); +}); + +test('nothing here changes the tree or the set it is given', () => { + const before = JSON.stringify(tree); + const shown = set(A1, A2); + toggleNode(tree, shown, INV); toggleNode(tree, shown, ROOT); toggleLeaf(tree, shown, K); framedNodes(tree, shown); onlyNode(tree, RET); migrateScope(tree, 'all'); + expect(JSON.stringify(tree)).toBe(before); + expect(sorted(shown)).toEqual([A1, A2].sort()); +}); diff --git a/src/viewer/app/scope-tree.ts b/src/viewer/app/scope-tree.ts new file mode 100644 index 0000000..922e9cb --- /dev/null +++ b/src/viewer/app/scope-tree.ts @@ -0,0 +1,192 @@ +/// +// The scope as ONE tree (owner 2026-12-03: "I want to somehow effectively see All group ... then this will have two other +// sub groups: Fidelity and ADP"; "convenient to do such separation and aggregation by groups or custom subgroups or +// accounts selection"): All -> source (Fidelity, ADP) -> group -> account. No group in a group; a group lives in one +// source, a mix of sources is made by ticking (owner: "yes if these accounts were selected simultaneously"). +// The scope is the set of ticked leaves; nothing ticked shows the same as everything ticked (owner 2026-11-24). Every +// function here is pure and never changes the tree or the set it is given +import { shelterOf, type Shelter } from '../../shared/tax'; +import { FIDELITY_LEAF, LEAF_401K, LEAF_PAY } from './pages'; + +export { FIDELITY_LEAF, LEAF_401K, LEAF_PAY }; +export type NodeKind = 'all' | 'source' | 'group' | 'account'; +export interface ScopeNode { + id: string; // 'all', 'fidelity', 'adp', 'group:fidelity/', or a leaf: 'fidelity:', 'adp:401k', 'adp:pay' + kind: NodeKind; + name: string; // the full name: the tooltip, the cards, a screen reader + short?: string; // the chip's label where the full name repeats its parent ("401k" under ADP) + shelter?: Shelter | null; // a leaf: how its earnings are taxed (shared/tax.ts), null = taxable + kids?: ScopeNode[]; +} + +export const ROOT = 'all'; +export const FIDELITY = 'fidelity'; +export const ADP = 'adp'; +export const fidelityLeaf = (number: string): string => `${FIDELITY_LEAF}${number}`; +export const groupId = (source: string, name: string): string => `group:${source}/${name}`; + +/** the accounts by their group, the groups in the order their first account comes, the accounts in their own order */ +export function groupAccounts(accounts: readonly T[]): Array<{ name: string; accounts: T[] }> { + const out: Array<{ name: string; accounts: T[] }> = []; + accounts.forEach((a) => { + let g = out.find((x) => x.name === a.group); + if (!g) { g = { name: a.group, accounts: [] }; out.push(g); } + g.accounts.push(a); + }); + return out; +} + +export interface TreeWords { all: string; allShort?: string; fidelity: string; adp: string; k401: string; k401Short: string; pay: string; payShort: string } +export const TREE_WORDS: TreeWords = { all: 'All accounts', fidelity: 'Fidelity', adp: 'ADP', k401: 'ADP mykplan 401k', k401Short: '401k', pay: 'ADP Workforce', payShort: 'Work' }; + +/** + * The tree of what has data: the Fidelity accounts (in the owner's order) by their groups, the ADP 401k and the ADP pay + * when read. A source with nothing read is left out; All is always there + */ +export function buildTree(have: { fidelity: ReadonlyArray<{ number: string; name: string; group: string; type?: string }>; k401?: boolean; pay?: boolean }, words: TreeWords = TREE_WORDS): ScopeNode { + const kids: ScopeNode[] = []; + if (have.fidelity.length) { + kids.push({ id: FIDELITY, kind: 'source', name: words.fidelity, kids: groupAccounts(have.fidelity).map((g) => ({ + id: groupId(FIDELITY, g.name), kind: 'group' as const, name: g.name, + kids: g.accounts.map((a) => ({ id: fidelityLeaf(a.number), kind: 'account' as const, name: a.name, shelter: shelterOf(a) })), + })) }); + } + const adp: ScopeNode[] = []; + if (have.k401) adp.push({ id: LEAF_401K, kind: 'account', name: words.k401, short: words.k401Short, shelter: 'deferred' }); + if (have.pay) adp.push({ id: LEAF_PAY, kind: 'account', name: words.pay, short: words.payShort, shelter: null }); + if (adp.length) kids.push({ id: ADP, kind: 'source', name: words.adp, kids: adp }); + return { id: ROOT, kind: 'all', name: words.all, ...(words.allShort ? { short: words.allShort } : {}), kids }; +} + +/** the leaf ids under a node, in the tree's order (a leaf: itself) */ +export const leavesOf = (node: ScopeNode): string[] => (node.kids ? node.kids.reduce((all, k) => all.concat(leavesOf(k)), []) : [node.id]); + +/** the nodes from the root down to `id`, both ends included; null when it is not in the tree */ +export function pathTo(root: ScopeNode, id: string): ScopeNode[] | null { + if (root.id === id) return [root]; + for (const k of root.kids ?? []) { + const p = pathTo(k, id); + if (p) return [root].concat(p); + } + return null; +} +export const nodeOf = (root: ScopeNode, id: string): ScopeNode | null => { const p = pathTo(root, id); return p ? p[p.length - 1]! : null; }; +export const parentOf = (root: ScopeNode, id: string): ScopeNode | null => { const p = pathTo(root, id); return p && p.length > 1 ? p[p.length - 2]! : null; }; + +/** the ticked leaves that are in the tree, in the tree's order: the scope as it is kept */ +export const scopeOf = (root: ScopeNode, shown: ReadonlySet): string[] => leavesOf(root).filter((x) => shown.has(x)); + +/** the leaves whose numbers are shown: the ticked ones, or every one when none is ticked (owner 2026-11-24) */ +export function shownLeaves(root: ScopeNode, shown: ReadonlySet): string[] { + const some = scopeOf(root, shown); + return some.length ? some : leavesOf(root); +} + +/** a click on an account (or a chip that stands for one leaf): only it */ +export const onlyNode = (root: ScopeNode, id: string): Set => { const n = nodeOf(root, id); return new Set(n ? leavesOf(n) : []); }; + +/** + * The checkbox of All, a source or a group (owner 2026-12-03, toggleGroup generalised): when the shown set is exactly a + * larger node above it chosen whole -> only this node (All + tick Investment -> Investment); else this node chosen whole + * -> it is taken away; else it is added whole. All itself: everything ticked -> nothing, else everything + */ +export function toggleNode(root: ScopeNode, shown: ReadonlySet, id: string): Set { + const now = scopeOf(root, shown); + const path = pathTo(root, id); + if (!path) return new Set(now); + const mine = leavesOf(path[path.length - 1]!); + if (id === root.id) return new Set(now.length === mine.length ? [] : mine); + const isShown = (x: string) => shown.has(x); + const wholeAbove = path.slice(0, -1).some((a) => { const l = leavesOf(a); return l.length > mine.length && l.length === now.length && l.every(isShown); }); + if (wholeAbove) return new Set(mine); + if (mine.every(isShown)) return new Set(now.filter((x) => mine.indexOf(x) < 0)); + return new Set(now.concat(mine.filter((x) => !isShown(x)))); +} + +/** the checkbox of an account (owner 2026-11-23: "only Elena and Elena ROTH IRA"): adds or removes that one */ +export function toggleLeaf(root: ScopeNode, shown: ReadonlySet, id: string): Set { + const now = scopeOf(root, shown); + if (now.indexOf(id) >= 0) return new Set(now.filter((x) => x !== id)); + return leavesOf(root).indexOf(id) >= 0 ? new Set(now.concat(id)) : new Set(now); +} + +/** + * The chips framed as chosen (owner 2026-12-03: "we want to select most responsible group"): the highest node whose leaves + * are all ticked and whose parent's are not. Nothing ticked: no frame + */ +export function framedNodes(root: ScopeNode, shown: ReadonlySet): Set { + const out = new Set(); + if (!scopeOf(root, shown).length) return out; + const walk = (n: ScopeNode) => { + const l = leavesOf(n); + if (!l.length) return; + if (l.every((x) => shown.has(x))) out.add(n.id); + else (n.kids ?? []).forEach(walk); + }; + walk(root); + return out; +} + +/** the checkbox of a node: ticked when all its leaves are, partly when some are */ +export function checkState(node: ScopeNode, shown: ReadonlySet): { checked: boolean; mixed: boolean } { + const l = leavesOf(node); + const n = l.filter((x) => shown.has(x)).length; + return { checked: l.length > 0 && n === l.length, mixed: n > 0 && n < l.length }; +} + +/** + * The name of what is shown, the Balance card's title (owner 2026-11-24): nothing or everything = All's name; one account + * = its name; one whole source or group = its name; up to three accounts = their names joined by " + "; more = a count + */ +export function scopeTitle(root: ScopeNode, shown: ReadonlySet, count: (n: number) => string): string { + const leaves = shownLeaves(root, shown); + const all = leavesOf(root); + if (leaves.length === all.length) return root.name; + const name = (id: string) => nodeOf(root, id)?.name ?? id; + if (leaves.length === 1) return name(leaves[0]!); + const framed = Array.from(framedNodes(root, new Set(leaves))); + if (framed.length === 1) return name(framed[0]!); + return leaves.length <= 3 ? leaves.map(name).join(' + ') : count(leaves.length); +} + +/** + * A level with one child is one chip (owner 2026-12-03: "ADP 401k"; with Workforce pay it becomes ADP -> 401k, Work): + * All with one source draws that source's children itself, a source with one account is drawn as that account. The + * children drawn under a chip + */ +export function chipKids(root: ScopeNode, node: ScopeNode): ScopeNode[] { + const kids = node.kids ?? []; + if (node.id === root.id && kids.length === 1 && kids[0]!.kind === 'source') return chipKids(root, kids[0]!); + return kids.map((k) => (k.kind === 'source' && k.kids?.length === 1 && !k.kids[0]!.kids ? k.kids[0]! : k)); +} + +/** + * The label of a chip: the short label under its parent (the full name repeats it: "401k" under ADP), and the source's + * name with it when the account is alone in its source and stands for it ("ADP 401k"); else the full name + */ +export function chipLabel(root: ScopeNode, id: string): string { + const node = nodeOf(root, id); + if (!node) return id; + if (!node.short) return node.name; + const parent = parentOf(root, id); + const lone = !node.kids && parent?.kind === 'source' && parent.kids?.length === 1; + return lone ? `${parent!.name} ${node.short}` : node.short; +} + +/** a kept scope whose leaves are gone (an account closed, another browser): only the leaves still there; none = everything */ +export const validScope = (root: ScopeNode, shown: ReadonlySet): Set => new Set(scopeOf(root, shown)); + +/** + * The scope kept before the tree (`Prefs.scope`: 'all', 'none', 'group:', 'account:', 'set:,') as + * ticked leaves: 'all' ticks every leaf, 'none' none, a group its accounts, an account itself + */ +export function migrateScope(root: ScopeNode, scope: string): Set { + if (scope === 'all') return new Set(leavesOf(root)); + if (scope.startsWith('group:')) { const g = nodeOf(root, groupId(FIDELITY, scope.slice(6))); return new Set(g ? leavesOf(g) : []); } + if (scope.startsWith('account:')) return new Set(scopeOf(root, new Set([fidelityLeaf(scope.slice(8))]))); + if (scope.startsWith('set:')) return new Set(scopeOf(root, new Set(scope.slice(4).split(',').map(fidelityLeaf)))); + return new Set(); +} + +/** the folded chips kept before the tree (`Prefs.collapsed`: '*' for All, Fidelity's group names) as node ids */ +export const migrateFolded = (collapsed: readonly string[]): string[] => collapsed.map((c) => (c === '*' ? ROOT : c.startsWith('group:') ? c : groupId(FIDELITY, c)));