1"use client"
2
3import React, {
4 createContext,
5 ReactNode,
6 useCallback,
7 useContext,
8 useEffect,
9 useReducer,
10 useRef,
11 useState,
12} from "react"
13import { AnimatePresence, motion, useWillChange } from "motion/react"
14
15const stiffness = 400
16const damping = 30
17const MIN_WIDTH = 691
18const MAX_HEIGHT_MOBILE_ULTRA = 400
19const MAX_HEIGHT_MOBILE_MASSIVE = 700
20
21const min = (a: number, b: number) => (a < b ? a : b)
22
23export type SizePresets =
24 | "reset"
25 | "empty"
26 | "default"
27 | "compact"
28 | "compactLong"
29 | "large"
30 | "long"
31 | "minimalLeading"
32 | "minimalTrailing"
33 | "compactMedium"
34 | "medium"
35 | "tall"
36 | "ultra"
37 | "massive"
38
39const SIZE_PRESETS = {
40 RESET: "reset",
41 EMPTY: "empty",
42 DEFAULT: "default",
43 COMPACT: "compact",
44 COMPACT_LONG: "compactLong",
45 LARGE: "large",
46 LONG: "long",
47 MINIMAL_LEADING: "minimalLeading",
48 MINIMAL_TRAILING: "minimalTrailing",
49 COMPACT_MEDIUM: "compactMedium",
50 MEDIUM: "medium",
51 TALL: "tall",
52 ULTRA: "ultra",
53 MASSIVE: "massive",
54} as const
55
56type Preset = {
57 width: number
58 height?: number
59 aspectRatio: number
60 borderRadius: number
61}
62
63const DynamicIslandSizePresets: Record<SizePresets, Preset> = {
64 [SIZE_PRESETS.RESET]: {
65 width: 150,
66 aspectRatio: 1,
67 borderRadius: 20,
68 },
69 [SIZE_PRESETS.EMPTY]: {
70 width: 0,
71 aspectRatio: 0,
72 borderRadius: 0,
73 },
74 [SIZE_PRESETS.DEFAULT]: {
75 width: 150,
76 aspectRatio: 44 / 150,
77 borderRadius: 46,
78 },
79 [SIZE_PRESETS.MINIMAL_LEADING]: {
80 width: 52.33,
81 aspectRatio: 44 / 52.33,
82 borderRadius: 22,
83 },
84 [SIZE_PRESETS.MINIMAL_TRAILING]: {
85 width: 52.33,
86 aspectRatio: 44 / 52.33,
87 borderRadius: 22,
88 },
89 [SIZE_PRESETS.COMPACT]: {
90 width: 235,
91 aspectRatio: 44 / 235,
92 borderRadius: 46,
93 },
94 [SIZE_PRESETS.COMPACT_LONG]: {
95 width: 300,
96 aspectRatio: 44 / 235,
97 borderRadius: 46,
98 },
99 [SIZE_PRESETS.COMPACT_MEDIUM]: {
100 width: 351,
101 aspectRatio: 64 / 371,
102 borderRadius: 44,
103 },
104 [SIZE_PRESETS.LONG]: {
105 width: 371,
106 aspectRatio: 84 / 371,
107 borderRadius: 42,
108 },
109 [SIZE_PRESETS.MEDIUM]: {
110 width: 371,
111 aspectRatio: 210 / 371,
112 borderRadius: 22,
113 },
114 [SIZE_PRESETS.LARGE]: {
115 width: 371,
116 aspectRatio: 84 / 371,
117 borderRadius: 42,
118 },
119 [SIZE_PRESETS.TALL]: {
120 width: 371,
121 aspectRatio: 210 / 371,
122 borderRadius: 42,
123 },
124 [SIZE_PRESETS.ULTRA]: {
125 width: 630,
126 aspectRatio: 630 / 800,
127 borderRadius: 42,
128 },
129 [SIZE_PRESETS.MASSIVE]: {
130 width: 891,
131 height: 1900,
132 aspectRatio: 891 / 891,
133 borderRadius: 42,
134 },
135}
136
137type BlobStateType = {
138 size: SizePresets
139 previousSize: SizePresets | undefined
140 animationQueue: Array<{ size: SizePresets; delay: number }>
141 isAnimating: boolean
142}
143
144type BlobAction =
145 | { type: "SET_SIZE"; newSize: SizePresets }
146 | { type: "INITIALIZE"; firstState: SizePresets }
147 | {
148 type: "SCHEDULE_ANIMATION"
149 animationSteps: Array<{ size: SizePresets; delay: number }>
150 }
151 | { type: "ANIMATION_END" }
152
153type BlobContextType = {
154 state: BlobStateType
155 dispatch: React.Dispatch<BlobAction>
156 setSize: (size: SizePresets) => void
157 scheduleAnimation: (
158 animationSteps: Array<{ size: SizePresets; delay: number }>
159 ) => void
160 presets: Record<SizePresets, Preset>
161}
162
163const BlobContext = createContext<BlobContextType | undefined>(undefined)
164
165const blobReducer = (
166 state: BlobStateType,
167 action: BlobAction
168): BlobStateType => {
169 switch (action.type) {
170 case "SET_SIZE":
171 return {
172 ...state,
173 size: action.newSize,
174 previousSize: state.size,
175 isAnimating: false, // Only set isAnimating to true if there are more steps
176 }
177 case "SCHEDULE_ANIMATION":
178 return {
179 ...state,
180 animationQueue: action.animationSteps,
181 isAnimating: action.animationSteps.length > 0,
182 }
183 case "INITIALIZE":
184 return {
185 ...state,
186 size: action.firstState,
187 previousSize: SIZE_PRESETS.EMPTY,
188 isAnimating: false,
189 }
190 case "ANIMATION_END":
191 return {
192 ...state,
193 isAnimating: false,
194 }
195 default:
196 return state
197 }
198}
199
200interface DynamicIslandProviderProps {
201 children: React.ReactNode
202 initialSize?: SizePresets
203 initialAnimation?: Array<{ size: SizePresets; delay: number }>
204}
205
206const DynamicIslandProvider: React.FC<DynamicIslandProviderProps> = ({
207 children,
208 initialSize = SIZE_PRESETS.DEFAULT,
209 initialAnimation = [],
210}) => {
211 const initialState: BlobStateType = {
212 size: initialSize,
213 previousSize: SIZE_PRESETS.EMPTY,
214 animationQueue: initialAnimation,
215 isAnimating: initialAnimation.length > 0,
216 }
217
218 const [state, dispatch] = useReducer(blobReducer, initialState)
219
220 useEffect(() => {
221 const processQueue = async () => {
222 for (const step of state.animationQueue) {
223 await new Promise((resolve) => setTimeout(resolve, step.delay))
224 dispatch({ type: "SET_SIZE", newSize: step.size })
225 }
226 dispatch({ type: "ANIMATION_END" })
227 }
228
229 if (state.animationQueue.length > 0) {
230 processQueue()
231 }
232 }, [state.animationQueue])
233
234 // biome-ignore lint/correctness/useExhaustiveDependencies: needed for dispatch
235 const setSize = useCallback(
236 (newSize: SizePresets) => {
237 if (state.previousSize !== newSize && newSize !== state.size) {
238 dispatch({ type: "SET_SIZE", newSize })
239 }
240 },
241 [state.previousSize, state.size, dispatch]
242 )
243
244 // biome-ignore lint/correctness/useExhaustiveDependencies: needed for dispatch
245 const scheduleAnimation = useCallback(
246 (animationSteps: Array<{ size: SizePresets; delay: number }>) => {
247 dispatch({ type: "SCHEDULE_ANIMATION", animationSteps })
248 },
249 [dispatch]
250 )
251
252 const contextValue = {
253 state,
254 dispatch,
255 setSize,
256 scheduleAnimation,
257 presets: DynamicIslandSizePresets,
258 }
259
260 return (
261 <BlobContext.Provider value={contextValue}>{children}</BlobContext.Provider>
262 )
263}
264
265const useDynamicIslandSize = () => {
266 const context = useContext(BlobContext)
267 if (!context) {
268 throw new Error(
269 "useDynamicIslandSize must be used within a DynamicIslandProvider"
270 )
271 }
272 return context
273}
274
275const useScheduledAnimations = (
276 animations: Array<{ size: SizePresets; delay: number }>
277) => {
278 const { scheduleAnimation } = useDynamicIslandSize()
279 const animationsRef = useRef(animations)
280
281 useEffect(() => {
282 scheduleAnimation(animationsRef.current)
283 }, [scheduleAnimation])
284}
285
286const DynamicIslandContainer = ({ children }: { children: ReactNode }) => {
287 return (
288 <div className="z-10 flex h-full w-full items-end justify-center bg-transparent">
289 {children}
290 </div>
291 )
292}
293
294const DynamicIsland = ({
295 children,
296 id,
297 ...props
298}: {
299 children: ReactNode
300 id: string
301}) => {
302 const willChange = useWillChange()
303 const [screenSize, setScreenSize] = useState("desktop")
304
305 useEffect(() => {
306 const handleResize = () => {
307 if (window.innerWidth <= 640) {
308 setScreenSize("mobile")
309 } else if (window.innerWidth <= 1024) {
310 setScreenSize("tablet")
311 } else {
312 setScreenSize("desktop")
313 }
314 }
315
316 handleResize()
317 window.addEventListener("resize", handleResize)
318 return () => window.removeEventListener("resize", handleResize)
319 }, [])
320
321 return (
322 <DynamicIslandContainer>
323 <DynamicIslandContent
324 id={id}
325 willChange={willChange}
326 screenSize={screenSize}
327 {...props}
328 >
329 {children}
330 </DynamicIslandContent>
331 </DynamicIslandContainer>
332 )
333}
334
335const calculateDimensions = (
336 size: SizePresets,
337 screenSize: string,
338 currentSize: Preset
339): { width: string; height: number } => {
340 const isMassiveOnMobile = size === "massive" && screenSize === "mobile"
341 const isUltraOnMobile = size === "ultra" && screenSize === "mobile"
342
343 if (isMassiveOnMobile) {
344 return { width: "350px", height: MAX_HEIGHT_MOBILE_MASSIVE }
345 }
346
347 if (isUltraOnMobile) {
348 return { width: "350px", height: MAX_HEIGHT_MOBILE_ULTRA }
349 }
350
351 const width = min(currentSize.width, MIN_WIDTH)
352 return { width: `${width}px`, height: currentSize.aspectRatio * width }
353}
354
355const DynamicIslandContent = ({
356 children,
357 id,
358 willChange,
359 screenSize,
360 ...props
361}: {
362 children: React.ReactNode
363 id: string
364 willChange: any
365 screenSize: string
366 [key: string]: any
367}) => {
368 const { state, presets } = useDynamicIslandSize()
369 const currentSize = presets[state.size]
370
371 const dimensions = calculateDimensions(state.size, screenSize, currentSize)
372
373 return (
374 <motion.div
375 id={id}
376 className="mx-auto h-0 w-0 items-center justify-center border border-black/10 bg-black text-center text-black transition duration-300 ease-in-out focus-within:bg-neutral-900 hover:shadow-md dark:border dark:border-white/5 dark:focus-within:bg-black"
377 animate={{
378 width: dimensions.width,
379 height: dimensions.height,
380 borderRadius: currentSize.borderRadius,
381 transition: {
382 type: "spring",
383 stiffness,
384 damping,
385 },
386 clipPath: `none`,
387 transitionEnd: {
388 clipPath: `url(#squircle-${state.size})`,
389 },
390 }}
391 style={{ willChange }}
392 {...props}
393 >
394 <AnimatePresence>{children}</AnimatePresence>
395 </motion.div>
396 )
397}
398
399type DynamicContainerProps = {
400 className?: string
401 children?: React.ReactNode
402}
403
404const DynamicContainer = ({ className, children }: DynamicContainerProps) => {
405 const willChange = useWillChange()
406 const { state } = useDynamicIslandSize()
407 const { size, previousSize } = state
408
409 const isSizeChanged = size !== previousSize
410
411 const initialState = {
412 opacity: size === previousSize ? 1 : 0,
413 scale: size === previousSize ? 1 : 0.9,
414 y: size === previousSize ? 0 : 5,
415 }
416
417 const animateState = {
418 opacity: 1,
419 scale: 1,
420 y: 0,
421 }
422
423 const transition = {
424 type: "spring" as const,
425 stiffness,
426 damping,
427 duration: isSizeChanged ? 0.5 : 0.8,
428 }
429
430 return (
431 <motion.div
432 initial={initialState}
433 animate={animateState}
434 transition={transition}
435 exit={{ opacity: 0, filter: "blur(10px)", scale: 0.95, y: 20 }}
436 style={{ willChange }}
437 className={className}
438 >
439 {children}
440 </motion.div>
441 )
442}
443
444type DynamicChildrenProps = {
445 className?: string
446 children?: React.ReactNode
447}
448
449const DynamicDiv = ({ className, children }: DynamicChildrenProps) => {
450 const { state } = useDynamicIslandSize()
451 const { size, previousSize } = state
452 const willChange = useWillChange()
453
454 return (
455 <motion.div
456 initial={{
457 opacity: size === previousSize ? 1 : 0,
458 scale: size === previousSize ? 1 : 0.9,
459 }}
460 animate={{
461 opacity: size === previousSize ? 0 : 1,
462 scale: size === previousSize ? 0.9 : 1,
463 transition: {
464 type: "spring",
465 stiffness,
466 damping,
467 },
468 }}
469 exit={{ opacity: 0, filter: "blur(10px)", scale: 0 }}
470 style={{ willChange }}
471 className={className}
472 >
473 {children}
474 </motion.div>
475 )
476}
477
478type MotionProps = {
479 className: string
480 children: React.ReactNode
481}
482
483const DynamicTitle = ({ className, children }: MotionProps) => {
484 const { state } = useDynamicIslandSize()
485 const { size, previousSize } = state
486 const willChange = useWillChange()
487
488 return (
489 <motion.h3
490 className={className}
491 initial={{ opacity: 0, scale: 0 }}
492 animate={{
493 opacity: size === previousSize ? 0 : 1,
494 scale: size === previousSize ? 0.9 : 1,
495 transition: { type: "spring", stiffness, damping },
496 }}
497 style={{ willChange }}
498 >
499 {children}
500 </motion.h3>
501 )
502}
503
504const DynamicDescription = ({ className, children }: MotionProps) => {
505 const { state } = useDynamicIslandSize()
506 const { size, previousSize } = state
507 const willChange = useWillChange()
508
509 return (
510 <motion.p
511 className={className}
512 initial={{ opacity: 0, scale: 0 }}
513 animate={{
514 opacity: size === previousSize ? 0 : 1,
515 scale: size === previousSize ? 0.9 : 1,
516 transition: { type: "spring", stiffness, damping },
517 }}
518 style={{ willChange }}
519 >
520 {children}
521 </motion.p>
522 )
523}
524
525export {
526 DynamicContainer,
527 DynamicTitle,
528 DynamicDescription,
529 DynamicIsland,
530 SIZE_PRESETS,
531 stiffness,
532 DynamicDiv,
533 damping,
534 DynamicIslandSizePresets,
535 BlobContext,
536 useDynamicIslandSize,
537 useScheduledAnimations,
538 DynamicIslandProvider,
539}
540
541export default DynamicIsland
542