diff --git "a/static/app.js" "b/static/app.js" --- "a/static/app.js" +++ "b/static/app.js" @@ -1,60 +1,146 @@ 'use strict'; -const $ = s => document.querySelector(s), app = $('#app'); +const $ = s => document.querySelector(s), $$ = s => document.querySelectorAll(s), app = $('#app'); const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); -let TOK = localStorage.getItem('ember.tok'), ME = JSON.parse(localStorage.getItem('ember.me') || 'null'), deferredPrompt = null; +let TOK = localStorage.getItem('ember.tok'), ME = JSON.parse(localStorage.getItem('ember.me') || 'null'), deferredPrompt = null, CH = []; const pad = n => String(n).padStart(2, '0'); const iso = d => `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`; const TODAY = () => iso(new Date()); const addD = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; }; -const COLORS = ['#f2c46d','#ff7a3d','#ff5d7a','#c77dff','#6c8cff','#4cc9f0','#3ddc97','#e9e4d8']; -const ICONS = ['πŸ‹οΈ','πŸ“š','🧘','πŸ™','πŸƒ','πŸ’§','πŸ₯—','😴','✍️','🎸','🧠','πŸ’Š','🚭','πŸŒ…','🚢','🧹','πŸ’»','🎨','πŸ“΅','🌿','πŸ•Œ','πŸ“–','❀️','✨']; + +/* ---------- icon set (custom line icons, no emoji) ---------- */ +const P = { + dumbbell:'M6 7v10M18 7v10M3 9.5v5M21 9.5v5M6 12h12', book:'M4 4.5A2.5 2.5 0 0 1 6.5 2H20v16H6.5A2.5 2.5 0 0 0 4 20.5zM20 18v4H6.5A2.5 2.5 0 0 1 4 19.5', + lotus:'M12 20c-4 0-8-2-9-6 3 0 6 1 9 4 3-3 6-4 9-4-1 4-5 6-9 6zM12 18c-2-2-3-5-3-8 1 0 2.5 1 3 2 .5-1 2-2 3-2 0 3-1 6-3 8zM12 10V5', pray:'M12 3v8M9 6l-3 6v5l3 4h3M15 6l3 6v5l-3 4h-3', + run:'M14 3.5a1.5 1.5 0 1 0 3 0 1.5 1.5 0 1 0-3 0M5 21l4-6 3 2 1-5 3 3h3M9 11l2-3h4l-2 4', drop:'M12 3s6 6.5 6 11a6 6 0 0 1-12 0c0-4.5 6-11 6-11z', + leaf:'M5 19c0-8 5-14 15-14 0 10-6 15-14 15M5 19l8-8', moon:'M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z', pen:'M4 20h4L19 9l-4-4L4 16v4zM13.5 6.5l4 4', + music:'M9 18V5l11-2v13M9 18a3 3 0 1 1-6 0 3 3 0 0 1 6 0zM20 16a3 3 0 1 1-6 0 3 3 0 0 1 6 0z', brain:'M9 4a3 3 0 0 0-3 3 3 3 0 0 0-2 5 3 3 0 0 0 2 5 3 3 0 0 0 6 1V5a2 2 0 0 0-3-1zM15 4a3 3 0 0 1 3 3 3 3 0 0 1 2 5 3 3 0 0 1-2 5 3 3 0 0 1-6 1', + pill:'M10.5 3.5a5 5 0 0 1 7 7l-7 7a5 5 0 0 1-7-7zM7 10l7 7', sun:'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4', + walk:'M12 2.5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 1 0 0-3M10 21l2-6-2-3 1-4 4 3 3 1M8 13l2-5M14 15l2 6', code:'M8 7l-5 5 5 5M16 7l5 5-5 5M14 4l-4 16', + palette:'M12 3a9 9 0 1 0 0 18c1.5 0 2-1 2-2s-1-2 0-3h3a4 4 0 0 0 4-4c0-5-4-9-9-9zM7.5 11h.01M10 7h.01M15 7h.01', nophone:'M8 3h8a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zM3 3l18 18', + heart:'M12 20s-8-4.5-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 9c0 6.5-8 11-8 11z', spark:'M12 3l2 6.5L20.5 12 14 14l-2 7-2-7-6.5-2L10 9.5z', + star:'M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z', trophy:'M8 4h8v6a4 4 0 0 1-8 0V4zM8 6H4a3 3 0 0 0 4 4M16 6h4a3 3 0 0 1-4 4M12 14v4M8 21h8M9 18h6', + flame:'M12 3c1 3 5 5 5 10a5 5 0 0 1-10 0c0-2 1-3 2-4 0 2 1 3 2 3 0-3-1-6 1-9z', crown:'M3 8l4 4 5-7 5 7 4-4-2 11H5z', bell:'M6 16v-5a6 6 0 0 1 12 0v5l2 2H4zM10 21h4', + ban:'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM5.6 5.6l12.8 12.8', bolt:'M13 2L4 14h7l-1 8 9-12h-7z', infinity:'M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z', + shield:'M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z', lock:'M6 11h12v10H6zM8 11V7a4 4 0 0 1 8 0v4', download:'M12 3v12M7 10l5 5 5-5M5 21h14', logout:'M15 4h4v16h-4M10 8l-4 4 4 4M6 12h11', + trash:'M4 7h16M9 7V4h6v3M6 7l1 14h10l1-14', clock:'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l3 2', share:'M12 3v12M7 8l5-5 5 5M5 14v6h14v-6', snow:'M12 2v20M4 7l16 10M20 7L4 17', + cloud:'M7 18a5 5 0 1 1 1-9.9A6 6 0 0 1 19.5 10 4 4 0 0 1 18 18z', chart:'M4 20V10M10 20V4M16 20v-7M22 20H2', target:'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10zM12 11a1 1 0 1 0 0 2 1 1 0 0 0 0-2z', + calendar:'M4 6h16v15H4zM4 10h16M8 3v4M16 3v4', users:'M9 4.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7zM2.5 20c.8-4 3.4-6 6.5-6s5.7 2 6.5 6M16 4.5a3.5 3.5 0 0 1 0 7M18 14c2 .6 3.2 2.6 3.6 6', + sound:'M4 9v6h4l5 4V5L8 9zM16 9a4 4 0 0 1 0 6M19 6a8 8 0 0 1 0 12', install:'M8 2h8a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1zM12 7v7M9 11l3 3 3-3', + user:'M12 4a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM4 21c1-4.5 4.2-7 8-7s7 2.5 8 7', doc:'M6 2h9l5 5v15H6zM14 2v6h6M9 13h8M9 17h6', medal:'M8 2l4 6 4-6M12 22a6 6 0 1 0 0-12 6 6 0 0 0 0 12z', + rocket:'M5 15c-1 1-2 5-2 5s4-1 5-2M9 15l-3-3c1-4 5-9 12-9 0 7-5 11-9 12zM14 7a1.5 1.5 0 1 0 0 3 1.5 1.5 0 1 0 0-3', plus:'M12 5v14M5 12h14', check:'M5 12.5l4.5 4.5L19 7.5', + back:'M15 5l-7 7 7 7', edit:'M4 20h4L19 9l-4-4L4 16v4z' +}; +const EMO = {'πŸ‹οΈ':'dumbbell','πŸ‹':'dumbbell','πŸ“š':'book','πŸ“–':'book','🧘':'lotus','πŸ™':'pray','πŸƒ':'run','πŸ’§':'drop','πŸ₯—':'leaf','🌿':'leaf','😴':'moon','✍️':'pen','🎸':'music','🧠':'brain','πŸ’Š':'pill','🚭':'ban','🍬':'ban','πŸŒ…':'sun','🚢':'walk','🧹':'spark','πŸ’»':'code','🎨':'palette','πŸ“΅':'nophone','πŸ•Œ':'star','❀️':'heart','✨':'spark','πŸ†':'trophy','πŸ”₯':'flame'}; +const ik = k => P[k] ? k : (EMO[k] || 'spark'); +const ic = (k, cls = '') => ``; +const ICONS = ['dumbbell','book','lotus','pray','run','drop','leaf','moon','pen','music','brain','pill','sun','walk','code','palette','nophone','heart','spark','star','ban','bolt','target','rocket']; +const COLORS = ['#ffb13b','#ff6a2b','#ff2d8a','#c45cff','#8b5cff','#3d8bff','#38e1ff','#2fe0a0']; const PRESETS = [ - {name:'Gym', icon:'πŸ‹οΈ', color:'#ff7a3d', kind:'weekly', n:4, cat:'fitness'}, - {name:'Read 20 pages', icon:'πŸ“š', color:'#f2c46d', kind:'daily', n:1, cat:'mind'}, - {name:'Meditate', icon:'🧘', color:'#c77dff', kind:'daily', n:1, cat:'spirit'}, - {name:'Prayer', icon:'πŸ™', color:'#e9e4d8', kind:'daily', n:1, cat:'spirit'}, - {name:'Run', icon:'πŸƒ', color:'#3ddc97', kind:'weekly', n:3, cat:'fitness'}, - {name:'Drink water', icon:'πŸ’§', color:'#4cc9f0', kind:'daily', n:1, cat:'health'}, - {name:'Journal', icon:'✍️', color:'#6c8cff', kind:'daily', n:1, cat:'mind'}, - {name:'No phone in bed', icon:'πŸ“΅', color:'#ff5d7a', kind:'daily', n:1, cat:'health'}, + {name:'Gym', icon:'dumbbell', color:'#ff6a2b', kind:'weekly', n:4, cat:'fitness'}, + {name:'Read 20 pages', icon:'book', color:'#ffb13b', kind:'daily', n:1, cat:'mind'}, + {name:'Meditate', icon:'lotus', color:'#c45cff', kind:'daily', n:1, cat:'spirit'}, + {name:'Prayer', icon:'pray', color:'#8b5cff', kind:'daily', n:1, cat:'spirit'}, + {name:'Run', icon:'run', color:'#2fe0a0', kind:'weekly', n:3, cat:'fitness'}, + {name:'Drink water', icon:'drop', color:'#38e1ff', kind:'daily', n:1, cat:'health'}, + {name:'Journal', icon:'pen', color:'#3d8bff', kind:'daily', n:1, cat:'mind'}, + {name:'No phone in bed', icon:'nophone', color:'#ff2d8a', kind:'daily', n:1, cat:'health'}, +]; +const PAL = [['#ff7a2f','#ff2d8a'],['#8b5cff','#38e1ff'],['#ffd36b','#ff6a2b'],['#ff2d8a','#8b5cff'],['#2fe0a0','#38e1ff'],['#ff9b7a','#c2185b'],['#c45cff','#ff2d8a'],['#38e1ff','#3d5bff']]; +const hash = s => [...String(s)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 7); +function av(u, cls = '') { const m = /^p(\d)$/.exec(u.avatar || ''), p = PAL[m ? +m[1] : hash(u.username || u.display) % PAL.length], ch = [...(u.display || u.username || '?').trim()][0] || '?'; + return `
${esc(ch.toUpperCase())}
`; } +const QUOTES = [ + ['We are what we repeatedly do. Excellence, then, is not an act, but a habit.','Will Durant'],['The journey of a thousand miles begins with a single step.','Lao Tzu'], + ['Little by little, one travels far.','J.R.R. Tolkien'],['It does not matter how slowly you go as long as you do not stop.','Confucius'], + ['Waste no more time arguing what a good man should be. Be one.','Marcus Aurelius'],['Small deeds done are better than great deeds planned.','Peter Marshall'], + ['Begin at once to live.','Seneca'],['What you do every day matters more than what you do once in a while.','Gretchen Rubin'], + ['Set your life on fire. Seek those who fan your flames.','Rumi'],['Motivation gets you going, but habit gets you there.','Zig Ziglar'], + ['Success is the sum of small efforts, repeated day in and day out.','Robert Collier'],['The secret of getting ahead is getting started.','Mark Twain'], + ['Do not wait to strike till the iron is hot; make it hot by striking.','W.B. Yeats'],['Energy and persistence conquer all things.','Benjamin Franklin'], + ['Well begun is half done.','Aristotle'],['Act as if what you do makes a difference. It does.','William James'], + ['Habit is a cable; we weave a thread of it each day.','Horace Mann'],['First we make our habits, then our habits make us.','John Dryden'], ]; -const AVATARS = ['πŸ”₯','🦁','🐺','πŸ¦…','πŸŒ™','β˜€οΈ','🌊','🌸','⚑','πŸ€','πŸ‰','πŸ‘‘']; +const quote = () => QUOTES[Math.floor(Date.now() / 864e5) % QUOTES.length]; -/* ---------- haptics & fx ---------- */ +/* ---------- haptics, sound, confetti ---------- */ const buzz = (p = 12) => { try { navigator.vibrate && navigator.vibrate(p); } catch(e){} }; -const AC = window.AudioContext && new (window.AudioContext || window.webkitAudioContext)(); -function tick(f = 880) { if (!AC || localStorage.getItem('ember.sound') === '0') return; try { const o = AC.createOscillator(), g = AC.createGain(); o.frequency.value = f; o.type = 'sine'; g.gain.setValueAtTime(.0001, AC.currentTime); g.gain.exponentialRampToValueAtTime(.08, AC.currentTime + .01); g.gain.exponentialRampToValueAtTime(.0001, AC.currentTime + .18); o.connect(g).connect(AC.destination); o.start(); o.stop(AC.currentTime + .2); } catch(e){} } -const fx = $('#fx'), ctx = fx.getContext('2d'); let parts = []; -function burst(x, y, color = '#f2c46d', n = 26) { +let AC = null; +function tick(f = 880, d = .18) { if (localStorage.getItem('ember.sound') === '0') return; try { AC = AC || new (window.AudioContext || window.webkitAudioContext)(); const o = AC.createOscillator(), g = AC.createGain(); o.frequency.value = f; o.type = 'triangle'; g.gain.setValueAtTime(.0001, AC.currentTime); g.gain.exponentialRampToValueAtTime(.07, AC.currentTime + .01); g.gain.exponentialRampToValueAtTime(.0001, AC.currentTime + d); o.connect(g).connect(AC.destination); o.start(); o.stop(AC.currentTime + d + .02); } catch(e){} } +const chime = () => { tick(660); setTimeout(() => tick(880), 80); setTimeout(() => tick(1320, .3), 160); }; +const fx = $('#fx'), ctx = fx.getContext('2d'); let parts = [], fxOn = false; +const CONF = ['#ffd36b','#ff7a2f','#ff2d8a','#8b5cff','#38e1ff','#ffffff']; +function burst(x, y, color = '#ff7a2f', n = 34, big = false) { fx.width = innerWidth * devicePixelRatio; fx.height = innerHeight * devicePixelRatio; ctx.setTransform(devicePixelRatio,0,0,devicePixelRatio,0,0); - for (let i = 0; i < n; i++) { const a = Math.random() * Math.PI * 2, s = 2 + Math.random() * 5; parts.push({x, y, vx: Math.cos(a)*s, vy: Math.sin(a)*s - 2, l: 1, c: Math.random() < .5 ? color : '#ffe9b8', r: 1.5 + Math.random()*2.5}); } - if (parts.length === n) requestAnimationFrame(step); + for (let i = 0; i < n; i++) { const a = Math.random() * Math.PI * 2, s = (big ? 5 : 2.5) + Math.random() * (big ? 9 : 6); + parts.push({x, y, vx: Math.cos(a)*s, vy: Math.sin(a)*s - (big ? 6 : 3), l: 1, c: Math.random() < .35 ? color : CONF[i % CONF.length], w: 4 + Math.random()*6, h: 3 + Math.random()*4, r: Math.random()*6, vr: (Math.random() - .5) * .4, k: Math.random() < .4 ? 0 : 1}); } + if (!fxOn) { fxOn = true; requestAnimationFrame(step); } +} +function step() { ctx.clearRect(0,0,innerWidth,innerHeight); parts = parts.filter(p => p.l > 0 && p.y < innerHeight + 20); + for (const p of parts) { p.x += p.vx; p.y += p.vy; p.vy += .22; p.vx *= .985; p.r += p.vr; p.l -= .012; ctx.globalAlpha = Math.min(1, p.l * 1.6); ctx.fillStyle = p.c; + if (p.k) { ctx.save(); ctx.translate(p.x, p.y); ctx.rotate(p.r); ctx.fillRect(-p.w/2, -p.h/2, p.w, p.h * Math.abs(Math.cos(p.r * 2))); ctx.restore(); } else { ctx.shadowBlur = 10; ctx.shadowColor = p.c; ctx.beginPath(); ctx.arc(p.x, p.y, p.h/1.6, 0, 7); ctx.fill(); ctx.shadowBlur = 0; } } + if (parts.length) requestAnimationFrame(step); else { ctx.clearRect(0,0,innerWidth,innerHeight); fxOn = false; } } +function confettiRain() { for (let i = 0; i < 6; i++) setTimeout(() => burst(Math.random() * innerWidth, innerHeight * (.15 + Math.random() * .3), '#ffd36b', 40, true), i * 140); } +function floatText(x, y, t) { const e = document.createElement('div'); e.textContent = t; e.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:80;font-weight:900;font-size:18px;pointer-events:none;background:linear-gradient(90deg,#ffd36b,#ff2d8a);-webkit-background-clip:text;color:transparent;transform:translate(-50%,0);transition:all 1.1s cubic-bezier(.2,1,.3,1);filter:drop-shadow(0 0 8px #ff2d8a)`; document.body.appendChild(e); requestAnimationFrame(() => { e.style.transform = 'translate(-50%,-70px) scale(1.3)'; e.style.opacity = '0'; }); setTimeout(() => e.remove(), 1200); } +function toast(m) { const t = $('#toast'); t.innerHTML = m; t.classList.add('on'); clearTimeout(t._t); t._t = setTimeout(() => t.classList.remove('on'), 2600); } + +/* ---------- living flame (SVG core + additive particle canvas) ---------- */ +const flameSVG = (on = true, w = 90) => ` + + + + + + +`; +const flameScale = s => .62 + .5 * Math.min(1, s / 30); +function flame(streak, base = 96, on = true) { const w = Math.round(base * (on ? flameScale(streak) : .62)), cw = Math.round(w * 2.2); + return `
${on ? `` : ''}
${flameSVG(on, w)}
`; } +const SPR = ['#fff3c4','#ffb13b','#ff5a2b','#ff2d8a','#8b5cff'].map(c => { const s = document.createElement('canvas'); s.width = s.height = 64; const g = s.getContext('2d'), r = g.createRadialGradient(32,32,0,32,32,32); r.addColorStop(0, c); r.addColorStop(.4, c + '88'); r.addColorStop(1, c + '00'); g.fillStyle = r; g.fillRect(0,0,64,64); return s; }); +let flames = [], flameRAF = 0; +function mountFlames() { flames = [...$$('.fcv')].map(c => ({c, g: c.getContext('2d'), w: +c.dataset.w * 2, p: []})); if (!flameRAF && flames.length) flameRAF = requestAnimationFrame(flameLoop); } +function flameLoop() { + flames = flames.filter(f => f.c.isConnected); + for (const f of flames) { const {g, c, w} = f, W = c.width, H = c.height, bx = W / 2, by = H - w * .3; + for (let i = 0; i < 3; i++) f.p.push({x: bx + (Math.random() - .5) * w * .45, y: by - Math.random() * w * .2, vx: (Math.random() - .5) * .6, vy: -(1 + Math.random() * 2.2) * w / 110, l: 1, s: w * (.22 + Math.random() * .2), d: .012 + Math.random() * .014}); + if (Math.random() < .25) f.p.push({x: bx + (Math.random() - .5) * w * .5, y: by - w * .6, vx: (Math.random() - .5) * 1.4, vy: -(2 + Math.random() * 2.5) * w / 110, l: 1, s: w * .05, d: .008, e: 1}); + g.clearRect(0, 0, W, H); g.globalCompositeOperation = 'lighter'; + f.p = f.p.filter(p => p.l > 0); + for (const p of f.p) { p.x += p.vx + Math.sin((p.y + performance.now() * .05) * .03) * .4; p.y += p.vy; p.l -= p.d; if (!p.e) p.x += (bx - p.x) * .012; + const k = p.e ? 1 : p.l > .75 ? 0 : p.l > .5 ? 1 : p.l > .3 ? 2 : p.l > .15 ? 3 : 4, sz = p.e ? p.s : p.s * (.4 + p.l * .8); + g.globalAlpha = Math.min(1, p.l * (p.e ? 1.2 : .55)); g.drawImage(SPR[k], p.x - sz, p.y - sz, sz * 2, sz * 2); } + if (f.p.length > 260) f.p.splice(0, f.p.length - 260); + } + flameRAF = flames.length ? requestAnimationFrame(flameLoop) : 0; } -function step() { ctx.clearRect(0,0,innerWidth,innerHeight); parts = parts.filter(p => p.l > 0); for (const p of parts) { p.x += p.vx; p.y += p.vy; p.vy += .18; p.vx *= .98; p.l -= .022; ctx.globalAlpha = Math.max(p.l,0); ctx.fillStyle = p.c; ctx.beginPath(); ctx.arc(p.x,p.y,p.r,0,7); ctx.fill(); } if (parts.length) requestAnimationFrame(step); else ctx.clearRect(0,0,innerWidth,innerHeight); } -function toast(m) { const t = $('#toast'); t.textContent = m; t.classList.add('on'); clearTimeout(t._t); t._t = setTimeout(() => t.classList.remove('on'), 2600); } + +/* ---------- parallax & tilt ---------- */ +let tx = 0, ty = 0; +function applyTilt() { $$('.tilt').forEach(el => el.style.transform = `perspective(900px) rotateX(${ty * -5}deg) rotateY(${tx * 6}deg)`); ['.o1', '.o2', '.o3'].forEach((s, i) => { const o = $(s); if (o) o.style.translate = `${tx * (20 + i * 14)}px ${ty * (20 + i * 10) - scrollY * (.08 + i * .05)}px`; }); } +addEventListener('pointermove', e => { if (e.pointerType !== 'mouse') return; tx = e.clientX / innerWidth - .5; ty = e.clientY / innerHeight - .5; requestAnimationFrame(applyTilt); }, {passive: true}); +addEventListener('deviceorientation', e => { if (e.gamma == null) return; tx = Math.max(-1, Math.min(1, e.gamma / 30)) / 2; ty = Math.max(-1, Math.min(1, (e.beta - 45) / 30)) / 2; requestAnimationFrame(applyTilt); }, {passive: true}); +addEventListener('scroll', () => requestAnimationFrame(applyTilt), {passive: true}); /* ---------- API ---------- */ async function api(path, body, method) { const r = await fetch('/api' + path, {method: method || (body ? 'POST' : 'GET'), headers: {'content-type': 'application/json', ...(TOK ? {authorization: 'Bearer ' + TOK} : {})}, body: body ? JSON.stringify(body) : undefined}); let j = null; try { j = await r.json(); } catch(e){} - if (r.status === 401 && TOK && !path.startsWith('/login')) { logout(true); } + if (r.status === 401 && TOK && !path.startsWith('/login')) logout(true); if (!r.ok) throw new Error((j && (typeof j.detail === 'string' ? j.detail : 'Please check your input')) || 'Network error'); return j; } function setMe(m) { if (!m || !m.username) return; ME = m; localStorage.setItem('ember.me', JSON.stringify(m)); badge(); } function logout(silent) { TOK = null; ME = null; localStorage.removeItem('ember.tok'); localStorage.removeItem('ember.me'); if (!silent) toast('Signed out'); location.hash = '#/welcome'; } -// offline queue for check-ins let Q = JSON.parse(localStorage.getItem('ember.q') || '[]'); async function flush() { while (Q.length && navigator.onLine) { const op = Q[0]; try { setMe(await api(op.p, op.b)); Q.shift(); localStorage.setItem('ember.q', JSON.stringify(Q)); } catch(e) { break; } } } addEventListener('online', flush); -/* ---------- streak maths ---------- */ +/* ---------- streaks, XP, badges ---------- */ function streakOf(h, today = new Date()) { const s = new Set(h.days || []); if (h.kind === 'weekly') { const wk = d => { const x = new Date(d); x.setDate(x.getDate() - ((x.getDay() + 6) % 7)); return iso(x); }; const cnt = {}; for (const d of s) { const k = wk(new Date(d + 'T12:00')); cnt[k] = (cnt[k] || 0) + 1; } - let cur = new Date(today); let c = 0; if ((cnt[wk(cur)] || 0) < h.n) cur = addD(cur, -7); + let cur = new Date(today), c = 0; if ((cnt[wk(cur)] || 0) < h.n) cur = addD(cur, -7); while ((cnt[wk(cur)] || 0) >= h.n) { c++; cur = addD(cur, -7); } return c; } let cur = new Date(today); if (!s.has(iso(cur))) cur = addD(cur, -1); @@ -65,54 +151,79 @@ const weekDone = h => { const now = new Date(), mon = addD(now, -((now.getDay() const habits = () => (ME && ME.habits) || []; const topStreak = () => Math.max(0, ...habits().map(h => streakOf(h))); const unit = h => h.kind === 'weekly' ? 'week' : 'day'; +function perfectDays() { const d = habits().filter(h => h.kind !== 'weekly'); if (!d.length) return 0; const cnt = {}; d.forEach(h => (h.days||[]).forEach(x => cnt[x] = (cnt[x] || 0) + 1)); return Object.values(cnt).filter(v => v >= d.length).length; } +const TITLES = ['Spark','Kindle','Flicker','Flame','Blaze','Wildfire','Inferno','Phoenix','Solar','Supernova']; +function xpInfo() { const hs = habits(), total = hs.reduce((a, h) => a + (h.days||[]).length, 0); + const xp = total * 10 + hs.reduce((a, h) => a + bestEver(h), 0) * 5 + perfectDays() * 15 + ((ME && ME.friends) || []).length * 20; + let lv = 1, need = 100, acc = 0; while (xp >= acc + need) { acc += need; lv++; need = 100 + (lv - 1) * 60; } + return {xp, lv, into: xp - acc, need, title: TITLES[Math.min(TITLES.length - 1, Math.floor((lv - 1) / 2))], total}; } +const BADGES = [ + ['first','First Spark','Your first check-in',['#ffd36b','#ff6a2b'],'spark', s => s.total >= 1], + ['s3','Kindled','3-day streak',['#ff9b4a','#ff2d8a'],'flame', s => s.best >= 3], + ['s7','Week Warrior','7-day streak',['#ff6a2b','#ff2d8a'],'bolt', s => s.best >= 7], + ['s14','Fortnight','14-day streak',['#ff2d8a','#8b5cff'],'star', s => s.best >= 14], + ['s30','Monthly Flame','30-day streak',['#8b5cff','#38e1ff'],'crown', s => s.best >= 30], + ['s66','Habit Formed','66-day streak',['#38e1ff','#2fe0a0'],'medal', s => s.best >= 66], + ['c50','Half Century','50 check-ins',['#ffd36b','#c45cff'],'target', s => s.total >= 50], + ['c100','Centurion','100 check-ins',['#ff6a2b','#8b5cff'],'trophy', s => s.total >= 100], + ['perfect','Perfect Day','Every daily habit, one day',['#2fe0a0','#38e1ff'],'check', s => s.perfect >= 1], + ['p7','Flawless Seven','7 perfect days',['#38e1ff','#8b5cff'],'shield', s => s.perfect >= 7], + ['col','Collector','5 active habits',['#c45cff','#ff2d8a'],'palette', s => s.habits >= 5], + ['friend','Better Together','Add a friend',['#ff2d8a','#ffd36b'],'heart', s => s.friends >= 1], + ['circle','Inner Circle','5 friends',['#ff7a2f','#c2185b'],'users', s => s.friends >= 5], + ['chal','Challenger','Join a group challenge',['#ffd36b','#ff2d8a'],'rocket', s => s.chal >= 1], + ['lv5','Blaze','Reach level 5',['#ff6a2b','#ffd36b'],'flame', s => s.lv >= 5], +]; +function badgeStats() { const hs = habits(), x = xpInfo(); return {total: x.total, best: Math.max(0, ...hs.map(bestEver)), perfect: perfectDays(), habits: hs.length, friends: (ME.friends || []).length, chal: Number(localStorage.getItem('ember.chal') || 0), lv: x.lv}; } +const earned = () => { const s = badgeStats(); return BADGES.filter(b => b[5](s)).map(b => b[0]); }; +const medal = (b, lock) => `
${ic(lock ? 'lock' : b[4])}
`; /* ---------- svg bits ---------- */ -const flame = (on = true, size = '') => ` - - - - -`; -const ringSvg = (p, c = '#f2c46d', sz = 64, w = 5) => { const r = (sz - w) / 2, C = 2 * Math.PI * r; return ``; }; -const backBtn = (to = '#/home') => ``; -const check = ''; +function ring(p, sz = 64, w = 6, id = 'r' + Math.random().toString(36).slice(2, 7), c1 = '#ffd36b', c2 = '#ff2d8a') { const r = (sz - w) / 2, C = 2 * Math.PI * r; + return ``; } +const animateRings = () => requestAnimationFrame(() => requestAnimationFrame(() => $$('.arc').forEach(a => a.style.strokeDashoffset = a.dataset.to))); +const backBtn = to => ``; +const checkCore = ''; +function habitProgress(h) { return h.kind === 'weekly' ? Math.min(1, weekDone(h) / h.n) : (h.days||[]).includes(TODAY()) ? 1 : 0; } /* ---------- router ---------- */ const routes = {}; function go() { - const [_, r, arg] = (location.hash || '#/').split('/'); + const [, r, arg] = (location.hash || '#/').split('/'); const pub = ['welcome', 'auth', 'privacy', 'terms', 'pro']; if (!TOK && !pub.includes(r)) { location.hash = '#/welcome'; return; } if (TOK && (!r || r === 'welcome')) { location.hash = '#/home'; return; } closeSheet(); - const fn = routes[r] || routes.home; $('#tabs').classList.toggle('hidden', !TOK || ['welcome','auth','privacy','terms','share'].includes(r)); - document.querySelectorAll('#tabs a').forEach(a => a.classList.toggle('on', a.dataset.t === r)); - app.innerHTML = ''; scrollTo(0, 0); fn(arg); + $$('#tabs a').forEach(a => a.classList.toggle('on', a.dataset.t === r || (r === 'badges' && a.dataset.t === 'stats'))); + app.innerHTML = ''; scrollTo(0, 0); (routes[r] || routes.home)(arg); after(); } +function after() { mountFlames(); animateRings(); applyTilt(); } addEventListener('hashchange', go); /* ---------- onboarding ---------- */ +const sat = (k, c, pos, d = 0) => `
${ic(k)}
`; const SLIDES = [ - {art: () => `
${flame(true,'width:110px;height:132px')}
πŸ‹οΈ
πŸ“š
🧘
`, - t: 'Small rituals.
Lasting fire.', p: 'Ember turns the things you care about β€” training, reading, prayer, stillness β€” into a streak worth protecting.'}, - {art: () => `
${Array.from({length: 105}, (_, i) => ``).join('')}
`, - t: 'See every day you showed up.', p: 'A living heatmap, elegant stats and a flame that grows with you. Miss a day? Begin again β€” gently.'}, - {art: () => `
${['🦁','πŸŒ™','πŸ”₯','⚑'].map((a, i) => `
${a}
`).join('')}
`, - t: 'Better together.', p: 'Invite friends with a link, join group challenges, climb the leaderboard and send a cheer when it matters.'}, + {art: () => `
${flame(20, 104)}${sat('dumbbell','#ff6a2b','top:-8px;left:99px')}${sat('book','#ffb13b','bottom:24px;left:-14px',-1)}${sat('lotus','#c45cff','bottom:24px;right:-14px',-2)}
`, + t: 'Small rituals.
Lasting fire.', p: 'Ember turns the things you care about (training, reading, prayer, stillness) into a streak worth protecting.'}, + {art: () => `
${ic('bolt')} LEVEL 7 Β· BLAZE
${Array.from({length: 98}, (_, i) => ``).join('')}
`, + t: 'Watch yourself level up.', p: 'Earn XP, unlock badges and grow a flame that gets bigger with every day you show up.'}, + {art: () => `
${[['Maya','p0'],['Leo','p1'],['Ava','p2'],['Kai','p3']].map(([d, a], i) => `
${av({display: d, avatar: a}, 'xl')}
`).join('')}
`, + t: 'Better together.', p: 'Invite friends with a link, join group challenges, climb the podium and send a cheer when it matters.'}, ]; routes.welcome = () => { - let i = 0; const inv = localStorage.getItem('ember.inv'); + let i = 0; const draw = () => { const s = SLIDES[i]; app.innerHTML = `
-
${i < 2 ? '' : ''}
+
${i < 2 ? '' : ''}
${s.art()}

${s.t}

${s.p}

- ${inv && invInfo ? `
${esc(invInfo.avatar)}
${esc(invInfo.display)} invited you
Join and you'll be friends automatically
` : ''} + ${invInfo ? `
${av(invInfo)}
${esc(invInfo.display)} invited you
Join and you'll be friends automatically
` : ''}
${SLIDES.map((_, j) => ``).join('')}
`; $('#next').onclick = () => { buzz(); if (i < 2) { i++; draw(); } else location.hash = '#/auth/signup'; }; const sk = $('#skip'); if (sk) sk.onclick = () => { i = 2; draw(); }; let x0 = null; $('#sl').ontouchstart = e => x0 = e.touches[0].clientX; $('#sl').ontouchend = e => { const dx = e.changedTouches[0].clientX - x0; if (dx < -40 && i < 2) { i++; draw(); } else if (dx > 40 && i > 0) { i--; draw(); } }; + after(); }; draw(); }; @@ -120,8 +231,8 @@ let invInfo = null; routes.auth = mode => { const su = mode !== 'login'; app.innerHTML = `
${backBtn('#/welcome')} -
${flame(true,'width:54px;height:66px')}

${su ? 'Light your first ember.' : 'Welcome back.'}

-

${su ? 'Free forever. No email needed β€” just a username your friends can find.' : 'Sign in to keep your streaks burning.'}

+
${flame(8, 60)}

${su ? 'Light your first ember.' : 'Welcome back.'}

+

${su ? 'Free forever. No email needed, just a username your friends can find.' : 'Sign in to keep your streaks burning.'}

${su ? `
` : ''}
@@ -132,89 +243,110 @@ routes.auth = mode => { $('#f').onsubmit = async e => { e.preventDefault(); const fd = Object.fromEntries(new FormData(e.target)); fd.invite = localStorage.getItem('ember.inv') || null; const b = $('#go'); b.disabled = true; b.textContent = su ? 'Creating…' : 'Signing in…'; $('#err').textContent = ''; - try { const r = await api(su ? '/signup' : '/login', fd); TOK = r.token; localStorage.setItem('ember.tok', TOK); setMe(r.me); localStorage.removeItem('ember.inv'); buzz([10, 40, 20]); - if (su) { location.hash = '#/home'; setTimeout(() => presetSheet(true), 350); } else location.hash = '#/home'; + try { const r = await api(su ? '/signup' : '/login', fd); TOK = r.token; localStorage.setItem('ember.tok', TOK); setMe(r.me); localStorage.removeItem('ember.inv'); invInfo = null; buzz([10, 40, 20]); + location.hash = '#/home'; if (su) setTimeout(() => presetSheet(true), 350); } catch(err) { $('#err').textContent = err.message; b.disabled = false; b.textContent = su ? 'Create account' : 'Sign in'; buzz([30, 30, 30]); } }; }; /* ---------- home ---------- */ function greet() { const h = new Date().getHours(); return h < 5 ? 'Still up' : h < 12 ? 'Good morning' : h < 18 ? 'Good afternoon' : 'Good evening'; } +const tickSvg = ''; routes.home = () => { - const hs = habits(), t = TODAY(), st = topStreak(); - const doneToday = hs.filter(h => (h.days||[]).includes(t)).length; + const hs = habits(), t = TODAY(), st = topStreak(), x = xpInfo(), q = quote(); + const doneToday = hs.filter(h => (h.days||[]).includes(t)).length, pct = hs.length ? doneToday / hs.length : 0; const now = new Date(), mon = addD(now, -((now.getDay() + 6) % 7)); - const wk = Array.from({length: 7}, (_, i) => { const d = addD(mon, i), k = iso(d); return {k, l: 'MTWTFSS'[i], n: d.getDate(), on: hs.some(h => (h.days||[]).includes(k)), today: k === t}; }); - app.innerHTML = `
${greet()},
${esc(ME.display)}
${esc(ME.avatar)}
+ const wk = Array.from({length: 7}, (_, i) => { const d = addD(mon, i), k = iso(d); return {l: 'MTWTFSS'[i], n: d.getDate(), on: hs.some(h => (h.days||[]).includes(k)), today: k === t}; }); + app.innerHTML = `
${greet()},
${esc(ME.display)}
${av(ME)}
${installBanner()} -
Best streak
-
${st}${st === 1 ? 'day' : 'days'}
-
${hs.length ? `${doneToday} of ${hs.length} done today` : 'Add a habit to begin'}
${flame(st > 0 || doneToday > 0)}
-
${wk.map(d => `
${d.l}${d.on ? 'βœ“' : d.n}
`).join('')}
+
+ ${ic('bolt')} LV ${x.lv} Β· ${x.title.toUpperCase()} +
${st}${st === 1 ? 'day' : 'days'}
streak
+
${flame(st, 92, st > 0 || doneToday > 0)}
+
${ring(pct, 62, 7, 'hr')}${Math.round(pct * 100)}%
+
${hs.length ? `${doneToday} of ${hs.length} today` : 'Add a habit to begin'}${x.into}/${x.need} XP
+
+
${wk.map(d => `
${d.l}${d.on ? tickSvg : d.n}
`).join('')}

Today Β· ${new Date().toLocaleDateString(undefined, {weekday: 'long', day: 'numeric', month: 'short'})}

-
${hs.length ? hs.map((h, i) => habitRow(h, i)).join('') : `
🌱
Begin with one ritual

Tiny and daily beats big and rare.

`}
- ${hs.length ? `` : ''}`; +
${hs.length ? hs.map((h, i) => habitRow(h, i)).join('') : `
${ic('leaf')}
Begin with one ritual

Tiny and daily beats big and rare.

`}
+ ${hs.length ? `` : ''} +
TODAY'S SPARK
${esc(q[0])}
${esc(q[1])}
`; bindRows(); - api('/me').then(m => { const was = JSON.stringify(ME); setMe(m); if (JSON.stringify(m) !== was && location.hash.startsWith('#/home')) routes.home(); }).catch(() => {}); + api('/me').then(m => { const was = JSON.stringify(ME); setMe(m); if (JSON.stringify(m) !== was && location.hash.startsWith('#/home') && $('#sheet').classList.contains('hidden')) { routes.home(); after(); } }).catch(() => {}); }; function habitRow(h, i) { const on = (h.days||[]).includes(TODAY()), s = streakOf(h); - const sub = h.kind === 'weekly' ? `${weekDone(h)}/${h.n} this week` : 'Every day'; - return `
-
${esc(h.icon)}
${esc(h.name)}
${s ? `πŸ”₯ ${s} ${unit(h)}${s > 1 ? 's' : ''}` : 'Start a streak'} Β· ${sub}
-
`; + const sub = h.kind === 'weekly' ? `${weekDone(h)}/${h.n} this week` : 'Daily'; + return `
+
${ic(h.icon)}
${esc(h.name)}
${s ? `${s} ${unit(h)}${s > 1 ? 's' : ''}` : 'Start a streak'} Β· ${sub}
+
`; } function bindRows() { - document.querySelectorAll('.habit').forEach(el => { + $$('.habit').forEach(el => { el.querySelector('[data-open]').onclick = el.querySelector('.hicon').onclick = () => location.hash = '#/habit/' + el.dataset.id; el.querySelector('.chk').onclick = e => { e.stopPropagation(); toggle(el.dataset.id, TODAY(), e.currentTarget); }; }); } async function toggle(id, day, btn) { const h = habits().find(x => x.id === id); if (!h) return; - const done = !(h.days||[]).includes(day), before = streakOf(h); + const done = !(h.days||[]).includes(day), before = streakOf(h), lv0 = xpInfo().lv, pd0 = perfectDays(), b0 = earned(); h.days = done ? [...(h.days||[]), day].sort() : (h.days||[]).filter(d => d !== day); setMe(ME); - if (btn) { const r = btn.getBoundingClientRect(); btn.classList.toggle('on', done); btn.classList.remove('pop'); void btn.offsetWidth; btn.classList.add('pop'); btn.closest('.habit')?.classList.toggle('done', done); if (done) burst(r.left + r.width/2, r.top + r.height/2, h.color); } - if (done) { buzz([8, 30, 14]); tick(660); setTimeout(() => tick(990), 90); const a = streakOf(h); if (a > before && [3,7,14,21,30,50,66,100,200,365].includes(a)) setTimeout(() => milestone(h, a), 500); } - else buzz(6); + if (btn) { const r = btn.getBoundingClientRect(); btn.classList.toggle('on', done); btn.classList.remove('pop'); void btn.offsetWidth; btn.classList.add('pop'); btn.closest('.habit')?.classList.toggle('done', done); + const a = btn.querySelector('.arc'); if (a) { const C = +a.getAttribute('stroke-dasharray'); a.style.strokeDashoffset = C * (1 - habitProgress(h)); } + if (done) { burst(r.left + r.width/2, r.top + r.height/2, h.color, 46); floatText(r.left + r.width/2, r.top - 6, '+10 XP'); } } + let celebrated = false; + if (done) { buzz([8, 30, 14]); chime(); const a = streakOf(h), lv1 = xpInfo().lv, nb = earned().filter(b => !b0.includes(b)); + if (a > before && [3,7,14,21,30,50,66,100,200,365].includes(a)) { celebrated = true; setTimeout(() => celebrate('streak', h, a), 600); } + else if (perfectDays() > pd0 && day === TODAY()) { celebrated = true; setTimeout(() => celebrate('perfect', h), 600); } + else if (lv1 > lv0) { celebrated = true; setTimeout(() => celebrate('level', h, lv1), 600); } + if (nb.length) { const B = BADGES.find(b => b[0] === nb[0]); setTimeout(() => toast(`${ic(B[4])} Badge unlocked: ${B[1]}`), celebrated ? 2200 : 700); } + } else buzz(6); const op = {p: `/habits/${id}/check`, b: {day, done}}; - try { setMe(await api(op.p, op.b)); } catch(e) { Q.push(op); localStorage.setItem('ember.q', JSON.stringify(Q)); toast('Saved offline β€” will sync'); } - const r = location.hash.split('/')[1]; if (r === 'home' || !r) setTimeout(() => { const sc = scrollY; routes.home(); scrollTo(0, sc); }, 420); if (r === 'habit') routes.habit(id); + try { setMe(await api(op.p, op.b)); } catch(e) { Q.push(op); localStorage.setItem('ember.q', JSON.stringify(Q)); toast('Saved offline, will sync'); } + const r = location.hash.split('/')[1]; + if ((r === 'home' || !r) && !celebrated) setTimeout(() => { if (!$('#sheet').classList.contains('hidden')) return; const sc = scrollY; routes.home(); after(); scrollTo(0, sc); }, 650); + if (r === 'habit') { const sc = scrollY; routes.habit(id); after(); scrollTo(0, sc); } } -function milestone(h, n) { - openSheet(`
${flame(true,'width:110px;height:132px')}
Milestone
-

${n} ${unit(h)}s of ${esc(h.name)}

That's not luck. That's who you are now.

-
`); - const r = innerWidth / 2; for (let i = 0; i < 3; i++) setTimeout(() => burst(r, innerHeight * .35, h.color, 40), i * 180); +function celebrate(kind, h, n) { + const x = xpInfo(), pd = perfectDays(); + const T = {streak: [`${n} ${unit(h)}s`, `of ${esc(h.name)}`, "That's not luck. That's who you are now."], + perfect: ['Perfect day', 'Every ritual, complete.', `+15 bonus XP Β· ${pd} perfect day${pd > 1 ? 's' : ''} so far`], + level: [`Level ${n}`, x.title, 'Your flame burns brighter. Keep feeding it.']}[kind]; + openSheet(`
${flame(30, 110)}
${kind === 'level' ? 'Level up' : kind === 'perfect' ? 'Flawless' : 'Milestone'}
+

${T[0]}

${T[1]}

${T[2]}

+
${ic('bolt')} LV ${x.lv}
+
`); + $('#kg').onclick = () => { closeSheet(); go(); }; + mountFlames(); confettiRain(); buzz([20, 40, 20, 40, 60]); setTimeout(() => tick(1567, .4), 250); } /* ---------- habit sheet ---------- */ function presetSheet(first) { - openSheet(`

${first ? 'What will you tend?' : 'New habit'}

Pick a classic or craft your own.

-
${PRESETS.map((p, i) => ``).join('')}
- `); - document.querySelectorAll('[data-p]').forEach(b => b.onclick = () => { buzz(); habitSheet({...PRESETS[b.dataset.p]}); }); - $('#custom').onclick = () => habitSheet({name: '', icon: '✨', color: '#f2c46d', kind: 'daily', n: 1, cat: 'custom'}); + openSheet(`

${first ? 'What will you tend?' : 'New habit'}

Pick a classic or craft your own.

+
${PRESETS.map((p, i) => ``).join('')}
+ `); + $$('[data-p]').forEach(b => b.onclick = () => { buzz(); habitSheet({...PRESETS[b.dataset.p]}); }); + $('#custom').onclick = () => habitSheet({name: '', icon: 'spark', color: '#ff6a2b', kind: 'daily', n: 1, cat: 'custom'}); } function habitSheet(h) { - const edit = !!h.id; - openSheet(`

${edit ? 'Edit habit' : 'Make it yours'}

+ const edit = !!h.id; h.icon = ik(h.icon); + openSheet(`

${edit ? 'Edit habit' : 'Make it yours'}

-
${ICONS.map(i => ``).join('')}
-
${COLORS.map(c => ``).join('')}
-
-
Γ— per week
- +
${ICONS.map(i => ``).join('')}
+
${COLORS.map(c => ``).join('')}
+
+
Γ— per week
+
- ${edit ? '' : ''}`); - const sync = () => { document.querySelectorAll('#kind button').forEach(b => b.classList.toggle('on', b.dataset.k === h.kind)); $('#nw').classList.toggle('hidden', h.kind !== 'weekly'); $('#nv').textContent = h.n; }; + ${edit ? '' : ''}`); + const sync = () => { $$('#kind button').forEach(b => b.classList.toggle('on', b.dataset.k === h.kind)); $('#nw').classList.toggle('hidden', h.kind !== 'weekly'); $('#nv').textContent = h.n; }; sync(); - document.querySelectorAll('[data-i]').forEach(b => b.onclick = () => { h.icon = b.dataset.i; buzz(5); document.querySelectorAll('[data-i]').forEach(x => x.classList.toggle('on', x === b)); }); - document.querySelectorAll('[data-c]').forEach(b => b.onclick = () => { h.color = b.dataset.c; buzz(5); document.querySelectorAll('[data-c]').forEach(x => x.classList.toggle('on', x === b)); }); - document.querySelectorAll('#kind button').forEach(b => b.onclick = () => { h.kind = b.dataset.k; if (h.kind === 'weekly' && h.n < 2) h.n = 3; buzz(5); sync(); }); + $$('[data-i]').forEach(b => b.onclick = () => { h.icon = b.dataset.i; buzz(5); $$('[data-i]').forEach(x => x.classList.toggle('on', x === b)); }); + $$('[data-c]').forEach(b => b.onclick = () => { h.color = b.dataset.c; buzz(5); $$('[data-c]').forEach(x => x.classList.toggle('on', x === b)); $$('[data-i]').forEach(x => x.style.setProperty('--c', h.color)); }); + $$('#kind button').forEach(b => b.onclick = () => { h.kind = b.dataset.k; if (h.kind === 'weekly' && h.n < 2) h.n = 3; buzz(5); sync(); }); $('#nm').onclick = () => { h.n = Math.max(1, h.n - 1); sync(); buzz(4); }; $('#np').onclick = () => { h.n = Math.min(7, h.n + 1); sync(); buzz(4); }; $('#hs').onclick = async () => { h.name = $('#hn').value.trim(); h.private = $('#priv').checked; if (!h.name) { $('#herr').textContent = 'Give it a name'; return; } - try { const m = await api('/habits', {...h, days: undefined}); setMe(m); closeSheet(); buzz([10, 30, 10]); toast(edit ? 'Saved' : `${h.icon} ${h.name} added`); go(); } catch(e) { $('#herr').textContent = e.message; } }; + try { const m = await api('/habits', {...h, days: undefined, undone: undefined}); setMe(m); closeSheet(); buzz([10, 30, 10]); toast(`${ic(h.icon)} ${esc(h.name)} ${edit ? 'saved' : 'added'}`); go(); } catch(e) { $('#herr').textContent = e.message; } }; if (edit) $('#hd').onclick = async () => { if (!confirm(`Delete β€œ${h.name}” and its history?`)) return; setMe(await api('/habits/' + h.id, null, 'DELETE')); closeSheet(); location.hash = '#/home'; }; } function openSheet(html) { const w = $('#sheet'); w.querySelector('.sheet').innerHTML = html; w.classList.remove('hidden'); w.querySelector('.scrim').onclick = closeSheet; } @@ -235,127 +367,152 @@ routes.habit = id => { const m0 = calMonth, first = (m0.getDay() + 6) % 7, dim = new Date(m0.getFullYear(), m0.getMonth() + 1, 0).getDate(); const cal = Array.from({length: first}, () => '').join('') + Array.from({length: dim}, (_, i) => { const d = new Date(m0.getFullYear(), m0.getMonth(), i + 1), k = iso(d); return ``; }).join(''); const on = set.has(TODAY()); - app.innerHTML = `
${backBtn('#/home')}
-
${esc(h.icon)}

${esc(h.name)}

${h.kind === 'weekly' ? `${h.n}Γ— per week Β· ${weekDone(h)} done this week` : 'Every day'}
-
${flame(s > 0, 'width:70px;height:84px')}
${s}
${unit(h)} streak
-
-
${best}
BEST
${total}
CHECK-INS
${rate}%
CONSISTENCY
+ app.innerHTML = `
${backBtn('#/home')}
${ic('share')}
+
${ic(h.icon)}

${esc(h.name)}

${h.kind === 'weekly' ? `${h.n}Γ— per week Β· ${weekDone(h)} done this week` : 'Every day'}
+
${flame(s, 84, s > 0)}
${s}
${unit(h)} streak
+ +
${on ? 'Done today. Beautiful.' : 'Tap to check in for today'}
+
${best}
BEST
${total}
CHECK-INS
${rate}%
CONSISTENCY

Last 18 weeks

${cells}
-

${m0.toLocaleDateString(undefined, {month: 'long', year: 'numeric'})}

+

${m0.toLocaleDateString(undefined, {month: 'long', year: 'numeric'})}

${['M','T','W','T','F','S','S'].map(x => `${x}`).join('')}${cal}

Tap a past day to log or undo it.

-
`; +
`; $('#tg').onclick = e => toggle(id, TODAY(), e.currentTarget); - document.querySelectorAll('[data-d]').forEach(b => b.onclick = () => toggle(id, b.dataset.d, null)); - $('#pm').onclick = () => { calMonth = new Date(m0.getFullYear(), m0.getMonth() - 1, 1); routes.habit(id); }; - $('#nm2').onclick = () => { if (m0 < new Date(t.getFullYear(), t.getMonth(), 1)) { calMonth = new Date(m0.getFullYear(), m0.getMonth() + 1, 1); routes.habit(id); } }; + $$('[data-d]').forEach(b => b.onclick = () => toggle(id, b.dataset.d, null)); + $('#pm').onclick = () => { calMonth = new Date(m0.getFullYear(), m0.getMonth() - 1, 1); routes.habit(id); after(); }; + $('#nm2').onclick = () => { if (m0 < new Date(t.getFullYear(), t.getMonth(), 1)) { calMonth = new Date(m0.getFullYear(), m0.getMonth() + 1, 1); routes.habit(id); after(); } }; $('#ed').onclick = () => habitSheet({...h}); }; /* ---------- stats ---------- */ routes.stats = () => { - const hs = habits(), t = new Date(); + const hs = habits(), t = new Date(), x = xpInfo(); const days = Array.from({length: 14}, (_, i) => { const d = addD(t, i - 13), k = iso(d); return {l: d.toLocaleDateString(undefined, {weekday: 'narrow'}), v: hs.filter(h => (h.days||[]).includes(k)).length}; }); - const mx = Math.max(1, ...days.map(d => d.v)), total = hs.reduce((a, h) => a + (h.days||[]).length, 0); + const mx = Math.max(1, ...days.map(d => d.v)), total = x.total; const last30 = hs.reduce((a, h) => a + (h.days||[]).filter(d => d > iso(addD(t, -30))).length, 0); const possible = Math.max(1, hs.reduce((a, h) => a + (h.kind === 'weekly' ? h.n * 30 / 7 : 30), 0)); const all = new Set(hs.flatMap(h => h.days || [])), st = new Date(t.getFullYear(), t.getMonth(), t.getDate() - 7 * 25 - ((t.getDay() + 6) % 7)); - const heat = Array.from({length: 26 * 7}, (_, i) => { const d = addD(st, i), k = iso(d), n = hs.filter(h => (h.days||[]).includes(k)).length; return d > t ? '' : ``; }).join(''); - app.innerHTML = `

Your fire, measured.

Every check-in, across every habit.

-
${topStreak()}
BEST NOW
${total}
ALL-TIME
${Math.min(100, Math.round(last30 / possible * 100))}%
30-DAY RATE
-

Last 14 days

${days.map((d, i) => `
${d.l}
`).join('')}
-

Six months

${heat}
${all.size} active days
-

By habit

${hs.length ? hs.map(h => { const s = streakOf(h); return `
${esc(h.icon)}
${esc(h.name)}
Best ${bestEver(h)} Β· ${(h.days||[]).length} total
${s}πŸ”₯
`; }).join('') : '

No habits yet.

'}
- ✦
Advanced insights
Best time of day, correlations, yearly review
Pro
`; + const heat = Array.from({length: 26 * 7}, (_, i) => { const d = addD(st, i), k = iso(d), n = hs.filter(h => (h.days||[]).includes(k)).length; return d > t ? '' : ``; }).join(''); + const eb = earned(); + app.innerHTML = `

Your fire, measured.

Every check-in, across every habit.

+
${ring(x.into / x.need, 84, 8, 'lv')}${x.lv}
LEVEL Β· ${x.title.toUpperCase()}
${x.xp.toLocaleString()} XP
${eb.length}/${BADGES.length} badges Β· tap to view
+
${topStreak()}
BEST NOW
${total}
ALL-TIME
${Math.min(100, Math.round(last30 / possible * 100))}%
30-DAY RATE
+

Last 14 days

${days.map((d, i) => `
${d.l}
`).join('')}
+

Six months

${heat}
${all.size} active days
+

By habit

${hs.length ? hs.map(h => { const s = streakOf(h); return `
${ic(h.icon)}
${esc(h.name)}
Best ${bestEver(h)} Β· ${(h.days||[]).length} total
${s}
`; }).join('') : '

No habits yet.

'}
+ ${ic('chart')}
Advanced insights
Best time of day, correlations, yearly review
Pro
`; +}; + +/* ---------- badges ---------- */ +routes.badges = () => { + const x = xpInfo(), eb = earned(); + app.innerHTML = `
${backBtn('#/stats')}${ic('bolt')} ${x.xp.toLocaleString()} XP
+
${ring(x.into / x.need, 120, 10, 'bl')}
${x.lv}
LEVEL
+

${x.title}

${x.need - x.into} XP to level ${x.lv + 1} Β· ${eb.length} of ${BADGES.length} badges

+

+10 per check-in Β· +5 per best-streak day Β· +15 per perfect day Β· +20 per friend

+

Achievements

${BADGES.map((b, i) => { const ok = eb.includes(b[0]); return `
${medal(b, !ok)}
${b[1]}
${b[2]}
`; }).join('')}
`; }; /* ---------- friends ---------- */ -const RX = {cheer: ['πŸ‘', 'cheered you on'], nudge: ['πŸ‘‰', 'nudged you β€” time to check in'], fire: ['πŸ”₯', 'sent you fire'], clap: ['πŸ’ͺ', 'is proud of you']}; +const RX = {cheer: ['spark', 'cheered you on'], nudge: ['bell', 'nudged you: time to check in'], fire: ['flame', 'sent you fire'], clap: ['heart', 'is proud of you']}; function badge() { const n = ((ME && ME.inbox) || []).filter(m => !m.r).length, b = $('#badge'); b.textContent = n; b.classList.toggle('hidden', !n); } const inviteUrl = () => `${location.origin}/i/${ME.invite}`; +function podium(lb) { + const top = lb.slice(0, 3), order = [top[1], top[0], top[2]], cls = ['p2', 'p1', 'p3'], rk = [2, 1, 3]; + return `
${order.map((r, i) => r ? `
${i === 1 ? `` : ''}${av(r, i === 1 ? 'xl' : '')}
${esc(r.display)}${r.username === ME.username ? ' (you)' : ''}
${r.streak}
${rk[i]}
` : '
').join('')}
`; +} routes.friends = async () => { - app.innerHTML = `

Your circle

Streaks are lighter when they're shared.

Loading…
`; + app.innerHTML = `

Your circle

Streaks are lighter when they're shared.

Loading…
`; let lb = [], ch = []; try { [lb, ch] = await Promise.all([api('/leaderboard'), api('/challenges')]); setMe(await api('/me')); } catch(e) { lb = [{...ME, streak: topStreak(), week: 0}]; } + CH = ch; localStorage.setItem('ember.chal', ch.filter(c => c.joined).length); const inbox = (ME.inbox || []).slice(0, 6); $('#fbody').innerHTML = ` - ${inbox.length ? `

Activity

${inbox.map(m => `
${RX[m.k][0]}
@${esc(m.f)} ${RX[m.k][1]}
${ago(m.t)}
`).join('')}
` : ''} -

Leaderboard

${lb.map((r, i) => `
${i < 3 && lb.length > 1 ? ['πŸ₯‡','πŸ₯ˆ','πŸ₯‰'][i] : i + 1}
${esc(r.avatar)}
${esc(r.display)}${r.username === ME.username ? ' (you)' : ''}
@${esc(r.username)} Β· ${r.week} this week
- ${r.username !== ME.username ? `
` : ''}
${r.streak}πŸ”₯
`).join('')} +
LEADERBOARD Β· STREAK
${podium(lb)} + ${lb.map((r, i) => `
${i + 1}
${av(r)}
${esc(r.display)}${r.username === ME.username ? ' (you)' : ''}
@${esc(r.username)} Β· ${r.week} this week
+ ${r.username !== ME.username ? `
` : ''}
${r.streak}
`).join('')} ${lb.length < 2 ? '

Invite a friend to start competing.

' : ''}
-

Group challenges

- ${ch.length ? ch.map(chalCard).join('') : `
πŸ†

Start a 30-day challenge with your friends.

`} -

Invite friends

Your invite code
${esc(ME.invite)}
+ ${inbox.length ? `

Activity

${inbox.map(m => `
${ic((RX[m.k] || RX.cheer)[0])}
@${esc(m.f)} ${(RX[m.k] || RX.cheer)[1]}
${ago(m.t)}
`).join('')}
` : ''} +

Group challenges

+ ${ch.length ? ch.map(chalCard).join('') : `
${ic('trophy')}

Start a 30-day challenge with your friends.

`} +

Invite friends

Your invite code
${esc(ME.invite)}
-
Have a code or username?
`; - document.querySelectorAll('.react button').forEach(b => b.onclick = async e => { const u = b.parentNode.dataset.u, r = b.getBoundingClientRect(); buzz([6, 20, 6]); burst(r.left + 18, r.top + 18, '#f2c46d', 14); - try { await api('/react/' + u, {kind: b.dataset.k}); toast(`${RX[b.dataset.k][0]} Sent to @${u}`); } catch(err) { toast(err.message); } }); - $('#sh').onclick = async () => { const d = {title: 'Join me on Ember', text: `I'm building streaks on Ember πŸ”₯ Join me β€” my code is ${ME.invite}`, url: inviteUrl()}; buzz(); if (navigator.share) { try { await navigator.share(d); } catch(e){} } else { copy(inviteUrl()); } }; +
Have a code or username?
`; + after(); + $$('.react button').forEach(b => b.onclick = async () => { const u = b.parentNode.dataset.u, r = b.getBoundingClientRect(); buzz([6, 20, 6]); burst(r.left + 19, r.top + 19, '#ff2d8a', 20); + try { await api('/react/' + u, {kind: b.dataset.k}); toast(`${ic(RX[b.dataset.k][0])} Sent to @${esc(u)}`); } catch(err) { toast(esc(err.message)); } }); + $('#sh').onclick = async () => { const d = {title: 'Join me on Ember', text: `I'm building streaks on Ember. Join me, my code is ${ME.invite}`, url: inviteUrl()}; buzz(); if (navigator.share) { try { await navigator.share(d); } catch(e){} } else copy(inviteUrl()); }; $('#cp').onclick = () => copy(inviteUrl()); - $('#af').onsubmit = async e => { e.preventDefault(); $('#ferr').textContent = ''; try { setMe(await api('/friends', {code: $('#fc').value})); buzz([10, 30, 10]); toast('Friend added ✨'); routes.friends(); } catch(err) { $('#ferr').textContent = err.message; } }; + $('#af').onsubmit = async e => { e.preventDefault(); $('#ferr').textContent = ''; try { setMe(await api('/friends', {code: $('#fc').value})); buzz([10, 30, 10]); confettiRain(); toast('Friend added'); routes.friends(); } catch(err) { $('#ferr').textContent = err.message; } }; [$('#nc'), $('#nc2')].forEach(b => b && (b.onclick = chalSheet)); - document.querySelectorAll('[data-cj]').forEach(b => b.onclick = async () => { await api(`/challenges/${b.dataset.cj}/join`, {}); buzz(); toast('Joined!'); routes.friends(); }); - document.querySelectorAll('[data-cc]').forEach(b => b.onclick = async () => { const on = b.classList.contains('on'); b.classList.toggle('on'); buzz([8, 30, 14]); if (!on) { const r = b.getBoundingClientRect(); burst(r.left + 25, r.top + 25); } await api(`/challenges/${b.dataset.cc}/check`, {day: TODAY(), done: !on}); routes.friends(); }); + $$('[data-cj]').forEach(b => b.onclick = async () => { await api(`/challenges/${b.dataset.cj}/join`, {}); buzz(); toast('Joined!'); routes.friends(); }); + $$('[data-cc]').forEach(b => b.onclick = async () => { const on = b.classList.contains('on'); b.classList.toggle('on'); buzz([8, 30, 14]); if (!on) { const r = b.getBoundingClientRect(); burst(r.left + 27, r.top + 27); chime(); } await api(`/challenges/${b.dataset.cc}/check`, {day: TODAY(), done: !on}); routes.friends(); }); if ((ME.inbox || []).some(m => !m.r)) api('/inbox/read', {}).then(() => { ME.inbox.forEach(m => m.r = 1); setMe(ME); }); }; function chalCard(c) { - const day = Math.min(c.days, Math.max(1, Math.round((new Date(TODAY()) - new Date(c.start)) / 864e5) + 1)), on = c.mine.includes(TODAY()); - return `
${esc(c.icon)}
${esc(c.title)}
Day ${day} of ${c.days} Β· ${c.members.length} member${c.members.length > 1 ? 's' : ''}
- ${c.joined ? `` : ``}
-
${c.members.slice(0, 5).map(m => `
${esc(m.avatar)}${esc(m.display)}
${m.count}/${c.days}
`).join('')}
`; + const day = Math.min(c.days, Math.max(1, Math.round((new Date(TODAY()) - new Date(c.start)) / 864e5) + 1)), on = c.mine.includes(TODAY()), col = /^#[0-9a-f]{6}$/i.test(c.color) ? c.color : '#ffb13b'; + return `
${ic(c.icon)}
${esc(c.title)}
Day ${day} of ${c.days} Β· ${c.members.length} member${c.members.length > 1 ? 's' : ''}
+ ${c.joined ? `` : ``}
+
${c.members.slice(0, 5).map(m => `
${av(m)}
${esc(m.display)}
${m.count}/${c.days}
`).join('')}
`; } function chalSheet() { - const fr = ME.friends || []; let ic = 'πŸ†', days = 30; - openSheet(`

New challenge

-
${[['30 days of gym','πŸ‹οΈ'],['Read daily','πŸ“š'],['Morning prayer','πŸ™'],['Meditate 10 min','🧘'],['No sugar','🍬'],['10k steps','🚢']].map(([t, i]) => ``).join('')}
+ const fr = ME.friends || []; let icn = 'trophy', days = 30; + openSheet(`

New challenge

+
${[['30 days of gym','dumbbell'],['Read daily','book'],['Morning prayer','pray'],['Meditate 10 min','lotus'],['No sugar','ban'],['10k steps','walk']].map(([t, i]) => ``).join('')}
-
${[7, 21, 30, 66].map(d => ``).join('')}
- -
${fr.length ? fr.map(f => ``).join('') : '

Add friends first β€” or create it now and invite later.

'}
+
${[7, 21, 30, 66].map(d => ``).join('')}
+ +
${fr.length ? fr.map(f => ``).join('') : '

Add friends first, or create it now and invite later.

'}
`); - document.querySelectorAll('.chips button').forEach(b => b.onclick = () => { const t = b.dataset.t; $('#ct').value = t; ic = b.dataset.ic; buzz(4); }); - document.querySelectorAll('#cl button').forEach(b => b.onclick = () => { days = +b.dataset.l; document.querySelectorAll('#cl button').forEach(x => x.classList.toggle('on', x === b)); }); - $('#cs').onclick = async () => { const title = $('#ct').value.trim() || '30-day challenge'; await api('/challenges', {title, icon: ic, days, invite: [...document.querySelectorAll('.ci:checked')].map(x => x.value)}); closeSheet(); buzz([10, 30, 10]); toast('Challenge started πŸ†'); routes.friends(); }; + $$('.chips button').forEach(b => b.onclick = () => { $('#ct').value = b.dataset.t; icn = b.dataset.ic; buzz(4); }); + $$('#cl button').forEach(b => b.onclick = () => { days = +b.dataset.l; $$('#cl button').forEach(x => x.classList.toggle('on', x === b)); }); + $('#cs').onclick = async () => { const title = $('#ct').value.trim() || '30-day challenge'; await api('/challenges', {title, icon: icn, days, color: '#ffb13b', invite: [...$$('.ci:checked')].map(x => x.value)}); closeSheet(); buzz([10, 30, 10]); confettiRain(); toast(`${ic('trophy')} Challenge started`); routes.friends(); }; } function ago(t) { const s = (Date.now() - t) / 1000; return s < 60 ? 'now' : s < 3600 ? Math.floor(s / 60) + 'm' : s < 86400 ? Math.floor(s / 3600) + 'h' : Math.floor(s / 86400) + 'd'; } -function copy(t) { (navigator.clipboard ? navigator.clipboard.writeText(t) : Promise.reject()).then(() => toast('Link copied ✨'), () => prompt('Copy this link', t)); buzz(); } +function copy(t) { (navigator.clipboard ? navigator.clipboard.writeText(t) : Promise.reject()).then(() => toast('Link copied'), () => prompt('Copy this link', t)); buzz(); } /* ---------- share card ---------- */ routes.share = id => { const hs = habits(), h = hs.find(x => x.id === id) || hs.slice().sort((a, b) => streakOf(b) - streakOf(a))[0]; if (!h) { location.hash = '#/home'; return; } - app.innerHTML = `
${backBtn('#/habit/' + h.id)}
Share
-
- -

1080 Γ— 1920 Β· perfect for Instagram & WhatsApp stories

`; - let theme = 'gold', blob = null; + app.innerHTML = `
${backBtn('#/habit/' + h.id)}
Share
+
+ +

1080 Γ— 1920 Β· made for Instagram & WhatsApp stories

`; + let theme = 'blaze', blob = null; const render = async () => { blob = await drawCard(h, theme); $('#card').src = URL.createObjectURL(blob); }; - document.querySelectorAll('[data-th]').forEach(b => b.onclick = () => { theme = b.dataset.th; buzz(4); document.querySelectorAll('[data-th]').forEach(x => x.classList.toggle('on', x === b)); render(); }); + $$('[data-th]').forEach(b => b.onclick = () => { theme = b.dataset.th; buzz(4); $$('[data-th]').forEach(x => x.classList.toggle('on', x === b)); render(); }); const fname = `ember-${h.name.replace(/\W+/g, '-').toLowerCase()}-${streakOf(h)}.png`; const save = () => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = fname; a.click(); toast('Image saved'); }; $('#dl').onclick = save; $('#sv').onclick = async () => { buzz(); const f = new File([blob], fname, {type: 'image/png'}); if (navigator.canShare && navigator.canShare({files: [f]})) { try { await navigator.share({files: [f], title: 'My Ember streak'}); } catch(e){} } else save(); }; document.fonts.ready.then(render); }; +const loadImg = src => new Promise(r => { const i = new Image(); i.onload = () => r(i); i.onerror = () => r(null); i.src = src; }); async function drawCard(h, theme) { const W = 1080, H = 1920, c = document.createElement('canvas'); c.width = W; c.height = H; const g = c.getContext('2d'); - const T = {gold: ['#1c1408', '#070504', '#f2c46d'], ember: ['#3a1206', '#0a0303', '#ff8a4a'], night: ['#141433', '#04040c', '#b9a6ff']}[theme]; - let bg = g.createRadialGradient(W/2, 640, 50, W/2, 800, 1400); bg.addColorStop(0, T[0]); bg.addColorStop(1, T[1]); g.fillStyle = bg; g.fillRect(0, 0, W, H); - for (let i = 0; i < 90; i++) { g.globalAlpha = Math.random() * .5; g.fillStyle = T[2]; g.beginPath(); g.arc(Math.random() * W, Math.random() * H, Math.random() * 3, 0, 7); g.fill(); } + const T = {blaze: ['#ff6a2b', '#ff2d8a', '#8b5cff'], aurora: ['#8b5cff', '#38e1ff', '#ff2d8a'], neon: ['#ff2d8a', '#c45cff', '#ffd36b']}[theme]; + g.fillStyle = '#07030b'; g.fillRect(0, 0, W, H); + const blob = (x, y, r, col, a) => { const gr = g.createRadialGradient(x, y, 0, x, y, r); gr.addColorStop(0, col + a); gr.addColorStop(1, col + '00'); g.fillStyle = gr; g.fillRect(0, 0, W, H); }; + g.globalCompositeOperation = 'lighter'; blob(150, 250, 900, T[0], 'aa'); blob(1000, 900, 800, T[1], '88'); blob(200, 1750, 900, T[2], '99'); blob(W/2, 760, 480, '#ff8a3a', '66'); g.globalCompositeOperation = 'source-over'; + const vg = g.createLinearGradient(0, 0, 0, H); vg.addColorStop(0, 'rgba(7,3,11,.1)'); vg.addColorStop(.55, 'rgba(7,3,11,.35)'); vg.addColorStop(1, 'rgba(7,3,11,.8)'); g.fillStyle = vg; g.fillRect(0, 0, W, H); + for (let i = 0; i < 140; i++) { g.globalAlpha = Math.random() * .7; g.fillStyle = Math.random() < .5 ? '#ffd36b' : '#fff'; g.beginPath(); g.arc(Math.random() * W, Math.random() * H, Math.random() * 3.2, 0, 7); g.fill(); } g.globalAlpha = 1; - const glow = g.createRadialGradient(W/2, 720, 10, W/2, 720, 420); glow.addColorStop(0, 'rgba(255,150,60,.55)'); glow.addColorStop(1, 'rgba(255,150,60,0)'); g.fillStyle = glow; g.fillRect(0, 200, W, 1000); - // flame - const fl = new Image(); fl.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(flame(true).replace('class="flame "', 'xmlns="http://www.w3.org/2000/svg" width="400" height="480"')); - await new Promise(r => { fl.onload = r; fl.onerror = r; }); try { g.drawImage(fl, W/2 - 200, 420, 400, 480); } catch(e){} - g.textAlign = 'center'; g.fillStyle = T[2]; g.font = '500 40px "Playfair Display", Georgia, serif'; g.letterSpacing = '18px'; g.fillText('E M B E R', W/2, 210); g.letterSpacing = '0px'; - const s = streakOf(h); - const gr = g.createLinearGradient(0, 1000, 0, 1300); gr.addColorStop(0, '#fff3d1'); gr.addColorStop(1, T[2]); g.fillStyle = gr; - g.font = '500 300px "Playfair Display", Georgia, serif'; g.fillText(String(s), W/2, 1250); - g.fillStyle = '#f6efe2'; g.font = '500 56px Inter, sans-serif'; g.fillText(`${unit(h)} streak`.toUpperCase().split('').join(' '), W/2, 1350); - g.font = 'italic 500 76px "Playfair Display", Georgia, serif'; g.fillText(`${h.icon} ${h.name}`, W/2, 1500); - // mini heat strip (last 28 days) + g.fillStyle = 'rgba(255,255,255,.07)'; rr(g, 80, 1430, W - 160, 330, 56); g.fill(); g.strokeStyle = 'rgba(255,255,255,.18)'; g.lineWidth = 2; g.stroke(); + const fl = await loadImg('data:image/svg+xml;charset=utf-8,' + encodeURIComponent(flameSVG(true, 420).replace('class="flame "', 'xmlns="http://www.w3.org/2000/svg"'))); + if (fl) { g.shadowColor = '#ff5a2b'; g.shadowBlur = 120; g.drawImage(fl, W/2 - 210, 300, 420, 504); g.shadowBlur = 0; } + g.textAlign = 'center'; g.fillStyle = '#fff'; g.font = '700 42px "Playfair Display", Georgia, serif'; g.fillText('E M B E R', W/2, 190); + const s = streakOf(h), x = xpInfo(); + const gr = g.createLinearGradient(200, 900, 880, 1200); gr.addColorStop(0, '#ffe7a8'); gr.addColorStop(.5, '#ff8a3a'); gr.addColorStop(1, '#ff2d8a'); g.fillStyle = gr; + g.shadowColor = '#ff2d8a'; g.shadowBlur = 60; g.font = '700 330px "Playfair Display", Georgia, serif'; g.fillText(String(s), W/2, 1170); g.shadowBlur = 0; + g.fillStyle = '#fff'; g.font = '800 50px Inter, sans-serif'; g.fillText(`${unit(h)} streak`.toUpperCase().split('').join(' '), W/2, 1265); + const icon = await loadImg('data:image/svg+xml;charset=utf-8,' + encodeURIComponent(``)); + g.fillStyle = h.color; rr(g, 130, 1480, 120, 120, 34); g.fill(); if (icon) g.drawImage(icon, 142, 1492, 96, 96); + g.textAlign = 'left'; g.fillStyle = '#fff'; g.font = 'italic 700 64px "Playfair Display", Georgia, serif'; g.fillText(h.name.slice(0, 22), 285, 1545); + g.fillStyle = 'rgba(255,255,255,.65)'; g.font = '600 34px Inter, sans-serif'; g.fillText(`Level ${x.lv} Β· ${x.title} Β· best ${bestEver(h)}`, 285, 1595); const set = new Set(h.days || []), t = new Date(); - for (let i = 0; i < 28; i++) { const k = iso(addD(t, i - 27)), x = 150 + (i % 14) * 56, y = 1590 + Math.floor(i / 14) * 56; g.fillStyle = set.has(k) ? h.color : 'rgba(255,255,255,.08)'; rr(g, x, y, 44, 44, 11); g.fill(); } - g.fillStyle = 'rgba(246,239,226,.55)'; g.font = '400 34px Inter, sans-serif'; g.fillText(`@${ME.username} Β· ${location.host}`, W/2, 1820); + for (let i = 0; i < 28; i++) { const k = iso(addD(t, i - 27)), xx = 130 + i * 29.4; g.fillStyle = set.has(k) ? h.color : 'rgba(255,255,255,.12)'; rr(g, xx, 1655, 22, 50, 8); g.fill(); } + g.textAlign = 'center'; g.fillStyle = 'rgba(255,255,255,.7)'; g.font = '500 34px Inter, sans-serif'; g.fillText(`@${ME.username} Β· ${location.host}`, W/2, 1850); return new Promise(r => c.toBlob(r, 'image/png')); } function rr(g, x, y, w, h, r) { g.beginPath(); g.moveTo(x + r, y); g.arcTo(x + w, y, x + w, y + h, r); g.arcTo(x + w, y + h, x, y + h, r); g.arcTo(x, y + h, x, y, r); g.arcTo(x, y, x + w, y, r); g.closePath(); } @@ -366,36 +523,39 @@ function installBanner() { if (standalone || localStorage.getItem('ember.noinst')) return ''; const ios = /iphone|ipad|ipod/i.test(navigator.userAgent); if (!deferredPrompt && !ios) return ''; - return `
πŸ“²
Install Ember
${ios ? 'Tap Share, then β€œAdd to Home Screen”' : 'One tap. Works offline.'}
${ios ? '' : ''}
`; + return `
${ic('install')}
Install Ember
${ios ? 'Tap Share, then β€œAdd to Home Screen”' : 'One tap. Works offline.'}
${ios ? '' : ''}
`; } async function doInstall() { if (!deferredPrompt) return; deferredPrompt.prompt(); await deferredPrompt.userChoice; deferredPrompt = null; $('#inst')?.remove(); } -addEventListener('beforeinstallprompt', e => { e.preventDefault(); deferredPrompt = e; if (location.hash.startsWith('#/home') && !$('#inst')) routes.home(); }); +addEventListener('beforeinstallprompt', e => { e.preventDefault(); deferredPrompt = e; if (location.hash.startsWith('#/home') && !$('#inst') && $('#sheet').classList.contains('hidden')) { routes.home(); after(); } }); routes.me = () => { - const total = habits().reduce((a, h) => a + (h.days||[]).length, 0); - app.innerHTML = `

${esc(ME.display)}

@${esc(ME.username)} Β· ${total} check-ins
-
Ember Pro
Unlock the full flame
Themes Β· Unlimited habits Β· Advanced stats
+ const x = xpInfo(), eb = earned(); + app.innerHTML = `

${esc(ME.display)}

@${esc(ME.username)}
+ ${ic('bolt')} LEVEL ${x.lv} Β· ${x.title.toUpperCase()} Β· ${eb.length} BADGES
+
Ember Pro
Unlock the full flame
Themes Β· Unlimited habits Β· Advanced stats

Settings

- - ${deferredPrompt ? '' : ''} - - - -
-
πŸ›‘οΈ Privacyβ€ΊπŸ“œ Termsβ€Ί -
-

Ember 1.0 Β· made with care Β· ${ME.synced === false ? 'sync pending' : 'synced'}

`; - $('#av').onclick = () => { openSheet(`

Choose your sigil

${AVATARS.map(a => ``).join('')}
`); - document.querySelectorAll('[data-a]').forEach(b => b.onclick = async () => { buzz(); setMe(await api('/profile', {avatar: b.dataset.a})); closeSheet(); routes.me(); }); }; + + + ${deferredPrompt ? `` : ''} + + + +
+
${ic('shield')} Privacyβ€Ί${ic('doc')} Termsβ€Ί +
+

Ember 2.0 Β· ${ME.synced === false ? 'sync pending' : 'synced'}

`; + const pick = () => { openSheet(`

Choose your colours

${PAL.map((_, i) => ``).join('')}
`); + $$('[data-a]').forEach(b => b.onclick = async () => { buzz(); setMe(await api('/profile', {avatar: b.dataset.a})); closeSheet(); routes.me(); after(); }); }; + $('#av').onclick = pick; $('#avb').onclick = pick; $('#nmb').onclick = async () => { const n = prompt('Display name', ME.display); if (n && n.trim()) { setMe(await api('/profile', {display: n.trim()})); routes.me(); } }; $('#snd').onclick = () => { localStorage.setItem('ember.sound', localStorage.getItem('ember.sound') === '0' ? '1' : '0'); routes.me(); }; $('#rem').onclick = remSheet; - $('#pw').onclick = async () => { const o = prompt('Current password'); if (!o) return; const n = prompt('New password (8+ characters)'); if (!n) return; try { const r = await api('/password', {old: o, new: n}); TOK = r.token; localStorage.setItem('ember.tok', TOK); toast('Password changed'); } catch(e) { toast(e.message); } }; + $('#pw').onclick = async () => { const o = prompt('Current password'); if (!o) return; const n = prompt('New password (8+ characters)'); if (!n) return; try { const r = await api('/password', {old: o, new: n}); TOK = r.token; localStorage.setItem('ember.tok', TOK); toast('Password changed'); } catch(e) { toast(esc(e.message)); } }; $('#ex').onclick = async () => { const d = await api('/export'); const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([JSON.stringify(d, null, 2)], {type: 'application/json'})); a.download = 'ember-export.json'; a.click(); }; $('#lo').onclick = () => logout(); - $('#del').onclick = async () => { const p = prompt('This permanently deletes your account and history. Type your password to confirm.'); if (!p) return; try { await api('/delete_account', {username: ME.username, password: p}); logout(true); toast('Account deleted'); } catch(e) { toast(e.message); } }; + $('#del').onclick = async () => { const p = prompt('This permanently deletes your account and history. Type your password to confirm.'); if (!p) return; try { await api('/delete_account', {username: ME.username, password: p}); logout(true); toast('Account deleted'); } catch(e) { toast(esc(e.message)); } }; }; function remSheet() { - openSheet(`

Gentle reminder

We'll remind you while Ember is open or installed on this device, if you haven't checked in yet.

+ openSheet(`

Gentle reminder

We'll remind you while Ember is open or installed on this device, if you haven't checked in yet.

`); $('#rs').onclick = async () => { if ('Notification' in window) { const p = await Notification.requestPermission(); if (p !== 'granted') { toast('Notifications are blocked in your browser settings'); return; } } localStorage.setItem('ember.rem', $('#rt').value); closeSheet(); toast('Reminder set for ' + $('#rt').value); routes.me(); }; @@ -403,19 +563,19 @@ function remSheet() { } setInterval(async () => { const r = localStorage.getItem('ember.rem'); if (!r || !ME || !('Notification' in window) || Notification.permission !== 'granted') return; const n = new Date(), hm = `${pad(n.getHours())}:${pad(n.getMinutes())}`, k = 'ember.remd'; if (hm < r || localStorage.getItem(k) === TODAY()) return; localStorage.setItem(k, TODAY()); const left = habits().filter(h => h.kind === 'daily' && !(h.days||[]).includes(TODAY())); if (!left.length) return; - const reg = await navigator.serviceWorker?.getRegistration(); const body = `${left.length} ritual${left.length > 1 ? 's' : ''} left today. Keep your ${topStreak()}-day flame alive πŸ”₯`; + const reg = await navigator.serviceWorker?.getRegistration(); const body = `${left.length} ritual${left.length > 1 ? 's' : ''} left today. Keep your ${topStreak()}-day flame alive.`; reg ? reg.showNotification('Ember', {body, icon: '/static/icon-192.png', badge: '/static/icon-192.png', tag: 'rem'}) : new Notification('Ember', {body}); }, 30000); routes.pro = () => { - const F = [['🎨', 'Signature themes', 'Obsidian, RosΓ©, Midnight Sapphire and animated app icons.'], ['∞', 'Unlimited habits', 'Track everything that matters, with sub-goals and notes.'], ['πŸ“ˆ', 'Advanced stats', 'Best time of day, habit correlations and a beautiful yearly review.'], ['🧊', 'Streak freezes', 'Protect your flame on sick days and holidays.'], ['πŸ‘₯', 'Private circles', 'Bigger group challenges with custom rules and prizes.'], ['☁️', 'Priority sync', 'Instant multi-device sync and full history backup.']]; + const F = [['palette', 'Signature themes', 'Obsidian, RosΓ©, Midnight Sapphire and animated app icons.'], ['infinity', 'Unlimited habits', 'Track everything that matters, with sub-goals and notes.'], ['chart', 'Advanced stats', 'Best time of day, habit correlations and a beautiful yearly review.'], ['snow', 'Streak freezes', 'Protect your flame on sick days and holidays.'], ['users', 'Private circles', 'Bigger group challenges with custom rules and prizes.'], ['cloud', 'Priority sync', 'Instant multi-device sync and full history backup.']]; app.innerHTML = `
${backBtn(TOK ? '#/me' : '#/welcome')}
-
${flame(true,'width:80px;height:96px')}
Coming soon

Ember Pro

Everything in Ember stays free. Pro is for those who want a little more fire.

-
${F.map(f => `
${f[0]}
${f[1]}
${f[2]}
`).join('')}
-
Β£2.99 / month
or Β£19.99 / year Β· indicative pricing
Soon
+
${flame(30, 90)}
Coming soon

Ember Pro

Everything in Ember stays free. Pro is for those who want a little more fire.

+
${F.map(f => `
${ic(f[0])}
${f[1]}
${f[2]}
`).join('')}
+
Β£2.99 / month
or Β£19.99 / year Β· indicative pricing
Soon

No payment is taken. Ember Pro isn't available yet.

`; - $('#wl').onclick = () => { localStorage.setItem('ember.prowait', 1); buzz([10, 30, 10]); burst(innerWidth / 2, innerHeight - 160); toast("You're on the list ✨"); }; + $('#wl').onclick = () => { localStorage.setItem('ember.prowait', 1); buzz([10, 30, 10]); confettiRain(); toast("You're on the list"); }; }; -async function doc(name) { app.innerHTML = `
${backBtn(TOK ? '#/me' : '#/welcome')}
Loading…
`; try { const t = await (await fetch('/' + name)).text(); $('#dc').innerHTML = (new DOMParser().parseFromString(t, 'text/html')).querySelector('article').innerHTML; } catch(e) { $('#dc').textContent = 'Offline β€” please try again.'; } } +async function doc(name) { app.innerHTML = `
${backBtn(TOK ? '#/me' : '#/welcome')}
Loading…
`; try { const t = await (await fetch('/' + name)).text(); $('#dc').innerHTML = (new DOMParser().parseFromString(t, 'text/html')).querySelector('article').innerHTML; } catch(e) { $('#dc').textContent = 'Offline. Please try again.'; } } routes.privacy = () => doc('privacy'); routes.terms = () => doc('terms'); /* ---------- boot ---------- */ @@ -424,8 +584,8 @@ routes.privacy = () => doc('privacy'); routes.terms = () => doc('terms'); if (m) { localStorage.setItem('ember.inv', m[1].toUpperCase()); history.replaceState(null, '', '/' + (TOK ? '#/friends' : '#/welcome')); } const inv = localStorage.getItem('ember.inv'); if (inv) { try { invInfo = await api('/invite/' + inv); } catch(e) { localStorage.removeItem('ember.inv'); } } - if (inv && TOK && invInfo) { try { setMe(await api('/friends', {code: inv})); localStorage.removeItem('ember.inv'); toast(`You and ${invInfo.display} are now friends ✨`); } catch(e) { localStorage.removeItem('ember.inv'); } } + if (inv && TOK && invInfo) { try { setMe(await api('/friends', {code: inv})); localStorage.removeItem('ember.inv'); toast(`You and ${esc(invInfo.display)} are now friends`); } catch(e) { localStorage.removeItem('ember.inv'); } invInfo = null; } if (TOK) { flush(); api('/me').then(setMe).catch(() => {}); } go(); badge(); - if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js').catch(() => {}); + if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js').then(r => r.update()).catch(() => {}); })();