Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat(frontend): add context menu for bulk actions (#1235)

Rodrigo Tavares8413c07054b2
diff --git a/frontend/src/components/category-picker.test.tsx b/frontend/src/components/category-picker.test.tsx
new file mode 100644
index 00000000..e5b8e2f6
--- /dev/null
+++ b/frontend/src/components/category-picker.test.tsx
@@ -0,0 +1,67 @@
+import { screen } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+
+import { renderWithProviders, t } from '@/test/utils'
+import type { Category, CategoryGroup } from '@/types'
+
+vi.mock('@/lib/api', () => ({ categories: { create: vi.fn() } }))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+
+import { CategoryPicker } from './category-picker'
+
+const groceries = { id: 'cat-1', name: 'Groceries', group_id: 'grp-1' } as unknown as Category
+const rent = { id: 'cat-2', name: 'Rent', group_id: 'grp-1' } as unknown as Category
+const movies = { id: 'cat-3', name: 'Movies', group_id: null } as unknown as Category
+const essentials = { id: 'grp-1', name: 'Essentials', categories: [groceries, rent] } as unknown as CategoryGroup
+
+function renderPicker(props: Partial<React.ComponentProps<typeof CategoryPicker>> = {}) {
+ const onChange = vi.fn()
+ const utils = renderWithProviders(
+ <CategoryPicker
+ value={null}
+ onChange={onChange}
+ categories={[groceries, rent, movies]}
+ groups={[essentials]}
+ {...props}
+ />,
+ )
+ return { ...utils, onChange }
+}
+
+describe('CategoryPicker', () => {
+ it('lists categories under their group, with the rest under "no group"', () => {
+ renderPicker()
+
+ expect(screen.getByText('Essentials')).toBeInTheDocument()
+ expect(screen.getByText(t('groups.noGroup'))).toBeInTheDocument()
+ expect(screen.getByText('Groceries')).toBeInTheDocument()
+ expect(screen.getByText('Movies')).toBeInTheDocument()
+ })
+
+ it('filters by name and reports the chosen category', async () => {
+ const { user, onChange } = renderPicker()
+
+ await user.type(screen.getByPlaceholderText(t('transactions.searchCategory')), 'ren')
+
+ expect(screen.queryByText('Groceries')).not.toBeInTheDocument()
+ await user.click(screen.getByText('Rent'))
+ expect(onChange).toHaveBeenCalledWith('cat-2')
+ })
+
+ it('offers "no category" only when asked and reports an empty value', async () => {
+ const { onChange, unmount } = renderPicker()
+ expect(screen.queryByText(t('transactions.noCategory'))).not.toBeInTheDocument()
+ unmount()
+
+ const second = renderPicker({ allowNone: true })
+ await second.user.click(screen.getByText(t('transactions.noCategory')))
+ expect(second.onChange).toHaveBeenCalledWith('')
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('does not mark "no category" as current when there is no selection to show', () => {
+ renderPicker({ allowNone: true, value: null })
+
+ expect(document.querySelector('svg.lucide-check')).toBeNull()
+ })
+})
diff --git a/frontend/src/components/category-picker.tsx b/frontend/src/components/category-picker.tsx
new file mode 100644
index 00000000..3b11d683
--- /dev/null
+++ b/frontend/src/components/category-picker.tsx
@@ -0,0 +1,165 @@
+import { useEffect, useRef, useState, useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+import { CheckIcon, PlusIcon } from 'lucide-react'
+import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from '@/components/ui/command'
+import { categories as categoriesApi } from '@/lib/api'
+import { extractApiError } from '@/lib/api-errors'
+import { invalidateCategoryQueries } from '@/lib/invalidate-queries'
+import { inlineCreateItemValue, inlineCreateName } from '@/lib/inline-create'
+import type { Category, CategoryGroup } from '@/types'
+import { normalizeText } from '@/lib/utils'
+
+// Same starting look the categories page gives a new category, so one made
+// from a picker is indistinguishable from one made there.
+const NEW_CATEGORY_ICON = 'circle-help'
+const NEW_CATEGORY_COLOR = '#6366f1'
+
+interface CategoryPickerProps {
+ /** The current selection; `null` when there is none to show (e.g. a bulk action). */
+ value: string | null
+ onChange: (value: string) => void
+ categories: Category[]
+ groups: CategoryGroup[]
+ allowNone?: boolean
+ /** Offer to create a category named after the search text when nothing matches it. */
+ creatable?: boolean
+ /** Called with a category just created from the search text, before `onChange`. */
+ onCreated?: (category: Category) => void
+ /** Focus the search field once mounted, for hosts that don't do it themselves. */
+ autoFocus?: boolean
+}
+
+/**
+ * The searchable, grouped category list. Hosts (the select's popover, the
+ * transactions context menu) provide the surface around it.
+ */
+export function CategoryPicker({
+ value,
+ onChange,
+ categories,
+ groups,
+ allowNone = false,
+ creatable = false,
+ onCreated,
+ autoFocus = false,
+}: CategoryPickerProps) {
+ const [search, setSearch] = useState('')
+ const rootRef = useRef<HTMLDivElement>(null)
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+
+ const createMutation = useMutation({
+ mutationFn: (name: string) =>
+ categoriesApi.create({ name, icon: NEW_CATEGORY_ICON, color: NEW_CATEGORY_COLOR }),
+ onSuccess: (category) => {
+ // Only the category lists refetch. Whatever form hosts this picker
+ // (an import preview, a half-filled transaction) keeps its state.
+ invalidateCategoryQueries(queryClient)
+ onCreated?.(category)
+ onChange(category.id)
+ toast.success(t('categories.created'))
+ },
+ onError: (err: unknown) => toast.error(extractApiError(err, t('common.error'))),
+ })
+
+ // Deferred a tick: a Radix menu keeps focus on its own trigger while the
+ // pointer is still over it, and would take it back from an eager autoFocus.
+ useEffect(() => {
+ if (!autoFocus) return
+ const id = setTimeout(() => rootRef.current?.querySelector('input')?.focus(), 50)
+ return () => clearTimeout(id)
+ }, [autoFocus])
+
+ const createName = creatable
+ ? inlineCreateName(search, (categories ?? []).map((c) => c.name))
+ : null
+
+ const displayGroups = useMemo(() => {
+ const ungrouped = (categories ?? []).filter((c) => !c.group_id)
+ if (ungrouped.length === 0) return groups
+
+ return [
+ ...groups,
+ {
+ id: 'ungrouped-virtual',
+ name: t('groups.noGroup'),
+ categories: ungrouped,
+ } as CategoryGroup,
+ ]
+ }, [categories, groups, t])
+
+ return (
+ <Command
+ ref={rootRef}
+ filter={(itemValue, search) => {
+ return normalizeText(itemValue).includes(normalizeText(search)) ? 1 : 0
+ }}
+ >
+ <CommandInput
+ placeholder={t('transactions.searchCategory')}
+ value={search}
+ onValueChange={setSearch}
+ />
+ <CommandList>
+ <CommandEmpty>{t('transactions.noCategoryFound')}</CommandEmpty>
+ {allowNone && (
+ <CommandGroup>
+ <CommandItem
+ value={`none ${t('transactions.noCategory')}`}
+ onSelect={() => {
+ onChange('')
+ }}
+ className="italic text-muted-foreground cursor-pointer"
+ >
+ <span className="flex-1">{t('transactions.noCategory')}</span>
+ {value === '' && <CheckIcon className="size-4 shrink-0" />}
+ </CommandItem>
+ </CommandGroup>
+ )}
+ {displayGroups.map((group) => (
+ <CommandGroup key={group.id}>
+ <div className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">
+ {group.name}
+ </div>
+ {group.categories.map((cat) => (
+ <CommandItem
+ key={cat.id}
+ value={`${group.name} ${cat.name}`}
+ onSelect={() => {
+ onChange(cat.id)
+ }}
+ className="cursor-pointer"
+ >
+ <div className="flex items-center gap-2 min-w-0 truncate flex-1">
+ {cat.color ? (
+ <span
+ className="size-2.5 shrink-0 rounded-full border border-black/5"
+ style={{ backgroundColor: cat.color }}
+ />
+ ) : null}
+ <span className="truncate">{cat.name}</span>
+ </div>
+ {value === cat.id && <CheckIcon className="size-4 shrink-0" />}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ ))}
+ {createName && (
+ <CommandGroup>
+ <CommandItem
+ value={inlineCreateItemValue(search)}
+ disabled={createMutation.isPending}
+ onSelect={() => createMutation.mutate(createName)}
+ className="cursor-pointer"
+ >
+ <PlusIcon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="truncate">{t('common.createNamed', { name: createName })}</span>
+ </CommandItem>
+ </CommandGroup>
+ )}
+ </CommandList>
+ </Command>
+ )
+}
diff --git a/frontend/src/components/category-select.tsx b/frontend/src/components/category-select.tsx
index d73701db..2df6393b 100644
--- a/frontend/src/components/category-select.tsx
+++ b/frontend/src/components/category-select.tsx
@@ -1,27 +1,16 @@
import { useState, useMemo, useContext } from 'react'
import { useTranslation } from 'react-i18next'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { toast } from 'sonner'
-import { ChevronDownIcon, CheckIcon, PlusIcon } from 'lucide-react'
+import { ChevronDownIcon } from 'lucide-react'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
-import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from '@/components/ui/command'
+import { CategoryPicker } from '@/components/category-picker'
import { WorkspaceContext } from '@/contexts/workspace-context'
-import { categories as categoriesApi } from '@/lib/api'
-import { extractApiError } from '@/lib/api-errors'
-import { invalidateCategoryQueries } from '@/lib/invalidate-queries'
-import { inlineCreateItemValue, inlineCreateName } from '@/lib/inline-create'
import type { Category, CategoryGroup } from '@/types'
-import { cn, normalizeText } from '@/lib/utils'
+import { cn } from '@/lib/utils'
import {
isCategoryHiddenFromSelection,
resolveSelectedCategory,
} from '@/lib/category-selection-utils'
-// Same starting look the categories page gives a new category, so one made
-// from a picker is indistinguishable from one made there.
-const NEW_CATEGORY_ICON = 'circle-help'
-const NEW_CATEGORY_COLOR = '#6366f1'
-
interface CategorySelectProps {
value: string
onChange: (value: string) => void
@@ -55,57 +44,21 @@ export function CategorySelect({
contentProps,
}: CategorySelectProps) {
const [open, setOpen] = useState(false)
- const [search, setSearch] = useState('')
// The category just created here. The list catches up once the refetch
// lands; until then this keeps the trigger showing the new name.
const [created, setCreated] = useState<Category | null>(null)
const { t } = useTranslation()
- const queryClient = useQueryClient()
// Read the context directly rather than through useWorkspace, so the
// picker still renders (without creation) outside a workspace provider.
const canWrite = useContext(WorkspaceContext)?.canWrite ?? false
const canCreate = creatable && canWrite
- const createMutation = useMutation({
- mutationFn: (name: string) =>
- categoriesApi.create({ name, icon: NEW_CATEGORY_ICON, color: NEW_CATEGORY_COLOR }),
- onSuccess: (category) => {
- // Only the category lists refetch. Whatever form hosts this picker
- // (an import preview, a half-filled transaction) keeps its state.
- invalidateCategoryQueries(queryClient)
- setCreated(category)
- onChange(category.id)
- handleOpenChange(false)
- toast.success(t('categories.created'))
- },
- onError: (err: unknown) => toast.error(extractApiError(err, t('common.error'))),
- })
-
function handleOpenChange(next: boolean) {
setOpen(next)
- if (!next) setSearch('')
}
- const createName = canCreate
- ? inlineCreateName(search, (categories ?? []).map((c) => c.name))
- : null
-
const resolvedPlaceholder = placeholder ?? t('transactions.selectCategory', 'Select category')
- const displayGroups = useMemo(() => {
- const ungrouped = (categories ?? []).filter((c) => !c.group_id)
- if (ungrouped.length === 0) return groups
-
- return [
- ...groups,
- {
- id: 'ungrouped-virtual',
- name: t('groups.noGroup'),
- categories: ungrouped,
- } as CategoryGroup,
- ]
- }, [categories, groups, t])
-
const selectedCategory = useMemo(() => {
const fallback = created && created.id === value ? created : currentCategory
return resolveSelectedCategory(categories ?? [], value, fallback)
@@ -156,77 +109,18 @@ export function CategorySelect({
className="w-[var(--radix-popover-trigger-width)] p-0 overflow-hidden"
{...contentProps}
>
- <Command
- filter={(itemValue, search) => {
- return normalizeText(itemValue).includes(normalizeText(search)) ? 1 : 0
+ <CategoryPicker
+ value={value}
+ onChange={(next) => {
+ onChange(next)
+ handleOpenChange(false)
}}
- >
- <CommandInput
- placeholder={t('transactions.searchCategory')}
- value={search}
- onValueChange={setSearch}
- />
- <CommandList>
- <CommandEmpty>{t('transactions.noCategoryFound')}</CommandEmpty>
- {allowNone && (
- <CommandGroup>
- <CommandItem
- value={`none ${t('transactions.noCategory')}`}
- onSelect={() => {
- onChange('')
- handleOpenChange(false)
- }}
- className="italic text-muted-foreground cursor-pointer"
- >
- <span className="flex-1">{t('transactions.noCategory')}</span>
- {value === '' && <CheckIcon className="size-4 shrink-0" />}
- </CommandItem>
- </CommandGroup>
- )}
- {displayGroups.map((group) => (
- <CommandGroup key={group.id}>
- <div className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">
- {group.name}
- </div>
- {group.categories.map((cat) => (
- <CommandItem
- key={cat.id}
- value={`${group.name} ${cat.name}`}
- onSelect={() => {
- onChange(cat.id)
- handleOpenChange(false)
- }}
- className="cursor-pointer"
- >
- <div className="flex items-center gap-2 min-w-0 truncate flex-1">
- {cat.color ? (
- <span
- className="size-2.5 shrink-0 rounded-full border border-black/5"
- style={{ backgroundColor: cat.color }}
- />
- ) : null}
- <span className="truncate">{cat.name}</span>
- </div>
- {value === cat.id && <CheckIcon className="size-4 shrink-0" />}
- </CommandItem>
- ))}
- </CommandGroup>
- ))}
- {createName && (
- <CommandGroup>
- <CommandItem
- value={inlineCreateItemValue(search)}
- disabled={createMutation.isPending}
- onSelect={() => createMutation.mutate(createName)}
- className="cursor-pointer"
- >
- <PlusIcon className="size-4 shrink-0 text-muted-foreground" />
- <span className="truncate">{t('common.createNamed', { name: createName })}</span>
- </CommandItem>
- </CommandGroup>
- )}
- </CommandList>
- </Command>
+ categories={categories}
+ groups={groups}
+ allowNone={allowNone}
+ creatable={canCreate}
+ onCreated={setCreated}
+ />
</PopoverContent>
</Popover>
)
diff --git a/frontend/src/components/ui/context-menu.tsx b/frontend/src/components/ui/context-menu.tsx
new file mode 100644
index 00000000..c8def4d8
--- /dev/null
+++ b/frontend/src/components/ui/context-menu.tsx
@@ -0,0 +1,246 @@
+"use client"
+
+import * as React from "react"
+import { ContextMenu as ContextMenuPrimitive } from "radix-ui"
+import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function ContextMenu({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
+ return <ContextMenuPrimitive.Root {...props} />
+}
+
+function ContextMenuTrigger({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
+ return <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
+}
+
+function ContextMenuGroup({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
+ return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
+}
+
+function ContextMenuPortal({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
+ return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
+}
+
+function ContextMenuSub({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
+ return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
+}
+
+function ContextMenuRadioGroup({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
+ return (
+ <ContextMenuPrimitive.RadioGroup
+ data-slot="context-menu-radio-group"
+ {...props}
+ />
+ )
+}
+
+function ContextMenuSubTrigger({
+ className,
+ inset,
+ children,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
+ inset?: boolean
+}) {
+ return (
+ <ContextMenuPrimitive.SubTrigger
+ data-slot="context-menu-sub-trigger"
+ data-inset={inset}
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRightIcon className="ml-auto size-4" />
+ </ContextMenuPrimitive.SubTrigger>
+ )
+}
+
+function ContextMenuSubContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
+ return (
+ <ContextMenuPrimitive.SubContent
+ data-slot="context-menu-sub-content"
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] overflow-hidden rounded-md border p-1 shadow-lg",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ContextMenuContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
+ return (
+ <ContextMenuPrimitive.Portal>
+ <ContextMenuPrimitive.Content
+ data-slot="context-menu-content"
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] overflow-hidden rounded-md border p-1 shadow-md",
+ className
+ )}
+ {...props}
+ />
+ </ContextMenuPrimitive.Portal>
+ )
+}
+
+function ContextMenuItem({
+ className,
+ inset,
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
+ inset?: boolean
+ variant?: "default" | "destructive"
+}) {
+ return (
+ <ContextMenuPrimitive.Item
+ data-slot="context-menu-item"
+ data-inset={inset}
+ data-variant={variant}
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ContextMenuCheckboxItem({
+ className,
+ children,
+ checked,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
+ return (
+ <ContextMenuPrimitive.CheckboxItem
+ data-slot="context-menu-checkbox-item"
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <ContextMenuPrimitive.ItemIndicator>
+ <CheckIcon className="size-4" />
+ </ContextMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </ContextMenuPrimitive.CheckboxItem>
+ )
+}
+
+function ContextMenuRadioItem({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
+ return (
+ <ContextMenuPrimitive.RadioItem
+ data-slot="context-menu-radio-item"
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <ContextMenuPrimitive.ItemIndicator>
+ <CircleIcon className="size-2 fill-current" />
+ </ContextMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </ContextMenuPrimitive.RadioItem>
+ )
+}
+
+function ContextMenuLabel({
+ className,
+ inset,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
+ inset?: boolean
+}) {
+ return (
+ <ContextMenuPrimitive.Label
+ data-slot="context-menu-label"
+ data-inset={inset}
+ className={cn(
+ "px-2 py-1.5 text-sm font-medium text-foreground data-[inset]:pl-8",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ContextMenuSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
+ return (
+ <ContextMenuPrimitive.Separator
+ data-slot="context-menu-separator"
+ className={cn("bg-border -mx-1 my-1 h-px", className)}
+ {...props}
+ />
+ )
+}
+
+function ContextMenuShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="context-menu-shortcut"
+ className={cn(
+ "text-muted-foreground ml-auto text-xs tracking-widest",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ ContextMenu,
+ ContextMenuTrigger,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuCheckboxItem,
+ ContextMenuRadioGroup,
+ ContextMenuRadioItem,
+ ContextMenuLabel,
+ ContextMenuSeparator,
+ ContextMenuShortcut,
+ ContextMenuGroup,
+ ContextMenuPortal,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+}
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index b9bb1613..fc35559b 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -12,6 +12,17 @@ import { transactions, categories as categoriesApi, categoryGroups as categoryGr
import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuPortal,
+ ContextMenuSeparator,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+ ContextMenuTrigger,
+} from '@/components/ui/context-menu'
import {
Dialog,
DialogContent,
@@ -36,7 +47,7 @@ import {
TableRow,
} from '@/components/ui/table'
import { Skeleton } from '@/components/ui/skeleton'
-import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, Clock, HelpCircle, Info, Paperclip, Trash2, Users, X, EyeClosed, ChartNoAxesColumn, SlidersHorizontal, Receipt } from 'lucide-react'
+import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, Clock, HelpCircle, Info, Paperclip, TagIcon, Trash2, Users, X, EyeClosed, ChartNoAxesColumn, SlidersHorizontal, Receipt } from 'lucide-react'
import type { Transaction, Rule, InstallmentSeriesInput, TransactionApplyScope, TransactionEditPayload, ReconciliationSuggestion } from '@/types'
import { RuleDialog, type RuleDialogInitialData } from '@/components/rule-dialog'
import { PageHeader } from '@/components/page-header'
@@ -44,6 +55,7 @@ import { calculateRangeSelection } from '@/lib/selection-utils'
import { isManualInstallmentSeriesRow } from '@/lib/installment-series'
import { CategoryIcon } from '@/components/category-icon'
import { CategorySelect } from '@/components/category-select'
+import { CategoryPicker } from '@/components/category-picker'
import { TransactionDialog, type SaveAction, type TransactionSavePayload } from '@/components/transaction-dialog'
import { extractApiError } from '@/lib/api-errors'
import { refreshTransactionsView } from '@/lib/transactions-refresh'
@@ -219,6 +231,9 @@ export default function TransactionsPage() {
const [bulkTagInput, setBulkTagInput] = useState<string>('')
const [createRuleOpen, setCreateRuleOpen] = useState(false)
const [createRuleInitialData, setCreateRuleInitialData] = useState<RuleDialogInitialData | undefined>(undefined)
+ const [isBulkBarPulsing, setIsBulkBarPulsing] = useState(false)
+ const [menuEpoch, setMenuEpoch] = useState(0)
+ const bulkTagInputRef = useRef<HTMLInputElement>(null)
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)
const highlightId = searchParams.get('highlight')
const highlightedRowRef = useRef<HTMLTableRowElement | null>(null)
@@ -849,6 +864,16 @@ export default function TransactionsPage() {
const totalPages = data ? Math.ceil(data.total / limit) : 0
+ const handleFocusTagInput = () => {
+ setIsBulkBarPulsing(true)
+ setTimeout(() => {
+ bulkTagInputRef.current?.focus()
+ }, 50)
+ setTimeout(() => {
+ setIsBulkBarPulsing(false)
+ }, 800)
+ }
+
const isTransferCategoryPromptOpen = !!pendingTransferCategoryUpdate
const submitPendingTransferCategoryUpdate = (applyToTransferPair: boolean) => {
@@ -1585,42 +1610,119 @@ export default function TransactionsPage() {
</TableHeader>
<TableBody>
{filteredItems.map((tx) => (
- <TableRow
- key={tx.id}
- ref={tx.id === highlightId ? highlightedRowRef : undefined}
- className={`hover:bg-muted border-b border-border last:border-0 ${
- selectedIds.has(tx.id) ? 'bg-primary/5' : ''
- } ${tx.is_shared || !canWrite ? 'cursor-default' : 'cursor-pointer'}`}
- onClick={() => {
- if (tx.is_shared) {
- // Owned by another user — view in the group context instead.
- if (tx.group_id) navigate(`/groups/${tx.group_id}`)
- return
- }
- if (!canWrite) return
- setEditingTx(tx)
- setDialogOpen(true)
- }}
- >
- <TableCell style={{ width: 40, minWidth: 40 }} className="py-2.5 pl-4 pr-0">
- {/* Bulk operations are scoped to user.id so they
- silently skip shared rows — hide the checkbox
- on those to avoid the dead-end UX. */}
- {canWrite && !tx.is_shared && (
- <input
- type="checkbox"
- checked={selectedIds.has(tx.id)}
- onChange={() => {}}
- onClick={(e) => {
- e.stopPropagation()
- toggleSelect(tx.id, e.shiftKey)
- }}
- className="h-4 w-4 rounded border-border accent-primary cursor-pointer"
- />
- )}
- </TableCell>
- {grid.visibleColumns.map(col => renderBodyCell(col, tx))}
- </TableRow>
+ <ContextMenu key={`${tx.id}:${menuEpoch}`}>
+ <ContextMenuTrigger asChild disabled={!canWrite || tx.is_shared}>
+ <TableRow
+ ref={tx.id === highlightId ? highlightedRowRef : undefined}
+ onContextMenu={() => {
+ if (canWrite && !tx.is_shared && !selectedIds.has(tx.id)) {
+ setSelectedIds(new Set([tx.id]))
+ setLastSelectedId(tx.id)
+ }
+ }}
+ className={`hover:bg-muted border-b border-border last:border-0 ${
+ selectedIds.has(tx.id) ? 'bg-primary/5' : ''
+ } ${tx.is_shared || !canWrite ? 'cursor-default' : 'cursor-pointer'}`}
+ onClick={() => {
+ if (tx.is_shared) {
+ // Owned by another user — view in the group context instead.
+ if (tx.group_id) navigate(`/groups/${tx.group_id}`)
+ return
+ }
+ if (!canWrite) return
+ setEditingTx(tx)
+ setDialogOpen(true)
+ }}
+ >
+ <TableCell style={{ width: 40, minWidth: 40 }} className="py-2.5 pl-4 pr-0">
+ {/* Bulk operations are scoped to user.id so they
+ silently skip shared rows — hide the checkbox
+ on those to avoid the dead-end UX. */}
+ {canWrite && !tx.is_shared && (
+ <input
+ type="checkbox"
+ checked={selectedIds.has(tx.id)}
+ onChange={() => {}}
+ onClick={(e) => {
+ e.stopPropagation()
+ toggleSelect(tx.id, e.shiftKey)
+ }}
+ className="h-4 w-4 rounded border-border accent-primary cursor-pointer"
+ />
+ )}
+ </TableCell>
+ {grid.visibleColumns.map(col => renderBodyCell(col, tx))}
+ </TableRow>
+ </ContextMenuTrigger>
+ <ContextMenuPortal>
+ <ContextMenuContent className="w-64">
+ <ContextMenuItem
+ disabled={!canOpenLinkDialog}
+ onSelect={() => setLinkTransferDialogOpen(true)}
+ >
+ <ArrowLeftRight className="mr-2 h-4 w-4" />
+ {t('transactions.linkAsTransfer')}
+ </ContextMenuItem>
+
+ <ContextMenuSub>
+ <ContextMenuSubTrigger>
+ <TagIcon className="mr-2 h-4 w-4" />
+ {t('transactions.selectCategory')}
+ </ContextMenuSubTrigger>
+ <ContextMenuPortal>
+ <ContextMenuSubContent className="w-64 p-0">
+ {/* A text field inside a Radix menu would have its arrow keys
+ and typing (typeahead) handled as menu navigation, so keep
+ the key events inside the picker. Escape still closes the
+ menu, as it is handled on the document. */}
+ <div onKeyDown={(e) => e.stopPropagation()}>
+ <CategoryPicker
+ value={null}
+ onChange={(categoryId) => {
+ bulkCategorizeMutation.mutate({ ids: Array.from(selectedIds), categoryId: categoryId || null })
+ // Radix's context menu can't be closed from outside and
+ // picker rows are not menu items, so remount it to dismiss.
+ setMenuEpoch((n) => n + 1)
+ }}
+ categories={categoriesList ?? []}
+ groups={categoryGroupsList ?? []}
+ allowNone
+ autoFocus
+ />
+ </div>
+ </ContextMenuSubContent>
+ </ContextMenuPortal>
+ </ContextMenuSub>
+
+ <ContextMenuItem onSelect={() => setBulkAddToGroupOpen(true)}>
+ <Users className="mr-2 h-4 w-4" />
+ {t('transactions.addToGroup')}
+ </ContextMenuItem>
+
+ <ContextMenuItem onSelect={handleFocusTagInput}>
+ <TagIcon className="mr-2 h-4 w-4" />
+ {t('transactions.bulkAddTags')}
+ </ContextMenuItem>
+
+ {selectedSingleTx && (
+ <ContextMenuItem onSelect={() => handleCreateRuleFromTransaction(selectedSingleTx)}>
+ <SlidersHorizontal className="mr-2 h-4 w-4" />
+ {t('transactions.createRule')}
+ </ContextMenuItem>
+ )}
+
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ variant="destructive"
+ disabled={bulkDeleteMutation.isPending}
+ onSelect={() => setBulkDeleteConfirmOpen(true)}
+ >
+ <Trash2 className="mr-2 h-4 w-4" />
+ {t('common.delete')}
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenuPortal>
+ </ContextMenu>
))}
{filteredItems.length === 0 && (
<TableRow>
@@ -1787,7 +1889,7 @@ export default function TransactionsPage() {
sidebarCollapsed ? 'lg:left-16' : 'lg:left-60',
)}>
<div className="mx-auto max-w-7xl px-3 md:px-6 pb-4 md:pb-6">
- <div className="flex items-stretch gap-1.5 bg-card border border-border shadow-xl rounded-2xl p-2">
+ <div className="flex items-stretch gap-1.5 bg-card border border-border shadow-xl rounded-2xl p-2 transition-all duration-500">
<MobileBulkSelectionActions
selectedCount={selectedIds.size}
categoryValue={bulkCategory}
@@ -1884,12 +1986,16 @@ export default function TransactionsPage() {
<div className="w-px bg-border/60 self-stretch" />
{/* Add tags inline */}
- <div className="flex items-center gap-1 px-1">
+ <div
+ className={`flex items-center gap-1 px-1 rounded-xl transition-all duration-300 ${
+ isBulkBarPulsing ? 'ring-2 ring-primary ring-offset-2 scale-[1.05] bg-primary/5' : ''
+ }`}>
<input
+ ref={bulkTagInputRef}
type="text"
value={bulkTagInput}
onChange={(e) => setBulkTagInput(e.target.value)}
- placeholder={t('transactions.addTagsPlaceholder', '#tag…')}
+ placeholder={t('transactions.addTagsPlaceholder')}
className="rounded-lg px-2.5 py-2 text-sm bg-transparent text-foreground placeholder:text-muted-foreground/70 focus:outline-none focus:bg-muted/60 w-28 md:w-40"
onKeyDown={(e) => {
if (e.key === 'Enter' && bulkTagInput.trim()) {
@@ -1909,7 +2015,7 @@ export default function TransactionsPage() {
bulkAddTagsMutation.mutate({ ids: Array.from(selectedIds), tags: tagList })
}}
className="h-8 w-8 px-0 shrink-0"
- title={t('transactions.bulkAddTags', 'Add tags')}
+ title={t('transactions.bulkAddTags')}
>
<Check size={15} />
</Button>