Spaces:
Paused
Paused
feat(design-system): implement absolute inversion principle, typographic audits, waitlist interactive features & WCAG 2.1 compliance
d8804ab Download components/ui/icon-cloud.tsx from samirhosninet/HubAPI: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/spaces/samirhosninet/HubAPI/resolve/main/components/ui/icon-cloud.tsx
- Command line
-
hf download hf://spaces/samirhosninet/HubAPI/components/ui/icon-cloud.tsx
-
curl -L -o icon-cloud.tsx https://huggingface.co/spaces/samirhosninet/HubAPI/resolve/main/components/ui/icon-cloud.tsx
18.5 kB
| "use client" | |
| import React, { useEffect, useRef, useState } from "react" | |
| import { renderToString } from "react-dom/server" | |
| interface Icon { | |
| x: number | |
| y: number | |
| z: number | |
| scale: number | |
| opacity: number | |
| id: number | |
| } | |
| export interface CloudItem { | |
| id: string | |
| title: string | |
| url: string | |
| image: string | |
| } | |
| interface IconCloudProps { | |
| icons?: React.ReactNode[] | |
| images?: string[] | |
| items?: CloudItem[] | |
| } | |
| function easeOutCubic(t: number): number { | |
| return 1 - Math.pow(1 - t, 3) | |
| } | |
| export function IconCloud({ icons, images, items }: IconCloudProps) { | |
| const canvasRef = useRef<HTMLCanvasElement>(null) | |
| const [iconPositions, setIconPositions] = useState<Icon[]>([]) | |
| const [isDragging, setIsDragging] = useState(false) | |
| const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 }) | |
| const [mousePos, setMousePos] = useState({ x: 0, y: 0 }) | |
| const [dragMoved, setDragMoved] = useState(false) | |
| const [targetRotation, setTargetRotation] = useState<{ | |
| x: number | |
| y: number | |
| startX: number | |
| startY: number | |
| distance: number | |
| startTime: number | |
| duration: number | |
| } | null>(null) | |
| const animationFrameRef = useRef<number>(0) | |
| const rotationRef = useRef({ x: 0, y: 0 }) | |
| const velocityRef = useRef({ x: 0.002, y: -0.002 }) | |
| const iconCanvasesRef = useRef<HTMLCanvasElement[]>([]) | |
| const imagesLoadedRef = useRef<boolean[]>([]) | |
| // Create icon canvases once when icons/images change | |
| useEffect(() => { | |
| if (!icons && !images && !items) return | |
| const targetItems = items ?? icons ?? images ?? [] | |
| imagesLoadedRef.current = new Array(targetItems.length).fill(false) | |
| const newIconCanvases = targetItems.map((item, index) => { | |
| const size = 100; // High-res offscreen canvas for crisp SVG rendering | |
| const offscreen = document.createElement("canvas") | |
| offscreen.width = size | |
| offscreen.height = size | |
| const offCtx = offscreen.getContext("2d") | |
| if (offCtx) { | |
| if (images || items) { | |
| // Handle image URLs directly | |
| const src = items ? items[index].image : images![index] | |
| const img = new Image() | |
| img.crossOrigin = "anonymous" | |
| img.src = src | |
| img.onload = () => { | |
| // Create a temporary canvas to measure the actual pixel bounds | |
| const tempCanvas = document.createElement("canvas") | |
| tempCanvas.width = size | |
| tempCanvas.height = size | |
| const tempCtx = tempCanvas.getContext("2d") | |
| if (!tempCtx) return | |
| tempCtx.drawImage(img, 0, 0, size, size) | |
| try { | |
| // Find bounding box of non-transparent pixels | |
| const imageData = tempCtx.getImageData(0, 0, size, size) | |
| const data = imageData.data | |
| let minX = size, minY = size, maxX = 0, maxY = 0 | |
| for (let y = 0; y < size; y++) { | |
| for (let x = 0; x < size; x++) { | |
| const alpha = data[(y * size + x) * 4 + 3] | |
| if (alpha > 10) { // Ignore faint shadows/anti-aliasing | |
| if (x < minX) minX = x | |
| if (y < minY) minY = y | |
| if (x > maxX) maxX = x | |
| if (y > maxY) maxY = y | |
| } | |
| } | |
| } | |
| // Fallback if image is completely empty | |
| if (minX > maxX || minY > maxY) { | |
| minX = 0; minY = 0; maxX = size; maxY = size; | |
| } | |
| const cropWidth = maxX - minX + 1 | |
| const cropHeight = maxY - minY + 1 | |
| // Calculate scaling to fit the maximum dimension, preserving aspect ratio | |
| const scale = size / Math.max(cropWidth, cropHeight) | |
| // Make them slightly smaller than the absolute edge (e.g. 90% of max size) | |
| const paddingScale = 0.9 | |
| const finalWidth = cropWidth * scale * paddingScale | |
| const finalHeight = cropHeight * scale * paddingScale | |
| const dx = (size - finalWidth) / 2 | |
| const dy = (size - finalHeight) / 2 | |
| offCtx.clearRect(0, 0, size, size) | |
| // Draw the tightly cropped image scaled up | |
| offCtx.drawImage( | |
| tempCanvas, | |
| minX, minY, cropWidth, cropHeight, | |
| dx, dy, finalWidth, finalHeight | |
| ) | |
| } catch { | |
| // Fallback if CORS prevents getImageData | |
| offCtx.clearRect(0, 0, size, size) | |
| offCtx.drawImage(img, 0, 0, size, size) | |
| } | |
| imagesLoadedRef.current[index] = true | |
| } | |
| } else { | |
| // Handle SVG icons | |
| offCtx.scale(size / 24, size / 24) // scale up assuming 24x24 standard SVG | |
| const svgString = renderToString(item as React.ReactElement) | |
| const img = new Image() | |
| img.src = "data:image/svg+xml;base64," + btoa(svgString) | |
| img.onload = () => { | |
| offCtx.clearRect(0, 0, size, size) | |
| offCtx.drawImage(img, 0, 0, size, size) | |
| imagesLoadedRef.current[index] = true | |
| } | |
| } | |
| } | |
| return offscreen | |
| }) | |
| iconCanvasesRef.current = newIconCanvases | |
| }, [icons, images, items]) | |
| // Generate initial icon positions on a sphere | |
| useEffect(() => { | |
| const targetItems = items ?? icons ?? images ?? [] | |
| const newIcons: Icon[] = [] | |
| const numIcons = targetItems.length || 20 | |
| // Fibonacci sphere parameters | |
| const offset = 2 / numIcons | |
| const increment = Math.PI * (3 - Math.sqrt(5)) | |
| for (let i = 0; i < numIcons; i++) { | |
| const y = i * offset - 1 + offset / 2 | |
| const r = Math.sqrt(1 - y * y) | |
| const phi = i * increment | |
| const x = Math.cos(phi) * r | |
| const z = Math.sin(phi) * r | |
| newIcons.push({ | |
| x: x * 100, | |
| y: y * 100, | |
| z: z * 100, | |
| scale: 1, | |
| opacity: 1, | |
| id: i, | |
| }) | |
| } | |
| const timer = setTimeout(() => { | |
| setIconPositions(newIcons) | |
| }, 0) | |
| return () => clearTimeout(timer) | |
| }, [icons, images, items]) | |
| // Handle mouse events | |
| const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => { | |
| const rect = canvasRef.current?.getBoundingClientRect() | |
| if (!rect || !canvasRef.current) return | |
| const scaleX = canvasRef.current.width / rect.width | |
| const scaleY = canvasRef.current.height / rect.height | |
| const x = (e.clientX - rect.left) * scaleX | |
| const y = (e.clientY - rect.top) * scaleY | |
| const ctx = canvasRef.current.getContext("2d") | |
| if (!ctx) return | |
| iconPositions.forEach((icon) => { | |
| 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 screenX = canvasRef.current!.width / 2 + rotatedX | |
| const screenY = canvasRef.current!.height / 2 + rotatedY | |
| const scale = (rotatedZ + 200) / 300 | |
| const radius = 20 * scale | |
| const dx = x - screenX | |
| const dy = y - screenY | |
| if (dx * dx + dy * dy < radius * radius) { | |
| const targetX = -Math.atan2( | |
| icon.y, | |
| Math.sqrt(icon.x * icon.x + icon.z * icon.z) | |
| ) | |
| const targetY = Math.atan2(icon.x, icon.z) | |
| const currentX = rotationRef.current.x | |
| const currentY = rotationRef.current.y | |
| const distance = Math.sqrt( | |
| Math.pow(targetX - currentX, 2) + Math.pow(targetY - currentY, 2) | |
| ) | |
| const duration = Math.min(2000, Math.max(800, distance * 1000)) | |
| setTargetRotation({ | |
| x: targetX, | |
| y: targetY, | |
| startX: currentX, | |
| startY: currentY, | |
| distance, | |
| startTime: performance.now(), | |
| duration, | |
| }) | |
| return | |
| } | |
| }) | |
| setIsDragging(true) | |
| setDragMoved(false) | |
| setLastMousePos({ x: e.clientX, y: e.clientY }) | |
| } | |
| const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => { | |
| const rect = canvasRef.current?.getBoundingClientRect() | |
| if (rect && canvasRef.current) { | |
| const scaleX = canvasRef.current.width / rect.width | |
| const scaleY = canvasRef.current.height / rect.height | |
| const x = (e.clientX - rect.left) * scaleX | |
| const y = (e.clientY - rect.top) * scaleY | |
| setMousePos({ x, y }) | |
| } | |
| if (isDragging) { | |
| const deltaX = e.clientX - lastMousePos.x | |
| const deltaY = e.clientY - lastMousePos.y | |
| if (Math.abs(deltaX) > 2 || Math.abs(deltaY) > 2) { | |
| setDragMoved(true) | |
| } | |
| rotationRef.current = { | |
| x: rotationRef.current.x + deltaY * 0.002, | |
| y: rotationRef.current.y + deltaX * 0.002, | |
| } | |
| // Update velocity immediately based on drag to maintain inertia after release | |
| velocityRef.current = { | |
| x: deltaY * 0.002, | |
| y: deltaX * 0.002, | |
| } | |
| setLastMousePos({ x: e.clientX, y: e.clientY }) | |
| } | |
| } | |
| const handleMouseUp = () => { | |
| if (!dragMoved && !isDragging && items) { | |
| // Click handled separately | |
| } | |
| setIsDragging(false) | |
| } | |
| const handleMouseLeave = () => { | |
| setIsDragging(false) | |
| // When mouse leaves, reset the target mouse pos to center smoothly | |
| setMousePos({ x: 0, y: 0 }) | |
| } | |
| const handleClick = (e: React.MouseEvent<HTMLCanvasElement>) => { | |
| if (dragMoved) return // Was dragging | |
| const rect = canvasRef.current?.getBoundingClientRect() | |
| if (!rect || !canvasRef.current || !items) return | |
| const scaleX = canvasRef.current.width / rect.width | |
| const scaleY = canvasRef.current.height / rect.height | |
| const x = (e.clientX - rect.left) * scaleX | |
| const y = (e.clientY - rect.top) * scaleY | |
| let clickedItem: CloudItem | null = null | |
| let maxZ = -Infinity | |
| 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 screenX = canvasRef.current!.width / 2 + rotatedX | |
| const screenY = canvasRef.current!.height / 2 + rotatedY | |
| const scale = (rotatedZ + 200) / 300 | |
| const radius = 20 * scale | |
| const dx = x - screenX | |
| const dy = y - screenY | |
| if (dx * dx + dy * dy < radius * radius) { | |
| if (rotatedZ > maxZ && rotatedZ > -50) { | |
| maxZ = rotatedZ | |
| clickedItem = items[index] | |
| } | |
| } | |
| }) | |
| if (clickedItem) { | |
| window.open((clickedItem as CloudItem).url, "_blank") | |
| } | |
| } | |
| // Animation and rendering | |
| useEffect(() => { | |
| const canvas = canvasRef.current | |
| const ctx = canvas?.getContext("2d") | |
| if (canvas && ctx) { | |
| const animate = () => { | |
| ctx.clearRect(0, 0, canvas.width, canvas.height) | |
| const centerX = canvas.width / 2 | |
| const centerY = canvas.height / 2 | |
| // Calculate normalized mouse coordinates [-1, 1] relative to center | |
| // If mousePos is 0,0 (mouse left canvas), it will naturally go to a constant drift | |
| const nx = mousePos.x === 0 && mousePos.y === 0 ? 0.2 : (mousePos.x - centerX) / centerX | |
| const ny = mousePos.x === 0 && mousePos.y === 0 ? 0.2 : (mousePos.y - centerY) / centerY | |
| let targetVelocityX = 0.002 // default idle speed X | |
| let targetVelocityY = -0.002 // default idle speed Y | |
| // If mouse is interacting over canvas bounds, adjust velocity based on pointer | |
| if (mousePos.x > 0 && mousePos.x < canvas.width && mousePos.y > 0 && mousePos.y < canvas.height) { | |
| targetVelocityX = ny * 0.008 | |
| targetVelocityY = nx * 0.008 | |
| } else if (mousePos.x === 0 && mousePos.y === 0) { | |
| // When mouse hasn't interacted or left, fallback to gentle diagonal spin | |
| targetVelocityX = 0.002 | |
| targetVelocityY = -0.002 | |
| } | |
| let hoveredItemIndex: number | null = null | |
| let maxZ = -Infinity | |
| 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) { | |
| // Apply inertia (smoothly transition to the target velocity) | |
| velocityRef.current.x += (targetVelocityX - velocityRef.current.x) * 0.05 | |
| velocityRef.current.y += (targetVelocityY - velocityRef.current.y) * 0.05 | |
| rotationRef.current = { | |
| x: rotationRef.current.x + velocityRef.current.x, | |
| y: rotationRef.current.y + velocityRef.current.y, | |
| } | |
| } else { | |
| // While dragging, we let handleMouseMove control rotation directly | |
| // but we still smoothly decay the targetVelocity to zero to avoid snapping | |
| velocityRef.current.x *= 0.95 | |
| velocityRef.current.y *= 0.95 | |
| } | |
| 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)) | |
| // Check hover state | |
| const screenX = canvas.width / 2 + rotatedX | |
| const screenY = canvas.height / 2 + rotatedY | |
| const radius = 20 * scale | |
| const hdx = mousePos.x - screenX | |
| const hdy = mousePos.y - screenY | |
| if (hdx * hdx + hdy * hdy < radius * radius && rotatedZ > maxZ && rotatedZ > -50) { | |
| maxZ = rotatedZ | |
| hoveredItemIndex = index | |
| } | |
| ctx.save() | |
| ctx.translate( | |
| canvas.width / 2 + rotatedX, | |
| canvas.height / 2 + rotatedY | |
| ) | |
| ctx.scale(scale, scale) | |
| ctx.globalAlpha = opacity | |
| if (icons || images || items) { | |
| // 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) | |
| } | |
| ctx.restore() | |
| }) | |
| if (hoveredItemIndex !== null && items) { | |
| canvas.style.cursor = "pointer" | |
| const hoveredItem = items[hoveredItemIndex] | |
| // Draw tooltip | |
| const hoveredIcon = iconPositions[hoveredItemIndex] | |
| 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 = hoveredIcon.x * cosY - hoveredIcon.z * sinY | |
| const rotatedZ = hoveredIcon.x * sinY + hoveredIcon.z * cosY | |
| const rotatedY = hoveredIcon.y * cosX + rotatedZ * sinX | |
| const screenX = canvas.width / 2 + rotatedX | |
| const screenY = canvas.height / 2 + rotatedY | |
| ctx.font = "14px Inter, sans-serif" | |
| const textWidth = ctx.measureText(hoveredItem.title).width | |
| // Tooltip background | |
| ctx.fillStyle = "rgba(0, 0, 0, 0.75)" | |
| // Use a simple rect instead of roundRect for better compatibility, or emulate it | |
| // Since it's modern web, roundRect is fine in most places, but let's use standard arcs | |
| const rw = textWidth + 24 | |
| const rh = 28 | |
| const rx = screenX - rw / 2 | |
| const ry = screenY - 50 | |
| const r = 6 | |
| ctx.beginPath() | |
| ctx.moveTo(rx + r, ry) | |
| ctx.lineTo(rx + rw - r, ry) | |
| ctx.quadraticCurveTo(rx + rw, ry, rx + rw, ry + r) | |
| ctx.lineTo(rx + rw, ry + rh - r) | |
| ctx.quadraticCurveTo(rx + rw, ry + rh, rx + rw - r, ry + rh) | |
| ctx.lineTo(rx + r, ry + rh) | |
| ctx.quadraticCurveTo(rx, ry + rh, rx, ry + rh - r) | |
| ctx.lineTo(rx, ry + r) | |
| ctx.quadraticCurveTo(rx, ry, rx + r, ry) | |
| ctx.closePath() | |
| ctx.fill() | |
| // Tooltip text | |
| ctx.fillStyle = "#ffffff" | |
| ctx.textAlign = "center" | |
| ctx.textBaseline = "middle" | |
| ctx.fillText(hoveredItem.title, screenX, ry + rh / 2) | |
| } else { | |
| canvas.style.cursor = isDragging ? "grabbing" : "grab" | |
| } | |
| animationFrameRef.current = requestAnimationFrame(animate) | |
| } | |
| animate() | |
| } | |
| return () => { | |
| if (animationFrameRef.current) { | |
| cancelAnimationFrame(animationFrameRef.current) | |
| } | |
| } | |
| }, [icons, images, items, iconPositions, isDragging, mousePos, targetRotation]) | |
| return ( | |
| <canvas | |
| ref={canvasRef} | |
| width={400} | |
| height={400} | |
| onMouseDown={handleMouseDown} | |
| onMouseMove={handleMouseMove} | |
| onMouseUp={handleMouseUp} | |
| onMouseLeave={handleMouseLeave} | |
| onClick={handleClick} | |
| className="rounded-lg" | |
| aria-label="Interactive 3D Icon Cloud" | |
| role="img" | |
| /> | |
| ) | |
| } | |