Polish AccountTreeGrid: dual-value crossfade and smooth animations
CI / docker (push) Has been cancelled
CI / build-and-test (push) Has been cancelled

The tree grid now matches v5 Open Ledgers behavior:

Value crossfade (v5 pattern):
- Each parent cell holds BOTH the aggregate (Σ) and own value
- Two absolutely-positioned overlapping elements at right: 0
- isCollapsed toggles opacity between them via CSS transition
- One fades out, the other fades in — pure crossfade, no value swap
- Single state change drives everything, no JavaScript animation timing

Row animation:
- AnimatedCellContent wraps each cell's content in a height-animated div
- Fixed ROW_HEIGHT (28px) for consistent layout
- overflow: hidden clips vertically without horizontal shift
- Children slide in/out simultaneously with the parent value crossfade

Column stability:
- tableLayout: fixed with colgroup for locked column widths
- All cells use identical CELL_PX padding
- DualValueCell shared between root and animated rows
- position: absolute + right: 0 ensures alignment regardless of text length

Visual polish:
- Σ prefix: 14px bold, only on collapsed non-zero aggregates
- Expanded parents with zero own-value show empty (reduce clutter)
- Chevron rotates 90° smoothly on expand
- Folder/FolderOpen icons for parents, Description for leaves

Made-with: Cursor
This commit is contained in:
2026-04-09 10:51:01 +02:00
parent afde51abf2
commit 90b9bc2425
+313 -153
View File
@@ -1,4 +1,4 @@
import { useState, useMemo, useCallback } from 'react'
import { useState, useMemo, useCallback, useRef, useEffect } from 'react'
import {
Table, TableBody, TableCell, TableContainer, TableHead, TableRow,
Paper, IconButton, Box, Typography,
@@ -17,77 +17,59 @@ export interface AccountTreeGridProps {
nodes: TreeNode[]
columnHeaders: string[]
title?: string
currencyCode?: string
onDownloadCsv?: () => void
/** Show sign-reversed display for result accounts (Income/Cost) */
reverseSign?: boolean
}
interface FlatRow {
node: TreeNode
depth: number
isLeaf: boolean
hasOwnValue: boolean
interface BuiltNode {
id: number
name: string
parentId: number
ownValues: number[]
children: BuiltNode[]
aggregatedValues: number[]
isLeaf: boolean
depth: number
}
function buildTree(nodes: TreeNode[]): TreeNode[] {
const byId = new Map<number, TreeNode>()
const roots: TreeNode[] = []
function buildTree(flatNodes: TreeNode[], colCount: number): BuiltNode[] {
const byId = new Map<number, BuiltNode>()
for (const n of nodes) {
byId.set(n.id, { ...n, children: [] })
for (const n of flatNodes) {
byId.set(n.id, {
id: n.id, name: n.name, parentId: n.parentId,
ownValues: n.ownValues,
children: [], aggregatedValues: new Array(colCount).fill(0),
isLeaf: true, depth: 0,
})
}
for (const n of nodes) {
const roots: BuiltNode[] = []
for (const n of flatNodes) {
const node = byId.get(n.id)!
if (n.parentId === 0 || !byId.has(n.parentId)) {
roots.push(node)
} else {
byId.get(n.parentId)!.children!.push(node)
const parent = byId.get(n.parentId)!
parent.children.push(node)
parent.isLeaf = false
}
}
return roots
}
function computeAggregates(node: TreeNode, colCount: number): number[] {
const sums = new Array(colCount).fill(0)
for (let i = 0; i < colCount; i++) {
sums[i] = node.ownValues[i] || 0
}
if (node.children) {
function computeAgg(node: BuiltNode, depth: number): number[] {
node.depth = depth
const sums = new Array(colCount).fill(0)
for (let i = 0; i < colCount; i++) sums[i] = node.ownValues[i] || 0
for (const child of node.children) {
const childSums = computeAggregates(child, colCount)
for (let i = 0; i < colCount; i++) {
sums[i] += childSums[i]
}
}
}
return sums
}
function flattenVisible(
nodes: TreeNode[],
expanded: Set<number>,
colCount: number,
depth: number = 0
): FlatRow[] {
const rows: FlatRow[] = []
for (const node of nodes) {
const isLeaf = !node.children || node.children.length === 0
const hasOwnValue = (node.ownValues || []).some(v => v !== 0)
const aggregatedValues = isLeaf ? node.ownValues : computeAggregates(node, colCount)
rows.push({ node, depth, isLeaf, hasOwnValue, aggregatedValues })
if (!isLeaf && expanded.has(node.id)) {
rows.push(...flattenVisible(node.children!, expanded, colCount, depth + 1))
const childSums = computeAgg(child, depth + 1)
for (let i = 0; i < colCount; i++) sums[i] += childSums[i]
}
node.aggregatedValues = sums
return sums
}
return rows
for (const root of roots) computeAgg(root, 0)
return roots
}
function formatValue(cents: number, reverseSign: boolean): string {
@@ -97,33 +79,62 @@ function formatValue(cents: number, reverseSign: boolean): string {
minimumFractionDigits: 0,
maximumFractionDigits: 0,
})
return val < 0 ? `−${formatted}` : val === 0 ? '0' : formatted
if (val === 0) return '0'
return val < 0 ? `−${formatted}` : formatted
}
function AnimatedRow({ visible, children }: { visible: boolean; children: React.ReactNode }) {
const rowRef = useRef<HTMLTableRowElement>(null)
const [height, setHeight] = useState<number | undefined>(undefined)
const [mounted, setMounted] = useState(visible)
useEffect(() => {
if (visible) {
setMounted(true)
requestAnimationFrame(() => {
if (rowRef.current) setHeight(rowRef.current.scrollHeight)
})
} else {
setHeight(0)
const timer = setTimeout(() => setMounted(false), 300)
return () => clearTimeout(timer)
}
}, [visible])
useEffect(() => {
if (mounted && visible && rowRef.current) {
setHeight(rowRef.current.scrollHeight)
}
}, [mounted, visible])
if (!mounted) return null
return (
<tr
ref={rowRef}
style={{
maxHeight: height !== undefined ? height : 'none',
overflow: 'hidden',
opacity: visible ? 1 : 0,
transition: 'max-height 0.3s ease, opacity 0.25s ease',
}}
>
{children}
</tr>
)
}
export default function AccountTreeGrid({
nodes,
columnHeaders,
title,
onDownloadCsv,
reverseSign = false,
nodes, columnHeaders, title, onDownloadCsv, reverseSign = false,
}: AccountTreeGridProps) {
const [expanded, setExpanded] = useState<Set<number>>(() => {
const topLevel = new Set<number>()
for (const n of nodes) {
if (n.children && n.children.length > 0 && n.parentId === 0) {
topLevel.add(n.id)
}
}
return topLevel
})
const tree = useMemo(() => buildTree(nodes), [nodes])
const colCount = columnHeaders.length
const tree = useMemo(() => buildTree(nodes, colCount), [nodes, colCount])
const visibleRows = useMemo(
() => flattenVisible(tree, expanded, colCount),
[tree, expanded, colCount]
)
const [expanded, setExpanded] = useState<Set<number>>(() => {
const initial = new Set<number>()
for (const root of tree) if (!root.isLeaf) initial.add(root.id)
return initial
})
const toggleExpand = useCallback((id: number) => {
setExpanded(prev => {
@@ -134,26 +145,41 @@ export default function AccountTreeGrid({
})
}, [])
// Flatten the FULL tree, tracking which rows should be visible
const allRows = useMemo(() => {
const rows: { node: BuiltNode; visible: boolean }[] = []
function walk(nodes: BuiltNode[], parentVisible: boolean) {
for (const node of nodes) {
rows.push({ node, visible: parentVisible })
if (!node.isLeaf) {
walk(node.children, parentVisible && expanded.has(node.id))
}
}
}
walk(tree, true)
return rows
}, [tree, expanded])
const totals = useMemo(() => {
const sums = new Array(colCount).fill(0)
for (const node of tree) {
const agg = computeAggregates(node, colCount)
for (let i = 0; i < colCount; i++) sums[i] += agg[i]
for (const root of tree) {
for (let i = 0; i < colCount; i++) sums[i] += root.aggregatedValues[i]
}
return sums
}, [tree, colCount])
// Fixed column widths: account name gets flex, value columns are fixed
const valColWidth = Math.max(90, Math.min(120, 700 / colCount))
return (
<Box>
{title && (
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
<Typography variant="h6" sx={{ fontWeight: 600 }}>{title}</Typography>
{onDownloadCsv && (
<Typography
variant="body2"
<Typography variant="body2"
sx={{ cursor: 'pointer', color: 'primary.main', textDecoration: 'underline' }}
onClick={onDownloadCsv}
>
onClick={onDownloadCsv}>
Download CSV
</Typography>
)}
@@ -161,100 +187,63 @@ export default function AccountTreeGrid({
)}
<TableContainer component={Paper} elevation={2}>
<Table size="small" sx={{ '& td, & th': { py: 0.5, fontSize: 13 } }}>
<Table size="small" sx={{
tableLayout: 'fixed',
'& td, & th': { py: 0.4, fontSize: 13 },
}}>
<colgroup>
<col />
{columnHeaders.map((_, i) => (
<col key={i} style={{ width: valColWidth }} />
))}
</colgroup>
<TableHead>
<TableRow sx={{ bgcolor: 'primary.main' }}>
<TableCell sx={{ color: 'white', fontWeight: 600, minWidth: 280 }}>Account</TableCell>
<TableCell sx={{ color: 'white', fontWeight: 600 }}>Account</TableCell>
{columnHeaders.map((h, i) => (
<TableCell key={i} align="right" sx={{ color: 'white', fontWeight: 600, minWidth: 100 }}>
{h}
</TableCell>
<TableCell key={i} align="right" sx={{ color: 'white', fontWeight: 600 }}>{h}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{visibleRows.map(row => {
const isExpanded = expanded.has(row.node.id)
const isParent = !row.isLeaf
const showAggregate = isParent && !isExpanded
{allRows.map(({ node, visible }) => {
const isParent = !node.isLeaf
const isExpanded = expanded.has(node.id)
const isCollapsed = isParent && !isExpanded
if (node.depth === 0) {
return (
<TableRow key={node.id} hover sx={{
bgcolor: isParent ? 'rgba(25, 118, 210, 0.03)' : undefined,
}}>
{renderAccountCell(node, isParent, isExpanded, () => toggleExpand(node.id))}
{renderValueCells(node, isCollapsed, reverseSign)}
</TableRow>
)
}
return (
<TableRow
key={row.node.id}
hover
key={node.id}
sx={{
bgcolor: isParent && row.depth === 0 ? 'rgba(25, 118, 210, 0.04)' : undefined,
'&:hover': { bgcolor: 'action.hover' },
transition: 'background-color 0.2s',
'& td': {
p: 0,
borderBottom: visible ? undefined : 'none',
transition: 'border-color 0.3s ease',
},
}}
>
<TableCell sx={{ pl: 1 + row.depth * 2.5 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
{isParent ? (
<IconButton size="small" onClick={() => toggleExpand(row.node.id)} sx={{ p: 0.25 }}>
{isExpanded ? <ExpandMore fontSize="small" /> : <ChevronRight fontSize="small" />}
</IconButton>
) : (
<Box sx={{ width: 24 }} />
)}
{isParent ? (
isExpanded ? <FolderOpen fontSize="small" sx={{ color: 'warning.main', mr: 0.5 }} />
: <Folder fontSize="small" sx={{ color: 'warning.main', mr: 0.5 }} />
) : (
<Description fontSize="small" sx={{ color: 'action.disabled', mr: 0.5 }} />
)}
<Typography variant="body2" sx={{
fontWeight: isParent ? 600 : 400,
fontSize: 13,
}}>
{row.node.name}
</Typography>
</Box>
</TableCell>
{row.aggregatedValues.map((val, i) => (
<TableCell
key={i}
align="right"
sx={{
fontFamily: 'monospace',
fontSize: 13,
fontWeight: isParent ? 600 : 400,
color: val < 0 ? 'error.main' : val === 0 ? 'text.disabled' : 'text.primary',
opacity: showAggregate ? 1 : 1,
transition: 'opacity 0.3s ease',
}}
>
<Box sx={{
display: 'inline-flex',
alignItems: 'center',
gap: 0.25,
transition: 'opacity 0.3s ease-in-out',
}}>
{showAggregate && val !== 0 && (
<Typography component="span" sx={{ fontSize: 11, color: 'text.secondary', fontWeight: 400 }}>
Σ
</Typography>
)}
{isParent && isExpanded && row.hasOwnValue ? (
formatValue(row.node.ownValues[i] || 0, reverseSign)
) : (
formatValue(val, reverseSign)
)}
</Box>
</TableCell>
))}
{renderAnimatedAccountCell(node, isParent, isExpanded, () => toggleExpand(node.id), visible)}
{renderAnimatedValueCells(node, isCollapsed, reverseSign, visible)}
</TableRow>
)
})}
{/* Totals row */}
<TableRow sx={{ bgcolor: 'grey.100', borderTop: 2, borderColor: 'divider' }}>
<TableRow sx={{ bgcolor: 'grey.100', borderTop: '2px solid', borderColor: 'divider' }}>
<TableCell sx={{ fontWeight: 700, fontSize: 13 }}>Total</TableCell>
{totals.map((val, i) => (
<TableCell key={i} align="right" sx={{
fontWeight: 700, fontFamily: 'monospace', fontSize: 13,
color: val < 0 ? 'error.main' : 'text.primary',
fontWeight: 700, fontFamily: '"Roboto Mono", monospace', fontSize: 13,
color: (reverseSign ? -val : val) < 0 ? 'error.main' : 'text.primary',
}}>
{formatValue(val, reverseSign)}
</TableCell>
@@ -266,3 +255,174 @@ export default function AccountTreeGrid({
</Box>
)
}
function DualValueCell({ aggVal, ownVal, isCollapsed, reverseSign, showOwnEmpty }: {
aggVal: number; ownVal: number; isCollapsed: boolean; reverseSign: boolean; showOwnEmpty: boolean
}) {
return (
<Box sx={{ position: 'relative', fontFamily: '"Roboto Mono", monospace', fontSize: 13, fontWeight: 600, textAlign: 'right', height: 20 }}>
<Box sx={{
position: 'absolute', top: 0, right: 0,
opacity: isCollapsed ? 1 : 0,
transition: 'opacity 0.25s ease-in-out',
color: (reverseSign ? -aggVal : aggVal) < 0 ? 'error.main' : aggVal === 0 ? 'text.disabled' : 'text.primary',
whiteSpace: 'nowrap',
}}>
{aggVal !== 0 && (
<Typography component="span" sx={{ fontSize: 14, fontWeight: 700, color: 'text.secondary', mr: 0.5 }}>Σ</Typography>
)}
{formatValue(aggVal, reverseSign)}
</Box>
<Box sx={{
position: 'absolute', top: 0, right: 0,
opacity: isCollapsed ? 0 : 1,
transition: 'opacity 0.25s ease-in-out',
color: (reverseSign ? -ownVal : ownVal) < 0 ? 'error.main' : ownVal === 0 ? 'text.disabled' : 'text.primary',
whiteSpace: 'nowrap',
}}>
{showOwnEmpty ? '' : formatValue(ownVal, reverseSign)}
</Box>
</Box>
)
}
const ROW_HEIGHT = 28
const CELL_PX = '3px 8px'
function AnimatedCellContent({ visible, children, align }: {
visible: boolean; children: React.ReactNode; align?: 'right' | 'left'
}) {
return (
<div style={{
height: visible ? ROW_HEIGHT : 0,
overflow: 'hidden',
transition: 'height 0.4s ease, opacity 0.35s ease',
opacity: visible ? 1 : 0,
textAlign: align,
}}>
<div style={{ padding: CELL_PX, whiteSpace: 'nowrap', height: ROW_HEIGHT, display: 'flex', alignItems: 'center', justifyContent: align === 'right' ? 'flex-end' : 'flex-start' }}>
{children}
</div>
</div>
)
}
function renderAnimatedAccountCell(
node: BuiltNode, isParent: boolean, isExpanded: boolean, onToggle: () => void, visible: boolean
) {
return (
<TableCell sx={{ p: '0 !important' }}>
<AnimatedCellContent visible={visible} align="left">
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, pl: node.depth * 2.5 }}>
{isParent ? (
<IconButton size="small" onClick={onToggle} sx={{ p: 0.25 }}>
<Box sx={{ transition: 'transform 0.2s ease', transform: isExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }}>
<ChevronRight fontSize="small" />
</Box>
</IconButton>
) : (
<Box sx={{ width: 24 }} />
)}
{isParent
? (isExpanded
? <FolderOpen fontSize="small" sx={{ color: 'warning.main', mr: 0.5 }} />
: <Folder fontSize="small" sx={{ color: 'warning.main', mr: 0.5 }} />)
: <Description fontSize="small" sx={{ color: 'action.disabled', mr: 0.5 }} />}
<Typography variant="body2" noWrap sx={{ fontWeight: isParent ? 600 : 400, fontSize: 13 }}>
{node.name}
</Typography>
</Box>
</AnimatedCellContent>
</TableCell>
)
}
function renderAnimatedValueCells(
node: BuiltNode, isCollapsed: boolean,
reverseSign: boolean, visible: boolean
) {
return node.aggregatedValues.map((aggVal, i) => {
const ownVal = node.ownValues[i] || 0
const isParent = !node.isLeaf
const showOwnEmpty = isParent && ownVal === 0
return (
<TableCell key={i} sx={{ p: '0 !important' }}>
<AnimatedCellContent visible={visible} align="right">
{isParent ? (
<DualValueCell
aggVal={aggVal} ownVal={ownVal} isCollapsed={isCollapsed}
reverseSign={reverseSign} showOwnEmpty={showOwnEmpty}
/>
) : (
<Box sx={{
fontFamily: '"Roboto Mono", monospace', fontSize: 13, textAlign: 'right',
color: (reverseSign ? -ownVal : ownVal) < 0 ? 'error.main' : ownVal === 0 ? 'text.disabled' : 'text.primary',
}}>
{formatValue(ownVal, reverseSign)}
</Box>
)}
</AnimatedCellContent>
</TableCell>
)
})
}
function renderAccountCell(
node: BuiltNode, isParent: boolean, isExpanded: boolean, onToggle: () => void
) {
return (
<TableCell sx={{ pl: 1 + node.depth * 2.5 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
{isParent ? (
<IconButton size="small" onClick={onToggle} sx={{ p: 0.25 }}>
<Box sx={{ transition: 'transform 0.2s ease', transform: isExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }}>
<ChevronRight fontSize="small" />
</Box>
</IconButton>
) : (
<Box sx={{ width: 24 }} />
)}
{isParent
? (isExpanded
? <FolderOpen fontSize="small" sx={{ color: 'warning.main', mr: 0.5 }} />
: <Folder fontSize="small" sx={{ color: 'warning.main', mr: 0.5 }} />)
: <Description fontSize="small" sx={{ color: 'action.disabled', mr: 0.5 }} />}
<Typography variant="body2" noWrap sx={{
fontWeight: isParent ? 600 : 400, fontSize: 13,
}}>
{node.name}
</Typography>
</Box>
</TableCell>
)
}
function renderValueCells(
node: BuiltNode, isCollapsed: boolean, reverseSign: boolean
) {
return node.aggregatedValues.map((aggVal, i) => {
const ownVal = node.ownValues[i] || 0
const isParent = !node.isLeaf
const showOwnEmpty = isParent && ownVal === 0
return (
<TableCell key={i} sx={{ p: `${CELL_PX} !important`, whiteSpace: 'nowrap', height: ROW_HEIGHT }}>
{isParent ? (
<DualValueCell
aggVal={aggVal} ownVal={ownVal} isCollapsed={isCollapsed}
reverseSign={reverseSign} showOwnEmpty={showOwnEmpty}
/>
) : (
<Box sx={{
fontFamily: '"Roboto Mono", monospace', fontSize: 13,
textAlign: 'right',
color: (reverseSign ? -ownVal : ownVal) < 0 ? 'error.main' : ownVal === 0 ? 'text.disabled' : 'text.primary',
}}>
{formatValue(ownVal, reverseSign)}
</Box>
)}
</TableCell>
)
})
}