custom-html-gallery / components /spin-wheel.json
freddyaboulton's picture
Add manifest.json and individual component files
dcdc07a verified
{
"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
},
"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"
}