Calculator widget
A small interactive tool inside an answer. Sliders and exact fields drive live results, from formulas the model writes or a compute function you pass.
On this page
Sliders and exact fields on one side, live results and a breakdown on the other.
Installation
Usage
import { CalculatorWidget } from "@/components/ui/chatcn/calculator-widget"
<CalculatorWidget
title="Savings in 10 years"
inputs={[
{ name: "monthly", label: "Monthly deposit", min: 50, max: 2000, step: 50, defaultValue: 400, format: "currency" },
{ name: "rate", label: "Yearly return", min: 0, max: 10, step: 0.5, defaultValue: 5, format: "percent" },
]}
outputs={[
{ name: "total", label: "Balance", primary: true, format: "currency",
formula: "monthly * ((1 + rate / 1200) ^ 120 - 1) / (rate / 1200)" },
]}
/>Formulas reference input names and earlier outputs, with + - * / % ^, parentheses and min, max, round, floor, ceil, abs, sqrt, pow, log, exp. A small parser evaluates them: no eval, no globals. evaluateFormula is exported for tests.
Props
| Prop | Type | Notes |
|---|---|---|
inputs | CalculatorInput[] | name, label, min, max, step?, defaultValue?, format?, unit? |
outputs | CalculatorOutput[] | name, label, formula, format?, primary?, hint? |
breakdown | { label, formula }[] | Parts of a whole under the results |
compute | (values) => values | Compute in code. Wins over formulas for the keys it returns |
values, defaultValues, onValuesChange | Controlled or uncontrolled | |
onSubmit, submitLabel | Sends the numbers back to the agent | |
currency, locale |
Keyboard
| Key | Action |
|---|---|
Arrow keys | Step a slider, or the number field next to it |
Page Up / Page Down | Larger slider steps |
Home / End | Slider minimum or maximum |
Enter | Commit a typed value. It snaps to the step and range |
Escape | Discard a typed value |
Accessibility
- Sliders are native range inputs under a drawn track, so screen readers, touch and RTL behave natively. Each reads its formatted value.
- The headline result is announced once the user stops adjusting, not on every step.
Motion
- The thumb grows slightly while dragged. Results update in place, with tabular figures so digits do not jitter.