'use strict';
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 = '') => ` `;
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 `
${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 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) => `
`;
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;
}
/* ---------- 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) => `${ic(lock ? 'lock' : b[4])}
`;
/* ---------- 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 ` `; }
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 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) => `${ic(k)}
`;
const SLIDES = [
{art: () => `${flame(30, 120)}
`,
t: 'Small rituals.Lasting fire. ', p: 'Ember turns the things you care about (training, reading, prayer, stillness) into a streak worth protecting.'},
{art: () => `Last 14 weeks
${Array.from({length: 98}, (_, i) => ` `).join('')}
42
day streak Level 7 · Blaze
`,
t: 'See every dayyou showed up. ', p: 'Quiet stats, levels and badges that reward consistency, not noise.'},
{art: () => `${[['Maya',31],['Leo',24],['Kai',12]].map(([d, n], i) => `
0${i + 1}
${av({display: d, username: d}, 'top3')}
${d}
${n}
`).join('')}
`,
t: 'Bettertogether. ', 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 = `
Ember
${i < 2 ? '
Skip ' : ''}
${invInfo ? `
${av(invInfo)}
${esc(invInfo.display)} invited you
Join and you'll be friends automatically
` : ''}
${SLIDES.map((_, j) => ` `).join('')}
${i < 2 ? 'Continue' : 'Create your account'}
I already have an account · Sign in `;
$('#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 = `${backBtn('#/welcome')}
${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 ? 'Have an account? Sign in ' : 'New here? Create an account '}
${su ? '
By continuing you agree to our Terms and Privacy Policy .
' : ''}
`;
$('#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 = ' ';
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 = `
${installBanner()}
${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('') : `
${ic('leaf')}
Begin with one ritual
Tiny and daily beats big and rare.
Add your first habit `}
${hs.length ? `${ic('plus')} New habit ` : ''}
Today's thought
${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') && $('#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 `
${ic(h.icon)}
${esc(h.name)}
${s ? `${s} ${unit(h)}${s > 1 ? 's' : ''}` : 'Start a streak'} · ${sub}
${ring(habitProgress(h), 54, 4, 'hr' + h.id, h.color, '#ff2d8a')}${checkCore} `;
}
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[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) && !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(`${flame(30, 110)}
${kind === 'level' ? 'Level up' : kind === 'perfect' ? 'Flawless' : 'Milestone'}
${T[0]} ${T[1]}
${T[2]}
Share your streak Keep going `);
$('#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) => `${ic(p.icon)} ${p.name}${p.kind === 'weekly' ? p.n + '× / week' : 'Daily'} `).join('')}
${ic('spark')} Create custom habit `);
$$('[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(`${edit ? 'Edit habit' : 'Make it yours '}
Name
Icon ${ICONS.map(i => `${ic(i)} `).join('')}
Colour ${COLORS.map(c => ` `).join('')}
Target Every day Times per week
− × per week +
Keep private (hidden from friends)
${edit ? 'Save changes' : 'Add habit'}
${edit ? 'Delete habit ' : ''}`);
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 ? ' ' : ` `; }).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}, () => ' ').join('') + Array.from({length: dim}, (_, i) => { const d = new Date(m0.getFullYear(), m0.getMonth(), i + 1), k = iso(d); return ` t ? 'disabled' : ''}>${i + 1} `; }).join('');
const on = set.has(TODAY());
app.innerHTML = `
${ic(h.icon)}
${esc(h.name)} ${h.kind === 'weekly' ? `${h.n}× per week · ${weekDone(h)} of ${h.n} this week` : 'Every day'}
${ring(habitProgress(h), 72, 3, 'dr')} ${on ? 'Done' : 'Check in'}
Last 18 weeks
${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.
${ic('share')} Share streak card `;
$('#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 ? ' ' : ` `; }).join('');
const eb = earned();
app.innerHTML = ``;
};
/* ---------- 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.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: ['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.
`;
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 = `
Leaderboard · current streak
${lb.map((r, i) => `
${String(i + 1).padStart(2, '0')}
${av(r, i < 3 && lb.length > 1 ? 'top3' : '')}
${esc(r.display)}${r.username === ME.username ? ' (you) ' : ''}
${r.week} this week
${r.username !== ME.username ? `
${ic('spark')} ${ic('bell')}
` : ''}
${r.streak}
`).join('')}
${lb.length < 2 ? '
Invite a friend to start competing.
' : ''}
${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 + New
${ch.length ? ch.map(chalCard).join('') : `${ic('trophy')}
Start a 30-day challenge with your friends.
Create challenge `}
Invite friends Your invite code
${esc(ME.invite)}
Share invite link Copy
`;
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 `${ic(c.icon)}
${esc(c.title)}
Day ${day} of ${c.days} · ${c.members.length} member${c.members.length > 1 ? 's' : ''}
${c.joined ? `
${ring(c.mine.length / c.days, 54, 4, 'c' + c.id, col, '#ff2d8a')}${checkCore} ` : `
Join `}
${c.members.slice(0, 5).map(m => `
${av(m)}
${esc(m.display)}
${m.count}/${c.days} `).join('')}
`;
}
function chalSheet() {
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]) => `${ic(i)} ${t} `).join('')}
Title
Length ${[7, 21, 30, 66].map(d => `${d} days `).join('')}
Invite friends
${fr.length ? fr.map(f => `
${av(f)}${esc(f.display)} `).join('') : '
Add friends first, or create it now and invite later.
'}
Start challenge `);
$$('.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 = `${backBtn('#/habit/' + h.id)}
Share
Noir Paper Umber
${ic('share')} Share to Stories ${ic('download')} Save image
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); };
$$('[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(` `));
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 `${ic('install')} Install Ember ${ios ? 'Tap Share, then “Add to Home Screen”' : 'One tap. Works offline.'}
${ios ? '' : '
Install '}
✕ `;
}
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 = `
Ember Pro
Unlock the full flame
Themes · Unlimited habits · Advanced stats
Settings
${ic('edit')} Display name ${esc(ME.display)} ›
${deferredPrompt ? `${ic('install')} Install app › ` : ''}
${ic('sound')} Sounds ${localStorage.getItem('ember.sound') === '0' ? 'Off' : 'On'}
${ic('clock')} Daily reminder ${localStorage.getItem('ember.rem') || 'Off'} ›
${ic('lock')} Change password ›
${ic('download')} Export my data ›
Ember 3.0 · ${ME.synced === false ? 'sync pending' : 'synced'}
`;
const pick = () => { openSheet(`Choose your colours ${PAL.map((_, i) => `${av({...ME, avatar: 'p' + i}, 'xl')} `).join('')}
`);
$$('[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(`Gentle reminder We'll remind you while Ember is open or installed on this device, if you haven't checked in yet.
Time
Turn on Turn off `);
$('#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 = `${backBtn(TOK ? '#/me' : '#/welcome')}
${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 => `
`).join('')}
£2.99 / month
or £19.99 / year · indicative pricing
Soon
Notify me when it launches No payment is taken. Ember Pro isn't available yet.
`;
$('#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.'; } }
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 ``; }
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 ` `; }
function av(u, cls = '') { const ch = [...(u.display || u.username || '?').trim()][0] || '?'; return `${esc(ch.toUpperCase())}
`; }
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 = `${kind === 'level' ? 'Level up' : kind === 'perfect' ? 'Today' : 'Milestone'}
${flame(30, 56)}
${T[0]}
${T[1]}
${T[2]} ${T[3]}
Share Continue
`;
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 = `${new Date().toLocaleDateString(undefined, {weekday: 'long', day: 'numeric', month: 'long'})}
${greet()}, ${esc(ME.display)}
${av(ME)}
${installBanner()}
Current streak
${st}
${st === 1 ? 'day' : 'days'}
${flame(st, 72, st > 0 || doneToday > 0)}
${ring(pct, 56, 2.5, 'hr')}${Math.round(pct * 100)}
${hs.length ? `${doneToday} of ${hs.length} today` : 'No habits yet'}
Level ${x.lv} · ${x.title} · ${x.into}/${x.need} XP
${wk.map(d => `
${d.l} ${d.n}
`).join('')}
Today
${hs.length ? hs.map((h, i) => habitRow(h, i)).join('') : `
Begin with one ritual
Tiny and daily beats big and rare.
Add a habit `}
Today's thought
${esc(q[0])} ${esc(q[1])}
`;
$$('.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(` `));
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(() => {});
})();