Spaces:
Paused
Paused
Download static/app.js from Karandeeps40/ember: direct link, hf CLI and curl.
- Browser
- Download file 83.7 kB
-
https://huggingface.co/spaces/Karandeeps40/ember/resolve/main/static/app.js
- Command line
-
hf download hf://spaces/Karandeeps40/ember/static/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Karandeeps40/ember/resolve/main/static/app.js
83.7 kB
| ; | |
| 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, 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; }; | |
| /* ---------- 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 = '') => `<svg class="ico ${cls}" viewBox="0 0 24 24"><path d="${P[ik(k)]}"/></svg>`; | |
| 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:'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 `<div class="av ${cls}" style="--a:${p[0]};--b:${p[1]}">${esc(ch.toUpperCase())}</div>`; } | |
| 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 quote = () => QUOTES[Math.floor(Date.now() / 864e5) % QUOTES.length]; | |
| /* ---------- haptics, sound, confetti ---------- */ | |
| const buzz = (p = 12) => { try { navigator.vibrate && navigator.vibrate(p); } catch(e){} }; | |
| 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(880, .12); | |
| 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 = (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) => `<svg class="flame ${on ? '' : 'off'}" width="${w}" height="${w * 1.2}" viewBox="0 0 100 120"><defs> | |
| <linearGradient id="fg1" x1="0" y1="1" x2="0" y2="0"><stop offset="0" stop-color="#ff1f6b"/><stop offset=".45" stop-color="#ff6a2b"/><stop offset="1" stop-color="#ffd36b"/></linearGradient> | |
| <linearGradient id="fg2" x1="0" y1="1" x2="0" y2="0"><stop offset="0" stop-color="#ff8a2b"/><stop offset="1" stop-color="#fff1c1"/></linearGradient> | |
| <radialGradient id="fg0" cx=".5" cy=".75" r=".6"><stop offset="0" stop-color="#8b5cff" stop-opacity=".9"/><stop offset="1" stop-color="#8b5cff" stop-opacity="0"/></radialGradient></defs> | |
| <ellipse cx="50" cy="108" rx="30" ry="9" fill="url(#fg0)" opacity=".7"/> | |
| <path class="f1" fill="url(#fg1)" d="M50 4C56 26 86 40 86 74a36 36 0 0 1-72 0c0-16 8-26 16-32 0 12 6 20 13 22C38 44 40 22 50 4z"/> | |
| <path class="f2" fill="url(#fg2)" d="M51 46c4 12 20 20 20 36a21 21 0 0 1-42 0c0-9 5-15 10-18 1 7 4 11 8 12-3-11-1-22 4-30z"/> | |
| <path class="f3" fill="#fffaf0" d="M51 74c2 6 10 9 10 17a10 10 0 0 1-20 0c0-5 3-8 5-9 1 3 2 5 4 5-1-4 0-9 1-13z"/></svg>`; | |
| 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 `<div class="flamebox" style="width:${cw}px;height:${Math.round(w * 1.9)}px">${on ? `<canvas class="fcv" data-w="${w}" width="${cw * 2}" height="${Math.round(w * 3.8)}" style="width:${cw}px;height:${Math.round(w * 1.9)}px"></canvas>` : ''}<div style="position:absolute;bottom:${Math.round(w*.1)}px">${flameSVG(on, w)}</div></div>`; } | |
| 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; | |
| } | |
| /* ---------- 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.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'; } | |
| 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); | |
| /* ---------- 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), 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); | |
| let c = 0; while (s.has(iso(cur))) { c++; cur = addD(cur, -1); } return c; | |
| } | |
| function bestEver(h) { const ds = [...(h.days||[])].sort(); let b = 0, c = 0, prev = null; for (const d of ds) { const t = new Date(d + 'T12:00'); c = prev && Math.round((t - prev) / 864e5) === 1 ? c + 1 : 1; b = Math.max(b, c); prev = t; } return h.kind === 'weekly' ? Math.max(b, streakOf(h)) : b; } | |
| const weekDone = h => { const now = new Date(), mon = addD(now, -((now.getDay() + 6) % 7)); return (h.days||[]).filter(d => d >= iso(mon)).length; }; | |
| 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) => `<div class="medal">${ic(lock ? 'lock' : b[4])}</div>`; | |
| /* ---------- svg bits ---------- */ | |
| 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 `<svg width="${sz}" height="${sz}" class="rg"><defs><linearGradient id="${id}" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${c1}"/><stop offset="1" stop-color="${c2}"/></linearGradient></defs><circle cx="${sz/2}" cy="${sz/2}" r="${r}" stroke="rgba(255,255,255,.09)" stroke-width="${w}" fill="none"/><circle class="arc" cx="${sz/2}" cy="${sz/2}" r="${r}" stroke="url(#${id})" stroke-width="${w}" fill="none" stroke-linecap="round" stroke-dasharray="${C}" stroke-dashoffset="${C}" data-to="${C*(1-Math.min(1,p))}" style="transition:stroke-dashoffset 1.1s cubic-bezier(.2,1,.3,1);filter:drop-shadow(0 0 5px ${c2})"/></svg>`; } | |
| const animateRings = () => requestAnimationFrame(() => requestAnimationFrame(() => $$('.arc').forEach(a => a.style.strokeDashoffset = a.dataset.to))); | |
| const backBtn = to => `<a class="back" href="${to}"><svg viewBox="0 0 24 24"><path d="${P.back}"/></svg></a>`; | |
| const checkCore = '<span class="core"><svg viewBox="0 0 24 24"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg></span>'; | |
| 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 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(); | |
| $('#tabs').classList.toggle('hidden', !TOK || ['welcome','auth','privacy','terms','share'].includes(r)); | |
| $$('#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) => `<div class="sat hicon" style="--c:${c};${pos};animation-delay:${d}s">${ic(k)}</div>`; | |
| const SLIDES = [ | |
| {art: () => `<div class="orbit">${flame(30, 120)}</div>`, | |
| t: 'Small rituals.<br><span class="grad">Lasting fire.</span>', p: 'Ember turns the things you care about (training, reading, prayer, stillness) into a streak worth protecting.'}, | |
| {art: () => `<div class="orbit" style="padding:24px;display:block;height:auto"><div class="eyebrow">Last 14 weeks</div><div class="heat" style="grid-template-rows:repeat(7,12px);margin-top:16px">${Array.from({length: 98}, (_, i) => `<i class="${(i * 37 % 100) < (i / 1.3 + 20) ? 'on' : ''}"></i>`).join('')}</div><div class="row" style="margin-top:24px;align-items:flex-end"><div class="big" style="font-size:64px">42</div><div class="mute small" style="padding-bottom:8px">day streak<br>Level 7 · Blaze</div></div></div>`, | |
| t: 'See every day<br><span class="grad">you showed up.</span>', p: 'Quiet stats, levels and badges that reward consistency, not noise.'}, | |
| {art: () => `<div class="orbit" style="padding:8px 24px;display:block;height:auto">${[['Maya',31],['Leo',24],['Kai',12]].map(([d, n], i) => `<div class="lb ${i === 0 ? 'top top1' : 'top'}"><div class="rk">0${i + 1}</div>${av({display: d, username: d}, 'top3')}<div class="sp" style="font-weight:500">${d}</div><div class="score">${n}</div></div>`).join('')}</div>`, | |
| t: 'Better<br><span class="grad">together.</span>', p: 'Invite friends with a link, join group challenges, and send a quiet cheer when it matters.'}, | |
| ]; | |
| routes.welcome = () => { | |
| let i = 0; | |
| const draw = () => { const s = SLIDES[i]; app.innerHTML = `<div class="ob"> | |
| <div class="row" style="justify-content:space-between"><div class="logo grad">Ember</div>${i < 2 ? '<button class="mute small" id="skip">Skip</button>' : ''}</div> | |
| <div class="slide" id="sl">${s.art()}<h1>${s.t}</h1><p>${s.p}</p></div> | |
| ${invInfo ? `<div class="glass card row fade-in">${av(invInfo)}<div><b>${esc(invInfo.display)}</b> invited you<div class="small mute">Join and you'll be friends automatically</div></div></div>` : ''} | |
| <div class="dots">${SLIDES.map((_, j) => `<i class="${j === i ? 'on' : ''}"></i>`).join('')}</div> | |
| <button class="btn primary" id="next">${i < 2 ? 'Continue' : 'Create your account'}</button> | |
| <button class="btn" style="margin-top:6px" onclick="location.hash='#/auth/login'"><span class="mute">I already have an account · </span><span class="link">Sign in</span></button></div>`; | |
| $('#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(); | |
| }; | |
| let invInfo = null; | |
| routes.auth = mode => { | |
| const su = mode !== 'login'; | |
| app.innerHTML = `<div class="fade-in" style="padding-top:10px">${backBtn('#/welcome')} | |
| <div style="margin:20px 0 22px">${flame(8, 60)}<h1 style="margin-top:6px;font-size:42px">${su ? 'Light your <span class="grad">first ember.</span>' : 'Welcome <span class="grad">back.</span>'}</h1> | |
| <p class="mute" style="margin-top:10px">${su ? 'Free forever. No email needed, just a username your friends can find.' : 'Sign in to keep your streaks burning.'}</p></div> | |
| <form id="f">${su ? `<div class="field"><label>Your name</label><input name="display" autocomplete="name" placeholder="Alex" maxlength="30"></div>` : ''} | |
| <div class="field"><label>Username</label><input name="username" autocomplete="username" autocapitalize="none" spellcheck="false" placeholder="alex_runs" required></div> | |
| <div class="field"><label>Password</label><input name="password" type="password" autocomplete="${su ? 'new-password' : 'current-password'}" placeholder="${su ? 'At least 8 characters' : '••••••••'}" required></div> | |
| <div class="err" id="err"></div> | |
| <button class="btn primary" id="go">${su ? 'Create account' : 'Sign in'}</button></form> | |
| <p class="center small mute" style="margin-top:18px">${su ? 'Have an account? <a class="link" href="#/auth/login">Sign in</a>' : 'New here? <a class="link" href="#/auth/signup">Create an account</a>'}</p> | |
| ${su ? '<p class="center small dim" style="margin-top:22px;line-height:1.6">By continuing you agree to our <a class="link" href="#/terms">Terms</a> and <a class="link" href="#/privacy">Privacy Policy</a>.</p>' : ''}</div>`; | |
| $('#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'); 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 = '<svg class="ico" style="width:16px;height:16px;stroke-width:3" viewBox="0 0 24 24"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>'; | |
| routes.home = () => { | |
| 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 {l: 'MTWTFSS'[i], n: d.getDate(), on: hs.some(h => (h.days||[]).includes(k)), today: k === t}; }); | |
| app.innerHTML = `<div class="top"><div><div class="small mute" style="font-weight:600">${greet()},</div><div class="serif" style="font-size:28px">${esc(ME.display)}</div></div><a href="#/me">${av(ME)}</a></div> | |
| ${installBanner()} | |
| <div class="hero glass tilt fade-in"><div class="row" style="align-items:flex-end"><div class="sp"> | |
| <a href="#/badges" class="lvl">${ic('bolt')} LV ${x.lv} · ${x.title.toUpperCase()}</a> | |
| <div class="row" style="gap:8px;align-items:baseline;margin-top:14px"><span class="big grad">${st}</span><span class="mute" style="font-weight:700">${st === 1 ? 'day' : 'days'}<br>streak</span></div></div> | |
| <div style="margin:-20px -18px -6px 0">${flame(st, 92, st > 0 || doneToday > 0)}</div></div> | |
| <div class="row" style="margin-top:16px;gap:14px"><div class="ring" style="width:62px;height:62px">${ring(pct, 62, 7, 'hr')}<b style="font-size:14px">${Math.round(pct * 100)}%</b></div> | |
| <div class="sp"><div class="row small" style="justify-content:space-between"><b>${hs.length ? `${doneToday} of ${hs.length} today` : 'Add a habit to begin'}</b><span class="mute">${x.into}/${x.need} XP</span></div> | |
| <div class="xpbar" style="margin-top:9px"><i style="width:${x.into / x.need * 100}%"></i></div></div></div> | |
| <div class="week">${wk.map(d => `<div class="${d.on ? 'on' : ''} ${d.today ? 'today' : ''}"><span>${d.l}</span><i>${d.on ? tickSvg : d.n}</i></div>`).join('')}</div></div> | |
| <h2>Today · ${new Date().toLocaleDateString(undefined, {weekday: 'long', day: 'numeric', month: 'short'})}</h2> | |
| <div id="list">${hs.length ? hs.map((h, i) => habitRow(h, i)).join('') : `<div class="empty glass"><div class="hicon" style="--c:#2fe0a0;margin:0 auto">${ic('leaf')}</div><div class="serif" style="font-size:24px;margin:14px 0 6px">Begin with one ritual</div><p class="mute small" style="margin-bottom:16px">Tiny and daily beats big and rare.</p><button class="btn primary" onclick="presetSheet()">Add your first habit</button></div>`}</div> | |
| ${hs.length ? `<button class="btn ghost" style="margin-top:4px" onclick="presetSheet()">${ic('plus')} New habit</button>` : ''} | |
| <div class="quote glass fade-in"><div class="eyebrow" style="margin-bottom:16px">Today's thought</div><q>${esc(q[0])}</q><div class="small mute" style="margin-top:10px">${esc(q[1])}</div></div>`; | |
| bindRows(); | |
| 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` : 'Daily'; | |
| return `<div class="habit glass ${on ? 'done' : ''}" style="--c:${h.color};animation-delay:${i * 70}ms" data-id="${h.id}"><i class="glow"></i> | |
| <div class="hicon">${ic(h.icon)}</div><div class="sp" data-open><div class="nm">${esc(h.name)}</div><div class="sub">${s ? `<span class="acc">${s}</span> ${unit(h)}${s > 1 ? 's' : ''}` : 'Start a streak'} · ${sub}</div></div> | |
| <button class="chk ${on ? 'on' : ''}" aria-label="Check in">${ring(habitProgress(h), 54, 4, 'hr' + h.id, h.color, '#ff2d8a')}${checkCore}</button></div>`; | |
| } | |
| function bindRows() { | |
| $$('.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), 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); | |
| 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>${B[1]}</b>`), 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) && !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 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(`<div class="center celebrate" style="padding:4px 0 6px">${flame(30, 110)}<div class="pill" style="margin-top:4px">${kind === 'level' ? 'Level up' : kind === 'perfect' ? 'Flawless' : 'Milestone'}</div> | |
| <h1 style="margin:14px 0 4px;font-size:46px"><span class="grad">${T[0]}</span></h1><div class="serif" style="font-size:22px;font-style:italic">${T[1]}</div><p class="mute" style="margin-top:10px">${T[2]}</p> | |
| <div class="row" style="margin:20px 0 4px;gap:10px"><span class="lvl">${ic('bolt')} LV ${x.lv}</span><div class="xpbar sp"><i style="width:${x.into / x.need * 100}%"></i></div></div> | |
| <button class="btn primary" style="margin-top:20px" onclick="location.hash='#/share/${h.id}'">Share your streak</button><button class="btn" id="kg">Keep going</button></div>`); | |
| $('#kg').onclick = () => { closeSheet(); go(); }; | |
| mountFlames(); confettiRain(); buzz([20, 40, 20, 40, 60]); setTimeout(() => tick(1567, .4), 250); | |
| } | |
| /* ---------- habit sheet ---------- */ | |
| function presetSheet(first) { | |
| openSheet(`<h1 style="font-size:30px">${first ? 'What will you <span class="grad">tend</span>?' : 'New <span class="grad">habit</span>'}</h1><p class="mute small" style="margin:6px 0 16px">Pick a classic or craft your own.</p> | |
| <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px">${PRESETS.map((p, i) => `<button class="glass row" style="padding:12px;border-radius:18px;text-align:left;--c:${p.color}" data-p="${i}"><span class="hicon" style="width:40px;height:40px;border-radius:13px">${ic(p.icon)}</span><span class="small" style="font-weight:700">${p.name}<br><span class="dim" style="font-weight:500">${p.kind === 'weekly' ? p.n + '× / week' : 'Daily'}</span></span></button>`).join('')}</div> | |
| <button class="btn ghost" id="custom">${ic('spark')} Create custom habit</button>`); | |
| $$('[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; h.icon = ik(h.icon); | |
| openSheet(`<h1 style="font-size:28px;margin-bottom:16px">${edit ? 'Edit habit' : 'Make it <span class="grad">yours</span>'}</h1> | |
| <div class="field"><label>Name</label><input id="hn" value="${esc(h.name)}" placeholder="e.g. Stretch 10 min" maxlength="40"></div> | |
| <label class="small mute" style="margin:0 4px 8px;display:block;font-weight:600">Icon</label><div class="grid-ic">${ICONS.map(i => `<button data-i="${i}" class="${i === h.icon ? 'on' : ''}" style="--c:${h.color}">${ic(i)}</button>`).join('')}</div> | |
| <label class="small mute" style="margin:0 4px 8px;display:block;font-weight:600">Colour</label><div class="colors">${COLORS.map(c => `<button data-c="${c}" style="--c:${c}" class="${c === h.color ? 'on' : ''}"></button>`).join('')}</div> | |
| <label class="small mute" style="margin:0 4px 8px;display:block;font-weight:600">Target</label><div class="seg" id="kind"><button data-k="daily">Every day</button><button data-k="weekly">Times per week</button></div> | |
| <div id="nw" class="row" style="margin-bottom:16px;justify-content:center;gap:18px"><button class="back" id="nm">−</button><span class="serif grad" style="font-size:34px" id="nv"></span><span class="mute">× per week</span><button class="back" id="np">+</button></div> | |
| <label class="row small" style="margin:0 4px 18px"><input type="checkbox" id="priv" ${h.private ? 'checked' : ''} style="width:18px;height:18px;accent-color:#ff2d8a"> <span class="mute">Keep private (hidden from friends)</span></label> | |
| <div class="err" id="herr"></div><button class="btn primary" id="hs">${edit ? 'Save changes' : 'Add habit'}</button> | |
| ${edit ? '<button class="btn" id="hd" style="color:#ff8f9a">Delete habit</button>' : ''}`); | |
| 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(); | |
| $$('[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, 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; } | |
| function closeSheet() { $('#sheet').classList.add('hidden'); } | |
| $('#fab').onclick = () => { buzz(); presetSheet(); }; | |
| /* ---------- habit detail ---------- */ | |
| let calMonth = null; | |
| routes.habit = id => { | |
| const h = habits().find(x => x.id === id); if (!h) { location.hash = '#/home'; return; } | |
| const s = streakOf(h), best = bestEver(h), total = (h.days||[]).length; | |
| const created = new Date(h.created || Date.now()), age = Math.max(1, Math.round((Date.now() - created) / 864e5) + 1); | |
| const rate = h.kind === 'weekly' ? Math.min(100, Math.round(total / (Math.ceil(age / 7) * h.n) * 100)) : Math.min(100, Math.round(total / age * 100)); | |
| const set = new Set(h.days || []), t = new Date(); | |
| const start = addD(t, -7 * 17 - ((t.getDay() + 6) % 7)); | |
| const cells = Array.from({length: 18 * 7}, (_, i) => { const d = addD(start, i), k = iso(d); return d > t ? '<i style="opacity:0"></i>' : `<i class="${set.has(k) ? 'on' : ''} ${k === TODAY() ? 't' : ''}"></i>`; }).join(''); | |
| calMonth = calMonth || new Date(t.getFullYear(), t.getMonth(), 1); | |
| const m0 = calMonth, first = (m0.getDay() + 6) % 7, dim = new Date(m0.getFullYear(), m0.getMonth() + 1, 0).getDate(); | |
| const cal = Array.from({length: first}, () => '<span></span>').join('') + Array.from({length: dim}, (_, i) => { const d = new Date(m0.getFullYear(), m0.getMonth(), i + 1), k = iso(d); return `<button data-d="${k}" class="${set.has(k) ? 'on' : ''} ${k === TODAY() ? 't' : ''}" ${d > t ? 'disabled' : ''}>${i + 1}</button>`; }).join(''); | |
| const on = set.has(TODAY()); | |
| app.innerHTML = `<div class="fade-in" style="--c:${h.color}"><div class="top">${backBtn('#/home')}<div class="row" style="gap:8px"><button class="back" id="ed" aria-label="Edit">${ic('edit')}</button><a class="back" href="#/share/${h.id}" aria-label="Share">${ic('share')}</a></div></div> | |
| <div class="row" style="margin-bottom:24px"><div class="hicon">${ic(h.icon)}</div><div class="sp"><h1 style="font-size:28px">${esc(h.name)}</h1><div class="mute small" style="margin-top:4px">${h.kind === 'weekly' ? `${h.n}× per week · ${weekDone(h)} of ${h.n} this week` : 'Every day'}</div></div></div> | |
| <div class="hero row" style="align-items:flex-end"><div class="sp"><div class="eyebrow">${unit(h)} streak</div><div class="big" style="margin-top:16px">${s}</div></div> | |
| <div class="center"><button class="chk ${on ? 'on' : ''}" id="tg" style="width:72px;height:72px">${ring(habitProgress(h), 72, 3, 'dr')}<span class="core" style="width:56px;height:56px"><svg viewBox="0 0 24 24" style="width:24px;height:24px"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg></span></button><div class="small mute" style="margin-top:8px">${on ? 'Done' : 'Check in'}</div></div></div> | |
| <div class="stats3"><div class="glass"><div class="v grad">${best}</div><div class="l">BEST</div></div><div class="glass"><div class="v">${total}</div><div class="l">TOTAL</div></div><div class="glass"><div class="v">${rate}<span style="font-size:16px">%</span></div><div class="l">CONSISTENCY</div></div></div> | |
| <h2>Last 18 weeks</h2><div class="glass card"><div class="heat">${cells}</div></div> | |
| <h2 class="row"><span class="sp">${m0.toLocaleDateString(undefined, {month: 'long', year: 'numeric'})}</span><button id="pm" class="back" style="width:34px;height:34px">‹</button><button id="nm2" class="back" style="width:34px;height:34px">›</button></h2> | |
| <div class="glass card"><div class="cal">${['M','T','W','T','F','S','S'].map(x => `<b>${x}</b>`).join('')}${cal}</div><p class="small dim center" style="margin-top:12px">Tap a past day to log or undo it.</p></div> | |
| <button class="btn primary" style="margin-top:8px" onclick="location.hash='#/share/${h.id}'">${ic('share')} Share streak card</button></div>`; | |
| $('#tg').onclick = e => toggle(id, TODAY(), e.currentTarget); | |
| $$('[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(), 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 = 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 ? '<i style="opacity:0"></i>' : `<i class="${n ? 'on' : ''}" style="${n ? `opacity:${.4 + .6 * n / Math.max(1, hs.length)}` : ''}"></i>`; }).join(''); | |
| const eb = earned(); | |
| app.innerHTML = `<div class="fade-in"><h1>Your <span class="grad">fire</span>, measured.</h1><p class="mute" style="margin:8px 0 18px">Every check-in, across every habit.</p> | |
| <a href="#/badges" class="hero glass tilt row" style="display:flex;gap:16px"><div class="ring" style="width:84px;height:84px">${ring(x.into / x.need, 84, 8, 'lv')}<b class="serif" style="font-size:28px">${x.lv}</b></div><div class="sp"><div class="small mute" style="font-weight:700;letter-spacing:.12em">LEVEL · ${x.title.toUpperCase()}</div><div class="serif" style="font-size:26px;margin:4px 0">${x.xp.toLocaleString()} XP</div><div class="small mute">${eb.length}/${BADGES.length} badges · tap to view</div></div></a> | |
| <div class="stats3"><div class="glass"><div class="v grad">${topStreak()}</div><div class="l">BEST NOW</div></div><div class="glass"><div class="v">${total}</div><div class="l">ALL-TIME</div></div><div class="glass"><div class="v">${Math.min(100, Math.round(last30 / possible * 100))}<span style="font-size:16px">%</span></div><div class="l">30-DAY RATE</div></div></div> | |
| <h2>Last 14 days</h2><div class="glass card"><div class="bars">${days.map((d, i) => `<div><i style="height:${d.v / mx * 85}%;animation-delay:${i * 35}ms"></i>${d.l}</div>`).join('')}</div></div> | |
| <h2>Six months</h2><div class="glass card"><div class="heat" style="--c:#ff6a2b">${heat}</div><div class="small dim" style="margin-top:10px">${all.size} active days</div></div> | |
| <h2>By habit</h2><div class="glass card">${hs.length ? hs.map(h => { const s = streakOf(h); return `<a class="lb" href="#/habit/${h.id}" style="--c:${h.color}"><div class="hicon" style="width:40px;height:40px;border-radius:13px">${ic(h.icon)}</div><div class="sp"><div style="font-weight:700">${esc(h.name)}</div><div class="small mute">Best ${bestEver(h)} · ${(h.days||[]).length} total</div></div><div class="grad serif" style="font-size:24px">${s}</div></a>`; }).join('') : '<p class="mute">No habits yet.</p>'}</div> | |
| <a href="#/pro" class="glass card row" style="margin-top:6px"><span class="hicon" style="--c:#8b5cff;width:42px;height:42px">${ic('chart')}</span><div class="sp"><b>Advanced insights</b><div class="small mute">Best time of day, correlations, yearly review</div></div><span class="pill">Pro</span></a></div>`; | |
| }; | |
| /* ---------- badges ---------- */ | |
| routes.badges = () => { | |
| const x = xpInfo(), eb = earned(); | |
| app.innerHTML = `<div class="fade-in"><div class="top">${backBtn('#/stats')}<span class="lvl">${ic('bolt')} ${x.xp.toLocaleString()} XP</span></div> | |
| <div class="hero glass tilt center"><div class="ring" style="width:120px;height:120px;margin:4px auto 10px">${ring(x.into / x.need, 120, 10, 'bl')}<div style="position:absolute;inset:0;display:grid;place-items:center"><div><div class="serif grad" style="font-size:46px;line-height:1">${x.lv}</div><div class="small mute" style="font-weight:700">LEVEL</div></div></div></div> | |
| <h1 style="font-size:32px">${x.title}</h1><p class="mute small" style="margin-top:6px">${x.need - x.into} XP to level ${x.lv + 1} · ${eb.length} of ${BADGES.length} badges</p> | |
| <p class="small dim" style="margin-top:10px">+10 per check-in · +5 per best-streak day · +15 per perfect day · +20 per friend</p></div> | |
| <h2>Achievements</h2><div class="bgrid">${BADGES.map((b, i) => { const ok = eb.includes(b[0]); return `<div class="bdg glass ${ok ? '' : 'lock'}" style="animation-delay:${i * 40}ms">${medal(b, !ok)}<div class="nm">${b[1]}</div><div class="ds">${b[2]}</div></div>`; }).join('')}</div></div>`; | |
| }; | |
| /* ---------- friends ---------- */ | |
| 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 `<div class="podium">${order.map((r, i) => r ? `<div class="p ${cls[i]}">${i === 1 ? `<svg class="crown" viewBox="0 0 24 24" fill="currentColor"><path d="${P.crown}"/></svg>` : ''}${av(r, i === 1 ? 'xl' : '')}<div class="nm">${esc(r.display)}${r.username === ME.username ? ' (you)' : ''}</div><div class="st grad">${r.streak}</div><div class="blk">${rk[i]}</div></div>` : '<div></div>').join('')}</div>`; | |
| } | |
| routes.friends = async () => { | |
| app.innerHTML = `<div class="fade-in"><h1>Your <span class="grad">circle</span></h1><p class="mute" style="margin:8px 0 18px">Streaks are lighter when they're shared.</p><div id="fbody"><div class="glass card mute">Loading…</div></div></div>`; | |
| 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 = ` | |
| <h2 style="margin-top:8px">Leaderboard · current streak</h2><div class="glass card" style="padding:4px 24px"> | |
| ${lb.map((r, i) => `<div class="lb ${r.username === ME.username ? 'me' : ''} ${i < 3 && lb.length > 1 ? 'top' : ''} ${i === 0 && lb.length > 1 ? 'top1' : ''}"><div class="rk">${String(i + 1).padStart(2, '0')}</div>${av(r, i < 3 && lb.length > 1 ? 'top3' : '')}<div class="sp"><div style="font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${esc(r.display)}${r.username === ME.username ? ' <span class="dim small">(you)</span>' : ''}</div><div class="small mute">${r.week} this week</div></div> | |
| ${r.username !== ME.username ? `<div class="react" data-u="${esc(r.username)}"><button data-k="cheer" title="Cheer" aria-label="Cheer">${ic('spark')}</button><button data-k="nudge" title="Nudge" aria-label="Nudge">${ic('bell')}</button></div>` : ''}<div class="score">${r.streak}</div></div>`).join('')} | |
| ${lb.length < 2 ? '<p class="small mute center" style="padding:14px 0 6px">Invite a friend to start competing.</p>' : ''}</div> | |
| ${inbox.length ? `<h2>Activity</h2><div class="glass card">${inbox.map(m => `<div class="inbox"><span class="hicon" style="--c:${m.k === 'nudge' ? '#8b5cff' : '#ff2d8a'};width:38px;height:38px;border-radius:12px">${ic((RX[m.k] || RX.cheer)[0])}</span><div class="sp"><b>@${esc(m.f)}</b> ${(RX[m.k] || RX.cheer)[1]}</div><span class="small dim">${ago(m.t)}</span></div>`).join('')}</div>` : ''} | |
| <h2 class="row"><span class="sp">Group challenges</span><button class="link" style="letter-spacing:0;text-transform:none;font-size:14px" id="nc">+ New</button></h2> | |
| ${ch.length ? ch.map(chalCard).join('') : `<div class="glass card center"><div class="hicon" style="--c:#ffb13b;margin:0 auto">${ic('trophy')}</div><p class="mute small" style="margin:12px 0">Start a 30-day challenge with your friends.</p><button class="btn sm ghost" style="margin:0 auto" id="nc2">Create challenge</button></div>`} | |
| <h2>Invite friends</h2><div class="glass card"><div class="small mute">Your invite code</div><div class="code grad">${esc(ME.invite)}</div> | |
| <div class="row"><button class="btn primary sm sp" id="sh">Share invite link</button><button class="btn ghost sm" id="cp">Copy</button></div></div> | |
| <div class="glass card"><div class="small mute" style="margin-bottom:8px">Have a code or username?</div><form class="row" id="af"><input id="fc" placeholder="CODE or @username" autocapitalize="characters" style="flex:1;min-width:0;height:48px;border-radius:15px;padding:0 14px;background:rgba(255,255,255,.06);border:1px solid var(--line)"><button class="btn primary sm" style="height:48px">Add</button></form><div class="err" id="ferr"></div></div>`; | |
| 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]); confettiRain(); toast('Friend added'); routes.friends(); } catch(err) { $('#ferr').textContent = err.message; } }; | |
| [$('#nc'), $('#nc2')].forEach(b => b && (b.onclick = chalSheet)); | |
| $$('[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()), col = /^#[0-9a-f]{6}$/i.test(c.color) ? c.color : '#ffb13b'; | |
| return `<div class="glass card" style="--c:${col}"><div class="row"><div class="hicon">${ic(c.icon)}</div><div class="sp"><div style="font-weight:700;font-size:16.5px">${esc(c.title)}</div><div class="small mute">Day ${day} of ${c.days} · ${c.members.length} member${c.members.length > 1 ? 's' : ''}</div></div> | |
| ${c.joined ? `<button class="chk ${on ? 'on' : ''}" data-cc="${c.id}">${ring(c.mine.length / c.days, 54, 4, 'c' + c.id, col, '#ff2d8a')}${checkCore}</button>` : `<button class="btn primary sm" data-cj="${c.id}">Join</button>`}</div> | |
| <div style="margin-top:14px">${c.members.slice(0, 5).map(m => `<div class="row small" style="margin:9px 0"><div style="transform:scale(.72);margin:-6px">${av(m)}</div><span style="width:70px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600">${esc(m.display)}</span><div class="prog sp"><i style="width:${m.count / c.days * 100}%"></i></div><span class="mute" style="width:42px;text-align:right">${m.count}/${c.days}</span></div>`).join('')}</div></div>`; | |
| } | |
| function chalSheet() { | |
| const fr = ME.friends || []; let icn = 'trophy', days = 30; | |
| openSheet(`<h1 style="font-size:28px;margin-bottom:14px">New <span class="grad">challenge</span></h1> | |
| <div class="chips">${[['30 days of gym','dumbbell'],['Read daily','book'],['Morning prayer','pray'],['Meditate 10 min','lotus'],['No sugar','ban'],['10k steps','walk']].map(([t, i]) => `<button data-t="${t}" data-ic="${i}">${ic(i)} ${t}</button>`).join('')}</div> | |
| <div class="field"><label>Title</label><input id="ct" placeholder="30 days of gym" maxlength="40"></div> | |
| <label class="small mute" style="margin:0 4px 8px;display:block;font-weight:600">Length</label><div class="seg" id="cl">${[7, 21, 30, 66].map(d => `<button data-l="${d}" class="${d === 30 ? 'on' : ''}">${d} days</button>`).join('')}</div> | |
| <label class="small mute" style="margin:0 4px 8px;display:block;font-weight:600">Invite friends</label> | |
| <div style="margin-bottom:16px">${fr.length ? fr.map(f => `<label class="row" style="padding:8px 4px"><input type="checkbox" value="${esc(f.username)}" class="ci" checked style="width:18px;height:18px;accent-color:#ff2d8a">${av(f)}<span>${esc(f.display)}</span></label>`).join('') : '<p class="small dim">Add friends first, or create it now and invite later.</p>'}</div> | |
| <button class="btn primary" id="cs">Start challenge</button>`); | |
| $$('.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(); } | |
| /* ---------- 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 = `<div class="fade-in"><div class="top">${backBtn('#/habit/' + h.id)}<div class="serif" style="font-size:22px">Share</div><span style="width:42px"></span></div> | |
| <img id="card" class="share-prev" alt="Streak card"><div class="seg" id="th"><button data-th="blaze" class="on">Noir</button><button data-th="aurora">Paper</button><button data-th="neon">Umber</button></div> | |
| <button class="btn primary" id="sv">${ic('share')} Share to Stories</button><button class="btn ghost" style="margin-top:10px" id="dl">${ic('download')} Save image</button> | |
| <p class="center small dim" style="margin-top:14px">1080 × 1920 · made for Instagram & WhatsApp stories</p></div>`; | |
| let theme = 'blaze', blob = null; | |
| const render = async () => { blob = await drawCard(h, theme); $('#card').src = URL.createObjectURL(blob); }; | |
| $$('[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 = {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; | |
| 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(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="${P[ik(h.icon)]}"/></svg>`)); | |
| 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)), 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(); } | |
| /* ---------- me / pro / docs ---------- */ | |
| function installBanner() { | |
| const standalone = matchMedia('(display-mode: standalone)').matches || navigator.standalone; | |
| if (standalone || localStorage.getItem('ember.noinst')) return ''; | |
| const ios = /iphone|ipad|ipod/i.test(navigator.userAgent); | |
| if (!deferredPrompt && !ios) return ''; | |
| return `<div class="install fade-in" id="inst"><span class="hicon" style="--c:#ff6a2b;width:42px;height:42px">${ic('install')}</span><div class="sp"><b>Install Ember</b><div class="small mute">${ios ? 'Tap Share, then “Add to Home Screen”' : 'One tap. Works offline.'}</div></div>${ios ? '' : '<button class="btn primary sm" onclick="doInstall()">Install</button>'}<button class="mute" onclick="localStorage.setItem(\'ember.noinst\',1);this.parentNode.remove()">✕</button></div>`; | |
| } | |
| 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') && $('#sheet').classList.contains('hidden')) { routes.home(); after(); } }); | |
| routes.me = () => { | |
| const x = xpInfo(), eb = earned(); | |
| app.innerHTML = `<div class="fade-in"><div class="center" style="padding:14px 0 6px"><button id="av" style="margin:0 auto;display:block">${av(ME, 'lg')}</button><h1 style="margin-top:16px">${esc(ME.display)}</h1><div class="mute" style="margin-top:4px">@${esc(ME.username)}</div> | |
| <a href="#/badges" class="lvl" style="margin-top:12px">${ic('bolt')} LEVEL ${x.lv} · ${x.title.toUpperCase()} · ${eb.length} BADGES</a></div> | |
| <a href="#/pro" class="pro-hero tilt" style="display:block;margin:20px 0 6px;border:1px solid #ff7a2f66"><div class="pill">Ember Pro</div><div class="serif" style="font-size:26px;margin:12px 0 4px">Unlock the <span class="grad">full flame</span></div><div class="small mute">Themes · Unlimited habits · Advanced stats</div></a> | |
| <h2>Settings</h2><div class="glass card list" style="padding:4px 16px"> | |
| <button id="nmb">${ic('edit')} <span>Display name</span><span class="chev">${esc(ME.display)} ›</span></button> | |
| ${deferredPrompt ? `<button onclick="doInstall()">${ic('install')} <span>Install app</span><span class="chev">›</span></button>` : ''} | |
| <button id="snd">${ic('sound')} <span>Sounds</span><span class="chev">${localStorage.getItem('ember.sound') === '0' ? 'Off' : 'On'}</span></button> | |
| <button id="rem">${ic('clock')} <span>Daily reminder</span><span class="chev">${localStorage.getItem('ember.rem') || 'Off'} ›</span></button> | |
| <button id="pw">${ic('lock')} <span>Change password</span><span class="chev">›</span></button> | |
| <button id="ex">${ic('download')} <span>Export my data</span><span class="chev">›</span></button></div> | |
| <div class="glass card list" style="padding:4px 16px"><a href="#/privacy">${ic('shield')} <span>Privacy</span><span class="chev">›</span></a><a href="#/terms">${ic('doc')} <span>Terms</span><span class="chev">›</span></a> | |
| <button id="lo">${ic('logout')} <span>Sign out</span></button><button id="del" style="color:#ff8f9a">${ic('trash')} <span>Delete account</span></button></div> | |
| <p class="center small dim" style="margin:10px 0">Ember 3.0 · ${ME.synced === false ? 'sync pending' : 'synced'}</p></div>`; | |
| const pick = () => { openSheet(`<h1 style="font-size:26px;margin-bottom:16px">Choose your <span class="grad">colours</span></h1><div class="grid-ic" style="grid-template-columns:repeat(4,1fr);gap:16px">${PAL.map((_, i) => `<button data-a="p${i}" style="border:0;background:none">${av({...ME, avatar: 'p' + i}, 'xl')}</button>`).join('')}</div>`); | |
| $$('[data-a]').forEach(b => b.onclick = async () => { buzz(); setMe(await api('/profile', {avatar: b.dataset.a})); closeSheet(); routes.me(); after(); }); }; | |
| $('#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(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(esc(e.message)); } }; | |
| }; | |
| function remSheet() { | |
| openSheet(`<h1 style="font-size:28px">Gentle <span class="grad">reminder</span></h1><p class="mute small" style="margin:8px 0 16px">We'll remind you while Ember is open or installed on this device, if you haven't checked in yet.</p> | |
| <div class="field"><label>Time</label><input type="time" id="rt" value="${localStorage.getItem('ember.rem') || '20:00'}"></div> | |
| <button class="btn primary" id="rs">Turn on</button><button class="btn" id="ro">Turn off</button>`); | |
| $('#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(); }; | |
| $('#ro').onclick = () => { localStorage.removeItem('ember.rem'); closeSheet(); routes.me(); }; | |
| } | |
| 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.`; | |
| 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 = [['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 = `<div class="fade-in"><div class="top">${backBtn(TOK ? '#/me' : '#/welcome')}<span></span></div> | |
| <div class="pro-hero glass tilt">${flame(30, 90)}<div class="pill">Coming soon</div><h1 style="margin:14px 0 8px;font-size:46px">Ember <span class="grad">Pro</span></h1><p class="mute">Everything in Ember stays free. Pro is for those who want a little more fire.</p></div> | |
| <div class="glass card" style="margin-top:16px">${F.map(f => `<div class="feat"><div class="fi">${ic(f[0])}</div><div><b>${f[1]}</b><div class="small mute" style="margin-top:3px;line-height:1.5">${f[2]}</div></div></div>`).join('')}</div> | |
| <div class="glass card row" style="justify-content:space-between"><div><div class="serif" style="font-size:30px"><span class="grad">£2.99</span><span class="small mute"> / month</span></div><div class="small dim">or £19.99 / year · indicative pricing</div></div><span class="pill">Soon</span></div> | |
| <button class="btn primary" id="wl">Notify me when it launches</button><p class="center small dim" style="margin-top:12px">No payment is taken. Ember Pro isn't available yet.</p></div>`; | |
| $('#wl').onclick = () => { localStorage.setItem('ember.prowait', 1); buzz([10, 30, 10]); confettiRain(); toast("You're on the list"); }; | |
| }; | |
| async function doc(name) { app.innerHTML = `<div class="fade-in doc"><div class="top">${backBtn(TOK ? '#/me' : '#/welcome')}<span></span></div><div id="dc" class="mute">Loading…</div></div>`; 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'); | |
| /* ---------- v3 restrained overrides ---------- */ | |
| const ACC = '#E8A04C'; | |
| function burst() {} | |
| function confettiRain() {} | |
| function applyTilt() {} | |
| function mountFlames() {} | |
| 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:500 12px Inter,sans-serif;letter-spacing:.04em;color:${ACC};pointer-events:none;transform:translate(-50%,0);opacity:1;transition:transform .9s cubic-bezier(.2,.8,.2,1),opacity .9s`; document.body.appendChild(e); requestAnimationFrame(() => { e.style.transform = 'translate(-50%,-24px)'; e.style.opacity = '0'; }); setTimeout(() => e.remove(), 1000); } | |
| function flame(streak, base = 96, on = true) { const w = Math.round(base * (.72 + .28 * Math.min(1, (streak || 0) / 30))); | |
| return `<div class="flamebox" style="width:${w}px;height:${w}px"><svg class="mark ${on ? '' : 'off'}" width="${w}" height="${w}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${(24 / w * 1.1).toFixed(2)}" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22a7 7 0 0 0 7-7c0-3.6-2-6-3.8-8.2-.4 1.9-1.4 3-2.6 3.4.3-3.3-1-6.5-3.6-8.2.3 3.7-1.6 6.2-3.3 8.4A7.4 7.4 0 0 0 5 15a7 7 0 0 0 7 7z"/><path class="core" fill="currentColor" stroke="none" d="M12 20a2.9 2.9 0 0 0 2.9-2.9c0-2-1.5-3-2.9-5.3-1.4 2.3-2.9 3.3-2.9 5.3A2.9 2.9 0 0 0 12 20z"/></svg></div>`; } | |
| function ring(p, sz = 64, w = 6, id) { w = Math.max(1.5, Math.min(w, sz / 22)); const r = (sz - w) / 2, C = 2 * Math.PI * r; | |
| return `<svg width="${sz}" height="${sz}" class="rg"><circle cx="${sz/2}" cy="${sz/2}" r="${r}" stroke="rgba(255,255,255,.08)" stroke-width="${w}" fill="none"/><circle class="arc" cx="${sz/2}" cy="${sz/2}" r="${r}" stroke="${ACC}" stroke-width="${w}" fill="none" stroke-linecap="round" stroke-dasharray="${C}" stroke-dashoffset="${C}" data-to="${C*(1-Math.min(1,p))}" style="transition:stroke-dashoffset .9s cubic-bezier(.2,.8,.2,1)"/></svg>`; } | |
| function av(u, cls = '') { const ch = [...(u.display || u.username || '?').trim()][0] || '?'; return `<div class="av ${cls}">${esc(ch.toUpperCase())}</div>`; } | |
| function podium() { return ''; } | |
| function closeSheet() { $('#sheet').classList.add('hidden'); $$('.moment').forEach(m => m.remove()); } | |
| function celebrate(kind, h, n) { | |
| const x = xpInfo(), pd = perfectDays(); | |
| const T = {streak: [String(n), `${unit(h)} streak`, esc(h.name), "Consistency, quietly compounding."], | |
| perfect: [String(habits().filter(z => z.kind !== 'weekly').length), 'of ' + habits().filter(z => z.kind !== 'weekly').length + ' complete', 'Perfect day', `${pd} perfect day${pd > 1 ? 's' : ''} so far · +15 XP`], | |
| level: [String(n), 'level', x.title, 'A new level. Same quiet work.']}[kind]; | |
| const m = document.createElement('div'); m.className = 'moment celebrate'; | |
| m.innerHTML = `<div class="in"><div class="eyebrow">${kind === 'level' ? 'Level up' : kind === 'perfect' ? 'Today' : 'Milestone'}</div> | |
| <div style="margin:48px 0 8px">${flame(30, 56)}</div><div class="big">${T[0]}</div><div class="mute" style="font-size:17px;margin-top:8px">${T[1]}</div> | |
| <h1 style="margin-top:40px;font-size:28px">${T[2]}</h1><p class="mute" style="margin-top:8px">${T[3]}</p> | |
| <div style="margin-top:48px"><button class="btn primary" id="msh">Share</button><button class="btn" id="mkg" style="margin-top:8px">Continue</button></div></div>`; | |
| document.body.appendChild(m); buzz(18); | |
| m.querySelector('#msh').onclick = () => { m.remove(); location.hash = '#/share/' + h.id; }; | |
| m.querySelector('#mkg').onclick = () => { m.remove(); go(); }; | |
| } | |
| routes.home = () => { | |
| 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 {l: 'MTWTFSS'[i], n: d.getDate(), on: hs.some(h => (h.days||[]).includes(k)), today: k === t}; }); | |
| app.innerHTML = `<div class="top"><div><div class="eyebrow">${new Date().toLocaleDateString(undefined, {weekday: 'long', day: 'numeric', month: 'long'})}</div><div style="font-size:24px;font-weight:600;letter-spacing:-.03em;margin-top:8px">${greet()}, ${esc(ME.display)}</div></div><a href="#/me">${av(ME)}</a></div> | |
| ${installBanner()} | |
| <div class="hero row fade-in" style="align-items:flex-end"><div class="sp"><div class="eyebrow">Current streak</div><div class="big" style="margin-top:16px">${st}</div><div class="mute small" style="margin-top:8px">${st === 1 ? 'day' : 'days'}</div></div>${flame(st, 72, st > 0 || doneToday > 0)}</div> | |
| <div class="glass card row fade-in" style="padding:16px 24px"><div class="ring" style="width:56px;height:56px">${ring(pct, 56, 2.5, 'hr')}<b style="font-size:13px">${Math.round(pct * 100)}</b></div> | |
| <div class="sp"><div style="font-weight:500">${hs.length ? `${doneToday} of ${hs.length} today` : 'No habits yet'}</div><div class="small mute" style="margin-top:2px">Level ${x.lv} · ${x.title} · ${x.into}/${x.need} XP</div></div></div> | |
| <div class="week">${wk.map(d => `<div class="${d.on ? 'on' : ''} ${d.today ? 'today' : ''}"><span>${d.l}</span><i>${d.n}</i></div>`).join('')}</div> | |
| <h2>Today</h2> | |
| <div id="list">${hs.length ? hs.map((h, i) => habitRow(h, i)).join('') : `<div class="empty glass"><div style="font-size:20px;font-weight:600">Begin with one ritual</div><p class="mute small" style="margin:8px 0 24px">Tiny and daily beats big and rare.</p><button class="btn primary" onclick="presetSheet()">Add a habit</button></div>`}</div> | |
| <div class="quote fade-in"><div class="eyebrow" style="margin-bottom:16px">Today's thought</div><q>${esc(q[0])}</q><div class="small dim" style="margin-top:16px">${esc(q[1])}</div></div>`; | |
| $$('.habit').forEach(el => el.classList.add('glass')); | |
| bindRows(); | |
| api('/me').then(m => { const was = JSON.stringify(ME); setMe(m); if (JSON.stringify(m) !== was && location.hash.startsWith('#/home') && $('#sheet').classList.contains('hidden') && !$('.moment')) { routes.home(); after(); } }).catch(() => {}); | |
| }; | |
| async function drawCard(h, theme) { | |
| await Promise.all(['200 400px Inter', '500 60px Inter', '600 30px Inter'].map(f => document.fonts.load(f).catch(() => {}))); | |
| const W = 1080, H = 1920, c = document.createElement('canvas'); c.width = W; c.height = H; const g = c.getContext('2d'); | |
| const T = {blaze: ['#0A0A0B', '#F4F2EE', ACC], aurora: ['#F2EFE9', '#141414', '#B8692A'], neon: ['#17130F', '#F4EBDD', ACC]}[theme] || ['#0A0A0B', '#F4F2EE', ACC]; | |
| const [bg, ink, acc] = T, mute = theme === 'aurora' ? 'rgba(20,20,20,.5)' : 'rgba(244,242,238,.5)', line = theme === 'aurora' ? 'rgba(0,0,0,.12)' : 'rgba(255,255,255,.12)'; | |
| g.fillStyle = bg; g.fillRect(0, 0, W, H); | |
| const L = 104, s = streakOf(h), x = xpInfo(); | |
| g.fillStyle = ink; g.font = '600 30px Inter'; g.letterSpacing = '9px'; g.fillText('EMBER', L, 170); | |
| g.textAlign = 'right'; g.fillStyle = mute; g.font = '500 30px Inter'; g.letterSpacing = '3px'; g.fillText(new Date().toLocaleDateString('en-GB', {day: '2-digit', month: 'short', year: 'numeric'}).toUpperCase(), W - L, 170); g.textAlign = 'left'; | |
| g.fillStyle = mute; g.font = '500 30px Inter'; g.letterSpacing = '6px'; g.fillText(`${unit(h).toUpperCase()} STREAK`, L, 620); | |
| g.letterSpacing = '-24px'; g.fillStyle = ink; g.font = '200 520px Inter'; g.fillText(String(s), L - 24, 1080); | |
| g.letterSpacing = '0px'; g.fillStyle = line; g.fillRect(L, 1200, W - 2 * L, 2); | |
| g.fillStyle = ink; g.font = '500 76px Inter'; g.letterSpacing = '-2px'; g.fillText(h.name.slice(0, 22), L, 1330); | |
| g.fillStyle = mute; g.font = '400 36px Inter'; g.letterSpacing = '0px'; g.fillText(`Best ${bestEver(h)} · ${(h.days||[]).length} check-ins · Level ${x.lv}`, L, 1400); | |
| const set = new Set(h.days || []), t = new Date(), cw = (W - 2 * L - 27 * 10) / 28; | |
| for (let i = 0; i < 28; i++) { const k = iso(addD(t, i - 27)); g.fillStyle = set.has(k) ? acc : line; g.fillRect(L + i * (cw + 10), 1500, cw, 64); } | |
| g.fillStyle = mute; g.font = '400 28px Inter'; g.fillText('LAST 28 DAYS', L, 1620); | |
| const mk = await loadImg('data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="72" height="72" fill="none" stroke="${acc}" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22a7 7 0 0 0 7-7c0-3.6-2-6-3.8-8.2-.4 1.9-1.4 3-2.6 3.4.3-3.3-1-6.5-3.6-8.2.3 3.7-1.6 6.2-3.3 8.4A7.4 7.4 0 0 0 5 15a7 7 0 0 0 7 7z"/><path fill="${acc}" stroke="none" d="M12 20a2.9 2.9 0 0 0 2.9-2.9c0-2-1.5-3-2.9-5.3-1.4 2.3-2.9 3.3-2.9 5.3A2.9 2.9 0 0 0 12 20z"/></svg>`)); | |
| if (mk) g.drawImage(mk, L - 6, 1716, 72, 72); | |
| g.fillStyle = ink; g.font = '500 32px Inter'; g.fillText('@' + ME.username, L + 90, 1764); | |
| g.textAlign = 'right'; g.fillStyle = mute; g.font = '400 28px Inter'; g.fillText(location.host, W - L, 1764); | |
| return new Promise(r => c.toBlob(r, 'image/png')); | |
| } | |
| /* ---------- boot ---------- */ | |
| (async function boot() { | |
| const m = location.pathname.match(/^\/i\/([A-Za-z0-9]+)/); | |
| 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 ${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').then(r => r.update()).catch(() => {}); | |
| })(); | |