1"use client"
2
3import React, {
4 useCallback,
5 useEffect,
6 useMemo,
7 useRef,
8 useState,
9 type RefObject,
10} from "react"
11import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
12import { AnimatePresence, motion, MotionConfig } from "motion/react"
13
14import { cn } from "@/lib/utils"
15import { Badge } from "@/components/ui/badge"
16
17const transition = {
18 type: "spring" as const,
19 bounce: 0.1,
20 duration: 0.25,
21}
22
23interface DynamicStep {
24 id: string
25 title: string
26 description: string
27 icon:
28 | React.ComponentType<{ className?: string }>
29 | React.ReactElement<{ className?: string }>
30 content: React.ReactNode
31}
32
33interface DynamicToolbarExpandableProps {
34 steps: DynamicStep[]
35 badgeText?: string
36
37 className?: string
38 expanded?: boolean
39 onExpandedChange?: (expanded: boolean) => void
40 activeStep?: string | null
41 onActiveStepChange?: (stepId: string | null) => void
42}
43
44const DynamicToolbarExpandable = React.memo<DynamicToolbarExpandableProps>(
45 function DynamicToolbarExpandable({
46 steps,
47 badgeText,
48
49 className,
50 expanded: controlledExpanded,
51 onExpandedChange,
52 activeStep: controlledActiveStep,
53 onActiveStepChange,
54 }) {
55 const [internalActive, setInternalActive] = useState<string | null>(null)
56 const [internalIsOpen, setInternalIsOpen] = useState(false)
57
58 const active =
59 controlledActiveStep !== undefined ? controlledActiveStep : internalActive
60 const isOpen =
61 controlledExpanded !== undefined ? controlledExpanded : internalIsOpen
62
63 const setActive = useCallback(
64 (value: string | null) => {
65 if (onActiveStepChange) {
66 onActiveStepChange(value)
67 } else {
68 setInternalActive(value)
69 }
70 },
71 [onActiveStepChange]
72 )
73
74 const setIsOpen = useCallback(
75 (value: boolean) => {
76 if (onExpandedChange) {
77 onExpandedChange(value)
78 } else {
79 setInternalIsOpen(value)
80 }
81 },
82 [onExpandedChange]
83 )
84
85 const [previousIndex, setPreviousIndex] = useState<number | null>(null)
86 const [contentRef, contentBounds] = useMeasure()
87 const [menuRef, menuBounds] = useMeasure()
88 const menuContainerRef = useRef<any>(null)
89 const ref = useRef<HTMLDivElement>(null)
90 const [maxWidth, setMaxWidth] = useState(0)
91
92 const heightContent = contentBounds.height
93 const widthContainer = menuBounds.width
94
95 const handleClickOutside = useCallback(() => {
96 setIsOpen(false)
97 setActive(null)
98 }, [setIsOpen, setActive])
99
100 useClickOutside(ref, handleClickOutside)
101
102 useEffect(() => {
103 if (!widthContainer || maxWidth > 0) return
104 setMaxWidth(widthContainer)
105 }, [widthContainer, maxWidth])
106
107 const scrollButtonIntoView = useCallback(
108 (currentIndex: number, previousIndex: number | null) => {
109 if (!menuContainerRef.current) return
110
111 const isMovingForward =
112 previousIndex !== null && currentIndex > previousIndex
113 const isMovingBackward =
114 previousIndex !== null && currentIndex < previousIndex
115
116 let targetIndex = currentIndex
117
118 if (isMovingForward) {
119 const nextIndex = currentIndex + 1
120 if (nextIndex < steps.length) {
121 targetIndex = nextIndex
122 }
123 } else if (isMovingBackward) {
124 const prevIndex = currentIndex - 1
125 if (prevIndex >= 0) {
126 targetIndex = prevIndex
127 }
128 }
129
130 const targetButton = menuContainerRef.current.querySelector(
131 `[data-step-index="${targetIndex}"]`
132 ) as HTMLElement
133
134 if (targetButton) {
135 targetButton.scrollIntoView({
136 behavior: "smooth",
137 block: "nearest",
138 inline: "center",
139 })
140 }
141 },
142 [steps.length]
143 )
144
145 const handleNavClick = useCallback(
146 (item: string) => {
147 if (active === item && isOpen) {
148 setIsOpen(false)
149 setActive(null)
150 return
151 }
152
153 const currentIndex = steps.findIndex((step) => step.id === item)
154 setActive(item)
155 setIsOpen(true)
156
157 if (currentIndex >= 0) {
158 setTimeout(() => {
159 scrollButtonIntoView(currentIndex, previousIndex)
160 }, 100)
161
162 setPreviousIndex(currentIndex)
163 }
164 },
165 [
166 active,
167 isOpen,
168 steps,
169 scrollButtonIntoView,
170 previousIndex,
171 setActive,
172 setIsOpen,
173 ]
174 )
175
176 const renderContent = useCallback(() => {
177 if (!active) return null
178
179 const step = steps.find((s) => s.id === active)
180 if (!step) return null
181
182 return (
183 <div className="space-y-4 pb-3">
184 <div className="space-y-2">
185 <h3 className="text-lg font-medium text-foreground">
186 {step.title}
187 </h3>
188 <p className="text-sm text-muted-foreground">{step.description}</p>
189 </div>
190 {step.content}
191 </div>
192 )
193 }, [active, steps])
194
195 const activeTitle = useMemo(() => {
196 if (!active) return ""
197 const step = steps.find((s) => s.id === active)
198 return step?.title || ""
199 }, [active, steps])
200
201 const navigationButtons = useMemo(
202 () =>
203 steps.map((step, index) => ({
204 id: step.id,
205 label: step.title,
206 step: (index + 1).toString(),
207 onClick: () => handleNavClick(step.id),
208 isActive: active === step.id,
209 isFirst: index === 0,
210 isLast: index === steps.length - 1,
211 })),
212 [steps, active, handleNavClick]
213 )
214
215 return (
216 <div
217 className={cn(
218 "space-y-2 w-full max-w-sm sm:max-w-lg mx-auto px-2 sm:px-0",
219 className
220 )}
221 >
222 {badgeText && (
223 <Badge
224 variant="outline"
225 className="bg-muted border-border text-muted-foreground"
226 >
227 {badgeText}
228 </Badge>
229 )}
230
231 <MotionConfig transition={transition}>
232 <div
233 className="w-full rounded-2xl shadow-[0_0_0_1px_rgba(0,0,0,0.08),0px_2px_2px_rgba(0,0,0,0.04),0px_8px_16px_-4px_rgba(0,0,0,0.04)] dark:shadow-[0_0_0_1px_rgba(255,252,240,0.08),0px_2px_2px_rgba(0,0,0,0.2),0px_8px_16px_-4px_rgba(0,0,0,0.3)] bg-background overflow-hidden"
234 ref={ref}
235 >
236 <div className="rounded-2xl">
237 <div className="overflow-hidden">
238 <AnimatePresence initial={false} mode="wait">
239 {isOpen ? (
240 <motion.div
241 key="expanded-content"
242 initial={{ height: 0 }}
243 animate={{ height: heightContent || 0 }}
244 exit={{ height: 0 }}
245 className=""
246 >
247 <div ref={contentRef} className="pt-2 px-2 sm:px-2">
248 <h4 className="text-sm font-medium text-foreground px-2">
249 {activeTitle}
250 </h4>
251
252 <div className="pb-1">
253 <div className="shadow-[0px_1px_1px_0px_rgba(0,0,0,0.05),0px_1px_1px_0px_rgba(255,252,240,0.5)_inset,0px_0px_0px_1px_hsla(0,0%,100%,0.1)_inset,0px_0px_1px_0px_rgba(28,27,26,0.5)] dark:shadow-[0px_1px_1px_0px_rgba(0,0,0,0.2),0px_1px_1px_0px_rgba(255,255,255,0.05)_inset,0px_0px_0px_1px_hsla(0,0%,100%,0.05)_inset,0px_0px_1px_0px_rgba(0,0,0,0.8)] bg-muted/50 rounded-[0.8rem] px-3 py-4 mt-3 mb-2">
254 {renderContent()}
255 </div>
256 </div>
257 </div>
258 </motion.div>
259 ) : null}
260 </AnimatePresence>
261 </div>
262
263 {/* Navigation bar */}
264 <div className="relative z-10">
265 <ScrollArea
266 className="w-full"
267 viewportClassName="scrollbar-hide"
268 maskHeight={16}
269 ref={(element) => {
270 if (element) {
271 menuContainerRef.current = element
272 menuRef(element)
273 }
274 }}
275 >
276 <div className="flex items-center p-[1px] w-max min-w-full">
277 {navigationButtons.map((button, index) => (
278 <button
279 key={button.id}
280 data-step-index={index}
281 onClick={button.onClick}
282 className={cn(
283 "text-sm text-muted-foreground transition-colors py-3 px-3 sm:py-4 sm:px-4 whitespace-nowrap shrink-0 flex items-center gap-2 min-h-[44px] sm:min-h-0",
284 button.isActive
285 ? "text-foreground font-medium bg-muted/50"
286 : "hover:bg-muted/60 active:bg-muted/70"
287 )}
288 >
289 <div className="text-[10px] w-5 h-5 sm:w-5 sm:h-5 flex items-center justify-center shadow-[0px_1px_1px_0px_hsla(0,0%,0%,0.02)_inset,0px_1px_1px_0px_hsla(0,0%,0%,0.02)_inset,0px_0px_0px_1px_rgba(255,255,255,0.25)] dark:shadow-[0px_1px_1px_0px_hsla(0,0%,100%,0.02)_inset,0px_1px_1px_0px_rgba(255,255,255,0.05)_inset,0px_0px_0px_1px_hsla(0,0%,100%,0.05)_inset,0px_0px_1px_0px_rgba(0,0,0,0.25)] font-bold rounded-md transition-all duration-300">
290 <span
291 className={cn(
292 "w-full rounded-md",
293 button.isActive
294 ? "bg-blue-300/20 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400"
295 : "bg-muted/50 text-muted-foreground"
296 )}
297 >
298 {button.step}
299 </span>
300 </div>
301 <span className="text-xs sm:text-sm font-medium text-foreground">
302 {button.label}
303 </span>
304 </button>
305 ))}
306 </div>
307 </ScrollArea>
308 </div>
309 </div>
310 </div>
311 </MotionConfig>
312 </div>
313 )
314 }
315)
316
317DynamicToolbarExpandable.displayName = "DynamicToolbarExpandable"
318
319// ________________________ HOOKS ________________________
320interface Bounds {
321 left: number
322 top: number
323 width: number
324 height: number
325}
326
327function useMeasure(): [
328 (node: HTMLElement | null) => void,
329 Bounds,
330 () => void,
331] {
332 const [bounds, setBounds] = useState<Bounds>({
333 left: 0,
334 top: 0,
335 width: 0,
336 height: 0,
337 })
338
339 const [node, setNode] = useState<HTMLElement | null>(null)
340 const observer = useRef<ResizeObserver | null>(null)
341
342 const disconnect = useCallback(() => {
343 if (observer.current) {
344 observer.current.disconnect()
345 }
346 }, [])
347
348 const ref = useCallback((node: HTMLElement | null) => {
349 setNode(node)
350 }, [])
351
352 useEffect(() => {
353 if (!node) return
354
355 if (observer.current) {
356 observer.current.disconnect()
357 }
358
359 observer.current = new ResizeObserver(([entry]) => {
360 if (entry && entry.contentRect) {
361 const { left, top, width, height } = entry.contentRect
362 setBounds({ left, top, width, height })
363 }
364 })
365
366 observer.current.observe(node)
367
368 return () => {
369 if (observer.current) {
370 observer.current.disconnect()
371 }
372 }
373 }, [node])
374
375 return [ref, bounds, disconnect]
376}
377
378function useClickOutside<T extends HTMLElement = HTMLElement>(
379 ref: RefObject<T | null>,
380 handler: (event: MouseEvent | TouchEvent) => void
381) {
382 useEffect(() => {
383 const listener = (event: MouseEvent | TouchEvent) => {
384 const el = ref?.current
385 if (!el || el.contains((event?.target as Node) || null)) {
386 return
387 }
388
389 handler(event)
390 }
391
392 document.addEventListener("mousedown", listener)
393 document.addEventListener("touchstart", listener)
394
395 return () => {
396 document.removeEventListener("mousedown", listener)
397 document.removeEventListener("touchstart", listener)
398 }
399 }, [ref, handler])
400}
401
402function useTouchPrimary() {
403 const [isTouchPrimary, setIsTouchPrimary] = useState(false)
404
405 useEffect(() => {
406 if (typeof window === "undefined") return
407
408 const controller = new AbortController()
409 const { signal } = controller
410
411 const handleTouch = () => {
412 const hasTouch = "ontouchstart" in window || navigator.maxTouchPoints > 0
413 const prefersTouch = window.matchMedia("(pointer: coarse)").matches
414 setIsTouchPrimary(hasTouch && prefersTouch)
415 }
416
417 const mq = window.matchMedia("(pointer: coarse)")
418 mq.addEventListener("change", handleTouch, { signal })
419 window.addEventListener("pointerdown", handleTouch, { signal })
420
421 handleTouch()
422
423 return () => controller.abort()
424 }, [])
425
426 return isTouchPrimary
427}
428
429// ________________________ MODIFIED SCROLL AREA ________________________
430// https://lina.sameer.sh/
431
432const ScrollAreaContext = React.createContext<boolean>(false)
433type Mask = {
434 top: boolean
435 bottom: boolean
436 left: boolean
437 right: boolean
438}
439
440const ScrollArea = React.forwardRef<
441 React.ComponentRef<typeof ScrollAreaPrimitive.Root>,
442 React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> & {
443 viewportClassName?: string
444 /**
445 * `maskHeight` is the height of the mask in pixels.
446 * pass `0` to disable the mask
447 * @default 30
448 */
449 maskHeight?: number
450 maskClassName?: string
451 }
452>(
453 (
454 {
455 className,
456 children,
457 scrollHideDelay = 0,
458 viewportClassName,
459 maskClassName,
460 maskHeight = 30,
461 ...props
462 },
463 ref
464 ) => {
465 const [showMask, setShowMask] = React.useState<Mask>({
466 top: false,
467 bottom: false,
468 left: false,
469 right: false,
470 })
471 const viewportRef = React.useRef<HTMLDivElement>(null)
472 const isTouch = useTouchPrimary()
473
474 const checkScrollability = React.useCallback(() => {
475 const element = viewportRef.current
476 if (!element) return
477
478 const {
479 scrollTop,
480 scrollLeft,
481 scrollWidth,
482 clientWidth,
483 scrollHeight,
484 clientHeight,
485 } = element
486 setShowMask((prev) => ({
487 ...prev,
488 top: scrollTop > 0,
489 bottom: scrollTop + clientHeight < scrollHeight - 1,
490 left: scrollLeft > 0,
491 right: scrollLeft + clientWidth < scrollWidth - 1,
492 }))
493 }, [])
494
495 React.useEffect(() => {
496 if (typeof window === "undefined") return
497
498 const element = viewportRef.current
499 if (!element) return
500
501 const controller = new AbortController()
502 const { signal } = controller
503
504 const resizeObserver = new ResizeObserver(checkScrollability)
505 resizeObserver.observe(element)
506
507 element.addEventListener("scroll", checkScrollability, { signal })
508 window.addEventListener("resize", checkScrollability, { signal })
509
510 checkScrollability()
511
512 return () => {
513 controller.abort()
514 resizeObserver.disconnect()
515 }
516 }, [checkScrollability, isTouch])
517
518 return (
519 <ScrollAreaContext.Provider value={isTouch}>
520 {isTouch ? (
521 <div
522 ref={ref}
523 role="group"
524 data-slot="scroll-area"
525 aria-roledescription="scroll area"
526 className={cn("relative overflow-hidden", className)}
527 {...props}
528 >
529 <div
530 ref={viewportRef}
531 data-slot="scroll-area-viewport"
532 className={cn(
533 "size-full overflow-auto rounded-[inherit]",
534 viewportClassName
535 )}
536 tabIndex={0}
537 >
538 {children}
539 </div>
540
541 {maskHeight > 0 && (
542 <ScrollMask
543 showMask={showMask}
544 className={maskClassName}
545 maskHeight={maskHeight}
546 />
547 )}
548 </div>
549 ) : (
550 <ScrollAreaPrimitive.Root
551 ref={ref}
552 data-slot="scroll-area"
553 scrollHideDelay={scrollHideDelay}
554 className={cn("relative overflow-hidden", className)}
555 {...props}
556 >
557 <ScrollAreaPrimitive.Viewport
558 ref={viewportRef}
559 data-slot="scroll-area-viewport"
560 className={cn("size-full rounded-[inherit]", viewportClassName)}
561 >
562 {children}
563 </ScrollAreaPrimitive.Viewport>
564
565 {maskHeight > 0 && (
566 <ScrollMask
567 showMask={showMask}
568 className={maskClassName}
569 maskHeight={maskHeight}
570 />
571 )}
572 <ScrollBar />
573 <ScrollAreaPrimitive.Corner />
574 </ScrollAreaPrimitive.Root>
575 )}
576 </ScrollAreaContext.Provider>
577 )
578 }
579)
580
581ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
582
583const ScrollBar = React.forwardRef<
584 React.ComponentRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
585 React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
586>(({ className, orientation = "vertical", ...props }, ref) => {
587 const isTouch = React.useContext(ScrollAreaContext)
588
589 if (isTouch) return null
590
591 return (
592 <ScrollAreaPrimitive.ScrollAreaScrollbar
593 ref={ref}
594 orientation={orientation}
595 data-slot="scroll-area-scrollbar"
596 className={cn(
597 "hover:bg-muted dark:hover:bg-muted/50 data-[state=visible]:fade-in-0 data-[state=hidden]:fade-out-0 data-[state=visible]:animate-in data-[state=hidden]:animate-out flex touch-none p-px transition-[colors] duration-150 select-none",
598 orientation === "vertical" &&
599 "h-full w-2.5 border-l border-l-transparent",
600 orientation === "horizontal" &&
601 "h-2.5 flex-col border-t border-t-transparent px-1 pr-1.25",
602 className
603 )}
604 {...props}
605 >
606 <ScrollAreaPrimitive.ScrollAreaThumb
607 data-slot="scroll-area-thumb"
608 className={cn(
609 "bg-border relative flex-1 origin-center rounded-full transition-[scale]",
610 orientation === "vertical" && "my-1 active:scale-y-95",
611 orientation === "horizontal" && "active:scale-x-98"
612 )}
613 />
614 </ScrollAreaPrimitive.ScrollAreaScrollbar>
615 )
616})
617
618ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
619
620const ScrollMask = ({
621 showMask,
622 maskHeight,
623 className,
624 ...props
625}: React.ComponentProps<"div"> & {
626 showMask: Mask
627 maskHeight: number
628}) => {
629 return (
630 <>
631 <div
632 {...props}
633 aria-hidden="true"
634 style={
635 {
636 "--top-fade-height": showMask.top ? `${maskHeight}px` : "0px",
637 "--bottom-fade-height": showMask.bottom ? `${maskHeight}px` : "0px",
638 } as React.CSSProperties
639 }
640 className={cn(
641 "pointer-events-none absolute inset-0 z-10",
642 "before:absolute before:inset-x-0 before:top-0 before:transition-[height,opacity] before:duration-300 before:content-['']",
643 "after:absolute after:inset-x-0 after:bottom-0 after:transition-[height,opacity] after:duration-300 after:content-['']",
644 "before:h-(--top-fade-height) after:h-(--bottom-fade-height)",
645 showMask.top ? "before:opacity-100" : "before:opacity-0",
646 showMask.bottom ? "after:opacity-100" : "after:opacity-0",
647 "before:from-background before:bg-gradient-to-b before:to-transparent",
648 "after:from-background after:bg-gradient-to-t after:to-transparent",
649 className
650 )}
651 />
652 <div
653 {...props}
654 aria-hidden="true"
655 style={
656 {
657 "--left-fade-width": showMask.left ? `${maskHeight}px` : "0px",
658 "--right-fade-width": showMask.right ? `${maskHeight}px` : "0px",
659 } as React.CSSProperties
660 }
661 className={cn(
662 "pointer-events-none absolute inset-0 z-10",
663 "before:absolute before:inset-y-0 before:left-0 before:transition-[width,opacity] before:duration-300 before:content-['']",
664 "after:absolute after:inset-y-0 after:right-0 after:transition-[width,opacity] after:duration-300 after:content-['']",
665 "before:w-(--left-fade-width) after:w-(--right-fade-width)",
666 showMask.left ? "before:opacity-100" : "before:opacity-0",
667 showMask.right ? "after:opacity-100" : "after:opacity-0",
668 "before:from-background before:bg-gradient-to-r before:to-transparent",
669 "after:from-background after:bg-gradient-to-l after:to-transparent",
670 className
671 )}
672 />
673 </>
674 )
675}
676
677export default function ToolbarExpandable(
678 props: DynamicToolbarExpandableProps
679) {
680 return <DynamicToolbarExpandable {...props} />
681}
682