Skip to content

UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.

fix: resolve consistent-return issues across Magic UI components (#912)

Yeom-JinHoa1a761ef5a4e
diff --git a/apps/www/public/llms-full.txt b/apps/www/public/llms-full.txt
index 5dd0ebc9..14037f8d 100644
--- a/apps/www/public/llms-full.txt
+++ b/apps/www/public/llms-full.txt
@@ -2428,28 +2428,32 @@ export function AnimatedGridPattern({
useEffect(() => {
const element = containerRef.current
- if (!element) return
-
- const resizeObserver = new ResizeObserver((entries) => {
- for (const entry of entries) {
- setDimensions((currentDimensions) => {
- const nextWidth = entry.contentRect.width
- const nextHeight = entry.contentRect.height
- if (
- currentDimensions.width === nextWidth &&
- currentDimensions.height === nextHeight
- ) {
- return currentDimensions
- }
- return { width: nextWidth, height: nextHeight }
- })
- }
- })
+ let resizeObserver: ResizeObserver | null = null
+
+ if (element) {
+ resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ setDimensions((currentDimensions) => {
+ const nextWidth = entry.contentRect.width
+ const nextHeight = entry.contentRect.height
+ if (
+ currentDimensions.width === nextWidth &&
+ currentDimensions.height === nextHeight
+ ) {
+ return currentDimensions
+ }
+ return { width: nextWidth, height: nextHeight }
+ })
+ }
+ })
- resizeObserver.observe(element)
+ resizeObserver.observe(element)
+ }
return () => {
- resizeObserver.disconnect()
+ if (resizeObserver) {
+ resizeObserver.disconnect()
+ }
}
}, [])
@@ -2580,12 +2584,18 @@ export const AnimatedList = React.memo(
)
useEffect(() => {
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
if (index < childrenArray.length - 1) {
- const timeout = setTimeout(() => {
+ timeout = setTimeout(() => {
setIndex((prevIndex) => (prevIndex + 1) % childrenArray.length)
}, delay)
+ }
- return () => clearTimeout(timeout)
+ return () => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
}
}, [index, delay, childrenArray.length])
@@ -4982,8 +4992,17 @@ export const CoolMode: React.FC<CoolModeProps> = ({ children, options }) => {
const ref = useRef<HTMLSpanElement>(null)
useEffect(() => {
- if (ref.current) {
- return applyParticleEffect(ref.current, options)
+ const element = ref.current
+ let cleanup: (() => void) | null = null
+
+ if (element) {
+ cleanup = applyParticleEffect(element, options)
+ }
+
+ return () => {
+ if (cleanup) {
+ cleanup()
+ }
}
}, [options])
@@ -6730,66 +6749,70 @@ export const FlickeringGrid: React.FC<FlickeringGridProps> = ({
useEffect(() => {
const canvas = canvasRef.current
const container = containerRef.current
- if (!canvas || !container) return
-
- const ctx = canvas.getContext("2d")
- if (!ctx) return
-
- let animationFrameId: number
- let gridParams: ReturnType<typeof setupCanvas>
-
- const updateCanvasSize = () => {
- const newWidth = width || container.clientWidth
- const newHeight = height || container.clientHeight
- setCanvasSize({ width: newWidth, height: newHeight })
- gridParams = setupCanvas(canvas, newWidth, newHeight)
- }
-
- updateCanvasSize()
-
- let lastTime = 0
- const animate = (time: number) => {
- if (!isInView) return
-
- const deltaTime = (time - lastTime) / 1000
- lastTime = time
-
- updateSquares(gridParams.squares, deltaTime)
- drawGrid(
- ctx,
- canvas.width,
- canvas.height,
- gridParams.cols,
- gridParams.rows,
- gridParams.squares,
- gridParams.dpr
- )
- animationFrameId = requestAnimationFrame(animate)
- }
+ const ctx = canvas?.getContext("2d") ?? null
+ let animationFrameId: number | null = null
+ let resizeObserver: ResizeObserver | null = null
+ let intersectionObserver: IntersectionObserver | null = null
+ let gridParams: ReturnType<typeof setupCanvas> | null = null
+
+ if (canvas && container && ctx) {
+ const updateCanvasSize = () => {
+ const newWidth = width || container.clientWidth
+ const newHeight = height || container.clientHeight
+ setCanvasSize({ width: newWidth, height: newHeight })
+ gridParams = setupCanvas(canvas, newWidth, newHeight)
+ }
- const resizeObserver = new ResizeObserver(() => {
updateCanvasSize()
- })
- resizeObserver.observe(container)
+ let lastTime = 0
+ const animate = (time: number) => {
+ if (!isInView || !gridParams) return
+
+ const deltaTime = (time - lastTime) / 1000
+ lastTime = time
+
+ updateSquares(gridParams.squares, deltaTime)
+ drawGrid(
+ ctx,
+ canvas.width,
+ canvas.height,
+ gridParams.cols,
+ gridParams.rows,
+ gridParams.squares,
+ gridParams.dpr
+ )
+ animationFrameId = requestAnimationFrame(animate)
+ }
- const intersectionObserver = new IntersectionObserver(
- ([entry]) => {
- setIsInView(entry.isIntersecting)
- },
- { threshold: 0 }
- )
+ resizeObserver = new ResizeObserver(() => {
+ updateCanvasSize()
+ })
+ resizeObserver.observe(container)
- intersectionObserver.observe(canvas)
+ intersectionObserver = new IntersectionObserver(
+ ([entry]) => {
+ setIsInView(entry.isIntersecting)
+ },
+ { threshold: 0 }
+ )
+ intersectionObserver.observe(canvas)
- if (isInView) {
- animationFrameId = requestAnimationFrame(animate)
+ if (isInView) {
+ animationFrameId = requestAnimationFrame(animate)
+ }
}
return () => {
- cancelAnimationFrame(animationFrameId)
- resizeObserver.disconnect()
- intersectionObserver.disconnect()
+ if (animationFrameId !== null) {
+ cancelAnimationFrame(animationFrameId)
+ }
+ if (resizeObserver) {
+ resizeObserver.disconnect()
+ }
+ if (intersectionObserver) {
+ intersectionObserver.disconnect()
+ }
}
}, [setupCanvas, updateSquares, drawGrid, width, height, isInView])
@@ -7456,37 +7479,40 @@ export function Highlighter({
const shouldShow = !isView || isInView
useEffect(() => {
- if (!shouldShow) return
-
const element = elementRef.current
- if (!element) return
-
- const annotationConfig = {
- type: action,
- color,
- strokeWidth,
- animationDuration,
- iterations,
- padding,
- multiline,
- }
-
- const annotation = annotate(element, annotationConfig)
+ let resizeObserver: ResizeObserver | null = null
+
+ if (shouldShow && element) {
+ const annotationConfig = {
+ type: action,
+ color,
+ strokeWidth,
+ animationDuration,
+ iterations,
+ padding,
+ multiline,
+ }
- annotationRef.current = annotation
- annotationRef.current.show()
+ const annotation = annotate(element, annotationConfig)
- const resizeObserver = new ResizeObserver(() => {
- annotation.hide()
+ annotationRef.current = annotation
annotation.show()
- })
- resizeObserver.observe(element)
- resizeObserver.observe(document.body)
+ resizeObserver = new ResizeObserver(() => {
+ annotation.hide()
+ annotation.show()
+ })
+
+ resizeObserver.observe(element)
+ resizeObserver.observe(document.body)
+ }
return () => {
- if (element) {
- annotate(element, { type: action }).remove()
+ if (annotationRef.current) {
+ annotationRef.current.remove()
+ annotationRef.current = null
+ }
+ if (resizeObserver) {
resizeObserver.disconnect()
}
}
@@ -7586,37 +7612,40 @@ export function Highlighter({
const shouldShow = !isView || isInView
useEffect(() => {
- if (!shouldShow) return
-
const element = elementRef.current
- if (!element) return
-
- const annotationConfig = {
- type: action,
- color,
- strokeWidth,
- animationDuration,
- iterations,
- padding,
- multiline,
- }
-
- const annotation = annotate(element, annotationConfig)
+ let resizeObserver: ResizeObserver | null = null
+
+ if (shouldShow && element) {
+ const annotationConfig = {
+ type: action,
+ color,
+ strokeWidth,
+ animationDuration,
+ iterations,
+ padding,
+ multiline,
+ }
- annotationRef.current = annotation
- annotationRef.current.show()
+ const annotation = annotate(element, annotationConfig)
- const resizeObserver = new ResizeObserver(() => {
- annotation.hide()
+ annotationRef.current = annotation
annotation.show()
- })
- resizeObserver.observe(element)
- resizeObserver.observe(document.body)
+ resizeObserver = new ResizeObserver(() => {
+ annotation.hide()
+ annotation.show()
+ })
+
+ resizeObserver.observe(element)
+ resizeObserver.observe(document.body)
+ }
return () => {
- if (element) {
- annotate(element, { type: action }).remove()
+ if (annotationRef.current) {
+ annotationRef.current.remove()
+ annotationRef.current = null
+ }
+ if (resizeObserver) {
resizeObserver.disconnect()
}
}
@@ -7771,38 +7800,43 @@ export function HyperText({
// Handle scramble animation
useEffect(() => {
- if (!isAnimating) return
+ let animationFrameId: number | null = null
- const maxIterations = children.length
- const startTime = performance.now()
- let animationFrameId: number
+ if (isAnimating) {
+ const maxIterations = children.length
+ const startTime = performance.now()
- const animate = (currentTime: number) => {
- const elapsed = currentTime - startTime
- const progress = Math.min(elapsed / duration, 1)
+ const animate = (currentTime: number) => {
+ const elapsed = currentTime - startTime
+ const progress = Math.min(elapsed / duration, 1)
- iterationCount.current = progress * maxIterations
+ iterationCount.current = progress * maxIterations
- setDisplayText((currentText) =>
- currentText.map((letter, index) =>
- letter === " "
- ? letter
- : index <= iterationCount.current
- ? children[index]
- : characterSet[getRandomInt(characterSet.length)]
+ setDisplayText((currentText) =>
+ currentText.map((letter, index) =>
+ letter === " "
+ ? letter
+ : index <= iterationCount.current
+ ? children[index]
+ : characterSet[getRandomInt(characterSet.length)]
+ )
)
- )
- if (progress < 1) {
- animationFrameId = requestAnimationFrame(animate)
- } else {
- setIsAnimating(false)
+ if (progress < 1) {
+ animationFrameId = requestAnimationFrame(animate)
+ } else {
+ setIsAnimating(false)
+ }
}
- }
- animationFrameId = requestAnimationFrame(animate)
+ animationFrameId = requestAnimationFrame(animate)
+ }
- return () => cancelAnimationFrame(animationFrameId)
+ return () => {
+ if (animationFrameId !== null) {
+ cancelAnimationFrame(animationFrameId)
+ }
+ }
}, [children, duration, isAnimating, characterSet])
return (
@@ -8060,88 +8094,91 @@ export function IconCloud({ icons, images }: IconCloudProps) {
useEffect(() => {
const canvas = canvasRef.current
const ctx = canvas?.getContext("2d")
- if (!canvas || !ctx) return
-
- const animate = () => {
- ctx.clearRect(0, 0, canvas.width, canvas.height)
-
- const centerX = canvas.width / 2
- const centerY = canvas.height / 2
- const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY)
- const dx = mousePos.x - centerX
- const dy = mousePos.y - centerY
- const distance = Math.sqrt(dx * dx + dy * dy)
- const speed = 0.003 + (distance / maxDistance) * 0.01
-
- if (targetRotation) {
- const elapsed = performance.now() - targetRotation.startTime
- const progress = Math.min(1, elapsed / targetRotation.duration)
- const easedProgress = easeOutCubic(progress)
-
- rotationRef.current = {
- x:
- targetRotation.startX +
- (targetRotation.x - targetRotation.startX) * easedProgress,
- y:
- targetRotation.startY +
- (targetRotation.y - targetRotation.startY) * easedProgress,
- }
+ if (canvas && ctx) {
+ const animate = () => {
+ ctx.clearRect(0, 0, canvas.width, canvas.height)
+
+ const centerX = canvas.width / 2
+ const centerY = canvas.height / 2
+ const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY)
+ const dx = mousePos.x - centerX
+ const dy = mousePos.y - centerY
+ const distance = Math.sqrt(dx * dx + dy * dy)
+ const speed = 0.003 + (distance / maxDistance) * 0.01
+
+ if (targetRotation) {
+ const elapsed = performance.now() - targetRotation.startTime
+ const progress = Math.min(1, elapsed / targetRotation.duration)
+ const easedProgress = easeOutCubic(progress)
+
+ rotationRef.current = {
+ x:
+ targetRotation.startX +
+ (targetRotation.x - targetRotation.startX) * easedProgress,
+ y:
+ targetRotation.startY +
+ (targetRotation.y - targetRotation.startY) * easedProgress,
+ }
- if (progress >= 1) {
- setTargetRotation(null)
- }
- } else if (!isDragging) {
- rotationRef.current = {
- x: rotationRef.current.x + (dy / canvas.height) * speed,
- y: rotationRef.current.y + (dx / canvas.width) * speed,
+ if (progress >= 1) {
+ setTargetRotation(null)
+ }
+ } else if (!isDragging) {
+ rotationRef.current = {
+ x: rotationRef.current.x + (dy / canvas.height) * speed,
+ y: rotationRef.current.y + (dx / canvas.width) * speed,
+ }
}
- }
-
- iconPositions.forEach((icon, index) => {
- const cosX = Math.cos(rotationRef.current.x)
- const sinX = Math.sin(rotationRef.current.x)
- const cosY = Math.cos(rotationRef.current.y)
- const sinY = Math.sin(rotationRef.current.y)
- const rotatedX = icon.x * cosY - icon.z * sinY
- const rotatedZ = icon.x * sinY + icon.z * cosY
- const rotatedY = icon.y * cosX + rotatedZ * sinX
+ iconPositions.forEach((icon, index) => {
+ const cosX = Math.cos(rotationRef.current.x)
+ const sinX = Math.sin(rotationRef.current.x)
+ const cosY = Math.cos(rotationRef.current.y)
+ const sinY = Math.sin(rotationRef.current.y)
- const scale = (rotatedZ + 200) / 300
- const opacity = Math.max(0.2, Math.min(1, (rotatedZ + 150) / 200))
+ const rotatedX = icon.x * cosY - icon.z * sinY
+ const rotatedZ = icon.x * sinY + icon.z * cosY
+ const rotatedY = icon.y * cosX + rotatedZ * sinX
- ctx.save()
- ctx.translate(canvas.width / 2 + rotatedX, canvas.height / 2 + rotatedY)
- ctx.scale(scale, scale)
- ctx.globalAlpha = opacity
+ const scale = (rotatedZ + 200) / 300
+ const opacity = Math.max(0.2, Math.min(1, (rotatedZ + 150) / 200))
- if (icons || images) {
- // Only try to render icons/images if they exist
- if (
- iconCanvasesRef.current[index] &&
- imagesLoadedRef.current[index]
- ) {
- ctx.drawImage(iconCanvasesRef.current[index], -20, -20, 40, 40)
+ ctx.save()
+ ctx.translate(
+ canvas.width / 2 + rotatedX,
+ canvas.height / 2 + rotatedY
+ )
+ ctx.scale(scale, scale)
+ ctx.globalAlpha = opacity
+
+ if (icons || images) {
+ // Only try to render icons/images if they exist
+ if (
+ iconCanvasesRef.current[index] &&
+ imagesLoadedRef.current[index]
+ ) {
+ ctx.drawImage(iconCanvasesRef.current[index], -20, -20, 40, 40)
+ }
+ } else {
+ // Show numbered circles if no icons/images are provided
+ ctx.beginPath()
+ ctx.arc(0, 0, 20, 0, Math.PI * 2)
+ ctx.fillStyle = "#4444ff"
+ ctx.fill()
+ ctx.fillStyle = "white"
+ ctx.textAlign = "center"
+ ctx.textBaseline = "middle"
+ ctx.font = "16px Arial"
+ ctx.fillText(`${icon.id + 1}`, 0, 0)
}
- } else {
- // Show numbered circles if no icons/images are provided
- ctx.beginPath()
- ctx.arc(0, 0, 20, 0, Math.PI * 2)
- ctx.fillStyle = "#4444ff"
- ctx.fill()
- ctx.fillStyle = "white"
- ctx.textAlign = "center"
- ctx.textBaseline = "middle"
- ctx.font = "16px Arial"
- ctx.fillText(`${icon.id + 1}`, 0, 0)
- }
- ctx.restore()
- })
- animationFrameRef.current = requestAnimationFrame(animate)
- }
+ ctx.restore()
+ })
+ animationFrameRef.current = requestAnimationFrame(animate)
+ }
- animate()
+ animate()
+ }
return () => {
if (animationFrameRef.current) {
@@ -10647,11 +10684,18 @@ export function NumberTicker({
const isInView = useInView(ref, { once: true, margin: "0px" })
useEffect(() => {
+ let timer: ReturnType<typeof setTimeout> | null = null
+
if (isInView) {
- const timer = setTimeout(() => {
+ timer = setTimeout(() => {
motionValue.set(direction === "down" ? startValue : value)
}, delay * 1000)
- return () => clearTimeout(timer)
+ }
+
+ return () => {
+ if (timer !== null) {
+ clearTimeout(timer)
+ }
}
}, [motionValue, isInView, delay, value, direction, startValue])
@@ -11515,41 +11559,40 @@ export function Pointer({
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
- if (typeof window !== "undefined" && containerRef.current) {
- // Get the parent element directly from the ref
- const parentElement = containerRef.current.parentElement
-
- if (parentElement) {
- // Add cursor-none to parent
- parentElement.style.cursor = "none"
-
- // Add event listeners to parent
- const handleMouseMove = (e: MouseEvent) => {
- x.set(e.clientX)
- y.set(e.clientY)
- setIsActive(true)
- }
+ const parentElement =
+ typeof window !== "undefined"
+ ? (containerRef.current?.parentElement ?? null)
+ : null
+
+ const handleMouseMove = (e: MouseEvent) => {
+ x.set(e.clientX)
+ y.set(e.clientY)
+ setIsActive(true)
+ }
- const handleMouseEnter = (e: MouseEvent) => {
- x.set(e.clientX)
- y.set(e.clientY)
- setIsActive(true)
- }
+ const handleMouseEnter = (e: MouseEvent) => {
+ x.set(e.clientX)
+ y.set(e.clientY)
+ setIsActive(true)
+ }
- const handleMouseLeave = () => {
- setIsActive(false)
- }
+ const handleMouseLeave = () => {
+ setIsActive(false)
+ }
- parentElement.addEventListener("mousemove", handleMouseMove)
- parentElement.addEventListener("mouseenter", handleMouseEnter)
- parentElement.addEventListener("mouseleave", handleMouseLeave)
+ if (parentElement) {
+ parentElement.style.cursor = "none"
+ parentElement.addEventListener("mousemove", handleMouseMove)
+ parentElement.addEventListener("mouseenter", handleMouseEnter)
+ parentElement.addEventListener("mouseleave", handleMouseLeave)
+ }
- return () => {
- parentElement.style.cursor = ""
- parentElement.removeEventListener("mousemove", handleMouseMove)
- parentElement.removeEventListener("mouseenter", handleMouseEnter)
- parentElement.removeEventListener("mouseleave", handleMouseLeave)
- }
+ return () => {
+ if (parentElement) {
+ parentElement.style.cursor = ""
+ parentElement.removeEventListener("mousemove", handleMouseMove)
+ parentElement.removeEventListener("mouseenter", handleMouseEnter)
+ parentElement.removeEventListener("mouseleave", handleMouseLeave)
}
}
}, [x, y])
@@ -12247,14 +12290,21 @@ export const RippleButton = React.forwardRef<
}
useEffect(() => {
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
if (buttonRipples.length > 0) {
const lastRipple = buttonRipples[buttonRipples.length - 1]
- const timeout = setTimeout(() => {
+ timeout = setTimeout(() => {
setButtonRipples((prevRipples) =>
prevRipples.filter((ripple) => ripple.key !== lastRipple.key)
)
}, parseInt(duration))
- return () => clearTimeout(timeout)
+ }
+
+ return () => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
}
}, [buttonRipples, duration])
@@ -12722,47 +12772,59 @@ function ScrollVelocityRowImpl({
useEffect(() => {
const container = containerRef.current
const block = blockRef.current
- if (!container || !block) return
-
- const updateSizes = () => {
- const cw = container.offsetWidth || 0
- const bw = block.scrollWidth || 0
- unitWidth.set(bw)
- const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1
- setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies))
+ let ro: ResizeObserver | null = null
+ let io: IntersectionObserver | null = null
+ let mq: MediaQueryList | null = null
+ const handleVisibility = () => {
+ isPageVisibleRef.current = document.visibilityState === "visible"
+ }
+ const handlePRM = () => {
+ if (mq) {
+ prefersReducedMotionRef.current = mq.matches
+ }
}
- updateSizes()
+ if (container && block) {
+ const updateSizes = () => {
+ const cw = container.offsetWidth || 0
+ const bw = block.scrollWidth || 0
+ unitWidth.set(bw)
+ const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1
+ setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies))
+ }
- const ro = new ResizeObserver(updateSizes)
- ro.observe(container)
- ro.observe(block)
+ updateSizes()
- const io = new IntersectionObserver(([entry]) => {
- isInViewRef.current = entry.isIntersecting
- })
- io.observe(container)
+ ro = new ResizeObserver(updateSizes)
+ ro.observe(container)
+ ro.observe(block)
- const handleVisibility = () => {
- isPageVisibleRef.current = document.visibilityState === "visible"
- }
- document.addEventListener("visibilitychange", handleVisibility, {
- passive: true,
- })
- handleVisibility()
+ io = new IntersectionObserver(([entry]) => {
+ isInViewRef.current = entry.isIntersecting
+ })
+ io.observe(container)
- const mq = window.matchMedia("(prefers-reduced-motion: reduce)")
- const handlePRM = () => {
- prefersReducedMotionRef.current = mq.matches
+ document.addEventListener("visibilitychange", handleVisibility, {
+ passive: true,
+ })
+ handleVisibility()
+
+ mq = window.matchMedia("(prefers-reduced-motion: reduce)")
+ mq.addEventListener("change", handlePRM)
+ handlePRM()
}
- mq.addEventListener("change", handlePRM)
- handlePRM()
return () => {
- ro.disconnect()
- io.disconnect()
+ if (ro) {
+ ro.disconnect()
+ }
+ if (io) {
+ io.disconnect()
+ }
document.removeEventListener("visibilitychange", handleVisibility)
- mq.removeEventListener("change", handlePRM)
+ if (mq) {
+ mq.removeEventListener("change", handlePRM)
+ }
}
}, [children, unitWidth])
@@ -13488,6 +13550,8 @@ export function SmoothCursor({
})
useEffect(() => {
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
const updateVelocity = (currentPos: Position) => {
const currentTime = Date.now()
const deltaTime = currentTime - lastUpdateTime.current
@@ -13529,12 +13593,14 @@ export function SmoothCursor({
scale.set(0.95)
setIsMoving(true)
- const timeout = setTimeout(() => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
+
+ timeout = setTimeout(() => {
scale.set(1)
setIsMoving(false)
}, 150)
-
- return () => clearTimeout(timeout)
}
}
@@ -13555,6 +13621,9 @@ export function SmoothCursor({
window.removeEventListener("mousemove", throttledMouseMove)
document.body.style.cursor = "auto"
if (rafId) cancelAnimationFrame(rafId)
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
}
}, [cursorX, cursorY, rotation, scale])
@@ -14177,24 +14246,25 @@ export const TypingAnimation = ({
const itemIndex = useItemIndex()
useEffect(() => {
+ let startTimeout: ReturnType<typeof setTimeout> | null = null
+
if (sequence && itemIndex !== null) {
- if (!sequence.sequenceStarted) return
- if (started) return
- if (sequence.activeIndex === itemIndex) {
+ if (
+ sequence.sequenceStarted &&
+ !started &&
+ sequence.activeIndex === itemIndex
+ ) {
setStarted(true)
}
- return
+ } else if (!startOnView || isInView) {
+ startTimeout = setTimeout(() => setStarted(true), delay)
}
- if (!startOnView) {
- const startTimeout = setTimeout(() => setStarted(true), delay)
- return () => clearTimeout(startTimeout)
+ return () => {
+ if (startTimeout !== null) {
+ clearTimeout(startTimeout)
+ }
}
-
- if (!isInView) return
-
- const startTimeout = setTimeout(() => setStarted(true), delay)
- return () => clearTimeout(startTimeout)
}, [
delay,
startOnView,
@@ -14206,23 +14276,29 @@ export const TypingAnimation = ({
])
useEffect(() => {
- if (!started) return
-
- let i = 0
- const typingEffect = setInterval(() => {
- if (i < children.length) {
- setDisplayedText(children.substring(0, i + 1))
- i++
- } else {
- clearInterval(typingEffect)
- if (sequence && itemIndex !== null) {
- sequence.completeItem(itemIndex)
+ let typingEffect: ReturnType<typeof setInterval> | null = null
+
+ if (started) {
+ let i = 0
+ typingEffect = setInterval(() => {
+ if (i < children.length) {
+ setDisplayedText(children.substring(0, i + 1))
+ i++
+ } else {
+ if (typingEffect !== null) {
+ clearInterval(typingEffect)
+ }
+ if (sequence && itemIndex !== null) {
+ sequence.completeItem(itemIndex)
+ }
}
- }
- }, duration)
+ }, duration)
+ }
return () => {
- clearInterval(typingEffect)
+ if (typingEffect !== null) {
+ clearInterval(typingEffect)
+ }
}
}, [children, duration, started])
@@ -15321,6 +15397,8 @@ export const TweetBody = ({ tweet }: { tweet: EnrichedTweet }) => (
dangerouslySetInnerHTML={{ __html: entity.text }}
/>
)
+ default:
+ return null
}
})}
</div>
@@ -15594,54 +15672,65 @@ export function TypingAnimation({
}, [animationSourceKey])
useEffect(() => {
- if (!shouldStart || wordsToAnimate.length === 0) return
-
- const timeoutDelay =
- delay > 0 && displayedText === ""
- ? delay
- : phase === "typing"
- ? typingSpeed
- : phase === "deleting"
- ? deletingSpeed
- : pauseDelay
-
- const timeout = setTimeout(() => {
- const currentWord = wordsToAnimate[currentWordIndex] || ""
- const graphemes = Array.from(currentWord)
-
- switch (phase) {
- case "typing":
- if (currentCharIndex < graphemes.length) {
- setDisplayedText(graphemes.slice(0, currentCharIndex + 1).join(""))
- setCurrentCharIndex(currentCharIndex + 1)
- } else {
- if (hasMultipleWords || loop) {
- const isLastWord = currentWordIndex === wordsToAnimate.length - 1
- if (!isLastWord || loop) {
- setPhase("pause")
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
+ if (shouldStart && wordsToAnimate.length > 0) {
+ const timeoutDelay =
+ delay > 0 && displayedText === ""
+ ? delay
+ : phase === "typing"
+ ? typingSpeed
+ : phase === "deleting"
+ ? deletingSpeed
+ : pauseDelay
+
+ timeout = setTimeout(() => {
+ const currentWord = wordsToAnimate[currentWordIndex] || ""
+ const graphemes = Array.from(currentWord)
+
+ switch (phase) {
+ case "typing":
+ if (currentCharIndex < graphemes.length) {
+ setDisplayedText(
+ graphemes.slice(0, currentCharIndex + 1).join("")
+ )
+ setCurrentCharIndex(currentCharIndex + 1)
+ } else {
+ if (hasMultipleWords || loop) {
+ const isLastWord =
+ currentWordIndex === wordsToAnimate.length - 1
+ if (!isLastWord || loop) {
+ setPhase("pause")
+ }
}
}
- }
- break
-
- case "pause":
- setPhase("deleting")
- break
+ break
+
+ case "pause":
+ setPhase("deleting")
+ break
+
+ case "deleting":
+ if (currentCharIndex > 0) {
+ setDisplayedText(
+ graphemes.slice(0, currentCharIndex - 1).join("")
+ )
+ setCurrentCharIndex(currentCharIndex - 1)
+ } else {
+ const nextIndex = (currentWordIndex + 1) % wordsToAnimate.length
+ setCurrentWordIndex(nextIndex)
+ setPhase("typing")
+ }
+ break
+ }
+ }, timeoutDelay)
+ }
- case "deleting":
- if (currentCharIndex > 0) {
- setDisplayedText(graphemes.slice(0, currentCharIndex - 1).join(""))
- setCurrentCharIndex(currentCharIndex - 1)
- } else {
- const nextIndex = (currentWordIndex + 1) % wordsToAnimate.length
- setCurrentWordIndex(nextIndex)
- setPhase("typing")
- }
- break
+ return () => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
}
- }, timeoutDelay)
-
- return () => clearTimeout(timeout)
+ }
}, [
shouldStart,
phase,
diff --git a/apps/www/public/r/animated-grid-pattern.json b/apps/www/public/r/animated-grid-pattern.json
index 51ec70c8..a0b208ea 100644
--- a/apps/www/public/r/animated-grid-pattern.json
+++ b/apps/www/public/r/animated-grid-pattern.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/animated-grid-pattern.tsx",
- "content": "\"use client\"\n\nimport {\n useCallback,\n useEffect,\n useId,\n useRef,\n useState,\n type ComponentPropsWithoutRef,\n} from \"react\"\nimport { motion } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport interface AnimatedGridPatternProps extends ComponentPropsWithoutRef<\"svg\"> {\n width?: number\n height?: number\n x?: number\n y?: number\n strokeDasharray?: number\n numSquares?: number\n maxOpacity?: number\n duration?: number\n repeatDelay?: number\n}\n\ntype Square = {\n id: number\n pos: [number, number]\n iteration: number\n}\n\nexport function AnimatedGridPattern({\n width = 40,\n height = 40,\n x = -1,\n y = -1,\n strokeDasharray = 0,\n numSquares = 50,\n className,\n maxOpacity = 0.5,\n duration = 4,\n repeatDelay = 0.5,\n ...props\n}: AnimatedGridPatternProps) {\n const id = useId()\n const containerRef = useRef<SVGSVGElement | null>(null)\n const [dimensions, setDimensions] = useState({ width: 0, height: 0 })\n const [squares, setSquares] = useState<Array<Square>>([])\n\n const getPos = useCallback((): [number, number] => {\n return [\n Math.floor((Math.random() * dimensions.width) / width),\n Math.floor((Math.random() * dimensions.height) / height),\n ]\n }, [dimensions.height, dimensions.width, height, width])\n\n const generateSquares = useCallback(\n (count: number) => {\n return Array.from({ length: count }, (_, i) => ({\n id: i,\n pos: getPos(),\n iteration: 0,\n }))\n },\n [getPos]\n )\n\n const updateSquarePosition = useCallback(\n (squareId: number) => {\n setSquares((currentSquares) => {\n const current = currentSquares[squareId]\n if (!current || current.id !== squareId) return currentSquares\n\n const nextSquares = currentSquares.slice()\n nextSquares[squareId] = {\n ...current,\n pos: getPos(),\n iteration: current.iteration + 1,\n }\n\n return nextSquares\n })\n },\n [getPos]\n )\n\n useEffect(() => {\n if (dimensions.width && dimensions.height) {\n setSquares(generateSquares(numSquares))\n }\n }, [dimensions.width, dimensions.height, generateSquares, numSquares])\n\n useEffect(() => {\n const element = containerRef.current\n if (!element) return\n\n const resizeObserver = new ResizeObserver((entries) => {\n for (const entry of entries) {\n setDimensions((currentDimensions) => {\n const nextWidth = entry.contentRect.width\n const nextHeight = entry.contentRect.height\n if (\n currentDimensions.width === nextWidth &&\n currentDimensions.height === nextHeight\n ) {\n return currentDimensions\n }\n return { width: nextWidth, height: nextHeight }\n })\n }\n })\n\n resizeObserver.observe(element)\n\n return () => {\n resizeObserver.disconnect()\n }\n }, [])\n\n return (\n <svg\n ref={containerRef}\n aria-hidden=\"true\"\n className={cn(\n \"pointer-events-none absolute inset-0 h-full w-full fill-gray-400/30 stroke-gray-400/30\",\n className\n )}\n {...props}\n >\n <defs>\n <pattern\n id={id}\n width={width}\n height={height}\n patternUnits=\"userSpaceOnUse\"\n x={x}\n y={y}\n >\n <path\n d={`M.5 ${height}V.5H${width}`}\n fill=\"none\"\n strokeDasharray={strokeDasharray}\n />\n </pattern>\n </defs>\n <rect width=\"100%\" height=\"100%\" fill={`url(#${id})`} />\n <svg x={x} y={y} className=\"overflow-visible\">\n {squares.map(({ pos: [squareX, squareY], id, iteration }, index) => (\n <motion.rect\n initial={{ opacity: 0 }}\n animate={{ opacity: maxOpacity }}\n transition={{\n duration,\n repeat: 1,\n delay: index * 0.1,\n repeatType: \"reverse\",\n repeatDelay,\n }}\n onAnimationComplete={() => updateSquarePosition(id)}\n key={`${id}-${iteration}`}\n width={width - 1}\n height={height - 1}\n x={squareX * width + 1}\n y={squareY * height + 1}\n fill=\"currentColor\"\n strokeWidth=\"0\"\n />\n ))}\n </svg>\n </svg>\n )\n}\n",
+ "content": "\"use client\"\n\nimport {\n useCallback,\n useEffect,\n useId,\n useRef,\n useState,\n type ComponentPropsWithoutRef,\n} from \"react\"\nimport { motion } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport interface AnimatedGridPatternProps extends ComponentPropsWithoutRef<\"svg\"> {\n width?: number\n height?: number\n x?: number\n y?: number\n strokeDasharray?: number\n numSquares?: number\n maxOpacity?: number\n duration?: number\n repeatDelay?: number\n}\n\ntype Square = {\n id: number\n pos: [number, number]\n iteration: number\n}\n\nexport function AnimatedGridPattern({\n width = 40,\n height = 40,\n x = -1,\n y = -1,\n strokeDasharray = 0,\n numSquares = 50,\n className,\n maxOpacity = 0.5,\n duration = 4,\n repeatDelay = 0.5,\n ...props\n}: AnimatedGridPatternProps) {\n const id = useId()\n const containerRef = useRef<SVGSVGElement | null>(null)\n const [dimensions, setDimensions] = useState({ width: 0, height: 0 })\n const [squares, setSquares] = useState<Array<Square>>([])\n\n const getPos = useCallback((): [number, number] => {\n return [\n Math.floor((Math.random() * dimensions.width) / width),\n Math.floor((Math.random() * dimensions.height) / height),\n ]\n }, [dimensions.height, dimensions.width, height, width])\n\n const generateSquares = useCallback(\n (count: number) => {\n return Array.from({ length: count }, (_, i) => ({\n id: i,\n pos: getPos(),\n iteration: 0,\n }))\n },\n [getPos]\n )\n\n const updateSquarePosition = useCallback(\n (squareId: number) => {\n setSquares((currentSquares) => {\n const current = currentSquares[squareId]\n if (!current || current.id !== squareId) return currentSquares\n\n const nextSquares = currentSquares.slice()\n nextSquares[squareId] = {\n ...current,\n pos: getPos(),\n iteration: current.iteration + 1,\n }\n\n return nextSquares\n })\n },\n [getPos]\n )\n\n useEffect(() => {\n if (dimensions.width && dimensions.height) {\n setSquares(generateSquares(numSquares))\n }\n }, [dimensions.width, dimensions.height, generateSquares, numSquares])\n\n useEffect(() => {\n const element = containerRef.current\n let resizeObserver: ResizeObserver | null = null\n\n if (element) {\n resizeObserver = new ResizeObserver((entries) => {\n for (const entry of entries) {\n setDimensions((currentDimensions) => {\n const nextWidth = entry.contentRect.width\n const nextHeight = entry.contentRect.height\n if (\n currentDimensions.width === nextWidth &&\n currentDimensions.height === nextHeight\n ) {\n return currentDimensions\n }\n return { width: nextWidth, height: nextHeight }\n })\n }\n })\n\n resizeObserver.observe(element)\n }\n\n return () => {\n if (resizeObserver) {\n resizeObserver.disconnect()\n }\n }\n }, [])\n\n return (\n <svg\n ref={containerRef}\n aria-hidden=\"true\"\n className={cn(\n \"pointer-events-none absolute inset-0 h-full w-full fill-gray-400/30 stroke-gray-400/30\",\n className\n )}\n {...props}\n >\n <defs>\n <pattern\n id={id}\n width={width}\n height={height}\n patternUnits=\"userSpaceOnUse\"\n x={x}\n y={y}\n >\n <path\n d={`M.5 ${height}V.5H${width}`}\n fill=\"none\"\n strokeDasharray={strokeDasharray}\n />\n </pattern>\n </defs>\n <rect width=\"100%\" height=\"100%\" fill={`url(#${id})`} />\n <svg x={x} y={y} className=\"overflow-visible\">\n {squares.map(({ pos: [squareX, squareY], id, iteration }, index) => (\n <motion.rect\n initial={{ opacity: 0 }}\n animate={{ opacity: maxOpacity }}\n transition={{\n duration,\n repeat: 1,\n delay: index * 0.1,\n repeatType: \"reverse\",\n repeatDelay,\n }}\n onAnimationComplete={() => updateSquarePosition(id)}\n key={`${id}-${iteration}`}\n width={width - 1}\n height={height - 1}\n x={squareX * width + 1}\n y={squareY * height + 1}\n fill=\"currentColor\"\n strokeWidth=\"0\"\n />\n ))}\n </svg>\n </svg>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/animated-list.json b/apps/www/public/r/animated-list.json
index 0c7ac391..8241bbf6 100644
--- a/apps/www/public/r/animated-list.json
+++ b/apps/www/public/r/animated-list.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/animated-list.tsx",
- "content": "\"use client\"\n\nimport React, {\n useEffect,\n useMemo,\n useState,\n type ComponentPropsWithoutRef,\n} from \"react\"\nimport { AnimatePresence, motion, type MotionProps } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport function AnimatedListItem({ children }: { children: React.ReactNode }) {\n const animations: MotionProps = {\n initial: { scale: 0, opacity: 0 },\n animate: { scale: 1, opacity: 1, originY: 0 },\n exit: { scale: 0, opacity: 0 },\n transition: { type: \"spring\", stiffness: 350, damping: 40 },\n }\n\n return (\n <motion.div {...animations} layout className=\"mx-auto w-full\">\n {children}\n </motion.div>\n )\n}\n\nexport interface AnimatedListProps extends ComponentPropsWithoutRef<\"div\"> {\n children: React.ReactNode\n delay?: number\n}\n\nexport const AnimatedList = React.memo(\n ({ children, className, delay = 1000, ...props }: AnimatedListProps) => {\n const [index, setIndex] = useState(0)\n const childrenArray = useMemo(\n () => React.Children.toArray(children),\n [children]\n )\n\n useEffect(() => {\n if (index < childrenArray.length - 1) {\n const timeout = setTimeout(() => {\n setIndex((prevIndex) => (prevIndex + 1) % childrenArray.length)\n }, delay)\n\n return () => clearTimeout(timeout)\n }\n }, [index, delay, childrenArray.length])\n\n const itemsToShow = useMemo(() => {\n const result = childrenArray.slice(0, index + 1).reverse()\n return result\n }, [index, childrenArray])\n\n return (\n <div\n className={cn(`flex flex-col items-center gap-4`, className)}\n {...props}\n >\n <AnimatePresence>\n {itemsToShow.map((item) => (\n <AnimatedListItem key={(item as React.ReactElement).key}>\n {item}\n </AnimatedListItem>\n ))}\n </AnimatePresence>\n </div>\n )\n }\n)\n\nAnimatedList.displayName = \"AnimatedList\"\n",
+ "content": "\"use client\"\n\nimport React, {\n useEffect,\n useMemo,\n useState,\n type ComponentPropsWithoutRef,\n} from \"react\"\nimport { AnimatePresence, motion, type MotionProps } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport function AnimatedListItem({ children }: { children: React.ReactNode }) {\n const animations: MotionProps = {\n initial: { scale: 0, opacity: 0 },\n animate: { scale: 1, opacity: 1, originY: 0 },\n exit: { scale: 0, opacity: 0 },\n transition: { type: \"spring\", stiffness: 350, damping: 40 },\n }\n\n return (\n <motion.div {...animations} layout className=\"mx-auto w-full\">\n {children}\n </motion.div>\n )\n}\n\nexport interface AnimatedListProps extends ComponentPropsWithoutRef<\"div\"> {\n children: React.ReactNode\n delay?: number\n}\n\nexport const AnimatedList = React.memo(\n ({ children, className, delay = 1000, ...props }: AnimatedListProps) => {\n const [index, setIndex] = useState(0)\n const childrenArray = useMemo(\n () => React.Children.toArray(children),\n [children]\n )\n\n useEffect(() => {\n let timeout: ReturnType<typeof setTimeout> | null = null\n\n if (index < childrenArray.length - 1) {\n timeout = setTimeout(() => {\n setIndex((prevIndex) => (prevIndex + 1) % childrenArray.length)\n }, delay)\n }\n\n return () => {\n if (timeout !== null) {\n clearTimeout(timeout)\n }\n }\n }, [index, delay, childrenArray.length])\n\n const itemsToShow = useMemo(() => {\n const result = childrenArray.slice(0, index + 1).reverse()\n return result\n }, [index, childrenArray])\n\n return (\n <div\n className={cn(`flex flex-col items-center gap-4`, className)}\n {...props}\n >\n <AnimatePresence>\n {itemsToShow.map((item) => (\n <AnimatedListItem key={(item as React.ReactElement).key}>\n {item}\n </AnimatedListItem>\n ))}\n </AnimatePresence>\n </div>\n )\n }\n)\n\nAnimatedList.displayName = \"AnimatedList\"\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/cool-mode.json b/apps/www/public/r/cool-mode.json
index b6c776b6..026466d5 100644
--- a/apps/www/public/r/cool-mode.json
+++ b/apps/www/public/r/cool-mode.json
@@ -7,7 +7,7 @@
"files": [
{
"path": "registry/magicui/cool-mode.tsx",
- "content": "\"use client\"\n\nimport React, { ReactNode, useEffect, useRef } from \"react\"\n\nexport interface BaseParticle {\n element: HTMLElement | SVGSVGElement\n left: number\n size: number\n top: number\n}\n\nexport interface BaseParticleOptions {\n particle?: string\n size?: number\n}\n\nexport interface CoolParticle extends BaseParticle {\n direction: number\n speedHorz: number\n speedUp: number\n spinSpeed: number\n spinVal: number\n}\n\nexport interface CoolParticleOptions extends BaseParticleOptions {\n particleCount?: number\n speedHorz?: number\n speedUp?: number\n}\n\nconst getContainer = () => {\n const id = \"_coolMode_effect\"\n const existingContainer = document.getElementById(id)\n\n if (existingContainer) {\n return existingContainer\n }\n\n const container = document.createElement(\"div\")\n container.setAttribute(\"id\", id)\n container.setAttribute(\n \"style\",\n \"overflow:hidden; position:fixed; height:100%; top:0; left:0; right:0; bottom:0; pointer-events:none; z-index:2147483647\"\n )\n\n document.body.appendChild(container)\n\n return container\n}\n\nlet instanceCounter = 0\n\nconst applyParticleEffect = (\n element: HTMLElement,\n options?: CoolParticleOptions\n): (() => void) => {\n instanceCounter++\n\n const defaultParticle = \"circle\"\n const particleType = options?.particle || defaultParticle\n const sizes = [15, 20, 25, 35, 45]\n const limit = 45\n\n let particles: CoolParticle[] = []\n let autoAddParticle = false\n let mouseX = 0\n let mouseY = 0\n\n const container = getContainer()\n\n function generateParticle() {\n const size =\n options?.size || sizes[Math.floor(Math.random() * sizes.length)]\n const speedHorz = options?.speedHorz || Math.random() * 10\n const speedUp = options?.speedUp || Math.random() * 25\n const spinVal = Math.random() * 360\n const spinSpeed = Math.random() * 35 * (Math.random() <= 0.5 ? -1 : 1)\n const top = mouseY - size / 2\n const left = mouseX - size / 2\n const direction = Math.random() <= 0.5 ? -1 : 1\n\n const particle = document.createElement(\"div\")\n\n if (particleType === \"circle\") {\n const svgNS = \"http://www.w3.org/2000/svg\"\n const circleSVG = document.createElementNS(svgNS, \"svg\")\n const circle = document.createElementNS(svgNS, \"circle\")\n circle.setAttributeNS(null, \"cx\", (size / 2).toString())\n circle.setAttributeNS(null, \"cy\", (size / 2).toString())\n circle.setAttributeNS(null, \"r\", (size / 2).toString())\n circle.setAttributeNS(\n null,\n \"fill\",\n `hsl(${Math.random() * 360}, 70%, 50%)`\n )\n\n circleSVG.appendChild(circle)\n circleSVG.setAttribute(\"width\", size.toString())\n circleSVG.setAttribute(\"height\", size.toString())\n\n particle.appendChild(circleSVG)\n } else if (\n particleType.startsWith(\"http\") ||\n particleType.startsWith(\"/\")\n ) {\n // Handle URL-based images\n particle.innerHTML = `<img src=\"${particleType}\" width=\"${size}\" height=\"${size}\" style=\"border-radius: 50%\">`\n } else {\n // Handle emoji or text characters\n const fontSizeMultiplier = 3 // Make emojis 3x bigger\n const emojiSize = size * fontSizeMultiplier\n particle.innerHTML = `<div style=\"font-size: ${emojiSize}px; line-height: 1; text-align: center; width: ${size}px; height: ${size}px; display: flex; align-items: center; justify-content: center; transform: scale(${fontSizeMultiplier}); transform-origin: center;\">${particleType}</div>`\n }\n\n particle.style.position = \"absolute\"\n particle.style.transform = `translate3d(${left}px, ${top}px, 0px) rotate(${spinVal}deg)`\n\n container.appendChild(particle)\n\n particles.push({\n direction,\n element: particle,\n left,\n size,\n speedHorz,\n speedUp,\n spinSpeed,\n spinVal,\n top,\n })\n }\n\n function refreshParticles() {\n particles.forEach((p) => {\n p.left = p.left - p.speedHorz * p.direction\n p.top = p.top - p.speedUp\n p.speedUp = Math.min(p.size, p.speedUp - 1)\n p.spinVal = p.spinVal + p.spinSpeed\n\n if (\n p.top >=\n Math.max(window.innerHeight, document.body.clientHeight) + p.size\n ) {\n particles = particles.filter((o) => o !== p)\n p.element.remove()\n }\n\n p.element.setAttribute(\n \"style\",\n [\n \"position:absolute\",\n \"will-change:transform\",\n `top:${p.top}px`,\n `left:${p.left}px`,\n `transform:rotate(${p.spinVal}deg)`,\n ].join(\";\")\n )\n })\n }\n\n let animationFrame: number | undefined\n\n let lastParticleTimestamp = 0\n const particleGenerationDelay = 30\n\n function loop() {\n const currentTime = performance.now()\n if (\n autoAddParticle &&\n particles.length < limit &&\n currentTime - lastParticleTimestamp > particleGenerationDelay\n ) {\n generateParticle()\n lastParticleTimestamp = currentTime\n }\n\n refreshParticles()\n animationFrame = requestAnimationFrame(loop)\n }\n\n loop()\n\n const isTouchInteraction = \"ontouchstart\" in window\n\n const tap = isTouchInteraction ? \"touchstart\" : \"mousedown\"\n const tapEnd = isTouchInteraction ? \"touchend\" : \"mouseup\"\n const move = isTouchInteraction ? \"touchmove\" : \"mousemove\"\n\n const updateMousePosition = (e: MouseEvent | TouchEvent) => {\n if (\"touches\" in e) {\n mouseX = e.touches?.[0].clientX\n mouseY = e.touches?.[0].clientY\n } else {\n mouseX = e.clientX\n mouseY = e.clientY\n }\n }\n\n const tapHandler = (e: MouseEvent | TouchEvent) => {\n updateMousePosition(e)\n autoAddParticle = true\n }\n\n const disableAutoAddParticle = () => {\n autoAddParticle = false\n }\n\n element.addEventListener(move, updateMousePosition, { passive: true })\n element.addEventListener(tap, tapHandler, { passive: true })\n element.addEventListener(tapEnd, disableAutoAddParticle, { passive: true })\n element.addEventListener(\"mouseleave\", disableAutoAddParticle, {\n passive: true,\n })\n\n return () => {\n element.removeEventListener(move, updateMousePosition)\n element.removeEventListener(tap, tapHandler)\n element.removeEventListener(tapEnd, disableAutoAddParticle)\n element.removeEventListener(\"mouseleave\", disableAutoAddParticle)\n\n const interval = setInterval(() => {\n if (animationFrame && particles.length === 0) {\n cancelAnimationFrame(animationFrame)\n clearInterval(interval)\n\n if (--instanceCounter === 0) {\n container.remove()\n }\n }\n }, 500)\n }\n}\n\ninterface CoolModeProps {\n children: ReactNode\n options?: CoolParticleOptions\n}\n\nexport const CoolMode: React.FC<CoolModeProps> = ({ children, options }) => {\n const ref = useRef<HTMLSpanElement>(null)\n\n useEffect(() => {\n if (ref.current) {\n return applyParticleEffect(ref.current, options)\n }\n }, [options])\n\n return <span ref={ref}>{children}</span>\n}\n",
+ "content": "\"use client\"\n\nimport React, { ReactNode, useEffect, useRef } from \"react\"\n\nexport interface BaseParticle {\n element: HTMLElement | SVGSVGElement\n left: number\n size: number\n top: number\n}\n\nexport interface BaseParticleOptions {\n particle?: string\n size?: number\n}\n\nexport interface CoolParticle extends BaseParticle {\n direction: number\n speedHorz: number\n speedUp: number\n spinSpeed: number\n spinVal: number\n}\n\nexport interface CoolParticleOptions extends BaseParticleOptions {\n particleCount?: number\n speedHorz?: number\n speedUp?: number\n}\n\nconst getContainer = () => {\n const id = \"_coolMode_effect\"\n const existingContainer = document.getElementById(id)\n\n if (existingContainer) {\n return existingContainer\n }\n\n const container = document.createElement(\"div\")\n container.setAttribute(\"id\", id)\n container.setAttribute(\n \"style\",\n \"overflow:hidden; position:fixed; height:100%; top:0; left:0; right:0; bottom:0; pointer-events:none; z-index:2147483647\"\n )\n\n document.body.appendChild(container)\n\n return container\n}\n\nlet instanceCounter = 0\n\nconst applyParticleEffect = (\n element: HTMLElement,\n options?: CoolParticleOptions\n): (() => void) => {\n instanceCounter++\n\n const defaultParticle = \"circle\"\n const particleType = options?.particle || defaultParticle\n const sizes = [15, 20, 25, 35, 45]\n const limit = 45\n\n let particles: CoolParticle[] = []\n let autoAddParticle = false\n let mouseX = 0\n let mouseY = 0\n\n const container = getContainer()\n\n function generateParticle() {\n const size =\n options?.size || sizes[Math.floor(Math.random() * sizes.length)]\n const speedHorz = options?.speedHorz || Math.random() * 10\n const speedUp = options?.speedUp || Math.random() * 25\n const spinVal = Math.random() * 360\n const spinSpeed = Math.random() * 35 * (Math.random() <= 0.5 ? -1 : 1)\n const top = mouseY - size / 2\n const left = mouseX - size / 2\n const direction = Math.random() <= 0.5 ? -1 : 1\n\n const particle = document.createElement(\"div\")\n\n if (particleType === \"circle\") {\n const svgNS = \"http://www.w3.org/2000/svg\"\n const circleSVG = document.createElementNS(svgNS, \"svg\")\n const circle = document.createElementNS(svgNS, \"circle\")\n circle.setAttributeNS(null, \"cx\", (size / 2).toString())\n circle.setAttributeNS(null, \"cy\", (size / 2).toString())\n circle.setAttributeNS(null, \"r\", (size / 2).toString())\n circle.setAttributeNS(\n null,\n \"fill\",\n `hsl(${Math.random() * 360}, 70%, 50%)`\n )\n\n circleSVG.appendChild(circle)\n circleSVG.setAttribute(\"width\", size.toString())\n circleSVG.setAttribute(\"height\", size.toString())\n\n particle.appendChild(circleSVG)\n } else if (\n particleType.startsWith(\"http\") ||\n particleType.startsWith(\"/\")\n ) {\n // Handle URL-based images\n particle.innerHTML = `<img src=\"${particleType}\" width=\"${size}\" height=\"${size}\" style=\"border-radius: 50%\">`\n } else {\n // Handle emoji or text characters\n const fontSizeMultiplier = 3 // Make emojis 3x bigger\n const emojiSize = size * fontSizeMultiplier\n particle.innerHTML = `<div style=\"font-size: ${emojiSize}px; line-height: 1; text-align: center; width: ${size}px; height: ${size}px; display: flex; align-items: center; justify-content: center; transform: scale(${fontSizeMultiplier}); transform-origin: center;\">${particleType}</div>`\n }\n\n particle.style.position = \"absolute\"\n particle.style.transform = `translate3d(${left}px, ${top}px, 0px) rotate(${spinVal}deg)`\n\n container.appendChild(particle)\n\n particles.push({\n direction,\n element: particle,\n left,\n size,\n speedHorz,\n speedUp,\n spinSpeed,\n spinVal,\n top,\n })\n }\n\n function refreshParticles() {\n particles.forEach((p) => {\n p.left = p.left - p.speedHorz * p.direction\n p.top = p.top - p.speedUp\n p.speedUp = Math.min(p.size, p.speedUp - 1)\n p.spinVal = p.spinVal + p.spinSpeed\n\n if (\n p.top >=\n Math.max(window.innerHeight, document.body.clientHeight) + p.size\n ) {\n particles = particles.filter((o) => o !== p)\n p.element.remove()\n }\n\n p.element.setAttribute(\n \"style\",\n [\n \"position:absolute\",\n \"will-change:transform\",\n `top:${p.top}px`,\n `left:${p.left}px`,\n `transform:rotate(${p.spinVal}deg)`,\n ].join(\";\")\n )\n })\n }\n\n let animationFrame: number | undefined\n\n let lastParticleTimestamp = 0\n const particleGenerationDelay = 30\n\n function loop() {\n const currentTime = performance.now()\n if (\n autoAddParticle &&\n particles.length < limit &&\n currentTime - lastParticleTimestamp > particleGenerationDelay\n ) {\n generateParticle()\n lastParticleTimestamp = currentTime\n }\n\n refreshParticles()\n animationFrame = requestAnimationFrame(loop)\n }\n\n loop()\n\n const isTouchInteraction = \"ontouchstart\" in window\n\n const tap = isTouchInteraction ? \"touchstart\" : \"mousedown\"\n const tapEnd = isTouchInteraction ? \"touchend\" : \"mouseup\"\n const move = isTouchInteraction ? \"touchmove\" : \"mousemove\"\n\n const updateMousePosition = (e: MouseEvent | TouchEvent) => {\n if (\"touches\" in e) {\n mouseX = e.touches?.[0].clientX\n mouseY = e.touches?.[0].clientY\n } else {\n mouseX = e.clientX\n mouseY = e.clientY\n }\n }\n\n const tapHandler = (e: MouseEvent | TouchEvent) => {\n updateMousePosition(e)\n autoAddParticle = true\n }\n\n const disableAutoAddParticle = () => {\n autoAddParticle = false\n }\n\n element.addEventListener(move, updateMousePosition, { passive: true })\n element.addEventListener(tap, tapHandler, { passive: true })\n element.addEventListener(tapEnd, disableAutoAddParticle, { passive: true })\n element.addEventListener(\"mouseleave\", disableAutoAddParticle, {\n passive: true,\n })\n\n return () => {\n element.removeEventListener(move, updateMousePosition)\n element.removeEventListener(tap, tapHandler)\n element.removeEventListener(tapEnd, disableAutoAddParticle)\n element.removeEventListener(\"mouseleave\", disableAutoAddParticle)\n\n const interval = setInterval(() => {\n if (animationFrame && particles.length === 0) {\n cancelAnimationFrame(animationFrame)\n clearInterval(interval)\n\n if (--instanceCounter === 0) {\n container.remove()\n }\n }\n }, 500)\n }\n}\n\ninterface CoolModeProps {\n children: ReactNode\n options?: CoolParticleOptions\n}\n\nexport const CoolMode: React.FC<CoolModeProps> = ({ children, options }) => {\n const ref = useRef<HTMLSpanElement>(null)\n\n useEffect(() => {\n const element = ref.current\n let cleanup: (() => void) | null = null\n\n if (element) {\n cleanup = applyParticleEffect(element, options)\n }\n\n return () => {\n if (cleanup) {\n cleanup()\n }\n }\n }, [options])\n\n return <span ref={ref}>{children}</span>\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/flickering-grid.json b/apps/www/public/r/flickering-grid.json
index 9c414e73..a3c8a8b6 100644
--- a/apps/www/public/r/flickering-grid.json
+++ b/apps/www/public/r/flickering-grid.json
@@ -7,7 +7,7 @@
"files": [
{
"path": "registry/magicui/flickering-grid.tsx",
- "content": "\"use client\"\n\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface FlickeringGridProps extends React.HTMLAttributes<HTMLDivElement> {\n squareSize?: number\n gridGap?: number\n flickerChance?: number\n color?: string\n width?: number\n height?: number\n className?: string\n maxOpacity?: number\n}\n\nexport const FlickeringGrid: React.FC<FlickeringGridProps> = ({\n squareSize = 4,\n gridGap = 6,\n flickerChance = 0.3,\n color = \"rgb(0, 0, 0)\",\n width,\n height,\n className,\n maxOpacity = 0.3,\n ...props\n}) => {\n const canvasRef = useRef<HTMLCanvasElement>(null)\n const containerRef = useRef<HTMLDivElement>(null)\n const [isInView, setIsInView] = useState(false)\n const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 })\n\n const memoizedColor = useMemo(() => {\n const toRGBA = (color: string) => {\n if (typeof window === \"undefined\") {\n return `rgba(0, 0, 0,`\n }\n const canvas = document.createElement(\"canvas\")\n canvas.width = canvas.height = 1\n const ctx = canvas.getContext(\"2d\")\n if (!ctx) return \"rgba(255, 0, 0,\"\n ctx.fillStyle = color\n ctx.fillRect(0, 0, 1, 1)\n const [r, g, b] = Array.from(ctx.getImageData(0, 0, 1, 1).data)\n return `rgba(${r}, ${g}, ${b},`\n }\n return toRGBA(color)\n }, [color])\n\n const setupCanvas = useCallback(\n (canvas: HTMLCanvasElement, width: number, height: number) => {\n const dpr = window.devicePixelRatio || 1\n canvas.width = width * dpr\n canvas.height = height * dpr\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n const cols = Math.ceil(width / (squareSize + gridGap))\n const rows = Math.ceil(height / (squareSize + gridGap))\n\n const squares = new Float32Array(cols * rows)\n for (let i = 0; i < squares.length; i++) {\n squares[i] = Math.random() * maxOpacity\n }\n\n return { cols, rows, squares, dpr }\n },\n [squareSize, gridGap, maxOpacity]\n )\n\n const updateSquares = useCallback(\n (squares: Float32Array, deltaTime: number) => {\n for (let i = 0; i < squares.length; i++) {\n if (Math.random() < flickerChance * deltaTime) {\n squares[i] = Math.random() * maxOpacity\n }\n }\n },\n [flickerChance, maxOpacity]\n )\n\n const drawGrid = useCallback(\n (\n ctx: CanvasRenderingContext2D,\n width: number,\n height: number,\n cols: number,\n rows: number,\n squares: Float32Array,\n dpr: number\n ) => {\n ctx.clearRect(0, 0, width, height)\n ctx.fillStyle = \"transparent\"\n ctx.fillRect(0, 0, width, height)\n\n for (let i = 0; i < cols; i++) {\n for (let j = 0; j < rows; j++) {\n const opacity = squares[i * rows + j]\n ctx.fillStyle = `${memoizedColor}${opacity})`\n ctx.fillRect(\n i * (squareSize + gridGap) * dpr,\n j * (squareSize + gridGap) * dpr,\n squareSize * dpr,\n squareSize * dpr\n )\n }\n }\n },\n [memoizedColor, squareSize, gridGap]\n )\n\n useEffect(() => {\n const canvas = canvasRef.current\n const container = containerRef.current\n if (!canvas || !container) return\n\n const ctx = canvas.getContext(\"2d\")\n if (!ctx) return\n\n let animationFrameId: number\n let gridParams: ReturnType<typeof setupCanvas>\n\n const updateCanvasSize = () => {\n const newWidth = width || container.clientWidth\n const newHeight = height || container.clientHeight\n setCanvasSize({ width: newWidth, height: newHeight })\n gridParams = setupCanvas(canvas, newWidth, newHeight)\n }\n\n updateCanvasSize()\n\n let lastTime = 0\n const animate = (time: number) => {\n if (!isInView) return\n\n const deltaTime = (time - lastTime) / 1000\n lastTime = time\n\n updateSquares(gridParams.squares, deltaTime)\n drawGrid(\n ctx,\n canvas.width,\n canvas.height,\n gridParams.cols,\n gridParams.rows,\n gridParams.squares,\n gridParams.dpr\n )\n animationFrameId = requestAnimationFrame(animate)\n }\n\n const resizeObserver = new ResizeObserver(() => {\n updateCanvasSize()\n })\n\n resizeObserver.observe(container)\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => {\n setIsInView(entry.isIntersecting)\n },\n { threshold: 0 }\n )\n\n intersectionObserver.observe(canvas)\n\n if (isInView) {\n animationFrameId = requestAnimationFrame(animate)\n }\n\n return () => {\n cancelAnimationFrame(animationFrameId)\n resizeObserver.disconnect()\n intersectionObserver.disconnect()\n }\n }, [setupCanvas, updateSquares, drawGrid, width, height, isInView])\n\n return (\n <div\n ref={containerRef}\n className={cn(`h-full w-full ${className}`)}\n {...props}\n >\n <canvas\n ref={canvasRef}\n className=\"pointer-events-none\"\n style={{\n width: canvasSize.width,\n height: canvasSize.height,\n }}\n />\n </div>\n )\n}\n",
+ "content": "\"use client\"\n\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface FlickeringGridProps extends React.HTMLAttributes<HTMLDivElement> {\n squareSize?: number\n gridGap?: number\n flickerChance?: number\n color?: string\n width?: number\n height?: number\n className?: string\n maxOpacity?: number\n}\n\nexport const FlickeringGrid: React.FC<FlickeringGridProps> = ({\n squareSize = 4,\n gridGap = 6,\n flickerChance = 0.3,\n color = \"rgb(0, 0, 0)\",\n width,\n height,\n className,\n maxOpacity = 0.3,\n ...props\n}) => {\n const canvasRef = useRef<HTMLCanvasElement>(null)\n const containerRef = useRef<HTMLDivElement>(null)\n const [isInView, setIsInView] = useState(false)\n const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 })\n\n const memoizedColor = useMemo(() => {\n const toRGBA = (color: string) => {\n if (typeof window === \"undefined\") {\n return `rgba(0, 0, 0,`\n }\n const canvas = document.createElement(\"canvas\")\n canvas.width = canvas.height = 1\n const ctx = canvas.getContext(\"2d\")\n if (!ctx) return \"rgba(255, 0, 0,\"\n ctx.fillStyle = color\n ctx.fillRect(0, 0, 1, 1)\n const [r, g, b] = Array.from(ctx.getImageData(0, 0, 1, 1).data)\n return `rgba(${r}, ${g}, ${b},`\n }\n return toRGBA(color)\n }, [color])\n\n const setupCanvas = useCallback(\n (canvas: HTMLCanvasElement, width: number, height: number) => {\n const dpr = window.devicePixelRatio || 1\n canvas.width = width * dpr\n canvas.height = height * dpr\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n const cols = Math.ceil(width / (squareSize + gridGap))\n const rows = Math.ceil(height / (squareSize + gridGap))\n\n const squares = new Float32Array(cols * rows)\n for (let i = 0; i < squares.length; i++) {\n squares[i] = Math.random() * maxOpacity\n }\n\n return { cols, rows, squares, dpr }\n },\n [squareSize, gridGap, maxOpacity]\n )\n\n const updateSquares = useCallback(\n (squares: Float32Array, deltaTime: number) => {\n for (let i = 0; i < squares.length; i++) {\n if (Math.random() < flickerChance * deltaTime) {\n squares[i] = Math.random() * maxOpacity\n }\n }\n },\n [flickerChance, maxOpacity]\n )\n\n const drawGrid = useCallback(\n (\n ctx: CanvasRenderingContext2D,\n width: number,\n height: number,\n cols: number,\n rows: number,\n squares: Float32Array,\n dpr: number\n ) => {\n ctx.clearRect(0, 0, width, height)\n ctx.fillStyle = \"transparent\"\n ctx.fillRect(0, 0, width, height)\n\n for (let i = 0; i < cols; i++) {\n for (let j = 0; j < rows; j++) {\n const opacity = squares[i * rows + j]\n ctx.fillStyle = `${memoizedColor}${opacity})`\n ctx.fillRect(\n i * (squareSize + gridGap) * dpr,\n j * (squareSize + gridGap) * dpr,\n squareSize * dpr,\n squareSize * dpr\n )\n }\n }\n },\n [memoizedColor, squareSize, gridGap]\n )\n\n useEffect(() => {\n const canvas = canvasRef.current\n const container = containerRef.current\n const ctx = canvas?.getContext(\"2d\") ?? null\n let animationFrameId: number | null = null\n let resizeObserver: ResizeObserver | null = null\n let intersectionObserver: IntersectionObserver | null = null\n let gridParams: ReturnType<typeof setupCanvas> | null = null\n\n if (canvas && container && ctx) {\n const updateCanvasSize = () => {\n const newWidth = width || container.clientWidth\n const newHeight = height || container.clientHeight\n setCanvasSize({ width: newWidth, height: newHeight })\n gridParams = setupCanvas(canvas, newWidth, newHeight)\n }\n\n updateCanvasSize()\n\n let lastTime = 0\n const animate = (time: number) => {\n if (!isInView || !gridParams) return\n\n const deltaTime = (time - lastTime) / 1000\n lastTime = time\n\n updateSquares(gridParams.squares, deltaTime)\n drawGrid(\n ctx,\n canvas.width,\n canvas.height,\n gridParams.cols,\n gridParams.rows,\n gridParams.squares,\n gridParams.dpr\n )\n animationFrameId = requestAnimationFrame(animate)\n }\n\n resizeObserver = new ResizeObserver(() => {\n updateCanvasSize()\n })\n resizeObserver.observe(container)\n\n intersectionObserver = new IntersectionObserver(\n ([entry]) => {\n setIsInView(entry.isIntersecting)\n },\n { threshold: 0 }\n )\n intersectionObserver.observe(canvas)\n\n if (isInView) {\n animationFrameId = requestAnimationFrame(animate)\n }\n }\n\n return () => {\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId)\n }\n if (resizeObserver) {\n resizeObserver.disconnect()\n }\n if (intersectionObserver) {\n intersectionObserver.disconnect()\n }\n }\n }, [setupCanvas, updateSquares, drawGrid, width, height, isInView])\n\n return (\n <div\n ref={containerRef}\n className={cn(`h-full w-full ${className}`)}\n {...props}\n >\n <canvas\n ref={canvasRef}\n className=\"pointer-events-none\"\n style={{\n width: canvasSize.width,\n height: canvasSize.height,\n }}\n />\n </div>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/highlighter-demo.json b/apps/www/public/r/highlighter-demo.json
index a8234c0d..e6e76479 100644
--- a/apps/www/public/r/highlighter-demo.json
+++ b/apps/www/public/r/highlighter-demo.json
@@ -18,7 +18,7 @@
},
{
"path": "registry/magicui/highlighter.tsx",
- "content": "\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport type React from \"react\"\nimport { useInView } from \"motion/react\"\nimport { annotate } from \"rough-notation\"\nimport { type RoughAnnotation } from \"rough-notation/lib/model\"\n\ntype AnnotationAction =\n | \"highlight\"\n | \"underline\"\n | \"box\"\n | \"circle\"\n | \"strike-through\"\n | \"crossed-off\"\n | \"bracket\"\n\ninterface HighlighterProps {\n children: React.ReactNode\n action?: AnnotationAction\n color?: string\n strokeWidth?: number\n animationDuration?: number\n iterations?: number\n padding?: number\n multiline?: boolean\n isView?: boolean\n}\n\nexport function Highlighter({\n children,\n action = \"highlight\",\n color = \"#ffd1dc\",\n strokeWidth = 1.5,\n animationDuration = 600,\n iterations = 2,\n padding = 2,\n multiline = true,\n isView = false,\n}: HighlighterProps) {\n const elementRef = useRef<HTMLSpanElement>(null)\n const annotationRef = useRef<RoughAnnotation | null>(null)\n\n const isInView = useInView(elementRef, {\n once: true,\n margin: \"-10%\",\n })\n\n // If isView is false, always show. If isView is true, wait for inView\n const shouldShow = !isView || isInView\n\n useEffect(() => {\n if (!shouldShow) return\n\n const element = elementRef.current\n if (!element) return\n\n const annotationConfig = {\n type: action,\n color,\n strokeWidth,\n animationDuration,\n iterations,\n padding,\n multiline,\n }\n\n const annotation = annotate(element, annotationConfig)\n\n annotationRef.current = annotation\n annotationRef.current.show()\n\n const resizeObserver = new ResizeObserver(() => {\n annotation.hide()\n annotation.show()\n })\n\n resizeObserver.observe(element)\n resizeObserver.observe(document.body)\n\n return () => {\n if (element) {\n annotate(element, { type: action }).remove()\n resizeObserver.disconnect()\n }\n }\n }, [\n shouldShow,\n action,\n color,\n strokeWidth,\n animationDuration,\n iterations,\n padding,\n multiline,\n ])\n\n return (\n <span ref={elementRef} className=\"relative inline-block bg-transparent\">\n {children}\n </span>\n )\n}\n",
+ "content": "\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport type React from \"react\"\nimport { useInView } from \"motion/react\"\nimport { annotate } from \"rough-notation\"\nimport { type RoughAnnotation } from \"rough-notation/lib/model\"\n\ntype AnnotationAction =\n | \"highlight\"\n | \"underline\"\n | \"box\"\n | \"circle\"\n | \"strike-through\"\n | \"crossed-off\"\n | \"bracket\"\n\ninterface HighlighterProps {\n children: React.ReactNode\n action?: AnnotationAction\n color?: string\n strokeWidth?: number\n animationDuration?: number\n iterations?: number\n padding?: number\n multiline?: boolean\n isView?: boolean\n}\n\nexport function Highlighter({\n children,\n action = \"highlight\",\n color = \"#ffd1dc\",\n strokeWidth = 1.5,\n animationDuration = 600,\n iterations = 2,\n padding = 2,\n multiline = true,\n isView = false,\n}: HighlighterProps) {\n const elementRef = useRef<HTMLSpanElement>(null)\n const annotationRef = useRef<RoughAnnotation | null>(null)\n\n const isInView = useInView(elementRef, {\n once: true,\n margin: \"-10%\",\n })\n\n // If isView is false, always show. If isView is true, wait for inView\n const shouldShow = !isView || isInView\n\n useEffect(() => {\n const element = elementRef.current\n let resizeObserver: ResizeObserver | null = null\n\n if (shouldShow && element) {\n const annotationConfig = {\n type: action,\n color,\n strokeWidth,\n animationDuration,\n iterations,\n padding,\n multiline,\n }\n\n const annotation = annotate(element, annotationConfig)\n\n annotationRef.current = annotation\n annotation.show()\n\n resizeObserver = new ResizeObserver(() => {\n annotation.hide()\n annotation.show()\n })\n\n resizeObserver.observe(element)\n resizeObserver.observe(document.body)\n }\n\n return () => {\n if (annotationRef.current) {\n annotationRef.current.remove()\n annotationRef.current = null\n }\n if (resizeObserver) {\n resizeObserver.disconnect()\n }\n }\n }, [\n shouldShow,\n action,\n color,\n strokeWidth,\n animationDuration,\n iterations,\n padding,\n multiline,\n ])\n\n return (\n <span ref={elementRef} className=\"relative inline-block bg-transparent\">\n {children}\n </span>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/highlighter.json b/apps/www/public/r/highlighter.json
index 3a35e895..f8b3ce58 100644
--- a/apps/www/public/r/highlighter.json
+++ b/apps/www/public/r/highlighter.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/highlighter.tsx",
- "content": "\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport type React from \"react\"\nimport { useInView } from \"motion/react\"\nimport { annotate } from \"rough-notation\"\nimport { type RoughAnnotation } from \"rough-notation/lib/model\"\n\ntype AnnotationAction =\n | \"highlight\"\n | \"underline\"\n | \"box\"\n | \"circle\"\n | \"strike-through\"\n | \"crossed-off\"\n | \"bracket\"\n\ninterface HighlighterProps {\n children: React.ReactNode\n action?: AnnotationAction\n color?: string\n strokeWidth?: number\n animationDuration?: number\n iterations?: number\n padding?: number\n multiline?: boolean\n isView?: boolean\n}\n\nexport function Highlighter({\n children,\n action = \"highlight\",\n color = \"#ffd1dc\",\n strokeWidth = 1.5,\n animationDuration = 600,\n iterations = 2,\n padding = 2,\n multiline = true,\n isView = false,\n}: HighlighterProps) {\n const elementRef = useRef<HTMLSpanElement>(null)\n const annotationRef = useRef<RoughAnnotation | null>(null)\n\n const isInView = useInView(elementRef, {\n once: true,\n margin: \"-10%\",\n })\n\n // If isView is false, always show. If isView is true, wait for inView\n const shouldShow = !isView || isInView\n\n useEffect(() => {\n if (!shouldShow) return\n\n const element = elementRef.current\n if (!element) return\n\n const annotationConfig = {\n type: action,\n color,\n strokeWidth,\n animationDuration,\n iterations,\n padding,\n multiline,\n }\n\n const annotation = annotate(element, annotationConfig)\n\n annotationRef.current = annotation\n annotationRef.current.show()\n\n const resizeObserver = new ResizeObserver(() => {\n annotation.hide()\n annotation.show()\n })\n\n resizeObserver.observe(element)\n resizeObserver.observe(document.body)\n\n return () => {\n if (element) {\n annotate(element, { type: action }).remove()\n resizeObserver.disconnect()\n }\n }\n }, [\n shouldShow,\n action,\n color,\n strokeWidth,\n animationDuration,\n iterations,\n padding,\n multiline,\n ])\n\n return (\n <span ref={elementRef} className=\"relative inline-block bg-transparent\">\n {children}\n </span>\n )\n}\n",
+ "content": "\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport type React from \"react\"\nimport { useInView } from \"motion/react\"\nimport { annotate } from \"rough-notation\"\nimport { type RoughAnnotation } from \"rough-notation/lib/model\"\n\ntype AnnotationAction =\n | \"highlight\"\n | \"underline\"\n | \"box\"\n | \"circle\"\n | \"strike-through\"\n | \"crossed-off\"\n | \"bracket\"\n\ninterface HighlighterProps {\n children: React.ReactNode\n action?: AnnotationAction\n color?: string\n strokeWidth?: number\n animationDuration?: number\n iterations?: number\n padding?: number\n multiline?: boolean\n isView?: boolean\n}\n\nexport function Highlighter({\n children,\n action = \"highlight\",\n color = \"#ffd1dc\",\n strokeWidth = 1.5,\n animationDuration = 600,\n iterations = 2,\n padding = 2,\n multiline = true,\n isView = false,\n}: HighlighterProps) {\n const elementRef = useRef<HTMLSpanElement>(null)\n const annotationRef = useRef<RoughAnnotation | null>(null)\n\n const isInView = useInView(elementRef, {\n once: true,\n margin: \"-10%\",\n })\n\n // If isView is false, always show. If isView is true, wait for inView\n const shouldShow = !isView || isInView\n\n useEffect(() => {\n const element = elementRef.current\n let resizeObserver: ResizeObserver | null = null\n\n if (shouldShow && element) {\n const annotationConfig = {\n type: action,\n color,\n strokeWidth,\n animationDuration,\n iterations,\n padding,\n multiline,\n }\n\n const annotation = annotate(element, annotationConfig)\n\n annotationRef.current = annotation\n annotation.show()\n\n resizeObserver = new ResizeObserver(() => {\n annotation.hide()\n annotation.show()\n })\n\n resizeObserver.observe(element)\n resizeObserver.observe(document.body)\n }\n\n return () => {\n if (annotationRef.current) {\n annotationRef.current.remove()\n annotationRef.current = null\n }\n if (resizeObserver) {\n resizeObserver.disconnect()\n }\n }\n }, [\n shouldShow,\n action,\n color,\n strokeWidth,\n animationDuration,\n iterations,\n padding,\n multiline,\n ])\n\n return (\n <span ref={elementRef} className=\"relative inline-block bg-transparent\">\n {children}\n </span>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/hyper-text.json b/apps/www/public/r/hyper-text.json
index 99afbe19..e9737d04 100644
--- a/apps/www/public/r/hyper-text.json
+++ b/apps/www/public/r/hyper-text.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/hyper-text.tsx",
- "content": "\"use client\"\n\nimport {\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type RefAttributes,\n} from \"react\"\nimport {\n AnimatePresence,\n motion,\n type DOMMotionComponents,\n type HTMLMotionProps,\n type MotionProps,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\ntype CharacterSet = string[] | readonly string[]\n\nconst motionElements = {\n article: motion.article,\n div: motion.div,\n h1: motion.h1,\n h2: motion.h2,\n h3: motion.h3,\n h4: motion.h4,\n h5: motion.h5,\n h6: motion.h6,\n li: motion.li,\n p: motion.p,\n section: motion.section,\n span: motion.span,\n} as const\n\ntype MotionElementType = Extract<\n keyof DOMMotionComponents,\n keyof typeof motionElements\n>\ntype HyperTextMotionComponent = ComponentType<\n Omit<HTMLMotionProps<\"div\">, \"ref\"> & RefAttributes<HTMLElement>\n>\n\ninterface HyperTextProps extends Omit<MotionProps, \"children\"> {\n /** The text content to be animated */\n children: string\n /** Optional className for styling */\n className?: string\n /** Duration of the animation in milliseconds */\n duration?: number\n /** Delay before animation starts in milliseconds */\n delay?: number\n /** Component to render as - defaults to div */\n as?: MotionElementType\n /** Whether to start animation when element comes into view */\n startOnView?: boolean\n /** Whether to trigger animation on hover */\n animateOnHover?: boolean\n /** Custom character set for scramble effect. Defaults to uppercase alphabet */\n characterSet?: CharacterSet\n}\n\nconst DEFAULT_CHARACTER_SET = Object.freeze(\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".split(\"\")\n) as readonly string[]\n\nconst getRandomInt = (max: number): number => Math.floor(Math.random() * max)\n\nexport function HyperText({\n children,\n className,\n duration = 800,\n delay = 0,\n as: Component = \"div\",\n startOnView = false,\n animateOnHover = true,\n characterSet = DEFAULT_CHARACTER_SET,\n ...props\n}: HyperTextProps) {\n const MotionComponent = motionElements[Component] as HyperTextMotionComponent\n\n const [displayText, setDisplayText] = useState<string[]>(() =>\n children.split(\"\")\n )\n const [isAnimating, setIsAnimating] = useState(false)\n const iterationCount = useRef(0)\n const elementRef = useRef<HTMLElement | null>(null)\n\n const handleAnimationTrigger = () => {\n if (animateOnHover && !isAnimating) {\n iterationCount.current = 0\n setIsAnimating(true)\n }\n }\n\n // Handle animation start based on view or delay\n useEffect(() => {\n if (!startOnView) {\n const startTimeout = setTimeout(() => {\n setIsAnimating(true)\n }, delay)\n return () => clearTimeout(startTimeout)\n }\n\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) {\n setTimeout(() => {\n setIsAnimating(true)\n }, delay)\n observer.disconnect()\n }\n },\n { threshold: 0.1, rootMargin: \"-30% 0px -30% 0px\" }\n )\n\n if (elementRef.current) {\n observer.observe(elementRef.current)\n }\n\n return () => observer.disconnect()\n }, [delay, startOnView])\n\n // Handle scramble animation\n useEffect(() => {\n if (!isAnimating) return\n\n const maxIterations = children.length\n const startTime = performance.now()\n let animationFrameId: number\n\n const animate = (currentTime: number) => {\n const elapsed = currentTime - startTime\n const progress = Math.min(elapsed / duration, 1)\n\n iterationCount.current = progress * maxIterations\n\n setDisplayText((currentText) =>\n currentText.map((letter, index) =>\n letter === \" \"\n ? letter\n : index <= iterationCount.current\n ? children[index]\n : characterSet[getRandomInt(characterSet.length)]\n )\n )\n\n if (progress < 1) {\n animationFrameId = requestAnimationFrame(animate)\n } else {\n setIsAnimating(false)\n }\n }\n\n animationFrameId = requestAnimationFrame(animate)\n\n return () => cancelAnimationFrame(animationFrameId)\n }, [children, duration, isAnimating, characterSet])\n\n return (\n <MotionComponent\n ref={elementRef}\n className={cn(\"overflow-hidden py-2 text-4xl font-bold\", className)}\n onMouseEnter={handleAnimationTrigger}\n {...props}\n >\n <AnimatePresence>\n {displayText.map((letter, index) => (\n <motion.span\n key={index}\n className={cn(\"font-mono\", letter === \" \" ? \"w-3\" : \"\")}\n >\n {letter.toUpperCase()}\n </motion.span>\n ))}\n </AnimatePresence>\n </MotionComponent>\n )\n}\n",
+ "content": "\"use client\"\n\nimport {\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type RefAttributes,\n} from \"react\"\nimport {\n AnimatePresence,\n motion,\n type DOMMotionComponents,\n type HTMLMotionProps,\n type MotionProps,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\ntype CharacterSet = string[] | readonly string[]\n\nconst motionElements = {\n article: motion.article,\n div: motion.div,\n h1: motion.h1,\n h2: motion.h2,\n h3: motion.h3,\n h4: motion.h4,\n h5: motion.h5,\n h6: motion.h6,\n li: motion.li,\n p: motion.p,\n section: motion.section,\n span: motion.span,\n} as const\n\ntype MotionElementType = Extract<\n keyof DOMMotionComponents,\n keyof typeof motionElements\n>\ntype HyperTextMotionComponent = ComponentType<\n Omit<HTMLMotionProps<\"div\">, \"ref\"> & RefAttributes<HTMLElement>\n>\n\ninterface HyperTextProps extends Omit<MotionProps, \"children\"> {\n /** The text content to be animated */\n children: string\n /** Optional className for styling */\n className?: string\n /** Duration of the animation in milliseconds */\n duration?: number\n /** Delay before animation starts in milliseconds */\n delay?: number\n /** Component to render as - defaults to div */\n as?: MotionElementType\n /** Whether to start animation when element comes into view */\n startOnView?: boolean\n /** Whether to trigger animation on hover */\n animateOnHover?: boolean\n /** Custom character set for scramble effect. Defaults to uppercase alphabet */\n characterSet?: CharacterSet\n}\n\nconst DEFAULT_CHARACTER_SET = Object.freeze(\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".split(\"\")\n) as readonly string[]\n\nconst getRandomInt = (max: number): number => Math.floor(Math.random() * max)\n\nexport function HyperText({\n children,\n className,\n duration = 800,\n delay = 0,\n as: Component = \"div\",\n startOnView = false,\n animateOnHover = true,\n characterSet = DEFAULT_CHARACTER_SET,\n ...props\n}: HyperTextProps) {\n const MotionComponent = motionElements[Component] as HyperTextMotionComponent\n\n const [displayText, setDisplayText] = useState<string[]>(() =>\n children.split(\"\")\n )\n const [isAnimating, setIsAnimating] = useState(false)\n const iterationCount = useRef(0)\n const elementRef = useRef<HTMLElement | null>(null)\n\n const handleAnimationTrigger = () => {\n if (animateOnHover && !isAnimating) {\n iterationCount.current = 0\n setIsAnimating(true)\n }\n }\n\n // Handle animation start based on view or delay\n useEffect(() => {\n if (!startOnView) {\n const startTimeout = setTimeout(() => {\n setIsAnimating(true)\n }, delay)\n return () => clearTimeout(startTimeout)\n }\n\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) {\n setTimeout(() => {\n setIsAnimating(true)\n }, delay)\n observer.disconnect()\n }\n },\n { threshold: 0.1, rootMargin: \"-30% 0px -30% 0px\" }\n )\n\n if (elementRef.current) {\n observer.observe(elementRef.current)\n }\n\n return () => observer.disconnect()\n }, [delay, startOnView])\n\n // Handle scramble animation\n useEffect(() => {\n let animationFrameId: number | null = null\n\n if (isAnimating) {\n const maxIterations = children.length\n const startTime = performance.now()\n\n const animate = (currentTime: number) => {\n const elapsed = currentTime - startTime\n const progress = Math.min(elapsed / duration, 1)\n\n iterationCount.current = progress * maxIterations\n\n setDisplayText((currentText) =>\n currentText.map((letter, index) =>\n letter === \" \"\n ? letter\n : index <= iterationCount.current\n ? children[index]\n : characterSet[getRandomInt(characterSet.length)]\n )\n )\n\n if (progress < 1) {\n animationFrameId = requestAnimationFrame(animate)\n } else {\n setIsAnimating(false)\n }\n }\n\n animationFrameId = requestAnimationFrame(animate)\n }\n\n return () => {\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId)\n }\n }\n }, [children, duration, isAnimating, characterSet])\n\n return (\n <MotionComponent\n ref={elementRef}\n className={cn(\"overflow-hidden py-2 text-4xl font-bold\", className)}\n onMouseEnter={handleAnimationTrigger}\n {...props}\n >\n <AnimatePresence>\n {displayText.map((letter, index) => (\n <motion.span\n key={index}\n className={cn(\"font-mono\", letter === \" \" ? \"w-3\" : \"\")}\n >\n {letter.toUpperCase()}\n </motion.span>\n ))}\n </AnimatePresence>\n </MotionComponent>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/icon-cloud.json b/apps/www/public/r/icon-cloud.json
index 412ba23e..ee894ac5 100644
--- a/apps/www/public/r/icon-cloud.json
+++ b/apps/www/public/r/icon-cloud.json
@@ -8,7 +8,7 @@
"files": [
{
"path": "registry/magicui/icon-cloud.tsx",
- "content": "\"use client\"\n\nimport React, { useEffect, useRef, useState } from \"react\"\nimport { renderToString } from \"react-dom/server\"\n\ninterface Icon {\n x: number\n y: number\n z: number\n scale: number\n opacity: number\n id: number\n}\n\ninterface IconCloudProps {\n icons?: React.ReactNode[]\n images?: string[]\n}\n\nfunction easeOutCubic(t: number): number {\n return 1 - Math.pow(1 - t, 3)\n}\n\nexport function IconCloud({ icons, images }: IconCloudProps) {\n const canvasRef = useRef<HTMLCanvasElement>(null)\n const [iconPositions, setIconPositions] = useState<Icon[]>([])\n const [rotation, setRotation] = useState({ x: 0, y: 0 })\n const [isDragging, setIsDragging] = useState(false)\n const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 })\n const [mousePos, setMousePos] = useState({ x: 0, y: 0 })\n const [targetRotation, setTargetRotation] = useState<{\n x: number\n y: number\n startX: number\n startY: number\n distance: number\n startTime: number\n duration: number\n } | null>(null)\n const animationFrameRef = useRef<number>(0)\n const rotationRef = useRef(rotation)\n const iconCanvasesRef = useRef<HTMLCanvasElement[]>([])\n const imagesLoadedRef = useRef<boolean[]>([])\n\n // Create icon canvases once when icons/images change\n useEffect(() => {\n if (!icons && !images) return\n\n const items = icons ?? images ?? []\n imagesLoadedRef.current = new Array(items.length).fill(false)\n\n const newIconCanvases = items.map((item, index) => {\n const offscreen = document.createElement(\"canvas\")\n offscreen.width = 40\n offscreen.height = 40\n const offCtx = offscreen.getContext(\"2d\")\n\n if (offCtx) {\n if (images) {\n // Handle image URLs directly\n const img = new Image()\n img.crossOrigin = \"anonymous\"\n img.src = items[index] as string\n img.onload = () => {\n offCtx.clearRect(0, 0, offscreen.width, offscreen.height)\n\n // Create circular clipping path\n offCtx.beginPath()\n offCtx.arc(20, 20, 20, 0, Math.PI * 2)\n offCtx.closePath()\n offCtx.clip()\n\n // Draw the image\n offCtx.drawImage(img, 0, 0, 40, 40)\n\n imagesLoadedRef.current[index] = true\n }\n } else {\n // Handle SVG icons\n offCtx.scale(0.4, 0.4)\n const svgString = renderToString(item as React.ReactElement)\n const img = new Image()\n img.src = \"data:image/svg+xml;base64,\" + btoa(svgString)\n img.onload = () => {\n offCtx.clearRect(0, 0, offscreen.width, offscreen.height)\n offCtx.drawImage(img, 0, 0)\n imagesLoadedRef.current[index] = true\n }\n }\n }\n return offscreen\n })\n\n iconCanvasesRef.current = newIconCanvases\n }, [icons, images])\n\n // Generate initial icon positions on a sphere\n useEffect(() => {\n const items = icons ?? images ?? []\n const newIcons: Icon[] = []\n const numIcons = items.length || 20\n\n // Fibonacci sphere parameters\n const offset = 2 / numIcons\n const increment = Math.PI * (3 - Math.sqrt(5))\n\n for (let i = 0; i < numIcons; i++) {\n const y = i * offset - 1 + offset / 2\n const r = Math.sqrt(1 - y * y)\n const phi = i * increment\n\n const x = Math.cos(phi) * r\n const z = Math.sin(phi) * r\n\n newIcons.push({\n x: x * 100,\n y: y * 100,\n z: z * 100,\n scale: 1,\n opacity: 1,\n id: i,\n })\n }\n setIconPositions(newIcons)\n }, [icons, images])\n\n // Handle mouse events\n const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {\n const rect = canvasRef.current?.getBoundingClientRect()\n if (!rect || !canvasRef.current) return\n\n const x = e.clientX - rect.left\n const y = e.clientY - rect.top\n\n const ctx = canvasRef.current.getContext(\"2d\")\n if (!ctx) return\n\n iconPositions.forEach((icon) => {\n const cosX = Math.cos(rotationRef.current.x)\n const sinX = Math.sin(rotationRef.current.x)\n const cosY = Math.cos(rotationRef.current.y)\n const sinY = Math.sin(rotationRef.current.y)\n\n const rotatedX = icon.x * cosY - icon.z * sinY\n const rotatedZ = icon.x * sinY + icon.z * cosY\n const rotatedY = icon.y * cosX + rotatedZ * sinX\n\n const screenX = canvasRef.current!.width / 2 + rotatedX\n const screenY = canvasRef.current!.height / 2 + rotatedY\n\n const scale = (rotatedZ + 200) / 300\n const radius = 20 * scale\n const dx = x - screenX\n const dy = y - screenY\n\n if (dx * dx + dy * dy < radius * radius) {\n const targetX = -Math.atan2(\n icon.y,\n Math.sqrt(icon.x * icon.x + icon.z * icon.z)\n )\n const targetY = Math.atan2(icon.x, icon.z)\n\n const currentX = rotationRef.current.x\n const currentY = rotationRef.current.y\n const distance = Math.sqrt(\n Math.pow(targetX - currentX, 2) + Math.pow(targetY - currentY, 2)\n )\n\n const duration = Math.min(2000, Math.max(800, distance * 1000))\n\n setTargetRotation({\n x: targetX,\n y: targetY,\n startX: currentX,\n startY: currentY,\n distance,\n startTime: performance.now(),\n duration,\n })\n return\n }\n })\n\n setIsDragging(true)\n setLastMousePos({ x: e.clientX, y: e.clientY })\n }\n\n const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {\n const rect = canvasRef.current?.getBoundingClientRect()\n if (rect) {\n const x = e.clientX - rect.left\n const y = e.clientY - rect.top\n setMousePos({ x, y })\n }\n\n if (isDragging) {\n const deltaX = e.clientX - lastMousePos.x\n const deltaY = e.clientY - lastMousePos.y\n\n rotationRef.current = {\n x: rotationRef.current.x + deltaY * 0.002,\n y: rotationRef.current.y + deltaX * 0.002,\n }\n\n setLastMousePos({ x: e.clientX, y: e.clientY })\n }\n }\n\n const handleMouseUp = () => {\n setIsDragging(false)\n }\n\n // Animation and rendering\n useEffect(() => {\n const canvas = canvasRef.current\n const ctx = canvas?.getContext(\"2d\")\n if (!canvas || !ctx) return\n\n const animate = () => {\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n\n const centerX = canvas.width / 2\n const centerY = canvas.height / 2\n const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY)\n const dx = mousePos.x - centerX\n const dy = mousePos.y - centerY\n const distance = Math.sqrt(dx * dx + dy * dy)\n const speed = 0.003 + (distance / maxDistance) * 0.01\n\n if (targetRotation) {\n const elapsed = performance.now() - targetRotation.startTime\n const progress = Math.min(1, elapsed / targetRotation.duration)\n const easedProgress = easeOutCubic(progress)\n\n rotationRef.current = {\n x:\n targetRotation.startX +\n (targetRotation.x - targetRotation.startX) * easedProgress,\n y:\n targetRotation.startY +\n (targetRotation.y - targetRotation.startY) * easedProgress,\n }\n\n if (progress >= 1) {\n setTargetRotation(null)\n }\n } else if (!isDragging) {\n rotationRef.current = {\n x: rotationRef.current.x + (dy / canvas.height) * speed,\n y: rotationRef.current.y + (dx / canvas.width) * speed,\n }\n }\n\n iconPositions.forEach((icon, index) => {\n const cosX = Math.cos(rotationRef.current.x)\n const sinX = Math.sin(rotationRef.current.x)\n const cosY = Math.cos(rotationRef.current.y)\n const sinY = Math.sin(rotationRef.current.y)\n\n const rotatedX = icon.x * cosY - icon.z * sinY\n const rotatedZ = icon.x * sinY + icon.z * cosY\n const rotatedY = icon.y * cosX + rotatedZ * sinX\n\n const scale = (rotatedZ + 200) / 300\n const opacity = Math.max(0.2, Math.min(1, (rotatedZ + 150) / 200))\n\n ctx.save()\n ctx.translate(canvas.width / 2 + rotatedX, canvas.height / 2 + rotatedY)\n ctx.scale(scale, scale)\n ctx.globalAlpha = opacity\n\n if (icons || images) {\n // Only try to render icons/images if they exist\n if (\n iconCanvasesRef.current[index] &&\n imagesLoadedRef.current[index]\n ) {\n ctx.drawImage(iconCanvasesRef.current[index], -20, -20, 40, 40)\n }\n } else {\n // Show numbered circles if no icons/images are provided\n ctx.beginPath()\n ctx.arc(0, 0, 20, 0, Math.PI * 2)\n ctx.fillStyle = \"#4444ff\"\n ctx.fill()\n ctx.fillStyle = \"white\"\n ctx.textAlign = \"center\"\n ctx.textBaseline = \"middle\"\n ctx.font = \"16px Arial\"\n ctx.fillText(`${icon.id + 1}`, 0, 0)\n }\n\n ctx.restore()\n })\n animationFrameRef.current = requestAnimationFrame(animate)\n }\n\n animate()\n\n return () => {\n if (animationFrameRef.current) {\n cancelAnimationFrame(animationFrameRef.current)\n }\n }\n }, [icons, images, iconPositions, isDragging, mousePos, targetRotation])\n\n return (\n <canvas\n ref={canvasRef}\n width={400}\n height={400}\n onMouseDown={handleMouseDown}\n onMouseMove={handleMouseMove}\n onMouseUp={handleMouseUp}\n onMouseLeave={handleMouseUp}\n className=\"rounded-lg\"\n aria-label=\"Interactive 3D Icon Cloud\"\n role=\"img\"\n />\n )\n}\n",
+ "content": "\"use client\"\n\nimport React, { useEffect, useRef, useState } from \"react\"\nimport { renderToString } from \"react-dom/server\"\n\ninterface Icon {\n x: number\n y: number\n z: number\n scale: number\n opacity: number\n id: number\n}\n\ninterface IconCloudProps {\n icons?: React.ReactNode[]\n images?: string[]\n}\n\nfunction easeOutCubic(t: number): number {\n return 1 - Math.pow(1 - t, 3)\n}\n\nexport function IconCloud({ icons, images }: IconCloudProps) {\n const canvasRef = useRef<HTMLCanvasElement>(null)\n const [iconPositions, setIconPositions] = useState<Icon[]>([])\n const [rotation, setRotation] = useState({ x: 0, y: 0 })\n const [isDragging, setIsDragging] = useState(false)\n const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 })\n const [mousePos, setMousePos] = useState({ x: 0, y: 0 })\n const [targetRotation, setTargetRotation] = useState<{\n x: number\n y: number\n startX: number\n startY: number\n distance: number\n startTime: number\n duration: number\n } | null>(null)\n const animationFrameRef = useRef<number>(0)\n const rotationRef = useRef(rotation)\n const iconCanvasesRef = useRef<HTMLCanvasElement[]>([])\n const imagesLoadedRef = useRef<boolean[]>([])\n\n // Create icon canvases once when icons/images change\n useEffect(() => {\n if (!icons && !images) return\n\n const items = icons ?? images ?? []\n imagesLoadedRef.current = new Array(items.length).fill(false)\n\n const newIconCanvases = items.map((item, index) => {\n const offscreen = document.createElement(\"canvas\")\n offscreen.width = 40\n offscreen.height = 40\n const offCtx = offscreen.getContext(\"2d\")\n\n if (offCtx) {\n if (images) {\n // Handle image URLs directly\n const img = new Image()\n img.crossOrigin = \"anonymous\"\n img.src = items[index] as string\n img.onload = () => {\n offCtx.clearRect(0, 0, offscreen.width, offscreen.height)\n\n // Create circular clipping path\n offCtx.beginPath()\n offCtx.arc(20, 20, 20, 0, Math.PI * 2)\n offCtx.closePath()\n offCtx.clip()\n\n // Draw the image\n offCtx.drawImage(img, 0, 0, 40, 40)\n\n imagesLoadedRef.current[index] = true\n }\n } else {\n // Handle SVG icons\n offCtx.scale(0.4, 0.4)\n const svgString = renderToString(item as React.ReactElement)\n const img = new Image()\n img.src = \"data:image/svg+xml;base64,\" + btoa(svgString)\n img.onload = () => {\n offCtx.clearRect(0, 0, offscreen.width, offscreen.height)\n offCtx.drawImage(img, 0, 0)\n imagesLoadedRef.current[index] = true\n }\n }\n }\n return offscreen\n })\n\n iconCanvasesRef.current = newIconCanvases\n }, [icons, images])\n\n // Generate initial icon positions on a sphere\n useEffect(() => {\n const items = icons ?? images ?? []\n const newIcons: Icon[] = []\n const numIcons = items.length || 20\n\n // Fibonacci sphere parameters\n const offset = 2 / numIcons\n const increment = Math.PI * (3 - Math.sqrt(5))\n\n for (let i = 0; i < numIcons; i++) {\n const y = i * offset - 1 + offset / 2\n const r = Math.sqrt(1 - y * y)\n const phi = i * increment\n\n const x = Math.cos(phi) * r\n const z = Math.sin(phi) * r\n\n newIcons.push({\n x: x * 100,\n y: y * 100,\n z: z * 100,\n scale: 1,\n opacity: 1,\n id: i,\n })\n }\n setIconPositions(newIcons)\n }, [icons, images])\n\n // Handle mouse events\n const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {\n const rect = canvasRef.current?.getBoundingClientRect()\n if (!rect || !canvasRef.current) return\n\n const x = e.clientX - rect.left\n const y = e.clientY - rect.top\n\n const ctx = canvasRef.current.getContext(\"2d\")\n if (!ctx) return\n\n iconPositions.forEach((icon) => {\n const cosX = Math.cos(rotationRef.current.x)\n const sinX = Math.sin(rotationRef.current.x)\n const cosY = Math.cos(rotationRef.current.y)\n const sinY = Math.sin(rotationRef.current.y)\n\n const rotatedX = icon.x * cosY - icon.z * sinY\n const rotatedZ = icon.x * sinY + icon.z * cosY\n const rotatedY = icon.y * cosX + rotatedZ * sinX\n\n const screenX = canvasRef.current!.width / 2 + rotatedX\n const screenY = canvasRef.current!.height / 2 + rotatedY\n\n const scale = (rotatedZ + 200) / 300\n const radius = 20 * scale\n const dx = x - screenX\n const dy = y - screenY\n\n if (dx * dx + dy * dy < radius * radius) {\n const targetX = -Math.atan2(\n icon.y,\n Math.sqrt(icon.x * icon.x + icon.z * icon.z)\n )\n const targetY = Math.atan2(icon.x, icon.z)\n\n const currentX = rotationRef.current.x\n const currentY = rotationRef.current.y\n const distance = Math.sqrt(\n Math.pow(targetX - currentX, 2) + Math.pow(targetY - currentY, 2)\n )\n\n const duration = Math.min(2000, Math.max(800, distance * 1000))\n\n setTargetRotation({\n x: targetX,\n y: targetY,\n startX: currentX,\n startY: currentY,\n distance,\n startTime: performance.now(),\n duration,\n })\n return\n }\n })\n\n setIsDragging(true)\n setLastMousePos({ x: e.clientX, y: e.clientY })\n }\n\n const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {\n const rect = canvasRef.current?.getBoundingClientRect()\n if (rect) {\n const x = e.clientX - rect.left\n const y = e.clientY - rect.top\n setMousePos({ x, y })\n }\n\n if (isDragging) {\n const deltaX = e.clientX - lastMousePos.x\n const deltaY = e.clientY - lastMousePos.y\n\n rotationRef.current = {\n x: rotationRef.current.x + deltaY * 0.002,\n y: rotationRef.current.y + deltaX * 0.002,\n }\n\n setLastMousePos({ x: e.clientX, y: e.clientY })\n }\n }\n\n const handleMouseUp = () => {\n setIsDragging(false)\n }\n\n // Animation and rendering\n useEffect(() => {\n const canvas = canvasRef.current\n const ctx = canvas?.getContext(\"2d\")\n if (canvas && ctx) {\n const animate = () => {\n ctx.clearRect(0, 0, canvas.width, canvas.height)\n\n const centerX = canvas.width / 2\n const centerY = canvas.height / 2\n const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY)\n const dx = mousePos.x - centerX\n const dy = mousePos.y - centerY\n const distance = Math.sqrt(dx * dx + dy * dy)\n const speed = 0.003 + (distance / maxDistance) * 0.01\n\n if (targetRotation) {\n const elapsed = performance.now() - targetRotation.startTime\n const progress = Math.min(1, elapsed / targetRotation.duration)\n const easedProgress = easeOutCubic(progress)\n\n rotationRef.current = {\n x:\n targetRotation.startX +\n (targetRotation.x - targetRotation.startX) * easedProgress,\n y:\n targetRotation.startY +\n (targetRotation.y - targetRotation.startY) * easedProgress,\n }\n\n if (progress >= 1) {\n setTargetRotation(null)\n }\n } else if (!isDragging) {\n rotationRef.current = {\n x: rotationRef.current.x + (dy / canvas.height) * speed,\n y: rotationRef.current.y + (dx / canvas.width) * speed,\n }\n }\n\n iconPositions.forEach((icon, index) => {\n const cosX = Math.cos(rotationRef.current.x)\n const sinX = Math.sin(rotationRef.current.x)\n const cosY = Math.cos(rotationRef.current.y)\n const sinY = Math.sin(rotationRef.current.y)\n\n const rotatedX = icon.x * cosY - icon.z * sinY\n const rotatedZ = icon.x * sinY + icon.z * cosY\n const rotatedY = icon.y * cosX + rotatedZ * sinX\n\n const scale = (rotatedZ + 200) / 300\n const opacity = Math.max(0.2, Math.min(1, (rotatedZ + 150) / 200))\n\n ctx.save()\n ctx.translate(\n canvas.width / 2 + rotatedX,\n canvas.height / 2 + rotatedY\n )\n ctx.scale(scale, scale)\n ctx.globalAlpha = opacity\n\n if (icons || images) {\n // Only try to render icons/images if they exist\n if (\n iconCanvasesRef.current[index] &&\n imagesLoadedRef.current[index]\n ) {\n ctx.drawImage(iconCanvasesRef.current[index], -20, -20, 40, 40)\n }\n } else {\n // Show numbered circles if no icons/images are provided\n ctx.beginPath()\n ctx.arc(0, 0, 20, 0, Math.PI * 2)\n ctx.fillStyle = \"#4444ff\"\n ctx.fill()\n ctx.fillStyle = \"white\"\n ctx.textAlign = \"center\"\n ctx.textBaseline = \"middle\"\n ctx.font = \"16px Arial\"\n ctx.fillText(`${icon.id + 1}`, 0, 0)\n }\n\n ctx.restore()\n })\n animationFrameRef.current = requestAnimationFrame(animate)\n }\n\n animate()\n }\n\n return () => {\n if (animationFrameRef.current) {\n cancelAnimationFrame(animationFrameRef.current)\n }\n }\n }, [icons, images, iconPositions, isDragging, mousePos, targetRotation])\n\n return (\n <canvas\n ref={canvasRef}\n width={400}\n height={400}\n onMouseDown={handleMouseDown}\n onMouseMove={handleMouseMove}\n onMouseUp={handleMouseUp}\n onMouseLeave={handleMouseUp}\n className=\"rounded-lg\"\n aria-label=\"Interactive 3D Icon Cloud\"\n role=\"img\"\n />\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/number-ticker.json b/apps/www/public/r/number-ticker.json
index c2962ae9..0806dace 100644
--- a/apps/www/public/r/number-ticker.json
+++ b/apps/www/public/r/number-ticker.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/number-ticker.tsx",
- "content": "\"use client\"\n\nimport { useEffect, useRef, type ComponentPropsWithoutRef } from \"react\"\nimport { useInView, useMotionValue, useSpring } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface NumberTickerProps extends ComponentPropsWithoutRef<\"span\"> {\n value: number\n startValue?: number\n direction?: \"up\" | \"down\"\n delay?: number\n decimalPlaces?: number\n}\n\nexport function NumberTicker({\n value,\n startValue = 0,\n direction = \"up\",\n delay = 0,\n className,\n decimalPlaces = 0,\n ...props\n}: NumberTickerProps) {\n const ref = useRef<HTMLSpanElement>(null)\n const motionValue = useMotionValue(direction === \"down\" ? value : startValue)\n const springValue = useSpring(motionValue, {\n damping: 60,\n stiffness: 100,\n })\n const isInView = useInView(ref, { once: true, margin: \"0px\" })\n\n useEffect(() => {\n if (isInView) {\n const timer = setTimeout(() => {\n motionValue.set(direction === \"down\" ? startValue : value)\n }, delay * 1000)\n return () => clearTimeout(timer)\n }\n }, [motionValue, isInView, delay, value, direction, startValue])\n\n useEffect(\n () =>\n springValue.on(\"change\", (latest) => {\n if (ref.current) {\n ref.current.textContent = Intl.NumberFormat(\"en-US\", {\n minimumFractionDigits: decimalPlaces,\n maximumFractionDigits: decimalPlaces,\n }).format(Number(latest.toFixed(decimalPlaces)))\n }\n }),\n [springValue, decimalPlaces]\n )\n\n return (\n <span\n ref={ref}\n className={cn(\n \"inline-block tracking-wider text-black tabular-nums dark:text-white\",\n className\n )}\n {...props}\n >\n {startValue}\n </span>\n )\n}\n",
+ "content": "\"use client\"\n\nimport { useEffect, useRef, type ComponentPropsWithoutRef } from \"react\"\nimport { useInView, useMotionValue, useSpring } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface NumberTickerProps extends ComponentPropsWithoutRef<\"span\"> {\n value: number\n startValue?: number\n direction?: \"up\" | \"down\"\n delay?: number\n decimalPlaces?: number\n}\n\nexport function NumberTicker({\n value,\n startValue = 0,\n direction = \"up\",\n delay = 0,\n className,\n decimalPlaces = 0,\n ...props\n}: NumberTickerProps) {\n const ref = useRef<HTMLSpanElement>(null)\n const motionValue = useMotionValue(direction === \"down\" ? value : startValue)\n const springValue = useSpring(motionValue, {\n damping: 60,\n stiffness: 100,\n })\n const isInView = useInView(ref, { once: true, margin: \"0px\" })\n\n useEffect(() => {\n let timer: ReturnType<typeof setTimeout> | null = null\n\n if (isInView) {\n timer = setTimeout(() => {\n motionValue.set(direction === \"down\" ? startValue : value)\n }, delay * 1000)\n }\n\n return () => {\n if (timer !== null) {\n clearTimeout(timer)\n }\n }\n }, [motionValue, isInView, delay, value, direction, startValue])\n\n useEffect(\n () =>\n springValue.on(\"change\", (latest) => {\n if (ref.current) {\n ref.current.textContent = Intl.NumberFormat(\"en-US\", {\n minimumFractionDigits: decimalPlaces,\n maximumFractionDigits: decimalPlaces,\n }).format(Number(latest.toFixed(decimalPlaces)))\n }\n }),\n [springValue, decimalPlaces]\n )\n\n return (\n <span\n ref={ref}\n className={cn(\n \"inline-block tracking-wider text-black tabular-nums dark:text-white\",\n className\n )}\n {...props}\n >\n {startValue}\n </span>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/pointer.json b/apps/www/public/r/pointer.json
index 7bee8f18..65c36887 100644
--- a/apps/www/public/r/pointer.json
+++ b/apps/www/public/r/pointer.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/pointer.tsx",
- "content": "\"use client\"\n\nimport { useEffect, useRef, useState } from \"react\"\nimport {\n AnimatePresence,\n HTMLMotionProps,\n motion,\n useMotionValue,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/**\n * A custom pointer component that displays an animated cursor.\n * Add this as a child to any component to enable a custom pointer when hovering.\n * You can pass custom children to render as the pointer.\n *\n * @component\n * @param {HTMLMotionProps<\"div\">} props - The component props\n */\nexport function Pointer({\n className,\n style,\n children,\n ...props\n}: HTMLMotionProps<\"div\">): React.ReactNode {\n const x = useMotionValue(0)\n const y = useMotionValue(0)\n const [isActive, setIsActive] = useState<boolean>(false)\n const containerRef = useRef<HTMLDivElement>(null)\n\n useEffect(() => {\n if (typeof window !== \"undefined\" && containerRef.current) {\n // Get the parent element directly from the ref\n const parentElement = containerRef.current.parentElement\n\n if (parentElement) {\n // Add cursor-none to parent\n parentElement.style.cursor = \"none\"\n\n // Add event listeners to parent\n const handleMouseMove = (e: MouseEvent) => {\n x.set(e.clientX)\n y.set(e.clientY)\n setIsActive(true)\n }\n\n const handleMouseEnter = (e: MouseEvent) => {\n x.set(e.clientX)\n y.set(e.clientY)\n setIsActive(true)\n }\n\n const handleMouseLeave = () => {\n setIsActive(false)\n }\n\n parentElement.addEventListener(\"mousemove\", handleMouseMove)\n parentElement.addEventListener(\"mouseenter\", handleMouseEnter)\n parentElement.addEventListener(\"mouseleave\", handleMouseLeave)\n\n return () => {\n parentElement.style.cursor = \"\"\n parentElement.removeEventListener(\"mousemove\", handleMouseMove)\n parentElement.removeEventListener(\"mouseenter\", handleMouseEnter)\n parentElement.removeEventListener(\"mouseleave\", handleMouseLeave)\n }\n }\n }\n }, [x, y])\n\n return (\n <>\n <div ref={containerRef} />\n <AnimatePresence>\n {isActive && (\n <motion.div\n className=\"pointer-events-none fixed z-50 transform-[translate(-50%,-50%)]\"\n style={{\n top: y,\n left: x,\n ...style,\n }}\n initial={{\n scale: 0,\n opacity: 0,\n }}\n animate={{\n scale: 1,\n opacity: 1,\n }}\n exit={{\n scale: 0,\n opacity: 0,\n }}\n {...props}\n >\n {children || (\n <svg\n stroke=\"currentColor\"\n fill=\"currentColor\"\n strokeWidth=\"1\"\n viewBox=\"0 0 16 16\"\n height=\"24\"\n width=\"24\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={cn(\n \"rotate-[-70deg] stroke-white text-black\",\n className\n )}\n >\n <path d=\"M14.082 2.182a.5.5 0 0 1 .103.557L8.528 15.467a.5.5 0 0 1-.917-.007L5.57 10.694.803 8.652a.5.5 0 0 1-.006-.916l12.728-5.657a.5.5 0 0 1 .556.103z\" />\n </svg>\n )}\n </motion.div>\n )}\n </AnimatePresence>\n </>\n )\n}\n",
+ "content": "\"use client\"\n\nimport { useEffect, useRef, useState } from \"react\"\nimport {\n AnimatePresence,\n HTMLMotionProps,\n motion,\n useMotionValue,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/**\n * A custom pointer component that displays an animated cursor.\n * Add this as a child to any component to enable a custom pointer when hovering.\n * You can pass custom children to render as the pointer.\n *\n * @component\n * @param {HTMLMotionProps<\"div\">} props - The component props\n */\nexport function Pointer({\n className,\n style,\n children,\n ...props\n}: HTMLMotionProps<\"div\">): React.ReactNode {\n const x = useMotionValue(0)\n const y = useMotionValue(0)\n const [isActive, setIsActive] = useState<boolean>(false)\n const containerRef = useRef<HTMLDivElement>(null)\n\n useEffect(() => {\n const parentElement =\n typeof window !== \"undefined\"\n ? (containerRef.current?.parentElement ?? null)\n : null\n\n const handleMouseMove = (e: MouseEvent) => {\n x.set(e.clientX)\n y.set(e.clientY)\n setIsActive(true)\n }\n\n const handleMouseEnter = (e: MouseEvent) => {\n x.set(e.clientX)\n y.set(e.clientY)\n setIsActive(true)\n }\n\n const handleMouseLeave = () => {\n setIsActive(false)\n }\n\n if (parentElement) {\n parentElement.style.cursor = \"none\"\n parentElement.addEventListener(\"mousemove\", handleMouseMove)\n parentElement.addEventListener(\"mouseenter\", handleMouseEnter)\n parentElement.addEventListener(\"mouseleave\", handleMouseLeave)\n }\n\n return () => {\n if (parentElement) {\n parentElement.style.cursor = \"\"\n parentElement.removeEventListener(\"mousemove\", handleMouseMove)\n parentElement.removeEventListener(\"mouseenter\", handleMouseEnter)\n parentElement.removeEventListener(\"mouseleave\", handleMouseLeave)\n }\n }\n }, [x, y])\n\n return (\n <>\n <div ref={containerRef} />\n <AnimatePresence>\n {isActive && (\n <motion.div\n className=\"pointer-events-none fixed z-50 transform-[translate(-50%,-50%)]\"\n style={{\n top: y,\n left: x,\n ...style,\n }}\n initial={{\n scale: 0,\n opacity: 0,\n }}\n animate={{\n scale: 1,\n opacity: 1,\n }}\n exit={{\n scale: 0,\n opacity: 0,\n }}\n {...props}\n >\n {children || (\n <svg\n stroke=\"currentColor\"\n fill=\"currentColor\"\n strokeWidth=\"1\"\n viewBox=\"0 0 16 16\"\n height=\"24\"\n width=\"24\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={cn(\n \"rotate-[-70deg] stroke-white text-black\",\n className\n )}\n >\n <path d=\"M14.082 2.182a.5.5 0 0 1 .103.557L8.528 15.467a.5.5 0 0 1-.917-.007L5.57 10.694.803 8.652a.5.5 0 0 1-.006-.916l12.728-5.657a.5.5 0 0 1 .556.103z\" />\n </svg>\n )}\n </motion.div>\n )}\n </AnimatePresence>\n </>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/ripple-button.json b/apps/www/public/r/ripple-button.json
index f4e6feb6..2731cb25 100644
--- a/apps/www/public/r/ripple-button.json
+++ b/apps/www/public/r/ripple-button.json
@@ -7,7 +7,7 @@
"files": [
{
"path": "registry/magicui/ripple-button.tsx",
- "content": "\"use client\"\n\nimport React, { MouseEvent, useEffect, useState } from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface RippleButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n rippleColor?: string\n duration?: string\n}\n\nexport const RippleButton = React.forwardRef<\n HTMLButtonElement,\n RippleButtonProps\n>(\n (\n {\n className,\n children,\n rippleColor = \"#ffffff\",\n duration = \"600ms\",\n onClick,\n ...props\n },\n ref\n ) => {\n const [buttonRipples, setButtonRipples] = useState<\n Array<{ x: number; y: number; size: number; key: number }>\n >([])\n\n const handleClick = (event: MouseEvent<HTMLButtonElement>) => {\n createRipple(event)\n onClick?.(event)\n }\n\n const createRipple = (event: MouseEvent<HTMLButtonElement>) => {\n const button = event.currentTarget\n const rect = button.getBoundingClientRect()\n const size = Math.max(rect.width, rect.height)\n const x = event.clientX - rect.left - size / 2\n const y = event.clientY - rect.top - size / 2\n\n const newRipple = { x, y, size, key: Date.now() }\n setButtonRipples((prevRipples) => [...prevRipples, newRipple])\n }\n\n useEffect(() => {\n if (buttonRipples.length > 0) {\n const lastRipple = buttonRipples[buttonRipples.length - 1]\n const timeout = setTimeout(() => {\n setButtonRipples((prevRipples) =>\n prevRipples.filter((ripple) => ripple.key !== lastRipple.key)\n )\n }, parseInt(duration))\n return () => clearTimeout(timeout)\n }\n }, [buttonRipples, duration])\n\n return (\n <button\n className={cn(\n \"bg-background text-primary relative flex cursor-pointer items-center justify-center overflow-hidden rounded-lg border-2 px-4 py-2 text-center\",\n className\n )}\n onClick={handleClick}\n ref={ref}\n {...props}\n >\n <div className=\"relative z-10\">{children}</div>\n <span className=\"pointer-events-none absolute inset-0\">\n {buttonRipples.map((ripple) => (\n <span\n className=\"animate-rippling bg-background absolute rounded-full opacity-30\"\n key={ripple.key}\n style={\n {\n width: `${ripple.size}px`,\n height: `${ripple.size}px`,\n top: `${ripple.y}px`,\n left: `${ripple.x}px`,\n backgroundColor: rippleColor,\n transform: `scale(0)`,\n \"--duration\": duration,\n } as React.CSSProperties\n }\n />\n ))}\n </span>\n </button>\n )\n }\n)\n\nRippleButton.displayName = \"RippleButton\"\n",
+ "content": "\"use client\"\n\nimport React, { MouseEvent, useEffect, useState } from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface RippleButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n rippleColor?: string\n duration?: string\n}\n\nexport const RippleButton = React.forwardRef<\n HTMLButtonElement,\n RippleButtonProps\n>(\n (\n {\n className,\n children,\n rippleColor = \"#ffffff\",\n duration = \"600ms\",\n onClick,\n ...props\n },\n ref\n ) => {\n const [buttonRipples, setButtonRipples] = useState<\n Array<{ x: number; y: number; size: number; key: number }>\n >([])\n\n const handleClick = (event: MouseEvent<HTMLButtonElement>) => {\n createRipple(event)\n onClick?.(event)\n }\n\n const createRipple = (event: MouseEvent<HTMLButtonElement>) => {\n const button = event.currentTarget\n const rect = button.getBoundingClientRect()\n const size = Math.max(rect.width, rect.height)\n const x = event.clientX - rect.left - size / 2\n const y = event.clientY - rect.top - size / 2\n\n const newRipple = { x, y, size, key: Date.now() }\n setButtonRipples((prevRipples) => [...prevRipples, newRipple])\n }\n\n useEffect(() => {\n let timeout: ReturnType<typeof setTimeout> | null = null\n\n if (buttonRipples.length > 0) {\n const lastRipple = buttonRipples[buttonRipples.length - 1]\n timeout = setTimeout(() => {\n setButtonRipples((prevRipples) =>\n prevRipples.filter((ripple) => ripple.key !== lastRipple.key)\n )\n }, parseInt(duration))\n }\n\n return () => {\n if (timeout !== null) {\n clearTimeout(timeout)\n }\n }\n }, [buttonRipples, duration])\n\n return (\n <button\n className={cn(\n \"bg-background text-primary relative flex cursor-pointer items-center justify-center overflow-hidden rounded-lg border-2 px-4 py-2 text-center\",\n className\n )}\n onClick={handleClick}\n ref={ref}\n {...props}\n >\n <div className=\"relative z-10\">{children}</div>\n <span className=\"pointer-events-none absolute inset-0\">\n {buttonRipples.map((ripple) => (\n <span\n className=\"animate-rippling bg-background absolute rounded-full opacity-30\"\n key={ripple.key}\n style={\n {\n width: `${ripple.size}px`,\n height: `${ripple.size}px`,\n top: `${ripple.y}px`,\n left: `${ripple.x}px`,\n backgroundColor: rippleColor,\n transform: `scale(0)`,\n \"--duration\": duration,\n } as React.CSSProperties\n }\n />\n ))}\n </span>\n </button>\n )\n }\n)\n\nRippleButton.displayName = \"RippleButton\"\n",
"type": "registry:ui"
}
],
diff --git a/apps/www/public/r/scroll-based-velocity.json b/apps/www/public/r/scroll-based-velocity.json
index 39aa940a..368bccf9 100644
--- a/apps/www/public/r/scroll-based-velocity.json
+++ b/apps/www/public/r/scroll-based-velocity.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/scroll-based-velocity.tsx",
- "content": "\"use client\"\n\nimport React, { useContext, useEffect, useRef, useState } from \"react\"\nimport {\n motion,\n useAnimationFrame,\n useMotionValue,\n useScroll,\n useSpring,\n useTransform,\n useVelocity,\n} from \"motion/react\"\nimport type { MotionValue } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface ScrollVelocityRowProps extends React.HTMLAttributes<HTMLDivElement> {\n children: React.ReactNode\n baseVelocity?: number\n direction?: 1 | -1\n scrollReactivity?: boolean\n}\n\nexport const wrap = (min: number, max: number, v: number) => {\n const rangeSize = max - min\n return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min\n}\n\nconst ScrollVelocityContext = React.createContext<MotionValue<number> | null>(\n null\n)\n\nexport function ScrollVelocityContainer({\n children,\n className,\n ...props\n}: React.HTMLAttributes<HTMLDivElement>) {\n const { scrollY } = useScroll()\n const scrollVelocity = useVelocity(scrollY)\n const smoothVelocity = useSpring(scrollVelocity, {\n damping: 50,\n stiffness: 400,\n })\n const velocityFactor = useTransform(smoothVelocity, (v) => {\n const sign = v < 0 ? -1 : 1\n const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5)\n return sign * magnitude\n })\n\n return (\n <ScrollVelocityContext.Provider value={velocityFactor}>\n <div className={cn(\"relative w-full\", className)} {...props}>\n {children}\n </div>\n </ScrollVelocityContext.Provider>\n )\n}\n\nexport function ScrollVelocityRow(props: ScrollVelocityRowProps) {\n const sharedVelocityFactor = useContext(ScrollVelocityContext)\n if (sharedVelocityFactor) {\n return (\n <ScrollVelocityRowImpl {...props} velocityFactor={sharedVelocityFactor} />\n )\n }\n return <ScrollVelocityRowLocal {...props} />\n}\n\ninterface ScrollVelocityRowImplProps extends ScrollVelocityRowProps {\n velocityFactor: MotionValue<number>\n}\n\nfunction ScrollVelocityRowImpl({\n children,\n baseVelocity = 5,\n direction = 1,\n className,\n velocityFactor,\n scrollReactivity = true,\n ...props\n}: ScrollVelocityRowImplProps) {\n const containerRef = useRef<HTMLDivElement>(null)\n const blockRef = useRef<HTMLDivElement>(null)\n const [numCopies, setNumCopies] = useState(1)\n\n const baseX = useMotionValue(0)\n const baseDirectionRef = useRef<number>(direction >= 0 ? 1 : -1)\n const currentDirectionRef = useRef<number>(direction >= 0 ? 1 : -1)\n const unitWidth = useMotionValue(0)\n\n const isInViewRef = useRef(true)\n const isPageVisibleRef = useRef(true)\n const prefersReducedMotionRef = useRef(false)\n\n useEffect(() => {\n const container = containerRef.current\n const block = blockRef.current\n if (!container || !block) return\n\n const updateSizes = () => {\n const cw = container.offsetWidth || 0\n const bw = block.scrollWidth || 0\n unitWidth.set(bw)\n const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1\n setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies))\n }\n\n updateSizes()\n\n const ro = new ResizeObserver(updateSizes)\n ro.observe(container)\n ro.observe(block)\n\n const io = new IntersectionObserver(([entry]) => {\n isInViewRef.current = entry.isIntersecting\n })\n io.observe(container)\n\n const handleVisibility = () => {\n isPageVisibleRef.current = document.visibilityState === \"visible\"\n }\n document.addEventListener(\"visibilitychange\", handleVisibility, {\n passive: true,\n })\n handleVisibility()\n\n const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n const handlePRM = () => {\n prefersReducedMotionRef.current = mq.matches\n }\n mq.addEventListener(\"change\", handlePRM)\n handlePRM()\n\n return () => {\n ro.disconnect()\n io.disconnect()\n document.removeEventListener(\"visibilitychange\", handleVisibility)\n mq.removeEventListener(\"change\", handlePRM)\n }\n }, [children, unitWidth])\n\n const x = useTransform([baseX, unitWidth], ([v, bw]) => {\n const width = Number(bw) || 1\n const offset = Number(v) || 0\n return `${-wrap(0, width, offset)}px`\n })\n\n useAnimationFrame((_, delta) => {\n if (!isInViewRef.current || !isPageVisibleRef.current) return\n const dt = delta / 1000\n const vf = scrollReactivity ? velocityFactor.get() : 0\n const absVf = Math.min(5, Math.abs(vf))\n const speedMultiplier = prefersReducedMotionRef.current ? 1 : 1 + absVf\n\n if (absVf > 0.1) {\n const scrollDirection = vf >= 0 ? 1 : -1\n currentDirectionRef.current = baseDirectionRef.current * scrollDirection\n }\n\n const bw = unitWidth.get() || 0\n if (bw <= 0) return\n const pixelsPerSecond = (bw * baseVelocity) / 100\n const moveBy =\n currentDirectionRef.current * pixelsPerSecond * speedMultiplier * dt\n baseX.set(baseX.get() + moveBy)\n })\n\n return (\n <div\n ref={containerRef}\n className={cn(\"w-full overflow-hidden whitespace-nowrap\", className)}\n {...props}\n >\n <motion.div\n className=\"inline-flex transform-gpu items-center will-change-transform select-none\"\n style={{ x }}\n >\n {Array.from({ length: numCopies }).map((_, i) => (\n <div\n key={i}\n ref={i === 0 ? blockRef : null}\n aria-hidden={i !== 0}\n className=\"inline-flex shrink-0 items-center\"\n >\n {children}\n </div>\n ))}\n </motion.div>\n </div>\n )\n}\n\nfunction ScrollVelocityRowLocal(props: ScrollVelocityRowProps) {\n const { scrollY } = useScroll()\n const localVelocity = useVelocity(scrollY)\n const localSmoothVelocity = useSpring(localVelocity, {\n damping: 50,\n stiffness: 400,\n })\n const localVelocityFactor = useTransform(localSmoothVelocity, (v) => {\n const sign = v < 0 ? -1 : 1\n const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5)\n return sign * magnitude\n })\n return (\n <ScrollVelocityRowImpl {...props} velocityFactor={localVelocityFactor} />\n )\n}\n",
+ "content": "\"use client\"\n\nimport React, { useContext, useEffect, useRef, useState } from \"react\"\nimport {\n motion,\n useAnimationFrame,\n useMotionValue,\n useScroll,\n useSpring,\n useTransform,\n useVelocity,\n} from \"motion/react\"\nimport type { MotionValue } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface ScrollVelocityRowProps extends React.HTMLAttributes<HTMLDivElement> {\n children: React.ReactNode\n baseVelocity?: number\n direction?: 1 | -1\n scrollReactivity?: boolean\n}\n\nexport const wrap = (min: number, max: number, v: number) => {\n const rangeSize = max - min\n return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min\n}\n\nconst ScrollVelocityContext = React.createContext<MotionValue<number> | null>(\n null\n)\n\nexport function ScrollVelocityContainer({\n children,\n className,\n ...props\n}: React.HTMLAttributes<HTMLDivElement>) {\n const { scrollY } = useScroll()\n const scrollVelocity = useVelocity(scrollY)\n const smoothVelocity = useSpring(scrollVelocity, {\n damping: 50,\n stiffness: 400,\n })\n const velocityFactor = useTransform(smoothVelocity, (v) => {\n const sign = v < 0 ? -1 : 1\n const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5)\n return sign * magnitude\n })\n\n return (\n <ScrollVelocityContext.Provider value={velocityFactor}>\n <div className={cn(\"relative w-full\", className)} {...props}>\n {children}\n </div>\n </ScrollVelocityContext.Provider>\n )\n}\n\nexport function ScrollVelocityRow(props: ScrollVelocityRowProps) {\n const sharedVelocityFactor = useContext(ScrollVelocityContext)\n if (sharedVelocityFactor) {\n return (\n <ScrollVelocityRowImpl {...props} velocityFactor={sharedVelocityFactor} />\n )\n }\n return <ScrollVelocityRowLocal {...props} />\n}\n\ninterface ScrollVelocityRowImplProps extends ScrollVelocityRowProps {\n velocityFactor: MotionValue<number>\n}\n\nfunction ScrollVelocityRowImpl({\n children,\n baseVelocity = 5,\n direction = 1,\n className,\n velocityFactor,\n scrollReactivity = true,\n ...props\n}: ScrollVelocityRowImplProps) {\n const containerRef = useRef<HTMLDivElement>(null)\n const blockRef = useRef<HTMLDivElement>(null)\n const [numCopies, setNumCopies] = useState(1)\n\n const baseX = useMotionValue(0)\n const baseDirectionRef = useRef<number>(direction >= 0 ? 1 : -1)\n const currentDirectionRef = useRef<number>(direction >= 0 ? 1 : -1)\n const unitWidth = useMotionValue(0)\n\n const isInViewRef = useRef(true)\n const isPageVisibleRef = useRef(true)\n const prefersReducedMotionRef = useRef(false)\n\n useEffect(() => {\n const container = containerRef.current\n const block = blockRef.current\n let ro: ResizeObserver | null = null\n let io: IntersectionObserver | null = null\n let mq: MediaQueryList | null = null\n const handleVisibility = () => {\n isPageVisibleRef.current = document.visibilityState === \"visible\"\n }\n const handlePRM = () => {\n if (mq) {\n prefersReducedMotionRef.current = mq.matches\n }\n }\n\n if (container && block) {\n const updateSizes = () => {\n const cw = container.offsetWidth || 0\n const bw = block.scrollWidth || 0\n unitWidth.set(bw)\n const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1\n setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies))\n }\n\n updateSizes()\n\n ro = new ResizeObserver(updateSizes)\n ro.observe(container)\n ro.observe(block)\n\n io = new IntersectionObserver(([entry]) => {\n isInViewRef.current = entry.isIntersecting\n })\n io.observe(container)\n\n document.addEventListener(\"visibilitychange\", handleVisibility, {\n passive: true,\n })\n handleVisibility()\n\n mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n mq.addEventListener(\"change\", handlePRM)\n handlePRM()\n }\n\n return () => {\n if (ro) {\n ro.disconnect()\n }\n if (io) {\n io.disconnect()\n }\n document.removeEventListener(\"visibilitychange\", handleVisibility)\n if (mq) {\n mq.removeEventListener(\"change\", handlePRM)\n }\n }\n }, [children, unitWidth])\n\n const x = useTransform([baseX, unitWidth], ([v, bw]) => {\n const width = Number(bw) || 1\n const offset = Number(v) || 0\n return `${-wrap(0, width, offset)}px`\n })\n\n useAnimationFrame((_, delta) => {\n if (!isInViewRef.current || !isPageVisibleRef.current) return\n const dt = delta / 1000\n const vf = scrollReactivity ? velocityFactor.get() : 0\n const absVf = Math.min(5, Math.abs(vf))\n const speedMultiplier = prefersReducedMotionRef.current ? 1 : 1 + absVf\n\n if (absVf > 0.1) {\n const scrollDirection = vf >= 0 ? 1 : -1\n currentDirectionRef.current = baseDirectionRef.current * scrollDirection\n }\n\n const bw = unitWidth.get() || 0\n if (bw <= 0) return\n const pixelsPerSecond = (bw * baseVelocity) / 100\n const moveBy =\n currentDirectionRef.current * pixelsPerSecond * speedMultiplier * dt\n baseX.set(baseX.get() + moveBy)\n })\n\n return (\n <div\n ref={containerRef}\n className={cn(\"w-full overflow-hidden whitespace-nowrap\", className)}\n {...props}\n >\n <motion.div\n className=\"inline-flex transform-gpu items-center will-change-transform select-none\"\n style={{ x }}\n >\n {Array.from({ length: numCopies }).map((_, i) => (\n <div\n key={i}\n ref={i === 0 ? blockRef : null}\n aria-hidden={i !== 0}\n className=\"inline-flex shrink-0 items-center\"\n >\n {children}\n </div>\n ))}\n </motion.div>\n </div>\n )\n}\n\nfunction ScrollVelocityRowLocal(props: ScrollVelocityRowProps) {\n const { scrollY } = useScroll()\n const localVelocity = useVelocity(scrollY)\n const localSmoothVelocity = useSpring(localVelocity, {\n damping: 50,\n stiffness: 400,\n })\n const localVelocityFactor = useTransform(localSmoothVelocity, (v) => {\n const sign = v < 0 ? -1 : 1\n const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5)\n return sign * magnitude\n })\n return (\n <ScrollVelocityRowImpl {...props} velocityFactor={localVelocityFactor} />\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/smooth-cursor.json b/apps/www/public/r/smooth-cursor.json
index 3c2ea020..160a6ba8 100644
--- a/apps/www/public/r/smooth-cursor.json
+++ b/apps/www/public/r/smooth-cursor.json
@@ -9,7 +9,7 @@
"files": [
{
"path": "registry/magicui/smooth-cursor.tsx",
- "content": "\"use client\"\n\nimport { FC, useEffect, useRef, useState } from \"react\"\nimport { motion, useSpring } from \"motion/react\"\n\ninterface Position {\n x: number\n y: number\n}\n\nexport interface SmoothCursorProps {\n cursor?: React.ReactNode\n springConfig?: {\n damping: number\n stiffness: number\n mass: number\n restDelta: number\n }\n}\n\nconst DefaultCursorSVG: FC = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={50}\n height={54}\n viewBox=\"0 0 50 54\"\n fill=\"none\"\n style={{ scale: 0.5 }}\n >\n <g filter=\"url(#filter0_d_91_7928)\">\n <path\n d=\"M42.6817 41.1495L27.5103 6.79925C26.7269 5.02557 24.2082 5.02558 23.3927 6.79925L7.59814 41.1495C6.75833 42.9759 8.52712 44.8902 10.4125 44.1954L24.3757 39.0496C24.8829 38.8627 25.4385 38.8627 25.9422 39.0496L39.8121 44.1954C41.6849 44.8902 43.4884 42.9759 42.6817 41.1495Z\"\n fill=\"black\"\n />\n <path\n d=\"M43.7146 40.6933L28.5431 6.34306C27.3556 3.65428 23.5772 3.69516 22.3668 6.32755L6.57226 40.6778C5.3134 43.4156 7.97238 46.298 10.803 45.2549L24.7662 40.109C25.0221 40.0147 25.2999 40.0156 25.5494 40.1082L39.4193 45.254C42.2261 46.2953 44.9254 43.4347 43.7146 40.6933Z\"\n stroke=\"white\"\n strokeWidth={2.25825}\n />\n </g>\n <defs>\n <filter\n id=\"filter0_d_91_7928\"\n x={0.602397}\n y={0.952444}\n width={49.0584}\n height={52.428}\n filterUnits=\"userSpaceOnUse\"\n colorInterpolationFilters=\"sRGB\"\n >\n <feFlood floodOpacity={0} result=\"BackgroundImageFix\" />\n <feColorMatrix\n in=\"SourceAlpha\"\n type=\"matrix\"\n values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\"\n result=\"hardAlpha\"\n />\n <feOffset dy={2.25825} />\n <feGaussianBlur stdDeviation={2.25825} />\n <feComposite in2=\"hardAlpha\" operator=\"out\" />\n <feColorMatrix\n type=\"matrix\"\n values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.08 0\"\n />\n <feBlend\n mode=\"normal\"\n in2=\"BackgroundImageFix\"\n result=\"effect1_dropShadow_91_7928\"\n />\n <feBlend\n mode=\"normal\"\n in=\"SourceGraphic\"\n in2=\"effect1_dropShadow_91_7928\"\n result=\"shape\"\n />\n </filter>\n </defs>\n </svg>\n )\n}\n\nexport function SmoothCursor({\n cursor = <DefaultCursorSVG />,\n springConfig = {\n damping: 45,\n stiffness: 400,\n mass: 1,\n restDelta: 0.001,\n },\n}: SmoothCursorProps) {\n const [isMoving, setIsMoving] = useState(false)\n const lastMousePos = useRef<Position>({ x: 0, y: 0 })\n const velocity = useRef<Position>({ x: 0, y: 0 })\n const lastUpdateTime = useRef(Date.now())\n const previousAngle = useRef(0)\n const accumulatedRotation = useRef(0)\n\n const cursorX = useSpring(0, springConfig)\n const cursorY = useSpring(0, springConfig)\n const rotation = useSpring(0, {\n ...springConfig,\n damping: 60,\n stiffness: 300,\n })\n const scale = useSpring(1, {\n ...springConfig,\n stiffness: 500,\n damping: 35,\n })\n\n useEffect(() => {\n const updateVelocity = (currentPos: Position) => {\n const currentTime = Date.now()\n const deltaTime = currentTime - lastUpdateTime.current\n\n if (deltaTime > 0) {\n velocity.current = {\n x: (currentPos.x - lastMousePos.current.x) / deltaTime,\n y: (currentPos.y - lastMousePos.current.y) / deltaTime,\n }\n }\n\n lastUpdateTime.current = currentTime\n lastMousePos.current = currentPos\n }\n\n const smoothMouseMove = (e: MouseEvent) => {\n const currentPos = { x: e.clientX, y: e.clientY }\n updateVelocity(currentPos)\n\n const speed = Math.sqrt(\n Math.pow(velocity.current.x, 2) + Math.pow(velocity.current.y, 2)\n )\n\n cursorX.set(currentPos.x)\n cursorY.set(currentPos.y)\n\n if (speed > 0.1) {\n const currentAngle =\n Math.atan2(velocity.current.y, velocity.current.x) * (180 / Math.PI) +\n 90\n\n let angleDiff = currentAngle - previousAngle.current\n if (angleDiff > 180) angleDiff -= 360\n if (angleDiff < -180) angleDiff += 360\n accumulatedRotation.current += angleDiff\n rotation.set(accumulatedRotation.current)\n previousAngle.current = currentAngle\n\n scale.set(0.95)\n setIsMoving(true)\n\n const timeout = setTimeout(() => {\n scale.set(1)\n setIsMoving(false)\n }, 150)\n\n return () => clearTimeout(timeout)\n }\n }\n\n let rafId: number\n const throttledMouseMove = (e: MouseEvent) => {\n if (rafId) return\n\n rafId = requestAnimationFrame(() => {\n smoothMouseMove(e)\n rafId = 0\n })\n }\n\n document.body.style.cursor = \"none\"\n window.addEventListener(\"mousemove\", throttledMouseMove)\n\n return () => {\n window.removeEventListener(\"mousemove\", throttledMouseMove)\n document.body.style.cursor = \"auto\"\n if (rafId) cancelAnimationFrame(rafId)\n }\n }, [cursorX, cursorY, rotation, scale])\n\n return (\n <motion.div\n style={{\n position: \"fixed\",\n left: cursorX,\n top: cursorY,\n translateX: \"-50%\",\n translateY: \"-50%\",\n rotate: rotation,\n scale: scale,\n zIndex: 100,\n pointerEvents: \"none\",\n willChange: \"transform\",\n }}\n initial={{ scale: 0 }}\n animate={{ scale: 1 }}\n transition={{\n type: \"spring\",\n stiffness: 400,\n damping: 30,\n }}\n >\n {cursor}\n </motion.div>\n )\n}\n",
+ "content": "\"use client\"\n\nimport { FC, useEffect, useRef, useState } from \"react\"\nimport { motion, useSpring } from \"motion/react\"\n\ninterface Position {\n x: number\n y: number\n}\n\nexport interface SmoothCursorProps {\n cursor?: React.ReactNode\n springConfig?: {\n damping: number\n stiffness: number\n mass: number\n restDelta: number\n }\n}\n\nconst DefaultCursorSVG: FC = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={50}\n height={54}\n viewBox=\"0 0 50 54\"\n fill=\"none\"\n style={{ scale: 0.5 }}\n >\n <g filter=\"url(#filter0_d_91_7928)\">\n <path\n d=\"M42.6817 41.1495L27.5103 6.79925C26.7269 5.02557 24.2082 5.02558 23.3927 6.79925L7.59814 41.1495C6.75833 42.9759 8.52712 44.8902 10.4125 44.1954L24.3757 39.0496C24.8829 38.8627 25.4385 38.8627 25.9422 39.0496L39.8121 44.1954C41.6849 44.8902 43.4884 42.9759 42.6817 41.1495Z\"\n fill=\"black\"\n />\n <path\n d=\"M43.7146 40.6933L28.5431 6.34306C27.3556 3.65428 23.5772 3.69516 22.3668 6.32755L6.57226 40.6778C5.3134 43.4156 7.97238 46.298 10.803 45.2549L24.7662 40.109C25.0221 40.0147 25.2999 40.0156 25.5494 40.1082L39.4193 45.254C42.2261 46.2953 44.9254 43.4347 43.7146 40.6933Z\"\n stroke=\"white\"\n strokeWidth={2.25825}\n />\n </g>\n <defs>\n <filter\n id=\"filter0_d_91_7928\"\n x={0.602397}\n y={0.952444}\n width={49.0584}\n height={52.428}\n filterUnits=\"userSpaceOnUse\"\n colorInterpolationFilters=\"sRGB\"\n >\n <feFlood floodOpacity={0} result=\"BackgroundImageFix\" />\n <feColorMatrix\n in=\"SourceAlpha\"\n type=\"matrix\"\n values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0\"\n result=\"hardAlpha\"\n />\n <feOffset dy={2.25825} />\n <feGaussianBlur stdDeviation={2.25825} />\n <feComposite in2=\"hardAlpha\" operator=\"out\" />\n <feColorMatrix\n type=\"matrix\"\n values=\"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.08 0\"\n />\n <feBlend\n mode=\"normal\"\n in2=\"BackgroundImageFix\"\n result=\"effect1_dropShadow_91_7928\"\n />\n <feBlend\n mode=\"normal\"\n in=\"SourceGraphic\"\n in2=\"effect1_dropShadow_91_7928\"\n result=\"shape\"\n />\n </filter>\n </defs>\n </svg>\n )\n}\n\nexport function SmoothCursor({\n cursor = <DefaultCursorSVG />,\n springConfig = {\n damping: 45,\n stiffness: 400,\n mass: 1,\n restDelta: 0.001,\n },\n}: SmoothCursorProps) {\n const [isMoving, setIsMoving] = useState(false)\n const lastMousePos = useRef<Position>({ x: 0, y: 0 })\n const velocity = useRef<Position>({ x: 0, y: 0 })\n const lastUpdateTime = useRef(Date.now())\n const previousAngle = useRef(0)\n const accumulatedRotation = useRef(0)\n\n const cursorX = useSpring(0, springConfig)\n const cursorY = useSpring(0, springConfig)\n const rotation = useSpring(0, {\n ...springConfig,\n damping: 60,\n stiffness: 300,\n })\n const scale = useSpring(1, {\n ...springConfig,\n stiffness: 500,\n damping: 35,\n })\n\n useEffect(() => {\n let timeout: ReturnType<typeof setTimeout> | null = null\n\n const updateVelocity = (currentPos: Position) => {\n const currentTime = Date.now()\n const deltaTime = currentTime - lastUpdateTime.current\n\n if (deltaTime > 0) {\n velocity.current = {\n x: (currentPos.x - lastMousePos.current.x) / deltaTime,\n y: (currentPos.y - lastMousePos.current.y) / deltaTime,\n }\n }\n\n lastUpdateTime.current = currentTime\n lastMousePos.current = currentPos\n }\n\n const smoothMouseMove = (e: MouseEvent) => {\n const currentPos = { x: e.clientX, y: e.clientY }\n updateVelocity(currentPos)\n\n const speed = Math.sqrt(\n Math.pow(velocity.current.x, 2) + Math.pow(velocity.current.y, 2)\n )\n\n cursorX.set(currentPos.x)\n cursorY.set(currentPos.y)\n\n if (speed > 0.1) {\n const currentAngle =\n Math.atan2(velocity.current.y, velocity.current.x) * (180 / Math.PI) +\n 90\n\n let angleDiff = currentAngle - previousAngle.current\n if (angleDiff > 180) angleDiff -= 360\n if (angleDiff < -180) angleDiff += 360\n accumulatedRotation.current += angleDiff\n rotation.set(accumulatedRotation.current)\n previousAngle.current = currentAngle\n\n scale.set(0.95)\n setIsMoving(true)\n\n if (timeout !== null) {\n clearTimeout(timeout)\n }\n\n timeout = setTimeout(() => {\n scale.set(1)\n setIsMoving(false)\n }, 150)\n }\n }\n\n let rafId: number\n const throttledMouseMove = (e: MouseEvent) => {\n if (rafId) return\n\n rafId = requestAnimationFrame(() => {\n smoothMouseMove(e)\n rafId = 0\n })\n }\n\n document.body.style.cursor = \"none\"\n window.addEventListener(\"mousemove\", throttledMouseMove)\n\n return () => {\n window.removeEventListener(\"mousemove\", throttledMouseMove)\n document.body.style.cursor = \"auto\"\n if (rafId) cancelAnimationFrame(rafId)\n if (timeout !== null) {\n clearTimeout(timeout)\n }\n }\n }, [cursorX, cursorY, rotation, scale])\n\n return (\n <motion.div\n style={{\n position: \"fixed\",\n left: cursorX,\n top: cursorY,\n translateX: \"-50%\",\n translateY: \"-50%\",\n rotate: rotation,\n scale: scale,\n zIndex: 100,\n pointerEvents: \"none\",\n willChange: \"transform\",\n }}\n initial={{ scale: 0 }}\n animate={{ scale: 1 }}\n transition={{\n type: \"spring\",\n stiffness: 400,\n damping: 30,\n }}\n >\n {cursor}\n </motion.div>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/terminal.json b/apps/www/public/r/terminal.json
index d679cdcf..98ca2abd 100644
--- a/apps/www/public/r/terminal.json
+++ b/apps/www/public/r/terminal.json
@@ -7,7 +7,7 @@
"files": [
{
"path": "registry/magicui/terminal.tsx",
- "content": "\"use client\"\n\nimport {\n Children,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type RefAttributes,\n} from \"react\"\nimport {\n motion,\n useInView,\n type DOMMotionComponents,\n type HTMLMotionProps,\n type MotionProps,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface SequenceContextValue {\n completeItem: (index: number) => void\n activeIndex: number\n sequenceStarted: boolean\n}\n\nconst SequenceContext = createContext<SequenceContextValue | null>(null)\n\nconst useSequence = () => useContext(SequenceContext)\n\nconst ItemIndexContext = createContext<number | null>(null)\nconst useItemIndex = () => useContext(ItemIndexContext)\n\nconst motionElements = {\n article: motion.article,\n div: motion.div,\n h1: motion.h1,\n h2: motion.h2,\n h3: motion.h3,\n h4: motion.h4,\n h5: motion.h5,\n h6: motion.h6,\n li: motion.li,\n p: motion.p,\n section: motion.section,\n span: motion.span,\n} as const\n\ntype MotionElementType = Extract<\n keyof DOMMotionComponents,\n keyof typeof motionElements\n>\ntype TerminalTypingMotionComponent = ComponentType<\n Omit<HTMLMotionProps<\"span\">, \"ref\"> & RefAttributes<HTMLElement>\n>\n\ninterface AnimatedSpanProps extends MotionProps {\n children: React.ReactNode\n delay?: number\n className?: string\n startOnView?: boolean\n}\n\nexport const AnimatedSpan = ({\n children,\n delay = 0,\n className,\n startOnView = false,\n ...props\n}: AnimatedSpanProps) => {\n const elementRef = useRef<HTMLDivElement | null>(null)\n const isInView = useInView(elementRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n })\n\n const sequence = useSequence()\n const itemIndex = useItemIndex()\n const [hasStarted, setHasStarted] = useState(false)\n useEffect(() => {\n if (!sequence || itemIndex === null) return\n if (!sequence.sequenceStarted) return\n if (hasStarted) return\n if (sequence.activeIndex === itemIndex) {\n setHasStarted(true)\n }\n }, [sequence?.activeIndex, sequence?.sequenceStarted, hasStarted, itemIndex])\n\n const shouldAnimate = sequence ? hasStarted : startOnView ? isInView : true\n\n return (\n <motion.div\n ref={elementRef}\n initial={{ opacity: 0, y: -5 }}\n animate={shouldAnimate ? { opacity: 1, y: 0 } : { opacity: 0, y: -5 }}\n transition={{ duration: 0.3, delay: sequence ? 0 : delay / 1000 }}\n className={cn(\"grid text-sm font-normal tracking-tight\", className)}\n onAnimationComplete={() => {\n if (!sequence) return\n if (itemIndex === null) return\n sequence.completeItem(itemIndex)\n }}\n {...props}\n >\n {children}\n </motion.div>\n )\n}\n\ninterface TypingAnimationProps extends Omit<MotionProps, \"children\"> {\n children: string\n className?: string\n duration?: number\n delay?: number\n as?: MotionElementType\n startOnView?: boolean\n}\n\nexport const TypingAnimation = ({\n children,\n className,\n duration = 60,\n delay = 0,\n as: Component = \"span\",\n startOnView = true,\n ...props\n}: TypingAnimationProps) => {\n if (typeof children !== \"string\") {\n throw new Error(\"TypingAnimation: children must be a string. Received:\")\n }\n\n const MotionComponent = motionElements[\n Component\n ] as TerminalTypingMotionComponent\n\n const [displayedText, setDisplayedText] = useState<string>(\"\")\n const [started, setStarted] = useState(false)\n const elementRef = useRef<HTMLElement | null>(null)\n const isInView = useInView(elementRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n })\n\n const sequence = useSequence()\n const itemIndex = useItemIndex()\n\n useEffect(() => {\n if (sequence && itemIndex !== null) {\n if (!sequence.sequenceStarted) return\n if (started) return\n if (sequence.activeIndex === itemIndex) {\n setStarted(true)\n }\n return\n }\n\n if (!startOnView) {\n const startTimeout = setTimeout(() => setStarted(true), delay)\n return () => clearTimeout(startTimeout)\n }\n\n if (!isInView) return\n\n const startTimeout = setTimeout(() => setStarted(true), delay)\n return () => clearTimeout(startTimeout)\n }, [\n delay,\n startOnView,\n isInView,\n started,\n sequence?.activeIndex,\n sequence?.sequenceStarted,\n itemIndex,\n ])\n\n useEffect(() => {\n if (!started) return\n\n let i = 0\n const typingEffect = setInterval(() => {\n if (i < children.length) {\n setDisplayedText(children.substring(0, i + 1))\n i++\n } else {\n clearInterval(typingEffect)\n if (sequence && itemIndex !== null) {\n sequence.completeItem(itemIndex)\n }\n }\n }, duration)\n\n return () => {\n clearInterval(typingEffect)\n }\n }, [children, duration, started])\n\n return (\n <MotionComponent\n ref={elementRef}\n className={cn(\"text-sm font-normal tracking-tight\", className)}\n {...props}\n >\n {displayedText}\n </MotionComponent>\n )\n}\n\ninterface TerminalProps {\n children: React.ReactNode\n className?: string\n sequence?: boolean\n startOnView?: boolean\n}\n\nexport const Terminal = ({\n children,\n className,\n sequence = true,\n startOnView = true,\n}: TerminalProps) => {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const isInView = useInView(containerRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n })\n\n const [activeIndex, setActiveIndex] = useState(0)\n const sequenceHasStarted = sequence ? !startOnView || isInView : false\n\n const contextValue = useMemo<SequenceContextValue | null>(() => {\n if (!sequence) return null\n return {\n completeItem: (index: number) => {\n setActiveIndex((current) => (index === current ? current + 1 : current))\n },\n activeIndex,\n sequenceStarted: sequenceHasStarted,\n }\n }, [sequence, activeIndex, sequenceHasStarted])\n\n const wrappedChildren = useMemo(() => {\n if (!sequence) return children\n const array = Children.toArray(children)\n return array.map((child, index) => (\n <ItemIndexContext.Provider key={index} value={index}>\n {child as React.ReactNode}\n </ItemIndexContext.Provider>\n ))\n }, [children, sequence])\n\n const content = (\n <div\n ref={containerRef}\n className={cn(\n \"border-border bg-background z-0 h-full max-h-[400px] w-full max-w-lg rounded-xl border\",\n className\n )}\n >\n <div className=\"border-border flex flex-col gap-y-2 border-b p-4\">\n <div className=\"flex flex-row gap-x-2\">\n <div className=\"h-2 w-2 rounded-full bg-red-500\"></div>\n <div className=\"h-2 w-2 rounded-full bg-yellow-500\"></div>\n <div className=\"h-2 w-2 rounded-full bg-green-500\"></div>\n </div>\n </div>\n <pre className=\"p-4\">\n <code className=\"grid gap-y-1 overflow-auto\">{wrappedChildren}</code>\n </pre>\n </div>\n )\n\n if (!sequence) return content\n\n return (\n <SequenceContext.Provider value={contextValue}>\n {content}\n </SequenceContext.Provider>\n )\n}\n",
+ "content": "\"use client\"\n\nimport {\n Children,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type RefAttributes,\n} from \"react\"\nimport {\n motion,\n useInView,\n type DOMMotionComponents,\n type HTMLMotionProps,\n type MotionProps,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface SequenceContextValue {\n completeItem: (index: number) => void\n activeIndex: number\n sequenceStarted: boolean\n}\n\nconst SequenceContext = createContext<SequenceContextValue | null>(null)\n\nconst useSequence = () => useContext(SequenceContext)\n\nconst ItemIndexContext = createContext<number | null>(null)\nconst useItemIndex = () => useContext(ItemIndexContext)\n\nconst motionElements = {\n article: motion.article,\n div: motion.div,\n h1: motion.h1,\n h2: motion.h2,\n h3: motion.h3,\n h4: motion.h4,\n h5: motion.h5,\n h6: motion.h6,\n li: motion.li,\n p: motion.p,\n section: motion.section,\n span: motion.span,\n} as const\n\ntype MotionElementType = Extract<\n keyof DOMMotionComponents,\n keyof typeof motionElements\n>\ntype TerminalTypingMotionComponent = ComponentType<\n Omit<HTMLMotionProps<\"span\">, \"ref\"> & RefAttributes<HTMLElement>\n>\n\ninterface AnimatedSpanProps extends MotionProps {\n children: React.ReactNode\n delay?: number\n className?: string\n startOnView?: boolean\n}\n\nexport const AnimatedSpan = ({\n children,\n delay = 0,\n className,\n startOnView = false,\n ...props\n}: AnimatedSpanProps) => {\n const elementRef = useRef<HTMLDivElement | null>(null)\n const isInView = useInView(elementRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n })\n\n const sequence = useSequence()\n const itemIndex = useItemIndex()\n const [hasStarted, setHasStarted] = useState(false)\n useEffect(() => {\n if (!sequence || itemIndex === null) return\n if (!sequence.sequenceStarted) return\n if (hasStarted) return\n if (sequence.activeIndex === itemIndex) {\n setHasStarted(true)\n }\n }, [sequence?.activeIndex, sequence?.sequenceStarted, hasStarted, itemIndex])\n\n const shouldAnimate = sequence ? hasStarted : startOnView ? isInView : true\n\n return (\n <motion.div\n ref={elementRef}\n initial={{ opacity: 0, y: -5 }}\n animate={shouldAnimate ? { opacity: 1, y: 0 } : { opacity: 0, y: -5 }}\n transition={{ duration: 0.3, delay: sequence ? 0 : delay / 1000 }}\n className={cn(\"grid text-sm font-normal tracking-tight\", className)}\n onAnimationComplete={() => {\n if (!sequence) return\n if (itemIndex === null) return\n sequence.completeItem(itemIndex)\n }}\n {...props}\n >\n {children}\n </motion.div>\n )\n}\n\ninterface TypingAnimationProps extends Omit<MotionProps, \"children\"> {\n children: string\n className?: string\n duration?: number\n delay?: number\n as?: MotionElementType\n startOnView?: boolean\n}\n\nexport const TypingAnimation = ({\n children,\n className,\n duration = 60,\n delay = 0,\n as: Component = \"span\",\n startOnView = true,\n ...props\n}: TypingAnimationProps) => {\n if (typeof children !== \"string\") {\n throw new Error(\"TypingAnimation: children must be a string. Received:\")\n }\n\n const MotionComponent = motionElements[\n Component\n ] as TerminalTypingMotionComponent\n\n const [displayedText, setDisplayedText] = useState<string>(\"\")\n const [started, setStarted] = useState(false)\n const elementRef = useRef<HTMLElement | null>(null)\n const isInView = useInView(elementRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n })\n\n const sequence = useSequence()\n const itemIndex = useItemIndex()\n\n useEffect(() => {\n let startTimeout: ReturnType<typeof setTimeout> | null = null\n\n if (sequence && itemIndex !== null) {\n if (\n sequence.sequenceStarted &&\n !started &&\n sequence.activeIndex === itemIndex\n ) {\n setStarted(true)\n }\n } else if (!startOnView || isInView) {\n startTimeout = setTimeout(() => setStarted(true), delay)\n }\n\n return () => {\n if (startTimeout !== null) {\n clearTimeout(startTimeout)\n }\n }\n }, [\n delay,\n startOnView,\n isInView,\n started,\n sequence?.activeIndex,\n sequence?.sequenceStarted,\n itemIndex,\n ])\n\n useEffect(() => {\n let typingEffect: ReturnType<typeof setInterval> | null = null\n\n if (started) {\n let i = 0\n typingEffect = setInterval(() => {\n if (i < children.length) {\n setDisplayedText(children.substring(0, i + 1))\n i++\n } else {\n if (typingEffect !== null) {\n clearInterval(typingEffect)\n }\n if (sequence && itemIndex !== null) {\n sequence.completeItem(itemIndex)\n }\n }\n }, duration)\n }\n\n return () => {\n if (typingEffect !== null) {\n clearInterval(typingEffect)\n }\n }\n }, [children, duration, started])\n\n return (\n <MotionComponent\n ref={elementRef}\n className={cn(\"text-sm font-normal tracking-tight\", className)}\n {...props}\n >\n {displayedText}\n </MotionComponent>\n )\n}\n\ninterface TerminalProps {\n children: React.ReactNode\n className?: string\n sequence?: boolean\n startOnView?: boolean\n}\n\nexport const Terminal = ({\n children,\n className,\n sequence = true,\n startOnView = true,\n}: TerminalProps) => {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const isInView = useInView(containerRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n })\n\n const [activeIndex, setActiveIndex] = useState(0)\n const sequenceHasStarted = sequence ? !startOnView || isInView : false\n\n const contextValue = useMemo<SequenceContextValue | null>(() => {\n if (!sequence) return null\n return {\n completeItem: (index: number) => {\n setActiveIndex((current) => (index === current ? current + 1 : current))\n },\n activeIndex,\n sequenceStarted: sequenceHasStarted,\n }\n }, [sequence, activeIndex, sequenceHasStarted])\n\n const wrappedChildren = useMemo(() => {\n if (!sequence) return children\n const array = Children.toArray(children)\n return array.map((child, index) => (\n <ItemIndexContext.Provider key={index} value={index}>\n {child as React.ReactNode}\n </ItemIndexContext.Provider>\n ))\n }, [children, sequence])\n\n const content = (\n <div\n ref={containerRef}\n className={cn(\n \"border-border bg-background z-0 h-full max-h-[400px] w-full max-w-lg rounded-xl border\",\n className\n )}\n >\n <div className=\"border-border flex flex-col gap-y-2 border-b p-4\">\n <div className=\"flex flex-row gap-x-2\">\n <div className=\"h-2 w-2 rounded-full bg-red-500\"></div>\n <div className=\"h-2 w-2 rounded-full bg-yellow-500\"></div>\n <div className=\"h-2 w-2 rounded-full bg-green-500\"></div>\n </div>\n </div>\n <pre className=\"p-4\">\n <code className=\"grid gap-y-1 overflow-auto\">{wrappedChildren}</code>\n </pre>\n </div>\n )\n\n if (!sequence) return content\n\n return (\n <SequenceContext.Provider value={contextValue}>\n {content}\n </SequenceContext.Provider>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/tweet-card.json b/apps/www/public/r/tweet-card.json
index f70b5fc0..27d209c3 100644
--- a/apps/www/public/r/tweet-card.json
+++ b/apps/www/public/r/tweet-card.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/tweet-card.tsx",
- "content": "/* eslint-disable @next/next/no-img-element */\nimport { Suspense } from \"react\"\nimport { enrichTweet, type EnrichedTweet, type TweetProps } from \"react-tweet\"\nimport { getTweet, type Tweet } from \"react-tweet/api\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface TwitterIconProps {\n className?: string\n [key: string]: unknown\n}\nconst Twitter = ({ className, ...props }: TwitterIconProps) => (\n <svg\n stroke=\"currentColor\"\n fill=\"currentColor\"\n strokeWidth=\"0\"\n viewBox=\"0 0 24 24\"\n height=\"1em\"\n width=\"1em\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={className}\n {...props}\n >\n <g>\n <path fill=\"none\" d=\"M0 0h24v24H0z\"></path>\n <path d=\"M22.162 5.656a8.384 8.384 0 0 1-2.402.658A4.196 4.196 0 0 0 21.6 4c-.82.488-1.719.83-2.656 1.015a4.182 4.182 0 0 0-7.126 3.814 11.874 11.874 0 0 1-8.62-4.37 4.168 4.168 0 0 0-.566 2.103c0 1.45.738 2.731 1.86 3.481a4.168 4.168 0 0 1-1.894-.523v.052a4.185 4.185 0 0 0 3.355 4.101 4.21 4.21 0 0 1-1.89.072A4.185 4.185 0 0 0 7.97 16.65a8.394 8.394 0 0 1-6.191 1.732 11.83 11.83 0 0 0 6.41 1.88c7.693 0 11.9-6.373 11.9-11.9 0-.18-.005-.362-.013-.54a8.496 8.496 0 0 0 2.087-2.165z\"></path>\n </g>\n </svg>\n)\n\nconst Verified = ({ className, ...props }: TwitterIconProps) => (\n <svg\n aria-label=\"Verified Account\"\n viewBox=\"0 0 24 24\"\n className={className}\n {...props}\n >\n <g fill=\"currentColor\">\n <path d=\"M22.5 12.5c0-1.58-.875-2.95-2.148-3.6.154-.435.238-.905.238-1.4 0-2.21-1.71-3.998-3.818-3.998-.47 0-.92.084-1.336.25C14.818 2.415 13.51 1.5 12 1.5s-2.816.917-3.437 2.25c-.415-.165-.866-.25-1.336-.25-2.11 0-3.818 1.79-3.818 4 0 .494.083.964.237 1.4-1.272.65-2.147 2.018-2.147 3.6 0 1.495.782 2.798 1.942 3.486-.02.17-.032.34-.032.514 0 2.21 1.708 4 3.818 4 .47 0 .92-.086 1.335-.25.62 1.334 1.926 2.25 3.437 2.25 1.512 0 2.818-.916 3.437-2.25.415.163.865.248 1.336.248 2.11 0 3.818-1.79 3.818-4 0-.174-.012-.344-.033-.513 1.158-.687 1.943-1.99 1.943-3.484zm-6.616-3.334l-4.334 6.5c-.145.217-.382.334-.625.334-.143 0-.288-.04-.416-.126l-.115-.094-2.415-2.415c-.293-.293-.293-.768 0-1.06s.768-.294 1.06 0l1.77 1.767 3.825-5.74c.23-.345.696-.436 1.04-.207.346.23.44.696.21 1.04z\" />\n </g>\n </svg>\n)\n\nexport const truncate = (str: string | null, length: number) => {\n if (!str || str.length <= length) return str\n return `${str.slice(0, length - 3)}...`\n}\n\nconst Skeleton = ({\n className,\n ...props\n}: React.HTMLAttributes<HTMLDivElement>) => {\n return (\n <div className={cn(\"bg-primary/10 rounded-md\", className)} {...props} />\n )\n}\n\nexport const TweetSkeleton = ({\n className,\n ...props\n}: {\n className?: string\n [key: string]: unknown\n}) => (\n <div\n className={cn(\n \"flex size-full max-h-max min-w-72 flex-col gap-2 rounded-xl border p-4\",\n className\n )}\n {...props}\n >\n <div className=\"flex flex-row gap-2\">\n <Skeleton className=\"size-10 shrink-0 rounded-full\" />\n <Skeleton className=\"h-10 w-full\" />\n </div>\n <Skeleton className=\"h-20 w-full\" />\n </div>\n)\n\nexport const TweetNotFound = ({\n className,\n ...props\n}: {\n className?: string\n [key: string]: unknown\n}) => (\n <div\n className={cn(\n \"flex size-full flex-col items-center justify-center gap-2 rounded-lg border p-4\",\n className\n )}\n {...props}\n >\n <h3>Tweet not found</h3>\n </div>\n)\n\nexport const TweetHeader = ({ tweet }: { tweet: EnrichedTweet }) => (\n <div className=\"flex flex-row items-start justify-between tracking-normal\">\n <div className=\"flex items-center space-x-3\">\n <a\n href={tweet.user.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"shrink-0\"\n >\n <img\n title={`Profile picture of ${tweet.user.name}`}\n alt={tweet.user.screen_name}\n height={48}\n width={48}\n src={tweet.user.profile_image_url_https}\n className=\"border-border/50 overflow-hidden rounded-full border\"\n />\n </a>\n <div className=\"flex flex-col gap-0.5\">\n <a\n href={tweet.user.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-foreground flex items-center font-medium whitespace-nowrap transition-opacity hover:opacity-80\"\n >\n {truncate(tweet.user.name, 20)}\n {tweet.user.verified ||\n (tweet.user.is_blue_verified && (\n <Verified className=\"ml-1 inline size-4 text-blue-500\" />\n ))}\n </a>\n <div className=\"flex items-center space-x-1\">\n <a\n href={tweet.user.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-muted-foreground hover:text-foreground text-sm transition-colors\"\n >\n @{truncate(tweet.user.screen_name, 16)}\n </a>\n </div>\n </div>\n </div>\n <a href={tweet.url} target=\"_blank\" rel=\"noreferrer\">\n <span className=\"sr-only\">Link to tweet</span>\n <Twitter className=\"text-muted-foreground hover:text-foreground size-5 items-start transition-all ease-in-out hover:scale-105\" />\n </a>\n </div>\n)\n\nexport const TweetBody = ({ tweet }: { tweet: EnrichedTweet }) => (\n <div className=\"text-[15px] leading-relaxed tracking-normal wrap-break-word\">\n {tweet.entities.map((entity, idx) => {\n switch (entity.type) {\n case \"url\":\n case \"symbol\":\n case \"hashtag\":\n case \"mention\":\n return (\n <a\n key={idx}\n href={entity.href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-muted-foreground hover:text-foreground text-[15px] font-normal transition-colors\"\n >\n <span>{entity.text}</span>\n </a>\n )\n case \"text\":\n return (\n <span\n key={idx}\n className=\"text-foreground text-[15px] font-normal\"\n dangerouslySetInnerHTML={{ __html: entity.text }}\n />\n )\n }\n })}\n </div>\n)\n\nexport const TweetMedia = ({ tweet }: { tweet: EnrichedTweet }) => {\n if (!tweet.video && !tweet.photos) return null\n return (\n <div className=\"flex flex-1 items-center justify-center\">\n {tweet.video && (\n <video\n poster={tweet.video.poster}\n autoPlay\n loop\n muted\n playsInline\n className=\"rounded-xl border shadow-sm\"\n >\n <source src={tweet.video.variants[0].src} type=\"video/mp4\" />\n Your browser does not support the video tag.\n </video>\n )}\n {tweet.photos && (\n <div className=\"relative flex transform-gpu snap-x snap-mandatory gap-4 overflow-x-auto\">\n <div className=\"shrink-0 snap-center sm:w-2\" />\n {tweet.photos.map((photo) => (\n <img\n key={photo.url}\n src={photo.url}\n width={photo.width}\n height={photo.height}\n title={\"Photo by \" + tweet.user.name}\n alt={tweet.text}\n className=\"h-64 w-5/6 shrink-0 snap-center snap-always rounded-xl border object-cover shadow-sm\"\n />\n ))}\n <div className=\"shrink-0 snap-center sm:w-2\" />\n </div>\n )}\n {!tweet.video &&\n !tweet.photos &&\n // @ts-expect-error package doesn't have type definitions\n tweet?.card?.binding_values?.thumbnail_image_large?.image_value.url && (\n <img\n src={\n // @ts-expect-error package doesn't have type definitions\n tweet.card.binding_values.thumbnail_image_large.image_value.url\n }\n className=\"h-64 rounded-xl border object-cover shadow-sm\"\n alt={tweet.text}\n />\n )}\n </div>\n )\n}\n\nexport const MagicTweet = ({\n tweet,\n className,\n ...props\n}: {\n tweet: Tweet\n className?: string\n}) => {\n const enrichedTweet = enrichTweet(tweet)\n return (\n <div\n className={cn(\n \"relative flex h-fit w-full max-w-lg flex-col gap-4 overflow-hidden rounded-xl border p-5\",\n className\n )}\n {...props}\n >\n <TweetHeader tweet={enrichedTweet} />\n <TweetBody tweet={enrichedTweet} />\n <TweetMedia tweet={enrichedTweet} />\n </div>\n )\n}\n\n/**\n * TweetCard (Server Side Only)\n */\nexport const TweetCard = async ({\n id,\n components,\n fallback = <TweetSkeleton />,\n onError,\n ...props\n}: TweetProps & {\n className?: string\n}) => {\n const tweet = id\n ? await getTweet(id).catch((err) => {\n if (onError) {\n onError(err)\n } else {\n console.error(err)\n }\n })\n : undefined\n\n if (!tweet) {\n const NotFound = components?.TweetNotFound ?? TweetNotFound\n return <NotFound {...props} />\n }\n\n return (\n <Suspense fallback={fallback}>\n <MagicTweet tweet={tweet} {...props} />\n </Suspense>\n )\n}\n",
+ "content": "/* eslint-disable @next/next/no-img-element */\nimport { Suspense } from \"react\"\nimport { enrichTweet, type EnrichedTweet, type TweetProps } from \"react-tweet\"\nimport { getTweet, type Tweet } from \"react-tweet/api\"\n\nimport { cn } from \"@/lib/utils\"\n\ninterface TwitterIconProps {\n className?: string\n [key: string]: unknown\n}\nconst Twitter = ({ className, ...props }: TwitterIconProps) => (\n <svg\n stroke=\"currentColor\"\n fill=\"currentColor\"\n strokeWidth=\"0\"\n viewBox=\"0 0 24 24\"\n height=\"1em\"\n width=\"1em\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className={className}\n {...props}\n >\n <g>\n <path fill=\"none\" d=\"M0 0h24v24H0z\"></path>\n <path d=\"M22.162 5.656a8.384 8.384 0 0 1-2.402.658A4.196 4.196 0 0 0 21.6 4c-.82.488-1.719.83-2.656 1.015a4.182 4.182 0 0 0-7.126 3.814 11.874 11.874 0 0 1-8.62-4.37 4.168 4.168 0 0 0-.566 2.103c0 1.45.738 2.731 1.86 3.481a4.168 4.168 0 0 1-1.894-.523v.052a4.185 4.185 0 0 0 3.355 4.101 4.21 4.21 0 0 1-1.89.072A4.185 4.185 0 0 0 7.97 16.65a8.394 8.394 0 0 1-6.191 1.732 11.83 11.83 0 0 0 6.41 1.88c7.693 0 11.9-6.373 11.9-11.9 0-.18-.005-.362-.013-.54a8.496 8.496 0 0 0 2.087-2.165z\"></path>\n </g>\n </svg>\n)\n\nconst Verified = ({ className, ...props }: TwitterIconProps) => (\n <svg\n aria-label=\"Verified Account\"\n viewBox=\"0 0 24 24\"\n className={className}\n {...props}\n >\n <g fill=\"currentColor\">\n <path d=\"M22.5 12.5c0-1.58-.875-2.95-2.148-3.6.154-.435.238-.905.238-1.4 0-2.21-1.71-3.998-3.818-3.998-.47 0-.92.084-1.336.25C14.818 2.415 13.51 1.5 12 1.5s-2.816.917-3.437 2.25c-.415-.165-.866-.25-1.336-.25-2.11 0-3.818 1.79-3.818 4 0 .494.083.964.237 1.4-1.272.65-2.147 2.018-2.147 3.6 0 1.495.782 2.798 1.942 3.486-.02.17-.032.34-.032.514 0 2.21 1.708 4 3.818 4 .47 0 .92-.086 1.335-.25.62 1.334 1.926 2.25 3.437 2.25 1.512 0 2.818-.916 3.437-2.25.415.163.865.248 1.336.248 2.11 0 3.818-1.79 3.818-4 0-.174-.012-.344-.033-.513 1.158-.687 1.943-1.99 1.943-3.484zm-6.616-3.334l-4.334 6.5c-.145.217-.382.334-.625.334-.143 0-.288-.04-.416-.126l-.115-.094-2.415-2.415c-.293-.293-.293-.768 0-1.06s.768-.294 1.06 0l1.77 1.767 3.825-5.74c.23-.345.696-.436 1.04-.207.346.23.44.696.21 1.04z\" />\n </g>\n </svg>\n)\n\nexport const truncate = (str: string | null, length: number) => {\n if (!str || str.length <= length) return str\n return `${str.slice(0, length - 3)}...`\n}\n\nconst Skeleton = ({\n className,\n ...props\n}: React.HTMLAttributes<HTMLDivElement>) => {\n return (\n <div className={cn(\"bg-primary/10 rounded-md\", className)} {...props} />\n )\n}\n\nexport const TweetSkeleton = ({\n className,\n ...props\n}: {\n className?: string\n [key: string]: unknown\n}) => (\n <div\n className={cn(\n \"flex size-full max-h-max min-w-72 flex-col gap-2 rounded-xl border p-4\",\n className\n )}\n {...props}\n >\n <div className=\"flex flex-row gap-2\">\n <Skeleton className=\"size-10 shrink-0 rounded-full\" />\n <Skeleton className=\"h-10 w-full\" />\n </div>\n <Skeleton className=\"h-20 w-full\" />\n </div>\n)\n\nexport const TweetNotFound = ({\n className,\n ...props\n}: {\n className?: string\n [key: string]: unknown\n}) => (\n <div\n className={cn(\n \"flex size-full flex-col items-center justify-center gap-2 rounded-lg border p-4\",\n className\n )}\n {...props}\n >\n <h3>Tweet not found</h3>\n </div>\n)\n\nexport const TweetHeader = ({ tweet }: { tweet: EnrichedTweet }) => (\n <div className=\"flex flex-row items-start justify-between tracking-normal\">\n <div className=\"flex items-center space-x-3\">\n <a\n href={tweet.user.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"shrink-0\"\n >\n <img\n title={`Profile picture of ${tweet.user.name}`}\n alt={tweet.user.screen_name}\n height={48}\n width={48}\n src={tweet.user.profile_image_url_https}\n className=\"border-border/50 overflow-hidden rounded-full border\"\n />\n </a>\n <div className=\"flex flex-col gap-0.5\">\n <a\n href={tweet.user.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-foreground flex items-center font-medium whitespace-nowrap transition-opacity hover:opacity-80\"\n >\n {truncate(tweet.user.name, 20)}\n {tweet.user.verified ||\n (tweet.user.is_blue_verified && (\n <Verified className=\"ml-1 inline size-4 text-blue-500\" />\n ))}\n </a>\n <div className=\"flex items-center space-x-1\">\n <a\n href={tweet.user.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-muted-foreground hover:text-foreground text-sm transition-colors\"\n >\n @{truncate(tweet.user.screen_name, 16)}\n </a>\n </div>\n </div>\n </div>\n <a href={tweet.url} target=\"_blank\" rel=\"noreferrer\">\n <span className=\"sr-only\">Link to tweet</span>\n <Twitter className=\"text-muted-foreground hover:text-foreground size-5 items-start transition-all ease-in-out hover:scale-105\" />\n </a>\n </div>\n)\n\nexport const TweetBody = ({ tweet }: { tweet: EnrichedTweet }) => (\n <div className=\"text-[15px] leading-relaxed tracking-normal wrap-break-word\">\n {tweet.entities.map((entity, idx) => {\n switch (entity.type) {\n case \"url\":\n case \"symbol\":\n case \"hashtag\":\n case \"mention\":\n return (\n <a\n key={idx}\n href={entity.href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-muted-foreground hover:text-foreground text-[15px] font-normal transition-colors\"\n >\n <span>{entity.text}</span>\n </a>\n )\n case \"text\":\n return (\n <span\n key={idx}\n className=\"text-foreground text-[15px] font-normal\"\n dangerouslySetInnerHTML={{ __html: entity.text }}\n />\n )\n default:\n return null\n }\n })}\n </div>\n)\n\nexport const TweetMedia = ({ tweet }: { tweet: EnrichedTweet }) => {\n if (!tweet.video && !tweet.photos) return null\n return (\n <div className=\"flex flex-1 items-center justify-center\">\n {tweet.video && (\n <video\n poster={tweet.video.poster}\n autoPlay\n loop\n muted\n playsInline\n className=\"rounded-xl border shadow-sm\"\n >\n <source src={tweet.video.variants[0].src} type=\"video/mp4\" />\n Your browser does not support the video tag.\n </video>\n )}\n {tweet.photos && (\n <div className=\"relative flex transform-gpu snap-x snap-mandatory gap-4 overflow-x-auto\">\n <div className=\"shrink-0 snap-center sm:w-2\" />\n {tweet.photos.map((photo) => (\n <img\n key={photo.url}\n src={photo.url}\n width={photo.width}\n height={photo.height}\n title={\"Photo by \" + tweet.user.name}\n alt={tweet.text}\n className=\"h-64 w-5/6 shrink-0 snap-center snap-always rounded-xl border object-cover shadow-sm\"\n />\n ))}\n <div className=\"shrink-0 snap-center sm:w-2\" />\n </div>\n )}\n {!tweet.video &&\n !tweet.photos &&\n // @ts-expect-error package doesn't have type definitions\n tweet?.card?.binding_values?.thumbnail_image_large?.image_value.url && (\n <img\n src={\n // @ts-expect-error package doesn't have type definitions\n tweet.card.binding_values.thumbnail_image_large.image_value.url\n }\n className=\"h-64 rounded-xl border object-cover shadow-sm\"\n alt={tweet.text}\n />\n )}\n </div>\n )\n}\n\nexport const MagicTweet = ({\n tweet,\n className,\n ...props\n}: {\n tweet: Tweet\n className?: string\n}) => {\n const enrichedTweet = enrichTweet(tweet)\n return (\n <div\n className={cn(\n \"relative flex h-fit w-full max-w-lg flex-col gap-4 overflow-hidden rounded-xl border p-5\",\n className\n )}\n {...props}\n >\n <TweetHeader tweet={enrichedTweet} />\n <TweetBody tweet={enrichedTweet} />\n <TweetMedia tweet={enrichedTweet} />\n </div>\n )\n}\n\n/**\n * TweetCard (Server Side Only)\n */\nexport const TweetCard = async ({\n id,\n components,\n fallback = <TweetSkeleton />,\n onError,\n ...props\n}: TweetProps & {\n className?: string\n}) => {\n const tweet = id\n ? await getTweet(id).catch((err) => {\n if (onError) {\n onError(err)\n } else {\n console.error(err)\n }\n })\n : undefined\n\n if (!tweet) {\n const NotFound = components?.TweetNotFound ?? TweetNotFound\n return <NotFound {...props} />\n }\n\n return (\n <Suspense fallback={fallback}>\n <MagicTweet tweet={tweet} {...props} />\n </Suspense>\n )\n}\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/public/r/typing-animation.json b/apps/www/public/r/typing-animation.json
index 8baccb45..e77fa24b 100644
--- a/apps/www/public/r/typing-animation.json
+++ b/apps/www/public/r/typing-animation.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/typing-animation.tsx",
- "content": "\"use client\"\n\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type RefAttributes,\n type RefObject,\n} from \"react\"\nimport {\n motion,\n useInView,\n type DOMMotionComponents,\n type HTMLMotionProps,\n type MotionProps,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst motionElements = {\n article: motion.article,\n div: motion.div,\n h1: motion.h1,\n h2: motion.h2,\n h3: motion.h3,\n h4: motion.h4,\n h5: motion.h5,\n h6: motion.h6,\n li: motion.li,\n p: motion.p,\n section: motion.section,\n span: motion.span,\n} as const\n\ntype MotionElementType = Extract<\n keyof DOMMotionComponents,\n keyof typeof motionElements\n>\ntype TypingAnimationMotionComponent = ComponentType<\n Omit<HTMLMotionProps<\"span\">, \"ref\"> & RefAttributes<HTMLElement>\n>\n\ninterface TypingAnimationProps extends Omit<MotionProps, \"children\"> {\n children?: string\n words?: string[]\n className?: string\n duration?: number\n typeSpeed?: number\n deleteSpeed?: number\n delay?: number\n pauseDelay?: number\n loop?: boolean\n as?: MotionElementType\n startOnView?: boolean\n showCursor?: boolean\n blinkCursor?: boolean\n cursorStyle?: \"line\" | \"block\" | \"underscore\"\n}\n\nexport function TypingAnimation({\n children,\n words,\n className,\n duration = 100,\n typeSpeed,\n deleteSpeed,\n delay = 0,\n pauseDelay = 1000,\n loop = false,\n as: Component = \"span\",\n startOnView = true,\n showCursor = true,\n blinkCursor = true,\n cursorStyle = \"line\",\n ...props\n}: TypingAnimationProps) {\n const MotionComponent = motionElements[\n Component\n ] as TypingAnimationMotionComponent\n\n const [displayedText, setDisplayedText] = useState<string>(\"\")\n const [currentWordIndex, setCurrentWordIndex] = useState(0)\n const [currentCharIndex, setCurrentCharIndex] = useState(0)\n const [phase, setPhase] = useState<\"typing\" | \"pause\" | \"deleting\">(\"typing\")\n const elementRef = useRef<HTMLElement | null>(null)\n const isInView = useInView(elementRef as RefObject<Element>, {\n amount: 0.3,\n once: true,\n })\n\n const wordsToAnimate = useMemo(\n () => words ?? (children ? [children] : []),\n [words, children]\n )\n const hasMultipleWords = wordsToAnimate.length > 1\n\n const typingSpeed = typeSpeed ?? duration\n const deletingSpeed = deleteSpeed ?? typingSpeed / 2\n\n const shouldStart = startOnView ? isInView : true\n const animationSourceKey = useMemo(\n () => (words ? words.join(\"\\u0000\") : (children ?? \"\")),\n [words, children]\n )\n\n useEffect(() => {\n setDisplayedText(\"\")\n setCurrentWordIndex(0)\n setCurrentCharIndex(0)\n setPhase(\"typing\")\n }, [animationSourceKey])\n\n useEffect(() => {\n if (!shouldStart || wordsToAnimate.length === 0) return\n\n const timeoutDelay =\n delay > 0 && displayedText === \"\"\n ? delay\n : phase === \"typing\"\n ? typingSpeed\n : phase === \"deleting\"\n ? deletingSpeed\n : pauseDelay\n\n const timeout = setTimeout(() => {\n const currentWord = wordsToAnimate[currentWordIndex] || \"\"\n const graphemes = Array.from(currentWord)\n\n switch (phase) {\n case \"typing\":\n if (currentCharIndex < graphemes.length) {\n setDisplayedText(graphemes.slice(0, currentCharIndex + 1).join(\"\"))\n setCurrentCharIndex(currentCharIndex + 1)\n } else {\n if (hasMultipleWords || loop) {\n const isLastWord = currentWordIndex === wordsToAnimate.length - 1\n if (!isLastWord || loop) {\n setPhase(\"pause\")\n }\n }\n }\n break\n\n case \"pause\":\n setPhase(\"deleting\")\n break\n\n case \"deleting\":\n if (currentCharIndex > 0) {\n setDisplayedText(graphemes.slice(0, currentCharIndex - 1).join(\"\"))\n setCurrentCharIndex(currentCharIndex - 1)\n } else {\n const nextIndex = (currentWordIndex + 1) % wordsToAnimate.length\n setCurrentWordIndex(nextIndex)\n setPhase(\"typing\")\n }\n break\n }\n }, timeoutDelay)\n\n return () => clearTimeout(timeout)\n }, [\n shouldStart,\n phase,\n currentCharIndex,\n currentWordIndex,\n displayedText,\n wordsToAnimate,\n hasMultipleWords,\n loop,\n typingSpeed,\n deletingSpeed,\n pauseDelay,\n delay,\n ])\n\n const currentWordGraphemes = Array.from(\n wordsToAnimate[currentWordIndex] || \"\"\n )\n const isComplete =\n !loop &&\n currentWordIndex === wordsToAnimate.length - 1 &&\n currentCharIndex >= currentWordGraphemes.length &&\n phase !== \"deleting\"\n\n const shouldShowCursor =\n showCursor &&\n !isComplete &&\n (hasMultipleWords || loop || currentCharIndex < currentWordGraphemes.length)\n\n const getCursorChar = () => {\n switch (cursorStyle) {\n case \"block\":\n return \"▌\"\n case \"underscore\":\n return \"_\"\n case \"line\":\n default:\n return \"|\"\n }\n }\n\n return (\n <MotionComponent\n ref={elementRef}\n className={cn(\n \"leading-20 tracking-[-0.02em]\",\n Component === \"span\" && \"inline-block\",\n className\n )}\n {...props}\n >\n {displayedText}\n {shouldShowCursor && (\n <span\n className={cn(\"inline-block\", blinkCursor && \"animate-blink-cursor\")}\n >\n {getCursorChar()}\n </span>\n )}\n </MotionComponent>\n )\n}\n",
+ "content": "\"use client\"\n\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type RefAttributes,\n type RefObject,\n} from \"react\"\nimport {\n motion,\n useInView,\n type DOMMotionComponents,\n type HTMLMotionProps,\n type MotionProps,\n} from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst motionElements = {\n article: motion.article,\n div: motion.div,\n h1: motion.h1,\n h2: motion.h2,\n h3: motion.h3,\n h4: motion.h4,\n h5: motion.h5,\n h6: motion.h6,\n li: motion.li,\n p: motion.p,\n section: motion.section,\n span: motion.span,\n} as const\n\ntype MotionElementType = Extract<\n keyof DOMMotionComponents,\n keyof typeof motionElements\n>\ntype TypingAnimationMotionComponent = ComponentType<\n Omit<HTMLMotionProps<\"span\">, \"ref\"> & RefAttributes<HTMLElement>\n>\n\ninterface TypingAnimationProps extends Omit<MotionProps, \"children\"> {\n children?: string\n words?: string[]\n className?: string\n duration?: number\n typeSpeed?: number\n deleteSpeed?: number\n delay?: number\n pauseDelay?: number\n loop?: boolean\n as?: MotionElementType\n startOnView?: boolean\n showCursor?: boolean\n blinkCursor?: boolean\n cursorStyle?: \"line\" | \"block\" | \"underscore\"\n}\n\nexport function TypingAnimation({\n children,\n words,\n className,\n duration = 100,\n typeSpeed,\n deleteSpeed,\n delay = 0,\n pauseDelay = 1000,\n loop = false,\n as: Component = \"span\",\n startOnView = true,\n showCursor = true,\n blinkCursor = true,\n cursorStyle = \"line\",\n ...props\n}: TypingAnimationProps) {\n const MotionComponent = motionElements[\n Component\n ] as TypingAnimationMotionComponent\n\n const [displayedText, setDisplayedText] = useState<string>(\"\")\n const [currentWordIndex, setCurrentWordIndex] = useState(0)\n const [currentCharIndex, setCurrentCharIndex] = useState(0)\n const [phase, setPhase] = useState<\"typing\" | \"pause\" | \"deleting\">(\"typing\")\n const elementRef = useRef<HTMLElement | null>(null)\n const isInView = useInView(elementRef as RefObject<Element>, {\n amount: 0.3,\n once: true,\n })\n\n const wordsToAnimate = useMemo(\n () => words ?? (children ? [children] : []),\n [words, children]\n )\n const hasMultipleWords = wordsToAnimate.length > 1\n\n const typingSpeed = typeSpeed ?? duration\n const deletingSpeed = deleteSpeed ?? typingSpeed / 2\n\n const shouldStart = startOnView ? isInView : true\n const animationSourceKey = useMemo(\n () => (words ? words.join(\"\\u0000\") : (children ?? \"\")),\n [words, children]\n )\n\n useEffect(() => {\n setDisplayedText(\"\")\n setCurrentWordIndex(0)\n setCurrentCharIndex(0)\n setPhase(\"typing\")\n }, [animationSourceKey])\n\n useEffect(() => {\n let timeout: ReturnType<typeof setTimeout> | null = null\n\n if (shouldStart && wordsToAnimate.length > 0) {\n const timeoutDelay =\n delay > 0 && displayedText === \"\"\n ? delay\n : phase === \"typing\"\n ? typingSpeed\n : phase === \"deleting\"\n ? deletingSpeed\n : pauseDelay\n\n timeout = setTimeout(() => {\n const currentWord = wordsToAnimate[currentWordIndex] || \"\"\n const graphemes = Array.from(currentWord)\n\n switch (phase) {\n case \"typing\":\n if (currentCharIndex < graphemes.length) {\n setDisplayedText(\n graphemes.slice(0, currentCharIndex + 1).join(\"\")\n )\n setCurrentCharIndex(currentCharIndex + 1)\n } else {\n if (hasMultipleWords || loop) {\n const isLastWord =\n currentWordIndex === wordsToAnimate.length - 1\n if (!isLastWord || loop) {\n setPhase(\"pause\")\n }\n }\n }\n break\n\n case \"pause\":\n setPhase(\"deleting\")\n break\n\n case \"deleting\":\n if (currentCharIndex > 0) {\n setDisplayedText(\n graphemes.slice(0, currentCharIndex - 1).join(\"\")\n )\n setCurrentCharIndex(currentCharIndex - 1)\n } else {\n const nextIndex = (currentWordIndex + 1) % wordsToAnimate.length\n setCurrentWordIndex(nextIndex)\n setPhase(\"typing\")\n }\n break\n }\n }, timeoutDelay)\n }\n\n return () => {\n if (timeout !== null) {\n clearTimeout(timeout)\n }\n }\n }, [\n shouldStart,\n phase,\n currentCharIndex,\n currentWordIndex,\n displayedText,\n wordsToAnimate,\n hasMultipleWords,\n loop,\n typingSpeed,\n deletingSpeed,\n pauseDelay,\n delay,\n ])\n\n const currentWordGraphemes = Array.from(\n wordsToAnimate[currentWordIndex] || \"\"\n )\n const isComplete =\n !loop &&\n currentWordIndex === wordsToAnimate.length - 1 &&\n currentCharIndex >= currentWordGraphemes.length &&\n phase !== \"deleting\"\n\n const shouldShowCursor =\n showCursor &&\n !isComplete &&\n (hasMultipleWords || loop || currentCharIndex < currentWordGraphemes.length)\n\n const getCursorChar = () => {\n switch (cursorStyle) {\n case \"block\":\n return \"▌\"\n case \"underscore\":\n return \"_\"\n case \"line\":\n default:\n return \"|\"\n }\n }\n\n return (\n <MotionComponent\n ref={elementRef}\n className={cn(\n \"leading-20 tracking-[-0.02em]\",\n Component === \"span\" && \"inline-block\",\n className\n )}\n {...props}\n >\n {displayedText}\n {shouldShowCursor && (\n <span\n className={cn(\"inline-block\", blinkCursor && \"animate-blink-cursor\")}\n >\n {getCursorChar()}\n </span>\n )}\n </MotionComponent>\n )\n}\n",
"type": "registry:ui"
}
],
diff --git a/apps/www/registry/magicui/animated-grid-pattern.tsx b/apps/www/registry/magicui/animated-grid-pattern.tsx
index ca1ecc4f..249c19d1 100644
--- a/apps/www/registry/magicui/animated-grid-pattern.tsx
+++ b/apps/www/registry/magicui/animated-grid-pattern.tsx
@@ -93,28 +93,32 @@ export function AnimatedGridPattern({
useEffect(() => {
const element = containerRef.current
- if (!element) return
-
- const resizeObserver = new ResizeObserver((entries) => {
- for (const entry of entries) {
- setDimensions((currentDimensions) => {
- const nextWidth = entry.contentRect.width
- const nextHeight = entry.contentRect.height
- if (
- currentDimensions.width === nextWidth &&
- currentDimensions.height === nextHeight
- ) {
- return currentDimensions
- }
- return { width: nextWidth, height: nextHeight }
- })
- }
- })
+ let resizeObserver: ResizeObserver | null = null
+
+ if (element) {
+ resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ setDimensions((currentDimensions) => {
+ const nextWidth = entry.contentRect.width
+ const nextHeight = entry.contentRect.height
+ if (
+ currentDimensions.width === nextWidth &&
+ currentDimensions.height === nextHeight
+ ) {
+ return currentDimensions
+ }
+ return { width: nextWidth, height: nextHeight }
+ })
+ }
+ })
- resizeObserver.observe(element)
+ resizeObserver.observe(element)
+ }
return () => {
- resizeObserver.disconnect()
+ if (resizeObserver) {
+ resizeObserver.disconnect()
+ }
}
}, [])
diff --git a/apps/www/registry/magicui/animated-list.tsx b/apps/www/registry/magicui/animated-list.tsx
index 1cd5ab0d..56028f04 100644
--- a/apps/www/registry/magicui/animated-list.tsx
+++ b/apps/www/registry/magicui/animated-list.tsx
@@ -39,12 +39,18 @@ export const AnimatedList = React.memo(
)
useEffect(() => {
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
if (index < childrenArray.length - 1) {
- const timeout = setTimeout(() => {
+ timeout = setTimeout(() => {
setIndex((prevIndex) => (prevIndex + 1) % childrenArray.length)
}, delay)
+ }
- return () => clearTimeout(timeout)
+ return () => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
}
}, [index, delay, childrenArray.length])
diff --git a/apps/www/registry/magicui/cool-mode.tsx b/apps/www/registry/magicui/cool-mode.tsx
index 61e2de0e..3508fd22 100644
--- a/apps/www/registry/magicui/cool-mode.tsx
+++ b/apps/www/registry/magicui/cool-mode.tsx
@@ -240,8 +240,17 @@ export const CoolMode: React.FC<CoolModeProps> = ({ children, options }) => {
const ref = useRef<HTMLSpanElement>(null)
useEffect(() => {
- if (ref.current) {
- return applyParticleEffect(ref.current, options)
+ const element = ref.current
+ let cleanup: (() => void) | null = null
+
+ if (element) {
+ cleanup = applyParticleEffect(element, options)
+ }
+
+ return () => {
+ if (cleanup) {
+ cleanup()
+ }
}
}, [options])
diff --git a/apps/www/registry/magicui/flickering-grid.tsx b/apps/www/registry/magicui/flickering-grid.tsx
index 17bb6750..e2764dd0 100644
--- a/apps/www/registry/magicui/flickering-grid.tsx
+++ b/apps/www/registry/magicui/flickering-grid.tsx
@@ -112,66 +112,70 @@ export const FlickeringGrid: React.FC<FlickeringGridProps> = ({
useEffect(() => {
const canvas = canvasRef.current
const container = containerRef.current
- if (!canvas || !container) return
-
- const ctx = canvas.getContext("2d")
- if (!ctx) return
-
- let animationFrameId: number
- let gridParams: ReturnType<typeof setupCanvas>
-
- const updateCanvasSize = () => {
- const newWidth = width || container.clientWidth
- const newHeight = height || container.clientHeight
- setCanvasSize({ width: newWidth, height: newHeight })
- gridParams = setupCanvas(canvas, newWidth, newHeight)
- }
-
- updateCanvasSize()
-
- let lastTime = 0
- const animate = (time: number) => {
- if (!isInView) return
-
- const deltaTime = (time - lastTime) / 1000
- lastTime = time
-
- updateSquares(gridParams.squares, deltaTime)
- drawGrid(
- ctx,
- canvas.width,
- canvas.height,
- gridParams.cols,
- gridParams.rows,
- gridParams.squares,
- gridParams.dpr
- )
- animationFrameId = requestAnimationFrame(animate)
- }
+ const ctx = canvas?.getContext("2d") ?? null
+ let animationFrameId: number | null = null
+ let resizeObserver: ResizeObserver | null = null
+ let intersectionObserver: IntersectionObserver | null = null
+ let gridParams: ReturnType<typeof setupCanvas> | null = null
+
+ if (canvas && container && ctx) {
+ const updateCanvasSize = () => {
+ const newWidth = width || container.clientWidth
+ const newHeight = height || container.clientHeight
+ setCanvasSize({ width: newWidth, height: newHeight })
+ gridParams = setupCanvas(canvas, newWidth, newHeight)
+ }
- const resizeObserver = new ResizeObserver(() => {
updateCanvasSize()
- })
- resizeObserver.observe(container)
+ let lastTime = 0
+ const animate = (time: number) => {
+ if (!isInView || !gridParams) return
+
+ const deltaTime = (time - lastTime) / 1000
+ lastTime = time
+
+ updateSquares(gridParams.squares, deltaTime)
+ drawGrid(
+ ctx,
+ canvas.width,
+ canvas.height,
+ gridParams.cols,
+ gridParams.rows,
+ gridParams.squares,
+ gridParams.dpr
+ )
+ animationFrameId = requestAnimationFrame(animate)
+ }
- const intersectionObserver = new IntersectionObserver(
- ([entry]) => {
- setIsInView(entry.isIntersecting)
- },
- { threshold: 0 }
- )
+ resizeObserver = new ResizeObserver(() => {
+ updateCanvasSize()
+ })
+ resizeObserver.observe(container)
- intersectionObserver.observe(canvas)
+ intersectionObserver = new IntersectionObserver(
+ ([entry]) => {
+ setIsInView(entry.isIntersecting)
+ },
+ { threshold: 0 }
+ )
+ intersectionObserver.observe(canvas)
- if (isInView) {
- animationFrameId = requestAnimationFrame(animate)
+ if (isInView) {
+ animationFrameId = requestAnimationFrame(animate)
+ }
}
return () => {
- cancelAnimationFrame(animationFrameId)
- resizeObserver.disconnect()
- intersectionObserver.disconnect()
+ if (animationFrameId !== null) {
+ cancelAnimationFrame(animationFrameId)
+ }
+ if (resizeObserver) {
+ resizeObserver.disconnect()
+ }
+ if (intersectionObserver) {
+ intersectionObserver.disconnect()
+ }
}
}, [setupCanvas, updateSquares, drawGrid, width, height, isInView])
diff --git a/apps/www/registry/magicui/highlighter.tsx b/apps/www/registry/magicui/highlighter.tsx
index 7ad02365..0d19a947 100644
--- a/apps/www/registry/magicui/highlighter.tsx
+++ b/apps/www/registry/magicui/highlighter.tsx
@@ -50,37 +50,40 @@ export function Highlighter({
const shouldShow = !isView || isInView
useEffect(() => {
- if (!shouldShow) return
-
const element = elementRef.current
- if (!element) return
-
- const annotationConfig = {
- type: action,
- color,
- strokeWidth,
- animationDuration,
- iterations,
- padding,
- multiline,
- }
+ let resizeObserver: ResizeObserver | null = null
- const annotation = annotate(element, annotationConfig)
+ if (shouldShow && element) {
+ const annotationConfig = {
+ type: action,
+ color,
+ strokeWidth,
+ animationDuration,
+ iterations,
+ padding,
+ multiline,
+ }
- annotationRef.current = annotation
- annotationRef.current.show()
+ const annotation = annotate(element, annotationConfig)
- const resizeObserver = new ResizeObserver(() => {
- annotation.hide()
+ annotationRef.current = annotation
annotation.show()
- })
- resizeObserver.observe(element)
- resizeObserver.observe(document.body)
+ resizeObserver = new ResizeObserver(() => {
+ annotation.hide()
+ annotation.show()
+ })
+
+ resizeObserver.observe(element)
+ resizeObserver.observe(document.body)
+ }
return () => {
- if (element) {
- annotate(element, { type: action }).remove()
+ if (annotationRef.current) {
+ annotationRef.current.remove()
+ annotationRef.current = null
+ }
+ if (resizeObserver) {
resizeObserver.disconnect()
}
}
diff --git a/apps/www/registry/magicui/hyper-text.tsx b/apps/www/registry/magicui/hyper-text.tsx
index 65ee46dd..045e992d 100644
--- a/apps/www/registry/magicui/hyper-text.tsx
+++ b/apps/www/registry/magicui/hyper-text.tsx
@@ -124,38 +124,43 @@ export function HyperText({
// Handle scramble animation
useEffect(() => {
- if (!isAnimating) return
-
- const maxIterations = children.length
- const startTime = performance.now()
- let animationFrameId: number
-
- const animate = (currentTime: number) => {
- const elapsed = currentTime - startTime
- const progress = Math.min(elapsed / duration, 1)
-
- iterationCount.current = progress * maxIterations
-
- setDisplayText((currentText) =>
- currentText.map((letter, index) =>
- letter === " "
- ? letter
- : index <= iterationCount.current
- ? children[index]
- : characterSet[getRandomInt(characterSet.length)]
+ let animationFrameId: number | null = null
+
+ if (isAnimating) {
+ const maxIterations = children.length
+ const startTime = performance.now()
+
+ const animate = (currentTime: number) => {
+ const elapsed = currentTime - startTime
+ const progress = Math.min(elapsed / duration, 1)
+
+ iterationCount.current = progress * maxIterations
+
+ setDisplayText((currentText) =>
+ currentText.map((letter, index) =>
+ letter === " "
+ ? letter
+ : index <= iterationCount.current
+ ? children[index]
+ : characterSet[getRandomInt(characterSet.length)]
+ )
)
- )
- if (progress < 1) {
- animationFrameId = requestAnimationFrame(animate)
- } else {
- setIsAnimating(false)
+ if (progress < 1) {
+ animationFrameId = requestAnimationFrame(animate)
+ } else {
+ setIsAnimating(false)
+ }
}
- }
- animationFrameId = requestAnimationFrame(animate)
+ animationFrameId = requestAnimationFrame(animate)
+ }
- return () => cancelAnimationFrame(animationFrameId)
+ return () => {
+ if (animationFrameId !== null) {
+ cancelAnimationFrame(animationFrameId)
+ }
+ }
}, [children, duration, isAnimating, characterSet])
return (
diff --git a/apps/www/registry/magicui/icon-cloud.tsx b/apps/www/registry/magicui/icon-cloud.tsx
index 3406e857..02a1d741 100644
--- a/apps/www/registry/magicui/icon-cloud.tsx
+++ b/apps/www/registry/magicui/icon-cloud.tsx
@@ -214,88 +214,91 @@ export function IconCloud({ icons, images }: IconCloudProps) {
useEffect(() => {
const canvas = canvasRef.current
const ctx = canvas?.getContext("2d")
- if (!canvas || !ctx) return
-
- const animate = () => {
- ctx.clearRect(0, 0, canvas.width, canvas.height)
-
- const centerX = canvas.width / 2
- const centerY = canvas.height / 2
- const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY)
- const dx = mousePos.x - centerX
- const dy = mousePos.y - centerY
- const distance = Math.sqrt(dx * dx + dy * dy)
- const speed = 0.003 + (distance / maxDistance) * 0.01
-
- if (targetRotation) {
- const elapsed = performance.now() - targetRotation.startTime
- const progress = Math.min(1, elapsed / targetRotation.duration)
- const easedProgress = easeOutCubic(progress)
-
- rotationRef.current = {
- x:
- targetRotation.startX +
- (targetRotation.x - targetRotation.startX) * easedProgress,
- y:
- targetRotation.startY +
- (targetRotation.y - targetRotation.startY) * easedProgress,
- }
+ if (canvas && ctx) {
+ const animate = () => {
+ ctx.clearRect(0, 0, canvas.width, canvas.height)
+
+ const centerX = canvas.width / 2
+ const centerY = canvas.height / 2
+ const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY)
+ const dx = mousePos.x - centerX
+ const dy = mousePos.y - centerY
+ const distance = Math.sqrt(dx * dx + dy * dy)
+ const speed = 0.003 + (distance / maxDistance) * 0.01
+
+ if (targetRotation) {
+ const elapsed = performance.now() - targetRotation.startTime
+ const progress = Math.min(1, elapsed / targetRotation.duration)
+ const easedProgress = easeOutCubic(progress)
+
+ rotationRef.current = {
+ x:
+ targetRotation.startX +
+ (targetRotation.x - targetRotation.startX) * easedProgress,
+ y:
+ targetRotation.startY +
+ (targetRotation.y - targetRotation.startY) * easedProgress,
+ }
- if (progress >= 1) {
- setTargetRotation(null)
- }
- } else if (!isDragging) {
- rotationRef.current = {
- x: rotationRef.current.x + (dy / canvas.height) * speed,
- y: rotationRef.current.y + (dx / canvas.width) * speed,
+ if (progress >= 1) {
+ setTargetRotation(null)
+ }
+ } else if (!isDragging) {
+ rotationRef.current = {
+ x: rotationRef.current.x + (dy / canvas.height) * speed,
+ y: rotationRef.current.y + (dx / canvas.width) * speed,
+ }
}
- }
- iconPositions.forEach((icon, index) => {
- const cosX = Math.cos(rotationRef.current.x)
- const sinX = Math.sin(rotationRef.current.x)
- const cosY = Math.cos(rotationRef.current.y)
- const sinY = Math.sin(rotationRef.current.y)
-
- const rotatedX = icon.x * cosY - icon.z * sinY
- const rotatedZ = icon.x * sinY + icon.z * cosY
- const rotatedY = icon.y * cosX + rotatedZ * sinX
-
- const scale = (rotatedZ + 200) / 300
- const opacity = Math.max(0.2, Math.min(1, (rotatedZ + 150) / 200))
-
- ctx.save()
- ctx.translate(canvas.width / 2 + rotatedX, canvas.height / 2 + rotatedY)
- ctx.scale(scale, scale)
- ctx.globalAlpha = opacity
-
- if (icons || images) {
- // Only try to render icons/images if they exist
- if (
- iconCanvasesRef.current[index] &&
- imagesLoadedRef.current[index]
- ) {
- ctx.drawImage(iconCanvasesRef.current[index], -20, -20, 40, 40)
+ iconPositions.forEach((icon, index) => {
+ const cosX = Math.cos(rotationRef.current.x)
+ const sinX = Math.sin(rotationRef.current.x)
+ const cosY = Math.cos(rotationRef.current.y)
+ const sinY = Math.sin(rotationRef.current.y)
+
+ const rotatedX = icon.x * cosY - icon.z * sinY
+ const rotatedZ = icon.x * sinY + icon.z * cosY
+ const rotatedY = icon.y * cosX + rotatedZ * sinX
+
+ const scale = (rotatedZ + 200) / 300
+ const opacity = Math.max(0.2, Math.min(1, (rotatedZ + 150) / 200))
+
+ ctx.save()
+ ctx.translate(
+ canvas.width / 2 + rotatedX,
+ canvas.height / 2 + rotatedY
+ )
+ ctx.scale(scale, scale)
+ ctx.globalAlpha = opacity
+
+ if (icons || images) {
+ // Only try to render icons/images if they exist
+ if (
+ iconCanvasesRef.current[index] &&
+ imagesLoadedRef.current[index]
+ ) {
+ ctx.drawImage(iconCanvasesRef.current[index], -20, -20, 40, 40)
+ }
+ } else {
+ // Show numbered circles if no icons/images are provided
+ ctx.beginPath()
+ ctx.arc(0, 0, 20, 0, Math.PI * 2)
+ ctx.fillStyle = "#4444ff"
+ ctx.fill()
+ ctx.fillStyle = "white"
+ ctx.textAlign = "center"
+ ctx.textBaseline = "middle"
+ ctx.font = "16px Arial"
+ ctx.fillText(`${icon.id + 1}`, 0, 0)
}
- } else {
- // Show numbered circles if no icons/images are provided
- ctx.beginPath()
- ctx.arc(0, 0, 20, 0, Math.PI * 2)
- ctx.fillStyle = "#4444ff"
- ctx.fill()
- ctx.fillStyle = "white"
- ctx.textAlign = "center"
- ctx.textBaseline = "middle"
- ctx.font = "16px Arial"
- ctx.fillText(`${icon.id + 1}`, 0, 0)
- }
- ctx.restore()
- })
- animationFrameRef.current = requestAnimationFrame(animate)
- }
+ ctx.restore()
+ })
+ animationFrameRef.current = requestAnimationFrame(animate)
+ }
- animate()
+ animate()
+ }
return () => {
if (animationFrameRef.current) {
diff --git a/apps/www/registry/magicui/number-ticker.tsx b/apps/www/registry/magicui/number-ticker.tsx
index 8a383aa0..99ef26e2 100644
--- a/apps/www/registry/magicui/number-ticker.tsx
+++ b/apps/www/registry/magicui/number-ticker.tsx
@@ -31,11 +31,18 @@ export function NumberTicker({
const isInView = useInView(ref, { once: true, margin: "0px" })
useEffect(() => {
+ let timer: ReturnType<typeof setTimeout> | null = null
+
if (isInView) {
- const timer = setTimeout(() => {
+ timer = setTimeout(() => {
motionValue.set(direction === "down" ? startValue : value)
}, delay * 1000)
- return () => clearTimeout(timer)
+ }
+
+ return () => {
+ if (timer !== null) {
+ clearTimeout(timer)
+ }
}
}, [motionValue, isInView, delay, value, direction, startValue])
diff --git a/apps/www/registry/magicui/pointer.tsx b/apps/www/registry/magicui/pointer.tsx
index f82baaf6..a977eea3 100644
--- a/apps/www/registry/magicui/pointer.tsx
+++ b/apps/www/registry/magicui/pointer.tsx
@@ -30,41 +30,40 @@ export function Pointer({
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
- if (typeof window !== "undefined" && containerRef.current) {
- // Get the parent element directly from the ref
- const parentElement = containerRef.current.parentElement
+ const parentElement =
+ typeof window !== "undefined"
+ ? (containerRef.current?.parentElement ?? null)
+ : null
- if (parentElement) {
- // Add cursor-none to parent
- parentElement.style.cursor = "none"
-
- // Add event listeners to parent
- const handleMouseMove = (e: MouseEvent) => {
- x.set(e.clientX)
- y.set(e.clientY)
- setIsActive(true)
- }
+ const handleMouseMove = (e: MouseEvent) => {
+ x.set(e.clientX)
+ y.set(e.clientY)
+ setIsActive(true)
+ }
- const handleMouseEnter = (e: MouseEvent) => {
- x.set(e.clientX)
- y.set(e.clientY)
- setIsActive(true)
- }
+ const handleMouseEnter = (e: MouseEvent) => {
+ x.set(e.clientX)
+ y.set(e.clientY)
+ setIsActive(true)
+ }
- const handleMouseLeave = () => {
- setIsActive(false)
- }
+ const handleMouseLeave = () => {
+ setIsActive(false)
+ }
- parentElement.addEventListener("mousemove", handleMouseMove)
- parentElement.addEventListener("mouseenter", handleMouseEnter)
- parentElement.addEventListener("mouseleave", handleMouseLeave)
+ if (parentElement) {
+ parentElement.style.cursor = "none"
+ parentElement.addEventListener("mousemove", handleMouseMove)
+ parentElement.addEventListener("mouseenter", handleMouseEnter)
+ parentElement.addEventListener("mouseleave", handleMouseLeave)
+ }
- return () => {
- parentElement.style.cursor = ""
- parentElement.removeEventListener("mousemove", handleMouseMove)
- parentElement.removeEventListener("mouseenter", handleMouseEnter)
- parentElement.removeEventListener("mouseleave", handleMouseLeave)
- }
+ return () => {
+ if (parentElement) {
+ parentElement.style.cursor = ""
+ parentElement.removeEventListener("mousemove", handleMouseMove)
+ parentElement.removeEventListener("mouseenter", handleMouseEnter)
+ parentElement.removeEventListener("mouseleave", handleMouseLeave)
}
}
}, [x, y])
diff --git a/apps/www/registry/magicui/ripple-button.tsx b/apps/www/registry/magicui/ripple-button.tsx
index 70f9b5a8..f583f981 100644
--- a/apps/www/registry/magicui/ripple-button.tsx
+++ b/apps/www/registry/magicui/ripple-button.tsx
@@ -45,14 +45,21 @@ export const RippleButton = React.forwardRef<
}
useEffect(() => {
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
if (buttonRipples.length > 0) {
const lastRipple = buttonRipples[buttonRipples.length - 1]
- const timeout = setTimeout(() => {
+ timeout = setTimeout(() => {
setButtonRipples((prevRipples) =>
prevRipples.filter((ripple) => ripple.key !== lastRipple.key)
)
}, parseInt(duration))
- return () => clearTimeout(timeout)
+ }
+
+ return () => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
}
}, [buttonRipples, duration])
diff --git a/apps/www/registry/magicui/scroll-based-velocity.tsx b/apps/www/registry/magicui/scroll-based-velocity.tsx
index c4540924..4b86e4bf 100644
--- a/apps/www/registry/magicui/scroll-based-velocity.tsx
+++ b/apps/www/registry/magicui/scroll-based-velocity.tsx
@@ -95,47 +95,59 @@ function ScrollVelocityRowImpl({
useEffect(() => {
const container = containerRef.current
const block = blockRef.current
- if (!container || !block) return
-
- const updateSizes = () => {
- const cw = container.offsetWidth || 0
- const bw = block.scrollWidth || 0
- unitWidth.set(bw)
- const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1
- setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies))
- }
-
- updateSizes()
-
- const ro = new ResizeObserver(updateSizes)
- ro.observe(container)
- ro.observe(block)
-
- const io = new IntersectionObserver(([entry]) => {
- isInViewRef.current = entry.isIntersecting
- })
- io.observe(container)
-
+ let ro: ResizeObserver | null = null
+ let io: IntersectionObserver | null = null
+ let mq: MediaQueryList | null = null
const handleVisibility = () => {
isPageVisibleRef.current = document.visibilityState === "visible"
}
- document.addEventListener("visibilitychange", handleVisibility, {
- passive: true,
- })
- handleVisibility()
-
- const mq = window.matchMedia("(prefers-reduced-motion: reduce)")
const handlePRM = () => {
- prefersReducedMotionRef.current = mq.matches
+ if (mq) {
+ prefersReducedMotionRef.current = mq.matches
+ }
+ }
+
+ if (container && block) {
+ const updateSizes = () => {
+ const cw = container.offsetWidth || 0
+ const bw = block.scrollWidth || 0
+ unitWidth.set(bw)
+ const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1
+ setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies))
+ }
+
+ updateSizes()
+
+ ro = new ResizeObserver(updateSizes)
+ ro.observe(container)
+ ro.observe(block)
+
+ io = new IntersectionObserver(([entry]) => {
+ isInViewRef.current = entry.isIntersecting
+ })
+ io.observe(container)
+
+ document.addEventListener("visibilitychange", handleVisibility, {
+ passive: true,
+ })
+ handleVisibility()
+
+ mq = window.matchMedia("(prefers-reduced-motion: reduce)")
+ mq.addEventListener("change", handlePRM)
+ handlePRM()
}
- mq.addEventListener("change", handlePRM)
- handlePRM()
return () => {
- ro.disconnect()
- io.disconnect()
+ if (ro) {
+ ro.disconnect()
+ }
+ if (io) {
+ io.disconnect()
+ }
document.removeEventListener("visibilitychange", handleVisibility)
- mq.removeEventListener("change", handlePRM)
+ if (mq) {
+ mq.removeEventListener("change", handlePRM)
+ }
}
}, [children, unitWidth])
diff --git a/apps/www/registry/magicui/smooth-cursor.tsx b/apps/www/registry/magicui/smooth-cursor.tsx
index bf338a04..a4c4e90c 100644
--- a/apps/www/registry/magicui/smooth-cursor.tsx
+++ b/apps/www/registry/magicui/smooth-cursor.tsx
@@ -110,6 +110,8 @@ export function SmoothCursor({
})
useEffect(() => {
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
const updateVelocity = (currentPos: Position) => {
const currentTime = Date.now()
const deltaTime = currentTime - lastUpdateTime.current
@@ -151,12 +153,14 @@ export function SmoothCursor({
scale.set(0.95)
setIsMoving(true)
- const timeout = setTimeout(() => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
+
+ timeout = setTimeout(() => {
scale.set(1)
setIsMoving(false)
}, 150)
-
- return () => clearTimeout(timeout)
}
}
@@ -177,6 +181,9 @@ export function SmoothCursor({
window.removeEventListener("mousemove", throttledMouseMove)
document.body.style.cursor = "auto"
if (rafId) cancelAnimationFrame(rafId)
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
}
}, [cursorX, cursorY, rotation, scale])
diff --git a/apps/www/registry/magicui/terminal.tsx b/apps/www/registry/magicui/terminal.tsx
index 9311ebdf..1a39d88e 100644
--- a/apps/www/registry/magicui/terminal.tsx
+++ b/apps/www/registry/magicui/terminal.tsx
@@ -148,24 +148,25 @@ export const TypingAnimation = ({
const itemIndex = useItemIndex()
useEffect(() => {
+ let startTimeout: ReturnType<typeof setTimeout> | null = null
+
if (sequence && itemIndex !== null) {
- if (!sequence.sequenceStarted) return
- if (started) return
- if (sequence.activeIndex === itemIndex) {
+ if (
+ sequence.sequenceStarted &&
+ !started &&
+ sequence.activeIndex === itemIndex
+ ) {
setStarted(true)
}
- return
+ } else if (!startOnView || isInView) {
+ startTimeout = setTimeout(() => setStarted(true), delay)
}
- if (!startOnView) {
- const startTimeout = setTimeout(() => setStarted(true), delay)
- return () => clearTimeout(startTimeout)
+ return () => {
+ if (startTimeout !== null) {
+ clearTimeout(startTimeout)
+ }
}
-
- if (!isInView) return
-
- const startTimeout = setTimeout(() => setStarted(true), delay)
- return () => clearTimeout(startTimeout)
}, [
delay,
startOnView,
@@ -177,23 +178,29 @@ export const TypingAnimation = ({
])
useEffect(() => {
- if (!started) return
-
- let i = 0
- const typingEffect = setInterval(() => {
- if (i < children.length) {
- setDisplayedText(children.substring(0, i + 1))
- i++
- } else {
- clearInterval(typingEffect)
- if (sequence && itemIndex !== null) {
- sequence.completeItem(itemIndex)
+ let typingEffect: ReturnType<typeof setInterval> | null = null
+
+ if (started) {
+ let i = 0
+ typingEffect = setInterval(() => {
+ if (i < children.length) {
+ setDisplayedText(children.substring(0, i + 1))
+ i++
+ } else {
+ if (typingEffect !== null) {
+ clearInterval(typingEffect)
+ }
+ if (sequence && itemIndex !== null) {
+ sequence.completeItem(itemIndex)
+ }
}
- }
- }, duration)
+ }, duration)
+ }
return () => {
- clearInterval(typingEffect)
+ if (typingEffect !== null) {
+ clearInterval(typingEffect)
+ }
}
}, [children, duration, started])
diff --git a/apps/www/registry/magicui/tweet-card.tsx b/apps/www/registry/magicui/tweet-card.tsx
index a7b10a75..e854a1c5 100644
--- a/apps/www/registry/magicui/tweet-card.tsx
+++ b/apps/www/registry/magicui/tweet-card.tsx
@@ -172,6 +172,8 @@ export const TweetBody = ({ tweet }: { tweet: EnrichedTweet }) => (
dangerouslySetInnerHTML={{ __html: entity.text }}
/>
)
+ default:
+ return null
}
})}
</div>
diff --git a/apps/www/registry/magicui/typing-animation.tsx b/apps/www/registry/magicui/typing-animation.tsx
index 43d59105..73f52a4c 100644
--- a/apps/www/registry/magicui/typing-animation.tsx
+++ b/apps/www/registry/magicui/typing-animation.tsx
@@ -113,54 +113,65 @@ export function TypingAnimation({
}, [animationSourceKey])
useEffect(() => {
- if (!shouldStart || wordsToAnimate.length === 0) return
-
- const timeoutDelay =
- delay > 0 && displayedText === ""
- ? delay
- : phase === "typing"
- ? typingSpeed
- : phase === "deleting"
- ? deletingSpeed
- : pauseDelay
-
- const timeout = setTimeout(() => {
- const currentWord = wordsToAnimate[currentWordIndex] || ""
- const graphemes = Array.from(currentWord)
-
- switch (phase) {
- case "typing":
- if (currentCharIndex < graphemes.length) {
- setDisplayedText(graphemes.slice(0, currentCharIndex + 1).join(""))
- setCurrentCharIndex(currentCharIndex + 1)
- } else {
- if (hasMultipleWords || loop) {
- const isLastWord = currentWordIndex === wordsToAnimate.length - 1
- if (!isLastWord || loop) {
- setPhase("pause")
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
+ if (shouldStart && wordsToAnimate.length > 0) {
+ const timeoutDelay =
+ delay > 0 && displayedText === ""
+ ? delay
+ : phase === "typing"
+ ? typingSpeed
+ : phase === "deleting"
+ ? deletingSpeed
+ : pauseDelay
+
+ timeout = setTimeout(() => {
+ const currentWord = wordsToAnimate[currentWordIndex] || ""
+ const graphemes = Array.from(currentWord)
+
+ switch (phase) {
+ case "typing":
+ if (currentCharIndex < graphemes.length) {
+ setDisplayedText(
+ graphemes.slice(0, currentCharIndex + 1).join("")
+ )
+ setCurrentCharIndex(currentCharIndex + 1)
+ } else {
+ if (hasMultipleWords || loop) {
+ const isLastWord =
+ currentWordIndex === wordsToAnimate.length - 1
+ if (!isLastWord || loop) {
+ setPhase("pause")
+ }
}
}
- }
- break
-
- case "pause":
- setPhase("deleting")
- break
-
- case "deleting":
- if (currentCharIndex > 0) {
- setDisplayedText(graphemes.slice(0, currentCharIndex - 1).join(""))
- setCurrentCharIndex(currentCharIndex - 1)
- } else {
- const nextIndex = (currentWordIndex + 1) % wordsToAnimate.length
- setCurrentWordIndex(nextIndex)
- setPhase("typing")
- }
- break
- }
- }, timeoutDelay)
+ break
+
+ case "pause":
+ setPhase("deleting")
+ break
+
+ case "deleting":
+ if (currentCharIndex > 0) {
+ setDisplayedText(
+ graphemes.slice(0, currentCharIndex - 1).join("")
+ )
+ setCurrentCharIndex(currentCharIndex - 1)
+ } else {
+ const nextIndex = (currentWordIndex + 1) % wordsToAnimate.length
+ setCurrentWordIndex(nextIndex)
+ setPhase("typing")
+ }
+ break
+ }
+ }, timeoutDelay)
+ }
- return () => clearTimeout(timeout)
+ return () => {
+ if (timeout !== null) {
+ clearTimeout(timeout)
+ }
+ }
}, [
shouldStart,
phase,