"use client"; import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import type { CSSProperties, KeyboardEvent, ReactNode } from "react"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; const EASE = [0.23, 1, 0.32, 1] as const; const EXIT_EASE = [0.4, 0, 1, 1] as const; const RAIL = { type: "spring", stiffness: 520, damping: 40, mass: 0.5 } as const; const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const; export type WizardDirection = 1 | -1; export type UseWizardOptions = { total: number; index?: number; defaultIndex?: number; onIndexChange?: (index: number, direction: WizardDirection) => void; onComplete?: () => void; }; function clampIndex(value: number, total: number) { if (total < 1) return 0; return Math.max(0, Math.min(total - 1, Math.trunc(value))); } export function useWizard({ total, index, defaultIndex = 0, onIndexChange, onComplete, }: UseWizardOptions) { const [internal, setInternal] = useState(() => clampIndex(defaultIndex, total)); const current = clampIndex(index ?? internal, total); const [seen, setSeen] = useState<{ index: number; direction: WizardDirection }>({ index: current, direction: 1, }); if (seen.index !== current) { setSeen({ index: current, direction: current > seen.index ? 1 : -1 }); } const [furthest, setFurthest] = useState(current); if (furthest < current) setFurthest(current); const emit = useRef(onIndexChange); const finish = useRef(onComplete); useEffect(() => { emit.current = onIndexChange; finish.current = onComplete; }, [onIndexChange, onComplete]); const controlled = index !== undefined; const goTo = useCallback( (to: number) => { const target = clampIndex(to, total); if (target === current) return; const direction: WizardDirection = target > current ? 1 : -1; if (!controlled) setInternal(target); emit.current?.(target, direction); }, [controlled, current, total], ); const next = useCallback(() => { if (current >= total - 1) { finish.current?.(); return; } goTo(current + 1); }, [current, goTo, total]); const back = useCallback(() => goTo(current - 1), [current, goTo]); return { index: current, direction: seen.direction, furthest: Math.min(furthest, Math.max(total - 1, 0)), total, isFirst: current === 0, isLast: current === total - 1, next, back, goTo, }; } export type WizardStep = { id: string; label: string; content: ReactNode; canSkip?: boolean; onSkip?: () => void; hideAdvance?: boolean; hideBack?: boolean; scrollMode?: "panel" | "content"; }; export type WizardNavigationControls = { back: () => void; next: () => void; goTo: (index: number) => void; index: number; total: number; isFirst: boolean; isLast: boolean; }; const WizardNavigationContext = createContext(null); export function useWizardNavigation(): WizardNavigationControls { const controls = useContext(WizardNavigationContext); if (!controls) throw new Error("useWizardNavigation must be used inside "); return controls; } export type WizardStepsProps = { steps: WizardStep[]; index?: number; defaultIndex?: number; onIndexChange?: (index: number, direction: WizardDirection) => void; onComplete?: () => void; complete?: boolean; height?: CSSProperties["height"]; backLabel?: string; nextLabel?: string; finishLabel?: string; skipLabel?: string; completeLabel?: string; completeHint?: string; label?: string; className?: string; spacious?: boolean; fill?: boolean; }; export function WizardSteps({ steps, index, defaultIndex = 0, onIndexChange, onComplete, complete = false, height = 184, backLabel = "Back", nextLabel = "Next", finishLabel = "Finish", skipLabel = "Skip", completeLabel = "All set", completeHint = "Step back to change anything", label = "Steps", className = "", spacious = false, fill = false, }: WizardStepsProps) { const wizard = useWizard({ total: steps.length, index, defaultIndex, onIndexChange, onComplete, }); const reduced = useReducedMotion(); const listRef = useRef(null); const viewportRef = useRef(null); const intent = useRef<"list" | "panel" | null>(null); const { index: at, direction, furthest, total, isFirst, isLast, next, back, goTo, } = wizard; useEffect(() => { const move = intent.current; intent.current = null; if (move === "list") { listRef.current ?.querySelector('button[data-current="true"]') ?.focus(); return; } if (move === "panel") viewportRef.current?.focus({ preventScroll: true }); }, [at]); const variants = useMemo( () => ({ enter: (nextDirection: WizardDirection) => ( reduced ? { opacity: 0 } : { opacity: 0, x: nextDirection * 22 } ), center: reduced ? { opacity: 1 } : { opacity: 1, x: 0 }, exit: (nextDirection: WizardDirection) => ( reduced ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, x: nextDirection * -22, transition: { duration: 0.14, ease: EXIT_EASE }, } ), }), [reduced], ); const panelTransition = reduced ? { duration: 0 } : CROSSFADE; const onStepKeyDown = (event: KeyboardEvent) => { let target: number; if (event.key === "ArrowRight" || event.key === "ArrowDown") target = at + 1; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") target = at - 1; else if (event.key === "Home") target = 0; else if (event.key === "End") target = furthest; else return; event.preventDefault(); target = Math.min(clampIndex(target, total), furthest); if (target === at) return; intent.current = "list"; goTo(target); }; const step = steps[at]; if (!step) return null; const position = `Step ${at + 1} of ${total}: ${step.label}`; const navigation = { back: () => { intent.current = "panel"; back(); }, next: () => { if (!isLast) intent.current = "panel"; next(); }, goTo, index: at, total, isFirst, isLast, } satisfies WizardNavigationControls; const showBack = !isFirst && !step.hideBack; const showSkip = Boolean(step.canSkip); const showAdvance = !complete && !step.hideAdvance; const showNavigation = showBack || showSkip || showAdvance; return (

{position}

{steps.map((candidate, stepIndex) => ( {candidate.label} ))}
    {steps.map((candidate, stepIndex) => { const done = complete || stepIndex < at; const here = !complete && stepIndex === at; const tile = ( {done ? ( ) : ( stepIndex + 1 )} ); return (
  1. {stepIndex <= furthest ? ( ) : ( {`Step ${stepIndex + 1} of ${total}: ${candidate.label}`} {tile} )} {stepIndex < total - 1 ? ( ) : null}
  2. ); })}
{complete ? (

{completeLabel}

{completeHint}

) : ( {step.content} )}
{showNavigation ?
{showBack ? ( { navigation.back(); }} className={`${spacious ? "h-11 px-4 text-sm" : "h-9 px-3 text-[13px]"} rounded-[9px] border border-border bg-background font-medium text-foreground outline-none transition-[border-color,box-shadow] duration-150 hover:border-foreground/20 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40`} > {backLabel} ) : null} {showSkip ? ( { step.onSkip?.(); if (!isLast) intent.current = "panel"; next(); }} className={`${spacious ? "h-11 px-4 text-sm" : "h-9 px-3 text-[13px]"} rounded-[9px] font-medium text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/40`} > {skipLabel} ) : null} {showAdvance ? ( { navigation.next(); }} initial={{ opacity: 0, scale: 0.96 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.96, transition: reduced ? { duration: 0 } : { duration: 0.14, ease: EXIT_EASE }, }} transition={reduced ? { duration: 0 } : CROSSFADE} className={`${spacious ? "h-11 px-4 text-sm" : "h-9 px-3.5 text-[13px]"} ml-auto grid place-items-center rounded-[9px] bg-foreground font-medium text-background outline-none focus-visible:shadow-[inset_0_0_0_1.5px_var(--ring)]`} > {finishLabel.length > nextLabel.length ? finishLabel : nextLabel} {nextLabel} {finishLabel} ) : null}
: null}
); }