1"use client";
2
3import { Slot as SlotPrimitive } from "radix-ui";
4import * as React from "react";
5import { cn } from "@/lib/utils";
6
7const CIRCULAR_PROGRESS_NAME = "CircularProgress";
8const INDICATOR_NAME = "CircularProgressIndicator";
9const TRACK_NAME = "CircularProgressTrack";
10const RANGE_NAME = "CircularProgressRange";
11const VALUE_TEXT_NAME = "CircularProgressValueText";
12
13const DEFAULT_MAX = 100;
14
15type ProgressState = "indeterminate" | "complete" | "loading";
16
17function getProgressState(
18 value: number | undefined | null,
19 maxValue: number,
20): ProgressState {
21 return value == null
22 ? "indeterminate"
23 : value === maxValue
24 ? "complete"
25 : "loading";
26}
27
28function getIsValidNumber(value: unknown): value is number {
29 return typeof value === "number" && Number.isFinite(value);
30}
31
32function getIsValidMaxNumber(max: unknown): max is number {
33 return getIsValidNumber(max) && max > 0;
34}
35
36function getIsValidValueNumber(
37 value: unknown,
38 min: number,
39 max: number,
40): value is number {
41 return getIsValidNumber(value) && value <= max && value >= min;
42}
43
44function getDefaultValueText(value: number, min: number, max: number): string {
45 const percentage = max === min ? 100 : ((value - min) / (max - min)) * 100;
46 return `${Math.round(percentage)}%`;
47}
48
49function getInvalidValueError(
50 propValue: string,
51 componentName: string,
52): string {
53 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 progress. The value will be clamped to the valid range.`;
54}
55
56function getInvalidMaxError(propValue: string, componentName: string): string {
57 return `Invalid prop \`max\` of value \`${propValue}\` supplied to \`${componentName}\`. Only numbers greater than 0 are valid. Defaulting to ${DEFAULT_MAX}.`;
58}
59
60interface CircularProgressContextValue {
61 value: number | null;
62 valueText: string | undefined;
63 max: number;
64 min: number;
65 state: ProgressState;
66 radius: number;
67 thickness: number;
68 size: number;
69 center: number;
70 circumference: number;
71 percentage: number | null;
72 valueTextId?: string;
73}
74
75const CircularProgressContext =
76 React.createContext<CircularProgressContextValue | null>(null);
77
78function useCircularProgressContext(consumerName: string) {
79 const context = React.useContext(CircularProgressContext);
80 if (!context) {
81 throw new Error(
82 `\`${consumerName}\` must be used within \`${CIRCULAR_PROGRESS_NAME}\``,
83 );
84 }
85 return context;
86}
87
88interface CircularProgressProps extends React.ComponentProps<"div"> {
89 value?: number | null | undefined;
90 getValueText?(value: number, min: number, max: number): string;
91 min?: number;
92 max?: number;
93 size?: number;
94 thickness?: number;
95 label?: string;
96 asChild?: boolean;
97}
98
99function CircularProgress(props: CircularProgressProps) {
100 const {
101 value: valueProp = null,
102 getValueText = getDefaultValueText,
103 min: minProp = 0,
104 max: maxProp,
105 size = 48,
106 thickness = 4,
107 label,
108 asChild,
109 className,
110 children,
111 ...rootProps
112 } = props;
113
114 if ((maxProp || maxProp === 0) && !getIsValidMaxNumber(maxProp)) {
115 if (process.env.NODE_ENV !== "production") {
116 console.error(getInvalidMaxError(`${maxProp}`, CIRCULAR_PROGRESS_NAME));
117 }
118 }
119
120 const rawMax = getIsValidMaxNumber(maxProp) ? maxProp : DEFAULT_MAX;
121 const min = getIsValidNumber(minProp) ? minProp : 0;
122 const max = rawMax <= min ? min + 1 : rawMax;
123
124 if (process.env.NODE_ENV !== "production" && thickness >= size) {
125 console.warn(
126 `CircularProgress: thickness (${thickness}) should be less than size (${size}) for proper rendering.`,
127 );
128 }
129
130 if (valueProp !== null && !getIsValidValueNumber(valueProp, min, max)) {
131 if (process.env.NODE_ENV !== "production") {
132 console.error(
133 getInvalidValueError(`${valueProp}`, CIRCULAR_PROGRESS_NAME),
134 );
135 }
136 }
137
138 const value = getIsValidValueNumber(valueProp, min, max)
139 ? valueProp
140 : getIsValidNumber(valueProp) && valueProp > max
141 ? max
142 : getIsValidNumber(valueProp) && valueProp < min
143 ? min
144 : null;
145
146 const valueText = getIsValidNumber(value)
147 ? getValueText(value, min, max)
148 : undefined;
149 const state = getProgressState(value, max);
150 const radius = Math.max(0, (size - thickness) / 2);
151 const center = size / 2;
152 const circumference = 2 * Math.PI * radius;
153
154 const percentage = getIsValidNumber(value)
155 ? max === min
156 ? 1
157 : (value - min) / (max - min)
158 : null;
159
160 const labelId = React.useId();
161 const valueTextId = React.useId();
162
163 const contextValue = React.useMemo<CircularProgressContextValue>(
164 () => ({
165 value,
166 valueText,
167 max,
168 min,
169 state,
170 radius,
171 thickness,
172 size,
173 center,
174 circumference,
175 percentage,
176 valueTextId,
177 }),
178 [
179 value,
180 valueText,
181 max,
182 min,
183 state,
184 radius,
185 thickness,
186 size,
187 center,
188 circumference,
189 percentage,
190 valueTextId,
191 ],
192 );
193
194 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
195
196 return (
197 <CircularProgressContext.Provider value={contextValue}>
198 <RootPrimitive
199 role="progressbar"
200 aria-describedby={valueText ? valueTextId : undefined}
201 aria-labelledby={label ? labelId : undefined}
202 aria-valuemax={max}
203 aria-valuemin={min}
204 aria-valuenow={getIsValidNumber(value) ? value : undefined}
205 aria-valuetext={valueText}
206 data-state={state}
207 data-value={value ?? undefined}
208 data-max={max}
209 data-min={min}
210 data-percentage={percentage}
211 {...rootProps}
212 className={cn(
213 "relative inline-flex w-fit items-center justify-center",
214 className,
215 )}
216 >
217 {children}
218 {label && <div id={labelId}>{label}</div>}
219 </RootPrimitive>
220 </CircularProgressContext.Provider>
221 );
222}
223
224function CircularProgressIndicator(props: React.ComponentProps<"svg">) {
225 const { className, ...indicatorProps } = props;
226
227 const context = useCircularProgressContext(INDICATOR_NAME);
228
229 return (
230 <svg
231 aria-hidden="true"
232 focusable="false"
233 viewBox={`0 0 ${context.size} ${context.size}`}
234 data-state={context.state}
235 data-value={context.value ?? undefined}
236 data-max={context.max}
237 data-min={context.min}
238 data-percentage={context.percentage}
239 width={context.size}
240 height={context.size}
241 {...indicatorProps}
242 className={cn("-rotate-90 transform", className)}
243 />
244 );
245}
246
247CircularProgressIndicator.displayName = INDICATOR_NAME;
248
249function CircularProgressTrack(props: React.ComponentProps<"circle">) {
250 const { className, ...trackProps } = props;
251
252 const context = useCircularProgressContext(TRACK_NAME);
253
254 return (
255 <circle
256 data-state={context.state}
257 cx={context.center}
258 cy={context.center}
259 r={context.radius}
260 fill="none"
261 stroke="currentColor"
262 strokeWidth={context.thickness}
263 strokeLinecap="round"
264 vectorEffect="non-scaling-stroke"
265 {...trackProps}
266 className={cn("text-muted-foreground/20", className)}
267 />
268 );
269}
270
271function CircularProgressRange(props: React.ComponentProps<"circle">) {
272 const { className, ...rangeProps } = props;
273
274 const context = useCircularProgressContext(RANGE_NAME);
275
276 const strokeDasharray = context.circumference;
277 const strokeDashoffset =
278 context.state === "indeterminate"
279 ? context.circumference * 0.75
280 : context.percentage !== null
281 ? context.circumference - context.percentage * context.circumference
282 : context.circumference;
283
284 return (
285 <circle
286 data-state={context.state}
287 data-value={context.value ?? undefined}
288 data-max={context.max}
289 data-min={context.min}
290 cx={context.center}
291 cy={context.center}
292 r={context.radius}
293 fill="none"
294 stroke="currentColor"
295 strokeWidth={context.thickness}
296 strokeLinecap="round"
297 strokeDasharray={strokeDasharray}
298 strokeDashoffset={strokeDashoffset}
299 vectorEffect="non-scaling-stroke"
300 {...rangeProps}
301 className={cn(
302 "origin-center text-primary transition-all duration-300 ease-in-out",
303 context.state === "indeterminate" &&
304 "motion-reduce:animate-none motion-safe:[animation:var(--animate-spin-around)]",
305 className,
306 )}
307 />
308 );
309}
310
311interface CircularProgressValueTextProps extends React.ComponentProps<"span"> {
312 asChild?: boolean;
313}
314
315function CircularProgressValueText(props: CircularProgressValueTextProps) {
316 const { asChild, className, children, ...valueTextProps } = props;
317
318 const context = useCircularProgressContext(VALUE_TEXT_NAME);
319
320 const ValueTextPrimitive = asChild ? SlotPrimitive.Slot : "span";
321
322 return (
323 <ValueTextPrimitive
324 id={context.valueTextId}
325 data-state={context.state}
326 {...valueTextProps}
327 className={cn(
328 "absolute inset-0 flex items-center justify-center font-medium text-sm",
329 className,
330 )}
331 >
332 {children ?? context.valueText}
333 </ValueTextPrimitive>
334 );
335}
336
337function CircularProgressCombined(props: CircularProgressProps) {
338 return (
339 <CircularProgress {...props}>
340 <CircularProgressIndicator>
341 <CircularProgressTrack />
342 <CircularProgressRange />
343 </CircularProgressIndicator>
344 <CircularProgressValueText />
345 </CircularProgress>
346 );
347}
348
349export {
350 CircularProgress,
351 CircularProgressCombined,
352 CircularProgressIndicator,
353 type CircularProgressProps,
354 CircularProgressRange,
355 CircularProgressTrack,
356 CircularProgressValueText,
357};
358