feat(calculadora): adicionar dialog arrastável e seleção de valor

- Calculadora agora é arrastável via drag handle no header
- Novo callback onSelectValue permite inserir valor no campo de lançamento
- Ajustado subtitle de categorias e estilo do collapse na sidebar
- Atualizado snapshot drizzle

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Felipe Coutinho
2026-02-06 13:22:31 +00:00
parent 4152a27f4d
commit 5bb5693baf
11 changed files with 2631 additions and 2510 deletions

View File

@@ -15,7 +15,7 @@ export default function RootLayout({
<PageDescription
icon={<RiPriceTag3Line />}
title="Categorias"
subtitle="Gerencie suas categorias de despesas e receitas acompanhando o histórico de desempenho dos últimos 9 meses, permitindo ajustes financeiros precisos conforme necessário."
subtitle="Gerencie suas categorias de despesas e receitas, permitindo ajustes financeiros precisos conforme necessário."
/>
{children}
</section>

View File

@@ -16,6 +16,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useDraggableDialog } from "@/hooks/use-draggable-dialog";
import { cn } from "@/lib/utils/ui";
type Variant = React.ComponentProps<typeof Button>["variant"];
@@ -27,18 +28,62 @@ type CalculatorDialogButtonProps = {
className?: string;
children?: React.ReactNode;
withTooltip?: boolean;
onSelectValue?: (value: string) => void;
};
function CalculatorDialogContent({
open,
onSelectValue,
}: {
open: boolean;
onSelectValue?: (value: string) => void;
}) {
const { dragHandleProps, contentRefCallback, resetPosition } =
useDraggableDialog();
React.useEffect(() => {
if (!open) {
resetPosition();
}
}, [open, resetPosition]);
return (
<DialogContent
ref={contentRefCallback}
className="p-4 sm:max-w-sm"
onEscapeKeyDown={(e) => e.preventDefault()}
>
<DialogHeader
className="cursor-grab select-none space-y-2 active:cursor-grabbing"
{...dragHandleProps}
>
<DialogTitle className="flex items-center gap-2 text-lg">
<RiCalculatorLine className="h-5 w-5" />
Calculadora
</DialogTitle>
</DialogHeader>
<Calculator isOpen={open} onSelectValue={onSelectValue} />
</DialogContent>
);
}
export function CalculatorDialogButton({
variant = "ghost",
size = "sm",
className,
children,
withTooltip = false,
onSelectValue,
}: CalculatorDialogButtonProps) {
const [open, setOpen] = React.useState(false);
// Se withTooltip for true, usa o estilo do header
const handleSelectValue = onSelectValue
? (value: string) => {
onSelectValue(value);
setOpen(false);
}
: undefined;
if (withTooltip) {
return (
<Dialog open={open} onOpenChange={setOpen}>
@@ -72,20 +117,14 @@ export function CalculatorDialogButton({
Calculadora
</TooltipContent>
</Tooltip>
<DialogContent className="p-4 sm:max-w-sm">
<DialogHeader className="space-y-2">
<DialogTitle className="flex items-center gap-2 text-lg">
<RiCalculatorLine className="h-5 w-5" />
Calculadora
</DialogTitle>
</DialogHeader>
<Calculator />
</DialogContent>
<CalculatorDialogContent
open={open}
onSelectValue={handleSelectValue}
/>
</Dialog>
);
}
// Estilo padrão para outros usos
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
@@ -95,15 +134,7 @@ export function CalculatorDialogButton({
)}
</Button>
</DialogTrigger>
<DialogContent className="p-4 sm:max-w-sm">
<DialogHeader className="space-y-2">
<DialogTitle className="flex items-center gap-2 text-lg">
<RiCalculatorLine className="h-5 w-5" />
Calculadora
</DialogTitle>
</DialogHeader>
<Calculator />
</DialogContent>
<CalculatorDialogContent open={open} onSelectValue={handleSelectValue} />
</Dialog>
);
}

View File

@@ -1,29 +1,49 @@
import { Button } from "@/components/ui/button";
import type { CalculatorButtonConfig } from "@/hooks/use-calculator-state";
import type { Operator } from "@/lib/utils/calculator";
import { cn } from "@/lib/utils/ui";
type CalculatorKeypadProps = {
buttons: CalculatorButtonConfig[][];
activeOperator: Operator | null;
};
export function CalculatorKeypad({ buttons }: CalculatorKeypadProps) {
const LABEL_TO_OPERATOR: Record<string, Operator> = {
"÷": "divide",
"×": "multiply",
"-": "subtract",
"+": "add",
};
export function CalculatorKeypad({
buttons,
activeOperator,
}: CalculatorKeypadProps) {
return (
<div className="grid grid-cols-4 gap-2">
{buttons.flat().map((btn, index) => (
<Button
key={`${btn.label}-${index}`}
type="button"
variant={btn.variant ?? "outline"}
onClick={btn.onClick}
className={cn(
"h-12 text-base font-semibold",
btn.colSpan === 2 && "col-span-2",
btn.colSpan === 3 && "col-span-3",
)}
>
{btn.label}
</Button>
))}
{buttons.flat().map((btn, index) => {
const op = LABEL_TO_OPERATOR[btn.label];
const isActive = op != null && op === activeOperator;
return (
<Button
key={`${btn.label}-${index}`}
type="button"
variant={isActive ? "default" : (btn.variant ?? "outline")}
onClick={btn.onClick}
className={cn(
"h-12 text-base font-semibold",
btn.colSpan === 2 && "col-span-2",
btn.colSpan === 3 && "col-span-3",
isActive &&
"bg-primary text-primary-foreground hover:bg-primary/90 ring-2 ring-primary/30",
btn.className,
)}
>
{btn.label}
</Button>
);
})}
</div>
);
}

View File

@@ -1,27 +1,61 @@
"use client";
import { CalculatorKeypad } from "@/components/calculadora/calculator-keypad";
import { Button } from "@/components/ui/button";
import { useCalculatorKeyboard } from "@/hooks/use-calculator-keyboard";
import { useCalculatorState } from "@/hooks/use-calculator-state";
import { CalculatorDisplay } from "./calculator-display";
export default function Calculator() {
type CalculatorProps = {
isOpen?: boolean;
onSelectValue?: (value: string) => void;
};
export default function Calculator({
isOpen = true,
onSelectValue,
}: CalculatorProps) {
const {
display,
operator,
expression,
history,
resultText,
copied,
buttons,
inputDigit,
inputDecimal,
setNextOperator,
evaluate,
deleteLastDigit,
reset,
applyPercent,
copyToClipboard,
pasteFromClipboard,
} = useCalculatorState();
useCalculatorKeyboard({
isOpen,
canCopy: Boolean(resultText),
onCopy: copyToClipboard,
onPaste: pasteFromClipboard,
inputDigit,
inputDecimal,
setNextOperator,
evaluate,
deleteLastDigit,
reset,
applyPercent,
});
const canUseValue = onSelectValue && display !== "Erro" && display !== "0";
const handleSelectValue = () => {
if (!onSelectValue) return;
const numericValue = Math.abs(Number(display)).toFixed(2);
onSelectValue(numericValue);
};
return (
<div className="space-y-4">
<CalculatorDisplay
@@ -31,7 +65,18 @@ export default function Calculator() {
copied={copied}
onCopy={copyToClipboard}
/>
<CalculatorKeypad buttons={buttons} />
<CalculatorKeypad buttons={buttons} activeOperator={operator} />
{onSelectValue && (
<Button
type="button"
variant="default"
className="w-full"
disabled={!canUseValue}
onClick={handleSelectValue}
>
Usar valor
</Button>
)}
</div>
);
}

View File

@@ -67,6 +67,7 @@ export function BasicFieldsSection({
variant="ghost"
size="icon-sm"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2"
onSelectValue={(value) => onFieldChange("amount", value)}
>
<RiCalculatorLine className="h-4 w-4 text-muted-foreground" />
</CalculatorDialogButton>

View File

@@ -7,7 +7,6 @@ import {
} from "@remixicon/react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import * as React from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import {
@@ -134,8 +133,8 @@ export function NavMain({ sections }: { sections: NavSection[] }) {
{item.items?.length ? (
<>
<CollapsibleTrigger asChild>
<SidebarMenuAction className="data-[state=open]:rotate-90 text-foreground px-2 trasition-transform duration-200">
<RiArrowRightSLine />
<SidebarMenuAction className="data-[state=open]:rotate-90 px-2 trasition-transform duration-200">
<RiArrowRightSLine className="text-primary" />
<span className="sr-only">Toggle</span>
</SidebarMenuAction>
</CollapsibleTrigger>

File diff suppressed because it is too large Load Diff

View File

@@ -1,118 +1,118 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1762993507299,
"tag": "0000_flashy_manta",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1765199006435,
"tag": "0001_young_mister_fear",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1765200545692,
"tag": "0002_slimy_flatman",
"breakpoints": true
},
{
"idx": 3,
"version": "7",
"when": 1767102605526,
"tag": "0003_green_korg",
"breakpoints": true
},
{
"idx": 4,
"version": "7",
"when": 1767104066872,
"tag": "0004_acoustic_mach_iv",
"breakpoints": true
},
{
"idx": 5,
"version": "7",
"when": 1767106121811,
"tag": "0005_adorable_bruce_banner",
"breakpoints": true
},
{
"idx": 6,
"version": "7",
"when": 1767107487318,
"tag": "0006_youthful_mister_fear",
"breakpoints": true
},
{
"idx": 7,
"version": "7",
"when": 1767118780033,
"tag": "0007_sturdy_kate_bishop",
"breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1767125796314,
"tag": "0008_fat_stick",
"breakpoints": true
},
{
"idx": 9,
"version": "7",
"when": 1768925100873,
"tag": "0009_add_dashboard_widgets",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1769369834242,
"tag": "0010_lame_psynapse",
"breakpoints": true
},
{
"idx": 11,
"version": "7",
"when": 1769447087678,
"tag": "0011_remove_unused_inbox_columns",
"breakpoints": true
},
{
"idx": 12,
"version": "7",
"when": 1769533200000,
"tag": "0012_rename_tables_to_portuguese",
"breakpoints": true
},
{
"idx": 13,
"version": "7",
"when": 1769523352777,
"tag": "0013_fancy_rick_jones",
"breakpoints": true
},
{
"idx": 14,
"version": "7",
"when": 1769619226903,
"tag": "0014_yielding_jack_flag",
"breakpoints": true
},
{
"idx": 15,
"version": "7",
"when": 1770332054481,
"tag": "0015_concerned_kat_farrell",
"breakpoints": true
}
]
}
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1762993507299,
"tag": "0000_flashy_manta",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1765199006435,
"tag": "0001_young_mister_fear",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1765200545692,
"tag": "0002_slimy_flatman",
"breakpoints": true
},
{
"idx": 3,
"version": "7",
"when": 1767102605526,
"tag": "0003_green_korg",
"breakpoints": true
},
{
"idx": 4,
"version": "7",
"when": 1767104066872,
"tag": "0004_acoustic_mach_iv",
"breakpoints": true
},
{
"idx": 5,
"version": "7",
"when": 1767106121811,
"tag": "0005_adorable_bruce_banner",
"breakpoints": true
},
{
"idx": 6,
"version": "7",
"when": 1767107487318,
"tag": "0006_youthful_mister_fear",
"breakpoints": true
},
{
"idx": 7,
"version": "7",
"when": 1767118780033,
"tag": "0007_sturdy_kate_bishop",
"breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1767125796314,
"tag": "0008_fat_stick",
"breakpoints": true
},
{
"idx": 9,
"version": "7",
"when": 1768925100873,
"tag": "0009_add_dashboard_widgets",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1769369834242,
"tag": "0010_lame_psynapse",
"breakpoints": true
},
{
"idx": 11,
"version": "7",
"when": 1769447087678,
"tag": "0011_remove_unused_inbox_columns",
"breakpoints": true
},
{
"idx": 12,
"version": "7",
"when": 1769533200000,
"tag": "0012_rename_tables_to_portuguese",
"breakpoints": true
},
{
"idx": 13,
"version": "7",
"when": 1769523352777,
"tag": "0013_fancy_rick_jones",
"breakpoints": true
},
{
"idx": 14,
"version": "7",
"when": 1769619226903,
"tag": "0014_yielding_jack_flag",
"breakpoints": true
},
{
"idx": 15,
"version": "7",
"when": 1770332054481,
"tag": "0015_concerned_kat_farrell",
"breakpoints": true
}
]
}

View File

@@ -1,9 +1,18 @@
import { useEffect } from "react";
import type { Operator } from "@/lib/utils/calculator";
type UseCalculatorKeyboardParams = {
isOpen: boolean;
canCopy: boolean;
onCopy: () => void | Promise<void>;
onPaste: () => void | Promise<void>;
inputDigit: (digit: string) => void;
inputDecimal: () => void;
setNextOperator: (op: Operator) => void;
evaluate: () => void;
deleteLastDigit: () => void;
reset: () => void;
applyPercent: () => void;
};
function shouldIgnoreForEditableTarget(target: EventTarget | null): boolean {
@@ -17,76 +26,118 @@ function shouldIgnoreForEditableTarget(target: EventTarget | null): boolean {
);
}
const KEY_TO_OPERATOR: Record<string, Operator> = {
"+": "add",
"-": "subtract",
"*": "multiply",
"/": "divide",
};
export function useCalculatorKeyboard({
isOpen,
canCopy,
onCopy,
onPaste,
inputDigit,
inputDecimal,
setNextOperator,
evaluate,
deleteLastDigit,
reset,
applyPercent,
}: UseCalculatorKeyboardParams) {
useEffect(() => {
if (!canCopy) {
return;
}
if (!isOpen) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (!(event.ctrlKey || event.metaKey)) {
const { key, ctrlKey, metaKey } = event;
// Ctrl/Cmd shortcuts
if (ctrlKey || metaKey) {
if (shouldIgnoreForEditableTarget(event.target)) return;
const lowerKey = key.toLowerCase();
if (lowerKey === "c" && canCopy) {
const selection = window.getSelection();
if (selection && selection.toString().trim().length > 0) return;
event.preventDefault();
void onCopy();
} else if (lowerKey === "v") {
const selection = window.getSelection();
if (selection && selection.toString().trim().length > 0) return;
if (!navigator.clipboard?.readText) return;
event.preventDefault();
void onPaste();
}
return;
}
if (shouldIgnoreForEditableTarget(event.target)) {
// Digits
if (key >= "0" && key <= "9") {
event.preventDefault();
inputDigit(key);
return;
}
if (event.key.toLowerCase() !== "c") {
// Decimal
if (key === "." || key === ",") {
event.preventDefault();
inputDecimal();
return;
}
const selection = window.getSelection();
if (selection && selection.toString().trim().length > 0) {
// Operators
const op = KEY_TO_OPERATOR[key];
if (op) {
event.preventDefault();
setNextOperator(op);
return;
}
event.preventDefault();
void onCopy();
// Evaluate
if (key === "Enter" || key === "=") {
event.preventDefault();
evaluate();
return;
}
// Backspace
if (key === "Backspace") {
event.preventDefault();
deleteLastDigit();
return;
}
// Escape resets calculator (dialog close is handled by onEscapeKeyDown)
if (key === "Escape") {
event.preventDefault();
reset();
return;
}
// Percent
if (key === "%") {
event.preventDefault();
applyPercent();
return;
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [canCopy, onCopy]);
useEffect(() => {
const handlePasteShortcut = (event: KeyboardEvent) => {
if (!(event.ctrlKey || event.metaKey)) {
return;
}
if (event.key.toLowerCase() !== "v") {
return;
}
if (shouldIgnoreForEditableTarget(event.target)) {
return;
}
const selection = window.getSelection();
if (selection && selection.toString().trim().length > 0) {
return;
}
if (!navigator.clipboard?.readText) {
return;
}
event.preventDefault();
void onPaste();
};
document.addEventListener("keydown", handlePasteShortcut);
return () => {
document.removeEventListener("keydown", handlePasteShortcut);
};
}, [onPaste]);
}, [
isOpen,
canCopy,
onCopy,
onPaste,
inputDigit,
inputDecimal,
setNextOperator,
evaluate,
deleteLastDigit,
reset,
applyPercent,
]);
}

View File

@@ -15,6 +15,7 @@ export type CalculatorButtonConfig = {
onClick: () => void;
variant?: VariantProps<typeof buttonVariants>["variant"];
colSpan?: number;
className?: string;
};
export function useCalculatorState() {
@@ -242,8 +243,8 @@ export function useCalculatorState() {
const buttons: CalculatorButtonConfig[][] = [
[
{ label: "C", onClick: reset, variant: "destructive" },
{ label: "⌫", onClick: deleteLastDigit, variant: "default" },
{ label: "%", onClick: applyPercent, variant: "default" },
{ label: "⌫", onClick: deleteLastDigit, variant: "secondary" },
{ label: "%", onClick: applyPercent, variant: "secondary" },
{
label: "÷",
onClick: makeOperatorHandler("divide"),
@@ -277,7 +278,7 @@ export function useCalculatorState() {
{ label: "+", onClick: makeOperatorHandler("add"), variant: "outline" },
],
[
{ label: "±", onClick: toggleSign, variant: "default" },
{ label: "±", onClick: toggleSign, variant: "secondary" },
{ label: "0", onClick: () => inputDigit("0") },
{ label: ",", onClick: inputDecimal },
{ label: "=", onClick: evaluate, variant: "default" },
@@ -358,11 +359,20 @@ export function useCalculatorState() {
}, []);
return {
display,
operator,
expression,
history,
resultText,
copied,
buttons,
inputDigit,
inputDecimal,
setNextOperator,
evaluate,
deleteLastDigit,
reset,
applyPercent,
copyToClipboard,
pasteFromClipboard,
};

View File

@@ -0,0 +1,90 @@
import { useCallback, useRef } from "react";
type Position = { x: number; y: number };
const MIN_VISIBLE_PX = 20;
function clampPosition(
x: number,
y: number,
elementWidth: number,
elementHeight: number,
): Position {
const maxX = window.innerWidth - MIN_VISIBLE_PX;
const minX = MIN_VISIBLE_PX - elementWidth;
const maxY = window.innerHeight - MIN_VISIBLE_PX;
const minY = MIN_VISIBLE_PX - elementHeight;
return {
x: Math.min(Math.max(x, minX), maxX),
y: Math.min(Math.max(y, minY), maxY),
};
}
function applyTranslate(el: HTMLElement, x: number, y: number) {
if (x === 0 && y === 0) {
el.style.translate = "";
} else {
el.style.translate = `${x}px ${y}px`;
}
}
export function useDraggableDialog() {
const offset = useRef<Position>({ x: 0, y: 0 });
const dragStart = useRef<Position | null>(null);
const initialOffset = useRef<Position>({ x: 0, y: 0 });
const contentRef = useRef<HTMLElement | null>(null);
const onPointerDown = useCallback((e: React.PointerEvent<HTMLElement>) => {
if (e.button !== 0) return;
dragStart.current = { x: e.clientX, y: e.clientY };
initialOffset.current = { x: offset.current.x, y: offset.current.y };
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
}, []);
const onPointerMove = useCallback((e: React.PointerEvent<HTMLElement>) => {
if (!dragStart.current || !contentRef.current) return;
const dx = e.clientX - dragStart.current.x;
const dy = e.clientY - dragStart.current.y;
const rawX = initialOffset.current.x + dx;
const rawY = initialOffset.current.y + dy;
const el = contentRef.current;
const clamped = clampPosition(rawX, rawY, el.offsetWidth, el.offsetHeight);
offset.current = clamped;
applyTranslate(el, clamped.x, clamped.y);
}, []);
const onPointerUp = useCallback((e: React.PointerEvent<HTMLElement>) => {
dragStart.current = null;
(e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
}, []);
const resetPosition = useCallback(() => {
offset.current = { x: 0, y: 0 };
if (contentRef.current) {
applyTranslate(contentRef.current, 0, 0);
}
}, []);
const dragHandleProps = {
onPointerDown,
onPointerMove,
onPointerUp,
style: { touchAction: "none" as const, cursor: "grab" },
};
const contentRefCallback = useCallback((node: HTMLElement | null) => {
contentRef.current = node;
}, []);
return {
dragHandleProps,
contentRefCallback,
resetPosition,
};
}