Debian Codegraph @

frontend/src/tree-table/helpers.ts

raw
1 import { getContext, setContext } from "svelte";
2 import type { Readable, Writable } from "svelte/store";
3 import { derived } from "svelte/store";
4
5 import type { AccountTreeNode } from "../charts/hierarchy";
6 import { is_empty } from "../lib/objects";
7 import { accounts, fava_options } from "../stores";
8 import { is_closed_account } from "../stores/accounts";
9
10 const key = Symbol("tree-table");
11
12 interface TreeTableContext {
13 /** The accounts for which the decsendants are currently hidden. */
14 readonly toggled: Writable<ReadonlySet<string>>;
15 /** The accounts that should not be shown. */
16 readonly not_shown: Readable<ReadonlySet<string>>;
17 }
18
19 export const setTreeTableContext = (ctx: TreeTableContext): TreeTableContext =>
20 setContext(key, ctx);
21
22 export const getTreeTableContext = (): TreeTableContext => getContext(key);
23
24 /** Recursively build set of accounts that should not be shown. */
25 export const get_not_shown = derived(
26 [fava_options, accounts, is_closed_account],
27 ([$fava_options, $accounts, $is_closed_account]) =>
28 (node: AccountTreeNode, end: Date | null): Set<string> => {
29 const {
30 show_accounts_with_zero_balance,
31 show_accounts_with_zero_transactions,
32 show_closed_accounts,
33 } = $fava_options;
34 const not_shown = new Set<string>();
35 const should_show_recursive = (n: AccountTreeNode): boolean => {
36 if (
37 // We need to evaluate this for all descendants recursively
38 // the .map().some() ensures it does not short-circuit
39 n.children.map(should_show_recursive).some((b) => b) ||
40 !is_empty(n.balance_children)
41 ) {
42 return true;
43 }
44 if (
45 !$accounts.includes(n.account) ||
46 (!show_closed_accounts && $is_closed_account(n.account, end)) ||
47 (!show_accounts_with_zero_balance && is_empty(n.balance)) ||
48 (!show_accounts_with_zero_transactions && !n.has_txns)
49 ) {
50 not_shown.add(n.account);
51 return false;
52 }
53 return true;
54 };
55 should_show_recursive(node);
56 return not_shown;
57 },
58 );
59
60 /** Determine the accounts that should initially be collapsed. */
61 export function get_collapsed(
62 root: AccountTreeNode,
63 $collapse_account: (s: string) => boolean,
64 ): Set<string> {
65 const s = new Set<string>();
66 const get_collapsed_recursive = ({ children, account }: AccountTreeNode) => {
67 if (children.length && $collapse_account(account)) {
68 s.add(account);
69 }
70 children.forEach(get_collapsed_recursive);
71 };
72 get_collapsed_recursive(root);
73 return s;
74 }