| [ | |
| { | |
| "id": "camera-control3-d", | |
| "name": "Camera Control 3D", | |
| "description": "A 3D camera control component using Three.js.", | |
| "author": "multimodalart", | |
| "tags": [ | |
| "3D", | |
| "Image" | |
| ], | |
| "category": "Input", | |
| "html_template": "\n <div id=\"camera-control-wrapper\" style=\"width: 100%; height: 450px; position: relative; background: #1a1a1a; border-radius: 12px; overflow: hidden;\">\n <div id=\"prompt-overlay\" style=\"position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); background: rgba(0,0,0,0.8); padding: 8px 16px; border-radius: 8px; font-family: monospace; font-size: 12px; color: #00ff88; white-space: nowrap; z-index: 10;\"></div>\n </div>\n ", | |
| "css_template": "", | |
| "js_on_load": "\n (() => {\n const wrapper = element.querySelector('#camera-control-wrapper');\n const promptOverlay = element.querySelector('#prompt-overlay');\n \n // Wait for THREE to load\n const initScene = () => {\n if (typeof THREE === 'undefined') {\n setTimeout(initScene, 100);\n return;\n }\n \n // Scene setup\n const scene = new THREE.Scene();\n scene.background = new THREE.Color(0x1a1a1a);\n \n const camera = new THREE.PerspectiveCamera(50, wrapper.clientWidth / wrapper.clientHeight, 0.1, 1000);\n camera.position.set(4.5, 3, 4.5);\n camera.lookAt(0, 0.75, 0);\n \n const renderer = new THREE.WebGLRenderer({ antialias: true });\n renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);\n renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));\n wrapper.insertBefore(renderer.domElement, promptOverlay);\n \n // Lighting\n scene.add(new THREE.AmbientLight(0xffffff, 0.6));\n const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);\n dirLight.position.set(5, 10, 5);\n scene.add(dirLight);\n \n // Grid\n scene.add(new THREE.GridHelper(8, 16, 0x333333, 0x222222));\n \n // Constants - reduced distances for tighter framing\n const CENTER = new THREE.Vector3(0, 0.75, 0);\n const BASE_DISTANCE = 1.6;\n const AZIMUTH_RADIUS = 2.4;\n const ELEVATION_RADIUS = 1.8;\n \n // State\n let azimuthAngle = props.value?.azimuth || 0;\n let elevationAngle = props.value?.elevation || 0;\n let distanceFactor = props.value?.distance || 1.0;\n \n // Mappings - reduced wide shot multiplier\n const azimuthSteps = [0, 45, 90, 135, 180, 225, 270, 315];\n const elevationSteps = [-30, 0, 30, 60];\n const distanceSteps = [0.6, 1.0, 1.4];\n \n const azimuthNames = {\n 0: 'front view', 45: 'front-right quarter view', 90: 'right side view',\n 135: 'back-right quarter view', 180: 'back view', 225: 'back-left quarter view',\n 270: 'left side view', 315: 'front-left quarter view'\n };\n const elevationNames = { '-30': 'low-angle shot', '0': 'eye-level shot', '30': 'elevated shot', '60': 'high-angle shot' };\n const distanceNames = { '0.6': 'close-up', '1': 'medium shot', '1.4': 'wide shot' };\n \n function snapToNearest(value, steps) {\n return steps.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);\n }\n \n // Create placeholder texture (smiley face)\n function createPlaceholderTexture() {\n const canvas = document.createElement('canvas');\n canvas.width = 256;\n canvas.height = 256;\n const ctx = canvas.getContext('2d');\n ctx.fillStyle = '#3a3a4a';\n ctx.fillRect(0, 0, 256, 256);\n ctx.fillStyle = '#ffcc99';\n ctx.beginPath();\n ctx.arc(128, 128, 80, 0, Math.PI * 2);\n ctx.fill();\n ctx.fillStyle = '#333';\n ctx.beginPath();\n ctx.arc(100, 110, 10, 0, Math.PI * 2);\n ctx.arc(156, 110, 10, 0, Math.PI * 2);\n ctx.fill();\n ctx.strokeStyle = '#333';\n ctx.lineWidth = 3;\n ctx.beginPath();\n ctx.arc(128, 130, 35, 0.2, Math.PI - 0.2);\n ctx.stroke();\n return new THREE.CanvasTexture(canvas);\n }\n \n // Target image plane\n let currentTexture = createPlaceholderTexture();\n const planeMaterial = new THREE.MeshBasicMaterial({ map: currentTexture, side: THREE.DoubleSide });\n let targetPlane = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.2), planeMaterial);\n targetPlane.position.copy(CENTER);\n scene.add(targetPlane);\n \n // Function to update texture from image URL\n function updateTextureFromUrl(url) {\n if (!url) {\n // Reset to placeholder\n planeMaterial.map = createPlaceholderTexture();\n planeMaterial.needsUpdate = true;\n // Reset plane to square\n scene.remove(targetPlane);\n targetPlane = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.2), planeMaterial);\n targetPlane.position.copy(CENTER);\n scene.add(targetPlane);\n return;\n }\n \n const loader = new THREE.TextureLoader();\n loader.crossOrigin = 'anonymous';\n loader.load(url, (texture) => {\n texture.minFilter = THREE.LinearFilter;\n texture.magFilter = THREE.LinearFilter;\n planeMaterial.map = texture;\n planeMaterial.needsUpdate = true;\n \n // Adjust plane aspect ratio to match image\n const img = texture.image;\n if (img && img.width && img.height) {\n const aspect = img.width / img.height;\n const maxSize = 1.5;\n let planeWidth, planeHeight;\n if (aspect > 1) {\n planeWidth = maxSize;\n planeHeight = maxSize / aspect;\n } else {\n planeHeight = maxSize;\n planeWidth = maxSize * aspect;\n }\n scene.remove(targetPlane);\n targetPlane = new THREE.Mesh(\n new THREE.PlaneGeometry(planeWidth, planeHeight),\n planeMaterial\n );\n targetPlane.position.copy(CENTER);\n scene.add(targetPlane);\n }\n }, undefined, (err) => {\n console.error('Failed to load texture:', err);\n });\n }\n \n // Check for initial imageUrl\n if (props.imageUrl) {\n updateTextureFromUrl(props.imageUrl);\n }\n \n // Camera model\n const cameraGroup = new THREE.Group();\n const bodyMat = new THREE.MeshStandardMaterial({ color: 0x6699cc, metalness: 0.5, roughness: 0.3 });\n const body = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.22, 0.38), bodyMat);\n cameraGroup.add(body);\n const lens = new THREE.Mesh(\n new THREE.CylinderGeometry(0.09, 0.11, 0.18, 16),\n new THREE.MeshStandardMaterial({ color: 0x6699cc, metalness: 0.5, roughness: 0.3 })\n );\n lens.rotation.x = Math.PI / 2;\n lens.position.z = 0.26;\n cameraGroup.add(lens);\n scene.add(cameraGroup);\n \n // GREEN: Azimuth ring\n const azimuthRing = new THREE.Mesh(\n new THREE.TorusGeometry(AZIMUTH_RADIUS, 0.04, 16, 64),\n new THREE.MeshStandardMaterial({ color: 0x00ff88, emissive: 0x00ff88, emissiveIntensity: 0.3 })\n );\n azimuthRing.rotation.x = Math.PI / 2;\n azimuthRing.position.y = 0.05;\n scene.add(azimuthRing);\n \n const azimuthHandle = new THREE.Mesh(\n new THREE.SphereGeometry(0.18, 16, 16),\n new THREE.MeshStandardMaterial({ color: 0x00ff88, emissive: 0x00ff88, emissiveIntensity: 0.5 })\n );\n azimuthHandle.userData.type = 'azimuth';\n scene.add(azimuthHandle);\n \n // PINK: Elevation arc\n const arcPoints = [];\n for (let i = 0; i <= 32; i++) {\n const angle = THREE.MathUtils.degToRad(-30 + (90 * i / 32));\n arcPoints.push(new THREE.Vector3(-0.8, ELEVATION_RADIUS * Math.sin(angle) + CENTER.y, ELEVATION_RADIUS * Math.cos(angle)));\n }\n const arcCurve = new THREE.CatmullRomCurve3(arcPoints);\n const elevationArc = new THREE.Mesh(\n new THREE.TubeGeometry(arcCurve, 32, 0.04, 8, false),\n new THREE.MeshStandardMaterial({ color: 0xff69b4, emissive: 0xff69b4, emissiveIntensity: 0.3 })\n );\n scene.add(elevationArc);\n \n const elevationHandle = new THREE.Mesh(\n new THREE.SphereGeometry(0.18, 16, 16),\n new THREE.MeshStandardMaterial({ color: 0xff69b4, emissive: 0xff69b4, emissiveIntensity: 0.5 })\n );\n elevationHandle.userData.type = 'elevation';\n scene.add(elevationHandle);\n \n // ORANGE: Distance line & handle\n const distanceLineGeo = new THREE.BufferGeometry();\n const distanceLine = new THREE.Line(distanceLineGeo, new THREE.LineBasicMaterial({ color: 0xffa500 }));\n scene.add(distanceLine);\n \n const distanceHandle = new THREE.Mesh(\n new THREE.SphereGeometry(0.18, 16, 16),\n new THREE.MeshStandardMaterial({ color: 0xffa500, emissive: 0xffa500, emissiveIntensity: 0.5 })\n );\n distanceHandle.userData.type = 'distance';\n scene.add(distanceHandle);\n \n function updatePositions() {\n const distance = BASE_DISTANCE * distanceFactor;\n const azRad = THREE.MathUtils.degToRad(azimuthAngle);\n const elRad = THREE.MathUtils.degToRad(elevationAngle);\n \n const camX = distance * Math.sin(azRad) * Math.cos(elRad);\n const camY = distance * Math.sin(elRad) + CENTER.y;\n const camZ = distance * Math.cos(azRad) * Math.cos(elRad);\n \n cameraGroup.position.set(camX, camY, camZ);\n cameraGroup.lookAt(CENTER);\n \n azimuthHandle.position.set(AZIMUTH_RADIUS * Math.sin(azRad), 0.05, AZIMUTH_RADIUS * Math.cos(azRad));\n elevationHandle.position.set(-0.8, ELEVATION_RADIUS * Math.sin(elRad) + CENTER.y, ELEVATION_RADIUS * Math.cos(elRad));\n \n const orangeDist = distance - 0.5;\n distanceHandle.position.set(\n orangeDist * Math.sin(azRad) * Math.cos(elRad),\n orangeDist * Math.sin(elRad) + CENTER.y,\n orangeDist * Math.cos(azRad) * Math.cos(elRad)\n );\n distanceLineGeo.setFromPoints([cameraGroup.position.clone(), CENTER.clone()]);\n \n // Update prompt\n const azSnap = snapToNearest(azimuthAngle, azimuthSteps);\n const elSnap = snapToNearest(elevationAngle, elevationSteps);\n const distSnap = snapToNearest(distanceFactor, distanceSteps);\n const distKey = distSnap === 1 ? '1' : distSnap.toFixed(1);\n const prompt = '<sks> ' + azimuthNames[azSnap] + ' ' + elevationNames[String(elSnap)] + ' ' + distanceNames[distKey];\n promptOverlay.textContent = prompt;\n }\n \n function updatePropsAndTrigger() {\n const azSnap = snapToNearest(azimuthAngle, azimuthSteps);\n const elSnap = snapToNearest(elevationAngle, elevationSteps);\n const distSnap = snapToNearest(distanceFactor, distanceSteps);\n \n props.value = { azimuth: azSnap, elevation: elSnap, distance: distSnap };\n trigger('change', props.value);\n }\n \n // Raycasting\n const raycaster = new THREE.Raycaster();\n const mouse = new THREE.Vector2();\n let isDragging = false;\n let dragTarget = null;\n let dragStartMouse = new THREE.Vector2();\n let dragStartDistance = 1.0;\n const intersection = new THREE.Vector3();\n \n const canvas = renderer.domElement;\n \n canvas.addEventListener('mousedown', (e) => {\n const rect = canvas.getBoundingClientRect();\n mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n \n raycaster.setFromCamera(mouse, camera);\n const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n \n if (intersects.length > 0) {\n isDragging = true;\n dragTarget = intersects[0].object;\n dragTarget.material.emissiveIntensity = 1.0;\n dragTarget.scale.setScalar(1.3);\n dragStartMouse.copy(mouse);\n dragStartDistance = distanceFactor;\n canvas.style.cursor = 'grabbing';\n }\n });\n \n canvas.addEventListener('mousemove', (e) => {\n const rect = canvas.getBoundingClientRect();\n mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n \n if (isDragging && dragTarget) {\n raycaster.setFromCamera(mouse, camera);\n \n if (dragTarget.userData.type === 'azimuth') {\n const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);\n if (raycaster.ray.intersectPlane(plane, intersection)) {\n azimuthAngle = THREE.MathUtils.radToDeg(Math.atan2(intersection.x, intersection.z));\n if (azimuthAngle < 0) azimuthAngle += 360;\n }\n } else if (dragTarget.userData.type === 'elevation') {\n const plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), -0.8);\n if (raycaster.ray.intersectPlane(plane, intersection)) {\n const relY = intersection.y - CENTER.y;\n const relZ = intersection.z;\n elevationAngle = THREE.MathUtils.clamp(THREE.MathUtils.radToDeg(Math.atan2(relY, relZ)), -30, 60);\n }\n } else if (dragTarget.userData.type === 'distance') {\n const deltaY = mouse.y - dragStartMouse.y;\n distanceFactor = THREE.MathUtils.clamp(dragStartDistance - deltaY * 1.5, 0.6, 1.4);\n }\n updatePositions();\n } else {\n raycaster.setFromCamera(mouse, camera);\n const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n [azimuthHandle, elevationHandle, distanceHandle].forEach(h => {\n h.material.emissiveIntensity = 0.5;\n h.scale.setScalar(1);\n });\n if (intersects.length > 0) {\n intersects[0].object.material.emissiveIntensity = 0.8;\n intersects[0].object.scale.setScalar(1.1);\n canvas.style.cursor = 'grab';\n } else {\n canvas.style.cursor = 'default';\n }\n }\n });\n \n const onMouseUp = () => {\n if (dragTarget) {\n dragTarget.material.emissiveIntensity = 0.5;\n dragTarget.scale.setScalar(1);\n \n // Snap and animate\n const targetAz = snapToNearest(azimuthAngle, azimuthSteps);\n const targetEl = snapToNearest(elevationAngle, elevationSteps);\n const targetDist = snapToNearest(distanceFactor, distanceSteps);\n \n const startAz = azimuthAngle, startEl = elevationAngle, startDist = distanceFactor;\n const startTime = Date.now();\n \n function animateSnap() {\n const t = Math.min((Date.now() - startTime) / 200, 1);\n const ease = 1 - Math.pow(1 - t, 3);\n \n let azDiff = targetAz - startAz;\n if (azDiff > 180) azDiff -= 360;\n if (azDiff < -180) azDiff += 360;\n azimuthAngle = startAz + azDiff * ease;\n if (azimuthAngle < 0) azimuthAngle += 360;\n if (azimuthAngle >= 360) azimuthAngle -= 360;\n \n elevationAngle = startEl + (targetEl - startEl) * ease;\n distanceFactor = startDist + (targetDist - startDist) * ease;\n \n updatePositions();\n if (t < 1) requestAnimationFrame(animateSnap);\n else updatePropsAndTrigger();\n }\n animateSnap();\n }\n isDragging = false;\n dragTarget = null;\n canvas.style.cursor = 'default';\n };\n \n canvas.addEventListener('mouseup', onMouseUp);\n canvas.addEventListener('mouseleave', onMouseUp);\n // Touch support for mobile\n canvas.addEventListener('touchstart', (e) => {\n e.preventDefault();\n const touch = e.touches[0];\n const rect = canvas.getBoundingClientRect();\n mouse.x = ((touch.clientX - rect.left) / rect.width) * 2 - 1;\n mouse.y = -((touch.clientY - rect.top) / rect.height) * 2 + 1;\n \n raycaster.setFromCamera(mouse, camera);\n const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n \n if (intersects.length > 0) {\n isDragging = true;\n dragTarget = intersects[0].object;\n dragTarget.material.emissiveIntensity = 1.0;\n dragTarget.scale.setScalar(1.3);\n dragStartMouse.copy(mouse);\n dragStartDistance = distanceFactor;\n }\n }, { passive: false });\n \n canvas.addEventListener('touchmove', (e) => {\n e.preventDefault();\n const touch = e.touches[0];\n const rect = canvas.getBoundingClientRect();\n mouse.x = ((touch.clientX - rect.left) / rect.width) * 2 - 1;\n mouse.y = -((touch.clientY - rect.top) / rect.height) * 2 + 1;\n \n if (isDragging && dragTarget) {\n raycaster.setFromCamera(mouse, camera);\n \n if (dragTarget.userData.type === 'azimuth') {\n const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);\n if (raycaster.ray.intersectPlane(plane, intersection)) {\n azimuthAngle = THREE.MathUtils.radToDeg(Math.atan2(intersection.x, intersection.z));\n if (azimuthAngle < 0) azimuthAngle += 360;\n }\n } else if (dragTarget.userData.type === 'elevation') {\n const plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), -0.8);\n if (raycaster.ray.intersectPlane(plane, intersection)) {\n const relY = intersection.y - CENTER.y;\n const relZ = intersection.z;\n elevationAngle = THREE.MathUtils.clamp(THREE.MathUtils.radToDeg(Math.atan2(relY, relZ)), -30, 60);\n }\n } else if (dragTarget.userData.type === 'distance') {\n const deltaY = mouse.y - dragStartMouse.y;\n distanceFactor = THREE.MathUtils.clamp(dragStartDistance - deltaY * 1.5, 0.6, 1.4);\n }\n updatePositions();\n }\n }, { passive: false });\n \n canvas.addEventListener('touchend', (e) => {\n e.preventDefault();\n onMouseUp();\n }, { passive: false });\n \n canvas.addEventListener('touchcancel', (e) => {\n e.preventDefault();\n onMouseUp();\n }, { passive: false });\n \n // Initial update\n updatePositions();\n \n // Render loop\n function render() {\n requestAnimationFrame(render);\n renderer.render(scene, camera);\n }\n render();\n \n // Handle resize\n new ResizeObserver(() => {\n camera.aspect = wrapper.clientWidth / wrapper.clientHeight;\n camera.updateProjectionMatrix();\n renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);\n }).observe(wrapper);\n \n // Store update functions for external calls\n wrapper._updateFromProps = (newVal) => {\n if (newVal && typeof newVal === 'object') {\n azimuthAngle = newVal.azimuth ?? azimuthAngle;\n elevationAngle = newVal.elevation ?? elevationAngle;\n distanceFactor = newVal.distance ?? distanceFactor;\n updatePositions();\n }\n };\n \n wrapper._updateTexture = updateTextureFromUrl;\n \n // Watch for prop changes (imageUrl and value)\n let lastImageUrl = props.imageUrl;\n let lastValue = JSON.stringify(props.value);\n setInterval(() => {\n // Check imageUrl changes\n if (props.imageUrl !== lastImageUrl) {\n lastImageUrl = props.imageUrl;\n updateTextureFromUrl(props.imageUrl);\n }\n // Check value changes (from sliders)\n const currentValue = JSON.stringify(props.value);\n if (currentValue !== lastValue) {\n lastValue = currentValue;\n if (props.value && typeof props.value === 'object') {\n azimuthAngle = props.value.azimuth ?? azimuthAngle;\n elevationAngle = props.value.elevation ?? elevationAngle;\n distanceFactor = props.value.distance ?? distanceFactor;\n updatePositions();\n }\n }\n }, 100);\n };\n \n initScene();\n })();\n ", | |
| "default_props": { | |
| "value": { | |
| "azimuth": 0, | |
| "elevation": 0, | |
| "distance": 1.0 | |
| }, | |
| "imageUrl": null | |
| }, | |
| "head": "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js\"></script>", | |
| "python_code": "class CameraControl3D(gr.HTML):\n \"\"\"\n A 3D camera control component using Three.js.\n Outputs: { azimuth: number, elevation: number, distance: number }\n Accepts imageUrl prop to display user's uploaded image on the plane.\n \"\"\"\n def __init__(self, value=None, imageUrl=None, **kwargs):\n if value is None:\n value = {\"azimuth\": 0, \"elevation\": 0, \"distance\": 1.0}\n\n html_template = \"\"\"\n <div id=\"camera-control-wrapper\" style=\"width: 100%; height: 450px; position: relative; background: #1a1a1a; border-radius: 12px; overflow: hidden;\">\n <div id=\"prompt-overlay\" style=\"position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); background: rgba(0,0,0,0.8); padding: 8px 16px; border-radius: 8px; font-family: monospace; font-size: 12px; color: #00ff88; white-space: nowrap; z-index: 10;\"></div>\n </div>\n \"\"\"\n\n js_on_load = \"\"\"\n (() => {\n const wrapper = element.querySelector('#camera-control-wrapper');\n const promptOverlay = element.querySelector('#prompt-overlay');\n\n // Wait for THREE to load\n const initScene = () => {\n if (typeof THREE === 'undefined') {\n setTimeout(initScene, 100);\n return;\n }\n\n // Scene setup\n const scene = new THREE.Scene();\n scene.background = new THREE.Color(0x1a1a1a);\n\n const camera = new THREE.PerspectiveCamera(50, wrapper.clientWidth / wrapper.clientHeight, 0.1, 1000);\n camera.position.set(4.5, 3, 4.5);\n camera.lookAt(0, 0.75, 0);\n\n const renderer = new THREE.WebGLRenderer({ antialias: true });\n renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);\n renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));\n wrapper.insertBefore(renderer.domElement, promptOverlay);\n\n // Lighting\n scene.add(new THREE.AmbientLight(0xffffff, 0.6));\n const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);\n dirLight.position.set(5, 10, 5);\n scene.add(dirLight);\n\n // Grid\n scene.add(new THREE.GridHelper(8, 16, 0x333333, 0x222222));\n\n // Constants - reduced distances for tighter framing\n const CENTER = new THREE.Vector3(0, 0.75, 0);\n const BASE_DISTANCE = 1.6;\n const AZIMUTH_RADIUS = 2.4;\n const ELEVATION_RADIUS = 1.8;\n\n // State\n let azimuthAngle = props.value?.azimuth || 0;\n let elevationAngle = props.value?.elevation || 0;\n let distanceFactor = props.value?.distance || 1.0;\n\n // Mappings - reduced wide shot multiplier\n const azimuthSteps = [0, 45, 90, 135, 180, 225, 270, 315];\n const elevationSteps = [-30, 0, 30, 60];\n const distanceSteps = [0.6, 1.0, 1.4];\n\n const azimuthNames = {\n 0: 'front view', 45: 'front-right quarter view', 90: 'right side view',\n 135: 'back-right quarter view', 180: 'back view', 225: 'back-left quarter view',\n 270: 'left side view', 315: 'front-left quarter view'\n };\n const elevationNames = { '-30': 'low-angle shot', '0': 'eye-level shot', '30': 'elevated shot', '60': 'high-angle shot' };\n const distanceNames = { '0.6': 'close-up', '1': 'medium shot', '1.4': 'wide shot' };\n\n function snapToNearest(value, steps) {\n return steps.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);\n }\n\n // Create placeholder texture (smiley face)\n function createPlaceholderTexture() {\n const canvas = document.createElement('canvas');\n canvas.width = 256;\n canvas.height = 256;\n const ctx = canvas.getContext('2d');\n ctx.fillStyle = '#3a3a4a';\n ctx.fillRect(0, 0, 256, 256);\n ctx.fillStyle = '#ffcc99';\n ctx.beginPath();\n ctx.arc(128, 128, 80, 0, Math.PI * 2);\n ctx.fill();\n ctx.fillStyle = '#333';\n ctx.beginPath();\n ctx.arc(100, 110, 10, 0, Math.PI * 2);\n ctx.arc(156, 110, 10, 0, Math.PI * 2);\n ctx.fill();\n ctx.strokeStyle = '#333';\n ctx.lineWidth = 3;\n ctx.beginPath();\n ctx.arc(128, 130, 35, 0.2, Math.PI - 0.2);\n ctx.stroke();\n return new THREE.CanvasTexture(canvas);\n }\n\n // Target image plane\n let currentTexture = createPlaceholderTexture();\n const planeMaterial = new THREE.MeshBasicMaterial({ map: currentTexture, side: THREE.DoubleSide });\n let targetPlane = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.2), planeMaterial);\n targetPlane.position.copy(CENTER);\n scene.add(targetPlane);\n\n // Function to update texture from image URL\n function updateTextureFromUrl(url) {\n if (!url) {\n // Reset to placeholder\n planeMaterial.map = createPlaceholderTexture();\n planeMaterial.needsUpdate = true;\n // Reset plane to square\n scene.remove(targetPlane);\n targetPlane = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.2), planeMaterial);\n targetPlane.position.copy(CENTER);\n scene.add(targetPlane);\n return;\n }\n\n const loader = new THREE.TextureLoader();\n loader.crossOrigin = 'anonymous';\n loader.load(url, (texture) => {\n texture.minFilter = THREE.LinearFilter;\n texture.magFilter = THREE.LinearFilter;\n planeMaterial.map = texture;\n planeMaterial.needsUpdate = true;\n\n // Adjust plane aspect ratio to match image\n const img = texture.image;\n if (img && img.width && img.height) {\n const aspect = img.width / img.height;\n const maxSize = 1.5;\n let planeWidth, planeHeight;\n if (aspect > 1) {\n planeWidth = maxSize;\n planeHeight = maxSize / aspect;\n } else {\n planeHeight = maxSize;\n planeWidth = maxSize * aspect;\n }\n scene.remove(targetPlane);\n targetPlane = new THREE.Mesh(\n new THREE.PlaneGeometry(planeWidth, planeHeight),\n planeMaterial\n );\n targetPlane.position.copy(CENTER);\n scene.add(targetPlane);\n }\n }, undefined, (err) => {\n console.error('Failed to load texture:', err);\n });\n }\n\n // Check for initial imageUrl\n if (props.imageUrl) {\n updateTextureFromUrl(props.imageUrl);\n }\n\n // Camera model\n const cameraGroup = new THREE.Group();\n const bodyMat = new THREE.MeshStandardMaterial({ color: 0x6699cc, metalness: 0.5, roughness: 0.3 });\n const body = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.22, 0.38), bodyMat);\n cameraGroup.add(body);\n const lens = new THREE.Mesh(\n new THREE.CylinderGeometry(0.09, 0.11, 0.18, 16),\n new THREE.MeshStandardMaterial({ color: 0x6699cc, metalness: 0.5, roughness: 0.3 })\n );\n lens.rotation.x = Math.PI / 2;\n lens.position.z = 0.26;\n cameraGroup.add(lens);\n scene.add(cameraGroup);\n\n // GREEN: Azimuth ring\n const azimuthRing = new THREE.Mesh(\n new THREE.TorusGeometry(AZIMUTH_RADIUS, 0.04, 16, 64),\n new THREE.MeshStandardMaterial({ color: 0x00ff88, emissive: 0x00ff88, emissiveIntensity: 0.3 })\n );\n azimuthRing.rotation.x = Math.PI / 2;\n azimuthRing.position.y = 0.05;\n scene.add(azimuthRing);\n\n const azimuthHandle = new THREE.Mesh(\n new THREE.SphereGeometry(0.18, 16, 16),\n new THREE.MeshStandardMaterial({ color: 0x00ff88, emissive: 0x00ff88, emissiveIntensity: 0.5 })\n );\n azimuthHandle.userData.type = 'azimuth';\n scene.add(azimuthHandle);\n\n // PINK: Elevation arc\n const arcPoints = [];\n for (let i = 0; i <= 32; i++) {\n const angle = THREE.MathUtils.degToRad(-30 + (90 * i / 32));\n arcPoints.push(new THREE.Vector3(-0.8, ELEVATION_RADIUS * Math.sin(angle) + CENTER.y, ELEVATION_RADIUS * Math.cos(angle)));\n }\n const arcCurve = new THREE.CatmullRomCurve3(arcPoints);\n const elevationArc = new THREE.Mesh(\n new THREE.TubeGeometry(arcCurve, 32, 0.04, 8, false),\n new THREE.MeshStandardMaterial({ color: 0xff69b4, emissive: 0xff69b4, emissiveIntensity: 0.3 })\n );\n scene.add(elevationArc);\n\n const elevationHandle = new THREE.Mesh(\n new THREE.SphereGeometry(0.18, 16, 16),\n new THREE.MeshStandardMaterial({ color: 0xff69b4, emissive: 0xff69b4, emissiveIntensity: 0.5 })\n );\n elevationHandle.userData.type = 'elevation';\n scene.add(elevationHandle);\n\n // ORANGE: Distance line & handle\n const distanceLineGeo = new THREE.BufferGeometry();\n const distanceLine = new THREE.Line(distanceLineGeo, new THREE.LineBasicMaterial({ color: 0xffa500 }));\n scene.add(distanceLine);\n\n const distanceHandle = new THREE.Mesh(\n new THREE.SphereGeometry(0.18, 16, 16),\n new THREE.MeshStandardMaterial({ color: 0xffa500, emissive: 0xffa500, emissiveIntensity: 0.5 })\n );\n distanceHandle.userData.type = 'distance';\n scene.add(distanceHandle);\n\n function updatePositions() {\n const distance = BASE_DISTANCE * distanceFactor;\n const azRad = THREE.MathUtils.degToRad(azimuthAngle);\n const elRad = THREE.MathUtils.degToRad(elevationAngle);\n\n const camX = distance * Math.sin(azRad) * Math.cos(elRad);\n const camY = distance * Math.sin(elRad) + CENTER.y;\n const camZ = distance * Math.cos(azRad) * Math.cos(elRad);\n\n cameraGroup.position.set(camX, camY, camZ);\n cameraGroup.lookAt(CENTER);\n\n azimuthHandle.position.set(AZIMUTH_RADIUS * Math.sin(azRad), 0.05, AZIMUTH_RADIUS * Math.cos(azRad));\n elevationHandle.position.set(-0.8, ELEVATION_RADIUS * Math.sin(elRad) + CENTER.y, ELEVATION_RADIUS * Math.cos(elRad));\n\n const orangeDist = distance - 0.5;\n distanceHandle.position.set(\n orangeDist * Math.sin(azRad) * Math.cos(elRad),\n orangeDist * Math.sin(elRad) + CENTER.y,\n orangeDist * Math.cos(azRad) * Math.cos(elRad)\n );\n distanceLineGeo.setFromPoints([cameraGroup.position.clone(), CENTER.clone()]);\n\n // Update prompt\n const azSnap = snapToNearest(azimuthAngle, azimuthSteps);\n const elSnap = snapToNearest(elevationAngle, elevationSteps);\n const distSnap = snapToNearest(distanceFactor, distanceSteps);\n const distKey = distSnap === 1 ? '1' : distSnap.toFixed(1);\n const prompt = '<sks> ' + azimuthNames[azSnap] + ' ' + elevationNames[String(elSnap)] + ' ' + distanceNames[distKey];\n promptOverlay.textContent = prompt;\n }\n\n function updatePropsAndTrigger() {\n const azSnap = snapToNearest(azimuthAngle, azimuthSteps);\n const elSnap = snapToNearest(elevationAngle, elevationSteps);\n const distSnap = snapToNearest(distanceFactor, distanceSteps);\n\n props.value = { azimuth: azSnap, elevation: elSnap, distance: distSnap };\n trigger('change', props.value);\n }\n\n // Raycasting\n const raycaster = new THREE.Raycaster();\n const mouse = new THREE.Vector2();\n let isDragging = false;\n let dragTarget = null;\n let dragStartMouse = new THREE.Vector2();\n let dragStartDistance = 1.0;\n const intersection = new THREE.Vector3();\n\n const canvas = renderer.domElement;\n\n canvas.addEventListener('mousedown', (e) => {\n const rect = canvas.getBoundingClientRect();\n mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n\n raycaster.setFromCamera(mouse, camera);\n const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n\n if (intersects.length > 0) {\n isDragging = true;\n dragTarget = intersects[0].object;\n dragTarget.material.emissiveIntensity = 1.0;\n dragTarget.scale.setScalar(1.3);\n dragStartMouse.copy(mouse);\n dragStartDistance = distanceFactor;\n canvas.style.cursor = 'grabbing';\n }\n });\n\n canvas.addEventListener('mousemove', (e) => {\n const rect = canvas.getBoundingClientRect();\n mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n\n if (isDragging && dragTarget) {\n raycaster.setFromCamera(mouse, camera);\n\n if (dragTarget.userData.type === 'azimuth') {\n const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);\n if (raycaster.ray.intersectPlane(plane, intersection)) {\n azimuthAngle = THREE.MathUtils.radToDeg(Math.atan2(intersection.x, intersection.z));\n if (azimuthAngle < 0) azimuthAngle += 360;\n }\n } else if (dragTarget.userData.type === 'elevation') {\n const plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), -0.8);\n if (raycaster.ray.intersectPlane(plane, intersection)) {\n const relY = intersection.y - CENTER.y;\n const relZ = intersection.z;\n elevationAngle = THREE.MathUtils.clamp(THREE.MathUtils.radToDeg(Math.atan2(relY, relZ)), -30, 60);\n }\n } else if (dragTarget.userData.type === 'distance') {\n const deltaY = mouse.y - dragStartMouse.y;\n distanceFactor = THREE.MathUtils.clamp(dragStartDistance - deltaY * 1.5, 0.6, 1.4);\n }\n updatePositions();\n } else {\n raycaster.setFromCamera(mouse, camera);\n const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n [azimuthHandle, elevationHandle, distanceHandle].forEach(h => {\n h.material.emissiveIntensity = 0.5;\n h.scale.setScalar(1);\n });\n if (intersects.length > 0) {\n intersects[0].object.material.emissiveIntensity = 0.8;\n intersects[0].object.scale.setScalar(1.1);\n canvas.style.cursor = 'grab';\n } else {\n canvas.style.cursor = 'default';\n }\n }\n });\n\n const onMouseUp = () => {\n if (dragTarget) {\n dragTarget.material.emissiveIntensity = 0.5;\n dragTarget.scale.setScalar(1);\n\n // Snap and animate\n const targetAz = snapToNearest(azimuthAngle, azimuthSteps);\n const targetEl = snapToNearest(elevationAngle, elevationSteps);\n const targetDist = snapToNearest(distanceFactor, distanceSteps);\n\n const startAz = azimuthAngle, startEl = elevationAngle, startDist = distanceFactor;\n const startTime = Date.now();\n\n function animateSnap() {\n const t = Math.min((Date.now() - startTime) / 200, 1);\n const ease = 1 - Math.pow(1 - t, 3);\n\n let azDiff = targetAz - startAz;\n if (azDiff > 180) azDiff -= 360;\n if (azDiff < -180) azDiff += 360;\n azimuthAngle = startAz + azDiff * ease;\n if (azimuthAngle < 0) azimuthAngle += 360;\n if (azimuthAngle >= 360) azimuthAngle -= 360;\n\n elevationAngle = startEl + (targetEl - startEl) * ease;\n distanceFactor = startDist + (targetDist - startDist) * ease;\n\n updatePositions();\n if (t < 1) requestAnimationFrame(animateSnap);\n else updatePropsAndTrigger();\n }\n animateSnap();\n }\n isDragging = false;\n dragTarget = null;\n canvas.style.cursor = 'default';\n };\n\n canvas.addEventListener('mouseup', onMouseUp);\n canvas.addEventListener('mouseleave', onMouseUp);\n // Touch support for mobile\n canvas.addEventListener('touchstart', (e) => {\n e.preventDefault();\n const touch = e.touches[0];\n const rect = canvas.getBoundingClientRect();\n mouse.x = ((touch.clientX - rect.left) / rect.width) * 2 - 1;\n mouse.y = -((touch.clientY - rect.top) / rect.height) * 2 + 1;\n\n raycaster.setFromCamera(mouse, camera);\n const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n\n if (intersects.length > 0) {\n isDragging = true;\n dragTarget = intersects[0].object;\n dragTarget.material.emissiveIntensity = 1.0;\n dragTarget.scale.setScalar(1.3);\n dragStartMouse.copy(mouse);\n dragStartDistance = distanceFactor;\n }\n }, { passive: false });\n\n canvas.addEventListener('touchmove', (e) => {\n e.preventDefault();\n const touch = e.touches[0];\n const rect = canvas.getBoundingClientRect();\n mouse.x = ((touch.clientX - rect.left) / rect.width) * 2 - 1;\n mouse.y = -((touch.clientY - rect.top) / rect.height) * 2 + 1;\n\n if (isDragging && dragTarget) {\n raycaster.setFromCamera(mouse, camera);\n\n if (dragTarget.userData.type === 'azimuth') {\n const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);\n if (raycaster.ray.intersectPlane(plane, intersection)) {\n azimuthAngle = THREE.MathUtils.radToDeg(Math.atan2(intersection.x, intersection.z));\n if (azimuthAngle < 0) azimuthAngle += 360;\n }\n } else if (dragTarget.userData.type === 'elevation') {\n const plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), -0.8);\n if (raycaster.ray.intersectPlane(plane, intersection)) {\n const relY = intersection.y - CENTER.y;\n const relZ = intersection.z;\n elevationAngle = THREE.MathUtils.clamp(THREE.MathUtils.radToDeg(Math.atan2(relY, relZ)), -30, 60);\n }\n } else if (dragTarget.userData.type === 'distance') {\n const deltaY = mouse.y - dragStartMouse.y;\n distanceFactor = THREE.MathUtils.clamp(dragStartDistance - deltaY * 1.5, 0.6, 1.4);\n }\n updatePositions();\n }\n }, { passive: false });\n\n canvas.addEventListener('touchend', (e) => {\n e.preventDefault();\n onMouseUp();\n }, { passive: false });\n\n canvas.addEventListener('touchcancel', (e) => {\n e.preventDefault();\n onMouseUp();\n }, { passive: false });\n\n // Initial update\n updatePositions();\n\n // Render loop\n function render() {\n requestAnimationFrame(render);\n renderer.render(scene, camera);\n }\n render();\n\n // Handle resize\n new ResizeObserver(() => {\n camera.aspect = wrapper.clientWidth / wrapper.clientHeight;\n camera.updateProjectionMatrix();\n renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);\n }).observe(wrapper);\n\n // Store update functions for external calls\n wrapper._updateFromProps = (newVal) => {\n if (newVal && typeof newVal === 'object') {\n azimuthAngle = newVal.azimuth ?? azimuthAngle;\n elevationAngle = newVal.elevation ?? elevationAngle;\n distanceFactor = newVal.distance ?? distanceFactor;\n updatePositions();\n }\n };\n\n wrapper._updateTexture = updateTextureFromUrl;\n\n // Watch for prop changes (imageUrl and value)\n let lastImageUrl = props.imageUrl;\n let lastValue = JSON.stringify(props.value);\n setInterval(() => {\n // Check imageUrl changes\n if (props.imageUrl !== lastImageUrl) {\n lastImageUrl = props.imageUrl;\n updateTextureFromUrl(props.imageUrl);\n }\n // Check value changes (from sliders)\n const currentValue = JSON.stringify(props.value);\n if (currentValue !== lastValue) {\n lastValue = currentValue;\n if (props.value && typeof props.value === 'object') {\n azimuthAngle = props.value.azimuth ?? azimuthAngle;\n elevationAngle = props.value.elevation ?? elevationAngle;\n distanceFactor = props.value.distance ?? distanceFactor;\n updatePositions();\n }\n }\n }, 100);\n };\n\n initScene();\n })();\n \"\"\"\n\n super().__init__(\n value=value,\n html_template=html_template,\n js_on_load=js_on_load,\n imageUrl=imageUrl,\n **kwargs\n )\n", | |
| "repo_url": "https://huggingface.co/spaces/multimodalart/qwen-image-multiple-angles-3d-camera/" | |
| }, | |
| { | |
| "id": "detection-viewer", | |
| "name": "Detection Viewer", | |
| "description": "Rich viewer for object detection model outputs", | |
| "author": "hysts", | |
| "tags": [], | |
| "category": "display", | |
| "html_template": "<div class=\"pose-viewer-container\" data-panel-title=\"Detections\" data-list-height=\"300\" data-score-threshold-min=\"0.0\" data-score-threshold-max=\"1.0\" data-keypoint-threshold=\"0.0\" data-keypoint-radius=\"3\">\n <script type=\"application/json\" class=\"pose-data\">${value}</script>\n <div class=\"canvas-wrapper\">\n <canvas></canvas>\n </div>\n <div class=\"tooltip\"></div>\n <div class=\"control-panel\">\n <div class=\"control-panel-header\">\n <div class=\"control-panel-header-info\">\n <span class=\"control-panel-title\">Detections</span>\n <span class=\"control-panel-count\"></span>\n </div>\n <div class=\"control-panel-actions\">\n <button class=\"cp-btn toggle-image-btn active\" title=\"Toggle base image (I)\">Image</button>\n <button class=\"cp-btn reset-btn\" title=\"Reset to defaults (R)\">↺</button>\n <button class=\"cp-btn help-btn\" title=\"Keyboard shortcuts (?)\">?</button>\n <button class=\"cp-btn maximize-btn\" title=\"Maximize (F)\">⛶</button>\n </div>\n </div>\n <div class=\"control-panel-body\">\n <div class=\"annotation-list\"></div>\n </div>\n </div>\n <div class=\"help-overlay\">\n <div class=\"help-dialog\">\n <div class=\"help-header\">\n <span>Keyboard Shortcuts</span>\n <button class=\"help-close-btn\">×</button>\n </div>\n <table class=\"help-table\">\n <tr><td><kbd>?</kbd></td><td>Show keyboard shortcuts</td></tr>\n <tr><td><kbd>F</kbd></td><td>Toggle maximize</td></tr>\n <tr><td><kbd>I</kbd></td><td>Toggle base image</td></tr>\n <tr><td><kbd>A</kbd></td><td>Toggle all annotations</td></tr>\n <tr><td><kbd>H</kbd></td><td>Hide selected annotation</td></tr>\n <tr><td><kbd>Shift+Click</kbd></td><td>Hide clicked annotation</td></tr>\n <tr><td><kbd>Esc</kbd></td><td>Deselect / exit maximize</td></tr>\n <tr><td><kbd>+</kbd> / <kbd>-</kbd></td><td>Zoom in / out</td></tr>\n <tr><td><kbd>0</kbd></td><td>Reset zoom</td></tr>\n <tr><td><kbd>R</kbd></td><td>Reset all to defaults</td></tr>\n </table>\n </div>\n </div>\n <div class=\"loading-indicator\"><div class=\"loading-spinner\"></div></div>\n <div class=\"placeholder\">No data</div>\n</div>\n", | |
| "css_template": ".pose-viewer-container {\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n user-select: none;\n width: 100%;\n position: relative;\n box-sizing: border-box;\n}\n\n/* \u2500\u2500 Maximized Overlay \u2500\u2500 */\n\n.pose-viewer-container.maximized {\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n z-index: 9999;\n background: var(--background-fill-primary, #fff);\n display: flex;\n flex-direction: column;\n padding: 0;\n overflow: hidden;\n}\n\n.pose-viewer-container.maximized .canvas-wrapper {\n flex: 1;\n min-height: 0;\n border-radius: 0;\n align-items: center;\n}\n\n.pose-viewer-container.maximized .control-panel {\n flex-shrink: 0;\n max-height: 40vh;\n border-radius: 0;\n border-left: none;\n border-right: none;\n border-bottom: none;\n margin-top: 0;\n}\n\n.pose-viewer-container.maximized .maximize-btn {\n background: var(--color-accent, #2196F3);\n color: #fff;\n border-color: var(--color-accent, #2196F3);\n}\n\n/* \u2500\u2500 Canvas \u2500\u2500 */\n\n.pose-viewer-container .canvas-wrapper {\n display: none;\n justify-content: center;\n border-radius: 4px;\n overflow: hidden;\n}\n\n.pose-viewer-container .canvas-wrapper canvas {\n display: block;\n touch-action: none;\n}\n\n/* \u2500\u2500 Loading Indicator \u2500\u2500 */\n\n.pose-viewer-container .loading-indicator {\n display: none;\n justify-content: center;\n align-items: center;\n border: 2px dashed var(--border-color-primary, #d0d0d0);\n border-radius: 8px;\n padding: 48px 24px;\n}\n\n.pose-viewer-container .loading-indicator.visible {\n display: flex;\n}\n\n.pose-viewer-container .loading-spinner {\n width: 24px;\n height: 24px;\n border: 3px solid var(--border-color-primary, #d0d0d0);\n border-top-color: var(--color-accent, #2196F3);\n border-radius: 50%;\n animation: detection-viewer-spin 0.8s linear infinite;\n}\n\n@keyframes detection-viewer-spin {\n to { transform: rotate(360deg); }\n}\n\n/* \u2500\u2500 Placeholder \u2500\u2500 */\n\n.pose-viewer-container .placeholder {\n border: 2px dashed var(--border-color-primary, #d0d0d0);\n border-radius: 8px;\n padding: 48px 24px;\n text-align: center;\n color: var(--body-text-color-subdued, #888);\n font-size: 14px;\n}\n\n.pose-viewer-container .placeholder.hidden {\n display: none;\n}\n\n/* \u2500\u2500 Tooltip \u2500\u2500 */\n\n.pose-viewer-container .tooltip {\n display: none;\n position: absolute;\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n padding: 4px 8px;\n border-radius: 4px;\n font-size: 12px;\n pointer-events: none;\n white-space: nowrap;\n z-index: 10;\n}\n\n.pose-viewer-container .tooltip.visible {\n display: block;\n}\n\n/* \u2500\u2500 Control Panel \u2500\u2500 */\n\n.pose-viewer-container .control-panel {\n display: none;\n flex-direction: column;\n border: 1px solid var(--border-color-primary, #e0e0e0);\n border-radius: 6px;\n margin-top: 8px;\n font-size: 12px;\n overflow: hidden;\n}\n\n.pose-viewer-container .control-panel.visible {\n display: flex;\n}\n\n.pose-viewer-container .control-panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 6px 10px;\n background: var(--background-fill-secondary, #f7f7f7);\n border-bottom: 1px solid var(--border-color-primary, #e0e0e0);\n}\n\n.pose-viewer-container .control-panel-header-info {\n display: flex;\n align-items: center;\n gap: 8px;\n}\n\n.pose-viewer-container .control-panel-title {\n font-weight: 600;\n color: var(--body-text-color, #333);\n}\n\n.pose-viewer-container .control-panel-count {\n font-weight: 400;\n color: var(--body-text-color-subdued, #888);\n}\n\n.pose-viewer-container .control-panel-actions {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n.pose-viewer-container .cp-btn {\n all: unset;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n height: 22px;\n padding: 0 8px;\n background: transparent;\n border: 1px solid var(--border-color-primary, #d0d0d0);\n border-radius: 3px;\n cursor: pointer;\n font-size: 11px;\n line-height: 1;\n color: var(--body-text-color, #333);\n box-sizing: border-box;\n}\n\n.pose-viewer-container .cp-btn:hover {\n background: var(--background-fill-primary, #eee);\n}\n\n.pose-viewer-container .toggle-image-btn.active {\n background: var(--color-accent, #2196F3);\n color: #fff;\n border-color: var(--color-accent, #2196F3);\n}\n\n.pose-viewer-container .toggle-image-btn.active:hover {\n opacity: 0.9;\n}\n\n.pose-viewer-container .control-panel-body {\n overflow-y: auto;\n min-height: 0;\n}\n\n.pose-viewer-container .annotation-rows {\n max-height: 300px;\n overflow: hidden auto;\n}\n\n/* \u2500\u2500 Select-All Row \u2500\u2500 */\n\n.pose-viewer-container .select-all-row {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 5px 10px;\n border-bottom: 1px solid var(--border-color-primary, #e0e0e0);\n border-left: 3px solid transparent;\n padding-left: 28px;\n}\n\n.pose-viewer-container .select-all-row .select-all-checkbox {\n flex-shrink: 0;\n cursor: pointer;\n}\n\n.pose-viewer-container .select-all-row .select-all-label {\n font-size: 12px;\n font-weight: 600;\n color: var(--body-text-color, #333);\n}\n\n/* \u2500\u2500 Annotation Row \u2500\u2500 */\n\n.pose-viewer-container .annotation-row {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 5px 10px;\n cursor: pointer;\n border-left: 3px solid transparent;\n transition: background 0.15s;\n}\n\n.pose-viewer-container .annotation-row:hover {\n background: var(--background-fill-secondary, #f5f5f5);\n}\n\n.pose-viewer-container .annotation-row .ann-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n flex-shrink: 0;\n}\n\n.pose-viewer-container .annotation-row .ann-checkbox {\n flex-shrink: 0;\n cursor: pointer;\n}\n\n.pose-viewer-container .annotation-row .ann-label {\n flex: 1;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n color: var(--body-text-color, #333);\n}\n\n.pose-viewer-container .annotation-row .ann-summary {\n color: var(--body-text-color-subdued, #888);\n white-space: nowrap;\n font-size: 11px;\n}\n\n/* \u2500\u2500 Expand Button \u2500\u2500 */\n\n.pose-viewer-container .annotation-row .ann-expand {\n all: unset;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 16px;\n height: 16px;\n flex-shrink: 0;\n cursor: pointer;\n font-size: 8px;\n color: var(--body-text-color-subdued, #888);\n border-radius: 3px;\n transition: transform 0.15s;\n}\n\n.pose-viewer-container .annotation-row .ann-expand:hover {\n background: var(--border-color-primary, #e0e0e0);\n color: var(--body-text-color, #333);\n}\n\n.pose-viewer-container .annotation-row .ann-expand.expanded {\n transform: rotate(90deg);\n}\n\n/* \u2500\u2500 Selected Row \u2500\u2500 */\n\n.pose-viewer-container .annotation-row.selected {\n border-left-color: var(--color-accent, #2196F3);\n background: var(--background-fill-secondary, #f0f7ff);\n}\n\n.pose-viewer-container .annotation-row.below-threshold {\n opacity: 0.4;\n}\n\n/* \u2500\u2500 Annotation Detail \u2500\u2500 */\n\n.pose-viewer-container .annotation-detail {\n display: none;\n padding: 6px 10px 8px 31px;\n font-size: 11px;\n color: var(--body-text-color-subdued, #666);\n border-bottom: 1px solid var(--border-color-primary, #eee);\n max-height: 150px;\n overflow-y: auto;\n}\n\n.pose-viewer-container .annotation-detail.visible {\n display: block;\n}\n\n.pose-viewer-container .annotation-detail table {\n width: 100%;\n border-collapse: collapse;\n}\n\n.pose-viewer-container .annotation-detail td {\n padding: 1px 6px 1px 0;\n}\n\n.pose-viewer-container .annotation-detail .detail-section-title {\n font-weight: 600;\n margin-bottom: 2px;\n color: var(--body-text-color, #333);\n}\n\n/* \u2500\u2500 Layer Toggles \u2500\u2500 */\n\n.pose-viewer-container .layer-toggles {\n display: flex;\n align-items: center;\n gap: 4px;\n padding: 6px 10px;\n border-bottom: 1px solid var(--border-color-primary, #e0e0e0);\n}\n\n.pose-viewer-container .layer-btn {\n all: unset;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n height: 22px;\n padding: 0 8px;\n background: var(--background-fill-primary, #eee);\n border: 1px solid var(--border-color-primary, #d0d0d0);\n border-radius: 3px;\n cursor: pointer;\n font-size: 11px;\n line-height: 1;\n color: var(--body-text-color, #333);\n box-sizing: border-box;\n}\n\n.pose-viewer-container .layer-btn.active {\n background: var(--color-accent, #2196F3);\n color: #fff;\n border-color: var(--color-accent, #2196F3);\n}\n\n/* \u2500\u2500 Label Filters \u2500\u2500 */\n\n.pose-viewer-container .label-filters {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 4px;\n padding: 6px 10px;\n border-bottom: 1px solid var(--border-color-primary, #e0e0e0);\n}\n\n.pose-viewer-container .label-filters-title {\n font-size: 11px;\n font-weight: 600;\n color: var(--body-text-color, #333);\n margin-right: 4px;\n}\n\n.pose-viewer-container .label-filter-btn {\n all: unset;\n display: inline-flex;\n align-items: center;\n touch-action: manipulation;\n gap: 4px;\n height: 22px;\n padding: 0 8px;\n background: var(--background-fill-primary, #eee);\n border: 1px solid var(--border-color-primary, #d0d0d0);\n border-radius: 3px;\n cursor: pointer;\n font-size: 11px;\n line-height: 1;\n color: var(--body-text-color-subdued, #888);\n box-sizing: border-box;\n}\n\n.pose-viewer-container .label-filter-btn.active {\n color: var(--body-text-color, #333);\n border-color: var(--body-text-color-subdued, #888);\n}\n\n.pose-viewer-container .label-color-dot {\n display: inline-block;\n width: 8px;\n height: 8px;\n border-radius: 50%;\n flex-shrink: 0;\n}\n\n.pose-viewer-container .label-count {\n opacity: 0.6;\n}\n\n/* \u2500\u2500 Sort Controls \u2500\u2500 */\n\n.pose-viewer-container .sort-controls {\n display: flex;\n align-items: center;\n gap: 4px;\n padding: 6px 10px;\n border-bottom: 1px solid var(--border-color-primary, #e0e0e0);\n}\n\n.pose-viewer-container .sort-controls-title {\n font-size: 11px;\n font-weight: 600;\n color: var(--body-text-color, #333);\n margin-right: 4px;\n}\n\n.pose-viewer-container .sort-btn {\n all: unset;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n height: 22px;\n padding: 0 8px;\n background: var(--background-fill-primary, #eee);\n border: 1px solid var(--border-color-primary, #d0d0d0);\n border-radius: 3px;\n cursor: pointer;\n font-size: 11px;\n line-height: 1;\n color: var(--body-text-color-subdued, #888);\n box-sizing: border-box;\n}\n\n.pose-viewer-container .sort-btn.active {\n color: var(--body-text-color, #333);\n border-color: var(--body-text-color-subdued, #888);\n}\n\n/* \u2500\u2500 Annotation Group Separator \u2500\u2500 */\n\n.pose-viewer-container .annotation-group-separator {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 4px 10px;\n font-size: 10px;\n color: var(--body-text-color-subdued, #888);\n}\n\n.pose-viewer-container .annotation-group-separator::before,\n.pose-viewer-container .annotation-group-separator::after {\n content: \"\";\n flex: 1;\n height: 1px;\n background: var(--border-color-primary, #e0e0e0);\n}\n\n/* \u2500\u2500 Filtered-out Row \u2500\u2500 */\n\n.pose-viewer-container .annotation-row.filtered-out {\n opacity: 0.4;\n}\n\n/* \u2500\u2500 Threshold Slider \u2500\u2500 */\n\n.pose-viewer-container .threshold-row {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 5px 10px;\n border-bottom: 1px solid var(--border-color-primary, #e0e0e0);\n font-size: 11px;\n color: var(--body-text-color, #333);\n}\n\n.pose-viewer-container .threshold-row input[type=\"range\"] {\n flex: 1;\n height: 14px;\n margin: 0;\n cursor: pointer;\n -webkit-appearance: none;\n appearance: none;\n background: transparent;\n}\n\n.pose-viewer-container .threshold-row input[type=\"range\"]::-webkit-slider-thumb {\n -webkit-appearance: none;\n appearance: none;\n width: 14px;\n height: 14px;\n border-radius: 50%;\n background: var(--color-accent, #2196F3);\n border: 2px solid #fff;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);\n cursor: pointer;\n}\n\n.pose-viewer-container .threshold-row input[type=\"range\"]::-moz-range-thumb {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n background: var(--color-accent, #2196F3);\n border: 2px solid #fff;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);\n cursor: pointer;\n}\n\n.pose-viewer-container .threshold-row .threshold-value,\n.pose-viewer-container .threshold-row .slider-value {\n min-width: 32px;\n text-align: right;\n color: var(--body-text-color-subdued, #888);\n}\n\n/* \u2500\u2500 Dual Range Slider \u2500\u2500 */\n\n.pose-viewer-container .dual-range-wrapper {\n position: relative;\n flex: 1;\n height: 4px;\n border-radius: 2px;\n background: var(--border-color-primary, #d0d0d0);\n}\n\n.pose-viewer-container .dual-range-wrapper input[type=\"range\"] {\n position: absolute;\n top: 50%;\n left: 0;\n transform: translateY(-50%);\n width: 100%;\n height: 14px;\n margin: 0;\n padding: 0;\n background: transparent;\n pointer-events: none;\n -webkit-appearance: none;\n appearance: none;\n}\n\n.pose-viewer-container .dual-range-wrapper input[type=\"range\"]::-webkit-slider-thumb {\n -webkit-appearance: none;\n appearance: none;\n width: 14px;\n height: 14px;\n border-radius: 50%;\n background: var(--color-accent, #2196F3);\n border: 2px solid #fff;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);\n cursor: pointer;\n pointer-events: all;\n}\n\n.pose-viewer-container .dual-range-wrapper input[type=\"range\"]::-moz-range-thumb {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n background: var(--color-accent, #2196F3);\n border: 2px solid #fff;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);\n cursor: pointer;\n pointer-events: all;\n}\n\n.pose-viewer-container .dual-range-wrapper input[type=\"range\"]::-webkit-slider-runnable-track {\n background: transparent;\n}\n\n.pose-viewer-container .dual-range-wrapper input[type=\"range\"]::-moz-range-track {\n background: transparent;\n}\n\n/* \u2500\u2500 Draw Options (collapsible) \u2500\u2500 */\n\n.pose-viewer-container .draw-options {\n border-bottom: 1px solid var(--border-color-primary, #e0e0e0);\n}\n\n.pose-viewer-container .draw-options-toggle {\n all: unset;\n display: flex;\n align-items: center;\n gap: 4px;\n width: 100%;\n padding: 4px 10px;\n cursor: pointer;\n font-size: 11px;\n color: var(--body-text-color-subdued, #888);\n box-sizing: border-box;\n}\n\n.pose-viewer-container .draw-options-toggle:hover {\n background: var(--background-fill-secondary, #f5f5f5);\n}\n\n.pose-viewer-container .draw-options-arrow {\n font-size: 8px;\n transition: transform 0.15s;\n}\n\n.pose-viewer-container .draw-options.open .draw-options-arrow {\n transform: rotate(90deg);\n}\n\n.pose-viewer-container .draw-options-body {\n display: none;\n}\n\n.pose-viewer-container .draw-options.open .draw-options-body {\n display: block;\n}\n\n.pose-viewer-container .draw-options-body .threshold-row {\n border-bottom: none;\n padding-top: 2px;\n padding-bottom: 2px;\n}\n\n.pose-viewer-container .draw-options-body .threshold-row:last-child {\n padding-bottom: 6px;\n}\n\n/* \u2500\u2500 Help Overlay \u2500\u2500 */\n\n.pose-viewer-container .help-overlay {\n display: none;\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.4);\n z-index: 10000;\n justify-content: center;\n align-items: center;\n}\n\n.pose-viewer-container.maximized .help-overlay {\n position: fixed;\n}\n\n.pose-viewer-container .help-overlay.visible {\n display: flex;\n}\n\n.pose-viewer-container .help-dialog {\n background: var(--background-fill-primary, #fff);\n border: 1px solid var(--border-color-primary, #e0e0e0);\n border-radius: 8px;\n padding: 16px 20px;\n max-width: 320px;\n width: 90%;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);\n}\n\n.pose-viewer-container .help-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 12px;\n font-size: 14px;\n font-weight: 600;\n color: var(--body-text-color, #333);\n}\n\n.pose-viewer-container .help-close-btn {\n all: unset;\n cursor: pointer;\n font-size: 18px;\n line-height: 1;\n color: var(--body-text-color-subdued, #888);\n padding: 0 4px;\n}\n\n.pose-viewer-container .help-close-btn:hover {\n color: var(--body-text-color, #333);\n}\n\n.pose-viewer-container .help-table {\n width: 100%;\n border-collapse: collapse;\n font-size: 12px;\n color: var(--body-text-color, #333);\n}\n\n.pose-viewer-container .help-table td {\n padding: 4px 0;\n}\n\n.pose-viewer-container .help-table td:first-child {\n white-space: nowrap;\n padding-right: 16px;\n}\n\n.pose-viewer-container .help-table kbd {\n display: inline-block;\n background: var(--background-fill-secondary, #f3f3f3);\n border: 1px solid var(--border-color-primary, #d0d0d0);\n border-radius: 3px;\n padding: 1px 5px;\n font-family: ui-monospace, SFMono-Regular, \"SF Mono\", Menlo, monospace;\n font-size: 11px;\n line-height: 1.4;\n}\n", | |
| "js_on_load": "// Guard: skip if already initialized\nif (element._poseInitialized) return;\nelement._poseInitialized = true;\n\n(function () {\n \"use strict\";\n\n var MAX_CANVAS_HEIGHT = 600;\n var KEYPOINT_RADIUS = 3;\n var HIT_RADIUS = 10;\n var MASK_ALPHA = 0.4;\n var CONNECTION_ALPHA = 0.7;\n var CONNECTION_WIDTH = 2;\n var BBOX_LINE_WIDTH = 2;\n var BBOX_LABEL_FONT = \"bold 11px -apple-system, BlinkMacSystemFont, sans-serif\";\n var DIM_ALPHA = 0.2;\n var MIN_ZOOM = 1;\n var MAX_ZOOM = 20;\n var ZOOM_SENSITIVITY = 0.001;\n var DRAG_THRESHOLD = 4;\n\n // \u2500\u2500 DOM References \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n var container = element.querySelector(\".pose-viewer-container\");\n var dataScript = element.querySelector(\"script.pose-data\");\n var canvasWrapper = element.querySelector(\".canvas-wrapper\");\n var canvas = element.querySelector(\"canvas\");\n var ctx = canvas.getContext(\"2d\");\n var tooltip = element.querySelector(\".tooltip\");\n var controlPanel = element.querySelector(\".control-panel\");\n var annotationList = element.querySelector(\".annotation-list\");\n\n // Read configurable threshold defaults\n var initialScoreThresholdMin = parseFloat(container.getAttribute(\"data-score-threshold-min\")) || 0;\n var initialScoreThresholdMax = parseFloat(container.getAttribute(\"data-score-threshold-max\"));\n if (isNaN(initialScoreThresholdMax)) initialScoreThresholdMax = 1;\n var initialKeypointThreshold = parseFloat(container.getAttribute(\"data-keypoint-threshold\")) || 0;\n var initialKeypointRadius = parseInt(container.getAttribute(\"data-keypoint-radius\"), 10);\n if (isNaN(initialKeypointRadius) || initialKeypointRadius < 1) initialKeypointRadius = KEYPOINT_RADIUS;\n var toggleImageBtn = element.querySelector(\".toggle-image-btn\");\n var resetBtn = element.querySelector(\".reset-btn\");\n var maximizeBtn = element.querySelector(\".maximize-btn\");\n var helpBtn = element.querySelector(\".help-btn\");\n var helpOverlay = element.querySelector(\".help-overlay\");\n var helpCloseBtn = element.querySelector(\".help-close-btn\");\n var loadingIndicator = element.querySelector(\".loading-indicator\");\n var placeholder = element.querySelector(\".placeholder\");\n var countEl = element.querySelector(\".control-panel-count\");\n\n // \u2500\u2500 State \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n var state = {\n image: null,\n annotations: [],\n scale: 1,\n visibility: [],\n selectedIndex: -1,\n showImage: true,\n layers: { masks: true, boxes: true, skeleton: true, keypoints: true },\n thresholdMin: initialScoreThresholdMin,\n thresholdMax: initialScoreThresholdMax,\n keypointThreshold: initialKeypointThreshold,\n keypointRadius: initialKeypointRadius,\n connectionWidth: CONNECTION_WIDTH,\n maskAlpha: MASK_ALPHA,\n connectionAlpha: CONNECTION_ALPHA,\n bboxLineWidth: BBOX_LINE_WIDTH,\n labelVisibility: {},\n maskImages: [],\n zoom: 1,\n panX: 0,\n panY: 0,\n isPanning: false,\n panStartX: 0,\n panStartY: 0,\n panStartPanX: 0,\n panStartPanY: 0,\n didDrag: false,\n maximized: false,\n sortMode: \"none\",\n sortedIndices: [],\n expandedIndex: -1,\n drawOptionsOpen: false\n };\n\n // \u2500\u2500 MutationObserver for value changes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n var observer = new MutationObserver(function () {\n handleValueChange();\n });\n observer.observe(dataScript, { childList: true, characterData: true, subtree: true });\n\n // Also handle initial value\n handleValueChange();\n\n // \u2500\u2500 Value Change Handler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function handleValueChange() {\n var raw = dataScript.textContent.trim();\n if (!raw || raw === \"null\") {\n showPlaceholder();\n return;\n }\n\n var data;\n try {\n data = JSON.parse(raw);\n } catch (e) {\n showPlaceholder();\n return;\n }\n\n if (!data || !data.image) {\n showPlaceholder();\n return;\n }\n\n // Update score threshold if provided in payload\n if (data.scoreThresholdMin != null) {\n initialScoreThresholdMin = data.scoreThresholdMin;\n state.thresholdMin = data.scoreThresholdMin;\n }\n if (data.scoreThresholdMax != null) {\n initialScoreThresholdMax = data.scoreThresholdMax;\n state.thresholdMax = data.scoreThresholdMax;\n }\n\n // Show loading spinner while the image is being fetched.\n // Gradio's updateDOM() resets JS-managed inline styles and\n // classes back to template defaults on every value change,\n // so we must re-establish the display state here.\n showLoading();\n\n var img = new Image();\n img.onload = function () {\n state.image = img;\n state.annotations = data.annotations || [];\n state.visibility = [];\n for (var i = 0; i < state.annotations.length; i++) {\n state.visibility.push(true);\n }\n state.selectedIndex = -1;\n\n // Build label visibility map\n state.labelVisibility = {};\n for (var i = 0; i < state.annotations.length; i++) {\n var lbl = state.annotations[i].label;\n if (lbl && !state.labelVisibility.hasOwnProperty(lbl)) {\n state.labelVisibility[lbl] = true;\n }\n }\n\n // Decode RLE masks to offscreen canvases\n state.maskImages = [];\n for (var i = 0; i < state.annotations.length; i++) {\n if (state.annotations[i].mask) {\n state.maskImages[i] = createMaskCanvas(state.annotations[i].mask, state.annotations[i].color);\n } else {\n state.maskImages[i] = null;\n }\n }\n\n showContent();\n state.sortMode = getDefaultSortMode();\n requestAnimationFrame(function () {\n fitCanvas();\n state.zoom = 1;\n state.panX = 0;\n state.panY = 0;\n render();\n renderControlPanel();\n });\n };\n img.src = data.image;\n }\n\n // \u2500\u2500 Display States: placeholder / loading / content \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function showPlaceholder() {\n state.image = null;\n state.annotations = [];\n state.visibility = [];\n state.selectedIndex = -1;\n canvasWrapper.style.display = \"none\";\n loadingIndicator.classList.remove(\"visible\");\n controlPanel.classList.remove(\"visible\");\n tooltip.classList.remove(\"visible\");\n placeholder.classList.remove(\"hidden\");\n }\n\n function showLoading() {\n placeholder.classList.add(\"hidden\");\n canvasWrapper.style.display = \"none\";\n controlPanel.classList.remove(\"visible\");\n loadingIndicator.classList.add(\"visible\");\n }\n\n function showContent() {\n placeholder.classList.add(\"hidden\");\n loadingIndicator.classList.remove(\"visible\");\n canvasWrapper.style.display = \"flex\";\n }\n\n // \u2500\u2500 Canvas Sizing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function fitCanvas() {\n if (!state.image) return;\n\n var img = state.image;\n\n if (state.maximized) {\n var wrapperW = canvasWrapper.clientWidth || window.innerWidth;\n var wrapperH = canvasWrapper.clientHeight || window.innerHeight;\n\n var w = wrapperW;\n var h = img.naturalHeight * (w / img.naturalWidth);\n\n if (h > wrapperH) {\n h = wrapperH;\n w = img.naturalWidth * (h / img.naturalHeight);\n }\n\n canvas.width = Math.round(w);\n canvas.height = Math.round(h);\n } else {\n var maxWidth = canvasWrapper.clientWidth || 800;\n\n var w = maxWidth;\n var h = img.naturalHeight * (w / img.naturalWidth);\n\n if (h > MAX_CANVAS_HEIGHT) {\n h = MAX_CANVAS_HEIGHT;\n w = img.naturalWidth * (h / img.naturalHeight);\n }\n\n canvas.width = Math.round(w);\n canvas.height = Math.round(h);\n }\n state.scale = canvas.width / img.naturalWidth;\n }\n\n // \u2500\u2500 Zoom/Pan Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function clientToCanvas(clientX, clientY) {\n var rect = canvas.getBoundingClientRect();\n var cssX = (clientX - rect.left) * (canvas.width / rect.width);\n var cssY = (clientY - rect.top) * (canvas.height / rect.height);\n return {\n x: (cssX - state.panX) / state.zoom,\n y: (cssY - state.panY) / state.zoom\n };\n }\n\n function clampPan() {\n if (state.zoom <= 1) {\n state.panX = 0;\n state.panY = 0;\n return;\n }\n var maxPanX = 0;\n var minPanX = canvas.width - canvas.width * state.zoom;\n var maxPanY = 0;\n var minPanY = canvas.height - canvas.height * state.zoom;\n if (state.panX > maxPanX) state.panX = maxPanX;\n if (state.panX < minPanX) state.panX = minPanX;\n if (state.panY > maxPanY) state.panY = maxPanY;\n if (state.panY < minPanY) state.panY = minPanY;\n }\n\n function zoomToCenter(newZoom) {\n newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, newZoom));\n var cx = canvas.width / 2;\n var cy = canvas.height / 2;\n state.panX = cx - (cx - state.panX) * (newZoom / state.zoom);\n state.panY = cy - (cy - state.panY) * (newZoom / state.zoom);\n state.zoom = newZoom;\n clampPan();\n render();\n }\n\n function resetZoom() {\n state.zoom = 1;\n state.panX = 0;\n state.panY = 0;\n render();\n }\n\n function resetToDefaults() {\n if (!state.image) return;\n\n state.showImage = true;\n toggleImageBtn.classList.add(\"active\");\n\n state.layers.masks = true;\n state.layers.boxes = true;\n state.layers.skeleton = true;\n state.layers.keypoints = true;\n\n state.thresholdMin = initialScoreThresholdMin;\n state.thresholdMax = initialScoreThresholdMax;\n state.keypointThreshold = initialKeypointThreshold;\n state.keypointRadius = initialKeypointRadius;\n state.connectionWidth = CONNECTION_WIDTH;\n state.maskAlpha = MASK_ALPHA;\n state.connectionAlpha = CONNECTION_ALPHA;\n state.bboxLineWidth = BBOX_LINE_WIDTH;\n\n for (var label in state.labelVisibility) {\n if (state.labelVisibility.hasOwnProperty(label)) {\n state.labelVisibility[label] = true;\n }\n }\n for (var i = 0; i < state.visibility.length; i++) {\n state.visibility[i] = true;\n }\n\n state.selectedIndex = -1;\n state.expandedIndex = -1;\n state.sortMode = getDefaultSortMode();\n state.zoom = 1;\n state.panX = 0;\n state.panY = 0;\n canvas.style.cursor = \"default\";\n\n render();\n renderControlPanel();\n }\n\n // \u2500\u2500 Rendering \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function isAnnotationVisible(i) {\n if (!state.visibility[i]) return false;\n var ann = state.annotations[i];\n if (ann.score != null && (ann.score < state.thresholdMin || ann.score > state.thresholdMax)) return false;\n if (ann.label && state.labelVisibility.hasOwnProperty(ann.label) && !state.labelVisibility[ann.label]) return false;\n return true;\n }\n\n function isKeypointVisible(kp) {\n if (kp.x == null || kp.y == null) return false;\n if (kp.confidence != null && kp.confidence < state.keypointThreshold) return false;\n return true;\n }\n\n function render() {\n if (!state.image) return;\n\n // Clear in screen space\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n // Dark background visible when zoomed/panned\n if (state.zoom > 1) {\n ctx.fillStyle = \"#1a1a1a\";\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n }\n\n // Apply zoom+pan transform\n ctx.setTransform(state.zoom, 0, 0, state.zoom, state.panX, state.panY);\n\n if (state.showImage) {\n ctx.drawImage(state.image, 0, 0, canvas.width, canvas.height);\n } else {\n ctx.fillStyle = \"#2a2a2a\";\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n }\n\n var hasSelection = state.selectedIndex >= 0;\n\n // Draw order: masks (back) \u2192 bbox \u2192 connections \u2192 keypoints (front)\n for (var pass = 0; pass < 4; pass++) {\n for (var i = 0; i < state.annotations.length; i++) {\n if (!isAnnotationVisible(i)) continue;\n\n var ann = state.annotations[i];\n var dim = hasSelection && i !== state.selectedIndex;\n\n ctx.save();\n if (dim) ctx.globalAlpha = DIM_ALPHA;\n\n if (pass === 0 && state.layers.masks) drawMask(i);\n else if (pass === 1 && state.layers.boxes) drawBbox(ann);\n else if (pass === 2 && state.layers.skeleton) drawConnections(ann);\n else if (pass === 3 && state.layers.keypoints) drawKeypoints(ann);\n\n ctx.restore();\n }\n }\n\n // Draw zoom indicator in screen space\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n if (state.zoom > 1) {\n var zoomText = Math.round(state.zoom * 100) + \"%\";\n ctx.font = \"bold 12px -apple-system, BlinkMacSystemFont, sans-serif\";\n var tm = ctx.measureText(zoomText);\n var px = canvas.width - tm.width - 12;\n var py = 8;\n ctx.fillStyle = \"rgba(0,0,0,0.5)\";\n ctx.beginPath();\n ctx.roundRect(px - 6, py - 2, tm.width + 12, 20, 4);\n ctx.fill();\n ctx.fillStyle = \"#fff\";\n ctx.textBaseline = \"top\";\n ctx.fillText(zoomText, px, py + 2);\n }\n }\n\n function drawMask(i) {\n var maskImg = state.maskImages[i];\n if (!maskImg) return;\n var baseAlpha = ctx.globalAlpha;\n ctx.globalAlpha = baseAlpha * state.maskAlpha;\n ctx.drawImage(maskImg, 0, 0, canvas.width, canvas.height);\n ctx.globalAlpha = baseAlpha;\n }\n\n function drawBbox(ann) {\n var bbox = ann.bbox;\n if (!bbox) return;\n\n var x = bbox.x * state.scale;\n var y = bbox.y * state.scale;\n var w = bbox.width * state.scale;\n var h = bbox.height * state.scale;\n var baseAlpha = ctx.globalAlpha;\n var iz = 1 / state.zoom;\n\n ctx.strokeStyle = ann.color;\n ctx.lineWidth = state.bboxLineWidth * iz;\n ctx.strokeRect(x, y, w, h);\n\n // Label + score text\n var labelText = ann.label || \"\";\n if (ann.score != null) {\n labelText += (labelText ? \" \" : \"\") + (ann.score * 100).toFixed(1) + \"%\";\n }\n if (labelText) {\n var fontSize = 11 * iz;\n ctx.font = \"bold \" + fontSize + \"px -apple-system, BlinkMacSystemFont, sans-serif\";\n var textMetrics = ctx.measureText(labelText);\n var textH = 16 * iz;\n var pad = 4 * iz;\n var bgW = textMetrics.width + pad * 2;\n var bgH = textH + pad;\n\n // Place label above bbox; if clipped, place inside top edge\n var labelAbove = y - bgH >= 0;\n var bgY = labelAbove ? y - bgH : y;\n var textY = labelAbove ? y - pad / 2 : y + bgH - pad / 2;\n\n // Semi-transparent background\n ctx.fillStyle = ann.color;\n ctx.globalAlpha = baseAlpha * 0.7;\n ctx.fillRect(x, bgY, bgW, bgH);\n\n // White text\n ctx.globalAlpha = baseAlpha;\n ctx.fillStyle = \"#ffffff\";\n ctx.textBaseline = \"bottom\";\n ctx.fillText(labelText, x + pad, textY);\n }\n }\n\n function drawConnections(ann) {\n var kps = ann.keypoints;\n var conns = ann.connections;\n if (!conns || conns.length === 0 || !kps || kps.length === 0) return;\n\n var baseAlpha = ctx.globalAlpha;\n ctx.strokeStyle = ann.color;\n ctx.lineWidth = state.connectionWidth / state.zoom;\n ctx.globalAlpha = baseAlpha * state.connectionAlpha;\n\n for (var i = 0; i < conns.length; i++) {\n var idxA = conns[i][0];\n var idxB = conns[i][1];\n if (idxA < 0 || idxA >= kps.length || idxB < 0 || idxB >= kps.length) continue;\n\n var a = kps[idxA];\n var b = kps[idxB];\n\n if (!isKeypointVisible(a) || !isKeypointVisible(b)) continue;\n\n ctx.beginPath();\n ctx.moveTo(a.x * state.scale, a.y * state.scale);\n ctx.lineTo(b.x * state.scale, b.y * state.scale);\n ctx.stroke();\n }\n\n ctx.globalAlpha = baseAlpha;\n }\n\n function drawKeypoints(ann) {\n var kps = ann.keypoints;\n if (!kps || kps.length === 0) return;\n\n var iz = 1 / state.zoom;\n for (var i = 0; i < kps.length; i++) {\n var kp = kps[i];\n if (!isKeypointVisible(kp)) continue;\n\n var cx = kp.x * state.scale;\n var cy = kp.y * state.scale;\n\n // White border\n ctx.beginPath();\n ctx.arc(cx, cy, (state.keypointRadius + 1) * iz, 0, 2 * Math.PI);\n ctx.fillStyle = \"#ffffff\";\n ctx.fill();\n\n // Colored fill\n ctx.beginPath();\n ctx.arc(cx, cy, state.keypointRadius * iz, 0, 2 * Math.PI);\n ctx.fillStyle = ann.color;\n ctx.fill();\n }\n }\n\n // \u2500\u2500 RLE Decode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function createMaskCanvas(rle, colorHex) {\n var counts = rle.counts;\n var h = rle.size[0], w = rle.size[1];\n var r = parseInt(colorHex.slice(1, 3), 16);\n var g = parseInt(colorHex.slice(3, 5), 16);\n var b = parseInt(colorHex.slice(5, 7), 16);\n var offscreen = document.createElement(\"canvas\");\n offscreen.width = w;\n offscreen.height = h;\n var offCtx = offscreen.getContext(\"2d\");\n var imageData = offCtx.createImageData(w, h);\n var data = imageData.data;\n // RLE is column-major (COCO format), convert to row-major ImageData\n var pos = 0;\n for (var i = 0; i < counts.length; i++) {\n var c = counts[i];\n if (i % 2 === 1) {\n var end = pos + c;\n for (var j = pos; j < end; j++) {\n var row = j % h;\n var col = (j / h) | 0;\n var idx = (row * w + col) * 4;\n data[idx] = r;\n data[idx + 1] = g;\n data[idx + 2] = b;\n data[idx + 3] = 255;\n }\n }\n pos += c;\n }\n offCtx.putImageData(imageData, 0, 0);\n return offscreen;\n }\n\n // \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function buildAnnotationSummary(ann) {\n var parts = [];\n if (ann.mask) {\n parts.push(\"mask\");\n }\n if (ann.bbox) {\n parts.push(\"bbox\");\n }\n var kps = ann.keypoints || [];\n if (kps.length > 0) {\n var validCount = 0;\n for (var j = 0; j < kps.length; j++) {\n if (isKeypointVisible(kps[j])) validCount++;\n }\n parts.push(validCount + \" pts\");\n }\n if (ann.score != null) {\n parts.push((ann.score * 100).toFixed(1) + \"%\");\n }\n return parts.join(\", \") || \"empty\";\n }\n\n function escapeHtml(text) {\n var div = document.createElement(\"div\");\n div.textContent = text;\n return div.innerHTML;\n }\n\n function getLabelColor(label) {\n // Return the color of the first annotation with this label\n for (var i = 0; i < state.annotations.length; i++) {\n if (state.annotations[i].label === label) {\n return state.annotations[i].color;\n }\n }\n return \"#888\";\n }\n\n function getDefaultSortMode() {\n var hasScores = false;\n var hasBboxes = false;\n for (var i = 0; i < state.annotations.length; i++) {\n if (state.annotations[i].score != null) hasScores = true;\n if (state.annotations[i].bbox) hasBboxes = true;\n if (hasScores && hasBboxes) break;\n }\n if (hasScores) return \"score-desc\";\n if (hasBboxes) return \"size-desc\";\n return \"none\";\n }\n\n function bboxArea(ann) {\n if (!ann.bbox) return null;\n return ann.bbox.width * ann.bbox.height;\n }\n\n function computeSortedIndices() {\n var n = state.annotations.length;\n var indices = [];\n for (var i = 0; i < n; i++) indices.push(i);\n\n var mode = state.sortMode;\n if (mode === \"score-desc\" || mode === \"score-asc\") {\n var dir = mode === \"score-desc\" ? -1 : 1;\n indices.sort(function (a, b) {\n var sa = state.annotations[a].score;\n var sb = state.annotations[b].score;\n var hasA = sa != null;\n var hasB = sb != null;\n if (hasA && hasB) return (sa - sb) * dir || a - b;\n if (hasA) return -1;\n if (hasB) return 1;\n return a - b;\n });\n } else if (mode === \"size-desc\" || mode === \"size-asc\") {\n var dir = mode === \"size-desc\" ? -1 : 1;\n indices.sort(function (a, b) {\n var aa = bboxArea(state.annotations[a]);\n var ab = bboxArea(state.annotations[b]);\n var hasA = aa != null;\n var hasB = ab != null;\n if (hasA && hasB) return (aa - ab) * dir || a - b;\n if (hasA) return -1;\n if (hasB) return 1;\n return a - b;\n });\n }\n\n // Stable partition: visible first, hidden last (only when some label filter is OFF)\n var anyLabelFiltered = false;\n var labels = Object.keys(state.labelVisibility);\n for (var li = 0; li < labels.length; li++) {\n if (!state.labelVisibility[labels[li]]) { anyLabelFiltered = true; break; }\n }\n if (anyLabelFiltered) {\n var visible = [];\n var hidden = [];\n for (var j = 0; j < indices.length; j++) {\n var idx = indices[j];\n var ann = state.annotations[idx];\n var labelHidden = ann.label && state.labelVisibility.hasOwnProperty(ann.label) && !state.labelVisibility[ann.label];\n if (labelHidden) hidden.push(idx);\n else visible.push(idx);\n }\n indices = visible.concat(hidden);\n }\n\n state.sortedIndices = indices;\n }\n\n function handleSortToggle(e) {\n var key = e.currentTarget.getAttribute(\"data-sort-key\");\n if (!key) return;\n // Toggle direction if same key is already active\n if (state.sortMode === key + \"-desc\") {\n state.sortMode = key + \"-asc\";\n } else if (state.sortMode === key + \"-asc\") {\n state.sortMode = key + \"-desc\";\n } else {\n state.sortMode = key + \"-desc\";\n }\n computeSortedIndices();\n renderControlPanel();\n }\n\n function updateHeaderStats() {\n if (!countEl) return;\n\n var total = state.annotations.length;\n var visibleCount = 0;\n var minScore = Infinity;\n var maxScore = -Infinity;\n var hasScores = false;\n\n for (var i = 0; i < state.annotations.length; i++) {\n if (!isAnnotationVisible(i)) continue;\n visibleCount++;\n var ann = state.annotations[i];\n if (ann.score != null) {\n hasScores = true;\n if (ann.score < minScore) minScore = ann.score;\n if (ann.score > maxScore) maxScore = ann.score;\n }\n }\n\n var text = visibleCount + \" / \" + total;\n if (hasScores && visibleCount > 0) {\n text += \" \\u00B7 \" + (minScore * 100).toFixed(0) + \"\\u2013\" + (maxScore * 100).toFixed(0) + \"%\";\n }\n countEl.textContent = text;\n }\n\n // \u2500\u2500 Control Panel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function renderControlPanel() {\n if (state.annotations.length === 0) {\n controlPanel.classList.remove(\"visible\");\n annotationList.innerHTML = \"\";\n return;\n }\n\n computeSortedIndices();\n\n var html = \"\";\n\n // Detect which layer types are present in annotations\n var availableLayers = [];\n var hasMasks = false, hasBoxes = false, hasSkeleton = false, hasKeypoints = false;\n for (var i = 0; i < state.annotations.length; i++) {\n var ann = state.annotations[i];\n if (ann.mask) hasMasks = true;\n if (ann.bbox) hasBoxes = true;\n if (ann.connections && ann.connections.length > 0) hasSkeleton = true;\n if (ann.keypoints && ann.keypoints.length > 0) hasKeypoints = true;\n }\n if (hasMasks) availableLayers.push(\"masks\");\n if (hasBoxes) availableLayers.push(\"boxes\");\n if (hasSkeleton) availableLayers.push(\"skeleton\");\n if (hasKeypoints) availableLayers.push(\"keypoints\");\n\n var layerLabels = { masks: \"Masks\", boxes: \"Boxes\", skeleton: \"Skeleton\", keypoints: \"Keypoints\" };\n\n // Only show layer toggles when 2+ types are present\n if (availableLayers.length >= 2) {\n html += '<div class=\"layer-toggles\">';\n for (var i = 0; i < availableLayers.length; i++) {\n var layer = availableLayers[i];\n html += '<button class=\"layer-btn' + (state.layers[layer] ? ' active' : '') + '\" data-layer=\"' + layer + '\">' + layerLabels[layer] + '</button>';\n }\n html += '</div>';\n }\n\n // Label filters with counts\n var labels = Object.keys(state.labelVisibility);\n if (labels.length > 0) {\n var labelTotalCounts = {};\n for (var i = 0; i < state.annotations.length; i++) {\n var lbl = state.annotations[i].label;\n if (lbl) labelTotalCounts[lbl] = (labelTotalCounts[lbl] || 0) + 1;\n }\n html += '<div class=\"label-filters\">';\n html += '<span class=\"label-filters-title\">Labels</span>';\n for (var li = 0; li < labels.length; li++) {\n var lbl = labels[li];\n var lblActive = state.labelVisibility[lbl];\n var lblColor = getLabelColor(lbl);\n html += '<button class=\"label-filter-btn' + (lblActive ? ' active' : '') + '\" data-label=\"' + escapeHtml(lbl) + '\">';\n html += '<span class=\"label-color-dot\" style=\"background:' + lblColor + '\"></span>';\n html += escapeHtml(lbl) + ' <span class=\"label-count\">' + (labelTotalCounts[lbl] || 0) + '</span>';\n html += '</button>';\n }\n html += '</div>';\n }\n\n // Sort controls\n var hasScoresForSort = false;\n var hasBboxesForSort = false;\n for (var si = 0; si < state.annotations.length; si++) {\n if (state.annotations[si].score != null) hasScoresForSort = true;\n if (state.annotations[si].bbox) hasBboxesForSort = true;\n }\n if (hasScoresForSort || hasBboxesForSort) {\n var sortButtons = [];\n if (hasScoresForSort) sortButtons.push(\"score\");\n if (hasBboxesForSort) sortButtons.push(\"size\");\n // Only show controls when 2+ sort options exist\n if (sortButtons.length >= 2) {\n var sortLabels = { score: \"Score\", size: \"Size\" };\n html += '<div class=\"sort-controls\">';\n html += '<span class=\"sort-controls-title\">Sort</span>';\n for (var sbi = 0; sbi < sortButtons.length; sbi++) {\n var sk = sortButtons[sbi];\n var isDesc = state.sortMode === sk + \"-desc\";\n var isAsc = state.sortMode === sk + \"-asc\";\n var isActive = isDesc || isAsc;\n var arrow = isActive ? (isDesc ? \" \\u25BC\" : \" \\u25B2\") : \"\";\n html += '<button class=\"sort-btn' + (isActive ? ' active' : '') + '\" data-sort-key=\"' + sk + '\">' + sortLabels[sk] + arrow + '</button>';\n }\n html += '</div>';\n }\n }\n\n // Dual-thumb score threshold slider\n html += '<div class=\"threshold-row\">';\n html += '<span>Score</span>';\n html += '<div class=\"dual-range-wrapper\">';\n html += '<input type=\"range\" class=\"threshold-slider-min\" min=\"0\" max=\"100\" value=\"' + Math.round(state.thresholdMin * 100) + '\">';\n html += '<input type=\"range\" class=\"threshold-slider-max\" min=\"0\" max=\"100\" value=\"' + Math.round(state.thresholdMax * 100) + '\">';\n html += '</div>';\n html += '<span class=\"threshold-value\">' + Math.round(state.thresholdMin * 100) + '%\\u2013' + Math.round(state.thresholdMax * 100) + '%</span>';\n html += '</div>';\n\n // Keypoint threshold slider (only when annotations have keypoints)\n if (hasKeypoints) {\n html += '<div class=\"threshold-row\">';\n html += '<span>Keypoint ≥</span>';\n html += '<input type=\"range\" class=\"keypoint-threshold-slider\" min=\"0\" max=\"100\" value=\"' + Math.round(state.keypointThreshold * 100) + '\">';\n html += '<span class=\"keypoint-threshold-value\">' + Math.round(state.keypointThreshold * 100) + '%</span>';\n html += '</div>';\n }\n\n // Collapsible draw options section\n var drawOptionsHtml = '';\n if (hasMasks) {\n drawOptionsHtml += '<div class=\"threshold-row\">';\n drawOptionsHtml += '<span>Mask Opacity</span>';\n drawOptionsHtml += '<input type=\"range\" class=\"mask-alpha-slider\" min=\"0\" max=\"100\" step=\"5\" value=\"' + Math.round(state.maskAlpha * 100) + '\">';\n drawOptionsHtml += '<span class=\"slider-value mask-alpha-value\">' + Math.round(state.maskAlpha * 100) + '%</span>';\n drawOptionsHtml += '</div>';\n }\n if (hasKeypoints) {\n drawOptionsHtml += '<div class=\"threshold-row\">';\n drawOptionsHtml += '<span>Keypoint Size</span>';\n drawOptionsHtml += '<input type=\"range\" class=\"keypoint-radius-slider\" min=\"1\" max=\"20\" step=\"1\" value=\"' + state.keypointRadius + '\">';\n drawOptionsHtml += '<span class=\"slider-value keypoint-radius-value\">' + state.keypointRadius + '</span>';\n drawOptionsHtml += '</div>';\n }\n if (hasSkeleton) {\n drawOptionsHtml += '<div class=\"threshold-row\">';\n drawOptionsHtml += '<span>Line Width</span>';\n drawOptionsHtml += '<input type=\"range\" class=\"connection-width-slider\" min=\"1\" max=\"10\" step=\"1\" value=\"' + state.connectionWidth + '\">';\n drawOptionsHtml += '<span class=\"slider-value connection-width-value\">' + state.connectionWidth + '</span>';\n drawOptionsHtml += '</div>';\n drawOptionsHtml += '<div class=\"threshold-row\">';\n drawOptionsHtml += '<span>Line Opacity</span>';\n drawOptionsHtml += '<input type=\"range\" class=\"connection-alpha-slider\" min=\"0\" max=\"100\" step=\"5\" value=\"' + Math.round(state.connectionAlpha * 100) + '\">';\n drawOptionsHtml += '<span class=\"slider-value connection-alpha-value\">' + Math.round(state.connectionAlpha * 100) + '%</span>';\n drawOptionsHtml += '</div>';\n }\n if (hasBoxes) {\n drawOptionsHtml += '<div class=\"threshold-row\">';\n drawOptionsHtml += '<span>Box Width</span>';\n drawOptionsHtml += '<input type=\"range\" class=\"bbox-line-width-slider\" min=\"1\" max=\"10\" step=\"1\" value=\"' + state.bboxLineWidth + '\">';\n drawOptionsHtml += '<span class=\"slider-value bbox-line-width-value\">' + state.bboxLineWidth + '</span>';\n drawOptionsHtml += '</div>';\n }\n if (drawOptionsHtml) {\n html += '<div class=\"draw-options' + (state.drawOptionsOpen ? ' open' : '') + '\">';\n html += '<button class=\"draw-options-toggle\">Draw Options <span class=\"draw-options-arrow\">▶</span></button>';\n html += '<div class=\"draw-options-body\">' + drawOptionsHtml + '</div>';\n html += '</div>';\n }\n\n // Select-all row + scrollable annotation rows container\n html += '<div class=\"annotation-rows\">';\n\n var allChecked = true;\n var anyChecked = false;\n for (var i = 0; i < state.visibility.length; i++) {\n if (state.visibility[i]) anyChecked = true;\n else allChecked = false;\n }\n html += '<div class=\"select-all-row\">';\n html += '<input type=\"checkbox\" class=\"select-all-checkbox\"' + (anyChecked ? ' checked' : '') + '>';\n html += '<span class=\"select-all-label\">All</span>';\n html += '</div>';\n\n // Annotation rows (iterate in sorted/grouped order)\n var anyLabelFiltered = false;\n var labelKeys = Object.keys(state.labelVisibility);\n for (var li = 0; li < labelKeys.length; li++) {\n if (!state.labelVisibility[labelKeys[li]]) { anyLabelFiltered = true; break; }\n }\n var separatorInserted = false;\n\n for (var si = 0; si < state.sortedIndices.length; si++) {\n var i = state.sortedIndices[si];\n var ann = state.annotations[i];\n var visible = state.visibility[i];\n var selected = state.selectedIndex === i;\n var summary = buildAnnotationSummary(ann);\n var outsideRange = ann.score != null && (ann.score < state.thresholdMin || ann.score > state.thresholdMax);\n var labelHidden = ann.label && state.labelVisibility.hasOwnProperty(ann.label) && !state.labelVisibility[ann.label];\n\n // Insert separator before the first label-hidden item\n if (anyLabelFiltered && labelHidden && !separatorInserted) {\n html += '<div class=\"annotation-group-separator\"><span>Hidden</span></div>';\n separatorInserted = true;\n }\n\n var expanded = state.expandedIndex === i;\n\n html += '<div class=\"annotation-row' + (selected ? ' selected' : '') + (outsideRange ? ' below-threshold' : '') + (labelHidden ? ' filtered-out' : '') + '\" data-index=\"' + i + '\">';\n html += '<span class=\"ann-dot\" style=\"background:' + ann.color + '\"></span>';\n html += '<input type=\"checkbox\" class=\"ann-checkbox\" data-index=\"' + i + '\"' + (visible ? ' checked' : '') + '>';\n html += '<span class=\"ann-label\">' + escapeHtml(ann.label) + '</span>';\n html += '<span class=\"ann-summary\">' + escapeHtml(summary) + '</span>';\n html += '<button class=\"ann-expand' + (expanded ? ' expanded' : '') + '\" data-index=\"' + i + '\">▶</button>';\n html += '</div>';\n\n // Detail panel (shown when expand button is clicked)\n html += '<div class=\"annotation-detail' + (expanded ? ' visible' : '') + '\" data-index=\"' + i + '\">';\n html += buildDetailHtml(ann);\n html += '</div>';\n }\n\n html += '</div>'; // close .annotation-rows\n\n annotationList.innerHTML = html;\n controlPanel.classList.add(\"visible\");\n updateHeaderStats();\n\n // Initialize dual-range track highlight\n var dualWrapper = annotationList.querySelector(\".dual-range-wrapper\");\n if (dualWrapper) updateDualRangeTrack(dualWrapper);\n\n // Bind layer toggle events\n var layerBtns = annotationList.querySelectorAll(\".layer-btn\");\n for (var i = 0; i < layerBtns.length; i++) {\n layerBtns[i].addEventListener(\"click\", handleLayerToggle);\n }\n\n // Bind label filter events (single-click: toggle, double-click: solo)\n var labelBtns = annotationList.querySelectorAll(\".label-filter-btn\");\n for (var i = 0; i < labelBtns.length; i++) {\n labelBtns[i].addEventListener(\"click\", handleLabelFilterClick);\n labelBtns[i].addEventListener(\"dblclick\", handleLabelFilterDblClick);\n }\n\n // Bind sort button events\n var sortBtns = annotationList.querySelectorAll(\".sort-btn\");\n for (var i = 0; i < sortBtns.length; i++) {\n sortBtns[i].addEventListener(\"click\", handleSortToggle);\n }\n\n // Bind dual threshold sliders\n var sliderMin = annotationList.querySelector(\".threshold-slider-min\");\n var sliderMax = annotationList.querySelector(\".threshold-slider-max\");\n if (sliderMin) sliderMin.addEventListener(\"input\", handleThresholdMinChange);\n if (sliderMax) sliderMax.addEventListener(\"input\", handleThresholdMaxChange);\n\n // Bind keypoint threshold slider\n var kpSlider = annotationList.querySelector(\".keypoint-threshold-slider\");\n if (kpSlider) {\n kpSlider.addEventListener(\"input\", handleKeypointThresholdChange);\n }\n\n // Bind draw options toggle\n var drawToggle = annotationList.querySelector(\".draw-options-toggle\");\n if (drawToggle) {\n drawToggle.addEventListener(\"click\", function () {\n var section = drawToggle.closest(\".draw-options\");\n section.classList.toggle(\"open\");\n state.drawOptionsOpen = section.classList.contains(\"open\");\n });\n }\n\n // Bind visual parameter sliders\n var maSlider = annotationList.querySelector(\".mask-alpha-slider\");\n if (maSlider) {\n maSlider.addEventListener(\"input\", handleMaskAlphaChange);\n }\n var krSlider = annotationList.querySelector(\".keypoint-radius-slider\");\n if (krSlider) {\n krSlider.addEventListener(\"input\", handleKeypointRadiusChange);\n }\n var cwSlider = annotationList.querySelector(\".connection-width-slider\");\n if (cwSlider) {\n cwSlider.addEventListener(\"input\", handleConnectionWidthChange);\n }\n var caSlider = annotationList.querySelector(\".connection-alpha-slider\");\n if (caSlider) {\n caSlider.addEventListener(\"input\", handleConnectionAlphaChange);\n }\n var blwSlider = annotationList.querySelector(\".bbox-line-width-slider\");\n if (blwSlider) {\n blwSlider.addEventListener(\"input\", handleBboxLineWidthChange);\n }\n\n // Initialize single slider track fills\n var singleSliders = annotationList.querySelectorAll('.threshold-row input[type=\"range\"]:not(.threshold-slider-min):not(.threshold-slider-max)');\n for (var i = 0; i < singleSliders.length; i++) {\n updateSliderTrack(singleSliders[i]);\n }\n\n // Bind select-all checkbox\n var selectAllCb = annotationList.querySelector(\".select-all-checkbox\");\n if (selectAllCb) {\n // Set indeterminate state: some checked but not all\n if (anyChecked && !allChecked) {\n selectAllCb.indeterminate = true;\n }\n selectAllCb.addEventListener(\"change\", function (e) {\n var newVal = e.target.checked;\n for (var i = 0; i < state.visibility.length; i++) {\n state.visibility[i] = newVal;\n }\n render();\n renderControlPanel();\n });\n }\n\n // Bind checkbox events\n var checkboxes = annotationList.querySelectorAll(\".ann-checkbox\");\n for (var i = 0; i < checkboxes.length; i++) {\n checkboxes[i].addEventListener(\"change\", handleCheckboxChange);\n checkboxes[i].addEventListener(\"click\", function (e) { e.stopPropagation(); });\n }\n\n // Bind expand button events\n var expandBtns = annotationList.querySelectorAll(\".ann-expand\");\n for (var i = 0; i < expandBtns.length; i++) {\n expandBtns[i].addEventListener(\"click\", handleExpandClick);\n }\n\n // Bind row click events\n var rows = annotationList.querySelectorAll(\".annotation-row\");\n for (var i = 0; i < rows.length; i++) {\n rows[i].addEventListener(\"click\", handleRowClick);\n }\n }\n\n function buildDetailHtml(ann) {\n var html = \"\";\n if (ann.bbox) {\n html += '<div class=\"detail-section-title\">Bounding Box</div>';\n html += '<table>';\n html += '<tr><td>Position:</td><td>' + ann.bbox.x.toFixed(1) + ', ' + ann.bbox.y.toFixed(1) + '</td></tr>';\n html += '<tr><td>Size:</td><td>' + ann.bbox.width.toFixed(1) + ' × ' + ann.bbox.height.toFixed(1) + '</td></tr>';\n if (ann.score != null) {\n html += '<tr><td>Score:</td><td>' + (ann.score * 100).toFixed(1) + '%</td></tr>';\n }\n html += '</table>';\n }\n var kps = ann.keypoints || [];\n if (kps.length > 0) {\n html += '<div class=\"detail-section-title\">Keypoints</div>';\n html += '<table>';\n for (var j = 0; j < kps.length; j++) {\n var kp = kps[j];\n var name = kp.name || (\"kp\" + j);\n var coords = (kp.x != null && kp.y != null) ? kp.x.toFixed(1) + ', ' + kp.y.toFixed(1) : \"missing\";\n var conf = kp.confidence != null ? (kp.confidence * 100).toFixed(1) + '%' : \"\";\n html += '<tr><td>' + escapeHtml(name) + '</td><td>' + coords + '</td><td>' + conf + '</td></tr>';\n }\n html += '</table>';\n }\n return html || '<span>No details available</span>';\n }\n\n // \u2500\u2500 Event Handlers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function handleLayerToggle(e) {\n var layer = e.target.getAttribute(\"data-layer\");\n if (layer && state.layers.hasOwnProperty(layer)) {\n state.layers[layer] = !state.layers[layer];\n render();\n renderControlPanel();\n }\n }\n\n var labelClickTimer = null;\n\n function handleLabelFilterClick(e) {\n var label = e.currentTarget.getAttribute(\"data-label\");\n if (!label || !state.labelVisibility.hasOwnProperty(label)) return;\n if (labelClickTimer) clearTimeout(labelClickTimer);\n labelClickTimer = setTimeout(function () {\n labelClickTimer = null;\n var newVal = !state.labelVisibility[label];\n state.labelVisibility[label] = newVal;\n for (var i = 0; i < state.annotations.length; i++) {\n if (state.annotations[i].label === label) {\n state.visibility[i] = newVal;\n }\n }\n render();\n renderControlPanel();\n }, 200);\n }\n\n function handleLabelFilterDblClick(e) {\n e.preventDefault();\n if (labelClickTimer) {\n clearTimeout(labelClickTimer);\n labelClickTimer = null;\n }\n var label = e.currentTarget.getAttribute(\"data-label\");\n if (!label || !state.labelVisibility.hasOwnProperty(label)) return;\n\n // Check if this label is already solo (only this one is ON)\n var labels = Object.keys(state.labelVisibility);\n var onlyThisOn = labels.every(function (l) {\n return l === label ? state.labelVisibility[l] : !state.labelVisibility[l];\n });\n\n if (onlyThisOn) {\n // Unsolo: turn all labels ON\n for (var li = 0; li < labels.length; li++) {\n state.labelVisibility[labels[li]] = true;\n }\n for (var i = 0; i < state.annotations.length; i++) {\n state.visibility[i] = true;\n }\n } else {\n // Solo: turn only this label ON\n for (var li = 0; li < labels.length; li++) {\n state.labelVisibility[labels[li]] = (labels[li] === label);\n }\n for (var i = 0; i < state.annotations.length; i++) {\n state.visibility[i] = (state.annotations[i].label === label);\n }\n }\n render();\n renderControlPanel();\n }\n\n function updateThresholdUI() {\n render();\n var label = annotationList.querySelector(\".threshold-value\");\n if (label) label.textContent = Math.round(state.thresholdMin * 100) + '%\\u2013' + Math.round(state.thresholdMax * 100) + '%';\n // Update row opacity for outside-range items\n var rows = annotationList.querySelectorAll(\".annotation-row\");\n for (var i = 0; i < rows.length; i++) {\n var idx = parseInt(rows[i].getAttribute(\"data-index\"), 10);\n var ann = state.annotations[idx];\n var outsideRange = ann.score != null && (ann.score < state.thresholdMin || ann.score > state.thresholdMax);\n if (outsideRange) {\n rows[i].classList.add(\"below-threshold\");\n } else {\n rows[i].classList.remove(\"below-threshold\");\n }\n }\n // Update track highlight\n var wrapper = annotationList.querySelector(\".dual-range-wrapper\");\n if (wrapper) updateDualRangeTrack(wrapper);\n updateHeaderStats();\n }\n\n function handleThresholdMinChange(e) {\n var val = parseInt(e.target.value, 10) / 100;\n state.thresholdMin = Math.min(val, state.thresholdMax);\n e.target.value = Math.round(state.thresholdMin * 100);\n updateThresholdUI();\n }\n\n function handleThresholdMaxChange(e) {\n var val = parseInt(e.target.value, 10) / 100;\n state.thresholdMax = Math.max(val, state.thresholdMin);\n e.target.value = Math.round(state.thresholdMax * 100);\n updateThresholdUI();\n }\n\n function updateSliderTrack(slider) {\n var min = parseFloat(slider.min) || 0;\n var max = parseFloat(slider.max) || 100;\n var val = parseFloat(slider.value) || 0;\n var pct = ((val - min) / (max - min)) * 100;\n var t = 'calc(50% - 2px)';\n var b = 'calc(50% + 2px)';\n slider.style.background =\n 'linear-gradient(to bottom, transparent ' + t + ', var(--color-accent, #2196F3) ' + t + ', var(--color-accent, #2196F3) ' + b + ', transparent ' + b + ') 0 0 / ' + pct + '% 100% no-repeat, ' +\n 'linear-gradient(to bottom, transparent ' + t + ', var(--border-color-primary, #d0d0d0) ' + t + ', var(--border-color-primary, #d0d0d0) ' + b + ', transparent ' + b + ')';\n }\n\n function updateDualRangeTrack(wrapper) {\n var minVal = Math.round(state.thresholdMin * 100);\n var maxVal = Math.round(state.thresholdMax * 100);\n wrapper.style.background = 'linear-gradient(to right, var(--border-color-primary, #d0d0d0) ' + minVal + '%, var(--color-accent, #2196F3) ' + minVal + '%, var(--color-accent, #2196F3) ' + maxVal + '%, var(--border-color-primary, #d0d0d0) ' + maxVal + '%)';\n }\n\n function handleKeypointThresholdChange(e) {\n state.keypointThreshold = parseInt(e.target.value, 10) / 100;\n render();\n updateSliderTrack(e.target);\n // Update keypoint threshold label\n var label = annotationList.querySelector(\".keypoint-threshold-value\");\n if (label) label.textContent = Math.round(state.keypointThreshold * 100) + '%';\n updateHeaderStats();\n // Update annotation summaries\n var summaryEls = annotationList.querySelectorAll(\".ann-summary\");\n for (var i = 0; i < summaryEls.length; i++) {\n var row = summaryEls[i].closest(\".annotation-row\");\n if (row) {\n var idx = parseInt(row.getAttribute(\"data-index\"), 10);\n summaryEls[i].textContent = buildAnnotationSummary(state.annotations[idx]);\n }\n }\n }\n\n function handleKeypointRadiusChange(e) {\n state.keypointRadius = parseInt(e.target.value, 10);\n render();\n updateSliderTrack(e.target);\n var label = annotationList.querySelector(\".keypoint-radius-value\");\n if (label) label.textContent = state.keypointRadius;\n }\n\n function handleConnectionWidthChange(e) {\n state.connectionWidth = parseInt(e.target.value, 10);\n render();\n updateSliderTrack(e.target);\n var label = annotationList.querySelector(\".connection-width-value\");\n if (label) label.textContent = state.connectionWidth;\n }\n\n function handleMaskAlphaChange(e) {\n state.maskAlpha = parseInt(e.target.value, 10) / 100;\n render();\n updateSliderTrack(e.target);\n var label = annotationList.querySelector(\".mask-alpha-value\");\n if (label) label.textContent = Math.round(state.maskAlpha * 100) + '%';\n }\n\n function handleConnectionAlphaChange(e) {\n state.connectionAlpha = parseInt(e.target.value, 10) / 100;\n render();\n updateSliderTrack(e.target);\n var label = annotationList.querySelector(\".connection-alpha-value\");\n if (label) label.textContent = Math.round(state.connectionAlpha * 100) + '%';\n }\n\n function handleBboxLineWidthChange(e) {\n state.bboxLineWidth = parseInt(e.target.value, 10);\n render();\n updateSliderTrack(e.target);\n var label = annotationList.querySelector(\".bbox-line-width-value\");\n if (label) label.textContent = state.bboxLineWidth;\n }\n\n function handleExpandClick(e) {\n e.stopPropagation();\n var idx = parseInt(e.currentTarget.getAttribute(\"data-index\"), 10);\n if (state.expandedIndex === idx) {\n state.expandedIndex = -1;\n } else {\n state.expandedIndex = idx;\n }\n renderControlPanel();\n }\n\n function handleCheckboxChange(e) {\n var idx = parseInt(e.target.getAttribute(\"data-index\"), 10);\n state.visibility[idx] = e.target.checked;\n render();\n updateHeaderStats();\n }\n\n function handleRowClick(e) {\n var idx = parseInt(e.currentTarget.getAttribute(\"data-index\"), 10);\n if (state.selectedIndex === idx) {\n state.selectedIndex = -1;\n } else {\n state.selectedIndex = idx;\n }\n render();\n renderControlPanel();\n }\n\n // Toggle base image\n toggleImageBtn.addEventListener(\"click\", function () {\n state.showImage = !state.showImage;\n toggleImageBtn.classList.toggle(\"active\", state.showImage);\n render();\n });\n\n // Reset to defaults\n resetBtn.addEventListener(\"click\", resetToDefaults);\n\n // Maximize / minimize\n function toggleMaximize() {\n state.maximized = !state.maximized;\n container.classList.toggle(\"maximized\", state.maximized);\n\n if (state.maximized) {\n document.body.style.overflow = \"hidden\";\n } else {\n document.body.style.overflow = \"\";\n }\n\n if (state.image) {\n requestAnimationFrame(function () {\n fitCanvas();\n resetZoom();\n });\n }\n }\n\n maximizeBtn.addEventListener(\"click\", toggleMaximize);\n\n // Help dialog\n function toggleHelp() {\n helpOverlay.classList.toggle(\"visible\");\n }\n\n helpBtn.addEventListener(\"click\", toggleHelp);\n helpCloseBtn.addEventListener(\"click\", toggleHelp);\n helpOverlay.addEventListener(\"click\", function (e) {\n if (e.target === helpOverlay) toggleHelp();\n });\n\n // \u2500\u2500 Canvas Mouse Interaction (Pan + Selection) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n canvas.addEventListener(\"mousedown\", function (e) {\n if (e.button !== 0) return;\n if (!state.image) return;\n\n state.isPanning = true;\n state.didDrag = false;\n state.panStartX = e.clientX;\n state.panStartY = e.clientY;\n state.panStartPanX = state.panX;\n state.panStartPanY = state.panY;\n\n if (state.zoom > 1) {\n canvas.style.cursor = \"grabbing\";\n }\n });\n\n window.addEventListener(\"mousemove\", function (e) {\n if (!state.image) return;\n\n if (state.isPanning) {\n var dx = e.clientX - state.panStartX;\n var dy = e.clientY - state.panStartY;\n\n if (!state.didDrag && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)) {\n state.didDrag = true;\n }\n\n if (state.didDrag && state.zoom > 1) {\n var rect = canvas.getBoundingClientRect();\n var cssToCanvasX = canvas.width / rect.width;\n var cssToCanvasY = canvas.height / rect.height;\n state.panX = state.panStartPanX + dx * cssToCanvasX;\n state.panY = state.panStartPanY + dy * cssToCanvasY;\n clampPan();\n render();\n }\n return;\n }\n\n // Tooltip logic (only when not dragging)\n var rect = canvas.getBoundingClientRect();\n if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;\n if (state.annotations.length === 0) return;\n\n var pt = clientToCanvas(e.clientX, e.clientY);\n var cx = pt.x;\n var cy = pt.y;\n\n // Update cursor\n var hitIndex = findHitAnnotationIndex(cx, cy);\n if (state.zoom > 1) {\n canvas.style.cursor = hitIndex >= 0 ? \"pointer\" : \"grab\";\n } else {\n canvas.style.cursor = hitIndex >= 0 ? \"pointer\" : \"default\";\n }\n\n var nearest = findNearestKeypoint(cx, cy);\n var tooltipText = \"\";\n if (nearest) {\n tooltipText = nearest.kp.name;\n if (nearest.kp.confidence != null) {\n tooltipText += \" (\" + (nearest.kp.confidence * 100).toFixed(1) + \"%)\";\n }\n } else {\n var bboxHit = findBboxAt(cx, cy);\n if (bboxHit) {\n tooltipText = bboxHit.label || \"\";\n if (bboxHit.score != null) {\n tooltipText += (tooltipText ? \" \" : \"\") + (bboxHit.score * 100).toFixed(1) + \"%\";\n }\n }\n }\n\n if (tooltipText) {\n tooltip.textContent = tooltipText;\n tooltip.classList.add(\"visible\");\n\n var containerRect = container.getBoundingClientRect();\n var tooltipX = e.clientX - containerRect.left + 12;\n var tooltipY = e.clientY - containerRect.top - 8;\n tooltip.style.left = tooltipX + \"px\";\n tooltip.style.top = tooltipY + \"px\";\n } else {\n tooltip.classList.remove(\"visible\");\n }\n });\n\n window.addEventListener(\"mouseup\", function (e) {\n if (!state.isPanning) return;\n state.isPanning = false;\n\n if (state.zoom > 1) {\n canvas.style.cursor = \"grab\";\n }\n\n if (!state.didDrag && state.image && state.annotations.length > 0) {\n var pt = clientToCanvas(e.clientX, e.clientY);\n var hits = findAllHitAnnotationIndices(pt.x, pt.y);\n if (e.shiftKey && hits.length > 0) {\n // Shift+click: hide the topmost hit\n var target = hits[0];\n state.visibility[target] = false;\n if (state.selectedIndex === target) state.selectedIndex = -1;\n } else if (hits.length === 0) {\n state.selectedIndex = -1;\n } else if (hits.length === 1) {\n // Single hit: toggle as before\n state.selectedIndex = state.selectedIndex === hits[0] ? -1 : hits[0];\n } else {\n // Multiple overlapping hits: cycle through them\n var curPos = hits.indexOf(state.selectedIndex);\n if (curPos < 0) {\n state.selectedIndex = hits[0];\n } else {\n state.selectedIndex = hits[(curPos + 1) % hits.length];\n }\n }\n render();\n renderControlPanel();\n }\n });\n\n function findHitAnnotationIndex(cx, cy) {\n var hits = findAllHitAnnotationIndices(cx, cy);\n return hits.length > 0 ? hits[0] : -1;\n }\n\n function findAllHitAnnotationIndices(cx, cy) {\n var hitR = HIT_RADIUS / state.zoom;\n var hitR2 = hitR * hitR;\n var result = [];\n var keypointHitSet = {};\n // Check keypoints first (more precise)\n for (var i = 0; i < state.annotations.length; i++) {\n if (!isAnnotationVisible(i)) continue;\n var kps = state.annotations[i].keypoints || [];\n for (var j = 0; j < kps.length; j++) {\n var kp = kps[j];\n if (!isKeypointVisible(kp)) continue;\n var dx = cx - kp.x * state.scale;\n var dy = cy - kp.y * state.scale;\n if (dx * dx + dy * dy < hitR2) {\n result.push(i);\n keypointHitSet[i] = true;\n break;\n }\n }\n }\n // Then check bboxes (topmost first)\n for (var i = state.annotations.length - 1; i >= 0; i--) {\n if (keypointHitSet[i]) continue;\n if (!isAnnotationVisible(i)) continue;\n var bbox = state.annotations[i].bbox;\n if (!bbox) continue;\n var bx = bbox.x * state.scale;\n var by = bbox.y * state.scale;\n if (cx >= bx && cx <= bx + bbox.width * state.scale && cy >= by && cy <= by + bbox.height * state.scale) {\n result.push(i);\n }\n }\n return result;\n }\n\n // \u2500\u2500 Tooltip (mouseleave) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n canvas.addEventListener(\"mouseleave\", function () {\n tooltip.classList.remove(\"visible\");\n if (!state.isPanning) {\n canvas.style.cursor = state.zoom > 1 ? \"grab\" : \"default\";\n }\n });\n\n function findNearestKeypoint(cx, cy) {\n var best = null;\n var hitR = HIT_RADIUS / state.zoom;\n var bestDist = hitR * hitR;\n\n for (var i = 0; i < state.annotations.length; i++) {\n if (!isAnnotationVisible(i)) continue;\n var ann = state.annotations[i];\n var kps = ann.keypoints || [];\n for (var j = 0; j < kps.length; j++) {\n var kp = kps[j];\n if (!isKeypointVisible(kp)) continue;\n\n var kx = kp.x * state.scale;\n var ky = kp.y * state.scale;\n var dx = cx - kx;\n var dy = cy - ky;\n var dist = dx * dx + dy * dy;\n\n if (dist < bestDist) {\n bestDist = dist;\n best = { kp: kp, ann: ann };\n }\n }\n }\n return best;\n }\n\n function findBboxAt(cx, cy) {\n for (var i = state.annotations.length - 1; i >= 0; i--) {\n if (!isAnnotationVisible(i)) continue;\n var ann = state.annotations[i];\n var bbox = ann.bbox;\n if (!bbox) continue;\n\n var bx = bbox.x * state.scale;\n var by = bbox.y * state.scale;\n var bw = bbox.width * state.scale;\n var bh = bbox.height * state.scale;\n\n if (cx >= bx && cx <= bx + bw && cy >= by && cy <= by + bh) {\n return ann;\n }\n }\n return null;\n }\n\n // \u2500\u2500 Wheel Zoom \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n canvas.addEventListener(\"wheel\", function (e) {\n if (!state.image) return;\n e.preventDefault();\n\n var delta = e.deltaY;\n if (e.deltaMode === 1) delta *= 16;\n else if (e.deltaMode === 2) delta *= 100;\n\n var newZoom = state.zoom * (1 - delta * ZOOM_SENSITIVITY);\n newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, newZoom));\n\n // Zoom toward cursor position\n var rect = canvas.getBoundingClientRect();\n var mx = (e.clientX - rect.left) * (canvas.width / rect.width);\n var my = (e.clientY - rect.top) * (canvas.height / rect.height);\n\n state.panX = mx - (mx - state.panX) * (newZoom / state.zoom);\n state.panY = my - (my - state.panY) * (newZoom / state.zoom);\n state.zoom = newZoom;\n clampPan();\n render();\n }, { passive: false });\n\n // \u2500\u2500 Double-click to Reset Zoom \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n canvas.addEventListener(\"dblclick\", function (e) {\n if (!state.image) return;\n e.preventDefault();\n resetZoom();\n canvas.style.cursor = \"default\";\n });\n\n // \u2500\u2500 Touch Support (Pinch-Zoom + Pan) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n var touchState = { lastDist: 0, lastCenterX: 0, lastCenterY: 0, touchCount: 0 };\n\n function getTouchDistance(t1, t2) {\n var dx = t1.clientX - t2.clientX;\n var dy = t1.clientY - t2.clientY;\n return Math.sqrt(dx * dx + dy * dy);\n }\n\n function getTouchCenter(t1, t2) {\n return { x: (t1.clientX + t2.clientX) / 2, y: (t1.clientY + t2.clientY) / 2 };\n }\n\n canvas.addEventListener(\"touchstart\", function (e) {\n if (!state.image) return;\n e.preventDefault();\n\n touchState.touchCount = e.touches.length;\n\n if (e.touches.length === 1) {\n state.isPanning = true;\n state.didDrag = false;\n state.panStartX = e.touches[0].clientX;\n state.panStartY = e.touches[0].clientY;\n state.panStartPanX = state.panX;\n state.panStartPanY = state.panY;\n } else if (e.touches.length === 2) {\n state.isPanning = false;\n touchState.lastDist = getTouchDistance(e.touches[0], e.touches[1]);\n var center = getTouchCenter(e.touches[0], e.touches[1]);\n touchState.lastCenterX = center.x;\n touchState.lastCenterY = center.y;\n }\n }, { passive: false });\n\n canvas.addEventListener(\"touchmove\", function (e) {\n if (!state.image) return;\n e.preventDefault();\n\n if (e.touches.length === 1 && state.isPanning) {\n var dx = e.touches[0].clientX - state.panStartX;\n var dy = e.touches[0].clientY - state.panStartY;\n\n if (!state.didDrag && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)) {\n state.didDrag = true;\n }\n\n if (state.didDrag && state.zoom > 1) {\n var rect = canvas.getBoundingClientRect();\n state.panX = state.panStartPanX + dx * (canvas.width / rect.width);\n state.panY = state.panStartPanY + dy * (canvas.height / rect.height);\n clampPan();\n render();\n }\n } else if (e.touches.length === 2) {\n var dist = getTouchDistance(e.touches[0], e.touches[1]);\n var center = getTouchCenter(e.touches[0], e.touches[1]);\n\n if (touchState.lastDist > 0) {\n var scale = dist / touchState.lastDist;\n var newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, state.zoom * scale));\n\n var rect = canvas.getBoundingClientRect();\n var mx = (center.x - rect.left) * (canvas.width / rect.width);\n var my = (center.y - rect.top) * (canvas.height / rect.height);\n\n state.panX = mx - (mx - state.panX) * (newZoom / state.zoom);\n state.panY = my - (my - state.panY) * (newZoom / state.zoom);\n\n // Simultaneous pan\n var panDx = (center.x - touchState.lastCenterX) * (canvas.width / rect.width);\n var panDy = (center.y - touchState.lastCenterY) * (canvas.height / rect.height);\n state.panX += panDx;\n state.panY += panDy;\n\n state.zoom = newZoom;\n clampPan();\n render();\n }\n\n touchState.lastDist = dist;\n touchState.lastCenterX = center.x;\n touchState.lastCenterY = center.y;\n }\n }, { passive: false });\n\n canvas.addEventListener(\"touchend\", function (e) {\n if (!state.image) return;\n e.preventDefault();\n\n if (e.touches.length === 0) {\n if (!state.didDrag && touchState.touchCount === 1 && state.annotations.length > 0) {\n var touch = e.changedTouches[0];\n var pt = clientToCanvas(touch.clientX, touch.clientY);\n var hits = findAllHitAnnotationIndices(pt.x, pt.y);\n if (hits.length === 0) {\n state.selectedIndex = -1;\n } else if (hits.length === 1) {\n state.selectedIndex = state.selectedIndex === hits[0] ? -1 : hits[0];\n } else {\n var curPos = hits.indexOf(state.selectedIndex);\n if (curPos < 0) {\n state.selectedIndex = hits[0];\n } else {\n state.selectedIndex = hits[(curPos + 1) % hits.length];\n }\n }\n render();\n renderControlPanel();\n }\n state.isPanning = false;\n touchState.lastDist = 0;\n touchState.touchCount = 0;\n } else if (e.touches.length === 1) {\n // Transitioned from two fingers to one \u2014 restart single-finger pan\n state.isPanning = true;\n state.didDrag = false;\n state.panStartX = e.touches[0].clientX;\n state.panStartY = e.touches[0].clientY;\n state.panStartPanX = state.panX;\n state.panStartPanY = state.panY;\n touchState.lastDist = 0;\n }\n }, { passive: false });\n\n // \u2500\u2500 Keyboard Shortcuts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n element.setAttribute(\"tabindex\", \"0\");\n element.style.outline = \"none\";\n\n element.addEventListener(\"keydown\", function (e) {\n // Help dialog shortcuts (work even without image data)\n if (e.key === \"?\" && e.target.tagName !== \"INPUT\") {\n toggleHelp();\n e.preventDefault();\n return;\n }\n if (e.key === \"Escape\" && helpOverlay.classList.contains(\"visible\")) {\n toggleHelp();\n e.preventDefault();\n return;\n }\n\n if (!state.image) return;\n\n if (e.key === \"Escape\") {\n if (state.maximized) {\n toggleMaximize();\n e.preventDefault();\n } else if (state.selectedIndex >= 0) {\n state.selectedIndex = -1;\n render();\n renderControlPanel();\n e.preventDefault();\n }\n } else if (e.key === \"f\" || e.key === \"F\") {\n if (e.target.tagName === \"INPUT\") return;\n toggleMaximize();\n e.preventDefault();\n } else if (e.key === \"i\" || e.key === \"I\") {\n if (e.target.tagName === \"INPUT\") return;\n state.showImage = !state.showImage;\n toggleImageBtn.classList.toggle(\"active\", state.showImage);\n render();\n e.preventDefault();\n } else if (e.key === \"a\" || e.key === \"A\") {\n if (e.target.tagName === \"INPUT\") return;\n var anyVisible = false;\n for (var i = 0; i < state.visibility.length; i++) {\n if (state.visibility[i]) { anyVisible = true; break; }\n }\n var newVal = !anyVisible;\n for (var i = 0; i < state.visibility.length; i++) {\n state.visibility[i] = newVal;\n }\n render();\n renderControlPanel();\n e.preventDefault();\n } else if (e.key === \"h\" || e.key === \"H\") {\n if (e.target.tagName === \"INPUT\") return;\n if (state.selectedIndex >= 0) {\n var idx = state.selectedIndex;\n state.visibility[idx] = false;\n state.selectedIndex = -1;\n render();\n renderControlPanel();\n }\n e.preventDefault();\n } else if (e.key === \"r\" || e.key === \"R\") {\n if (e.target.tagName === \"INPUT\") return;\n resetToDefaults();\n e.preventDefault();\n } else if (e.key === \"+\" || e.key === \"=\") {\n if (e.target.tagName === \"INPUT\") return;\n zoomToCenter(state.zoom * 1.25);\n e.preventDefault();\n } else if (e.key === \"-\" || e.key === \"_\") {\n if (e.target.tagName === \"INPUT\") return;\n zoomToCenter(state.zoom / 1.25);\n e.preventDefault();\n } else if (e.key === \"0\") {\n if (e.target.tagName === \"INPUT\") return;\n resetZoom();\n canvas.style.cursor = \"default\";\n e.preventDefault();\n }\n });\n\n // \u2500\u2500 Window Resize \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n var resizeTimer = null;\n window.addEventListener(\"resize\", function () {\n if (resizeTimer) clearTimeout(resizeTimer);\n resizeTimer = setTimeout(function () {\n if (state.image) {\n fitCanvas();\n if (!state.maximized) resetZoom();\n else render();\n }\n }, 150);\n });\n})();\n", | |
| "default_props": { | |
| "value": "{\"image\": \"https://huggingface.co/datasets/gradio/custom-html-gallery/resolve/main/assets/hyst_image.webp\", \"annotations\": [{\"keypoints\": [], \"connections\": [], \"color\": \"#FF0000\", \"label\": \"microwave\", \"bbox\": {\"x\": 1254.9686279296875, \"y\": 732.0140991210938, \"width\": 731.1876220703125, \"height\": 576.3329467773438}, \"score\": 0.941}, {\"keypoints\": [], \"connections\": [], \"color\": \"#2196F3\", \"label\": \"refrigerator\", \"bbox\": {\"x\": 339.1869812011719, \"y\": 990.19970703125, \"width\": 876.6739807128906, \"height\": 2429.93701171875}, \"score\": 0.933}, {\"keypoints\": [], \"connections\": [], \"color\": \"#4CAF50\", \"label\": \"bowl\", \"bbox\": {\"x\": 2060.535888671875, \"y\": 2244.39990234375, \"width\": 336.198486328125, \"height\": 167.25927734375}, \"score\": 0.876}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF9800\", \"label\": \"bottle\", \"bbox\": {\"x\": 4423.5615234375, \"y\": 2121.12939453125, \"width\": 234.41064453125, \"height\": 441.45458984375}, \"score\": 0.835}, {\"keypoints\": [], \"connections\": [], \"color\": \"#9C27B0\", \"label\": \"bowl\", \"bbox\": {\"x\": 2043.2069091796875, \"y\": 2370.33642578125, \"width\": 329.2586669921875, \"height\": 146.4755859375}, \"score\": 0.752}, {\"keypoints\": [], \"connections\": [], \"color\": \"#00BCD4\", \"label\": \"bottle\", \"bbox\": {\"x\": 3447.89111328125, \"y\": 1566.84814453125, \"width\": 134.972412109375, \"height\": 196.5047607421875}, \"score\": 0.74}, {\"keypoints\": [], \"connections\": [], \"color\": \"#E91E63\", \"label\": \"spoon\", \"bbox\": {\"x\": 2970.81494140625, \"y\": 1495.561767578125, \"width\": 140.395263671875, \"height\": 229.298095703125}, \"score\": 0.73}, {\"keypoints\": [], \"connections\": [], \"color\": \"#8BC34A\", \"label\": \"bowl\", \"bbox\": {\"x\": 2439.3310546875, \"y\": 2352.2724609375, \"width\": 310.017578125, \"height\": 198.46630859375}, \"score\": 0.663}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF0000\", \"label\": \"sink\", \"bbox\": {\"x\": 3237.94775390625, \"y\": 2000.548828125, \"width\": 1229.5615234375, \"height\": 525.7890625}, \"score\": 0.651}, {\"keypoints\": [], \"connections\": [], \"color\": \"#2196F3\", \"label\": \"spoon\", \"bbox\": {\"x\": 2434.916748046875, \"y\": 958.53125, \"width\": 90.868896484375, \"height\": 397.71923828125}, \"score\": 0.624}, {\"keypoints\": [], \"connections\": [], \"color\": \"#4CAF50\", \"label\": \"spoon\", \"bbox\": {\"x\": 2713.24267578125, \"y\": 938.8221435546875, \"width\": 59.1435546875, \"height\": 356.3812255859375}, \"score\": 0.595}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF9800\", \"label\": \"vase\", \"bbox\": {\"x\": 3051.519775390625, \"y\": 1703.9114990234375, \"width\": 163.010498046875, \"height\": 211.6363525390625}, \"score\": 0.534}, {\"keypoints\": [], \"connections\": [], \"color\": \"#9C27B0\", \"label\": \"spoon\", \"bbox\": {\"x\": 3219.201171875, \"y\": 1489.04345703125, \"width\": 131.72900390625, \"height\": 113.6300048828125}, \"score\": 0.529}, {\"keypoints\": [], \"connections\": [], \"color\": \"#00BCD4\", \"label\": \"cup\", \"bbox\": {\"x\": 1710.7325439453125, \"y\": 206.48187255859375, \"width\": 113.3707275390625, \"height\": 66.7637939453125}, \"score\": 0.519}, {\"keypoints\": [], \"connections\": [], \"color\": \"#E91E63\", \"label\": \"cup\", \"bbox\": {\"x\": 1905.1246337890625, \"y\": 1348.912841796875, \"width\": 162.7110595703125, \"height\": 180.4144287109375}, \"score\": 0.51}, {\"keypoints\": [], \"connections\": [], \"color\": \"#8BC34A\", \"label\": \"spoon\", \"bbox\": {\"x\": 2532.578857421875, \"y\": 956.0765380859375, \"width\": 110.283203125, \"height\": 391.587890625}, \"score\": 0.505}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF0000\", \"label\": \"cup\", \"bbox\": {\"x\": 1513.127685546875, \"y\": 233.4671173095703, \"width\": 121.0208740234375, \"height\": 74.86408996582031}, \"score\": 0.498}, {\"keypoints\": [], \"connections\": [], \"color\": \"#2196F3\", \"label\": \"cup\", \"bbox\": {\"x\": 3601.44775390625, \"y\": 1676.3946533203125, \"width\": 86.130126953125, \"height\": 83.6402587890625}, \"score\": 0.489}, {\"keypoints\": [], \"connections\": [], \"color\": \"#4CAF50\", \"label\": \"sink\", \"bbox\": {\"x\": 2045.0098876953125, \"y\": 1902.2047119140625, \"width\": 992.6627197265625, \"height\": 138.331298828125}, \"score\": 0.48}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF9800\", \"label\": \"spoon\", \"bbox\": {\"x\": 2750.8525390625, \"y\": 914.2452392578125, \"width\": 138.5458984375, \"height\": 454.1220703125}, \"score\": 0.479}, {\"keypoints\": [], \"connections\": [], \"color\": \"#9C27B0\", \"label\": \"cup\", \"bbox\": {\"x\": 1292.629150390625, \"y\": 249.5679168701172, \"width\": 106.822021484375, \"height\": 69.71885681152344}, \"score\": 0.475}, {\"keypoints\": [], \"connections\": [], \"color\": \"#00BCD4\", \"label\": \"knife\", \"bbox\": {\"x\": 2167.822021484375, \"y\": 960.3970947265625, \"width\": 43.119140625, \"height\": 483.4991455078125}, \"score\": 0.465}, {\"keypoints\": [], \"connections\": [], \"color\": \"#E91E63\", \"label\": \"bottle\", \"bbox\": {\"x\": 4585.04150390625, \"y\": 2098.5009765625, \"width\": 116.8916015625, \"height\": 316.954345703125}, \"score\": 0.459}, {\"keypoints\": [], \"connections\": [], \"color\": \"#8BC34A\", \"label\": \"cup\", \"bbox\": {\"x\": 1712.269775390625, \"y\": 1363.4146728515625, \"width\": 168.132568359375, \"height\": 171.383056640625}, \"score\": 0.45}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF0000\", \"label\": \"cup\", \"bbox\": {\"x\": 1754.1475830078125, \"y\": 1726.2864990234375, \"width\": 132.280517578125, \"height\": 180.217529296875}, \"score\": 0.443}, {\"keypoints\": [], \"connections\": [], \"color\": \"#2196F3\", \"label\": \"spoon\", \"bbox\": {\"x\": 2464.33349609375, \"y\": 962.2620239257812, \"width\": 98.230712890625, \"height\": 395.64776611328125}, \"score\": 0.432}, {\"keypoints\": [], \"connections\": [], \"color\": \"#4CAF50\", \"label\": \"oven\", \"bbox\": {\"x\": 2045.0098876953125, \"y\": 1902.2047119140625, \"width\": 992.6627197265625, \"height\": 138.331298828125}, \"score\": 0.43}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF9800\", \"label\": \"spoon\", \"bbox\": {\"x\": 2338.453369140625, \"y\": 970.2446899414062, \"width\": 88.694091796875, \"height\": 284.50689697265625}, \"score\": 0.415}, {\"keypoints\": [], \"connections\": [], \"color\": \"#9C27B0\", \"label\": \"cup\", \"bbox\": {\"x\": 1600.4539794921875, \"y\": 1722.7650146484375, \"width\": 126.56103515625, \"height\": 181.688720703125}, \"score\": 0.409}, {\"keypoints\": [], \"connections\": [], \"color\": \"#00BCD4\", \"label\": \"cup\", \"bbox\": {\"x\": 1915.982421875, \"y\": 1727.005859375, \"width\": 161.400634765625, \"height\": 180.8668212890625}, \"score\": 0.407}, {\"keypoints\": [], \"connections\": [], \"color\": \"#E91E63\", \"label\": \"knife\", \"bbox\": {\"x\": 2122.896240234375, \"y\": 973.0816040039062, \"width\": 45.917724609375, \"height\": 480.61651611328125}, \"score\": 0.402}, {\"keypoints\": [], \"connections\": [], \"color\": \"#8BC34A\", \"label\": \"knife\", \"bbox\": {\"x\": 2050.469970703125, \"y\": 1032.178955078125, \"width\": 48.721923828125, \"height\": 364.73681640625}, \"score\": 0.391}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF0000\", \"label\": \"knife\", \"bbox\": {\"x\": 2204.854736328125, \"y\": 1075.57177734375, \"width\": 37.0556640625, \"height\": 365.2413330078125}, \"score\": 0.388}, {\"keypoints\": [], \"connections\": [], \"color\": \"#2196F3\", \"label\": \"knife\", \"bbox\": {\"x\": 2137.04345703125, \"y\": 967.40380859375, \"width\": 46.23291015625, \"height\": 482.9554443359375}, \"score\": 0.382}, {\"keypoints\": [], \"connections\": [], \"color\": \"#4CAF50\", \"label\": \"cup\", \"bbox\": {\"x\": 1938.565185546875, \"y\": 184.62074279785156, \"width\": 144.8037109375, \"height\": 72.32969665527344}, \"score\": 0.379}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF9800\", \"label\": \"vase\", \"bbox\": {\"x\": 4364.35546875, \"y\": 1642.5433349609375, \"width\": 325.09130859375, \"height\": 552.6705322265625}, \"score\": 0.359}, {\"keypoints\": [], \"connections\": [], \"color\": \"#9C27B0\", \"label\": \"spoon\", \"bbox\": {\"x\": 3148.77392578125, \"y\": 1489.83251953125, \"width\": 200.311279296875, \"height\": 217.281494140625}, \"score\": 0.358}, {\"keypoints\": [], \"connections\": [], \"color\": \"#00BCD4\", \"label\": \"spoon\", \"bbox\": {\"x\": 2325.773193359375, \"y\": 966.5449829101562, \"width\": 126.0576171875, \"height\": 382.44464111328125}, \"score\": 0.351}, {\"keypoints\": [], \"connections\": [], \"color\": \"#E91E63\", \"label\": \"handbag\", \"bbox\": {\"x\": 342.6567077636719, \"y\": 832.3612060546875, \"width\": 408.2694396972656, \"height\": 182.2032470703125}, \"score\": 0.347}, {\"keypoints\": [], \"connections\": [], \"color\": \"#8BC34A\", \"label\": \"sink\", \"bbox\": {\"x\": 3422.76611328125, \"y\": 2016.8096923828125, \"width\": 776.34912109375, \"height\": 293.2298583984375}, \"score\": 0.346}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF0000\", \"label\": \"oven\", \"bbox\": {\"x\": 2040.9306640625, \"y\": 1891.8070068359375, \"width\": 998.08642578125, \"height\": 601.4830322265625}, \"score\": 0.34}, {\"keypoints\": [], \"connections\": [], \"color\": \"#2196F3\", \"label\": \"spoon\", \"bbox\": {\"x\": 2578.92724609375, \"y\": 950.519287109375, \"width\": 68.382080078125, \"height\": 385.21142578125}, \"score\": 0.339}, {\"keypoints\": [], \"connections\": [], \"color\": \"#4CAF50\", \"label\": \"bowl\", \"bbox\": {\"x\": 1938.565185546875, \"y\": 184.62074279785156, \"width\": 144.8037109375, \"height\": 72.32969665527344}, \"score\": 0.337}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF9800\", \"label\": \"knife\", \"bbox\": {\"x\": 2118.98876953125, \"y\": 976.58642578125, \"width\": 37.457763671875, \"height\": 448.0491943359375}, \"score\": 0.326}, {\"keypoints\": [], \"connections\": [], \"color\": \"#9C27B0\", \"label\": \"knife\", \"bbox\": {\"x\": 2080.163818359375, \"y\": 1028.6563720703125, \"width\": 46.5048828125, \"height\": 370.2650146484375}, \"score\": 0.318}, {\"keypoints\": [], \"connections\": [], \"color\": \"#00BCD4\", \"label\": \"spoon\", \"bbox\": {\"x\": 2581.24658203125, \"y\": 950.1279296875, \"width\": 67.4453125, \"height\": 384.987548828125}, \"score\": 0.318}, {\"keypoints\": [], \"connections\": [], \"color\": \"#E91E63\", \"label\": \"knife\", \"bbox\": {\"x\": 2095.49951171875, \"y\": 1014.590087890625, \"width\": 48.67724609375, \"height\": 420.140869140625}, \"score\": 0.317}, {\"keypoints\": [], \"connections\": [], \"color\": \"#8BC34A\", \"label\": \"knife\", \"bbox\": {\"x\": 2113.23095703125, \"y\": 977.2379760742188, \"width\": 38.787841796875, \"height\": 431.59820556640625}, \"score\": 0.312}, {\"keypoints\": [], \"connections\": [], \"color\": \"#FF0000\", \"label\": \"spoon\", \"bbox\": {\"x\": 3144.85888671875, \"y\": 1568.898681640625, \"width\": 87.18017578125, \"height\": 141.762939453125}, \"score\": 0.305}, {\"keypoints\": [], \"connections\": [], \"color\": \"#2196F3\", \"label\": \"knife\", \"bbox\": {\"x\": 2124.10546875, \"y\": 978.140380859375, \"width\": 38.487060546875, \"height\": 460.7664794921875}, \"score\": 0.302}], \"scoreThresholdMin\": 0.3, \"scoreThresholdMax\": 1.0}" | |
| }, | |
| "python_code": "class DetectionViewer(gr.HTML):\n def __init__(\n self,\n value: tuple[str | Path | Image.Image | np.ndarray, list[dict[str, Any]]]\n | tuple[str | Path | Image.Image | np.ndarray, list[dict[str, Any]], dict[str, Any]]\n | None = None,\n *,\n label: str | None = None,\n panel_title: str = \"Detections\",\n list_height: int = 300,\n score_threshold: tuple[float, float] = (0.0, 1.0),\n keypoint_threshold: float = 0.0,\n keypoint_radius: int = 3,\n **kwargs: object,\n ) -> None:\n html_template = (_STATIC_DIR / \"template.html\").read_text(encoding=\"utf-8\")\n html_template = html_template.replace(\"${panel_title}\", panel_title)\n html_template = html_template.replace(\"${list_height}\", str(list_height))\n html_template = html_template.replace(\"${score_threshold_min}\", str(score_threshold[0]))\n html_template = html_template.replace(\"${score_threshold_max}\", str(score_threshold[1]))\n html_template = html_template.replace(\"${keypoint_threshold}\", str(keypoint_threshold))\n html_template = html_template.replace(\"${keypoint_radius}\", str(keypoint_radius))\n css_template = (_STATIC_DIR / \"style.css\").read_text(encoding=\"utf-8\")\n css_template = css_template.replace(\"${list_height}\", str(list_height))\n js_on_load = (_STATIC_DIR / \"script.js\").read_text(encoding=\"utf-8\")\n\n has_label = label is not None\n super().__init__(\n value=value,\n label=label,\n show_label=has_label,\n container=has_label,\n html_template=html_template,\n css_template=css_template,\n js_on_load=js_on_load,\n **kwargs,\n )\n\n def postprocess(self, value: Any) -> str | None: # noqa: ANN401\n if isinstance(value, str):\n return value\n return self._process(value)\n\n def _process(\n self,\n value: tuple[str | Path | Image.Image | np.ndarray, list[dict[str, Any]]]\n | tuple[str | Path | Image.Image | np.ndarray, list[dict[str, Any]], dict[str, Any]]\n | None,\n ) -> str | None:\n if value is None:\n return None\n\n if len(value) == 3: # noqa: PLR2004 - tuple length check\n image_src, annotations, config = value\n else:\n image_src, annotations = value\n config = {}\n\n img = _load_image(image_src)\n image_url = _save_image_to_cache(img, self.GRADIO_CACHE)\n\n processed: list[dict[str, Any]] = []\n for i, ann in enumerate(annotations):\n has_kps = \"keypoints\" in ann and len(ann[\"keypoints\"]) > 0\n default_label = f\"Person {i + 1}\" if has_kps else f\"Detection {i + 1}\"\n\n entry: dict[str, Any] = {\n \"keypoints\": ann.get(\"keypoints\", []),\n \"connections\": ann.get(\"connections\", []),\n \"color\": ann.get(\"color\", _COLOR_PALETTE[i % len(_COLOR_PALETTE)]),\n \"label\": ann.get(\"label\", default_label),\n }\n if \"bbox\" in ann:\n entry[\"bbox\"] = ann[\"bbox\"]\n if \"score\" in ann:\n entry[\"score\"] = ann[\"score\"]\n if \"mask\" in ann:\n entry[\"mask\"] = ann[\"mask\"]\n processed.append(entry)\n\n result: dict[str, Any] = {\"image\": image_url, \"annotations\": processed}\n if \"score_threshold\" in config:\n result[\"scoreThresholdMin\"] = config[\"score_threshold\"][0]\n result[\"scoreThresholdMax\"] = config[\"score_threshold\"][1]\n\n return json.dumps(result)\n\n def api_info(self) -> dict[str, Any]:\n return {\n \"type\": \"string\",\n \"description\": (\n \"JSON string containing detection visualization data. \"\n \"Structure: {image: string (URL), annotations: [\"\n \"{color: string, label: string, \"\n \"bbox?: {x: float, y: float, width: float, height: float}, \"\n \"score?: float, \"\n \"mask?: {counts: [int], size: [int, int]}, \"\n \"keypoints?: [{x: float, y: float, name: string, confidence?: float}], \"\n \"connections?: [[int, int]]}], \"\n \"scoreThresholdMin?: float, scoreThresholdMax?: float}\"\n ),\n }\n", | |
| "repo_url": "https://github.com/hysts/gradio-detection-viewer/" | |
| }, | |
| { | |
| "id": "contribution-heatmap", | |
| "name": "Contribution Heatmap", | |
| "description": "Reusable GitHub-style contribution heatmap", | |
| "author": "ysharma", | |
| "tags": [ | |
| "Business" | |
| ], | |
| "category": "Display", | |
| "html_template": "\n<div class=\"heatmap-container\">\n <div class=\"heatmap-header\">\n <h2>${(() => {\n const total = Object.values(value || {}).reduce((a, b) => a + b, 0);\n return '\ud83d\udcca ' + total.toLocaleString() + ' contributions in ' + year;\n })()}</h2>\n <div class=\"legend\">\n <span>Less</span>\n <div class=\"legend-box\" style=\"background:${c0}\"></div>\n <div class=\"legend-box\" style=\"background:${c1}\"></div>\n <div class=\"legend-box\" style=\"background:${c2}\"></div>\n <div class=\"legend-box\" style=\"background:${c3}\"></div>\n <div class=\"legend-box\" style=\"background:${c4}\"></div>\n <span>More</span>\n </div>\n </div>\n <div class=\"month-labels\">\n ${(() => {\n const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];\n return months.map((m, i) =>\n '<span style=\"grid-column:' + (Math.floor(i * 4.33) + 2) + '\">' + m + '</span>'\n ).join('');\n })()}\n </div>\n <div class=\"heatmap-grid\">\n <div class=\"day-labels\">\n <span></span><span>Mon</span><span></span><span>Wed</span><span></span><span>Fri</span><span></span>\n </div>\n <div class=\"cells\">\n ${(() => {\n const v = value || {};\n const sd = new Date(year, 0, 1);\n const pad = sd.getDay();\n const cells = [];\n for (let i = 0; i < pad; i++) cells.push('<div class=\"cell empty\"></div>');\n const totalDays = Math.floor((new Date(year, 11, 31) - sd) / 86400000) + 1;\n for (let d = 0; d < totalDays; d++) {\n const dt = new Date(year, 0, 1 + d);\n const key = dt.getFullYear() + '-' + String(dt.getMonth()+1).padStart(2,'0') + '-' + String(dt.getDate()).padStart(2,'0');\n const count = v[key] || 0;\n let lv = 0;\n if (count > 0) lv = 1;\n if (count >= 3) lv = 2;\n if (count >= 6) lv = 3;\n if (count >= 10) lv = 4;\n const mn = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];\n const tip = count + ' contributions on ' + mn[dt.getMonth()] + ' ' + dt.getDate() + ', ' + year;\n cells.push('<div class=\"cell level-' + lv + '\" data-date=\"' + key + '\" data-count=\"' + count + '\" title=\"' + tip + '\"></div>');\n }\n return cells.join('');\n })()}\n </div>\n </div>\n <div class=\"stats-bar\">\n ${(() => {\n const v = value || {};\n const totalDays = Math.floor((new Date(year, 11, 31) - new Date(year, 0, 1)) / 86400000) + 1;\n let streak = 0, maxStreak = 0, total = 0, active = 0, best = 0;\n const vals = [];\n for (let d = 0; d < totalDays; d++) {\n const dt = new Date(year, 0, 1 + d);\n const key = dt.getFullYear() + '-' + String(dt.getMonth()+1).padStart(2,'0') + '-' + String(dt.getDate()).padStart(2,'0');\n const c = v[key] || 0;\n total += c;\n if (c > 0) { streak++; maxStreak = Math.max(maxStreak, streak); active++; best = Math.max(best, c); vals.push(c); }\n else { streak = 0; }\n }\n const avg = vals.length ? (total / vals.length).toFixed(1) : '0';\n const stats = [\n ['\ud83d\udd25', maxStreak, 'Longest Streak'],\n ['\ud83d\udcc5', active, 'Active Days'],\n ['\u26a1', best, 'Best Day'],\n ['\ud83d\udcc8', avg, 'Avg / Active Day'],\n ['\ud83c\udfc6', total.toLocaleString(), 'Total'],\n ];\n return stats.map(s =>\n '<div class=\"stat\"><span class=\"stat-value\">' + s[1] + '</span><span class=\"stat-label\">' + s[0] + ' ' + s[2] + '</span></div>'\n ).join('');\n })()}\n </div>\n</div>\n", | |
| "css_template": "\n .heatmap-container {\n background: #0d1117;\n border-radius: 12px;\n padding: 24px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n color: #c9d1d9;\n overflow-x: auto;\n }\n .heatmap-header {\n display: flex; justify-content: space-between; align-items: center;\n margin-bottom: 12px; flex-wrap: wrap; gap: 10px;\n }\n .heatmap-header h2 { margin: 0; font-size: 16px; font-weight: 500; color: #f0f6fc; }\n .legend { display: flex; align-items: center; gap: 4px; font-size: 11px; color: #8b949e; }\n .legend-box { width: 12px; height: 12px; border-radius: 2px; }\n .month-labels {\n display: grid; grid-template-columns: 30px repeat(53, 1fr);\n font-size: 11px; color: #8b949e; margin-bottom: 4px; padding-left: 2px;\n }\n .heatmap-grid { display: flex; gap: 4px; }\n .day-labels {\n display: grid; grid-template-rows: repeat(7, 1fr);\n font-size: 11px; color: #8b949e; width: 30px; gap: 2px;\n }\n .day-labels span { height: 13px; display: flex; align-items: center; }\n .cells {\n display: grid; grid-template-rows: repeat(7, 1fr);\n grid-auto-flow: column; gap: 2px; flex: 1;\n }\n .cell {\n width: 13px; height: 13px; border-radius: 2px; cursor: pointer;\n transition: all 0.15s ease; outline: 1px solid rgba(27,31,35,0.06);\n }\n .cell:hover {\n outline: 2px solid #58a6ff; outline-offset: -1px;\n transform: scale(1.3); z-index: 1;\n }\n .cell.empty { visibility: hidden; }\n .level-0 { background: ${c0}; }\n .level-1 { background: ${c1}; }\n .level-2 { background: ${c2}; }\n .level-3 { background: ${c3}; }\n .level-4 { background: ${c4}; }\n .stats-bar {\n display: flex; justify-content: space-around; margin-top: 20px;\n padding-top: 16px; border-top: 1px solid #21262d;\n flex-wrap: wrap; gap: 12px;\n }\n .stat { display: flex; flex-direction: column; align-items: center; gap: 4px; }\n .stat-value { font-size: 22px; font-weight: 700; color: ${c4}; }\n .stat-label { font-size: 12px; color: #8b949e; }\n", | |
| "js_on_load": "\n element.addEventListener('click', (e) => {\n if (e.target && e.target.classList.contains('cell') && !e.target.classList.contains('empty')) {\n const date = e.target.dataset.date;\n const cur = parseInt(e.target.dataset.count) || 0;\n const next = cur >= 12 ? 0 : cur + 1;\n const nv = {...(props.value || {})};\n if (next === 0) delete nv[date]; else nv[date] = next;\n props.value = nv;\n trigger('change');\n }\n });\n", | |
| "default_props": { | |
| "value": { | |
| "2025-01-01": 15, | |
| "2025-01-02": 10, | |
| "2025-01-05": 2, | |
| "2025-01-06": 2, | |
| "2025-01-07": 3, | |
| "2025-01-08": 7, | |
| "2025-01-13": 1, | |
| "2025-01-14": 3, | |
| "2025-01-15": 1, | |
| "2025-01-17": 1, | |
| "2025-01-19": 5, | |
| "2025-01-20": 4, | |
| "2025-01-22": 1, | |
| "2025-01-26": 2, | |
| "2025-01-27": 11, | |
| "2025-01-28": 1, | |
| "2025-01-29": 2, | |
| "2025-02-02": 2, | |
| "2025-02-04": 8, | |
| "2025-02-05": 2, | |
| "2025-02-07": 2, | |
| "2025-02-09": 7, | |
| "2025-02-10": 2, | |
| "2025-02-11": 6, | |
| "2025-02-12": 15, | |
| "2025-02-13": 1, | |
| "2025-02-15": 1, | |
| "2025-02-19": 1, | |
| "2025-02-21": 9, | |
| "2025-02-22": 9, | |
| "2025-02-26": 1, | |
| "2025-02-27": 1, | |
| "2025-02-28": 8, | |
| "2025-03-01": 8, | |
| "2025-03-02": 7, | |
| "2025-03-05": 1, | |
| "2025-03-07": 13, | |
| "2025-03-08": 5, | |
| "2025-03-09": 2, | |
| "2025-03-11": 2, | |
| "2025-03-12": 4, | |
| "2025-03-14": 3, | |
| "2025-03-15": 3, | |
| "2025-03-16": 3, | |
| "2025-03-18": 3, | |
| "2025-03-20": 5, | |
| "2025-03-21": 5, | |
| "2025-03-22": 15, | |
| "2025-03-25": 2, | |
| "2025-03-27": 1, | |
| "2025-03-28": 3, | |
| "2025-04-03": 2, | |
| "2025-04-04": 1, | |
| "2025-04-07": 1, | |
| "2025-04-11": 1, | |
| "2025-04-13": 7, | |
| "2025-04-14": 2, | |
| "2025-04-17": 1, | |
| "2025-04-19": 1, | |
| "2025-04-21": 4, | |
| "2025-04-22": 2, | |
| "2025-04-23": 3, | |
| "2025-04-24": 1, | |
| "2025-04-27": 1, | |
| "2025-04-29": 6, | |
| "2025-04-30": 1, | |
| "2025-05-01": 8, | |
| "2025-05-05": 4, | |
| "2025-05-07": 2, | |
| "2025-05-09": 1, | |
| "2025-05-11": 3, | |
| "2025-05-12": 1, | |
| "2025-05-13": 5, | |
| "2025-05-16": 13, | |
| "2025-05-17": 8, | |
| "2025-05-18": 2, | |
| "2025-05-19": 11, | |
| "2025-05-21": 1, | |
| "2025-05-24": 4, | |
| "2025-05-27": 8, | |
| "2025-05-28": 2, | |
| "2025-05-29": 1, | |
| "2025-05-30": 1, | |
| "2025-06-01": 5, | |
| "2025-06-02": 3, | |
| "2025-06-04": 3, | |
| "2025-06-05": 2, | |
| "2025-06-07": 5, | |
| "2025-06-14": 11, | |
| "2025-06-15": 5, | |
| "2025-06-19": 6, | |
| "2025-06-20": 5, | |
| "2025-06-22": 8, | |
| "2025-06-24": 5, | |
| "2025-06-25": 9, | |
| "2025-06-27": 5, | |
| "2025-06-28": 5, | |
| "2025-06-29": 6, | |
| "2025-06-30": 3, | |
| "2025-07-01": 1, | |
| "2025-07-02": 5, | |
| "2025-07-05": 2, | |
| "2025-07-08": 1, | |
| "2025-07-10": 2, | |
| "2025-07-12": 3, | |
| "2025-07-13": 2, | |
| "2025-07-14": 5, | |
| "2025-07-15": 5, | |
| "2025-07-16": 1, | |
| "2025-07-18": 9, | |
| "2025-07-19": 9, | |
| "2025-07-20": 2, | |
| "2025-07-22": 3, | |
| "2025-07-24": 5, | |
| "2025-07-25": 1, | |
| "2025-07-27": 5, | |
| "2025-07-30": 2, | |
| "2025-08-01": 13, | |
| "2025-08-02": 3, | |
| "2025-08-03": 2, | |
| "2025-08-04": 9, | |
| "2025-08-05": 4, | |
| "2025-08-07": 1, | |
| "2025-08-09": 5, | |
| "2025-08-12": 2, | |
| "2025-08-13": 5, | |
| "2025-08-14": 4, | |
| "2025-08-15": 4, | |
| "2025-08-18": 6, | |
| "2025-08-19": 6, | |
| "2025-08-20": 2, | |
| "2025-08-24": 6, | |
| "2025-08-25": 3, | |
| "2025-08-26": 12, | |
| "2025-08-27": 14, | |
| "2025-08-29": 1, | |
| "2025-08-31": 5, | |
| "2025-09-01": 1, | |
| "2025-09-02": 3, | |
| "2025-09-03": 2, | |
| "2025-09-04": 14, | |
| "2025-09-05": 6, | |
| "2025-09-06": 9, | |
| "2025-09-07": 4, | |
| "2025-09-08": 1, | |
| "2025-09-10": 1, | |
| "2025-09-16": 4, | |
| "2025-09-18": 4, | |
| "2025-09-19": 2, | |
| "2025-09-20": 3, | |
| "2025-09-23": 2, | |
| "2025-09-24": 6, | |
| "2025-09-25": 3, | |
| "2025-09-27": 1, | |
| "2025-09-28": 5, | |
| "2025-09-29": 5, | |
| "2025-10-02": 2, | |
| "2025-10-03": 2, | |
| "2025-10-06": 8, | |
| "2025-10-07": 8, | |
| "2025-10-08": 8, | |
| "2025-10-09": 3, | |
| "2025-10-10": 15, | |
| "2025-10-13": 2, | |
| "2025-10-14": 9, | |
| "2025-10-15": 1, | |
| "2025-10-16": 2, | |
| "2025-10-17": 1, | |
| "2025-10-20": 6, | |
| "2025-10-23": 9, | |
| "2025-10-26": 1, | |
| "2025-10-28": 2, | |
| "2025-10-31": 1, | |
| "2025-11-01": 2, | |
| "2025-11-02": 1, | |
| "2025-11-03": 1, | |
| "2025-11-05": 1, | |
| "2025-11-06": 5, | |
| "2025-11-07": 2, | |
| "2025-11-09": 3, | |
| "2025-11-10": 2, | |
| "2025-11-11": 1, | |
| "2025-11-13": 2, | |
| "2025-11-14": 1, | |
| "2025-11-15": 1, | |
| "2025-11-17": 4, | |
| "2025-11-19": 2, | |
| "2025-11-20": 11, | |
| "2025-11-21": 9, | |
| "2025-11-23": 1, | |
| "2025-11-24": 3, | |
| "2025-11-27": 7, | |
| "2025-11-28": 1, | |
| "2025-11-29": 5, | |
| "2025-12-01": 2, | |
| "2025-12-03": 1, | |
| "2025-12-05": 1, | |
| "2025-12-07": 6, | |
| "2025-12-08": 1, | |
| "2025-12-09": 3, | |
| "2025-12-10": 4, | |
| "2025-12-15": 2, | |
| "2025-12-19": 3, | |
| "2025-12-20": 15, | |
| "2025-12-23": 5, | |
| "2025-12-25": 2, | |
| "2025-12-26": 1, | |
| "2025-12-28": 4, | |
| "2025-12-29": 2 | |
| }, | |
| "year": 2025, | |
| "c0": "#161b22", | |
| "c1": "#0e4429", | |
| "c2": "#006d32", | |
| "c3": "#26a641", | |
| "c4": "#39d353" | |
| }, | |
| "python_code": "class ContributionHeatmap(gr.HTML):\n \"\"\"Reusable GitHub-style contribution heatmap built on gr.HTML.\"\"\"\n\n def __init__(self, value=None, year=2025, theme=\"green\",\n c0=None, c1=None, c2=None, c3=None, c4=None, **kwargs):\n if value is None:\n value = {}\n # Use explicit c0-c4 if provided (from gr.HTML updates), else derive from theme\n colors = COLOR_SCHEMES.get(theme, COLOR_SCHEMES[\"green\"])\n super().__init__(\n value=value,\n year=year,\n c0=c0 or colors[0],\n c1=c1 or colors[1],\n c2=c2 or colors[2],\n c3=c3 or colors[3],\n c4=c4 or colors[4],\n html_template=HEATMAP_HTML,\n css_template=HEATMAP_CSS,\n js_on_load=HEATMAP_JS,\n **kwargs,\n )\n\n def api_info(self):\n return {\"type\": \"object\", \"description\": \"Dict mapping YYYY-MM-DD to int counts\"}\n", | |
| "head": "", | |
| "repo_url": "https://huggingface.co/spaces/ysharma/github-contribution-heatmap" | |
| }, | |
| { | |
| "id": "spin-wheel", | |
| "name": "Spin Wheel", | |
| "description": "Spin the wheel to win a prize!", | |
| "author": "ysharma", | |
| "tags": [], | |
| "category": "display", | |
| "html_template": "\n<div class=\"wheel-container\">\n <div class=\"wheel-wrapper\">\n <!-- Pointer -->\n <div class=\"wheel-pointer\">\u25bc</div>\n \n <!-- Wheel - rotation prop preserves position across re-renders -->\n <div class=\"wheel\" id=\"prize-wheel\" style=\"transform: rotate(${rotation || 0}deg);\">\n <svg viewBox=\"0 0 400 400\" class=\"wheel-svg\">\n ${(() => {\n const segments = JSON.parse(segments_json || '[]');\n const cx = 200, cy = 200, r = 180;\n let html = '';\n \n segments.forEach((seg, i) => {\n const startRad = (seg.startAngle - 90) * Math.PI / 180;\n const endRad = (seg.endAngle - 90) * Math.PI / 180;\n const x1 = cx + r * Math.cos(startRad);\n const y1 = cy + r * Math.sin(startRad);\n const x2 = cx + r * Math.cos(endRad);\n const y2 = cy + r * Math.sin(endRad);\n const largeArc = seg.endAngle - seg.startAngle > 180 ? 1 : 0;\n \n const d = `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} Z`;\n html += `<path d=\"${d}\" fill=\"${seg.color}\" stroke=\"#fff\" stroke-width=\"2\" class=\"segment\" data-index=\"${i}\"/>`;\n \n // Text label\n const midRad = (seg.midAngle - 90) * Math.PI / 180;\n const textR = r * 0.65;\n const tx = cx + textR * Math.cos(midRad);\n const ty = cy + textR * Math.sin(midRad);\n const rotation = seg.midAngle;\n html += `<text x=\"${tx}\" y=\"${ty}\" fill=\"#fff\" font-size=\"11\" font-weight=\"bold\" \n text-anchor=\"middle\" dominant-baseline=\"middle\" \n transform=\"rotate(${rotation}, ${tx}, ${ty})\"\n style=\"text-shadow: 1px 1px 2px rgba(0,0,0,0.5); pointer-events: none;\">${seg.label}</text>`;\n });\n \n // Center circle\n html += `<circle cx=\"200\" cy=\"200\" r=\"35\" fill=\"#1a1a2e\" stroke=\"#FFD700\" stroke-width=\"4\" class=\"center-btn\"/>`;\n html += `<text x=\"200\" y=\"200\" fill=\"#FFD700\" font-size=\"14\" font-weight=\"bold\" text-anchor=\"middle\" dominant-baseline=\"middle\" style=\"pointer-events: none;\">SPIN</text>`;\n \n return html;\n })()}\n </svg>\n </div>\n \n <!-- Decorative lights -->\n <div class=\"wheel-lights\">\n ${Array.from({length: 16}, (_, i) => `<div class=\"light\" style=\"--i: ${i}\"></div>`).join('')}\n </div>\n </div>\n \n <!-- Result Display -->\n <div class=\"result-display ${value ? 'show' : ''}\" id=\"result-display\">\n ${value ? `<div class=\"result-text\">\ud83c\udf89 You won: <strong>${value}</strong></div>` : '<div class=\"result-text\">Spin to win!</div>'}\n </div>\n \n <!-- Spin Button -->\n <button class=\"spin-button\" id=\"spin-btn\">\n \ud83c\udfb0 SPIN TO WIN!\n </button>\n \n <!-- Confetti container -->\n <div class=\"confetti-container\" id=\"confetti\"></div>\n</div>\n", | |
| "css_template": "\n .wheel-container {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: 24px;\n background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);\n border-radius: 24px;\n position: relative;\n overflow: hidden;\n min-height: 500px;\n }\n \n .wheel-wrapper {\n position: relative;\n width: 320px;\n height: 320px;\n }\n \n .wheel {\n width: 100%;\n height: 100%;\n transform: rotate(0deg);\n }\n \n .wheel-svg {\n width: 100%;\n height: 100%;\n filter: drop-shadow(0 10px 30px rgba(0,0,0,0.4));\n }\n \n .segment {\n cursor: pointer;\n transition: filter 0.2s;\n }\n \n .segment:hover {\n filter: brightness(1.1);\n }\n \n .center-btn {\n cursor: pointer;\n transition: all 0.2s;\n }\n \n .center-btn:hover {\n filter: brightness(1.2);\n }\n \n /* Pointer */\n .wheel-pointer {\n position: absolute;\n top: -10px;\n left: 50%;\n transform: translateX(-50%);\n font-size: 48px;\n color: #FFD700;\n z-index: 10;\n filter: drop-shadow(0 4px 6px rgba(0,0,0,0.5));\n animation: bounce 0.6s ease-in-out infinite;\n }\n \n @keyframes bounce {\n 0%, 100% { transform: translateX(-50%) translateY(0); }\n 50% { transform: translateX(-50%) translateY(8px); }\n }\n \n /* Decorative lights */\n .wheel-lights {\n position: absolute;\n top: 50%;\n left: 50%;\n width: 360px;\n height: 360px;\n transform: translate(-50%, -50%);\n pointer-events: none;\n }\n \n .light {\n position: absolute;\n width: 14px;\n height: 14px;\n background: #FFD700;\n border-radius: 50%;\n top: 50%;\n left: 50%;\n transform-origin: center;\n transform: rotate(calc(var(--i) * 22.5deg)) translateY(-180px);\n box-shadow: 0 0 10px #FFD700, 0 0 20px #FFD700;\n animation: blink 0.5s ease-in-out infinite alternate;\n animation-delay: calc(var(--i) * 0.08s);\n }\n \n @keyframes blink {\n 0% { opacity: 0.4; transform: rotate(calc(var(--i) * 22.5deg)) translateY(-180px) scale(0.8); }\n 100% { opacity: 1; transform: rotate(calc(var(--i) * 22.5deg)) translateY(-180px) scale(1); box-shadow: 0 0 15px #FFD700, 0 0 30px #FFD700; }\n }\n \n /* Spin Button */\n .spin-button {\n margin-top: 24px;\n padding: 18px 56px;\n font-size: 20px;\n font-weight: 700;\n color: white;\n background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);\n border: none;\n border-radius: 50px;\n cursor: pointer;\n box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4);\n transition: all 0.3s ease;\n text-transform: uppercase;\n letter-spacing: 2px;\n }\n \n .spin-button:hover:not(:disabled) {\n transform: translateY(-3px);\n box-shadow: 0 12px 35px rgba(255, 107, 107, 0.5);\n }\n \n .spin-button:active:not(:disabled) {\n transform: translateY(0);\n }\n \n .spin-button:disabled {\n background: linear-gradient(135deg, #666 0%, #888 100%);\n cursor: not-allowed;\n box-shadow: none;\n transform: none;\n }\n \n /* Result Display */\n .result-display {\n margin-top: 20px;\n padding: 16px 32px;\n background: rgba(255,255,255,0.1);\n border-radius: 12px;\n backdrop-filter: blur(10px);\n border: 1px solid rgba(255,255,255,0.1);\n opacity: 0.7;\n transform: scale(0.95);\n transition: all 0.5s ease;\n }\n \n .result-display.show {\n opacity: 1;\n transform: scale(1);\n background: rgba(255,215,0,0.15);\n border-color: rgba(255,215,0,0.3);\n }\n \n .result-text {\n font-size: 18px;\n color: #fff;\n text-align: center;\n }\n \n .result-text strong {\n color: #FFD700;\n font-size: 22px;\n display: block;\n margin-top: 4px;\n }\n \n /* Confetti */\n .confetti-container {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n overflow: hidden;\n }\n \n .confetti {\n position: absolute;\n width: 10px;\n height: 10px;\n animation: fall 3s ease-out forwards;\n }\n \n @keyframes fall {\n 0% {\n transform: translateY(-100px) rotate(0deg);\n opacity: 1;\n }\n 100% {\n transform: translateY(600px) rotate(720deg);\n opacity: 0;\n }\n }\n \n /* Spinning state indicator */\n .wheel-container.spinning .wheel-pointer {\n animation: none;\n color: #fff;\n }\n \n .wheel-container.spinning .light {\n animation: rapid-blink 0.1s ease-in-out infinite alternate;\n }\n \n @keyframes rapid-blink {\n 0% { opacity: 0.3; }\n 100% { opacity: 1; }\n }\n", | |
| "js_on_load": "\n const container = element.querySelector('.wheel-container');\n const wheel = element.querySelector('#prize-wheel');\n const spinBtn = element.querySelector('#spin-btn');\n const confettiContainer = element.querySelector('#confetti');\n const resultDisplay = element.querySelector('#result-display');\n \n let isSpinning = false;\n \n // Initialize totalRotation from the rotation prop (persists across re-renders)\n let totalRotation = parseFloat(props.rotation) || 0;\n \n function getSegments() {\n try {\n return JSON.parse(props.segments_json || '[]');\n } catch (e) {\n return [];\n }\n }\n \n function createConfetti() {\n const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFEAA7', '#DDA0DD', '#FFD700', '#FF8E53', '#96CEB4'];\n for (let i = 0; i < 150; i++) {\n setTimeout(() => {\n const confetti = document.createElement('div');\n confetti.className = 'confetti';\n confetti.style.left = Math.random() * 100 + '%';\n confetti.style.background = colors[Math.floor(Math.random() * colors.length)];\n confetti.style.animationDelay = Math.random() * 0.3 + 's';\n confetti.style.animationDuration = (2 + Math.random() * 2) + 's';\n const size = 6 + Math.random() * 10;\n confetti.style.width = size + 'px';\n confetti.style.height = size + 'px';\n confetti.style.borderRadius = Math.random() > 0.5 ? '50%' : Math.random() > 0.5 ? '0' : '2px';\n confettiContainer.appendChild(confetti);\n \n setTimeout(() => confetti.remove(), 4000);\n }, i * 15);\n }\n }\n \n function spinWheel() {\n if (isSpinning) return;\n \n const segments = getSegments();\n if (segments.length === 0) return;\n \n isSpinning = true;\n container.classList.add('spinning');\n spinBtn.disabled = true;\n spinBtn.textContent = '\ud83c\udfb0 SPINNING...';\n \n // Pick a random winning segment\n const winningIndex = Math.floor(Math.random() * segments.length);\n const winningSegment = segments[winningIndex];\n \n // === ROTATION MATH ===\n // The pointer is fixed at TOP (0\u00b0). Segments are drawn with 0\u00b0 at top.\n // For pointer to hit segment, we need rotation where segment's midAngle aligns with top.\n \n // Add random offset within segment bounds\n const segmentSize = winningSegment.endAngle - winningSegment.startAngle;\n const randomOffset = (Math.random() - 0.5) * segmentSize * 0.7;\n \n // Target position (mod 360) where wheel should stop\n const targetMod = ((360 - winningSegment.midAngle + randomOffset) % 360 + 360) % 360;\n \n // Current wheel position (mod 360)\n const currentMod = ((totalRotation % 360) + 360) % 360;\n \n // Calculate additional rotation needed (always spin forward)\n let additionalRotation = targetMod - currentMod;\n if (additionalRotation <= 0) additionalRotation += 360;\n \n // Add extra full spins for dramatic effect (5-7 spins)\n const extraSpins = 5 + Math.floor(Math.random() * 3);\n const finalRotation = totalRotation + extraSpins * 360 + additionalRotation;\n \n // Apply rotation with CSS transition\n wheel.style.transition = 'transform 4s cubic-bezier(0.17, 0.67, 0.12, 0.99)';\n wheel.style.transform = `rotate(${finalRotation}deg)`;\n \n // Store FULL rotation for next spin\n totalRotation = finalRotation;\n \n // After spin completes, determine winner from ACTUAL landing position\n setTimeout(() => {\n isSpinning = false;\n container.classList.remove('spinning');\n spinBtn.disabled = false;\n spinBtn.textContent = '\ud83c\udfb0 SPIN AGAIN!';\n \n // Verify which segment the pointer actually landed on\n const landedRotation = ((totalRotation % 360) + 360) % 360;\n const pointerAngle = ((360 - landedRotation) % 360 + 360) % 360;\n \n // Find which segment contains this angle\n let actualWinner = winningSegment;\n for (const seg of segments) {\n if (pointerAngle >= seg.startAngle && pointerAngle < seg.endAngle) {\n actualWinner = seg;\n break;\n }\n }\n // Handle wrap-around edge case\n if (pointerAngle >= segments[segments.length - 1].endAngle || pointerAngle < segments[0].startAngle) {\n if (segments[0].startAngle === 0) {\n actualWinner = segments[0];\n }\n }\n \n // Persist rotation as prop so it survives re-renders\n props.rotation = totalRotation;\n \n // Update value - this automatically triggers 'change' event\n // Do NOT call trigger('change') separately or you'll get duplicate events!\n props.value = actualWinner.label;\n \n createConfetti();\n \n console.log('Spin complete:', {\n finalRotation: totalRotation,\n pointerAngle,\n winner: actualWinner.label\n });\n }, 4100);\n }\n \n // Button click\n spinBtn.addEventListener('click', spinWheel);\n \n // Click on wheel center\n element.addEventListener('click', (e) => {\n if (e.target && e.target.classList.contains('center-btn')) {\n spinWheel();\n }\n });\n \n // Keyboard support\n element.addEventListener('keydown', (e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n spinWheel();\n }\n });\n", | |
| "default_props": { | |
| "value": "", | |
| "segments_json": "[{\"label\": \"\\ud83c\\udf81 Grand Prize\", \"color\": \"#FF6B6B\", \"startAngle\": 0, \"endAngle\": 45.0, \"midAngle\": 22.5}, {\"label\": \"\\ud83d\\udc8e 50 Gems\", \"color\": \"#4ECDC4\", \"startAngle\": 45.0, \"endAngle\": 90.0, \"midAngle\": 67.5}, {\"label\": \"\\u2b50 100 XP\", \"color\": \"#45B7D1\", \"startAngle\": 90.0, \"endAngle\": 135.0, \"midAngle\": 112.5}, {\"label\": \"\\ud83c\\udfab Free Trial\", \"color\": \"#96CEB4\", \"startAngle\": 135.0, \"endAngle\": 180.0, \"midAngle\": 157.5}, {\"label\": \"\\ud83d\\udd25 Double Points\", \"color\": \"#FFEAA7\", \"startAngle\": 180.0, \"endAngle\": 225.0, \"midAngle\": 202.5}, {\"label\": \"\\ud83d\\udcb0 10% Off\", \"color\": \"#DDA0DD\", \"startAngle\": 225.0, \"endAngle\": 270.0, \"midAngle\": 247.5}, {\"label\": \"\\ud83c\\udfae Bonus Round\", \"color\": \"#98D8C8\", \"startAngle\": 270.0, \"endAngle\": 315.0, \"midAngle\": 292.5}, {\"label\": \"\\ud83c\\udf40 Try Again\", \"color\": \"#F7DC6F\", \"startAngle\": 315.0, \"endAngle\": 360.0, \"midAngle\": 337.5}]", | |
| "rotation": 0 | |
| }, | |
| "repo_url": "https://huggingface.co/spaces/ysharma/spin-wheel", | |
| "python_code": "class SpinWheel(gr.HTML):\n \"\"\"\n An interactive prize wheel component with:\n - Smooth CSS spinning animation\n - Customizable segments with colors\n - Win detection with callbacks\n - Confetti celebration effect\n \"\"\"\n def __init__(\n self,\n value=None, # Currently selected/won prize (string)\n segments=None, # List of {\"label\": str, \"color\": str, \"weight\": int}\n segments_json=None, # JSON string of computed segments (for updates)\n rotation=0, # Current wheel rotation in degrees (persists position)\n **kwargs\n ):\n # Use provided segments or default\n if segments is None:\n segments = DEFAULT_SEGMENTS\n\n # Compute segment data if not provided as JSON\n if segments_json is None:\n segment_data = compute_segment_data(segments)\n segments_json = json.dumps(segment_data)\n\n super().__init__(\n value=value,\n segments_json=segments_json,\n rotation=rotation,\n html_template=HTML_TEMPLATE,\n css_template=CSS_TEMPLATE,\n js_on_load=JS_ON_LOAD,\n **kwargs\n )\n\n def api_info(self):\n return {\"type\": \"string\", \"description\": \"The label of the winning segment\"}\n" | |
| }, | |
| { | |
| "id": "star-rating", | |
| "name": "Star Rating", | |
| "description": "Click stars to set a rating from 1 to 5", | |
| "author": "gradio", | |
| "tags": [ | |
| "input", | |
| "rating", | |
| "stars" | |
| ], | |
| "category": "input", | |
| "html_template": "<h2>${label} rating:</h2>\n${Array.from({length: 5}, (_, i) => `<img class='${i < value ? '' : 'faded'}' src='https://upload.wikimedia.org/wikipedia/commons/d/df/Award-star-gold-3d.svg'>`).join('')}", | |
| "css_template": "img { height: 50px; display: inline-block; cursor: pointer; }\n.faded { filter: grayscale(100%); opacity: 0.3; }", | |
| "js_on_load": "const imgs = element.querySelectorAll('img');\nimgs.forEach((img, index) => {\n img.addEventListener('click', () => {\n props.value = index + 1;\n });\n});", | |
| "default_props": { | |
| "value": 3, | |
| "label": "Food" | |
| }, | |
| "python_code": "class StarRating(gr.HTML):\n def __init__(self, label, value=0, **kwargs):\n html_template = \"\"\"\n <h2>${label} rating:</h2>\n ${Array.from({length: 5}, (_, i) => `<img class='${i < value ? '' : 'faded'}' src='https://upload.wikimedia.org/wikipedia/commons/d/df/Award-star-gold-3d.svg'>`).join('')}\n \"\"\"\n css_template = \"\"\"\n img { height: 50px; display: inline-block; cursor: pointer; }\n .faded { filter: grayscale(100%); opacity: 0.3; }\n \"\"\"\n js_on_load = \"\"\"\n const imgs = element.querySelectorAll('img');\n imgs.forEach((img, index) => {\n img.addEventListener('click', () => {\n props.value = index + 1;\n });\n });\n \"\"\"\n super().__init__(\n value=value, label=label,\n html_template=html_template,\n css_template=css_template,\n js_on_load=js_on_load, **kwargs\n )\n\n def api_info(self):\n return {\"type\": \"integer\", \"minimum\": 0, \"maximum\": 5}" | |
| }, | |
| { | |
| "id": "button-set", | |
| "name": "Button Set", | |
| "description": "Multiple buttons that trigger events with click data", | |
| "author": "gradio", | |
| "tags": [ | |
| "input", | |
| "buttons", | |
| "events" | |
| ], | |
| "category": "input", | |
| "html_template": "<button id='A'>A</button>\n<button id='B'>B</button>\n<button id='C'>C</button>", | |
| "css_template": "button {\n padding: 10px 20px;\n background-color: #f97316;\n color: white;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n font-weight: 600;\n margin-right: 8px;\n transition: background 0.15s;\n}\nbutton:hover { background-color: #ea580c; }", | |
| "js_on_load": "const buttons = element.querySelectorAll('button');\nbuttons.forEach(button => {\n button.addEventListener('click', () => {\n trigger('click', {clicked: button.innerText});\n });\n});", | |
| "default_props": {}, | |
| "python_code": "button_set = gr.HTML(\n html_template=\"\"\"\n <button id='A'>A</button>\n <button id='B'>B</button>\n <button id='C'>C</button>\n \"\"\",\n css_template=\"\"\"\n button {\n padding: 10px 20px;\n background-color: #f97316;\n color: white; border: none;\n border-radius: 8px; cursor: pointer;\n }\n button:hover { background-color: #ea580c; }\n \"\"\",\n js_on_load=\"\"\"\n const buttons = element.querySelectorAll('button');\n buttons.forEach(button => {\n button.addEventListener('click', () => {\n trigger('click', {clicked: button.innerText});\n });\n });\n \"\"\"\n)\n\ndef on_button_click(evt: gr.EventData):\n return evt.clicked\n\nbutton_set.click(on_button_click, outputs=clicked_box)" | |
| }, | |
| { | |
| "id": "progress-bar", | |
| "name": "Progress Bar", | |
| "description": "Interactive progress bar - click the track to set progress", | |
| "author": "gradio", | |
| "tags": [ | |
| "display", | |
| "progress", | |
| "animation" | |
| ], | |
| "category": "display", | |
| "html_template": "<div class=\"progress-container\">\n <div class=\"progress-label\">${label}</div>\n <div class=\"progress-track\">\n <div class=\"progress-fill\" style=\"width: ${value}%\"></div>\n </div>\n <div class=\"progress-text\">${value}%</div>\n</div>", | |
| "css_template": ".progress-container { padding: 8px 0; }\n.progress-label { font-weight: 600; margin-bottom: 8px; font-size: 15px; }\n.progress-track { width: 100%; height: 24px; background: #e5e7eb; border-radius: 12px; overflow: hidden; cursor: pointer; }\n.progress-fill { height: 100%; background: linear-gradient(90deg, #f97316, #fb923c); border-radius: 12px; transition: width 0.4s ease; }\n.progress-text { margin-top: 6px; font-size: 14px; color: #6b7280; text-align: right; font-variant-numeric: tabular-nums; }", | |
| "js_on_load": "const track = element.querySelector('.progress-track');\ntrack.addEventListener('click', (e) => {\n const rect = track.getBoundingClientRect();\n const pct = Math.round(((e.clientX - rect.left) / rect.width) * 100);\n props.value = Math.max(0, Math.min(100, pct));\n});", | |
| "default_props": { | |
| "value": 65, | |
| "label": "Upload Progress" | |
| }, | |
| "python_code": "progress = gr.HTML(\n value=65,\n label=\"Upload Progress\",\n html_template=\"\"\"\n <div class=\"progress-container\">\n <div class=\"progress-label\">${label}</div>\n <div class=\"progress-track\">\n <div class=\"progress-fill\" style=\"width: ${value}%\"></div>\n </div>\n <div class=\"progress-text\">${value}%</div>\n </div>\n \"\"\",\n css_template=\"\"\"\n .progress-track {\n width: 100%; height: 24px;\n background: #e5e7eb; border-radius: 12px;\n overflow: hidden; cursor: pointer;\n }\n .progress-fill {\n height: 100%;\n background: linear-gradient(90deg, #f97316, #fb923c);\n border-radius: 12px; transition: width 0.4s ease;\n }\n \"\"\",\n js_on_load=\"\"\"\n const track = element.querySelector('.progress-track');\n track.addEventListener('click', (e) => {\n const rect = track.getBoundingClientRect();\n const pct = Math.round(\n ((e.clientX - rect.left) / rect.width) * 100\n );\n props.value = Math.max(0, Math.min(100, pct));\n });\n \"\"\"\n)" | |
| }, | |
| { | |
| "id": "likert-scale", | |
| "name": "Likert Scale", | |
| "description": "Agreement scale from Strongly Disagree to Strongly Agree", | |
| "author": "gradio", | |
| "tags": [ | |
| "input", | |
| "survey", | |
| "scale" | |
| ], | |
| "category": "input", | |
| "html_template": "<div class=\"likert-container\">\n <div class=\"likert-question\">${question}</div>\n <div class=\"likert-scale\">\n ${['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'].map((label, i) => `\n <label class=\"likert-option ${value === i + 1 ? 'selected' : ''}\">\n <input type=\"radio\" name=\"likert\" value=\"${i + 1}\" ${value === i + 1 ? 'checked' : ''} />\n <span class=\"likert-dot\"></span>\n <span class=\"likert-label\">${label}</span>\n </label>\n `).join('')}\n </div>\n</div>", | |
| "css_template": ".likert-container { padding: 8px 0; }\n.likert-question { font-weight: 600; margin-bottom: 16px; font-size: 15px; }\n.likert-scale { display: flex; justify-content: space-between; gap: 4px; }\n.likert-option { display: flex; flex-direction: column; align-items: center; cursor: pointer; flex: 1; gap: 8px; }\n.likert-option input { display: none; }\n.likert-dot { width: 24px; height: 24px; border-radius: 50%; border: 2px solid #d1d5db; transition: all 0.2s; }\n.likert-option:hover .likert-dot { border-color: #f97316; }\n.likert-option.selected .likert-dot { background: #f97316; border-color: #f97316; }\n.likert-label { font-size: 11px; text-align: center; color: #6b7280; line-height: 1.3; }", | |
| "js_on_load": "const radios = element.querySelectorAll('input[type=\"radio\"]');\nradios.forEach(radio => {\n radio.addEventListener('change', () => {\n props.value = parseInt(radio.value);\n });\n});", | |
| "default_props": { | |
| "value": 0, | |
| "question": "This component is easy to use" | |
| }, | |
| "python_code": "class LikertScale(gr.HTML):\n def __init__(self, question=\"Rate this item\", value=0, **kwargs):\n html_template = \"\"\"\n <div class=\"likert-container\">\n <div class=\"likert-question\">${question}</div>\n <div class=\"likert-scale\">\n ${['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'].map((label, i) => `\n <label class=\"likert-option ${value === i + 1 ? 'selected' : ''}\">\n <input type=\"radio\" name=\"likert\" value=\"${i + 1}\" ${value === i + 1 ? 'checked' : ''} />\n <span class=\"likert-dot\"></span>\n <span class=\"likert-label\">${label}</span>\n </label>\n `).join('')}\n </div>\n </div>\n \"\"\"\n css_template = \"\"\"\n .likert-scale { display: flex; justify-content: space-between; }\n .likert-option { display: flex; flex-direction: column; align-items: center; cursor: pointer; }\n .likert-dot { width: 24px; height: 24px; border-radius: 50%; border: 2px solid #d1d5db; }\n .likert-option.selected .likert-dot { background: #f97316; border-color: #f97316; }\n \"\"\"\n js_on_load = \"\"\"\n const radios = element.querySelectorAll('input[type=\"radio\"]');\n radios.forEach(radio => {\n radio.addEventListener('change', () => {\n props.value = parseInt(radio.value);\n });\n });\n \"\"\"\n super().__init__(\n value=value, question=question,\n html_template=html_template,\n css_template=css_template,\n js_on_load=js_on_load, **kwargs\n )\n\n def api_info(self):\n return {\"type\": \"integer\", \"minimum\": 0, \"maximum\": 5}" | |
| }, | |
| { | |
| "id": "tag-input", | |
| "name": "Tag Input", | |
| "description": "Add and remove tags with keyboard input", | |
| "author": "gradio", | |
| "tags": [ | |
| "input", | |
| "tags", | |
| "text" | |
| ], | |
| "category": "input", | |
| "html_template": "<div class=\"tag-input-container\">\n <div class=\"tag-list\">\n ${(value || []).map((tag, i) => `\n <span class=\"tag-pill\">\n ${tag}\n <button class=\"tag-remove\" data-index=\"${i}\">×</button>\n </span>\n `).join('')}\n <input type=\"text\" class=\"tag-text-input\" placeholder=\"${(value || []).length === 0 ? 'Type a tag and press Enter...' : 'Add more...'}\" />\n </div>\n</div>", | |
| "css_template": ".tag-input-container { padding: 4px 0; }\n.tag-list { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; padding: 8px; border: 1px solid #e5e7eb; border-radius: 8px; min-height: 42px; }\n.tag-pill { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; background: #fff7ed; color: #ea580c; border-radius: 16px; font-size: 13px; font-weight: 500; border: 1px solid #fed7aa; }\n.tag-remove { background: none; border: none; color: #ea580c; cursor: pointer; font-size: 16px; padding: 0 2px; line-height: 1; opacity: 0.6; }\n.tag-remove:hover { opacity: 1; }\n.tag-text-input { border: none; outline: none; flex: 1; min-width: 120px; font-size: 14px; padding: 4px; background: transparent; }", | |
| "js_on_load": "const input = element.querySelector('.tag-text-input');\ninput.addEventListener('keydown', (e) => {\n if (e.key === 'Enter' && input.value.trim()) {\n e.preventDefault();\n const tags = [...(props.value || []), input.value.trim()];\n props.value = tags;\n input.value = '';\n }\n if (e.key === 'Backspace' && !input.value && props.value && props.value.length > 0) {\n props.value = props.value.slice(0, -1);\n }\n});\nelement.addEventListener('click', (e) => {\n const btn = e.target.closest('.tag-remove');\n if (!btn) return;\n const idx = parseInt(btn.dataset.index);\n const tags = [...(props.value || [])];\n tags.splice(idx, 1);\n props.value = tags;\n});", | |
| "default_props": { | |
| "value": [ | |
| "python", | |
| "gradio", | |
| "html" | |
| ] | |
| }, | |
| "python_code": "class TagInput(gr.HTML):\n def __init__(self, value=None, **kwargs):\n html_template = \"\"\"\n <div class=\"tag-input-container\">\n <div class=\"tag-list\">\n ${(value || []).map((tag, i) => `\n <span class=\"tag-pill\">\n ${tag}\n <button class=\"tag-remove\" data-index=\"${i}\">×</button>\n </span>\n `).join('')}\n <input type=\"text\" class=\"tag-text-input\"\n placeholder=\"Type a tag and press Enter...\" />\n </div>\n </div>\n \"\"\"\n css_template = \"\"\"\n .tag-list {\n display: flex; flex-wrap: wrap; gap: 6px;\n padding: 8px; border: 1px solid #e5e7eb;\n border-radius: 8px;\n }\n .tag-pill {\n padding: 4px 10px; background: #fff7ed;\n color: #ea580c; border-radius: 16px;\n font-size: 13px; border: 1px solid #fed7aa;\n }\n \"\"\"\n js_on_load = \"\"\"\n const input = element.querySelector('.tag-text-input');\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter' && input.value.trim()) {\n e.preventDefault();\n props.value = [...(props.value || []), input.value.trim()];\n input.value = '';\n }\n });\n element.addEventListener('click', (e) => {\n const btn = e.target.closest('.tag-remove');\n if (!btn) return;\n const idx = parseInt(btn.dataset.index);\n const tags = [...(props.value || [])];\n tags.splice(idx, 1);\n props.value = tags;\n });\n \"\"\"\n super().__init__(\n value=value or [],\n html_template=html_template,\n css_template=css_template,\n js_on_load=js_on_load, **kwargs\n )\n\n def api_info(self):\n return {\"type\": \"array\", \"items\": {\"type\": \"string\"}}" | |
| }, | |
| { | |
| "id": "colored-checkbox-group", | |
| "name": "Colored Checkbox Group", | |
| "description": "Multi-select checkbox group with custom colors per option", | |
| "author": "gradio", | |
| "tags": [ | |
| "input", | |
| "checkbox", | |
| "color" | |
| ], | |
| "category": "input", | |
| "html_template": "<div class=\"colored-checkbox-container\">\n ${label ? `<label class=\"container-label\">${label}</label>` : ''}\n <div class=\"colored-checkbox-group\">\n ${choices.map((choice, i) => `\n <label class=\"checkbox-label\" data-color-index=\"${i}\">\n <input type=\"checkbox\" value=\"${choice}\" ${(value || []).includes(choice) ? 'checked' : ''}>\n ${choice}\n </label>\n `).join('')}\n </div>\n</div>", | |
| "css_template": ".colored-checkbox-container { border: 1px solid #e5e7eb; border-radius: 12px; padding: 16px; }\n.container-label { display: block; margin-bottom: 12px; font-weight: 600; }\n.colored-checkbox-group { display: flex; flex-direction: column; gap: 6px; }\n.checkbox-label { display: flex; align-items: center; cursor: pointer; padding: 4px 0; }\n.checkbox-label input { margin-right: 8px; }\n${choices.map((choice, i) => `.checkbox-label[data-color-index=\"${i}\"] { color: ${colors[i]}; }`).join(' ')}", | |
| "js_on_load": "const checkboxes = element.querySelectorAll('input[type=\"checkbox\"]');\ncheckboxes.forEach(checkbox => {\n checkbox.addEventListener('change', () => {\n props.value = Array.from(checkboxes)\n .filter(cb => cb.checked)\n .map(cb => cb.value);\n });\n});", | |
| "default_props": { | |
| "value": [], | |
| "choices": [ | |
| "Apple", | |
| "Banana", | |
| "Cherry" | |
| ], | |
| "colors": [ | |
| "#dc2626", | |
| "#eab308", | |
| "#dc2626" | |
| ], | |
| "label": "Select fruits" | |
| }, | |
| "python_code": "class ColoredCheckboxGroup(gr.HTML):\n def __init__(self, choices, *, value=None, colors, label=None, **kwargs):\n html_template = \"\"\"\n <div class=\"colored-checkbox-container\">\n ${label ? `<label>${label}</label>` : ''}\n <div class=\"colored-checkbox-group\">\n ${choices.map((choice, i) => `\n <label class=\"checkbox-label\" data-color-index=\"${i}\">\n <input type=\"checkbox\" value=\"${choice}\"\n ${(value || []).includes(choice) ? 'checked' : ''}>\n ${choice}\n </label>\n `).join('')}\n </div>\n </div>\n \"\"\"\n css_template = \"\"\"\n .colored-checkbox-group { display: flex; flex-direction: column; gap: 6px; }\n .checkbox-label { display: flex; align-items: center; cursor: pointer; }\n ${choices.map((choice, i) =>\n `.checkbox-label[data-color-index=\"${i}\"] { color: ${colors[i]}; }`\n ).join(' ')}\n \"\"\"\n js_on_load = \"\"\"\n const checkboxes = element.querySelectorAll('input[type=\"checkbox\"]');\n checkboxes.forEach(checkbox => {\n checkbox.addEventListener('change', () => {\n props.value = Array.from(checkboxes)\n .filter(cb => cb.checked)\n .map(cb => cb.value);\n });\n });\n \"\"\"\n super().__init__(\n value=value or [], choices=choices,\n colors=colors, label=label,\n html_template=html_template,\n css_template=css_template,\n js_on_load=js_on_load, **kwargs\n )" | |
| }, | |
| { | |
| "id": "todo-list", | |
| "name": "Todo List", | |
| "description": "Interactive checklist with strikethrough on completed items", | |
| "author": "gradio", | |
| "tags": [ | |
| "form", | |
| "todo", | |
| "checklist" | |
| ], | |
| "category": "form", | |
| "html_template": "<h2>Todo List</h2>\n<ul>\n ${value.map((item, index) => `\n <li style=\"text-decoration: ${completed.includes(index) ? 'line-through' : 'none'}; list-style: none; padding: 6px 0;\">\n <input type=\"checkbox\" ${completed.includes(index) ? 'checked' : ''} data-index=\"${index}\" />\n ${item}\n </li>\n `).join('')}\n</ul>", | |
| "css_template": "h2 { font-size: 18px; font-weight: 700; margin-bottom: 8px; }\nul { padding: 0; margin: 0; }\nli { font-size: 14px; transition: opacity 0.2s; }\nli input { margin-right: 8px; cursor: pointer; }", | |
| "js_on_load": "const checkboxes = element.querySelectorAll('input[type=\"checkbox\"]');\ncheckboxes.forEach(checkbox => {\n checkbox.addEventListener('change', () => {\n const index = parseInt(checkbox.getAttribute('data-index'));\n let completed = props.completed || [];\n if (checkbox.checked) {\n if (!completed.includes(index)) {\n completed.push(index);\n }\n } else {\n completed = completed.filter(i => i !== index);\n }\n props.completed = [...completed];\n });\n});", | |
| "default_props": { | |
| "value": [ | |
| "Buy groceries", | |
| "Walk the dog", | |
| "Read a book", | |
| "Write code" | |
| ], | |
| "completed": [ | |
| 1 | |
| ] | |
| }, | |
| "python_code": "class TodoList(gr.HTML):\n def __init__(self, value=None, completed=None, **kwargs):\n html_template = \"\"\"\n <h2>Todo List</h2>\n <ul>\n ${value.map((item, index) => `\n <li style=\"text-decoration: ${completed.includes(index) ? 'line-through' : 'none'};\">\n <input type=\"checkbox\" ${completed.includes(index) ? 'checked' : ''} data-index=\"${index}\" />\n ${item}\n </li>\n `).join('')}\n </ul>\n \"\"\"\n js_on_load = \"\"\"\n const checkboxes = element.querySelectorAll('input[type=\"checkbox\"]');\n checkboxes.forEach(checkbox => {\n checkbox.addEventListener('change', () => {\n const index = parseInt(checkbox.getAttribute('data-index'));\n let completed = props.completed || [];\n if (checkbox.checked) {\n if (!completed.includes(index)) completed.push(index);\n } else {\n completed = completed.filter(i => i !== index);\n }\n props.completed = [...completed];\n });\n });\n \"\"\"\n super().__init__(\n value=value or [], completed=completed or [],\n html_template=html_template,\n js_on_load=js_on_load, **kwargs\n )" | |
| }, | |
| { | |
| "id": "audio-gallery", | |
| "name": "Audio Gallery", | |
| "description": "Grid of audio players with waveform visualization and selection", | |
| "author": "gradio", | |
| "tags": [ | |
| "display", | |
| "audio", | |
| "gallery", | |
| "media" | |
| ], | |
| "category": "display", | |
| "html_template": "<div class=\"audio-gallery-container\">\n ${label ? `<label class=\"container-label\">${label}</label>` : ''}\n <div class=\"audio-gallery-grid\" style=\"grid-template-columns: repeat(${columns}, 1fr);\">\n ${audio_urls.map((url, i) => `\n <div class=\"audio-item\" data-index=\"${i}\">\n <div class=\"audio-label\">${labels && labels[i] ? labels[i] : 'Audio ' + (i + 1)}</div>\n <canvas class=\"waveform-canvas\" data-url=\"${url}\" width=\"300\" height=\"80\"></canvas>\n <audio src=\"${url}\" preload=\"metadata\" ${value === url ? 'data-selected=\"true\"' : ''}></audio>\n <div class=\"audio-controls\">\n <button class=\"play-btn\">\u25b6</button>\n <div class=\"time-display\">0:00</div>\n </div>\n </div>\n `).join('')}\n </div>\n</div>", | |
| "css_template": ".audio-gallery-container { padding: 8px; }\n.container-label { display: block; margin-bottom: 12px; font-weight: 600; }\n.audio-gallery-grid { display: grid; gap: 12px; }\n.audio-item { border: 2px solid #e5e7eb; border-radius: 10px; padding: 12px; cursor: pointer; transition: all 0.2s; }\n.audio-item:hover { border-color: #f97316; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }\n.audio-item[data-selected=\"true\"] { border-color: #f97316; background-color: #fff7ed; }\n.audio-label { margin-bottom: 8px; text-align: center; font-size: 13px; font-weight: 500; }\n.waveform-canvas { width: 100%; height: 80px; background: #f9fafb; border-radius: 6px; margin-bottom: 8px; }\n.audio-controls { display: flex; align-items: center; gap: 8px; }\n.play-btn { width: 32px; height: 32px; border-radius: 50%; border: none; background: #f97316; color: white; cursor: pointer; font-size: 14px; }\n.play-btn:hover { opacity: 0.8; }\n.time-display { font-size: 12px; color: #6b7280; }", | |
| "js_on_load": "const audioItems = element.querySelectorAll('.audio-item');\naudioItems.forEach((item, index) => {\n const canvas = item.querySelector('.waveform-canvas');\n const audio = item.querySelector('audio');\n const playBtn = item.querySelector('.play-btn');\n const timeDisplay = item.querySelector('.time-display');\n const ctx = canvas.getContext('2d');\n drawWaveform(canvas, ctx);\n item.addEventListener('click', (e) => {\n if (e.target === playBtn) return;\n audioItems.forEach(i => i.removeAttribute('data-selected'));\n item.setAttribute('data-selected', 'true');\n props.value = audio.src;\n });\n playBtn.addEventListener('click', (e) => {\n e.stopPropagation();\n if (audio.paused) {\n element.querySelectorAll('audio').forEach(a => a.pause());\n element.querySelectorAll('.play-btn').forEach(b => b.textContent = '\u25b6');\n audio.play();\n playBtn.textContent = '\u23f8';\n } else {\n audio.pause();\n playBtn.textContent = '\u25b6';\n }\n });\n audio.addEventListener('timeupdate', () => {\n const currentTime = Math.floor(audio.currentTime);\n const minutes = Math.floor(currentTime / 60);\n const seconds = currentTime % 60;\n timeDisplay.textContent = minutes + ':' + seconds.toString().padStart(2, '0');\n const progress = audio.currentTime / audio.duration;\n drawWaveform(canvas, ctx, progress);\n });\n audio.addEventListener('ended', () => {\n playBtn.textContent = '\u25b6';\n drawWaveform(canvas, ctx, 0);\n });\n});\nfunction drawWaveform(canvas, ctx, progress) {\n progress = progress || 0;\n const width = canvas.width;\n const height = canvas.height;\n const bars = 50;\n const barWidth = width / bars;\n ctx.clearRect(0, 0, width, height);\n for (let i = 0; i < bars; i++) {\n const barHeight = (Math.sin(i * 0.5) * 0.3 + 0.5) * height * 0.8;\n const x = i * barWidth;\n const y = (height - barHeight) / 2;\n ctx.fillStyle = i / bars < progress ? '#f97316' : '#d1d5db';\n ctx.fillRect(x, y, barWidth - 2, barHeight);\n }\n}", | |
| "default_props": { | |
| "value": null, | |
| "audio_urls": [ | |
| "https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav", | |
| "https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample-1-4.wav", | |
| "https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/audio/cantina.wav" | |
| ], | |
| "labels": [ | |
| "Sample 1", | |
| "Sample 2", | |
| "Cantina" | |
| ], | |
| "columns": 3, | |
| "label": "Select an audio file" | |
| }, | |
| "python_code": "class AudioGallery(gr.HTML):\n def __init__(self, audio_urls, *, value=None, labels=None,\n columns=3, label=None, **kwargs):\n html_template = \"\"\"\n <div class=\"audio-gallery-container\">\n ${label ? `<label>${label}</label>` : ''}\n <div class=\"audio-gallery-grid\"\n style=\"grid-template-columns: repeat(${columns}, 1fr);\">\n ${audio_urls.map((url, i) => `\n <div class=\"audio-item\" data-index=\"${i}\">\n <div class=\"audio-label\">\n ${labels && labels[i] ? labels[i] : 'Audio ' + (i+1)}\n </div>\n <canvas class=\"waveform-canvas\" width=\"300\" height=\"80\"></canvas>\n <audio src=\"${url}\" preload=\"metadata\"></audio>\n <div class=\"audio-controls\">\n <button class=\"play-btn\">\u25b6</button>\n <div class=\"time-display\">0:00</div>\n </div>\n </div>\n `).join('')}\n </div>\n </div>\n \"\"\"\n super().__init__(\n value=value, audio_urls=audio_urls,\n labels=labels, columns=columns, label=label,\n html_template=html_template,\n css_template=CSS_TEMPLATE,\n js_on_load=JS_ON_LOAD, **kwargs\n )" | |
| }, | |
| { | |
| "id": "kanban-board", | |
| "name": "Kanban Board", | |
| "description": "Drag-and-drop Kanban board with inline editing, priority labels, and search", | |
| "author": "gradio", | |
| "tags": [ | |
| "input", | |
| "kanban", | |
| "drag-drop", | |
| "project-management" | |
| ], | |
| "category": "input", | |
| "html_template": "<div class=\"kanban-wrapper\">\n <div class=\"kanban-header\">\n <h2>${board_title}</h2>\n <div class=\"header-right\">\n <div class=\"search-box\">\n <span class=\"search-icon\">\ud83d\udd0d</span>\n <input type=\"text\" class=\"search-input\" placeholder=\"Search cards...\" />\n </div>\n <div class=\"header-stats\">\n ${(() => {\n const cols = (value && value.columns) || [];\n const total = cols.reduce((sum, col) => sum + col.cards.length, 0);\n const done = cols.find(c => c.id === 'done');\n const doneCount = done ? done.cards.length : 0;\n const pct = total > 0 ? Math.round((doneCount / total) * 100) : 0;\n return '<span class=\"stat-pill\">\ud83d\udcca ' + total + ' tasks</span>' +\n '<span class=\"stat-pill done-pill\">\u2705 ' + doneCount + ' done (' + pct + '%)</span>';\n })()}\n </div>\n </div>\n </div>\n <div class=\"kb-progress-track\">\n ${(() => {\n const cols = (value && value.columns) || [];\n const total = cols.reduce((sum, col) => sum + col.cards.length, 0);\n const done = cols.find(c => c.id === 'done');\n const doneCount = done ? done.cards.length : 0;\n const pct = total > 0 ? Math.round((doneCount / total) * 100) : 0;\n return '<div class=\"kb-progress-bar\" style=\"width: ' + pct + '%\"></div>';\n })()}\n </div>\n <div class=\"kanban-board\">\n ${((value && value.columns) || []).map((col, colIdx) => `\n <div class=\"kanban-column ${col.collapsed ? 'collapsed' : ''}\" data-col-idx=\"${colIdx}\" data-col-id=\"${col.id}\">\n <div class=\"column-header\" style=\"border-top: 3px solid ${col.color}\">\n <div class=\"col-header-left\">\n <button class=\"collapse-btn\" data-col-idx=\"${colIdx}\">${col.collapsed ? '\u25b6' : '\u25bc'}</button>\n <span class=\"col-title\">${col.title}</span>\n </div>\n <span class=\"col-count\" style=\"background: ${col.color}22; color: ${col.color}\">${col.cards.length}</span>\n </div>\n <div class=\"card-list ${col.collapsed ? 'hidden' : ''}\" data-col-idx=\"${colIdx}\">\n ${col.cards.map((card, cardIdx) => `\n <div class=\"kanban-card\" draggable=\"true\" data-col-idx=\"${colIdx}\" data-card-idx=\"${cardIdx}\" data-card-id=\"${card.id}\">\n <div class=\"card-priority priority-${card.priority}\"></div>\n <div class=\"card-content\">\n <div class=\"card-text\" data-col-idx=\"${colIdx}\" data-card-idx=\"${cardIdx}\">${card.text}</div>\n <div class=\"card-footer\">\n <div class=\"card-tags\">\n ${(card.tags || []).map(t => '<span class=\"kb-tag\">' + t + '</span>').join('')}\n </div>\n <div class=\"card-actions\">\n <button class=\"priority-cycle\" data-col-idx=\"${colIdx}\" data-card-idx=\"${cardIdx}\" title=\"Cycle priority\">\n ${card.priority === 'high' ? '\ud83d\udd34' : card.priority === 'medium' ? '\ud83d\udfe1' : '\ud83d\udfe2'}\n </button>\n <button class=\"delete-card\" data-col-idx=\"${colIdx}\" data-card-idx=\"${cardIdx}\" title=\"Delete card\">\u2715</button>\n </div>\n </div>\n </div>\n </div>\n `).join('')}\n </div>\n <div class=\"add-card-area ${col.collapsed ? 'hidden' : ''}\">\n <input type=\"text\" class=\"add-card-input\" data-col-idx=\"${colIdx}\" placeholder=\"+ Add a card\u2026 \u23ce\" />\n </div>\n </div>\n `).join('')}\n </div>\n</div>", | |
| "css_template": ".kanban-wrapper {\n background: linear-gradient(135deg, #0f172a 0%, #1a1a2e 100%);\n border-radius: 16px;\n padding: 24px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n color: #e2e8f0;\n overflow-x: auto;\n}\n.kanban-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; flex-wrap: wrap; gap: 12px; }\n.kanban-header h2 { margin: 0; font-size: 22px; color: #f8fafc; letter-spacing: -0.3px; }\n.header-right { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }\n.search-box { display: flex; align-items: center; background: rgba(255,255,255,0.06); border: 1px solid #334155; border-radius: 10px; padding: 4px 12px; transition: all 0.2s; }\n.search-box:focus-within { border-color: #6366f1; background: rgba(99, 102, 241, 0.06); }\n.search-icon { font-size: 13px; margin-right: 6px; }\n.search-input { background: none; border: none; color: #e2e8f0; font-size: 13px; outline: none; width: 140px; }\n.search-input::placeholder { color: #475569; }\n.header-stats { display: flex; gap: 8px; }\n.stat-pill { background: rgba(255,255,255,0.08); padding: 5px 14px; border-radius: 12px; font-size: 13px; color: #94a3b8; font-weight: 500; }\n.done-pill { color: #10b981; }\n.kb-progress-track { height: 4px; background: rgba(255,255,255,0.08); border-radius: 4px; margin-bottom: 20px; overflow: hidden; }\n.kb-progress-bar { height: 100%; background: linear-gradient(90deg, #6366f1, #10b981); border-radius: 4px; transition: width 0.5s ease; }\n.kanban-board { display: flex; gap: 16px; min-height: 400px; padding-bottom: 8px; }\n.kanban-column { background: #1e293b; border-radius: 12px; min-width: 270px; max-width: 310px; flex: 1; display: flex; flex-direction: column; transition: min-width 0.3s, max-width 0.3s; }\n.kanban-column.collapsed { min-width: 60px; max-width: 60px; }\n.column-header { padding: 14px 14px 10px; display: flex; justify-content: space-between; align-items: center; border-radius: 12px 12px 0 0; user-select: none; }\n.col-header-left { display: flex; align-items: center; gap: 8px; }\n.collapse-btn { background: none; border: none; color: #64748b; cursor: pointer; font-size: 10px; padding: 2px 4px; border-radius: 4px; transition: color 0.2s; }\n.collapse-btn:hover { color: #e2e8f0; }\n.col-title { font-weight: 600; font-size: 14px; white-space: nowrap; }\n.col-count { min-width: 26px; height: 26px; border-radius: 13px; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 600; }\n.card-list { flex: 1; padding: 6px 10px; min-height: 60px; transition: background 0.2s; }\n.card-list.hidden, .add-card-area.hidden { display: none; }\n.card-list.drag-over { background: rgba(99, 102, 241, 0.08); border-radius: 8px; }\n.kanban-card { background: #0f172a; border: 1px solid #334155; border-radius: 10px; padding: 12px 12px 12px 16px; margin-bottom: 8px; cursor: grab; transition: all 0.15s ease; position: relative; overflow: hidden; animation: cardIn 0.2s ease; }\n.kanban-card:hover { border-color: #6366f1; transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,0.3); }\n.kanban-card.dragging { opacity: 0.4; transform: rotate(2deg) scale(0.97); }\n.kanban-card.search-hidden { display: none; }\n.kanban-card.search-highlight { border-color: #f59e0b; box-shadow: 0 0 0 1px #f59e0b44; }\n.card-priority { width: 4px; height: 100%; position: absolute; left: 0; top: 0; border-radius: 10px 0 0 10px; }\n.priority-high { background: #ef4444; }\n.priority-medium { background: #f59e0b; }\n.priority-low { background: #10b981; }\n.card-content { padding-left: 4px; }\n.card-text { font-size: 13px; line-height: 1.5; color: #e2e8f0; cursor: text; border-radius: 4px; padding: 2px 4px; margin: -2px -4px; transition: background 0.15s; }\n.card-text:hover { background: rgba(255,255,255,0.04); }\n.card-text.editing { background: rgba(99, 102, 241, 0.1); outline: 1px solid #6366f1; min-height: 1.5em; }\n.card-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 10px; }\n.card-tags { display: flex; gap: 4px; flex-wrap: wrap; }\n.kb-tag { background: rgba(99, 102, 241, 0.15); color: #a5b4fc; padding: 2px 9px; border-radius: 10px; font-size: 11px; font-weight: 500; }\n.card-actions { display: flex; gap: 2px; opacity: 0; transition: opacity 0.15s; }\n.kanban-card:hover .card-actions { opacity: 1; }\n.priority-cycle, .delete-card { background: none; border: none; cursor: pointer; font-size: 13px; padding: 3px 6px; border-radius: 6px; transition: all 0.15s; color: #475569; }\n.delete-card:hover { color: #ef4444; background: rgba(239, 68, 68, 0.1); }\n.priority-cycle:hover { background: rgba(255,255,255,0.08); }\n.add-card-area { padding: 6px 10px 14px; }\n.add-card-input { width: 100%; background: rgba(255,255,255,0.04); border: 1px dashed #334155; border-radius: 10px; padding: 10px 14px; color: #94a3b8; font-size: 13px; outline: none; transition: all 0.2s; box-sizing: border-box; }\n.add-card-input:focus { border-color: #6366f1; border-style: solid; background: rgba(99, 102, 241, 0.05); color: #e2e8f0; }\n.add-card-input::placeholder { color: #475569; }\n@keyframes cardIn { from { opacity: 0; transform: translateY(-8px) scale(0.97); } to { opacity: 1; transform: translateY(0) scale(1); } }", | |
| "js_on_load": "let dragSrcColIdx = null;\nlet dragSrcCardIdx = null;\nelement.addEventListener('dragstart', (e) => {\n const card = e.target.closest('.kanban-card');\n if (!card) return;\n dragSrcColIdx = parseInt(card.dataset.colIdx);\n dragSrcCardIdx = parseInt(card.dataset.cardIdx);\n card.classList.add('dragging');\n e.dataTransfer.effectAllowed = 'move';\n});\nelement.addEventListener('dragend', (e) => {\n const card = e.target.closest('.kanban-card');\n if (card) card.classList.remove('dragging');\n element.querySelectorAll('.card-list').forEach(cl => cl.classList.remove('drag-over'));\n});\nelement.addEventListener('dragover', (e) => {\n e.preventDefault();\n const cardList = e.target.closest('.card-list');\n if (cardList) cardList.classList.add('drag-over');\n});\nelement.addEventListener('dragleave', (e) => {\n const cardList = e.target.closest('.card-list');\n if (cardList && !cardList.contains(e.relatedTarget)) {\n cardList.classList.remove('drag-over');\n }\n});\nelement.addEventListener('drop', (e) => {\n e.preventDefault();\n const cardList = e.target.closest('.card-list');\n if (!cardList || dragSrcColIdx === null) return;\n cardList.classList.remove('drag-over');\n const destColIdx = parseInt(cardList.dataset.colIdx);\n const nv = JSON.parse(JSON.stringify(props.value));\n const card = nv.columns[dragSrcColIdx].cards.splice(dragSrcCardIdx, 1)[0];\n const cardElements = cardList.querySelectorAll('.kanban-card:not(.dragging)');\n let insertIdx = nv.columns[destColIdx].cards.length;\n for (let i = 0; i < cardElements.length; i++) {\n const rect = cardElements[i].getBoundingClientRect();\n if (e.clientY < rect.top + rect.height / 2) { insertIdx = i; break; }\n }\n nv.columns[destColIdx].cards.splice(insertIdx, 0, card);\n props.value = nv;\n trigger('change');\n dragSrcColIdx = null;\n dragSrcCardIdx = null;\n});\nelement.addEventListener('click', (e) => {\n const delBtn = e.target.closest('.delete-card');\n if (!delBtn) return;\n e.stopPropagation();\n const colIdx = parseInt(delBtn.dataset.colIdx);\n const cardIdx = parseInt(delBtn.dataset.cardIdx);\n const nv = JSON.parse(JSON.stringify(props.value));\n nv.columns[colIdx].cards.splice(cardIdx, 1);\n props.value = nv;\n trigger('change');\n});\nelement.addEventListener('click', (e) => {\n const btn = e.target.closest('.priority-cycle');\n if (!btn) return;\n e.stopPropagation();\n const colIdx = parseInt(btn.dataset.colIdx);\n const cardIdx = parseInt(btn.dataset.cardIdx);\n const nv = JSON.parse(JSON.stringify(props.value));\n const card = nv.columns[colIdx].cards[cardIdx];\n const cycle = { low: 'medium', medium: 'high', high: 'low' };\n card.priority = cycle[card.priority] || 'low';\n props.value = nv;\n trigger('change');\n});\nelement.addEventListener('click', (e) => {\n const btn = e.target.closest('.collapse-btn');\n if (!btn) return;\n const colIdx = parseInt(btn.dataset.colIdx);\n const nv = JSON.parse(JSON.stringify(props.value));\n nv.columns[colIdx].collapsed = !nv.columns[colIdx].collapsed;\n props.value = nv;\n trigger('change');\n});\nelement.addEventListener('dblclick', (e) => {\n const textEl = e.target.closest('.card-text');\n if (!textEl) return;\n textEl.contentEditable = 'true';\n textEl.classList.add('editing');\n textEl.focus();\n const range = document.createRange();\n range.selectNodeContents(textEl);\n const sel = window.getSelection();\n sel.removeAllRanges();\n sel.addRange(range);\n});\nfunction commitEdit(textEl) {\n textEl.contentEditable = 'false';\n textEl.classList.remove('editing');\n const colIdx = parseInt(textEl.dataset.colIdx);\n const cardIdx = parseInt(textEl.dataset.cardIdx);\n const newText = textEl.innerText.trim();\n if (!newText) return;\n const nv = JSON.parse(JSON.stringify(props.value));\n nv.columns[colIdx].cards[cardIdx].text = newText;\n props.value = nv;\n trigger('change');\n}\nelement.addEventListener('blur', (e) => {\n if (e.target.classList && e.target.classList.contains('editing')) {\n commitEdit(e.target);\n }\n}, true);\nelement.addEventListener('keydown', (e) => {\n if (e.key === 'Enter' && e.target.classList.contains('editing')) {\n e.preventDefault();\n e.target.blur();\n return;\n }\n if (e.key === 'Enter' && e.target.classList.contains('add-card-input')) {\n const text = e.target.value.trim();\n if (!text) return;\n const colIdx = parseInt(e.target.dataset.colIdx);\n const nv = JSON.parse(JSON.stringify(props.value));\n nv.columns[colIdx].cards.push({\n id: String(Date.now()),\n text: text,\n priority: 'medium',\n tags: []\n });\n props.value = nv;\n e.target.value = '';\n trigger('change');\n }\n});\nelement.addEventListener('input', (e) => {\n if (!e.target.classList.contains('search-input')) return;\n const q = e.target.value.toLowerCase().trim();\n element.querySelectorAll('.kanban-card').forEach(card => {\n const text = card.querySelector('.card-text').innerText.toLowerCase();\n const tags = Array.from(card.querySelectorAll('.kb-tag')).map(t => t.innerText.toLowerCase()).join(' ');\n const match = !q || text.includes(q) || tags.includes(q);\n card.classList.toggle('search-hidden', !match);\n card.classList.toggle('search-highlight', !!q && match);\n });\n});", | |
| "default_props": { | |
| "board_title": "My Board", | |
| "value": { | |
| "columns": [ | |
| { | |
| "id": "todo", | |
| "title": "\ud83d\udccb To Do", | |
| "color": "#6366f1", | |
| "cards": [ | |
| { | |
| "id": "1", | |
| "text": "Research gr.HTML component", | |
| "priority": "high", | |
| "tags": [ | |
| "gradio" | |
| ] | |
| }, | |
| { | |
| "id": "2", | |
| "text": "Design the UI layout", | |
| "priority": "medium", | |
| "tags": [ | |
| "design" | |
| ] | |
| }, | |
| { | |
| "id": "3", | |
| "text": "Write documentation", | |
| "priority": "low", | |
| "tags": [ | |
| "docs" | |
| ] | |
| } | |
| ] | |
| }, | |
| { | |
| "id": "progress", | |
| "title": "\ud83d\udd28 In Progress", | |
| "color": "#f59e0b", | |
| "cards": [ | |
| { | |
| "id": "4", | |
| "text": "Build Kanban prototype", | |
| "priority": "high", | |
| "tags": [ | |
| "dev" | |
| ] | |
| } | |
| ] | |
| }, | |
| { | |
| "id": "review", | |
| "title": "\ud83d\udc40 Review", | |
| "color": "#8b5cf6", | |
| "cards": [] | |
| }, | |
| { | |
| "id": "done", | |
| "title": "\u2705 Done", | |
| "color": "#10b981", | |
| "cards": [ | |
| { | |
| "id": "5", | |
| "text": "Set up Gradio project", | |
| "priority": "medium", | |
| "tags": [ | |
| "setup" | |
| ] | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| }, | |
| "repo_url": "https://huggingface.co/spaces/ysharma/drag-and-drop-kanban-board/", | |
| "python_code": "class KanbanBoard(gr.HTML):\n \"\"\"A drag-and-drop Kanban board component.\"\"\"\n\n def __init__(self, value=None, board_title=\"My Board\", **kwargs):\n if value is None:\n value = {\n \"columns\": [\n {\n \"id\": \"todo\", \"title\": \"To Do\", \"color\": \"#6366f1\",\n \"cards\": [\n {\"id\": \"1\", \"text\": \"Research gr.HTML\", \"priority\": \"high\", \"tags\": [\"gradio\"]},\n {\"id\": \"2\", \"text\": \"Design UI layout\", \"priority\": \"medium\", \"tags\": [\"design\"]},\n ],\n },\n {\n \"id\": \"progress\", \"title\": \"In Progress\", \"color\": \"#f59e0b\",\n \"cards\": [\n {\"id\": \"3\", \"text\": \"Build prototype\", \"priority\": \"high\", \"tags\": [\"dev\"]},\n ],\n },\n {\"id\": \"review\", \"title\": \"Review\", \"color\": \"#8b5cf6\", \"cards\": []},\n {\n \"id\": \"done\", \"title\": \"Done\", \"color\": \"#10b981\",\n \"cards\": [\n {\"id\": \"4\", \"text\": \"Set up project\", \"priority\": \"medium\", \"tags\": [\"setup\"]},\n ],\n },\n ],\n }\n super().__init__(\n value=value, board_title=board_title,\n html_template=HTML_TEMPLATE,\n css_template=CSS_TEMPLATE,\n js_on_load=JS_ON_LOAD, **kwargs\n )\n\n def api_info(self):\n return {\"type\": \"object\", \"description\": \"Kanban board state\"}" | |
| } | |
| ] |