1"use client"
2
3import React, {
4 createContext,
5 ReactNode,
6 useCallback,
7 useContext,
8 useEffect,
9 useMemo,
10 useRef,
11 useState,
12} from "react"
13import {
14 animate,
15 AnimatePresence,
16 motion,
17 MotionValue,
18 useAnimation,
19 useMotionValue,
20 useSpring,
21 useTransform,
22} from "motion/react"
23
24import { cn } from "@/lib/utils"
25
26// Interface to define the types for our Dock context
27interface DockContextType {
28 width: number // Width of the dock
29 hovered: boolean // If the dock is hovered
30 setIsZooming: (value: boolean) => void // Function to set zooming state
31 zoomLevel: MotionValue<number> // Motion value for zoom level
32 mouseX: MotionValue<number> // Motion value for mouse X position
33 animatingIndexes: number[] // Array of animating indexes
34 setAnimatingIndexes: (indexes: number[]) => void // Function to set animating indexes
35}
36
37// Initial width for the dock
38const INITIAL_WIDTH = 48
39
40// Create a context to manage Dock state
41const DockContext = createContext<DockContextType>({
42 width: 0,
43 hovered: false,
44 setIsZooming: () => {},
45 zoomLevel: null as any,
46 mouseX: null as any,
47 animatingIndexes: [],
48 setAnimatingIndexes: () => {},
49})
50
51// Custom hook to use Dock context
52const useDock = () => useContext(DockContext)
53
54// Props for the Dock component
55interface DockProps {
56 className?: string
57 children: ReactNode // React children to be rendered within the dock
58}
59
60// Main Dock component: orchestrating the dock's animation behavior
61function Dock({ className, children }: DockProps) {
62 const [hovered, setHovered] = useState(false) // State to track if the dock is hovered. When the mouse hovers over the dock, this state changes to true.
63 const [width, setWidth] = useState(0) // State to track the width of the dock. This dynamically updates based on the dock's current width.
64 const dockRef = useRef<HTMLDivElement>(null) // Reference to the dock element in the DOM. This allows direct manipulation and measurement of the dock.
65 const isZooming = useRef(false) // Reference to track if the zooming animation is active. This prevents conflicting animations.
66 const [animatingIndexes, setAnimatingIndexes] = useState<number[]>([]) // State to track which dock items are currently animating. This array holds the indices of animating items.
67
68 // Callback to toggle the zooming state. This ensures that we don't trigger hover animations while zooming.
69 const setIsZooming = useCallback((value: boolean) => {
70 isZooming.current = value // Update the zooming reference
71 setHovered(!value) // Update the hover state based on zooming
72 }, [])
73
74 const zoomLevel = useMotionValue(1) // Motion value for the zoom level of the dock. This provides a smooth zooming animation.
75
76 // Hook to handle window resize events and update the dock's width accordingly.
77 useWindowResize(() => {
78 setWidth(dockRef.current?.clientWidth || 0) // Set width to the dock's current width or 0 if undefined
79 })
80
81 const mouseX = useMotionValue(Infinity) // Motion value to track the mouse's X position relative to the viewport. Initialized to Infinity to denote no tracking initially.
82
83 return (
84 // Provide the dock's state and control methods to the rest of the application through context.
85 <DockContext.Provider
86 value={{
87 hovered, // Current hover state of the dock
88 setIsZooming, // Method to set the zooming state
89 width, // Current width of the dock
90 zoomLevel, // Current zoom level motion value
91 mouseX, // Current mouse X position motion value
92 animatingIndexes, // Current animating indexes
93 setAnimatingIndexes, // Method to set animating indexes
94 }}
95 >
96 <motion.div
97 ref={dockRef} // Reference to the dock element
98 // className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex items-end h-14 p-2 gap-3 bg-neutral-50 dark:bg-black bg-opacity-90 rounded-xl"
99 className={cn(
100 "absolute bottom-4 left-3/4 transform -translate-x-1/2 flex items-end h-14 p-2 gap-3 bg-opacity-90 rounded-xl",
101 " dark:bg-neutral-900 bg-neutral-50 p-2 no-underline shadow-sm transition-colors hover:bg-neutral-100 dark:hover:bg-neutral-800/80 ",
102 "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)]",
103 "shadow-[rgba(17,24,28,0.08)_0_0_0_1px,rgba(17,24,28,0.08)_0_1px_2px_-1px,rgba(17,24,28,0.04)_0_2px_4px]",
104 "dark:shadow-[0_1px_0_0_rgba(255,255,255,0.03)_inset,0_0_0_1px_rgba(255,255,255,0.03)_inset,0_0_0_1px_rgba(0,0,0,0.1),0_2px_2px_0_rgba(0,0,0,0.1),0_4px_4px_0_rgba(0,0,0,0.1),0_8px_8px_0_rgba(0,0,0,0.1)]",
105 className
106 )}
107 // Event handler for mouse movement within the dock
108 onMouseMove={(e) => {
109 mouseX.set(e.pageX) // Update the mouseX motion value to the current mouse position
110 if (!isZooming.current) {
111 // Only set hovered if not zooming
112 setHovered(true) // Set hovered state to true
113 }
114 }}
115 // Event handler for when the mouse leaves the dock
116 onMouseLeave={() => {
117 mouseX.set(Infinity) // Reset mouseX motion value
118 setHovered(false) // Set hovered state to false
119 }}
120 style={{
121 x: "-50%", // Center the dock horizontally
122 scale: zoomLevel, // Bind the zoom level to the scale style property
123 }}
124 >
125 {children} {/* Render the dock's children within the motion div */}
126 </motion.div>
127 </DockContext.Provider>
128 )
129}
130
131// Props for the DockCardInner component
132interface DockCardInnerProps {
133 src: string // Source URL for the image
134 id: string // Unique identifier for the card
135 children?: ReactNode // Optional children for the card
136}
137
138// DockCardInner component to display images and handle animation states
139function DockCardInner({ src, id, children }: DockCardInnerProps) {
140 const { animatingIndexes } = useDock() // Access the Dock context to get the animating indexes. This determines which cards are currently animating.
141
142 return (
143 <span className="relative flex justify-center items-center z-0 overflow-hidden w-full h-full rounded-md">
144 {/* Background image with a blur effect to give a depth illusion */}
145 <motion.img
146 className="absolute z-10 opacity-40 filter blur-md transform translate-y-2.5 scale-125 "
147 src={src}
148 alt=""
149 />
150
151 {/* AnimatePresence component to handle the entrance and exit animations of children - in our case, the "openIcon" */}
152 <AnimatePresence>
153 {animatingIndexes.includes(parseInt(id)) && children ? (
154 <motion.div
155 className="relative z-0 h-full w-full rounded-full"
156 initial={{ scale: 0, opacity: 0, filter: "blur(4px)" }}
157 animate={{
158 scale: 1,
159 opacity: 1,
160 filter: "blur(0px)",
161 transition: { type: "spring", delay: 0.2 }, // Animation to spring into place with a delay so our layoutId animations can be smooth
162 }}
163 exit={{
164 scale: 0,
165 opacity: 0,
166 filter: "blur(4px)",
167 transition: { duration: 0 }, // Exit animation with no delay
168 }}
169 >
170 <div className="h-full w-full flex flex-col items-center justify-center">
171 {/* Render the openIcon */}
172 {children}
173 </div>
174 </motion.div>
175 ) : null}
176 </AnimatePresence>
177
178 {/* Another AnimatePresence to handle layout animations */}
179 <AnimatePresence mode="popLayout">
180 {!animatingIndexes.includes(parseInt(id)) ? (
181 <motion.img
182 layoutId={id} // Unique identifier for layout animations
183 className="relative z-0 w-1/2 h-1/2 rounded-full border border-black/30 dark:border-white/10"
184 src={src}
185 alt=""
186 />
187 ) : null}
188 </AnimatePresence>
189 </span>
190 )
191}
192
193// Props for the DockCard component
194interface DockCardProps {
195 children: ReactNode // React children to be rendered within the dock card
196 id: string // Unique identifier for the dock card
197}
198
199// DockCard component: manages individual card behavior within the dock
200function DockCard({ children, id }: DockCardProps) {
201 const cardRef = useRef<HTMLButtonElement>(null) // Reference to the card button element for direct DOM manipulation and measurement
202 const [elCenterX, setElCenterX] = useState(0) // State to store the center X position of the card for accurate mouse interaction calculations
203 const dock = useDock() // Access the Dock context to get shared state and control functions
204
205 // Spring animation for the size of the card, providing a smooth and responsive scaling effect
206 const size = useSpring(INITIAL_WIDTH, {
207 stiffness: 320,
208 damping: 20,
209 mass: 0.1,
210 })
211
212 // Spring animation for the opacity of the card, enabling smooth fade-in and fade-out effects
213 const opacity = useSpring(0, {
214 stiffness: 300,
215 damping: 20,
216 })
217
218 // Custom hook to track mouse position and update the card size dynamically based on proximity to the mouse
219 useMousePosition(
220 {
221 onChange: ({ value }) => {
222 const mouseX = value.x
223 if (dock.width > 0) {
224 // Calculate transformed value based on mouse position and card center, using a cosine function for a smooth curve
225 const transformedValue =
226 INITIAL_WIDTH +
227 36 *
228 Math.cos((((mouseX - elCenterX) / dock.width) * Math.PI) / 2) **
229 12
230
231 // Only animate size if the dock is hovered
232 if (dock.hovered) {
233 animate(size, transformedValue)
234 }
235 }
236 },
237 },
238 [elCenterX, dock]
239 )
240
241 // Hook to update the center X position of the card on window resize for accurate mouse interaction
242 useWindowResize(() => {
243 const { x } = cardRef.current?.getBoundingClientRect() || { x: 0 }
244 setElCenterX(x + 24) // 24 is the half of INITIAL_WIDTH (48 / 2), centering the element
245 })
246
247 const isAnimating = useRef(false) // Reference to track if the card is currently animating to avoid conflicting animations
248 const controls = useAnimation() // Animation controls for managing card's Y position during the animation loop
249 const timeoutRef = useRef<number | null>(null) // Reference to manage timeout cleanup on component unmount
250
251 // Handle click event to start or stop the card's animation
252 const handleClick = () => {
253 if (!isAnimating.current) {
254 isAnimating.current = true
255 // Add the card's id to the animatingIndexes array in the Dock context
256 dock.setAnimatingIndexes([...dock.animatingIndexes, parseInt(id)])
257 opacity.set(0.5) // Set opacity for the animation
258 controls.start({
259 y: -24, // Move the card up by 24 pixels
260 transition: {
261 repeat: Infinity, // Repeat the animation indefinitely
262 repeatType: "reverse", // Reverse the direction of the animation each cycle
263 duration: 0.5, // Duration of each cycle
264 },
265 })
266 } else {
267 isAnimating.current = false
268 // Remove the card's id from the animatingIndexes array in the Dock context
269 dock.setAnimatingIndexes(
270 dock.animatingIndexes.filter((index) => index !== parseInt(id))
271 )
272 opacity.set(0) // Reset opacity
273 controls.start({
274 y: 0, // Reset Y position to the original state
275 transition: { duration: 0.5 }, // Smooth transition back to original state
276 })
277 }
278 }
279
280 // Cleanup timeout on component unmount to prevent memory leaks
281 useEffect(() => {
282 return () => clearTimeout(timeoutRef.current!)
283 }, [])
284
285 // Calculate the distance from the mouse position to the center of the card
286 const distance = useTransform(dock.mouseX, (val) => {
287 const bounds = cardRef.current?.getBoundingClientRect() ?? {
288 x: 0,
289 width: 0,
290 }
291 return val - bounds.x - bounds.width / 2 // Calculate distance to the center of the card
292 })
293
294 // Transform the calculated distance into a responsive width for the card
295 let widthSync = useTransform(distance, [-150, 0, 150], [40, 80, 40])
296 let width = useSpring(widthSync, { mass: 0.1, stiffness: 150, damping: 12 })
297
298 return (
299 <div className="flex flex-col items-center gap-1" key={id}>
300 {/* Motion button for the card, handling click events and animations */}
301 <motion.button
302 ref={cardRef} // Reference to the button element
303 className="rounded-lg border aspect-square dark:border-white/5 border-black/5 border-opacity-10 dark:bg-neutral-800 bg-neutral-100 saturate-90 brightness-90 transition-filter duration-200 hover:saturate-100 hover:brightness-112"
304 onClick={handleClick} // Click handler to start/stop animation
305 style={{
306 width: width, // Responsive width based on mouse distance
307 }}
308 animate={controls} // Animation controls for Y position
309 whileTap={{ scale: 0.95 }} // Scale down slightly on tap for a tactile feel
310 >
311 {children}{" "}
312 {/* Render the children of the DockCard inside the motion button */}
313 </motion.button>
314
315 {/* AnimatePresence to manage the presence and layout animations of the card's indicator */}
316 <AnimatePresence mode="popLayout">
317 {dock.animatingIndexes.includes(parseInt(id)) ? (
318 <motion.div
319 key={id} // Unique key for the motion div
320 layoutId={id} // Layout identifier for smooth layout animations
321 className="rounded-full"
322 style={{ opacity }} // Bind opacity to the animated opacity spring
323 >
324 <motion.div
325 exit={{ transition: { duration: 0 } }} // Exit transition with no duration for immediate removal
326 className="w-1.5 h-1.5 rounded-full dark:bg-white bg-black"
327 style={{ opacity }} // Bind opacity to the animated opacity spring
328 />
329 </motion.div>
330 ) : null}
331 </AnimatePresence>
332 </div>
333 )
334}
335
336// Divider component for the dock
337function DockDivider() {
338 return (
339 <motion.div
340 className="h-full flex items-center p-1.5 cursor-ns-resize"
341 drag="y"
342 dragConstraints={{ top: -100, bottom: 50 }}
343 >
344 <span className="w-0.5 h-full rounded dark:bg-neutral-100/10 bg-neutral-800/10 "></span>
345 </motion.div>
346 )
347}
348
349type UseWindowResizeCallback = (width: number, height: number) => void
350
351// Custom hook to handle window resize events and invoke a callback with the new dimensions
352function useWindowResize(callback: UseWindowResizeCallback) {
353 // Create a stable callback reference to ensure the latest callback is always used
354 const callbackRef = useCallbackRef(callback)
355
356 useEffect(() => {
357 // Function to handle window resize and call the provided callback with updated dimensions
358 const handleResize = () => {
359 callbackRef(window.innerWidth, window.innerHeight)
360 }
361
362 // Initial call to handleResize to capture the current window size
363 handleResize()
364 // Adding event listener for window resize events
365 window.addEventListener("resize", handleResize)
366
367 // Cleanup function to remove the event listener when the component unmounts or dependencies change
368 return () => {
369 window.removeEventListener("resize", handleResize)
370 }
371 }, [callbackRef]) // Dependency array includes the stable callback reference
372}
373
374// Custom hook to create a stable callback reference
375function useCallbackRef<T extends (...args: any[]) => any>(callback: T): T {
376 // Use a ref to store the callback
377 const callbackRef = useRef(callback)
378
379 // Update the ref with the latest callback whenever it changes
380 useEffect(() => {
381 callbackRef.current = callback
382 })
383
384 // Return a memoized version of the callback that always uses the latest callback stored in the ref
385 return useMemo(() => ((...args) => callbackRef.current?.(...args)) as T, [])
386}
387
388// Interface for mouse position options
389interface MousePositionOptions {
390 onChange?: (position: { value: { x: number; y: number } }) => void
391}
392
393// Custom hook to track mouse position and animate values accordingly
394export function useMousePosition(
395 options: MousePositionOptions = {}, // Options to customize behavior, including an onChange callback
396 deps: readonly any[] = [] // Dependencies array to determine when the effect should re-run
397) {
398 const { onChange } = options // Destructure onChange from options for use in the effect
399
400 // Create motion values for x and y coordinates, initialized to 0
401 const x = useMotionValue(0)
402 const y = useMotionValue(0)
403
404 useEffect(() => {
405 // Function to handle mouse move events, animating the x and y motion values to the current mouse coordinates
406 const handleMouseMove = (event: MouseEvent) => {
407 animate(x, event.clientX)
408 animate(y, event.clientY)
409 }
410
411 // Function to handle changes in the motion values, calling the onChange callback if it exists
412 const handleChange = () => {
413 if (onChange) {
414 onChange({ value: { x: x.get(), y: y.get() } })
415 }
416 }
417
418 // Subscribe to changes in the x and y motion values
419 const unsubscribeX = x.on("change", handleChange)
420 const unsubscribeY = y.on("change", handleChange)
421
422 // Add event listener for mouse move events
423 window.addEventListener("mousemove", handleMouseMove)
424
425 // Cleanup function to remove event listener and unsubscribe from motion value changes
426 return () => {
427 window.removeEventListener("mousemove", handleMouseMove)
428 unsubscribeX()
429 unsubscribeY()
430 }
431 }, [x, y, onChange, ...deps]) // Dependency array includes x, y, onChange, and any additional dependencies
432
433 // Memoize and return the motion values for x and y coordinates
434 return useMemo(
435 () => ({
436 x, // Motion value for x coordinate
437 y, // Motion value for y coordinate
438 }),
439 [x, y] // Dependencies for the memoized return value
440 )
441}
442
443export { Dock, DockCard, DockCardInner, DockDivider, useDock }
444export default Dock
445