""" 🍅 Gamified Pomodoro Timer — Custom Gradio Component A beautiful Pomodoro timer where a pixel-art tree grows as you stay focused. Complete sessions to grow your forest! Built entirely with gr.HTML. """ import gradio as gr from datetime import datetime # ─── Constants ──────────────────────────────────────────────────── DURATIONS = { "focus": 25, "short_break": 5, "long_break": 15, } MODE_COLORS = { "focus": "#e74c3c", "short_break": "#2ecc71", "long_break": "#3498db", } TREE_THEMES = { "classic": {"trunk": "#8B5E3C", "crown": "#2ecc71", "crown_top": "#00b894", "fruit": "#e74c3c"}, "cherry": {"trunk": "#5D4037", "crown": "#F8BBD9", "crown_top": "#F48FB1", "fruit": "#E91E63"}, "autumn": {"trunk": "#6D4C41", "crown": "#FF9800", "crown_top": "#FFC107", "fruit": "#FF5722"}, "winter": {"trunk": "#455A64", "crown": "#B0BEC5", "crown_top": "#ECEFF1", "fruit": "#81D4FA"}, "sakura": {"trunk": "#4E342E", "crown": "#FCE4EC", "crown_top": "#F8BBD0", "fruit": "#EC407A"}, } # ─── Templates ──────────────────────────────────────────────────── HTML_TEMPLATE = """
${(() => { const remaining = Math.max(0, duration * 60 - (value?.elapsed || 0)); const mins = Math.floor(remaining / 60); const secs = remaining % 60; return String(mins).padStart(2, '0') + ':' + String(secs).padStart(2, '0'); })()}
${mode === 'focus' ? '🍅 Focus Time' : mode === 'short_break' ? '☕ Short Break' : '🌿 Long Break'}
${(() => { let particles = ''; const sessions = value?.sessions || 0; for (let i = 0; i < Math.min(sessions * 3, 30); i++) { const x = (i * 37 + 13) % 100; const y = (i * 23 + 7) % 60; const size = 1 + (i % 3); const delay = (i * 0.3) % 3; particles += '
'; } return particles; })()}
${(() => { const elapsed = value?.elapsed || 0; const sessions = value?.sessions || 0; const progress = Math.min(elapsed / (duration * 60), 1); const treeStage = Math.floor(progress * 5); const trees = []; // Previously completed session trees (small, in background) for (let i = 0; i < Math.min(sessions, 8); i++) { const x = 10 + (i * 11) % 80; trees.push('
'); } // Current growing tree (center) if (mode === 'focus') { const isIdle = elapsed === 0 && !value?.running; let treeHTML = '
'; if (isIdle) { // Show a full preview tree when idle so theme is visible treeHTML += '
'; treeHTML += '
'; treeHTML += '
'; treeHTML += '
'; treeHTML += '
'; treeHTML += '
'; treeHTML += '
'; treeHTML += '
'; treeHTML += '
Press Start to grow!
'; } else { // Show growing tree based on progress if (treeStage >= 1) treeHTML += '
'; if (treeStage >= 1) treeHTML += '
'; if (treeStage >= 2) treeHTML += '
'; if (treeStage >= 2) treeHTML += '
'; if (treeStage >= 3) treeHTML += '
'; if (treeStage >= 4) { treeHTML += '
'; treeHTML += '
'; treeHTML += '
'; } if (treeStage === 0) treeHTML += '
🌱
'; } treeHTML += '
'; trees.push(treeHTML); } else { // Show a resting indicator during breaks trees.push('
' + (mode === 'short_break' ? '☕' : '🌿') + '
'); } return trees.join(''); })()}
🌳 ${value?.sessions || 0} Trees Grown
⏱️ ${value?.total_minutes || 0} Minutes Focused
🏆 ${(() => { const s = value?.sessions || 0; if (s >= 20) return '🌟 Master'; if (s >= 12) return '🌿 Expert'; if (s >= 6) return '🌱 Growing'; if (s >= 1) return '🫘 Seedling'; return '💤 Start!'; })()} Rank
Today's Progress
${(() => { let dots = ''; for (let i = 0; i < 8; i++) { const filled = i < (value?.sessions || 0); dots += '
' + (filled ? '🌳' : '○') + '
'; } return dots; })()}
""" CSS_TEMPLATE = """ .pomo-container { background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%); border-radius: 16px; padding: 28px; font-family: 'Segoe UI', system-ui, sans-serif; color: #e0e0e0; text-align: center; max-width: 500px; margin: 0 auto; } .mode-tabs { display: flex; gap: 6px; justify-content: center; margin-bottom: 20px; flex-wrap: wrap; } .mode-btn { background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.15); color: #aaa; padding: 8px 16px; border-radius: 20px; cursor: pointer; font-size: 13px; transition: all 0.3s; } .mode-btn:hover { background: rgba(255,255,255,0.15); color: #fff; } .mode-btn.active { background: ${mode_color}; color: #fff; border-color: transparent; box-shadow: 0 0 15px ${mode_color}40; } .timer-ring-container { position: relative; width: 200px; height: 200px; margin: 0 auto 20px; } .timer-ring { width: 100%; height: 100%; transform: rotate(-90deg); } .ring-bg { fill: none; stroke: rgba(255,255,255,0.1); stroke-width: 6; } .ring-progress { fill: none; stroke: ${mode_color}; stroke-width: 6; stroke-linecap: round; transition: stroke-dashoffset 0.5s ease; filter: drop-shadow(0 0 8px ${mode_color}60); } .timer-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .time-remaining { font-size: 42px; font-weight: 700; font-variant-numeric: tabular-nums; color: #fff; letter-spacing: 2px; text-shadow: 0 0 20px ${mode_color}40; } .timer-label { font-size: 12px; color: #8899aa; margin-top: 4px; } .tree-scene { position: relative; height: 140px; margin: 16px 0; overflow: hidden; border-radius: 12px; box-shadow: inset 0 0 30px rgba(0,0,0,0.3); } .sky { position: absolute; inset: 0; background: linear-gradient(180deg, #0b0b2a 0%, #1a1a3e 60%, #2d4a22 100%); } .ground { position: absolute; bottom: 0; width: 100%; height: 25px; background: linear-gradient(180deg, #2d4a22, #1e3315); border-radius: 0 0 12px 12px; } .star { position: absolute; background: #fff; border-radius: 50%; animation: twinkle 2s infinite alternate; } @keyframes twinkle { 0% { opacity: 0.3; } 100% { opacity: 1; } } .completed-tree { position: absolute; bottom: 20px; transform: scale(0.6); opacity: 0.7; transition: all 0.3s; } .completed-tree:hover { transform: scale(0.75); opacity: 1; } .mini-trunk { width: 4px; height: 16px; background: ${trunk_color}; margin: 0 auto; } .mini-crown { width: 18px; height: 18px; background: ${crown_color}; border-radius: 50%; margin-top: -6px; margin-left: -7px; } .growing-tree { position: absolute; bottom: 22px; left: 50%; transform: translateX(-50%); animation: tree-sway 4s ease-in-out infinite; } @keyframes tree-sway { 0%, 100% { transform: translateX(-50%) rotate(0deg); } 25% { transform: translateX(-50%) rotate(1deg); } 75% { transform: translateX(-50%) rotate(-1deg); } } .seed { font-size: 24px; animation: seed-bounce 1s ease-in-out infinite; } @keyframes seed-bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-5px); } } .trunk { width: 8px; margin: 0 auto; background: ${trunk_color}; border-radius: 2px; transition: height 0.5s; } .t1 { height: 15px; } .t2 { height: 25px; } .t3 { height: 35px; } .t4 { height: 40px; } .branch-l, .branch-r { position: absolute; background: ${trunk_color}; height: 3px; border-radius: 2px; transition: all 0.5s; } .branch-l { transform: rotate(-30deg); transform-origin: right; } .branch-r { transform: rotate(30deg); transform-origin: left; } .b1 { width: 8px; top: -10px; } .b2 { width: 12px; top: -18px; } .b3 { width: 16px; top: -25px; } .b4 { width: 20px; top: -28px; } .branch-l.b1 { left: -6px; } .branch-r.b1 { left: 6px; } .branch-l.b2 { left: -10px; } .branch-r.b2 { left: 6px; } .branch-l.b3 { left: -14px; } .branch-r.b3 { left: 6px; } .branch-l.b4 { left: -18px; } .branch-r.b4 { left: 6px; } .crown { position: absolute; border-radius: 50%; background: radial-gradient(circle, ${crown_color}, ${crown_color}dd); left: 50%; transform: translateX(-50%); transition: all 0.5s; } .c2 { width: 30px; height: 28px; top: -38px; margin-left: 0; } .c3 { width: 40px; height: 36px; top: -50px; } .c4 { width: 48px; height: 42px; top: -58px; box-shadow: 0 0 20px ${crown_color}50; } .crown-top { position: absolute; border-radius: 50%; background: radial-gradient(circle, ${crown_top_color}, ${crown_top_color}dd); left: 50%; transform: translateX(-50%); transition: all 0.5s; } .crown-top.c3 { width: 22px; height: 20px; top: -60px; } .crown-top.c4 { width: 28px; height: 24px; top: -72px; } .fruit { position: absolute; width: 8px; height: 8px; background: ${fruit_color}; border-radius: 50%; box-shadow: 0 0 6px ${fruit_color}80; animation: fruit-bob 2s infinite alternate ease-in-out; } @keyframes fruit-bob { 0% { transform: translateY(0); } 100% { transform: translateY(-3px); } } .break-indicator { position: absolute; bottom: 35px; left: 50%; transform: translateX(-50%); font-size: 40px; animation: float 3s ease-in-out infinite; } .preview-label { position: absolute; bottom: -30px; left: 50%; transform: translateX(-50%); font-size: 10px; color: #8899aa; white-space: nowrap; background: rgba(0,0,0,0.5); padding: 2px 8px; border-radius: 8px; } @keyframes float { 0%, 100% { transform: translateX(-50%) translateY(0); } 50% { transform: translateX(-50%) translateY(-10px); } } .controls { display: flex; gap: 12px; justify-content: center; margin: 16px 0; } .ctrl-btn { padding: 12px 28px; border-radius: 25px; border: none; font-size: 15px; font-weight: 600; cursor: pointer; transition: all 0.3s; } .start-btn { background: ${mode_color}; color: #fff; box-shadow: 0 4px 15px ${mode_color}40; } .start-btn:hover { filter: brightness(1.2); transform: scale(1.05); } .reset-btn { background: rgba(255,255,255,0.1); color: #ccc; } .reset-btn:hover { background: rgba(255,255,255,0.2); } .stats-row { display: flex; justify-content: space-around; margin-top: 16px; padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.1); flex-wrap: wrap; gap: 8px; } .pomo-stat { display: flex; flex-direction: column; align-items: center; gap: 2px; } .pomo-stat-icon { font-size: 20px; } .pomo-stat-val { font-size: 18px; font-weight: 700; color: #fff; } .pomo-stat-lbl { font-size: 11px; color: #8899aa; } .streak-bar { margin-top: 16px; padding: 12px; background: rgba(255,255,255,0.05); border-radius: 10px; } .streak-label { font-size: 11px; color: #8899aa; margin-bottom: 8px; } .streak-dots { display: flex; justify-content: center; gap: 8px; } .streak-dot { width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; font-size: 14px; color: #555; transition: all 0.3s; } .streak-dot.filled { color: #fff; transform: scale(1.1); } """ JS_ON_LOAD = """ let interval = null; const startBtn = element.querySelector('#start-btn'); const resetBtn = element.querySelector('#reset-btn'); if (startBtn) { startBtn.addEventListener('click', () => { const val = {...(props.value || {elapsed: 0, running: false, sessions: 0, total_minutes: 0})}; if (val.running) { val.running = false; clearInterval(interval); interval = null; } else { val.running = true; interval = setInterval(() => { const v = {...(props.value || {})}; if (!v.running) { clearInterval(interval); interval = null; return; } v.elapsed = (v.elapsed || 0) + 1; const totalSeconds = props.duration * 60; if (v.elapsed >= totalSeconds) { v.running = false; v.elapsed = totalSeconds; if (props.mode === 'focus') { v.sessions = (v.sessions || 0) + 1; v.total_minutes = (v.total_minutes || 0) + props.duration; } clearInterval(interval); interval = null; trigger('submit'); } props.value = v; }, 1000); } props.value = val; }); } if (resetBtn) { resetBtn.addEventListener('click', () => { clearInterval(interval); interval = null; const v = {...(props.value || {})}; v.elapsed = 0; v.running = false; props.value = v; }); } // Event delegation for mode buttons element.addEventListener('click', (e) => { if (e.target && e.target.classList.contains('mode-btn')) { clearInterval(interval); interval = null; const newMode = e.target.dataset.mode; trigger('select', { mode: newMode }); } }); """ # ─── Component Class ────────────────────────────────────────────── class PomodoroTimer(gr.HTML): """A gamified Pomodoro timer with animated tree growth.""" def __init__( self, value=None, duration=25, mode="focus", tree_theme="classic", # Accept all derived props explicitly to avoid "multiple values" error mode_color=None, trunk_color=None, crown_color=None, crown_top_color=None, fruit_color=None, **kwargs, ): if value is None: value = {"elapsed": 0, "running": False, "sessions": 0, "total_minutes": 0} # Derive colors from theme if not explicitly provided colors = TREE_THEMES.get(tree_theme, TREE_THEMES["classic"]) mode_color = mode_color or MODE_COLORS.get(mode, "#e74c3c") trunk_color = trunk_color or colors["trunk"] crown_color = crown_color or colors["crown"] crown_top_color = crown_top_color or colors["crown_top"] fruit_color = fruit_color or colors["fruit"] super().__init__( value=value, duration=duration, mode=mode, tree_theme=tree_theme, mode_color=mode_color, trunk_color=trunk_color, crown_color=crown_color, crown_top_color=crown_top_color, fruit_color=fruit_color, html_template=HTML_TEMPLATE, css_template=CSS_TEMPLATE, js_on_load=JS_ON_LOAD, **kwargs, ) def api_info(self): return { "type": "object", "properties": { "elapsed": {"type": "integer"}, "running": {"type": "boolean"}, "sessions": {"type": "integer"}, "total_minutes": {"type": "integer"}, }, } # ─── Helper Functions (return gr.HTML, NOT PomodoroTimer) ───────── def _update_timer(value, duration, mode, tree_theme): """Safe update pattern: always return gr.HTML with props.""" colors = TREE_THEMES.get(tree_theme, TREE_THEMES["classic"]) mode_color = MODE_COLORS.get(mode, "#e74c3c") return gr.HTML( value=value, duration=int(duration), mode=mode, tree_theme=tree_theme, mode_color=mode_color, trunk_color=colors["trunk"], crown_color=colors["crown"], crown_top_color=colors["crown_top"], fruit_color=colors["fruit"], ) def _update_theme_only(tree_theme, mode): """Update just the tree theme colors.""" colors = TREE_THEMES.get(tree_theme, TREE_THEMES["classic"]) mode_color = MODE_COLORS.get(mode, "#e74c3c") return gr.HTML( tree_theme=tree_theme, mode_color=mode_color, trunk_color=colors["trunk"], crown_color=colors["crown"], crown_top_color=colors["crown_top"], fruit_color=colors["fruit"], ) # ─── App ────────────────────────────────────────────────────────── with gr.Blocks(title="🍅 Pomodoro Forest") as demo: gr.Markdown( """ # 🍅 Pomodoro Forest *Stay focused. Grow trees. Build your forest.* Start a focus session and watch your tree grow from seed to full bloom! Complete sessions to fill your forest with trees. Take breaks between sessions. """ ) # State current_mode = gr.State("focus") session_data = gr.State({"elapsed": 0, "running": False, "sessions": 0, "total_minutes": 0}) with gr.Row(): with gr.Column(scale=3): timer = PomodoroTimer( value={"elapsed": 0, "running": False, "sessions": 0, "total_minutes": 0}, duration=25, mode="focus", tree_theme="classic", ) with gr.Column(scale=1): gr.Markdown("### ⚙️ Settings") tree_theme = gr.Dropdown( choices=list(TREE_THEMES.keys()), value="classic", label="🌳 Tree Theme", ) focus_dur = gr.Slider(1, 60, value=25, step=1, label="🍅 Focus (min)") short_dur = gr.Slider(1, 15, value=5, step=1, label="☕ Short Break (min)") long_dur = gr.Slider(5, 30, value=15, step=5, label="🌿 Long Break (min)") gr.Markdown("---") log = gr.Textbox(label="📋 Session Log", interactive=False, lines=4) # ─── Event Handlers ─────────────────────────────────────────── def handle_mode_select(evt: gr.EventData, timer_val, focus_d, short_d, long_d, theme): """Handle mode button clicks via the 'select' event.""" # Access the custom event data safely try: new_mode = evt._data.get("mode", "focus") if evt._data else "focus" except: new_mode = "focus" durations = {"focus": focus_d, "short_break": short_d, "long_break": long_d} dur = durations.get(new_mode, 25) new_val = {**timer_val, "elapsed": 0, "running": False} timestamp = datetime.now().strftime("%H:%M") log_msg = f"[{timestamp}] Switched to {new_mode.replace('_', ' ').title()} ({int(dur)} min)" return ( _update_timer(new_val, dur, new_mode, theme), new_mode, new_val, log_msg, ) # Use 'select' event for mode changes (triggered from JS) timer.select( fn=handle_mode_select, inputs=[timer, focus_dur, short_dur, long_dur, tree_theme], outputs=[timer, current_mode, session_data, log], ) def handle_complete(timer_val, mode, focus_d, short_d, long_d, theme): """Handle session completion.""" sessions = timer_val.get("sessions", 0) total = timer_val.get("total_minutes", 0) timestamp = datetime.now().strftime("%H:%M") if mode == "focus": # After every 4 focus sessions, suggest a long break if sessions % 4 == 0 and sessions > 0: next_mode = "long_break" next_dur = long_d else: next_mode = "short_break" next_dur = short_d msg = f"[{timestamp}] 🌳 Tree #{sessions} grown! {total} min total. Time for a {next_mode.replace('_', ' ')}!" else: next_mode = "focus" next_dur = focus_d msg = f"[{timestamp}] Break complete! Ready to grow tree #{sessions + 1}." new_val = {**timer_val, "elapsed": 0, "running": False} return ( _update_timer(new_val, next_dur, next_mode, theme), next_mode, new_val, msg, ) timer.submit( fn=handle_complete, inputs=[timer, current_mode, focus_dur, short_dur, long_dur, tree_theme], outputs=[timer, current_mode, session_data, log], ) def handle_theme_change(theme, mode): """Handle tree theme dropdown change.""" return _update_theme_only(theme, mode) tree_theme.change( fn=handle_theme_change, inputs=[tree_theme, current_mode], outputs=timer, ) def handle_duration_change(focus_d, short_d, long_d, mode, timer_val, theme): """Update duration when sliders change (only if timer is stopped).""" if timer_val.get("running", False): # Don't change duration while running return gr.HTML() # No update durations = {"focus": focus_d, "short_break": short_d, "long_break": long_d} dur = durations.get(mode, 25) new_val = {**timer_val, "elapsed": 0} return _update_timer(new_val, dur, mode, theme) for slider in [focus_dur, short_dur, long_dur]: slider.release( fn=handle_duration_change, inputs=[focus_dur, short_dur, long_dur, current_mode, timer, tree_theme], outputs=timer, ) if __name__ == "__main__": demo.launch(theme=gr.themes.Citrus(primary_hue="red"))