Open-source personal finance manager. Self-hosted, privacy-first.
fix(dashboard): keep the drill-down panel open while editing a transaction (#1001)
Tássio Noronha7bfce402e358
diff --git a/frontend/src/components/transaction-drill-down.test.tsx b/frontend/src/components/transaction-drill-down.test.tsxnew file mode 100644index 00000000..80ae84f2--- /dev/null+++ b/frontend/src/components/transaction-drill-down.test.tsx@@ -0,0 +1,88 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { fireEvent, screen, waitFor } from '@testing-library/react'++import { TransactionDrillDown } from '@/components/transaction-drill-down'+import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'+import { admin, dashboard, transactions } from '@/lib/api'+import { renderWithProviders } from '@/test/utils'++vi.mock('@/contexts/auth-context', () => ({+ useAuth: () => ({ user: { preferences: { currency_display: 'USD' } } }),+}))++vi.mock('@/lib/api', () => ({+ transactions: { list: vi.fn() },+ dashboard: { projectedTransactions: vi.fn() },+ admin: { accountingMode: vi.fn() },+}))++const filter = { title: 'Uncategorized', uncategorized: true }++function renderPanel({ dialogOpen }: { dialogOpen: boolean }) {+ const onClose = vi.fn()+ const result = renderWithProviders(+ <>+ <TransactionDrillDown filter={filter} onClose={onClose} />+ <Dialog open={dialogOpen}>+ <DialogContent>+ <DialogTitle>Edit transaction</DialogTitle>+ <button type="button">Category</button>+ </DialogContent>+ </Dialog>+ </>,+ )+ return { ...result, onClose }+}++// The outside-click listener is attached after a short delay so the click+// that opened the panel does not close it.+async function waitForOutsideClickListener() {+ await new Promise(resolve => setTimeout(resolve, 150))+}++describe('TransactionDrillDown', () => {+ beforeEach(() => {+ vi.mocked(transactions.list).mockResolvedValue({ items: [], total: 0 } as never)+ vi.mocked(dashboard.projectedTransactions).mockResolvedValue([])+ vi.mocked(admin.accountingMode).mockResolvedValue({ mode: 'cash' } as never)+ })++ afterEach(() => {+ vi.resetAllMocks()+ })++ it('closes on a click outside the panel', async () => {+ const { onClose } = renderPanel({ dialogOpen: false })+ await waitForOutsideClickListener()++ fireEvent.mouseDown(document.body)++ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('stays open while the user clicks inside a dialog opened from it', async () => {+ const { onClose } = renderPanel({ dialogOpen: true })+ await waitForOutsideClickListener()++ fireEvent.mouseDown(await screen.findByRole('button', { name: 'Category' }))++ expect(onClose).not.toHaveBeenCalled()+ })++ it('leaves Escape to the open dialog', async () => {+ const { onClose } = renderPanel({ dialogOpen: true })+ await screen.findByRole('dialog')++ fireEvent.keyDown(document, { key: 'Escape' })++ expect(onClose).not.toHaveBeenCalled()+ })++ it('closes on Escape when no dialog is open', async () => {+ const { onClose } = renderPanel({ dialogOpen: false })++ fireEvent.keyDown(document, { key: 'Escape' })++ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))+ })+})diff --git a/frontend/src/components/transaction-drill-down.tsx b/frontend/src/components/transaction-drill-down.tsxindex 1d4bab65..6ad80f78 100644--- a/frontend/src/components/transaction-drill-down.tsx+++ b/frontend/src/components/transaction-drill-down.tsx@@ -7,6 +7,7 @@ import { AlertTriangle, Clock, Info, Paperclip, X } from 'lucide-react'import { CategoryIcon } from '@/components/category-icon'import { ProjectedTransactionBadge } from '@/components/projected-transaction-badge'import { sumDrillDownTotals } from '@/lib/drill-down-totals'+import { hasOpenDialog, isInsideOverlayLayer } from '@/lib/overlay-layers'import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'import { useAuth } from '@/contexts/auth-context'import { usePrivacyMode } from '@/hooks/use-privacy-mode'@@ -145,23 +146,27 @@ export function TransactionDrillDown({return items}, [data, projectedTxs, filter])- // Close on Escape+ // Close on Escape, unless the key belongs to a dialog opened from the+ // panel (Radix marks the Escape it handled as defaultPrevented).useEffect(() => {if (!filter) returnconst handleKey = (e: KeyboardEvent) => {- if (e.key === 'Escape') onClose()+ if (e.key !== 'Escape' || e.defaultPrevented || hasOpenDialog()) return+ onClose()}document.addEventListener('keydown', handleKey)return () => document.removeEventListener('keydown', handleKey)}, [filter, onClose])- // Close on click outside+ // Close on click outside. The transaction dialog opened from a row, and its+ // popovers and selects, are portaled to the body; clicks there keep the+ // panel open so the next row can be edited once the dialog closes.useEffect(() => {if (!filter) returnconst handleClick = (e: MouseEvent) => {- if (panelRef.current && !panelRef.current.contains(e.target as Node)) {- onClose()- }+ if (!panelRef.current || panelRef.current.contains(e.target as Node)) return+ if (isInsideOverlayLayer(e.target) || hasOpenDialog()) return+ onClose()}// Delay to avoid closing immediately from the click that opened itconst timer = setTimeout(() => {diff --git a/frontend/src/lib/overlay-layers.test.ts b/frontend/src/lib/overlay-layers.test.tsnew file mode 100644index 00000000..2a853a34--- /dev/null+++ b/frontend/src/lib/overlay-layers.test.ts@@ -0,0 +1,48 @@+import { afterEach, describe, expect, it } from 'vitest'++import { hasOpenDialog, isInsideOverlayLayer } from '@/lib/overlay-layers'++function mount(html: string) {+ document.body.innerHTML = html+}++describe('overlay layers', () => {+ afterEach(() => {+ document.body.innerHTML = ''+ })++ it('treats dialog, popper, listbox and overlay content as an overlay layer', () => {+ mount(`+ <div role="dialog"><button id="in-dialog">a</button></div>+ <div data-radix-popper-content-wrapper><span id="in-popper">b</span></div>+ <div role="listbox"><div id="in-listbox">c</div></div>+ <div data-slot="dialog-overlay" id="overlay"></div>+ <main><button id="page">d</button></main>+ `)++ expect(isInsideOverlayLayer(document.getElementById('in-dialog'))).toBe(true)+ expect(isInsideOverlayLayer(document.getElementById('in-popper'))).toBe(true)+ expect(isInsideOverlayLayer(document.getElementById('in-listbox'))).toBe(true)+ expect(isInsideOverlayLayer(document.getElementById('overlay'))).toBe(true)+ expect(isInsideOverlayLayer(document.getElementById('page'))).toBe(false)+ })++ it('resolves text nodes to their parent element', () => {+ mount('<div role="dialog"><span id="label">Category</span></div>')+ const text = document.getElementById('label')!.firstChild++ expect(isInsideOverlayLayer(text)).toBe(true)+ })++ it('ignores missing targets', () => {+ expect(isInsideOverlayLayer(null)).toBe(false)+ })++ it('reports an open dialog only while its state is open', () => {+ mount('<div role="dialog" data-state="closed"></div>')+ expect(hasOpenDialog()).toBe(false)++ mount('<div role="dialog" data-state="open"></div>')+ expect(hasOpenDialog()).toBe(true)+ })+})diff --git a/frontend/src/lib/overlay-layers.ts b/frontend/src/lib/overlay-layers.tsnew file mode 100644index 00000000..e456849b--- /dev/null+++ b/frontend/src/lib/overlay-layers.ts@@ -0,0 +1,33 @@+/**+ * Helpers for side panels that close on an outside click or on Escape.+ *+ * Dialogs, popovers, selects and menus render in portals attached to+ * `document.body`, so a click inside them is "outside" any panel in DOM terms.+ * A panel that opens a dialog (for example to edit one of its rows) must not+ * treat interaction with that dialog as a reason to close.+ */++const OVERLAY_LAYER_SELECTOR = [+ '[role="dialog"]',+ '[role="alertdialog"]',+ '[data-slot="dialog-overlay"]',+ '[data-radix-popper-content-wrapper]',+ '[role="listbox"]',+ '[role="menu"]',+ '[data-sonner-toaster]',+].join(', ')++const OPEN_DIALOG_SELECTOR =+ '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]'++/** True when the event target sits inside a portaled dialog, popover, menu or toast. */+export function isInsideOverlayLayer(target: EventTarget | null): boolean {+ if (!target || !(target instanceof Node)) return false+ const element = target instanceof Element ? target : target.parentElement+ return !!element?.closest(OVERLAY_LAYER_SELECTOR)+}++/** True while a dialog is open on top of the page. */+export function hasOpenDialog(doc: Document = document): boolean {+ return doc.querySelector(OPEN_DIALOG_SELECTOR) !== null+}