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:
@@ -1,11 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
import { ArrowLeftRight, BarChart3 } from 'lucide-react';
|
import { ArrowLeftRight, BarChart3, Grid3X3 } 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 {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -15,7 +11,6 @@ import {
|
|||||||
} from '@/components/ui/select';
|
} from '@/components/ui/select';
|
||||||
import SearchUnits from './SearchUnits';
|
import SearchUnits from './SearchUnits';
|
||||||
import VisualComparison from './VisualComparison';
|
import VisualComparison from './VisualComparison';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getAllMeasures,
|
getAllMeasures,
|
||||||
getUnitsForMeasure,
|
getUnitsForMeasure,
|
||||||
@@ -27,211 +22,313 @@ import {
|
|||||||
} from '@/lib/units/units';
|
} from '@/lib/units/units';
|
||||||
import { parseNumberInput, formatNumber, cn } from '@/lib/utils';
|
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() {
|
export default function MainConverter() {
|
||||||
const [selectedMeasure, setSelectedMeasure] = useState<Measure>('length');
|
const [selectedMeasure, setSelectedMeasure] = useState<Measure>('length');
|
||||||
const [selectedUnit, setSelectedUnit] = useState<string>('m');
|
const [selectedUnit, setSelectedUnit] = useState<string>('m');
|
||||||
const [targetUnit, setTargetUnit] = useState<string>('ft');
|
const [targetUnit, setTargetUnit] = useState<string>('ft');
|
||||||
const [inputValue, setInputValue] = useState<string>('1');
|
const [inputValue, setInputValue] = useState<string>('1');
|
||||||
const [conversions, setConversions] = useState<ConversionResult[]>([]);
|
const [conversions, setConversions] = useState<ConversionResult[]>([]);
|
||||||
const [showVisualComparison, setShowVisualComparison] = useState(false);
|
const [showChart, setShowChart] = useState(false);
|
||||||
const [isDragging, setIsDragging] = useState(false);
|
const [tab, setTab] = useState<Tab>('category');
|
||||||
|
|
||||||
const measures = getAllMeasures();
|
const measures = getAllMeasures();
|
||||||
const units = getUnitsForMeasure(selectedMeasure);
|
const units = getUnitsForMeasure(selectedMeasure);
|
||||||
|
|
||||||
// Update conversions when input changes
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const numValue = parseNumberInput(inputValue);
|
const numValue = parseNumberInput(inputValue);
|
||||||
if (numValue !== null && selectedUnit) {
|
if (numValue !== null && selectedUnit) {
|
||||||
const results = convertToAll(numValue, selectedUnit);
|
setConversions(convertToAll(numValue, selectedUnit));
|
||||||
setConversions(results);
|
|
||||||
} else {
|
} else {
|
||||||
setConversions([]);
|
setConversions([]);
|
||||||
}
|
}
|
||||||
}, [inputValue, selectedUnit]);
|
}, [inputValue, selectedUnit]);
|
||||||
|
|
||||||
// Update selected unit when measure changes
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const availableUnits = getUnitsForMeasure(selectedMeasure);
|
const availableUnits = getUnitsForMeasure(selectedMeasure);
|
||||||
if (availableUnits.length > 0) {
|
if (availableUnits.length > 0) {
|
||||||
setSelectedUnit(availableUnits[0]);
|
setSelectedUnit(availableUnits[0]);
|
||||||
setTargetUnit(availableUnits[1] || availableUnits[0]);
|
setTargetUnit(availableUnits[1] ?? availableUnits[0]);
|
||||||
}
|
}
|
||||||
}, [selectedMeasure]);
|
}, [selectedMeasure]);
|
||||||
|
|
||||||
// Swap units
|
|
||||||
const handleSwapUnits = useCallback(() => {
|
const handleSwapUnits = useCallback(() => {
|
||||||
const temp = selectedUnit;
|
|
||||||
setSelectedUnit(targetUnit);
|
|
||||||
setTargetUnit(temp);
|
|
||||||
|
|
||||||
// Convert the value
|
|
||||||
const numValue = parseNumberInput(inputValue);
|
const numValue = parseNumberInput(inputValue);
|
||||||
if (numValue !== null) {
|
if (numValue !== null) {
|
||||||
const converted = convertUnit(numValue, selectedUnit, targetUnit);
|
setInputValue(convertUnit(numValue, selectedUnit, targetUnit).toString());
|
||||||
setInputValue(converted.toString());
|
|
||||||
}
|
}
|
||||||
|
setSelectedUnit(targetUnit);
|
||||||
|
setTargetUnit(selectedUnit);
|
||||||
}, [selectedUnit, targetUnit, inputValue]);
|
}, [selectedUnit, targetUnit, inputValue]);
|
||||||
|
|
||||||
// Handle search selection
|
|
||||||
const handleSearchSelect = useCallback((unit: string, measure: Measure) => {
|
const handleSearchSelect = useCallback((unit: string, measure: Measure) => {
|
||||||
setSelectedMeasure(measure);
|
setSelectedMeasure(measure);
|
||||||
setSelectedUnit(unit);
|
setSelectedUnit(unit);
|
||||||
|
setTab('convert');
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Handle value change from draggable bars
|
const handleCategorySelect = useCallback((measure: Measure) => {
|
||||||
const handleValueChange = useCallback((value: number, unit: string, dragging: boolean) => {
|
setSelectedMeasure(measure);
|
||||||
setIsDragging(dragging);
|
setTab('convert');
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Convert the dragged unit's value back to the currently selected unit
|
const handleValueChange = useCallback(
|
||||||
// This keeps the source unit stable while updating the value
|
(value: number, unit: string, _dragging: boolean) => {
|
||||||
const convertedValue = convertUnit(value, unit, selectedUnit);
|
setInputValue(convertUnit(value, unit, selectedUnit).toString());
|
||||||
setInputValue(convertedValue.toString());
|
},
|
||||||
// Keep selectedUnit unchanged
|
[selectedUnit]
|
||||||
}, [selectedUnit]);
|
);
|
||||||
|
|
||||||
|
const resultValue = (() => {
|
||||||
|
const n = parseNumberInput(inputValue);
|
||||||
|
return n !== null ? convertUnit(n, selectedUnit, targetUnit) : null;
|
||||||
|
})();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full space-y-6">
|
<div className="flex flex-col gap-4">
|
||||||
|
|
||||||
{/* Quick Access Row */}
|
{/* ── Mobile tab switcher ────────────────────────────────── */}
|
||||||
<Card>
|
<div className="flex lg:hidden glass rounded-xl p-1 gap-1">
|
||||||
<CardContent className="flex flex-col md:flex-row md:items-center gap-3 justify-between">
|
{(['category', 'convert'] as Tab[]).map((t) => (
|
||||||
<div className="flex-1">
|
<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} />
|
<SearchUnits onSelectUnit={handleSearchSelect} />
|
||||||
</div>
|
</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 */}
|
{/* Category list */}
|
||||||
<Card>
|
<div className="glass rounded-xl p-3 flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||||
<CardHeader>
|
<div className="flex items-center justify-between mb-3 shrink-0">
|
||||||
<CardTitle>Convert {formatMeasureName(selectedMeasure)}</CardTitle>
|
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
|
||||||
</CardHeader>
|
Categories
|
||||||
<CardContent className="space-y-4">
|
</span>
|
||||||
<div className="flex flex-col gap-3 md:flex-row md:items-end md:gap-2">
|
<span className="text-[10px] text-muted-foreground/35 font-mono tabular-nums">
|
||||||
<div className="flex-1 w-full">
|
{measures.length}
|
||||||
<Label className="text-xs mb-1.5">Value</Label>
|
</span>
|
||||||
<Input
|
</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"
|
type="text"
|
||||||
inputMode="decimal"
|
inputMode="decimal"
|
||||||
value={inputValue}
|
value={inputValue}
|
||||||
onChange={(e) => setInputValue(e.target.value)}
|
onChange={(e) => setInputValue(e.target.value)}
|
||||||
placeholder="Enter value"
|
placeholder="0"
|
||||||
className={cn("text-lg", "w-full", "max-w-full")}
|
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">
|
{/* From unit */}
|
||||||
<Label className="text-xs mb-1.5">From</Label>
|
<Select value={selectedUnit} onValueChange={setSelectedUnit}>
|
||||||
<Select
|
<SelectTrigger className="w-28 h-9 shrink-0 text-xs border-border/30 bg-transparent hover:border-primary/30 transition-colors font-mono">
|
||||||
value={selectedUnit}
|
<SelectValue />
|
||||||
onValueChange={(value) => setSelectedUnit(value)}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="w-full">
|
|
||||||
<SelectValue placeholder="From" />
|
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{units.map((unit) => (
|
{units.map((unit) => (
|
||||||
<SelectItem key={unit} value={unit}>
|
<SelectItem key={unit} value={unit} className="font-mono text-xs">
|
||||||
{unit}
|
{unit}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
|
||||||
<Button
|
{/* Swap */}
|
||||||
variant="outline"
|
<button
|
||||||
size="icon"
|
|
||||||
onClick={handleSwapUnits}
|
onClick={handleSwapUnits}
|
||||||
className="shrink-0 w-full md:w-7"
|
|
||||||
title="Swap units"
|
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" />
|
<ArrowLeftRight className="w-3.5 h-3.5" />
|
||||||
</Button>
|
</button>
|
||||||
<div className="w-full md:w-36">
|
|
||||||
<Label className="text-xs mb-1.5">To</Label>
|
{/* To unit */}
|
||||||
<Select
|
<Select value={targetUnit} onValueChange={setTargetUnit}>
|
||||||
value={targetUnit}
|
<SelectTrigger className="w-28 h-9 shrink-0 text-xs border-border/30 bg-transparent hover:border-primary/30 transition-colors font-mono">
|
||||||
onValueChange={(value) => setTargetUnit(value)}
|
<SelectValue />
|
||||||
>
|
|
||||||
<SelectTrigger className="w-full">
|
|
||||||
<SelectValue placeholder="To" />
|
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{units.map((unit) => (
|
{units.map((unit) => (
|
||||||
<SelectItem key={unit} value={unit}>
|
<SelectItem key={unit} value={unit} className="font-mono text-xs">
|
||||||
{unit}
|
{unit}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
{parseNumberInput(inputValue) !== null && (
|
{/* Result display */}
|
||||||
<div className="p-3 rounded-lg bg-primary/5 border border-primary/15">
|
{resultValue !== null && (
|
||||||
<div className="text-xs text-muted-foreground mb-0.5">Result</div>
|
<div className="mt-3 px-3 py-2.5 rounded-lg bg-primary/5 border border-primary/15">
|
||||||
<div className="text-2xl font-bold text-primary tabular-nums">
|
<div className="text-[10px] text-muted-foreground/50 font-mono mb-0.5">Result</div>
|
||||||
{formatNumber(convertUnit(parseNumberInput(inputValue)!, selectedUnit, targetUnit))} <span className="text-base font-medium text-muted-foreground">{targetUnit}</span>
|
<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>
|
||||||
</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>
|
</div>
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
{/* All conversions */}
|
||||||
{showVisualComparison ? (
|
<div className="glass rounded-xl p-3 flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||||
<VisualComparison
|
<div className="flex items-center justify-between mb-3 shrink-0">
|
||||||
conversions={conversions}
|
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
|
||||||
onValueChange={handleValueChange}
|
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">
|
<div className="grid grid-cols-2 lg:grid-cols-3 gap-2">
|
||||||
{conversions.map((conversion) => (
|
{conversions.map((conversion) => {
|
||||||
<div
|
const isTarget = targetUnit === conversion.unit;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
key={conversion.unit}
|
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-[10px] text-muted-foreground/50 font-mono truncate mb-0.5">
|
||||||
<div className="text-lg font-bold tabular-nums mt-0.5">{formatNumber(conversion.value)}</div>
|
{conversion.unitInfo.plural}
|
||||||
<div className="text-xs text-muted-foreground">{conversion.unit}</div>
|
|
||||||
</div>
|
</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>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,6 @@
|
|||||||
import { useState, useEffect, useRef } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { Search, X } from 'lucide-react';
|
import { Search, X } from 'lucide-react';
|
||||||
import Fuse from 'fuse.js';
|
import Fuse from 'fuse.js';
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import {
|
import {
|
||||||
getAllMeasures,
|
getAllMeasures,
|
||||||
getUnitsForMeasure,
|
getUnitsForMeasure,
|
||||||
@@ -31,30 +29,17 @@ export default function SearchUnits({ onSelectUnit, className }: SearchUnitsProp
|
|||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
// Build search index
|
|
||||||
const searchIndex = useRef<Fuse<SearchResult> | null>(null);
|
const searchIndex = useRef<Fuse<SearchResult> | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Build comprehensive search data
|
|
||||||
const allData: SearchResult[] = [];
|
const allData: SearchResult[] = [];
|
||||||
const measures = getAllMeasures();
|
const measures = getAllMeasures();
|
||||||
|
|
||||||
for (const measure of measures) {
|
for (const measure of measures) {
|
||||||
const units = getUnitsForMeasure(measure);
|
for (const unit of getUnitsForMeasure(measure)) {
|
||||||
|
|
||||||
for (const unit of units) {
|
|
||||||
const unitInfo = getUnitInfo(unit);
|
const unitInfo = getUnitInfo(unit);
|
||||||
if (unitInfo) {
|
if (unitInfo) allData.push({ unitInfo, measure });
|
||||||
allData.push({
|
|
||||||
unitInfo,
|
|
||||||
measure,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize Fuse.js for fuzzy search
|
|
||||||
searchIndex.current = new Fuse(allData, {
|
searchIndex.current = new Fuse(allData, {
|
||||||
keys: [
|
keys: [
|
||||||
{ name: 'unitInfo.abbr', weight: 2 },
|
{ name: 'unitInfo.abbr', weight: 2 },
|
||||||
@@ -67,30 +52,22 @@ export default function SearchUnits({ onSelectUnit, className }: SearchUnitsProp
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Perform search
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!query.trim() || !searchIndex.current) {
|
if (!query.trim() || !searchIndex.current) {
|
||||||
setResults([]);
|
setResults([]);
|
||||||
setIsOpen(false);
|
setIsOpen(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
setResults(searchIndex.current.search(query).map((r) => r.item).slice(0, 10));
|
||||||
const searchResults = searchIndex.current.search(query);
|
|
||||||
setResults(searchResults.map(r => r.item).slice(0, 10));
|
|
||||||
setIsOpen(true);
|
setIsOpen(true);
|
||||||
}, [query]);
|
}, [query]);
|
||||||
|
|
||||||
// Handle click outside
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
function handleClickOutside(event: MouseEvent) {
|
function handleClickOutside(event: MouseEvent) {
|
||||||
if (
|
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
||||||
containerRef.current &&
|
|
||||||
!containerRef.current.contains(event.target as Node)
|
|
||||||
) {
|
|
||||||
setIsOpen(false);
|
setIsOpen(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('mousedown', handleClickOutside);
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||||
}, []);
|
}, []);
|
||||||
@@ -102,67 +79,60 @@ export default function SearchUnits({ onSelectUnit, className }: SearchUnitsProp
|
|||||||
inputRef.current?.blur();
|
inputRef.current?.blur();
|
||||||
};
|
};
|
||||||
|
|
||||||
const clearSearch = () => {
|
|
||||||
setQuery('');
|
|
||||||
setIsOpen(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={containerRef} className={cn("relative w-full", className)}>
|
<div ref={containerRef} className={cn('relative w-full', className)}>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground/40 pointer-events-none" />
|
||||||
<Input
|
<input
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Search units..."
|
placeholder="Search all units…"
|
||||||
value={query}
|
value={query}
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
onFocus={() => query && setIsOpen(true)}
|
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 && (
|
{query && (
|
||||||
<Button
|
<button
|
||||||
variant="ghost"
|
onClick={() => { setQuery(''); setIsOpen(false); }}
|
||||||
size="icon"
|
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground/40 hover:text-muted-foreground transition-colors"
|
||||||
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8"
|
|
||||||
onClick={clearSearch}
|
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="w-3 h-3" />
|
||||||
</Button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Results dropdown */}
|
|
||||||
{isOpen && results.length > 0 && (
|
{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) => (
|
{results.map((result, index) => (
|
||||||
<button
|
<button
|
||||||
key={`${result.measure}-${result.unitInfo.abbr}`}
|
key={`${result.measure}-${result.unitInfo.abbr}`}
|
||||||
onClick={() => handleSelectUnit(result.unitInfo.abbr, result.measure)}
|
onClick={() => handleSelectUnit(result.unitInfo.abbr, result.measure)}
|
||||||
className={cn(
|
className={cn(
|
||||||
'w-full px-4 py-3 text-left hover:bg-accent transition-colors',
|
'w-full px-3 py-2.5 text-left hover:bg-primary/8 hover:text-foreground transition-colors',
|
||||||
'flex items-center justify-between gap-4',
|
'flex items-center justify-between gap-3',
|
||||||
index !== 0 && 'border-t'
|
index !== 0 && 'border-t border-border/20'
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="font-medium truncate">
|
<div className="text-xs font-medium font-mono truncate">{result.unitInfo.plural}</div>
|
||||||
{result.unitInfo.plural}
|
<div className="text-[10px] text-muted-foreground/50 flex items-center gap-1.5 mt-0.5">
|
||||||
</div>
|
<span className="font-mono">{result.unitInfo.abbr}</span>
|
||||||
<div className="text-sm text-muted-foreground flex items-center gap-2">
|
<span>·</span>
|
||||||
<span className="truncate">{result.unitInfo.abbr}</span>
|
<span>{formatMeasureName(result.measure)}</span>
|
||||||
<span>•</span>
|
|
||||||
<span className="truncate">{formatMeasureName(result.measure)}</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<span className="text-[10px] text-muted-foreground/30 font-mono shrink-0">
|
||||||
|
{result.measure}
|
||||||
|
</span>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isOpen && query && results.length === 0 && (
|
{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">
|
<div className="absolute z-50 w-full mt-1.5 glass border border-border/40 rounded-xl p-4 text-center">
|
||||||
No units found for "{query}"
|
<p className="text-xs text-muted-foreground/40 font-mono italic">No units found for "{query}"</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -9,10 +9,7 @@ interface VisualComparisonProps {
|
|||||||
onValueChange?: (value: number, unit: string, dragging: boolean) => void;
|
onValueChange?: (value: number, unit: string, dragging: boolean) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function VisualComparison({
|
export default function VisualComparison({ conversions, onValueChange }: VisualComparisonProps) {
|
||||||
conversions,
|
|
||||||
onValueChange,
|
|
||||||
}: VisualComparisonProps) {
|
|
||||||
const [draggingUnit, setDraggingUnit] = useState<string | null>(null);
|
const [draggingUnit, setDraggingUnit] = useState<string | null>(null);
|
||||||
const [draggedPercentage, setDraggedPercentage] = useState<number | null>(null);
|
const [draggedPercentage, setDraggedPercentage] = useState<number | null>(null);
|
||||||
const dragStartX = useRef<number>(0);
|
const dragStartX = useRef<number>(0);
|
||||||
@@ -20,197 +17,130 @@ export default function VisualComparison({
|
|||||||
const activeBarRef = useRef<HTMLDivElement | null>(null);
|
const activeBarRef = useRef<HTMLDivElement | null>(null);
|
||||||
const lastUpdateTime = useRef<number>(0);
|
const lastUpdateTime = useRef<number>(0);
|
||||||
const baseConversionsRef = useRef<ConversionResult[]>([]);
|
const baseConversionsRef = useRef<ConversionResult[]>([]);
|
||||||
// Calculate percentages for visual bars using logarithmic scale
|
|
||||||
const withPercentages = useMemo(() => {
|
const withPercentages = useMemo(() => {
|
||||||
if (conversions.length === 0) return [];
|
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;
|
const scaleSource = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
|
||||||
|
const values = scaleSource.map((c) => Math.abs(c.value));
|
||||||
// Get all values from the SCALE SOURCE (not current conversions)
|
|
||||||
const values = scaleSource.map(c => Math.abs(c.value));
|
|
||||||
const maxValue = Math.max(...values);
|
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)) {
|
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);
|
const absValue = Math.abs(c.value);
|
||||||
|
if (absValue === 0 || !isFinite(absValue)) return { ...c, percentage: 2 };
|
||||||
if (absValue === 0 || !isFinite(absValue)) {
|
|
||||||
return { ...c, percentage: 2 }; // Show minimal bar
|
|
||||||
}
|
|
||||||
|
|
||||||
// Logarithmic scale
|
|
||||||
const logValue = Math.log10(absValue);
|
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 logMax = Math.log10(maxValue);
|
||||||
const logMin = minValue > 0 ? Math.log10(minValue) : logMax - 6;
|
const logMin = minValue > 0 ? Math.log10(minValue) : logMax - 6;
|
||||||
const logRange = logMax - logMin;
|
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 calculateValueFromPercentage = useCallback(
|
||||||
const logValue = logMin + (percentage / 100) * logRange;
|
(percentage: number, minValue: number, maxValue: number): number => {
|
||||||
// Convert log value back to actual value
|
const logMax = Math.log10(maxValue);
|
||||||
return Math.pow(10, logValue);
|
const logMin = minValue > 0 ? Math.log10(minValue) : logMax - 6;
|
||||||
}, []);
|
return Math.pow(10, logMin + (percentage / 100) * (logMax - logMin));
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
// Mouse drag handlers
|
const handleMouseDown = useCallback(
|
||||||
const handleMouseDown = useCallback((e: React.MouseEvent, unit: string, currentPercentage: number, barElement: HTMLDivElement) => {
|
(e: React.MouseEvent, unit: string, currentPercentage: number, barElement: HTMLDivElement) => {
|
||||||
if (!onValueChange) return;
|
if (!onValueChange) return;
|
||||||
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setDraggingUnit(unit);
|
setDraggingUnit(unit);
|
||||||
setDraggedPercentage(currentPercentage);
|
setDraggedPercentage(currentPercentage);
|
||||||
dragStartX.current = e.clientX;
|
dragStartX.current = e.clientX;
|
||||||
dragStartWidth.current = currentPercentage;
|
dragStartWidth.current = currentPercentage;
|
||||||
activeBarRef.current = barElement;
|
activeBarRef.current = barElement;
|
||||||
// Save the current conversions as reference
|
|
||||||
baseConversionsRef.current = [...conversions];
|
baseConversionsRef.current = [...conversions];
|
||||||
}, [onValueChange, conversions]);
|
},
|
||||||
|
[onValueChange, conversions]
|
||||||
|
);
|
||||||
|
|
||||||
const handleMouseMove = useCallback((e: MouseEvent) => {
|
const handleMouseMove = useCallback(
|
||||||
|
(e: MouseEvent) => {
|
||||||
if (!draggingUnit || !activeBarRef.current || !onValueChange) return;
|
if (!draggingUnit || !activeBarRef.current || !onValueChange) return;
|
||||||
|
|
||||||
// Throttle updates to every 16ms (~60fps)
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - lastUpdateTime.current < 16) return;
|
if (now - lastUpdateTime.current < 16) return;
|
||||||
lastUpdateTime.current = now;
|
lastUpdateTime.current = now;
|
||||||
|
const deltaPercentage = ((e.clientX - dragStartX.current) / activeBarRef.current.offsetWidth) * 100;
|
||||||
const barWidth = activeBarRef.current.offsetWidth;
|
const newPercentage = Math.max(3, Math.min(100, dragStartWidth.current + deltaPercentage));
|
||||||
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
|
|
||||||
setDraggedPercentage(newPercentage);
|
setDraggedPercentage(newPercentage);
|
||||||
|
const base = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
|
||||||
// Use the base conversions (from when drag started) for scale calculation
|
const vals = base.map((c) => Math.abs(c.value));
|
||||||
const baseConversions = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
|
const newValue = calculateValueFromPercentage(newPercentage, Math.min(...vals.filter((v) => v > 0)), Math.max(...vals));
|
||||||
|
onValueChange(newValue, draggingUnit, true);
|
||||||
// Calculate min/max values for the scale from BASE conversions
|
},
|
||||||
const values = baseConversions.map(c => Math.abs(c.value));
|
[draggingUnit, conversions, onValueChange, calculateValueFromPercentage]
|
||||||
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 handleMouseUp = useCallback(() => {
|
const handleMouseUp = useCallback(() => {
|
||||||
if (draggingUnit && onValueChange) {
|
if (draggingUnit && onValueChange) {
|
||||||
// Find the current value for the dragged unit
|
const conversion = conversions.find((c) => c.unit === draggingUnit);
|
||||||
const conversion = conversions.find(c => c.unit === draggingUnit);
|
if (conversion) onValueChange(conversion.value, draggingUnit, false);
|
||||||
if (conversion) {
|
|
||||||
onValueChange(conversion.value, draggingUnit, false); // false = drag ended
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
setDraggingUnit(null);
|
setDraggingUnit(null);
|
||||||
// Don't clear draggedPercentage yet - let it clear when conversions update
|
|
||||||
activeBarRef.current = null;
|
activeBarRef.current = null;
|
||||||
// baseConversionsRef cleared after conversions update
|
|
||||||
}, [draggingUnit, conversions, onValueChange]);
|
}, [draggingUnit, conversions, onValueChange]);
|
||||||
|
|
||||||
// Touch drag handlers
|
const handleTouchStart = useCallback(
|
||||||
const handleTouchStart = useCallback((e: React.TouchEvent, unit: string, currentPercentage: number, barElement: HTMLDivElement) => {
|
(e: React.TouchEvent, unit: string, currentPercentage: number, barElement: HTMLDivElement) => {
|
||||||
if (!onValueChange) return;
|
if (!onValueChange) return;
|
||||||
|
|
||||||
const touch = e.touches[0];
|
const touch = e.touches[0];
|
||||||
setDraggingUnit(unit);
|
setDraggingUnit(unit);
|
||||||
setDraggedPercentage(currentPercentage);
|
setDraggedPercentage(currentPercentage);
|
||||||
dragStartX.current = touch.clientX;
|
dragStartX.current = touch.clientX;
|
||||||
dragStartWidth.current = currentPercentage;
|
dragStartWidth.current = currentPercentage;
|
||||||
activeBarRef.current = barElement;
|
activeBarRef.current = barElement;
|
||||||
// Save the current conversions as reference
|
|
||||||
baseConversionsRef.current = [...conversions];
|
baseConversionsRef.current = [...conversions];
|
||||||
}, [onValueChange, conversions]);
|
},
|
||||||
|
[onValueChange, conversions]
|
||||||
|
);
|
||||||
|
|
||||||
const handleTouchMove = useCallback((e: TouchEvent) => {
|
const handleTouchMove = useCallback(
|
||||||
|
(e: TouchEvent) => {
|
||||||
if (!draggingUnit || !activeBarRef.current || !onValueChange) return;
|
if (!draggingUnit || !activeBarRef.current || !onValueChange) return;
|
||||||
|
|
||||||
// Throttle updates to every 16ms (~60fps)
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - lastUpdateTime.current < 16) return;
|
if (now - lastUpdateTime.current < 16) return;
|
||||||
lastUpdateTime.current = now;
|
lastUpdateTime.current = now;
|
||||||
|
e.preventDefault();
|
||||||
e.preventDefault(); // Prevent scrolling while dragging
|
|
||||||
const touch = e.touches[0];
|
const touch = e.touches[0];
|
||||||
const barWidth = activeBarRef.current.offsetWidth;
|
const deltaPercentage = ((touch.clientX - dragStartX.current) / activeBarRef.current.offsetWidth) * 100;
|
||||||
const deltaX = touch.clientX - dragStartX.current;
|
const newPercentage = Math.max(3, Math.min(100, dragStartWidth.current + deltaPercentage));
|
||||||
const deltaPercentage = (deltaX / barWidth) * 100;
|
|
||||||
|
|
||||||
let newPercentage = dragStartWidth.current + deltaPercentage;
|
|
||||||
newPercentage = Math.max(3, Math.min(100, newPercentage));
|
|
||||||
|
|
||||||
// Update visual percentage immediately
|
|
||||||
setDraggedPercentage(newPercentage);
|
setDraggedPercentage(newPercentage);
|
||||||
|
const base = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
|
||||||
// Use the base conversions (from when drag started) for scale calculation
|
const vals = base.map((c) => Math.abs(c.value));
|
||||||
const baseConversions = baseConversionsRef.current.length > 0 ? baseConversionsRef.current : conversions;
|
const newValue = calculateValueFromPercentage(newPercentage, Math.min(...vals.filter((v) => v > 0)), Math.max(...vals));
|
||||||
|
onValueChange(newValue, draggingUnit, true);
|
||||||
const values = baseConversions.map(c => Math.abs(c.value));
|
},
|
||||||
const maxValue = Math.max(...values);
|
[draggingUnit, conversions, onValueChange, calculateValueFromPercentage]
|
||||||
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 handleTouchEnd = useCallback(() => {
|
const handleTouchEnd = useCallback(() => {
|
||||||
if (draggingUnit && onValueChange) {
|
if (draggingUnit && onValueChange) {
|
||||||
// Find the current value for the dragged unit
|
const conversion = conversions.find((c) => c.unit === draggingUnit);
|
||||||
const conversion = conversions.find(c => c.unit === draggingUnit);
|
if (conversion) onValueChange(conversion.value, draggingUnit, false);
|
||||||
if (conversion) {
|
|
||||||
onValueChange(conversion.value, draggingUnit, false); // false = drag ended
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
setDraggingUnit(null);
|
setDraggingUnit(null);
|
||||||
// Don't clear draggedPercentage yet - let it clear when conversions update
|
|
||||||
activeBarRef.current = null;
|
activeBarRef.current = null;
|
||||||
// baseConversionsRef cleared after conversions update
|
|
||||||
}, [draggingUnit, conversions, onValueChange]);
|
}, [draggingUnit, conversions, onValueChange]);
|
||||||
|
|
||||||
// Add/remove global event listeners for drag
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (draggingUnit) {
|
if (draggingUnit) {
|
||||||
document.addEventListener('mousemove', handleMouseMove);
|
document.addEventListener('mousemove', handleMouseMove);
|
||||||
document.addEventListener('mouseup', handleMouseUp);
|
document.addEventListener('mouseup', handleMouseUp);
|
||||||
document.addEventListener('touchmove', handleTouchMove, { passive: false });
|
document.addEventListener('touchmove', handleTouchMove, { passive: false });
|
||||||
document.addEventListener('touchend', handleTouchEnd);
|
document.addEventListener('touchend', handleTouchEnd);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener('mousemove', handleMouseMove);
|
document.removeEventListener('mousemove', handleMouseMove);
|
||||||
document.removeEventListener('mouseup', handleMouseUp);
|
document.removeEventListener('mouseup', handleMouseUp);
|
||||||
@@ -220,10 +150,8 @@ export default function VisualComparison({
|
|||||||
}
|
}
|
||||||
}, [draggingUnit, handleMouseMove, handleMouseUp, handleTouchMove, handleTouchEnd]);
|
}, [draggingUnit, handleMouseMove, handleMouseUp, handleTouchMove, handleTouchEnd]);
|
||||||
|
|
||||||
// Clear drag state when conversions update after drag ends
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!draggingUnit && draggedPercentage !== null) {
|
if (!draggingUnit && draggedPercentage !== null) {
|
||||||
// Drag has ended, conversions have updated, now clear visual state
|
|
||||||
setDraggedPercentage(null);
|
setDraggedPercentage(null);
|
||||||
baseConversionsRef.current = [];
|
baseConversionsRef.current = [];
|
||||||
}
|
}
|
||||||
@@ -231,75 +159,57 @@ export default function VisualComparison({
|
|||||||
|
|
||||||
if (conversions.length === 0) {
|
if (conversions.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="text-center py-8 text-muted-foreground">
|
<div className="py-10 text-center">
|
||||||
Enter a value to see conversions
|
<p className="text-xs text-muted-foreground/35 font-mono italic">Enter a value to see conversions</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-3">
|
<div className="space-y-2.5">
|
||||||
{withPercentages.map(item => {
|
{withPercentages.map((item) => {
|
||||||
const isDragging = draggingUnit === item.unit;
|
const isDragging = draggingUnit === item.unit;
|
||||||
const isDraggable = !!onValueChange;
|
const isDraggable = !!onValueChange;
|
||||||
// Use draggedPercentage if this bar is being dragged
|
|
||||||
const displayPercentage = isDragging && draggedPercentage !== null ? draggedPercentage : item.percentage;
|
const displayPercentage = isDragging && draggedPercentage !== null ? draggedPercentage : item.percentage;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={item.unit} className="space-y-1.5">
|
<div key={item.unit} className="space-y-1">
|
||||||
<div className="flex items-baseline justify-between gap-4">
|
<div className="flex items-baseline justify-between gap-3">
|
||||||
<span className="text-sm font-medium text-foreground min-w-0 flex-shrink">
|
<span className="text-[10px] text-muted-foreground/60 font-mono truncate">{item.unitInfo.plural}</span>
|
||||||
{item.unitInfo.plural}
|
<span className="text-xs font-bold tabular-nums font-mono shrink-0 text-foreground/85">
|
||||||
</span>
|
|
||||||
<span className="text-lg font-bold tabular-nums flex-shrink-0">
|
|
||||||
{formatNumber(item.value)}
|
{formatNumber(item.value)}
|
||||||
<span className="text-sm font-normal text-muted-foreground ml-1">
|
<span className="text-[10px] font-normal text-muted-foreground/50 ml-1">{item.unit}</span>
|
||||||
{item.unit}
|
|
||||||
</span>
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{/* Progress bar */}
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"w-full h-8 bg-muted rounded-lg overflow-hidden border border-border relative",
|
'w-full h-5 rounded-md overflow-hidden relative',
|
||||||
"transition-all duration-200",
|
'bg-primary/6 border border-border/25',
|
||||||
isDraggable && "cursor-grab active:cursor-grabbing",
|
isDraggable && 'cursor-grab active:cursor-grabbing',
|
||||||
isDragging && "ring-2 ring-ring ring-offset-2 ring-offset-background scale-105"
|
isDragging && 'ring-1 ring-primary/40'
|
||||||
)}
|
)}
|
||||||
onMouseDown={(e) => {
|
onMouseDown={(e) => {
|
||||||
if (isDraggable && e.currentTarget instanceof HTMLDivElement) {
|
if (isDraggable && e.currentTarget instanceof HTMLDivElement)
|
||||||
handleMouseDown(e, item.unit, item.percentage, e.currentTarget);
|
handleMouseDown(e, item.unit, item.percentage, e.currentTarget);
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
onTouchStart={(e) => {
|
onTouchStart={(e) => {
|
||||||
if (isDraggable && e.currentTarget instanceof HTMLDivElement) {
|
if (isDraggable && e.currentTarget instanceof HTMLDivElement)
|
||||||
handleTouchStart(e, item.unit, item.percentage, e.currentTarget);
|
handleTouchStart(e, item.unit, item.percentage, e.currentTarget);
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{/* Colored fill */}
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"absolute inset-y-0 left-0 bg-primary",
|
'absolute inset-y-0 left-0 rounded-sm',
|
||||||
draggingUnit ? "transition-none" : "transition-all duration-500 ease-out"
|
draggingUnit ? 'transition-none' : 'transition-all duration-500 ease-out'
|
||||||
)}
|
)}
|
||||||
style={{
|
style={{
|
||||||
width: `${displayPercentage}%`,
|
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 && (
|
{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]">
|
<div className="absolute inset-0 flex items-center justify-end px-2 opacity-0 hover:opacity-100 transition-opacity">
|
||||||
<span className="text-xs font-semibold text-foreground drop-shadow-md">
|
<span className="text-[9px] font-mono text-muted-foreground/40">drag</span>
|
||||||
Drag to adjust
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user