refactor: refactor units tool to match calculate blueprint

Rewrites all three units components to use the same glass panel
layout, lg:grid-cols-5 two-panel split, and interactive patterns
established by the calculate tool.

- MainConverter: category sidebar (left 2/5) replaces Select dropdown;
  converter card + scrollable conversion grid (right 3/5); mobile
  'Category | Convert' tab switcher; clickable conversion cards set
  target unit; glass Grid/Chart toggle
- SearchUnits: native input with glass border, glass dropdown panel,
  compact result rows matching font selector style
- VisualComparison: polished gradient bars, tighter spacing, cleaner
  value display; all drag logic preserved

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-01 07:57:29 +01:00
parent 141ab1f4e3
commit 7eb28851b7
3 changed files with 377 additions and 400 deletions

View File

@@ -1,11 +1,7 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { ArrowLeftRight, BarChart3 } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { ArrowLeftRight, BarChart3, Grid3X3 } from 'lucide-react';
import {
Select,
SelectContent,
@@ -15,7 +11,6 @@ import {
} from '@/components/ui/select';
import SearchUnits from './SearchUnits';
import VisualComparison from './VisualComparison';
import {
getAllMeasures,
getUnitsForMeasure,
@@ -27,211 +22,313 @@ import {
} from '@/lib/units/units';
import { parseNumberInput, formatNumber, cn } from '@/lib/utils';
type Tab = 'category' | 'convert';
const CATEGORY_ICONS: Partial<Record<Measure, string>> = {
length: '📏', mass: '⚖️', temperature: '🌡️', speed: '⚡', time: '⏱️',
area: '⬛', volume: '🧊', digital: '💾', energy: '⚡', pressure: '🔵',
power: '🔆', frequency: '〰️', angle: '📐', current: '⚡', voltage: '🔌',
};
export default function MainConverter() {
const [selectedMeasure, setSelectedMeasure] = useState<Measure>('length');
const [selectedUnit, setSelectedUnit] = useState<string>('m');
const [targetUnit, setTargetUnit] = useState<string>('ft');
const [inputValue, setInputValue] = useState<string>('1');
const [conversions, setConversions] = useState<ConversionResult[]>([]);
const [showVisualComparison, setShowVisualComparison] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const [showChart, setShowChart] = useState(false);
const [tab, setTab] = useState<Tab>('category');
const measures = getAllMeasures();
const units = getUnitsForMeasure(selectedMeasure);
// Update conversions when input changes
useEffect(() => {
const numValue = parseNumberInput(inputValue);
if (numValue !== null && selectedUnit) {
const results = convertToAll(numValue, selectedUnit);
setConversions(results);
setConversions(convertToAll(numValue, selectedUnit));
} else {
setConversions([]);
}
}, [inputValue, selectedUnit]);
// Update selected unit when measure changes
useEffect(() => {
const availableUnits = getUnitsForMeasure(selectedMeasure);
if (availableUnits.length > 0) {
setSelectedUnit(availableUnits[0]);
setTargetUnit(availableUnits[1] || availableUnits[0]);
setTargetUnit(availableUnits[1] ?? availableUnits[0]);
}
}, [selectedMeasure]);
// Swap units
const handleSwapUnits = useCallback(() => {
const temp = selectedUnit;
setSelectedUnit(targetUnit);
setTargetUnit(temp);
// Convert the value
const numValue = parseNumberInput(inputValue);
if (numValue !== null) {
const converted = convertUnit(numValue, selectedUnit, targetUnit);
setInputValue(converted.toString());
setInputValue(convertUnit(numValue, selectedUnit, targetUnit).toString());
}
setSelectedUnit(targetUnit);
setTargetUnit(selectedUnit);
}, [selectedUnit, targetUnit, inputValue]);
// Handle search selection
const handleSearchSelect = useCallback((unit: string, measure: Measure) => {
setSelectedMeasure(measure);
setSelectedUnit(unit);
setTab('convert');
}, []);
// Handle value change from draggable bars
const handleValueChange = useCallback((value: number, unit: string, dragging: boolean) => {
setIsDragging(dragging);
const handleCategorySelect = useCallback((measure: Measure) => {
setSelectedMeasure(measure);
setTab('convert');
}, []);
// Convert the dragged unit's value back to the currently selected unit
// This keeps the source unit stable while updating the value
const convertedValue = convertUnit(value, unit, selectedUnit);
setInputValue(convertedValue.toString());
// Keep selectedUnit unchanged
}, [selectedUnit]);
const handleValueChange = useCallback(
(value: number, unit: string, _dragging: boolean) => {
setInputValue(convertUnit(value, unit, selectedUnit).toString());
},
[selectedUnit]
);
const resultValue = (() => {
const n = parseNumberInput(inputValue);
return n !== null ? convertUnit(n, selectedUnit, targetUnit) : null;
})();
return (
<div className="w-full space-y-6">
<div className="flex flex-col gap-4">
{/* Quick Access Row */}
<Card>
<CardContent className="flex flex-col md:flex-row md:items-center gap-3 justify-between">
<div className="flex-1">
{/* ── Mobile tab switcher ────────────────────────────────── */}
<div className="flex lg:hidden glass rounded-xl p-1 gap-1">
{(['category', 'convert'] as Tab[]).map((t) => (
<button
key={t}
onClick={() => setTab(t)}
className={cn(
'flex-1 py-2.5 rounded-lg text-sm font-medium capitalize transition-all',
tab === t
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
)}
>
{t === 'category' ? 'Category' : 'Convert'}
</button>
))}
</div>
{/* ── Main layout ────────────────────────────────────────── */}
<div
className="grid grid-cols-1 lg:grid-cols-5 gap-4"
style={{ height: 'calc(100svh - 220px)', minHeight: '620px' }}
>
{/* Left panel: search + categories */}
<div
className={cn(
'lg:col-span-2 flex flex-col gap-3 overflow-hidden',
tab !== 'category' && 'hidden lg:flex'
)}
>
{/* Search */}
<div className="glass rounded-xl p-4 shrink-0">
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest block mb-2">
Search
</span>
<SearchUnits onSelectUnit={handleSearchSelect} />
</div>
<div className="w-full md:w-56 shrink-0">
<Select
value={selectedMeasure}
onValueChange={(value) => setSelectedMeasure(value as Measure)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Measure" />
</SelectTrigger>
<SelectContent>
{measures.map((measure) => (
<SelectItem key={measure} value={measure}>
{formatMeasureName(measure)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
{/* Main Converter Card */}
<Card>
<CardHeader>
<CardTitle>Convert {formatMeasureName(selectedMeasure)}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex flex-col gap-3 md:flex-row md:items-end md:gap-2">
<div className="flex-1 w-full">
<Label className="text-xs mb-1.5">Value</Label>
<Input
{/* Category list */}
<div className="glass rounded-xl p-3 flex flex-col flex-1 min-h-0 overflow-hidden">
<div className="flex items-center justify-between mb-3 shrink-0">
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
Categories
</span>
<span className="text-[10px] text-muted-foreground/35 font-mono tabular-nums">
{measures.length}
</span>
</div>
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin scrollbar-thumb-primary/20 scrollbar-track-transparent space-y-0.5 pr-0.5">
{measures.map((measure) => {
const isSelected = selectedMeasure === measure;
const unitCount = getUnitsForMeasure(measure).length;
return (
<button
key={measure}
onClick={() => handleCategorySelect(measure)}
className={cn(
'w-full flex items-center gap-2 px-2 py-1.5 rounded-lg transition-all text-left',
'border-l-2',
isSelected
? 'bg-primary/10 border-primary text-primary'
: 'border-transparent text-foreground/65 hover:bg-primary/8 hover:text-foreground'
)}
>
<span className="text-xs leading-none shrink-0 opacity-70">
{CATEGORY_ICONS[measure] ?? '📦'}
</span>
<span className="flex-1 text-xs font-mono truncate">{formatMeasureName(measure)}</span>
<span
className={cn(
'text-[10px] font-mono tabular-nums shrink-0 px-1.5 py-0.5 rounded',
isSelected
? 'bg-primary/20 text-primary'
: 'bg-muted/40 text-muted-foreground/40'
)}
>
{unitCount}
</span>
</button>
);
})}
</div>
</div>
</div>
{/* Right panel: converter + results */}
<div
className={cn(
'lg:col-span-3 flex flex-col gap-3 overflow-hidden',
tab !== 'convert' && 'hidden lg:flex'
)}
>
{/* Converter card */}
<div className="glass rounded-xl p-4 shrink-0">
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest block mb-3">
Convert {formatMeasureName(selectedMeasure)}
</span>
{/* Input row */}
<div className="flex items-center gap-2">
{/* Value input */}
<input
type="text"
inputMode="decimal"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Enter value"
className={cn("text-lg", "w-full", "max-w-full")}
placeholder="0"
className="flex-1 min-w-0 bg-transparent border border-border/40 rounded-lg px-3 py-2 text-sm font-mono outline-none focus:border-primary/50 transition-colors placeholder:text-muted-foreground/30 tabular-nums"
/>
</div>
<div className="w-full md:w-36">
<Label className="text-xs mb-1.5">From</Label>
<Select
value={selectedUnit}
onValueChange={(value) => setSelectedUnit(value)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="From" />
{/* From unit */}
<Select value={selectedUnit} onValueChange={setSelectedUnit}>
<SelectTrigger className="w-28 h-9 shrink-0 text-xs border-border/30 bg-transparent hover:border-primary/30 transition-colors font-mono">
<SelectValue />
</SelectTrigger>
<SelectContent>
{units.map((unit) => (
<SelectItem key={unit} value={unit}>
<SelectItem key={unit} value={unit} className="font-mono text-xs">
{unit}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button
variant="outline"
size="icon"
{/* Swap */}
<button
onClick={handleSwapUnits}
className="shrink-0 w-full md:w-7"
title="Swap units"
className="shrink-0 w-8 h-8 flex items-center justify-center glass rounded-lg border border-border/30 text-muted-foreground hover:text-primary hover:border-primary/30 hover:bg-primary/10 transition-all"
>
<ArrowLeftRight className="h-3.5 w-3.5" />
</Button>
<div className="w-full md:w-36">
<Label className="text-xs mb-1.5">To</Label>
<Select
value={targetUnit}
onValueChange={(value) => setTargetUnit(value)}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="To" />
<ArrowLeftRight className="w-3.5 h-3.5" />
</button>
{/* To unit */}
<Select value={targetUnit} onValueChange={setTargetUnit}>
<SelectTrigger className="w-28 h-9 shrink-0 text-xs border-border/30 bg-transparent hover:border-primary/30 transition-colors font-mono">
<SelectValue />
</SelectTrigger>
<SelectContent>
{units.map((unit) => (
<SelectItem key={unit} value={unit}>
<SelectItem key={unit} value={unit} className="font-mono text-xs">
{unit}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{parseNumberInput(inputValue) !== null && (
<div className="p-3 rounded-lg bg-primary/5 border border-primary/15">
<div className="text-xs text-muted-foreground mb-0.5">Result</div>
<div className="text-2xl font-bold text-primary tabular-nums">
{formatNumber(convertUnit(parseNumberInput(inputValue)!, selectedUnit, targetUnit))} <span className="text-base font-medium text-muted-foreground">{targetUnit}</span>
{/* Result display */}
{resultValue !== null && (
<div className="mt-3 px-3 py-2.5 rounded-lg bg-primary/5 border border-primary/15">
<div className="text-[10px] text-muted-foreground/50 font-mono mb-0.5">Result</div>
<div className="flex items-baseline gap-2">
<span className="text-xl font-bold tabular-nums font-mono bg-gradient-to-r from-primary to-pink-400 bg-clip-text text-transparent">
{formatNumber(resultValue)}
</span>
<span className="text-sm text-muted-foreground/60 font-mono">{targetUnit}</span>
</div>
</div>
)}
</CardContent>
</Card>
{/* Results */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>All Conversions</CardTitle>
<Button
variant="outline"
size="xs"
onClick={() => setShowVisualComparison(!showVisualComparison)}
>
<BarChart3 className="h-3 w-3 mr-1" />
{showVisualComparison ? 'Grid' : 'Chart'}
</Button>
</div>
</CardHeader>
<CardContent>
{showVisualComparison ? (
<VisualComparison
conversions={conversions}
onValueChange={handleValueChange}
/>
{/* All conversions */}
<div className="glass rounded-xl p-3 flex flex-col flex-1 min-h-0 overflow-hidden">
<div className="flex items-center justify-between mb-3 shrink-0">
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
All Conversions
</span>
{/* Grid / Chart toggle */}
<div className="flex glass rounded-lg p-0.5 gap-0.5">
<button
onClick={() => setShowChart(false)}
title="Grid view"
className={cn(
'flex items-center gap-1 px-2 py-1 rounded-md text-xs transition-all',
!showChart
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
)}
>
<Grid3X3 className="w-3 h-3" />
</button>
<button
onClick={() => setShowChart(true)}
title="Chart view"
className={cn(
'flex items-center gap-1 px-2 py-1 rounded-md text-xs transition-all',
showChart
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
)}
>
<BarChart3 className="w-3 h-3" />
</button>
</div>
</div>
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin scrollbar-thumb-primary/20 scrollbar-track-transparent pr-0.5">
{showChart ? (
<VisualComparison conversions={conversions} onValueChange={handleValueChange} />
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
{conversions.map((conversion) => (
<div
<div className="grid grid-cols-2 lg:grid-cols-3 gap-2">
{conversions.map((conversion) => {
const isTarget = targetUnit === conversion.unit;
return (
<button
key={conversion.unit}
className="p-3 rounded-lg border border-border/50 hover:border-primary/30 transition-colors"
onClick={() => setTargetUnit(conversion.unit)}
className={cn(
'p-2.5 rounded-lg border text-left transition-all',
isTarget
? 'border-primary/50 bg-primary/10 text-primary'
: 'border-border/30 hover:border-primary/30 hover:bg-primary/6 text-foreground/75'
)}
>
<div className="text-xs text-muted-foreground">{conversion.unitInfo.plural}</div>
<div className="text-lg font-bold tabular-nums mt-0.5">{formatNumber(conversion.value)}</div>
<div className="text-xs text-muted-foreground">{conversion.unit}</div>
<div className="text-[10px] text-muted-foreground/50 font-mono truncate mb-0.5">
{conversion.unitInfo.plural}
</div>
))}
<div className="text-sm font-bold tabular-nums font-mono leading-none">
{formatNumber(conversion.value)}
</div>
<div className="text-[10px] text-muted-foreground/40 font-mono mt-0.5">
{conversion.unit}
</div>
</button>
);
})}
</div>
)}
</CardContent>
</Card>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -3,8 +3,6 @@
import { useState, useEffect, useRef } from 'react';
import { Search, X } from 'lucide-react';
import Fuse from 'fuse.js';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
getAllMeasures,
getUnitsForMeasure,
@@ -31,30 +29,17 @@ export default function SearchUnits({ onSelectUnit, className }: SearchUnitsProp
const [isOpen, setIsOpen] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
// Build search index
const searchIndex = useRef<Fuse<SearchResult> | null>(null);
useEffect(() => {
// Build comprehensive search data
const allData: SearchResult[] = [];
const measures = getAllMeasures();
for (const measure of measures) {
const units = getUnitsForMeasure(measure);
for (const unit of units) {
for (const unit of getUnitsForMeasure(measure)) {
const unitInfo = getUnitInfo(unit);
if (unitInfo) {
allData.push({
unitInfo,
measure,
});
if (unitInfo) allData.push({ unitInfo, measure });
}
}
}
// Initialize Fuse.js for fuzzy search
searchIndex.current = new Fuse(allData, {
keys: [
{ name: 'unitInfo.abbr', weight: 2 },
@@ -67,30 +52,22 @@ export default function SearchUnits({ onSelectUnit, className }: SearchUnitsProp
});
}, []);
// Perform search
useEffect(() => {
if (!query.trim() || !searchIndex.current) {
setResults([]);
setIsOpen(false);
return;
}
const searchResults = searchIndex.current.search(query);
setResults(searchResults.map(r => r.item).slice(0, 10));
setResults(searchIndex.current.search(query).map((r) => r.item).slice(0, 10));
setIsOpen(true);
}, [query]);
// Handle click outside
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (
containerRef.current &&
!containerRef.current.contains(event.target as Node)
) {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
@@ -102,67 +79,60 @@ export default function SearchUnits({ onSelectUnit, className }: SearchUnitsProp
inputRef.current?.blur();
};
const clearSearch = () => {
setQuery('');
setIsOpen(false);
};
return (
<div ref={containerRef} className={cn("relative w-full", className)}>
<div ref={containerRef} className={cn('relative w-full', className)}>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground/40 pointer-events-none" />
<input
ref={inputRef}
type="text"
placeholder="Search units..."
placeholder="Search all units"
value={query}
onChange={(e) => setQuery(e.target.value)}
onFocus={() => query && setIsOpen(true)}
className="pl-10 pr-10"
className="w-full bg-transparent border border-border/40 rounded-lg pl-8 pr-7 py-1.5 text-xs font-mono outline-none focus:border-primary/50 transition-colors placeholder:text-muted-foreground/30"
/>
{query && (
<Button
variant="ghost"
size="icon"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8"
onClick={clearSearch}
<button
onClick={() => { setQuery(''); setIsOpen(false); }}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground/40 hover:text-muted-foreground transition-colors"
>
<X className="h-4 w-4" />
</Button>
<X className="w-3 h-3" />
</button>
)}
</div>
{/* Results dropdown */}
{isOpen && results.length > 0 && (
<div className="absolute z-50 w-full mt-2 bg-popover border rounded-lg shadow-lg max-h-80 overflow-y-auto scrollbar">
<div className="absolute z-50 w-full mt-1.5 glass border border-border/40 rounded-xl shadow-xl max-h-72 overflow-y-auto scrollbar-thin scrollbar-thumb-primary/20 scrollbar-track-transparent">
{results.map((result, index) => (
<button
key={`${result.measure}-${result.unitInfo.abbr}`}
onClick={() => handleSelectUnit(result.unitInfo.abbr, result.measure)}
className={cn(
'w-full px-4 py-3 text-left hover:bg-accent transition-colors',
'flex items-center justify-between gap-4',
index !== 0 && 'border-t'
'w-full px-3 py-2.5 text-left hover:bg-primary/8 hover:text-foreground transition-colors',
'flex items-center justify-between gap-3',
index !== 0 && 'border-t border-border/20'
)}
>
<div className="flex-1 min-w-0">
<div className="font-medium truncate">
{result.unitInfo.plural}
</div>
<div className="text-sm text-muted-foreground flex items-center gap-2">
<span className="truncate">{result.unitInfo.abbr}</span>
<span></span>
<span className="truncate">{formatMeasureName(result.measure)}</span>
<div className="text-xs font-medium font-mono truncate">{result.unitInfo.plural}</div>
<div className="text-[10px] text-muted-foreground/50 flex items-center gap-1.5 mt-0.5">
<span className="font-mono">{result.unitInfo.abbr}</span>
<span>·</span>
<span>{formatMeasureName(result.measure)}</span>
</div>
</div>
<span className="text-[10px] text-muted-foreground/30 font-mono shrink-0">
{result.measure}
</span>
</button>
))}
</div>
)}
{isOpen && query && results.length === 0 && (
<div className="absolute z-50 w-full mt-2 bg-popover border rounded-lg shadow-lg p-4 text-center text-muted-foreground">
No units found for &quot;{query}&quot;
<div className="absolute z-50 w-full mt-1.5 glass border border-border/40 rounded-xl p-4 text-center">
<p className="text-xs text-muted-foreground/40 font-mono italic">No units found for &quot;{query}&quot;</p>
</div>
)}
</div>

View File

@@ -9,10 +9,7 @@ interface VisualComparisonProps {
onValueChange?: (value: number, unit: string, dragging: boolean) => void;
}
export default function VisualComparison({
conversions,
onValueChange,
}: VisualComparisonProps) {
export default function VisualComparison({ conversions, onValueChange }: VisualComparisonProps) {
const [draggingUnit, setDraggingUnit] = useState<string | null>(null);
const [draggedPercentage, setDraggedPercentage] = useState<number | null>(null);
const dragStartX = useRef<number>(0);
@@ -20,197 +17,130 @@ export default function VisualComparison({
const activeBarRef = useRef<HTMLDivElement | null>(null);
const lastUpdateTime = useRef<number>(0);
const baseConversionsRef = useRef<ConversionResult[]>([]);
// Calculate percentages for visual bars using logarithmic scale
const withPercentages = useMemo(() => {
if (conversions.length === 0) return [];
// Use base conversions for scale if we're dragging (keeps scale stable)
const scaleSource = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
// Get all values from the SCALE SOURCE (not current conversions)
const values = scaleSource.map(c => Math.abs(c.value));
const values = scaleSource.map((c) => Math.abs(c.value));
const maxValue = Math.max(...values);
const minValue = Math.min(...values.filter(v => v > 0));
const minValue = Math.min(...values.filter((v) => v > 0));
if (maxValue === 0 || !isFinite(maxValue)) {
return conversions.map(c => ({ ...c, percentage: 0 }));
return conversions.map((c) => ({ ...c, percentage: 0 }));
}
// Use logarithmic scale for better visualization
return conversions.map(c => {
return conversions.map((c) => {
const absValue = Math.abs(c.value);
if (absValue === 0 || !isFinite(absValue)) {
return { ...c, percentage: 2 }; // Show minimal bar
}
// Logarithmic scale
if (absValue === 0 || !isFinite(absValue)) return { ...c, percentage: 2 };
const logValue = Math.log10(absValue);
const logMax = Math.log10(maxValue);
const logMin = minValue > 0 ? Math.log10(minValue) : logMax - 6; // 6 orders of magnitude range
const logRange = logMax - logMin;
let percentage: number;
if (logRange === 0) {
percentage = 100;
} else {
percentage = ((logValue - logMin) / logRange) * 100;
// Ensure bars are visible - minimum 3%, maximum 100%
percentage = Math.max(3, Math.min(100, percentage));
}
return {
...c,
percentage,
};
});
}, [conversions]);
// Calculate value from percentage (reverse logarithmic scale)
const calculateValueFromPercentage = useCallback((
percentage: number,
minValue: number,
maxValue: number
): number => {
const logMax = Math.log10(maxValue);
const logMin = minValue > 0 ? Math.log10(minValue) : logMax - 6;
const logRange = logMax - logMin;
const percentage =
logRange === 0
? 100
: Math.max(3, Math.min(100, ((logValue - logMin) / logRange) * 100));
return { ...c, percentage };
});
}, [conversions]);
// Convert percentage back to log value
const logValue = logMin + (percentage / 100) * logRange;
// Convert log value back to actual value
return Math.pow(10, logValue);
}, []);
const calculateValueFromPercentage = useCallback(
(percentage: number, minValue: number, maxValue: number): number => {
const logMax = Math.log10(maxValue);
const logMin = minValue > 0 ? Math.log10(minValue) : logMax - 6;
return Math.pow(10, logMin + (percentage / 100) * (logMax - logMin));
},
[]
);
// Mouse drag handlers
const handleMouseDown = useCallback((e: React.MouseEvent, unit: string, currentPercentage: number, barElement: HTMLDivElement) => {
const handleMouseDown = useCallback(
(e: React.MouseEvent, unit: string, currentPercentage: number, barElement: HTMLDivElement) => {
if (!onValueChange) return;
e.preventDefault();
setDraggingUnit(unit);
setDraggedPercentage(currentPercentage);
dragStartX.current = e.clientX;
dragStartWidth.current = currentPercentage;
activeBarRef.current = barElement;
// Save the current conversions as reference
baseConversionsRef.current = [...conversions];
}, [onValueChange, conversions]);
},
[onValueChange, conversions]
);
const handleMouseMove = useCallback((e: MouseEvent) => {
const handleMouseMove = useCallback(
(e: MouseEvent) => {
if (!draggingUnit || !activeBarRef.current || !onValueChange) return;
// Throttle updates to every 16ms (~60fps)
const now = Date.now();
if (now - lastUpdateTime.current < 16) return;
lastUpdateTime.current = now;
const barWidth = activeBarRef.current.offsetWidth;
const deltaX = e.clientX - dragStartX.current;
const deltaPercentage = (deltaX / barWidth) * 100;
let newPercentage = dragStartWidth.current + deltaPercentage;
newPercentage = Math.max(3, Math.min(100, newPercentage));
// Update visual percentage immediately
const deltaPercentage = ((e.clientX - dragStartX.current) / activeBarRef.current.offsetWidth) * 100;
const newPercentage = Math.max(3, Math.min(100, dragStartWidth.current + deltaPercentage));
setDraggedPercentage(newPercentage);
// Use the base conversions (from when drag started) for scale calculation
const baseConversions = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
// Calculate min/max values for the scale from BASE conversions
const values = baseConversions.map(c => Math.abs(c.value));
const maxValue = Math.max(...values);
const minValue = Math.min(...values.filter(v => v > 0));
// Calculate new value from percentage
const newValue = calculateValueFromPercentage(newPercentage, minValue, maxValue);
onValueChange(newValue, draggingUnit, true); // true = currently dragging
}, [draggingUnit, conversions, onValueChange, calculateValueFromPercentage]);
const base = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
const vals = base.map((c) => Math.abs(c.value));
const newValue = calculateValueFromPercentage(newPercentage, Math.min(...vals.filter((v) => v > 0)), Math.max(...vals));
onValueChange(newValue, draggingUnit, true);
},
[draggingUnit, conversions, onValueChange, calculateValueFromPercentage]
);
const handleMouseUp = useCallback(() => {
if (draggingUnit && onValueChange) {
// Find the current value for the dragged unit
const conversion = conversions.find(c => c.unit === draggingUnit);
if (conversion) {
onValueChange(conversion.value, draggingUnit, false); // false = drag ended
}
const conversion = conversions.find((c) => c.unit === draggingUnit);
if (conversion) onValueChange(conversion.value, draggingUnit, false);
}
setDraggingUnit(null);
// Don't clear draggedPercentage yet - let it clear when conversions update
activeBarRef.current = null;
// baseConversionsRef cleared after conversions update
}, [draggingUnit, conversions, onValueChange]);
// Touch drag handlers
const handleTouchStart = useCallback((e: React.TouchEvent, unit: string, currentPercentage: number, barElement: HTMLDivElement) => {
const handleTouchStart = useCallback(
(e: React.TouchEvent, unit: string, currentPercentage: number, barElement: HTMLDivElement) => {
if (!onValueChange) return;
const touch = e.touches[0];
setDraggingUnit(unit);
setDraggedPercentage(currentPercentage);
dragStartX.current = touch.clientX;
dragStartWidth.current = currentPercentage;
activeBarRef.current = barElement;
// Save the current conversions as reference
baseConversionsRef.current = [...conversions];
}, [onValueChange, conversions]);
},
[onValueChange, conversions]
);
const handleTouchMove = useCallback((e: TouchEvent) => {
const handleTouchMove = useCallback(
(e: TouchEvent) => {
if (!draggingUnit || !activeBarRef.current || !onValueChange) return;
// Throttle updates to every 16ms (~60fps)
const now = Date.now();
if (now - lastUpdateTime.current < 16) return;
lastUpdateTime.current = now;
e.preventDefault(); // Prevent scrolling while dragging
e.preventDefault();
const touch = e.touches[0];
const barWidth = activeBarRef.current.offsetWidth;
const deltaX = touch.clientX - dragStartX.current;
const deltaPercentage = (deltaX / barWidth) * 100;
let newPercentage = dragStartWidth.current + deltaPercentage;
newPercentage = Math.max(3, Math.min(100, newPercentage));
// Update visual percentage immediately
const deltaPercentage = ((touch.clientX - dragStartX.current) / activeBarRef.current.offsetWidth) * 100;
const newPercentage = Math.max(3, Math.min(100, dragStartWidth.current + deltaPercentage));
setDraggedPercentage(newPercentage);
// Use the base conversions (from when drag started) for scale calculation
const baseConversions = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
const values = baseConversions.map(c => Math.abs(c.value));
const maxValue = Math.max(...values);
const minValue = Math.min(...values.filter(v => v > 0));
const newValue = calculateValueFromPercentage(newPercentage, minValue, maxValue);
onValueChange(newValue, draggingUnit, true); // true = currently dragging
}, [draggingUnit, conversions, onValueChange, calculateValueFromPercentage]);
const base = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
const vals = base.map((c) => Math.abs(c.value));
const newValue = calculateValueFromPercentage(newPercentage, Math.min(...vals.filter((v) => v > 0)), Math.max(...vals));
onValueChange(newValue, draggingUnit, true);
},
[draggingUnit, conversions, onValueChange, calculateValueFromPercentage]
);
const handleTouchEnd = useCallback(() => {
if (draggingUnit && onValueChange) {
// Find the current value for the dragged unit
const conversion = conversions.find(c => c.unit === draggingUnit);
if (conversion) {
onValueChange(conversion.value, draggingUnit, false); // false = drag ended
}
const conversion = conversions.find((c) => c.unit === draggingUnit);
if (conversion) onValueChange(conversion.value, draggingUnit, false);
}
setDraggingUnit(null);
// Don't clear draggedPercentage yet - let it clear when conversions update
activeBarRef.current = null;
// baseConversionsRef cleared after conversions update
}, [draggingUnit, conversions, onValueChange]);
// Add/remove global event listeners for drag
useEffect(() => {
if (draggingUnit) {
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('touchmove', handleTouchMove, { passive: false });
document.addEventListener('touchend', handleTouchEnd);
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
@@ -220,10 +150,8 @@ export default function VisualComparison({
}
}, [draggingUnit, handleMouseMove, handleMouseUp, handleTouchMove, handleTouchEnd]);
// Clear drag state when conversions update after drag ends
useEffect(() => {
if (!draggingUnit && draggedPercentage !== null) {
// Drag has ended, conversions have updated, now clear visual state
setDraggedPercentage(null);
baseConversionsRef.current = [];
}
@@ -231,75 +159,57 @@ export default function VisualComparison({
if (conversions.length === 0) {
return (
<div className="text-center py-8 text-muted-foreground">
Enter a value to see conversions
<div className="py-10 text-center">
<p className="text-xs text-muted-foreground/35 font-mono italic">Enter a value to see conversions</p>
</div>
);
}
return (
<div className="space-y-3">
{withPercentages.map(item => {
<div className="space-y-2.5">
{withPercentages.map((item) => {
const isDragging = draggingUnit === item.unit;
const isDraggable = !!onValueChange;
// Use draggedPercentage if this bar is being dragged
const displayPercentage = isDragging && draggedPercentage !== null ? draggedPercentage : item.percentage;
return (
<div key={item.unit} className="space-y-1.5">
<div className="flex items-baseline justify-between gap-4">
<span className="text-sm font-medium text-foreground min-w-0 flex-shrink">
{item.unitInfo.plural}
</span>
<span className="text-lg font-bold tabular-nums flex-shrink-0">
<div key={item.unit} className="space-y-1">
<div className="flex items-baseline justify-between gap-3">
<span className="text-[10px] text-muted-foreground/60 font-mono truncate">{item.unitInfo.plural}</span>
<span className="text-xs font-bold tabular-nums font-mono shrink-0 text-foreground/85">
{formatNumber(item.value)}
<span className="text-sm font-normal text-muted-foreground ml-1">
{item.unit}
</span>
<span className="text-[10px] font-normal text-muted-foreground/50 ml-1">{item.unit}</span>
</span>
</div>
{/* Progress bar */}
<div
className={cn(
"w-full h-8 bg-muted rounded-lg overflow-hidden border border-border relative",
"transition-all duration-200",
isDraggable && "cursor-grab active:cursor-grabbing",
isDragging && "ring-2 ring-ring ring-offset-2 ring-offset-background scale-105"
'w-full h-5 rounded-md overflow-hidden relative',
'bg-primary/6 border border-border/25',
isDraggable && 'cursor-grab active:cursor-grabbing',
isDragging && 'ring-1 ring-primary/40'
)}
onMouseDown={(e) => {
if (isDraggable && e.currentTarget instanceof HTMLDivElement) {
if (isDraggable && e.currentTarget instanceof HTMLDivElement)
handleMouseDown(e, item.unit, item.percentage, e.currentTarget);
}
}}
onTouchStart={(e) => {
if (isDraggable && e.currentTarget instanceof HTMLDivElement) {
if (isDraggable && e.currentTarget instanceof HTMLDivElement)
handleTouchStart(e, item.unit, item.percentage, e.currentTarget);
}
}}
>
{/* Colored fill */}
<div
className={cn(
"absolute inset-y-0 left-0 bg-primary",
draggingUnit ? "transition-none" : "transition-all duration-500 ease-out"
'absolute inset-y-0 left-0 rounded-sm',
draggingUnit ? 'transition-none' : 'transition-all duration-500 ease-out'
)}
style={{
width: `${displayPercentage}%`,
background: 'linear-gradient(to right, hsl(var(--primary) / 0.35), hsl(var(--primary) / 0.75))',
}}
/>
{/* Percentage label overlay */}
<div className="absolute inset-0 flex items-center px-3 text-xs font-bold pointer-events-none">
<span className="text-foreground drop-shadow-sm">
{Math.round(displayPercentage)}%
</span>
</div>
{/* Drag hint on hover */}
{isDraggable && !isDragging && (
<div className="absolute inset-0 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity bg-background/10 backdrop-blur-[1px]">
<span className="text-xs font-semibold text-foreground drop-shadow-md">
Drag to adjust
</span>
<div className="absolute inset-0 flex items-center justify-end px-2 opacity-0 hover:opacity-100 transition-opacity">
<span className="text-[9px] font-mono text-muted-foreground/40">drag</span>
</div>
)}
</div>