1"use client";
2
3import { Slot as SlotPrimitive } from "radix-ui";
4import * as React from "react";
5import { cn } from "@/lib/utils";
6
7const GAUGE_NAME = "Gauge";
8const INDICATOR_NAME = "GaugeIndicator";
9const TRACK_NAME = "GaugeTrack";
10const RANGE_NAME = "GaugeRange";
11const VALUE_TEXT_NAME = "GaugeValueText";
12const LABEL_NAME = "GaugeLabel";
13
14const DEFAULT_MAX = 100;
15const DEFAULT_START_ANGLE = 0;
16const DEFAULT_END_ANGLE = 360;
17
18type GaugeState = "indeterminate" | "complete" | "loading";
19
20interface DivProps extends React.ComponentProps<"div"> {
21 asChild?: boolean;
22}
23
24interface PathProps extends React.ComponentProps<"path"> {}
25
26function getGaugeState(
27 value: number | undefined | null,
28 maxValue: number,
29): GaugeState {
30 return value == null
31 ? "indeterminate"
32 : value === maxValue
33 ? "complete"
34 : "loading";
35}
36
37function getIsValidNumber(value: unknown): value is number {
38 return typeof value === "number" && Number.isFinite(value);
39}
40
41function getIsValidMaxNumber(max: unknown): max is number {
42 return getIsValidNumber(max) && max > 0;
43}
44
45function getIsValidValueNumber(
46 value: unknown,
47 min: number,
48 max: number,
49): value is number {
50 return getIsValidNumber(value) && value <= max && value >= min;
51}
52
53function getDefaultValueText(value: number, min: number, max: number): string {
54 const percentage = max === min ? 100 : ((value - min) / (max - min)) * 100;
55 return Math.round(percentage).toString();
56}
57
58function getInvalidValueError(
59 propValue: string,
60 componentName: string,
61): string {
62 return `Invalid prop \`value\` of value \`${propValue}\` supplied to \`${componentName}\`. The \`value\` prop must be a number between \`min\` and \`max\` (inclusive), or \`null\`/\`undefined\` for indeterminate state. The value will be clamped to the valid range.`;
63}
64
65function getInvalidMaxError(propValue: string, componentName: string): string {
66 return `Invalid prop \`max\` of value \`${propValue}\` supplied to \`${componentName}\`. Only numbers greater than 0 are valid. Defaulting to ${DEFAULT_MAX}.`;
67}
68
69function getNormalizedAngle(angle: number) {
70 return ((angle % 360) + 360) % 360;
71}
72
73function polarToCartesian(
74 centerX: number,
75 centerY: number,
76 radius: number,
77 angleInDegrees: number,
78) {
79 const angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0;
80 return {
81 x: centerX + radius * Math.cos(angleInRadians),
82 y: centerY + radius * Math.sin(angleInRadians),
83 };
84}
85
86function describeArc(
87 x: number,
88 y: number,
89 radius: number,
90 startAngle: number,
91 endAngle: number,
92) {
93 const angleDiff = endAngle - startAngle;
94
95 // For full circles (360 degrees), draw as two semi-circles
96 if (Math.abs(angleDiff) >= 360) {
97 const start = polarToCartesian(x, y, radius, startAngle);
98 const mid = polarToCartesian(x, y, radius, startAngle + 180);
99 return [
100 "M",
101 start.x,
102 start.y,
103 "A",
104 radius,
105 radius,
106 0,
107 0,
108 1,
109 mid.x,
110 mid.y,
111 "A",
112 radius,
113 radius,
114 0,
115 0,
116 1,
117 start.x,
118 start.y,
119 ].join(" ");
120 }
121
122 const start = polarToCartesian(x, y, radius, startAngle);
123 const end = polarToCartesian(x, y, radius, endAngle);
124 const largeArcFlag = angleDiff <= 180 ? "0" : "1";
125
126 return [
127 "M",
128 start.x,
129 start.y,
130 "A",
131 radius,
132 radius,
133 0,
134 largeArcFlag,
135 1,
136 end.x,
137 end.y,
138 ].join(" ");
139}
140
141interface GaugeContextValue {
142 value: number | null;
143 valueText: string | undefined;
144 max: number;
145 min: number;
146 state: GaugeState;
147 radius: number;
148 thickness: number;
149 size: number;
150 center: number;
151 percentage: number | null;
152 startAngle: number;
153 endAngle: number;
154 arcLength: number;
155 arcCenterY: number;
156 valueTextId?: string;
157 labelId?: string;
158}
159
160const GaugeContext = React.createContext<GaugeContextValue | null>(null);
161
162function useGaugeContext(consumerName: string) {
163 const context = React.useContext(GaugeContext);
164 if (!context) {
165 throw new Error(
166 `\`${consumerName}\` must be used within \`${GAUGE_NAME}\``,
167 );
168 }
169 return context;
170}
171
172interface GaugeProps extends DivProps {
173 value?: number | null | undefined;
174 getValueText?(value: number, min: number, max: number): string;
175 min?: number;
176 max?: number;
177 size?: number;
178 thickness?: number;
179 startAngle?: number;
180 endAngle?: number;
181}
182
183function Gauge(props: GaugeProps) {
184 const {
185 value: valueProp = null,
186 getValueText = getDefaultValueText,
187 min: minProp = 0,
188 max: maxProp,
189 size = 120,
190 thickness = 8,
191 startAngle = DEFAULT_START_ANGLE,
192 endAngle = DEFAULT_END_ANGLE,
193 asChild,
194 className,
195 ...rootProps
196 } = props;
197
198 if ((maxProp || maxProp === 0) && !getIsValidMaxNumber(maxProp)) {
199 if (process.env.NODE_ENV !== "production") {
200 console.error(getInvalidMaxError(`${maxProp}`, GAUGE_NAME));
201 }
202 }
203
204 const rawMax = getIsValidMaxNumber(maxProp) ? maxProp : DEFAULT_MAX;
205 const min = getIsValidNumber(minProp) ? minProp : 0;
206 const max = rawMax <= min ? min + 1 : rawMax;
207
208 if (process.env.NODE_ENV !== "production" && thickness >= size) {
209 console.warn(
210 `Gauge: thickness (${thickness}) should be less than size (${size}) for proper rendering.`,
211 );
212 }
213
214 if (valueProp !== null && !getIsValidValueNumber(valueProp, min, max)) {
215 if (process.env.NODE_ENV !== "production") {
216 console.error(getInvalidValueError(`${valueProp}`, GAUGE_NAME));
217 }
218 }
219
220 const value = getIsValidValueNumber(valueProp, min, max)
221 ? valueProp
222 : getIsValidNumber(valueProp) && valueProp > max
223 ? max
224 : getIsValidNumber(valueProp) && valueProp < min
225 ? min
226 : null;
227
228 const valueText = getIsValidNumber(value)
229 ? getValueText(value, min, max)
230 : undefined;
231 const state = getGaugeState(value, max);
232 const radius = Math.max(0, (size - thickness) / 2);
233 const center = size / 2;
234
235 const angleDiff = Math.abs(endAngle - startAngle);
236 const arcLength = (Math.min(angleDiff, 360) / 360) * (2 * Math.PI * radius);
237
238 const percentage = getIsValidNumber(value)
239 ? max === min
240 ? 1
241 : (value - min) / (max - min)
242 : null;
243
244 // Calculate the visual center Y of the arc for text positioning
245 // For full circles, use geometric center. For partial arcs, calculate based on bounding box
246 const angleDiffDeg = Math.abs(endAngle - startAngle);
247 const isFullCircle = angleDiffDeg >= 360;
248
249 let arcCenterY = center;
250 if (!isFullCircle) {
251 const startRad = (startAngle * Math.PI) / 180;
252 const endRad = (endAngle * Math.PI) / 180;
253
254 const startY = center - radius * Math.cos(startRad);
255 const endY = center - radius * Math.cos(endRad);
256
257 let minY = Math.min(startY, endY);
258 let maxY = Math.max(startY, endY);
259
260 const normStart = getNormalizedAngle(startAngle);
261 const normEnd = getNormalizedAngle(endAngle);
262
263 const includesTop =
264 normStart > normEnd
265 ? normStart <= 270 || normEnd >= 270
266 : normStart <= 270 && normEnd >= 270;
267 const includesBottom =
268 normStart > normEnd
269 ? normStart <= 90 || normEnd >= 90
270 : normStart <= 90 && normEnd >= 90;
271
272 if (includesTop) minY = Math.min(minY, center - radius);
273 if (includesBottom) maxY = Math.max(maxY, center + radius);
274
275 arcCenterY = (minY + maxY) / 2;
276 }
277
278 const labelId = React.useId();
279 const valueTextId = React.useId();
280
281 const contextValue = React.useMemo<GaugeContextValue>(
282 () => ({
283 value,
284 valueText,
285 max,
286 min,
287 state,
288 radius,
289 thickness,
290 size,
291 center,
292 percentage,
293 startAngle,
294 endAngle,
295 arcLength,
296 arcCenterY,
297 valueTextId,
298 labelId,
299 }),
300 [
301 value,
302 valueText,
303 max,
304 min,
305 state,
306 radius,
307 thickness,
308 size,
309 center,
310 percentage,
311 startAngle,
312 endAngle,
313 arcLength,
314 arcCenterY,
315 valueTextId,
316 labelId,
317 ],
318 );
319
320 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
321
322 return (
323 <GaugeContext.Provider value={contextValue}>
324 <RootPrimitive
325 role="meter"
326 aria-describedby={valueText ? valueTextId : undefined}
327 aria-labelledby={labelId}
328 aria-valuemax={max}
329 aria-valuemin={min}
330 aria-valuenow={getIsValidNumber(value) ? value : undefined}
331 aria-valuetext={valueText}
332 data-state={state}
333 data-value={value ?? undefined}
334 data-max={max}
335 data-min={min}
336 data-percentage={percentage}
337 {...rootProps}
338 className={cn(
339 "relative inline-flex w-fit flex-col items-center justify-center",
340 className,
341 )}
342 />
343 </GaugeContext.Provider>
344 );
345}
346
347function GaugeIndicator(props: React.ComponentProps<"svg">) {
348 const { className, ...indicatorProps } = props;
349
350 const { size, state, value, max, min, percentage } =
351 useGaugeContext(INDICATOR_NAME);
352
353 return (
354 <svg
355 aria-hidden="true"
356 focusable="false"
357 viewBox={`0 0 ${size} ${size}`}
358 data-state={state}
359 data-value={value ?? undefined}
360 data-max={max}
361 data-min={min}
362 data-percentage={percentage}
363 width={size}
364 height={size}
365 {...indicatorProps}
366 className={cn("transform", className)}
367 />
368 );
369}
370
371function GaugeTrack(props: PathProps) {
372 const { className, ...trackProps } = props;
373
374 const { center, radius, startAngle, endAngle, thickness, state } =
375 useGaugeContext(TRACK_NAME);
376
377 const pathData = describeArc(center, center, radius, startAngle, endAngle);
378
379 return (
380 <path
381 data-state={state}
382 d={pathData}
383 fill="none"
384 stroke="currentColor"
385 strokeWidth={thickness}
386 strokeLinecap="round"
387 vectorEffect="non-scaling-stroke"
388 {...trackProps}
389 className={cn("text-muted-foreground/20", className)}
390 />
391 );
392}
393
394function GaugeRange(props: PathProps) {
395 const { className, ...rangeProps } = props;
396
397 const {
398 center,
399 radius,
400 startAngle,
401 endAngle,
402 value,
403 max,
404 min,
405 state,
406 thickness,
407 arcLength,
408 percentage,
409 } = useGaugeContext(RANGE_NAME);
410
411 const pathData = describeArc(center, center, radius, startAngle, endAngle);
412
413 const strokeDasharray = arcLength;
414 const strokeDashoffset =
415 state === "indeterminate"
416 ? 0
417 : percentage !== null
418 ? arcLength - percentage * arcLength
419 : arcLength;
420
421 return (
422 <path
423 data-state={state}
424 data-value={value ?? undefined}
425 data-max={max}
426 data-min={min}
427 d={pathData}
428 fill="none"
429 stroke="currentColor"
430 strokeWidth={thickness}
431 strokeLinecap="round"
432 strokeDasharray={strokeDasharray}
433 strokeDashoffset={strokeDashoffset}
434 vectorEffect="non-scaling-stroke"
435 {...rangeProps}
436 className={cn(
437 "text-primary transition-[stroke-dashoffset] duration-700 ease-out",
438 className,
439 )}
440 />
441 );
442}
443
444function GaugeValueText(props: DivProps) {
445 const { asChild, className, children, style, ...valueTextProps } = props;
446
447 const { valueTextId, state, arcCenterY, valueText } =
448 useGaugeContext(VALUE_TEXT_NAME);
449
450 const ValueTextPrimitive = asChild ? SlotPrimitive.Slot : "div";
451
452 return (
453 <ValueTextPrimitive
454 id={valueTextId}
455 data-state={state}
456 {...valueTextProps}
457 style={{
458 top: `${arcCenterY}px`,
459 ...style,
460 }}
461 className={cn(
462 "absolute right-0 left-0 flex -translate-y-1/2 items-center justify-center font-semibold text-2xl",
463 className,
464 )}
465 >
466 {children ?? valueText}
467 </ValueTextPrimitive>
468 );
469}
470
471function GaugeLabel(props: DivProps) {
472 const { asChild, className, ...labelProps } = props;
473
474 const { labelId, state } = useGaugeContext(LABEL_NAME);
475
476 const LabelPrimitive = asChild ? SlotPrimitive.Slot : "div";
477
478 return (
479 <LabelPrimitive
480 id={labelId}
481 data-state={state}
482 {...labelProps}
483 className={cn(
484 "mt-2 font-medium text-muted-foreground text-sm",
485 className,
486 )}
487 />
488 );
489}
490
491function GaugeCombined(props: GaugeProps) {
492 return (
493 <Gauge {...props}>
494 <GaugeIndicator>
495 <GaugeTrack />
496 <GaugeRange />
497 </GaugeIndicator>
498 <GaugeValueText />
499 </Gauge>
500 );
501}
502
503export {
504 Gauge,
505 GaugeCombined,
506 GaugeIndicator,
507 GaugeLabel,
508 type GaugeProps,
509 GaugeRange,
510 GaugeTrack,
511 GaugeValueText,
512};
513