Metric Card
An interactive analytics card with smooth morphing charts, segmented breakdowns, date range selection, and period comparison.
The Metric Card is a sophisticated analytics visualization component that displays time-series metrics with interactive features. It includes smooth chart morphing, multi-segment breakdowns, drag-to-select date ranges, keyboard navigation, and period-over-period comparisons with animated transitions.
Installation
npx @ayushmxxn/shadcn add metric-cardCopy and paste the component source into your project.
File Structure
The component follows a simple structure with the main component file:
Usage
Import the component to display time-series metrics with automatic demo data:
import MetricCard from "@/components/craft-blocks/cards/metric-card/metric-card";
export default function AnalyticsDemo() {
return <MetricCard />;
}Custom Data
Provide your own data points with multiple segments:
const revenueData = [
{
date: "2024-01-01",
parts: [1200, 450, 180], // [Plans, Usage, Services]
},
{
date: "2024-01-02",
parts: [1250, 480, 195],
},
// ... more daily data points
];
<MetricCard
label="Revenue"
segments={["Plans", "Usage", "Services"]}
data={revenueData}
periods={[7, 30, 90]}
defaultPeriod={30}
format="currency"
currency="USD"
/>;Event Markers
Add notable events that appear as markers on the chart:
const events = [
{ date: "2024-09-15", label: "Product Launch" },
{ date: "2024-10-01", label: "New Pricing" },
];
<MetricCard
label="Users"
data={userData}
events={events}
format="number"
/>;Number Format
Display metrics as numbers instead of currency:
<MetricCard
label="Active Users"
segments={["Free", "Pro", "Enterprise"]}
data={userData}
format="number"
periods={[7, 14, 30, 90]}
/>Theming
The component uses Tailwind CSS with comprehensive theming support:
- Container: Clean card design (
rounded-3xl,border-zinc-200) - Chart Colors:
- Current period:
stroke-zinc-900(dark:stroke-zinc-100) - Previous period: Dashed line (
stroke-zinc-300) - Fill area: Semi-transparent overlay
- Current period:
- Segments: Color-coded breakdown with 4 default swatches
- Typography: Clear hierarchy with rolling number animations
- Period Pills: Smooth sliding indicator with spring easing
Customize segment colors:
const SWATCHES = [
"bg-zinc-900 dark:bg-zinc-100", // Active/focused segment
"bg-zinc-400 dark:bg-zinc-500", // Segment 1
"bg-zinc-200 dark:bg-zinc-700", // Segment 2
"bg-zinc-300 dark:bg-zinc-600", // Segment 3
];Animations
The component features multiple sophisticated animation systems:
Chart Morphing
- Shape Interpolation: Charts morph smoothly between periods and segments
- Resampling: All periods normalized to 90 points for smooth transitions
- Catmull-Rom Spline: Smooth curves through data points
- Easing: Custom ease-in-out cubic for natural motion (420ms duration)
Rolling Numbers
- Digit Wheels: Each digit animates independently on a vertical wheel
- Separators: Commas and symbols remain static
- Right-to-Left Keying: Units digit stays put when length changes
- Spring Easing: Smooth cubic bezier for natural feel
Selection Indicators
- Sliding Pill: Period selector pill slides with spring animation
- Lit Path: Chart highlights selected range with clip-path animation
- Day Markers: Dots and lines fade in/out smoothly
- Event Pins: Orange markers for notable dates
Breakdown Transitions
- Flex Growth: Bar segments transition smoothly based on values
- Opacity Fade: Non-focused segments fade to 25% opacity
- Background Highlight: Active segment gets subtle background
Motion Preferences
Respects prefers-reduced-motion to disable animations for accessibility.
How It Works
The metric card implements several advanced features:
1. Period Building
For each time period, the component:
- Extracts current period data (last N days)
- Extracts comparison period (previous N days)
- Normalizes values to 0-1 range based on min/max
- Resamples to fixed point count for morphing
function buildPeriod(data, days, focus) {
const current = data.slice(-days);
const previous = data.slice(-days * 2, -days);
// ... normalize and resample for smooth morphing
}2. Chart Morphing
When switching periods or segments:
- Starts from current visual state (not the new state)
- Interpolates point-by-point over 420ms
- Uses custom easing for natural acceleration
- Updates SVG path on every frame
3. Interactive Selection
Users can select specific dates or ranges:
- Click: Select a single day
- Drag: Create a date range
- Keyboard: Arrow keys with Shift for ranges
- Snap: Event markers pull cursor for easy targeting
4. Breakdown Calculation
The breakdown shows segment composition:
- Sums each segment across selected span
- Calculates percentages of total
- Updates on every selection change
- Focuses chart on segment when clicked
5. Delta Calculation
Compares current to previous period:
- Same selection span in previous period
- Percentage change with directional indicator
- Updates caption based on selection type
Props
Prop
Type
MetricPoint Interface
Prop
Type
MetricEvent Interface
Prop
Type
Accessibility
The component implements comprehensive accessibility features:
- Slider Role: Chart area acts as a slider for date selection
- ARIA Attributes:
aria-label: Describes the metric and interactionaria-valuemin/aria-valuemax: Date range boundsaria-valuenow: Current selected dayaria-valuetext: Human-readable selection
- Keyboard Navigation:
- Arrow Left/Right: Move by one day
- Home/End: Jump to first/last day
- Shift + Arrow: Extend range selection
- Escape: Clear selection
- Focus Management: Clear focus indicators on interactive elements
- Screen Readers: Live region announces selection changes
- Button States: Period pills use
aria-pressedfor toggle state - Segment Buttons: Clear labels for showing/hiding segments
Keyboard interaction example:
// Arrow keys walk through days
const handleKeyDown = (event) => {
if (event.key === "ArrowRight") {
// Move to next day
}
if (event.shiftKey) {
// Extend selection range
}
};Advanced Features
Magnetic Snap to Events
Event markers magnetically attract the cursor within 6 pixels for easier selection:
const SNAP_PX = 6;
const near = pinned.find(
(e) => Math.abs((e.at / last - t) * rect.width) < SNAP_PX
);Responsive Touch Handling
- Pointer Events: Unified handling for mouse, touch, and pen
- Capture: Prevents scroll during drag
- Touch-only: Hover highlights only on mouse, not touch
- Release: Clears touch selection, maintains mouse hover
Performance Optimizations
- Shape Caching: Resampled shapes cached between renders
- RAF Morphing: Uses requestAnimationFrame for 60fps transitions
- Memo Hooks: Expensive calculations memoized
- Direct DOM: Numbers and paths updated directly, bypassing React
- Cancellation: Animation cleanup on unmount
Data Requirements
The component expects data covering twice the longest period:
- If longest period is 90 days, provide 180 days of data
- This allows showing the comparison period
- Data should be continuous without gaps
- Points should be in chronological order (oldest first)
Example data generation:
const generateData = (days: number) => {
const data: MetricPoint[] = [];
const now = Date.now();
for (let i = 0; i < days; i++) {
const date = new Date(now - (days - i - 1) * 86400000);
data.push({
date: date.toISOString().slice(0, 10),
parts: [
Math.round(1000 + Math.random() * 200),
Math.round(400 + Math.random() * 100),
Math.round(150 + Math.random() * 50),
],
});
}
return data;
};Registry Bundle
This component is available as a registry bundle and can be installed with a single command. The bundle includes all necessary dependencies and configurations.
Contact
If you have any questions or need assistance with this component, please don't hesitate to reach out via email.
Last updated on
Liquid GaugeNew
An interactive liquid-filled gauge with realistic physics simulation, including wave dynamics, bubbles, and smooth animations.
Momentum RailNew
A card rail you flick with the mouse — release velocity snaps to the nearest card, scroll position drives cover-flow depth and image parallax with CSS scroll-driven animations.