1"use client";
2
3import { Check } from "lucide-react";
4import {
5 Direction as DirectionPrimitive,
6 Slot as SlotPrimitive,
7} from "radix-ui";
8import * as React from "react";
9import { useComposedRefs } from "@/lib/compose-refs";
10import { cn } from "@/lib/utils";
11import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
12import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
13import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
14
15const ROOT_NAME = "Stepper";
16const LIST_NAME = "StepperList";
17const ITEM_NAME = "StepperItem";
18const TRIGGER_NAME = "StepperTrigger";
19const INDICATOR_NAME = "StepperIndicator";
20const SEPARATOR_NAME = "StepperSeparator";
21const TITLE_NAME = "StepperTitle";
22const DESCRIPTION_NAME = "StepperDescription";
23const CONTENT_NAME = "StepperContent";
24const PREV_NAME = "StepperPrev";
25const NEXT_NAME = "StepperNext";
26
27const ENTRY_FOCUS = "stepperFocusGroup.onEntryFocus";
28const EVENT_OPTIONS = { bubbles: false, cancelable: true };
29const ARROW_KEYS = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
30
31type Direction = "ltr" | "rtl";
32type Orientation = "horizontal" | "vertical";
33type NavigationDirection = "next" | "prev";
34type ActivationMode = "automatic" | "manual";
35type DataState = "inactive" | "active" | "completed";
36
37interface DivProps extends React.ComponentProps<"div"> {
38 asChild?: boolean;
39}
40interface ButtonProps extends React.ComponentProps<"button"> {
41 asChild?: boolean;
42}
43
44type ListElement = React.ComponentRef<typeof StepperList>;
45type TriggerElement = React.ComponentRef<typeof StepperTrigger>;
46
47function getId(
48 id: string,
49 variant: "trigger" | "content" | "title" | "description",
50 value: string,
51) {
52 return `${id}-${variant}-${value}`;
53}
54
55type FocusIntent = "first" | "last" | "prev" | "next";
56
57const MAP_KEY_TO_FOCUS_INTENT: Record<string, FocusIntent> = {
58 ArrowLeft: "prev",
59 ArrowUp: "prev",
60 ArrowRight: "next",
61 ArrowDown: "next",
62 PageUp: "first",
63 Home: "first",
64 PageDown: "last",
65 End: "last",
66};
67
68function getDirectionAwareKey(key: string, dir?: Direction) {
69 if (dir !== "rtl") return key;
70 return key === "ArrowLeft"
71 ? "ArrowRight"
72 : key === "ArrowRight"
73 ? "ArrowLeft"
74 : key;
75}
76
77function getFocusIntent(
78 event: React.KeyboardEvent<TriggerElement>,
79 dir?: Direction,
80 orientation?: Orientation,
81) {
82 const key = getDirectionAwareKey(event.key, dir);
83 if (orientation === "horizontal" && ["ArrowUp", "ArrowDown"].includes(key))
84 return undefined;
85 if (orientation === "vertical" && ["ArrowLeft", "ArrowRight"].includes(key))
86 return undefined;
87 return MAP_KEY_TO_FOCUS_INTENT[key];
88}
89
90function focusFirst(
91 candidates: React.RefObject<TriggerElement | null>[],
92 preventScroll = false,
93) {
94 const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
95 for (const candidateRef of candidates) {
96 const candidate = candidateRef.current;
97 if (!candidate) continue;
98 if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;
99 candidate.focus({ preventScroll });
100 if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;
101 }
102}
103
104function wrapArray<T>(array: T[], startIndex: number) {
105 return array.map<T>(
106 (_, index) => array[(startIndex + index) % array.length] as T,
107 );
108}
109
110function getDataState(
111 value: string | undefined,
112 itemValue: string,
113 stepState: StepState | undefined,
114 steps: Map<string, StepState>,
115 variant: "item" | "separator" = "item",
116): DataState {
117 const stepKeys = Array.from(steps.keys());
118 const currentIndex = stepKeys.indexOf(itemValue);
119
120 if (stepState?.completed) return "completed";
121
122 if (value === itemValue) {
123 return variant === "separator" ? "inactive" : "active";
124 }
125
126 if (value) {
127 const activeIndex = stepKeys.indexOf(value);
128
129 if (activeIndex > currentIndex) return "completed";
130 }
131
132 return "inactive";
133}
134
135interface StepState {
136 value: string;
137 completed: boolean;
138 disabled: boolean;
139}
140
141interface StoreState {
142 steps: Map<string, StepState>;
143 value: string;
144}
145
146interface Store {
147 subscribe: (callback: () => void) => () => void;
148 getState: () => StoreState;
149 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => void;
150 setStateWithValidation: (
151 value: string,
152 direction: NavigationDirection,
153 ) => Promise<boolean>;
154 hasValidation: () => boolean;
155 notify: () => void;
156 addStep: (value: string, completed: boolean, disabled: boolean) => void;
157 removeStep: (value: string) => void;
158 setStep: (value: string, completed: boolean, disabled: boolean) => void;
159}
160
161const StoreContext = React.createContext<Store | null>(null);
162
163function useStoreContext(consumerName: string) {
164 const context = React.useContext(StoreContext);
165 if (!context) {
166 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
167 }
168 return context;
169}
170
171function useStore<T>(selector: (state: StoreState) => T): T {
172 const store = useStoreContext("useStore");
173
174 const getSnapshot = React.useCallback(
175 () => selector(store.getState()),
176 [store, selector],
177 );
178
179 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
180}
181
182interface ItemData {
183 id: string;
184 ref: React.RefObject<TriggerElement | null>;
185 value: string;
186 active: boolean;
187 disabled: boolean;
188}
189
190interface StepperContextValue {
191 rootId: string;
192 dir: Direction;
193 orientation: Orientation;
194 activationMode: ActivationMode;
195 disabled: boolean;
196 nonInteractive: boolean;
197 loop: boolean;
198}
199
200const StepperContext = React.createContext<StepperContextValue | null>(null);
201
202function useStepperContext(consumerName: string) {
203 const context = React.useContext(StepperContext);
204 if (!context) {
205 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
206 }
207 return context;
208}
209
210interface StepperProps extends DivProps {
211 value?: string;
212 defaultValue?: string;
213 onValueChange?: (value: string) => void;
214 onValueComplete?: (value: string, completed: boolean) => void;
215 onValueAdd?: (value: string) => void;
216 onValueRemove?: (value: string) => void;
217 onValidate?: (
218 value: string,
219 direction: NavigationDirection,
220 ) => boolean | Promise<boolean>;
221 activationMode?: ActivationMode;
222 dir?: Direction;
223 orientation?: Orientation;
224 disabled?: boolean;
225 loop?: boolean;
226 nonInteractive?: boolean;
227}
228
229function Stepper(props: StepperProps) {
230 const {
231 value,
232 defaultValue,
233 onValueChange,
234 onValueComplete,
235 onValueAdd,
236 onValueRemove,
237 onValidate,
238 dir: dirProp,
239 orientation = "horizontal",
240 activationMode = "automatic",
241 asChild,
242 disabled = false,
243 nonInteractive = false,
244 loop = false,
245 className,
246 id,
247 ...rootProps
248 } = props;
249
250 const listenersRef = useLazyRef(() => new Set<() => void>());
251 const stateRef = useLazyRef<StoreState>(() => ({
252 steps: new Map(),
253 value: value ?? defaultValue ?? "",
254 }));
255
256 const propsRef = useAsRef({
257 onValueChange,
258 onValueComplete,
259 onValueAdd,
260 onValueRemove,
261 onValidate,
262 });
263
264 const store = React.useMemo<Store>(() => {
265 return {
266 subscribe: (cb) => {
267 listenersRef.current.add(cb);
268 return () => listenersRef.current.delete(cb);
269 },
270 getState: () => stateRef.current,
271 setState: (key, value) => {
272 if (Object.is(stateRef.current[key], value)) return;
273
274 if (key === "value" && typeof value === "string") {
275 stateRef.current.value = value;
276 propsRef.current.onValueChange?.(value);
277 } else {
278 stateRef.current[key] = value;
279 }
280
281 store.notify();
282 },
283 setStateWithValidation: async (value, direction) => {
284 if (!propsRef.current.onValidate) {
285 store.setState("value", value);
286 return true;
287 }
288
289 try {
290 const isValid = await propsRef.current.onValidate(value, direction);
291 if (isValid) {
292 store.setState("value", value);
293 }
294 return isValid;
295 } catch {
296 return false;
297 }
298 },
299 hasValidation: () => !!propsRef.current.onValidate,
300 addStep: (value, completed, disabled) => {
301 const newStep: StepState = { value, completed, disabled };
302 stateRef.current.steps.set(value, newStep);
303 propsRef.current.onValueAdd?.(value);
304 store.notify();
305 },
306 removeStep: (value) => {
307 stateRef.current.steps.delete(value);
308 propsRef.current.onValueRemove?.(value);
309 store.notify();
310 },
311 setStep: (value, completed, disabled) => {
312 const step = stateRef.current.steps.get(value);
313 if (step) {
314 const updatedStep: StepState = { ...step, completed, disabled };
315 stateRef.current.steps.set(value, updatedStep);
316
317 if (completed !== step.completed) {
318 propsRef.current.onValueComplete?.(value, completed);
319 }
320
321 store.notify();
322 }
323 },
324 notify: () => {
325 for (const cb of listenersRef.current) {
326 cb();
327 }
328 },
329 };
330 }, [listenersRef, stateRef, propsRef]);
331
332 useIsomorphicLayoutEffect(() => {
333 if (value !== undefined) {
334 store.setState("value", value);
335 }
336 }, [value]);
337
338 const dir = DirectionPrimitive.useDirection(dirProp);
339
340 const instanceId = React.useId();
341 const rootId = id ?? instanceId;
342
343 const contextValue = React.useMemo<StepperContextValue>(
344 () => ({
345 rootId,
346 dir,
347 orientation,
348 activationMode,
349 disabled,
350 nonInteractive,
351 loop,
352 }),
353 [rootId, dir, orientation, activationMode, disabled, nonInteractive, loop],
354 );
355
356 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
357
358 return (
359 <StoreContext.Provider value={store}>
360 <StepperContext.Provider value={contextValue}>
361 <RootPrimitive
362 id={rootId}
363 data-disabled={disabled ? "" : undefined}
364 data-orientation={orientation}
365 data-slot="stepper"
366 dir={dir}
367 {...rootProps}
368 className={cn(
369 "flex gap-6",
370 orientation === "horizontal" ? "w-full flex-col" : "flex-row",
371 className,
372 )}
373 />
374 </StepperContext.Provider>
375 </StoreContext.Provider>
376 );
377}
378
379interface FocusContextValue {
380 tabStopId: string | null;
381 onItemFocus: (tabStopId: string) => void;
382 onItemShiftTab: () => void;
383 onFocusableItemAdd: () => void;
384 onFocusableItemRemove: () => void;
385 onItemRegister: (item: ItemData) => void;
386 onItemUnregister: (id: string) => void;
387 getItems: () => ItemData[];
388}
389
390const FocusContext = React.createContext<FocusContextValue | null>(null);
391
392function useFocusContext(consumerName: string) {
393 const context = React.useContext(FocusContext);
394 if (!context) {
395 throw new Error(
396 `\`${consumerName}\` must be used within \`FocusProvider\``,
397 );
398 }
399 return context;
400}
401
402function StepperList(props: DivProps) {
403 const {
404 asChild,
405 onBlur: onBlurProp,
406 onFocus: onFocusProp,
407 onMouseDown: onMouseDownProp,
408 className,
409 children,
410 ref,
411 ...listProps
412 } = props;
413
414 const context = useStepperContext(LIST_NAME);
415 const orientation = context.orientation;
416 const currentValue = useStore((state) => state.value);
417
418 const propsRef = useAsRef({
419 onBlur: onBlurProp,
420 onFocus: onFocusProp,
421 onMouseDown: onMouseDownProp,
422 });
423
424 const [tabStopId, setTabStopId] = React.useState<string | null>(null);
425 const [isTabbingBackOut, setIsTabbingBackOut] = React.useState(false);
426 const [focusableItemCount, setFocusableItemCount] = React.useState(0);
427 const isClickFocusRef = React.useRef(false);
428 const itemsRef = React.useRef<Map<string, ItemData>>(new Map());
429 const listRef = React.useRef<ListElement>(null);
430 const composedRef = useComposedRefs(ref, listRef);
431
432 const onItemFocus = React.useCallback((tabStopId: string) => {
433 setTabStopId(tabStopId);
434 }, []);
435
436 const onItemShiftTab = React.useCallback(() => {
437 setIsTabbingBackOut(true);
438 }, []);
439
440 const onFocusableItemAdd = React.useCallback(() => {
441 setFocusableItemCount((prevCount) => prevCount + 1);
442 }, []);
443
444 const onFocusableItemRemove = React.useCallback(() => {
445 setFocusableItemCount((prevCount) => prevCount - 1);
446 }, []);
447
448 const onItemRegister = React.useCallback((item: ItemData) => {
449 itemsRef.current.set(item.id, item);
450 }, []);
451
452 const onItemUnregister = React.useCallback((id: string) => {
453 itemsRef.current.delete(id);
454 }, []);
455
456 const getItems = React.useCallback(() => {
457 return Array.from(itemsRef.current.values())
458 .filter((item) => item.ref.current)
459 .sort((a, b) => {
460 const elementA = a.ref.current;
461 const elementB = b.ref.current;
462 if (!elementA || !elementB) return 0;
463 const position = elementA.compareDocumentPosition(elementB);
464 if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
465 return -1;
466 }
467 if (position & Node.DOCUMENT_POSITION_PRECEDING) {
468 return 1;
469 }
470 return 0;
471 });
472 }, []);
473
474 const onBlur = React.useCallback(
475 (event: React.FocusEvent<ListElement>) => {
476 propsRef.current.onBlur?.(event);
477 if (event.defaultPrevented) return;
478
479 setIsTabbingBackOut(false);
480 },
481 [propsRef],
482 );
483
484 const onFocus = React.useCallback(
485 (event: React.FocusEvent<ListElement>) => {
486 propsRef.current.onFocus?.(event);
487 if (event.defaultPrevented) return;
488
489 const isKeyboardFocus = !isClickFocusRef.current;
490 if (
491 event.target === event.currentTarget &&
492 isKeyboardFocus &&
493 !isTabbingBackOut
494 ) {
495 const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS);
496 event.currentTarget.dispatchEvent(entryFocusEvent);
497
498 if (!entryFocusEvent.defaultPrevented) {
499 const items = Array.from(itemsRef.current.values()).filter(
500 (item) => !item.disabled,
501 );
502 const selectedItem = currentValue
503 ? items.find((item) => item.value === currentValue)
504 : undefined;
505 const activeItem = items.find((item) => item.active);
506 const currentItem = items.find((item) => item.id === tabStopId);
507
508 const candidateItems = [
509 selectedItem,
510 activeItem,
511 currentItem,
512 ...items,
513 ].filter(Boolean) as ItemData[];
514 const candidateRefs = candidateItems.map((item) => item.ref);
515 focusFirst(candidateRefs, false);
516 }
517 }
518 isClickFocusRef.current = false;
519 },
520 [propsRef, isTabbingBackOut, currentValue, tabStopId],
521 );
522
523 const onMouseDown = React.useCallback(
524 (event: React.MouseEvent<ListElement>) => {
525 propsRef.current.onMouseDown?.(event);
526
527 if (event.defaultPrevented) return;
528
529 isClickFocusRef.current = true;
530 },
531 [propsRef],
532 );
533
534 const focusContextValue = React.useMemo<FocusContextValue>(
535 () => ({
536 tabStopId,
537 onItemFocus,
538 onItemShiftTab,
539 onFocusableItemAdd,
540 onFocusableItemRemove,
541 onItemRegister,
542 onItemUnregister,
543 getItems,
544 }),
545 [
546 tabStopId,
547 onItemFocus,
548 onItemShiftTab,
549 onFocusableItemAdd,
550 onFocusableItemRemove,
551 onItemRegister,
552 onItemUnregister,
553 getItems,
554 ],
555 );
556
557 const ListPrimitive = asChild ? SlotPrimitive.Slot : "div";
558
559 return (
560 <FocusContext.Provider value={focusContextValue}>
561 <ListPrimitive
562 role="tablist"
563 aria-orientation={orientation}
564 data-orientation={orientation}
565 data-slot="stepper-list"
566 dir={context.dir}
567 tabIndex={isTabbingBackOut || focusableItemCount === 0 ? -1 : 0}
568 {...listProps}
569 ref={composedRef}
570 className={cn(
571 "flex outline-none",
572 orientation === "horizontal"
573 ? "flex-row items-center"
574 : "flex-col items-start",
575 className,
576 )}
577 onBlur={onBlur}
578 onFocus={onFocus}
579 onMouseDown={onMouseDown}
580 >
581 {children}
582 </ListPrimitive>
583 </FocusContext.Provider>
584 );
585}
586
587interface StepperItemContextValue {
588 value: string;
589 stepState: StepState | undefined;
590}
591
592const StepperItemContext = React.createContext<StepperItemContextValue | null>(
593 null,
594);
595
596function useStepperItemContext(consumerName: string) {
597 const context = React.useContext(StepperItemContext);
598 if (!context) {
599 throw new Error(`\`${consumerName}\` must be used within \`${ITEM_NAME}\``);
600 }
601 return context;
602}
603
604interface StepperItemProps extends DivProps {
605 value: string;
606 completed?: boolean;
607 disabled?: boolean;
608}
609
610function StepperItem(props: StepperItemProps) {
611 const {
612 value: itemValue,
613 completed = false,
614 disabled = false,
615 asChild,
616 className,
617 children,
618 ref,
619 ...itemProps
620 } = props;
621
622 const context = useStepperContext(ITEM_NAME);
623 const store = useStoreContext(ITEM_NAME);
624 const orientation = context.orientation;
625 const value = useStore((state) => state.value);
626
627 useIsomorphicLayoutEffect(() => {
628 store.addStep(itemValue, completed, disabled);
629
630 return () => {
631 store.removeStep(itemValue);
632 };
633 }, [itemValue, completed, disabled]);
634
635 useIsomorphicLayoutEffect(() => {
636 store.setStep(itemValue, completed, disabled);
637 }, [itemValue, completed, disabled]);
638
639 const stepState = useStore((state) => state.steps.get(itemValue));
640 const steps = useStore((state) => state.steps);
641 const dataState = getDataState(value, itemValue, stepState, steps);
642
643 const itemContextValue = React.useMemo<StepperItemContextValue>(
644 () => ({
645 value: itemValue,
646 stepState,
647 }),
648 [itemValue, stepState],
649 );
650
651 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
652
653 return (
654 <StepperItemContext.Provider value={itemContextValue}>
655 <ItemPrimitive
656 data-disabled={stepState?.disabled ? "" : undefined}
657 data-orientation={orientation}
658 data-state={dataState}
659 data-slot="stepper-item"
660 dir={context.dir}
661 {...itemProps}
662 ref={ref}
663 className={cn(
664 "relative flex not-last:flex-1 items-center",
665 orientation === "horizontal" ? "flex-row" : "flex-col",
666 className,
667 )}
668 >
669 {children}
670 </ItemPrimitive>
671 </StepperItemContext.Provider>
672 );
673}
674
675function StepperTrigger(props: ButtonProps) {
676 const {
677 asChild,
678 onClick: onClickProp,
679 onFocus: onFocusProp,
680 onKeyDown: onKeyDownProp,
681 onMouseDown: onMouseDownProp,
682 disabled,
683 className,
684 ref,
685 ...triggerProps
686 } = props;
687
688 const context = useStepperContext(TRIGGER_NAME);
689 const itemContext = useStepperItemContext(TRIGGER_NAME);
690 const itemValue = itemContext.value;
691
692 const store = useStoreContext(TRIGGER_NAME);
693 const focusContext = useFocusContext(TRIGGER_NAME);
694 const value = useStore((state) => state.value);
695 const steps = useStore((state) => state.steps);
696 const stepState = useStore((state) => state.steps.get(itemValue));
697
698 const propsRef = useAsRef({
699 onClick: onClickProp,
700 onFocus: onFocusProp,
701 onKeyDown: onKeyDownProp,
702 onMouseDown: onMouseDownProp,
703 });
704
705 const activationMode = context.activationMode;
706 const orientation = context.orientation;
707 const loop = context.loop;
708
709 const stepIndex = Array.from(steps.keys()).indexOf(itemValue);
710
711 const stepPosition = stepIndex + 1;
712 const stepCount = steps.size;
713
714 const triggerId = getId(context.rootId, "trigger", itemValue);
715 const contentId = getId(context.rootId, "content", itemValue);
716 const titleId = getId(context.rootId, "title", itemValue);
717 const descriptionId = getId(context.rootId, "description", itemValue);
718
719 const isDisabled = disabled || stepState?.disabled || context.disabled;
720 const isActive = value === itemValue;
721 const isTabStop = focusContext.tabStopId === triggerId;
722 const dataState = getDataState(value, itemValue, stepState, steps);
723
724 const triggerRef = React.useRef<TriggerElement>(null);
725 const composedRef = useComposedRefs(ref, triggerRef);
726 const isArrowKeyPressedRef = React.useRef(false);
727 const isMouseClickRef = React.useRef(false);
728
729 React.useEffect(() => {
730 function onKeyDown(event: KeyboardEvent) {
731 if (ARROW_KEYS.includes(event.key)) {
732 isArrowKeyPressedRef.current = true;
733 }
734 }
735 function onKeyUp() {
736 isArrowKeyPressedRef.current = false;
737 }
738 document.addEventListener("keydown", onKeyDown);
739 document.addEventListener("keyup", onKeyUp);
740 return () => {
741 document.removeEventListener("keydown", onKeyDown);
742 document.removeEventListener("keyup", onKeyUp);
743 };
744 }, []);
745
746 useIsomorphicLayoutEffect(() => {
747 focusContext.onItemRegister({
748 id: triggerId,
749 ref: triggerRef,
750 value: itemValue,
751 active: isTabStop,
752 disabled: !!isDisabled,
753 });
754
755 if (!isDisabled) {
756 focusContext.onFocusableItemAdd();
757 }
758
759 return () => {
760 focusContext.onItemUnregister(triggerId);
761 if (!isDisabled) {
762 focusContext.onFocusableItemRemove();
763 }
764 };
765 }, [focusContext, triggerId, itemValue, isTabStop, isDisabled]);
766
767 const onClick = React.useCallback(
768 async (event: React.MouseEvent<TriggerElement>) => {
769 propsRef.current.onClick?.(event);
770 if (event.defaultPrevented) return;
771
772 if (!isDisabled && !context.nonInteractive) {
773 const currentStepIndex = Array.from(steps.keys()).indexOf(value ?? "");
774 const targetStepIndex = Array.from(steps.keys()).indexOf(itemValue);
775 const direction = targetStepIndex > currentStepIndex ? "next" : "prev";
776
777 await store.setStateWithValidation(itemValue, direction);
778 }
779 },
780 [
781 isDisabled,
782 context.nonInteractive,
783 store,
784 itemValue,
785 value,
786 steps,
787 propsRef,
788 ],
789 );
790
791 const onFocus = React.useCallback(
792 async (event: React.FocusEvent<TriggerElement>) => {
793 propsRef.current.onFocus?.(event);
794 if (event.defaultPrevented) return;
795
796 focusContext.onItemFocus(triggerId);
797
798 const isKeyboardFocus = !isMouseClickRef.current;
799
800 if (
801 !isActive &&
802 !isDisabled &&
803 activationMode !== "manual" &&
804 !context.nonInteractive &&
805 isKeyboardFocus
806 ) {
807 const currentStepIndex = Array.from(steps.keys()).indexOf(value || "");
808 const targetStepIndex = Array.from(steps.keys()).indexOf(itemValue);
809 const direction = targetStepIndex > currentStepIndex ? "next" : "prev";
810
811 await store.setStateWithValidation(itemValue, direction);
812 }
813
814 isMouseClickRef.current = false;
815 },
816 [
817 focusContext,
818 triggerId,
819 activationMode,
820 isActive,
821 isDisabled,
822 context.nonInteractive,
823 store,
824 itemValue,
825 value,
826 steps,
827 propsRef,
828 ],
829 );
830
831 const onKeyDown = React.useCallback(
832 async (event: React.KeyboardEvent<TriggerElement>) => {
833 propsRef.current.onKeyDown?.(event);
834 if (event.defaultPrevented) return;
835
836 if (event.key === "Enter" && context.nonInteractive) {
837 event.preventDefault();
838 return;
839 }
840
841 if (
842 (event.key === "Enter" || event.key === " ") &&
843 activationMode === "manual" &&
844 !context.nonInteractive
845 ) {
846 event.preventDefault();
847 if (!isDisabled && triggerRef.current) {
848 triggerRef.current.click();
849 }
850 return;
851 }
852
853 if (event.key === "Tab" && event.shiftKey) {
854 focusContext.onItemShiftTab();
855 return;
856 }
857
858 if (event.target !== event.currentTarget) return;
859
860 const focusIntent = getFocusIntent(event, context.dir, orientation);
861
862 if (focusIntent !== undefined) {
863 if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey)
864 return;
865 event.preventDefault();
866
867 const items = focusContext.getItems().filter((item) => !item.disabled);
868 let candidateRefs = items.map((item) => item.ref);
869
870 if (focusIntent === "last") {
871 candidateRefs.reverse();
872 } else if (focusIntent === "prev" || focusIntent === "next") {
873 if (focusIntent === "prev") candidateRefs.reverse();
874 const currentIndex = candidateRefs.findIndex(
875 (ref) => ref.current === event.currentTarget,
876 );
877 candidateRefs = loop
878 ? wrapArray(candidateRefs, currentIndex + 1)
879 : candidateRefs.slice(currentIndex + 1);
880 }
881
882 if (store.hasValidation() && candidateRefs.length > 0) {
883 const nextRef = candidateRefs[0];
884 const nextElement = nextRef?.current;
885 const nextItem = items.find(
886 (item) => item.ref.current === nextElement,
887 );
888
889 if (nextItem && nextItem.value !== itemValue) {
890 const currentStepIndex = Array.from(steps.keys()).indexOf(
891 value || "",
892 );
893 const targetStepIndex = Array.from(steps.keys()).indexOf(
894 nextItem.value,
895 );
896 const direction: NavigationDirection =
897 targetStepIndex > currentStepIndex ? "next" : "prev";
898
899 if (direction === "next") {
900 const isValid = await store.setStateWithValidation(
901 nextItem.value,
902 direction,
903 );
904 if (!isValid) return;
905 } else {
906 store.setState("value", nextItem.value);
907 }
908
909 queueMicrotask(() => nextElement?.focus());
910 return;
911 }
912 }
913
914 queueMicrotask(() => focusFirst(candidateRefs));
915 }
916 },
917 [
918 focusContext,
919 context.nonInteractive,
920 context.dir,
921 activationMode,
922 orientation,
923 loop,
924 isDisabled,
925 store,
926 propsRef,
927 itemValue,
928 value,
929 steps,
930 ],
931 );
932
933 const onMouseDown = React.useCallback(
934 (event: React.MouseEvent<TriggerElement>) => {
935 propsRef.current.onMouseDown?.(event);
936 if (event.defaultPrevented) return;
937
938 isMouseClickRef.current = true;
939
940 if (isDisabled) {
941 event.preventDefault();
942 } else {
943 focusContext.onItemFocus(triggerId);
944 }
945 },
946 [focusContext, triggerId, isDisabled, propsRef],
947 );
948
949 const TriggerPrimitive = asChild ? SlotPrimitive.Slot : "button";
950
951 return (
952 <TriggerPrimitive
953 id={triggerId}
954 role="tab"
955 type="button"
956 aria-controls={contentId}
957 aria-current={isActive ? "step" : undefined}
958 aria-describedby={`${titleId} ${descriptionId}`}
959 aria-posinset={stepPosition}
960 aria-selected={isActive}
961 aria-setsize={stepCount}
962 data-disabled={isDisabled ? "" : undefined}
963 data-state={dataState}
964 data-slot="stepper-trigger"
965 disabled={isDisabled}
966 tabIndex={isTabStop ? 0 : -1}
967 {...triggerProps}
968 ref={composedRef}
969 className={cn(
970 "inline-flex items-center justify-center gap-3 rounded-md text-left outline-none transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
971 "not-has-data-[slot=description]:rounded-full not-has-data-[slot=title]:rounded-full",
972 className,
973 )}
974 onClick={onClick}
975 onFocus={onFocus}
976 onKeyDown={onKeyDown}
977 onMouseDown={onMouseDown}
978 />
979 );
980}
981
982interface StepperIndicatorProps extends Omit<DivProps, "children"> {
983 children?: React.ReactNode | ((dataState: DataState) => React.ReactNode);
984}
985
986function StepperIndicator(props: StepperIndicatorProps) {
987 const { className, children, asChild, ref, ...indicatorProps } = props;
988
989 const context = useStepperContext(INDICATOR_NAME);
990 const itemContext = useStepperItemContext(INDICATOR_NAME);
991
992 const value = useStore((state) => state.value);
993 const itemValue = itemContext.value;
994 const stepState = useStore((state) => state.steps.get(itemValue));
995 const steps = useStore((state) => state.steps);
996
997 const stepPosition = Array.from(steps.keys()).indexOf(itemValue) + 1;
998
999 const dataState = getDataState(value, itemValue, stepState, steps);
1000
1001 const IndicatorPrimitive = asChild ? SlotPrimitive.Slot : "div";
1002
1003 return (
1004 <IndicatorPrimitive
1005 data-state={dataState}
1006 data-slot="stepper-indicator"
1007 dir={context.dir}
1008 {...indicatorProps}
1009 ref={ref}
1010 className={cn(
1011 "flex size-7 shrink-0 items-center justify-center rounded-full border-2 border-muted bg-background font-medium text-muted-foreground text-sm transition-colors data-[state=active]:border-primary data-[state=completed]:border-primary data-[state=active]:bg-primary data-[state=completed]:bg-primary data-[state=active]:text-primary-foreground data-[state=completed]:text-primary-foreground",
1012 className,
1013 )}
1014 >
1015 {typeof children === "function" ? (
1016 children(dataState)
1017 ) : children ? (
1018 children
1019 ) : dataState === "completed" ? (
1020 <Check className="size-4" />
1021 ) : (
1022 stepPosition
1023 )}
1024 </IndicatorPrimitive>
1025 );
1026}
1027
1028interface StepperSeparatorProps extends DivProps {
1029 forceMount?: boolean;
1030}
1031
1032function StepperSeparator(props: StepperSeparatorProps) {
1033 const {
1034 className,
1035 asChild,
1036 forceMount = false,
1037 ref,
1038 ...separatorProps
1039 } = props;
1040
1041 const context = useStepperContext(SEPARATOR_NAME);
1042 const itemContext = useStepperItemContext(SEPARATOR_NAME);
1043 const value = useStore((state) => state.value);
1044 const steps = useStore((state) => state.steps);
1045
1046 const orientation = context.orientation;
1047
1048 const stepIndex = Array.from(steps.keys()).indexOf(itemContext.value);
1049
1050 const isLastStep = stepIndex === steps.size - 1;
1051
1052 if (isLastStep && !forceMount) return null;
1053
1054 const dataState = getDataState(
1055 value,
1056 itemContext.value,
1057 itemContext.stepState,
1058 steps,
1059 "separator",
1060 );
1061
1062 const SeparatorPrimitive = asChild ? SlotPrimitive.Slot : "div";
1063
1064 return (
1065 <SeparatorPrimitive
1066 role="separator"
1067 aria-hidden="true"
1068 aria-orientation={orientation}
1069 data-orientation={orientation}
1070 data-state={dataState}
1071 data-slot="stepper-separator"
1072 dir={context.dir}
1073 {...separatorProps}
1074 ref={ref}
1075 className={cn(
1076 "bg-border transition-colors data-[state=active]:bg-primary data-[state=completed]:bg-primary",
1077 orientation === "horizontal" ? "h-px flex-1" : "h-10 w-px",
1078 className,
1079 )}
1080 />
1081 );
1082}
1083
1084interface StepperTitleProps extends React.ComponentProps<"span"> {
1085 asChild?: boolean;
1086}
1087
1088function StepperTitle(props: StepperTitleProps) {
1089 const { className, asChild, ref, ...titleProps } = props;
1090
1091 const context = useStepperContext(TITLE_NAME);
1092 const itemContext = useStepperItemContext(TITLE_NAME);
1093
1094 const titleId = getId(context.rootId, "title", itemContext.value);
1095
1096 const TitlePrimitive = asChild ? SlotPrimitive.Slot : "span";
1097
1098 return (
1099 <TitlePrimitive
1100 id={titleId}
1101 data-slot="title"
1102 dir={context.dir}
1103 {...titleProps}
1104 ref={ref}
1105 className={cn("font-medium text-sm", className)}
1106 />
1107 );
1108}
1109
1110interface StepperDescriptionProps extends React.ComponentProps<"span"> {
1111 asChild?: boolean;
1112}
1113
1114function StepperDescription(props: StepperDescriptionProps) {
1115 const { className, asChild, ref, ...descriptionProps } = props;
1116
1117 const context = useStepperContext(DESCRIPTION_NAME);
1118 const itemContext = useStepperItemContext(DESCRIPTION_NAME);
1119
1120 const descriptionId = getId(context.rootId, "description", itemContext.value);
1121
1122 const DescriptionPrimitive = asChild ? SlotPrimitive.Slot : "span";
1123
1124 return (
1125 <DescriptionPrimitive
1126 id={descriptionId}
1127 data-slot="description"
1128 dir={context.dir}
1129 {...descriptionProps}
1130 ref={ref}
1131 className={cn("text-muted-foreground text-xs", className)}
1132 />
1133 );
1134}
1135
1136interface StepperContentProps extends DivProps {
1137 value: string;
1138 forceMount?: boolean;
1139}
1140
1141function StepperContent(props: StepperContentProps) {
1142 const {
1143 value: valueProp,
1144 asChild,
1145 forceMount = false,
1146 ref,
1147 className,
1148 ...contentProps
1149 } = props;
1150
1151 const context = useStepperContext(CONTENT_NAME);
1152 const value = useStore((state) => state.value);
1153
1154 const contentId = getId(context.rootId, "content", valueProp);
1155 const triggerId = getId(context.rootId, "trigger", valueProp);
1156
1157 if (valueProp !== value && !forceMount) return null;
1158
1159 const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div";
1160
1161 return (
1162 <ContentPrimitive
1163 id={contentId}
1164 role="tabpanel"
1165 aria-labelledby={triggerId}
1166 data-slot="stepper-content"
1167 dir={context.dir}
1168 {...contentProps}
1169 ref={ref}
1170 className={cn("flex-1 outline-none", className)}
1171 />
1172 );
1173}
1174
1175function StepperPrev(props: ButtonProps) {
1176 const { asChild, onClick: onClickProp, disabled, ...prevProps } = props;
1177
1178 const store = useStoreContext(PREV_NAME);
1179 const value = useStore((state) => state.value);
1180 const steps = useStore((state) => state.steps);
1181
1182 const propsRef = useAsRef({
1183 onClick: onClickProp,
1184 });
1185
1186 const stepKeys = Array.from(steps.keys());
1187 const currentIndex = value ? stepKeys.indexOf(value) : -1;
1188 const isDisabled = disabled || currentIndex <= 0;
1189
1190 const onClick = React.useCallback(
1191 async (event: React.MouseEvent<HTMLButtonElement>) => {
1192 propsRef.current.onClick?.(event);
1193 if (event.defaultPrevented || isDisabled) return;
1194
1195 const prevIndex = Math.max(currentIndex - 1, 0);
1196 const prevStepValue = stepKeys[prevIndex];
1197
1198 if (prevStepValue) {
1199 store.setState("value", prevStepValue);
1200 }
1201 },
1202 [propsRef, isDisabled, currentIndex, stepKeys, store],
1203 );
1204
1205 const PrevPrimitive = asChild ? SlotPrimitive.Slot : "button";
1206
1207 return (
1208 <PrevPrimitive
1209 type="button"
1210 data-slot="stepper-prev"
1211 disabled={isDisabled}
1212 {...prevProps}
1213 onClick={onClick}
1214 />
1215 );
1216}
1217
1218function StepperNext(props: ButtonProps) {
1219 const { asChild, onClick: onClickProp, disabled, ...nextProps } = props;
1220
1221 const store = useStoreContext(NEXT_NAME);
1222 const value = useStore((state) => state.value);
1223 const steps = useStore((state) => state.steps);
1224
1225 const propsRef = useAsRef({
1226 onClick: onClickProp,
1227 });
1228
1229 const stepKeys = Array.from(steps.keys());
1230 const currentIndex = value ? stepKeys.indexOf(value) : -1;
1231 const isDisabled = disabled || currentIndex >= stepKeys.length - 1;
1232
1233 const onClick = React.useCallback(
1234 async (event: React.MouseEvent<HTMLButtonElement>) => {
1235 propsRef.current.onClick?.(event);
1236 if (event.defaultPrevented || isDisabled) return;
1237
1238 const nextIndex = Math.min(currentIndex + 1, stepKeys.length - 1);
1239 const nextStepValue = stepKeys[nextIndex];
1240
1241 if (nextStepValue) {
1242 await store.setStateWithValidation(nextStepValue, "next");
1243 }
1244 },
1245 [propsRef, isDisabled, currentIndex, stepKeys, store],
1246 );
1247
1248 const NextPrimitive = asChild ? SlotPrimitive.Slot : "button";
1249
1250 return (
1251 <NextPrimitive
1252 type="button"
1253 data-slot="stepper-next"
1254 disabled={isDisabled}
1255 {...nextProps}
1256 onClick={onClick}
1257 />
1258 );
1259}
1260
1261export {
1262 Stepper,
1263 StepperContent,
1264 StepperDescription,
1265 StepperIndicator,
1266 StepperItem,
1267 StepperList,
1268 StepperNext,
1269 StepperPrev,
1270 type StepperProps,
1271 StepperSeparator,
1272 StepperTitle,
1273 StepperTrigger,
1274 useStore as useStepper,
1275};
1276