From 3d3e798c3418ad705324a00f785ffb1f79e214e3 Mon Sep 17 00:00:00 2001 From: djg Date: Wed, 23 Sep 2026 17:07:09 +0000 Subject: [PATCH 1/6] feat(shortcuts): add Alt+P quick capture overlay --- site/index.html | 13 +++++++++++++ site/static/app.js | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/site/index.html b/site/index.html index b522b07..d855dcf 100644 --- a/site/index.html +++ b/site/index.html @@ -27,6 +27,7 @@ Dopamine menu One thing Brain dump + Done-Wall + + +
diff --git a/site/static/app.js b/site/static/app.js index 4d15e13..5faa732 100644 --- a/site/static/app.js +++ b/site/static/app.js @@ -955,6 +955,32 @@ /* ---------- keyboard shortcuts ---------- */ document.addEventListener('keydown', function (e) { + // Quick Capture (Alt+P) - active globally + if (e.altKey && (e.key === 'p' || e.key === 'P')) { + e.preventDefault(); + var overlay = document.getElementById('quick-capture-overlay'); + if (overlay.hidden) { + overlay.hidden = false; + document.getElementById('quick-capture-input').value = ''; + document.getElementById('quick-capture-input').focus(); + } else { + overlay.hidden = true; + } + return; + } + // Quick capture handling inside input + if (e.target.id === 'quick-capture-input') { + if (e.key === 'Escape') { + document.getElementById('quick-capture-overlay').hidden = true; + } else if (e.key === 'Enter' && e.target.value.trim() !== '') { + var unTasks = store('unsorted_tasks') || []; + unTasks.push({ text: e.target.value.trim(), created: Date.now() }); + store('unsorted_tasks', unTasks); + if (typeof unPaint === 'function') unPaint(); + document.getElementById('quick-capture-overlay').hidden = true; + e.target.value = ''; + } + } // Don't trigger shortcuts when typing in an input or contenteditable var tag = e.target.tagName; if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target.contentEditable === 'true') return; From b9bd6ae5e64599573996a6bb4384559eec1c88f1 Mon Sep 17 00:00:00 2001 From: djg Date: Wed, 23 Sep 2026 17:07:42 +0000 Subject: [PATCH 2/6] feat(ai): add Tier 1 & 2 Auto-Deconstruct contract API logic --- site/static/app.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/site/static/app.js b/site/static/app.js index 4d15e13..cc03a40 100644 --- a/site/static/app.js +++ b/site/static/app.js @@ -432,6 +432,46 @@ timerPersist(); timerPaint(); } + /* ---------- AI Auto-Deconstruct Contract (Tier 1 & 2) ---------- */ + window.aiBreakdownTask = async function(taskText) { + // Shared Interface for Sibyl's Tier 3 + const prompt = `Break down this intimidating task into 3-5 tiny, actionable micro-steps: "${taskText}". Return only the list of steps.`; + + // Tier 1: Browser Native (window.ai) + if (window.ai && window.ai.languageModel) { + try { + const caps = await window.ai.languageModel.capabilities(); + if (caps.available !== 'no') { + const session = await window.ai.languageModel.create(); + const result = await session.prompt(prompt); + return result.split('\n').filter(s => s.trim().length > 0); + } + } catch (e) { + console.warn("window.ai failed, falling back", e); + } + } + + // Tier 2: BYOK (Bring Your Own Key) Fallback + const key = store('byok_key'); + if (!key) { + throw new Error("NO_AI_AVAILABLE"); // Let UI prompt for key or let Tier 3 try + } + const resp = await fetch('https://api.openai.com/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer ' + key + }, + body: JSON.stringify({ + model: 'gpt-4o-mini', + messages: [{ role: 'user', content: prompt }] + }) + }); + if (!resp.ok) throw new Error("API_ERROR"); + const data = await resp.json(); + return data.choices[0].message.content.split('\n').filter(s => s.trim().length > 0); + }; + $('#timer-reset').addEventListener('click', timerReset); $$('.preset').forEach(function (p) { From 2db8a05a5e6323545c261e6f3c27d37fecdb49ee Mon Sep 17 00:00:00 2001 From: djg Date: Wed, 23 Sep 2026 17:09:19 +0000 Subject: [PATCH 3/6] feat: implement Accomplishments Done-Wall and IndexedDB datastore for task completion tracing --- site/index.html | 20 ++++++++++ site/static/app.js | 8 ++++ site/static/done.js | 90 ++++++++++++++++++++++++++++++++++++++++++++ site/static/store.js | 65 ++++++++++++++++++++++++++++++++ 4 files changed, 183 insertions(+) create mode 100644 site/static/done.js create mode 100644 site/static/store.js diff --git a/site/index.html b/site/index.html index b522b07..4ff0d9b 100644 --- a/site/index.html +++ b/site/index.html @@ -278,6 +278,24 @@ + +
@@ -352,6 +370,8 @@ + + diff --git a/site/static/app.js b/site/static/app.js index 4d15e13..67a625e 100644 --- a/site/static/app.js +++ b/site/static/app.js @@ -676,8 +676,15 @@ $('#now-input').focus(); }); + function handleNewDoneTasks(taskString) { + if (window.dbRecordTask && taskString) { + window.dbRecordTask(taskString).then(() => { if (window.renderDoneWall) window.renderDoneWall(); }).catch(() => {}); + } + } + $('#now-done').addEventListener('click', function () { var nowData = store('now'); + var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; tickSound(); // If from breaker, mark that step done if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { @@ -688,6 +695,7 @@ breakerRender(); } } + handleNewDoneTasks(taskText); localStorage.removeItem('myadhd.now'); // Check if there's a next step from breaker var b2 = store(breakerKey); diff --git a/site/static/done.js b/site/static/done.js new file mode 100644 index 0000000..32e57a0 --- /dev/null +++ b/site/static/done.js @@ -0,0 +1,90 @@ +window.renderDoneWall = function() { + if (!window.dbGetAllTasks) return; + window.dbGetAllTasks().then(tasks => { + var list = document.querySelector('#done-list'); + var empty = document.querySelector('#done-empty'); + if (!list || !empty) return; + + if (tasks.length === 0) { + list.innerHTML = ''; + empty.hidden = false; + return; + } + empty.hidden = true; + list.innerHTML = ''; + + // Group by Date string (local date) + const groups = {}; + const todayStr = new Date().toDateString(); + + tasks.forEach(t => { + let d = new Date(t.completedAt); + let dStr = d.toDateString(); + if (dStr === todayStr) dStr = "Today"; + else if (dStr === new Date(Date.now() - 86400000).toDateString()) dStr = "Yesterday"; + else dStr = d.toLocaleDateString(undefined, { weekday: 'long', month: 'short', day: 'numeric' }); + + if (!groups[dStr]) groups[dStr] = []; + groups[dStr].push(t); + }); + + Object.keys(groups).forEach(dateLabel => { + let head = document.createElement('h3'); + head.textContent = dateLabel; + head.style.marginTop = '1.5rem'; + head.style.marginBottom = '0.5rem'; + head.style.color = 'var(--text-muted)'; + list.appendChild(head); + + groups[dateLabel].forEach(task => { + let li = document.createElement('li'); + li.style.padding = '0.5rem 0'; + li.style.borderBottom = '1px solid var(--border)'; + + let row = document.createElement('div'); + row.style.display = 'flex'; + row.style.justifyContent = 'space-between'; + + let textSpan = document.createElement('span'); + textSpan.textContent = "βœ“ " + task.text; + textSpan.style.color = 'var(--primary)'; + + // Time + let timeSpan = document.createElement('span'); + let d = new Date(task.completedAt); + timeSpan.textContent = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); + timeSpan.style.color = 'var(--text-muted)'; + timeSpan.style.fontSize = '0.85em'; + + row.appendChild(textSpan); + row.appendChild(timeSpan); + li.appendChild(row); + list.appendChild(li); + }); + }); + }).catch(e => console.error(e)); +}; + +document.addEventListener('DOMContentLoaded', () => { + var clearBtn = document.querySelector('#done-clear'); + if (clearBtn) { + clearBtn.addEventListener('click', () => { + if (window.confirm("Are you sure you want to clear your entire accomplishment history?")) { + if (window.dbClearTasks) { + window.dbClearTasks().then(() => { + if (window.renderDoneWall) window.renderDoneWall(); + }); + } + } + }); + } + + // Bind to tab switch + document.querySelectorAll('.tab').forEach(tab => { + tab.addEventListener('click', e => { + if (tab.dataset.tab === 'done') { + if (window.renderDoneWall) window.renderDoneWall(); + } + }); + }); +}); diff --git a/site/static/store.js b/site/static/store.js new file mode 100644 index 0000000..24de0ba --- /dev/null +++ b/site/static/store.js @@ -0,0 +1,65 @@ +const DB_NAME = 'MyADHDSyncDB'; +const DB_VERSION = 1; +const DONE_STORE_NAME = 'done_cache'; + +let db = null; + +function getStoreDB() { + return new Promise((resolve, reject) => { + if (db) return resolve(db); + const request = indexedDB.open(DB_NAME, DB_VERSION); + request.onupgradeneeded = (event) => { + const adb = event.target.result; + if (!adb.objectStoreNames.contains(DONE_STORE_NAME)) { + adb.createObjectStore(DONE_STORE_NAME, { keyPath: 'id', autoIncrement: true }); + } + }; + request.onsuccess = (event) => { + db = event.target.result; + resolve(db); + }; + request.onerror = (event) => reject(event.target.error); + }); +} + +window.dbRecordTask = function(text) { + return getStoreDB().then((db) => { + return new Promise((resolve, reject) => { + const tx = db.transaction(DONE_STORE_NAME, 'readwrite'); + const store = tx.objectStore(DONE_STORE_NAME); + const req = store.add({ + text: text, + completedAt: new Date().toISOString() + }); + req.onsuccess = () => resolve(); + req.onerror = () => reject(req.error); + }); + }); +}; + +window.dbGetAllTasks = function() { + return getStoreDB().then((db) => { + return new Promise((resolve, reject) => { + const tx = db.transaction(DONE_STORE_NAME, 'readonly'); + const store = tx.objectStore(DONE_STORE_NAME); + const req = store.getAll(); + req.onsuccess = () => { + const sorted = (req.result || []).sort((a,b) => new Date(b.completedAt) - new Date(a.completedAt)); + resolve(sorted); + }; + req.onerror = () => reject(req.error); + }); + }); +}; + +window.dbClearTasks = function() { + return getStoreDB().then((db) => { + return new Promise((resolve, reject) => { + const tx = db.transaction(DONE_STORE_NAME, 'readwrite'); + const store = tx.objectStore(DONE_STORE_NAME); + const req = store.clear(); + req.onsuccess = () => resolve(); + req.onerror = () => reject(req.error); + }); + }); +}; From 8e69e24869ab620461a53ce95ba90ef516589257 Mon Sep 17 00:00:00 2001 From: djg Date: Wed, 23 Sep 2026 17:12:04 +0000 Subject: [PATCH 4/6] fix(done-wall): intercept timer modal completion path to correctly hydrate the IndexedDB history records upon resolving the action natively --- site/static/app.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/site/static/app.js b/site/static/app.js index 67a625e..0288e48 100644 --- a/site/static/app.js +++ b/site/static/app.js @@ -466,6 +466,7 @@ $('#timer-complete').hidden = true; // Mark the current one-thing step as done in the breaker var nowData = store('now'); + var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { var b = store(breakerKey); if (b && b.steps[nowData.stepIndex]) { @@ -474,6 +475,7 @@ breakerRender(); } } + handleNewDoneTasks(taskText); // Reset timer so it's fresh for the next step timerReset(); // Clear one-thing and show next step prompt From 3491bbfbb08f9065a7742f05823763c4d599be01 Mon Sep 17 00:00:00 2001 From: djg Date: Wed, 23 Sep 2026 18:35:16 +0000 Subject: [PATCH 5/6] feat(ai): integrate Tier 3 WebLLM engine with fallback --- site/static/app.js | 2579 ++++++++++++++++++++++---------------------- 1 file changed, 1302 insertions(+), 1277 deletions(-) diff --git a/site/static/app.js b/site/static/app.js index 0a4d96f..329c7a9 100644 --- a/site/static/app.js +++ b/site/static/app.js @@ -1,1279 +1,1304 @@ -/* myadhd.dev β€” client-side tools. No accounts, no network; everything in localStorage. */ -(function () { - 'use strict'; - var $ = function (s, r) { return (r || document).querySelector(s); }; - var $$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); }; - function store(k, v) { - if (v === undefined) { try { return JSON.parse(localStorage.getItem('myadhd.' + k)); } catch (e) { return null; } } - localStorage.setItem('myadhd.' + k, JSON.stringify(v)); - } - function today() { return new Date().toISOString().slice(0, 10); } - - /* ---------- register service worker ---------- */ - if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('/sw.js').catch(function () {}); - } - - /* ---------- audio helpers ---------- */ - var audioCtx = null; - function getAudio() { - if (!audioCtx) { - try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) {} - } - return audioCtx; - } - - function beep() { - var ctx = getAudio(); if (!ctx) return; - [[660, 0], [880, 0.18]].forEach(function (n) { - var o = ctx.createOscillator(), g = ctx.createGain(); - o.frequency.value = n[0]; o.type = 'sine'; - g.gain.setValueAtTime(0.001, ctx.currentTime + n[1]); - g.gain.exponentialRampToValueAtTime(0.12, ctx.currentTime + n[1] + 0.02); - g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + n[1] + 0.4); - o.connect(g); g.connect(ctx.destination); - o.start(ctx.currentTime + n[1]); o.stop(ctx.currentTime + n[1] + 0.45); - }); - } - - function tickSound() { - var ctx = getAudio(); if (!ctx) return; - var o = ctx.createOscillator(), g = ctx.createGain(); - o.frequency.value = 520; o.type = 'sine'; - g.gain.setValueAtTime(0.001, ctx.currentTime); - g.gain.exponentialRampToValueAtTime(0.08, ctx.currentTime + 0.01); - g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15); - o.connect(g); g.connect(ctx.destination); - o.start(ctx.currentTime); o.stop(ctx.currentTime + 0.2); - } - - function celebrateSound() { - var ctx = getAudio(); if (!ctx) return; - var notes = [523, 659, 784, 1047]; - notes.forEach(function (freq, i) { - var o = ctx.createOscillator(), g = ctx.createGain(); - o.frequency.value = freq; o.type = 'sine'; - g.gain.setValueAtTime(0.001, ctx.currentTime + i * 0.12); - g.gain.exponentialRampToValueAtTime(0.1, ctx.currentTime + i * 0.12 + 0.02); - g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + i * 0.12 + 0.35); - o.connect(g); g.connect(ctx.destination); - o.start(ctx.currentTime + i * 0.12); o.stop(ctx.currentTime + i * 0.12 + 0.4); - }); - } - - /* ---------- confetti ---------- */ - function confetti() { - var canvas = $('#confetti'); - if (!canvas) return; - var ctx2d = canvas.getContext('2d'); - canvas.width = window.innerWidth; - canvas.height = window.innerHeight; - var colors = ['#a78bfa', '#7dd3a0', '#f9c846', '#f472b6', '#60a5fa', '#e6e6f0']; - var pieces = []; - for (var i = 0; i < 80; i++) { - pieces.push({ - x: Math.random() * canvas.width, - y: Math.random() * canvas.height - canvas.height, - w: Math.random() * 8 + 4, - h: Math.random() * 6 + 3, - r: Math.random() * 6.28, - dx: (Math.random() - 0.5) * 4, - dy: Math.random() * 3 + 2, - dr: (Math.random() - 0.5) * 0.2, - color: colors[Math.floor(Math.random() * colors.length)], - life: 1 - }); - } - var frame; - function draw() { - ctx2d.clearRect(0, 0, canvas.width, canvas.height); - var alive = 0; - pieces.forEach(function (p) { - if (p.life <= 0) return; - alive++; - p.x += p.dx; - p.y += p.dy; - p.r += p.dr; - p.dy += 0.08; - p.life -= 0.008; - ctx2d.save(); - ctx2d.translate(p.x, p.y); - ctx2d.rotate(p.r); - ctx2d.globalAlpha = Math.max(0, p.life); - ctx2d.fillStyle = p.color; - ctx2d.fillRect(-p.w / 2, -p.h / 2, p.w, p.h); - ctx2d.restore(); - }); - if (alive > 0) { frame = requestAnimationFrame(draw); } - else { ctx2d.clearRect(0, 0, canvas.width, canvas.height); } - } - if (frame) cancelAnimationFrame(frame); - draw(); - } - - /* ---------- tabs ---------- */ - function showTab(name) { - $$('.tool').forEach(function (t) { t.hidden = (t.id !== name); }); - $$('.tab').forEach(function (t) { - var isOn = t.dataset.tab === name; - t.classList.toggle('on', isOn); - t.setAttribute('aria-selected', isOn ? 'true' : 'false'); - }); - try { history.replaceState(null, '', '#' + name); } catch (e) {} - } - $$('.tab').forEach(function (t) { - t.addEventListener('click', function (e) { e.preventDefault(); showTab(t.dataset.tab); }); - }); - - /* ---------- welcome / first visit ---------- */ - var visited = store('visited'); - var initial = location.hash.slice(1); - if (!visited && !initial) { - showTab('welcome'); - store('visited', true); - } else { - showTab(['breaker', 'timer', 'dopamine', 'now', 'inbox'].indexOf(initial) !== -1 ? initial : 'breaker'); - } - - $$('.welcome-btn').forEach(function (b) { - b.addEventListener('click', function () { - var target = b.dataset.goto; - if (target === 'pick') { - var tabs = ['breaker', 'timer', 'dopamine', 'now']; - target = tabs[Math.floor(Math.random() * tabs.length)]; - } - showTab(target); - }); - }); - - /* ---------- session stats ---------- */ - function paintStats() { - var sessions = store('sessions') || 0; - var el = $('#session-stats'); - var text = $('#stats-text'); - if (sessions > 0 && el && text) { - el.hidden = false; - text.textContent = sessions + ' focus round' + (sessions !== 1 ? 's' : '') + ' completed β€” nice work.'; - } - } - paintStats(); - - /* ---------- task breaker ---------- */ - var breakerKey = 'breaker'; - function breakerTemplates(task) { - return [ - { t: 'Write down what "done" looks like for: ' + task + '.', mins: 2, done: false }, - { t: 'Gather everything you need for "' + task + '" in one spot.', mins: 5, done: false }, - { t: 'Do the ugliest possible first draft of "' + task + '". Rough is the goal.', mins: 5, done: false }, - { t: 'Set a 10-minute timer and start "' + task + '". Starting is the whole job.', mins: 10, done: false }, - { t: 'Momentum check: keep going, or park it with a note for next time.', mins: 2, done: false }, - { t: 'Close the loop: tidy up and write down the very next step.', mins: 2, done: false } - ]; - } - - function breakerFindNextStep(b) { - if (!b || !b.steps) return -1; - for (var i = 0; i < b.steps.length; i++) { - if (!b.steps[i].done) return i; - } - return -1; - } - - function breakerRender() { - var b = store(breakerKey); - $('#breaker-out').hidden = !b; - if (!b) return; - var ul = $('#breaker-steps'); - ul.innerHTML = ''; - var done = 0; - var allDone = true; - b.steps.forEach(function (s, i) { - if (s.done) done++; - else allDone = false; - var li = document.createElement('li'); - li.className = s.done ? 'done' : ''; - var tick = document.createElement('button'); - tick.className = 'tick'; tick.type = 'button'; - tick.setAttribute('aria-label', s.done ? 'Mark undone' : 'Mark done'); - tick.addEventListener('click', function () { - var wasDone = s.done; - s.done = !s.done; - store(breakerKey, b); - if (!wasDone) { - tickSound(); - li.classList.add('step-just-done'); - setTimeout(function () { li.classList.remove('step-just-done'); }, 300); - } - breakerRender(); - // If all done, celebrate! - if (!wasDone) { - var allNow = b.steps.every(function (st) { return st.done; }); - if (allNow) { - celebrateSound(); - confetti(); - } - } - }); - var txt = document.createElement('span'); - txt.className = 'txt'; txt.contentEditable = 'true'; txt.textContent = s.t; - txt.setAttribute('role', 'textbox'); - txt.setAttribute('aria-label', 'Step ' + (i + 1) + ' text'); - txt.addEventListener('blur', function () { s.t = txt.textContent.trim(); store(breakerKey, b); }); - var mins = document.createElement('span'); - mins.className = 'mins'; mins.textContent = s.mins ? s.mins + ' min' : ''; - - // "start this step" button for undone steps - var actions = document.createElement('span'); - actions.className = 'step-actions'; - if (!s.done) { - var goBtn = document.createElement('button'); - goBtn.className = 'step-go'; - goBtn.textContent = 'start β†’'; - goBtn.type = 'button'; - goBtn.setAttribute('aria-label', 'Start working on this step'); - goBtn.addEventListener('click', function () { - // Set this step as the One Thing - store('now', { text: s.t, fromBreaker: true, stepIndex: i }); - showTab('now'); - nowRender(); - }); - actions.appendChild(goBtn); - } - - li.appendChild(tick); li.appendChild(txt); li.appendChild(mins); li.appendChild(actions); - ul.appendChild(li); - }); - - $('#breaker-progress').style.width = b.steps.length ? (100 * done / b.steps.length) + '%' : '0'; - $('#breaker-count').textContent = done + ' of ' + b.steps.length + ' steps done'; - - // Show/hide done message - var doneMsg = $('#breaker-done-msg'); - var actionsRow = $('#breaker-actions'); - if (allDone && b.steps.length) { - doneMsg.hidden = false; - actionsRow.hidden = true; - } else { - doneMsg.hidden = true; - actionsRow.hidden = false; - } - } - - $('#breaker-form').addEventListener('submit', function (e) { - e.preventDefault(); - var task = $('#breaker-input').value.trim(); - if (!task) return; - store(breakerKey, { task: task, steps: breakerTemplates(task) }); - breakerRender(); - }); - $('#breaker-add').addEventListener('click', function () { - var b = store(breakerKey); if (!b) return; - b.steps.push({ t: 'Next step…', mins: 0, done: false }); - store(breakerKey, b); breakerRender(); - }); - $('#breaker-reset').addEventListener('click', function () { - localStorage.removeItem('myadhd.' + breakerKey); - $('#breaker-input').value = ''; - breakerRender(); - }); - $('#breaker-new').addEventListener('click', function () { - localStorage.removeItem('myadhd.' + breakerKey); - $('#breaker-input').value = ''; - breakerRender(); - $('#breaker-input').focus(); - }); - breakerRender(); - - /* ---------- focus timer ---------- */ - var CIRC = 628.3; - // Restore persisted timer state or default - var timerState = store('timer_state'); - var timer; - if (timerState && timerState.left > 0) { - timer = { total: timerState.total, left: timerState.left, running: false, phase: timerState.phase || 'focus', iv: null }; - } else { - timer = { total: 25 * 60, left: 25 * 60, running: false, phase: 'focus', iv: null }; - } - - function timerPersist() { - store('timer_state', { total: timer.total, left: timer.left, phase: timer.phase }); - } - - window.groundingIv = null; - window.setGroundingInterval = function() { - if (window.groundingIv) { clearInterval(window.groundingIv); window.groundingIv = null; } - var activeBtn = $('.grounding-chime.active'); - if (!activeBtn) return; - var mins = parseInt(activeBtn.dataset.interval, 10); - if (mins > 0 && timer.running) { - window.groundingIv = setInterval(function() { - if (window.playGroundingPing) window.playGroundingPing(); - }, mins * 60 * 1000); - } - }; - - function timerPaint() { - var m = Math.floor(timer.left / 60), s = timer.left % 60; - $('#timer-time').textContent = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s; - $('#ring-fg').style.strokeDashoffset = CIRC * (1 - timer.left / timer.total); - - var portion = timer.total > 0 ? (timer.left / timer.total) : 0; - var piePath = $('#ring-pie-path'); - var pieSvg = $('#ring-pie-svg'); - if (piePath && pieSvg) { - if (portion <= 0) { - piePath.setAttribute("d", "M110,110 Z"); - } else if (portion >= 1) { - piePath.setAttribute("d", "M110,110 L110,10 A100,100 0 1,1 109.99,10 Z"); - } else { - var angle = portion * 360; - var rad = (angle * Math.PI) / 180; - var x = 110 + 100 * Math.sin(rad); - var y = 110 - 100 * Math.cos(rad); - var largeArc = angle > 180 ? 1 : 0; - piePath.setAttribute("d", "M110,110 L110,10 A100,100 0 " + largeArc + ",1 " + x + "," + y + " Z"); - } - pieSvg.classList.toggle('alert-amber', timer.left < 120 && timer.running); - } - - // Ring color matches phase - var ringFg = $('#ring-fg'); - if (timer.phase === 'break') { ringFg.classList.add('break-ring'); } - else { ringFg.classList.remove('break-ring'); } - var ph = $('#timer-phase'); - ph.textContent = timer.running ? (timer.phase === 'focus' ? 'focus β€” you got this' : 'break β€” actually rest') : ph.textContent; - ph.className = 'timer-phase' + (timer.phase === 'break' ? ' break' : ''); - // Update context bar - var nowData = store('now'); - var ctxBar = $('#timer-context-bar'); - var ctxText = $('#timer-context-text'); - if (nowData && nowData.text && ctxBar && ctxText) { - ctxBar.hidden = false; - ctxText.textContent = nowData.text; - } else if (ctxBar) { - ctxBar.hidden = true; - } - } - - function timerStop() { clearInterval(timer.iv); timer.iv = null; timer.running = false; - timerPersist(); } - - function timerComplete() { - timerStop(); beep(); - if (timer.phase === 'focus') { - var sessions = (store('sessions') || 0) + 1; - store('sessions', sessions); - paintStats(); - // Show completion overlay - var overlay = $('#timer-complete'); - if (overlay) { - overlay.hidden = false; - $('#timer-complete-sessions').textContent = sessions + ' focus round' + (sessions !== 1 ? 's' : '') + ' completed.'; - // Show "mark step done" only if there's a linked one-thing from breaker - var nowData = store('now'); - var markBtn = $('#timer-mark-done'); - if (markBtn) { - markBtn.hidden = !(nowData && nowData.fromBreaker); - } - } - celebrateSound(); - confetti(); - } else { - // Break is over - timer.phase = 'focus'; - timer.total = timer.left = 25 * 60; - $('#timer-start').textContent = 'start'; - $('#timer-note').textContent = 'Break over. Pick a length and go again β€” or stop here, that is allowed too.'; - } - timerPersist(); - timerPaint(); - } - - // Pie Mode Toggle - var modeToggleBtn = $('#timer-mode-toggle'); - if (modeToggleBtn) { - modeToggleBtn.addEventListener('click', function() { - var pieSvg = $('#ring-pie-svg'); - var ringSvg = $('.timer-wrap > svg.ring:not(.pie-mode)'); - var isPie = pieSvg.style.display !== 'none'; - if (isPie) { - pieSvg.style.display = 'none'; - ringSvg.style.display = ''; - this.innerHTML = ' switch to visual pie mode'; - } else { - pieSvg.style.display = ''; - ringSvg.style.display = 'none'; - this.innerHTML = ' switch to ring mode'; - } - timerPaint(); - }); - } - - $('#timer-start').addEventListener('click', function () { - if (window.setGroundingInterval) window.setGroundingInterval(); - if (timer.running) { timerStop(); $('#timer-start').textContent = 'resume'; timerPaint(); return; } - timer.running = true; - if (window.setGroundingInterval) window.setGroundingInterval(); - $('#timer-start').textContent = 'pause'; - timer.iv = setInterval(function () { - timer.left--; - timerPersist(); - if (timer.left <= 0) { - timerComplete(); - return; - } - timerPaint(); - }, 1000); - timerPaint(); - }); - - function timerReset() { - timerStop(); timer.left = timer.total; $('#timer-start').textContent = 'start'; - timerPersist(); timerPaint(); - } - - /* ---------- AI Auto-Deconstruct Contract (Tier 1 & 2) ---------- */ - window.aiBreakdownTask = async function(taskText) { - // Shared Interface for Sibyl's Tier 3 - const prompt = `Break down this intimidating task into 3-5 tiny, actionable micro-steps: "${taskText}". Return only the list of steps.`; - - // Tier 1: Browser Native (window.ai) - if (window.ai && window.ai.languageModel) { - try { - const caps = await window.ai.languageModel.capabilities(); - if (caps.available !== 'no') { - const session = await window.ai.languageModel.create(); - const result = await session.prompt(prompt); - return result.split('\n').filter(s => s.trim().length > 0); - } - } catch (e) { - console.warn("window.ai failed, falling back", e); - } - } - - // Tier 2: BYOK (Bring Your Own Key) Fallback - const key = store('byok_key'); - if (!key) { - throw new Error("NO_AI_AVAILABLE"); // Let UI prompt for key or let Tier 3 try - } - const resp = await fetch('https://api.openai.com/v1/chat/completions', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer ' + key - }, - body: JSON.stringify({ - model: 'gpt-4o-mini', - messages: [{ role: 'user', content: prompt }] - }) - }); - if (!resp.ok) throw new Error("API_ERROR"); - const data = await resp.json(); - return data.choices[0].message.content.split('\n').filter(s => s.trim().length > 0); - }; - - $('#timer-reset').addEventListener('click', timerReset); - - $$('.preset').forEach(function (p) { - p.addEventListener('click', function () { - timerStop(); - timer.total = timer.left = (+p.dataset.min) * 60; - timer.phase = p.classList.contains('break') ? 'break' : 'focus'; - $('#timer-start').textContent = 'start'; - timerPersist(); timerPaint(); - }); - }); - - $$('.grounding-chime').forEach(function(btn) { - btn.addEventListener('click', function() { - $$('.grounding-chime').forEach(function(b) { b.classList.remove('active'); }); - btn.classList.add('active'); - if (window.setGroundingInterval) window.setGroundingInterval(); - }); - }); - - // Timer completion overlay actions - $('#timer-take-break').addEventListener('click', function () { - $('#timer-complete').hidden = true; - timer.phase = 'break'; - timer.total = timer.left = 5 * 60; - $('#timer-start').textContent = 'start'; - $('#timer-note').textContent = 'Focus round done. Stand up. Drink water. Actually take the break.'; - timerPersist(); timerPaint(); - }); - - $('#timer-mark-done').addEventListener('click', function () { - $('#timer-complete').hidden = true; - // Mark the current one-thing step as done in the breaker - var nowData = store('now'); - var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; - if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { - var b = store(breakerKey); - if (b && b.steps[nowData.stepIndex]) { - b.steps[nowData.stepIndex].done = true; - store(breakerKey, b); - breakerRender(); - } - } - handleNewDoneTasks(taskText); - // Reset timer so it's fresh for the next step - timerReset(); - // Clear one-thing and show next step prompt - localStorage.removeItem('myadhd.now'); - showTab('now'); - nowShowNext(true); - }); - - timerPaint(); - - /* ---------- dopamine menu ---------- */ - var MENU = { - 5: [ - 'Put on one song and tidy one single surface.', - 'Drink a big glass of water like it is a magic potion.', - 'Step outside for two minutes and name five sounds you hear.', - 'Stretch your arms and neck slowly β€” like a cat waking up.', - 'Text someone one true compliment. No context, no apology.', - 'Draw the nearest object as badly as you possibly can.', - 'Open the window and take ten slow breaths.', - 'Rearrange exactly three things on your desk.', - 'Do ten squats or one ridiculous dance move.', - 'Write down three things you can see right now that you like.' - ], - 15: [ - 'Walk once around the block β€” phone stays home or in pocket.', - 'Build the fanciest snack possible from what you already have.', - 'Write a short thank-you note to your future self.', - 'Doodle your current mood as a weather report.', - 'Do a ten-minute follow-along stretch video.', - 'Clean one drawer. One. Set a timer so it cannot grow.', - 'Read five pages of any book you own.', - 'Water (or rescue) one plant.', - 'Have a shower, but treat it like a whole concert.', - 'Learn three words in a language you do not speak.' - ], - 30: [ - 'Cook something new with a video recipe playing.', - 'Go for a 25-minute walk with one podcast episode.', - 'Call someone you like. With your voice. Wild, we know.', - 'Build something with zero rules: LEGO, blanket fort, collage.', - 'Brain-dump everything in your head onto paper for ten minutes.', - 'Deep-clean the one object that quietly bothers you most.', - 'Follow a 30-minute workout video at whatever intensity you like.', - 'Walk or bike to a spot nearby you have never actually been.', - 'Pack a small comfort bag for your worst brain days.', - 'Ten minutes journaling, ten minutes stretching, ten minutes staring.' - ], - 60: [ - 'Long walk or bike ride somewhere with trees.', - 'One-hour hobby sprint β€” make something terrible and be proud.', - 'Bake something from scratch. Eat evidence.', - 'One-room tidy: music loud, timer rules, no mercy.', - 'Wandering trip (thrift store, library) with a $10 budget.', - 'Digital reset: close twenty tabs, clear the inbox as far as you can.', - 'Follow a full workout or yoga class at home.', - 'Meal-prep one lunch so tomorrow-you says thanks.', - 'Take a notebook to a cafΓ© or library and people-watch or sketch.', - 'Watch a documentary about something absurd and become an expert.' - ] - }; - var lastPick = null; - var currentMenuMins = store('menu_mins') || null; - - function menuPick(mins) { - currentMenuMins = mins; - store('menu_mins', mins); - // Highlight the selected time button - $$('.menu-pick').forEach(function (b) { - b.classList.toggle('on', +b.dataset.min === mins); - }); - var pool = MENU[mins].filter(function (x) { return x !== lastPick; }); - var item = pool[Math.floor(Math.random() * pool.length)]; - lastPick = item; - $('#menu-text').textContent = item; - $('#menu-item').hidden = false; - $('#menu-actions').hidden = false; - } - - $$('.menu-pick').forEach(function (b) { - b.addEventListener('click', function () { menuPick(+b.dataset.min); }); - }); - - $('#menu-reroll').addEventListener('click', function () { - // Use tracked mins instead of .on class - menuPick(currentMenuMins || 5); - }); - - function paintStreak() { - var s = store('streak'); - $('#menu-streak').innerHTML = s && s.streak ? - 'Streak: ' + s.streak + ' day' + (s.streak > 1 ? 's' : '') + ' of healthy dopamine. ' + - (s.last === today() ? 'Today is already logged.' : '') : ''; - } - $('#menu-done').addEventListener('click', function () { - var s = store('streak') || { last: '', streak: 0 }; - if (s.last !== today()) { - var y = new Date(Date.now() - 86400000).toISOString().slice(0, 10); - s.streak = (s.last === y) ? s.streak + 1 : 1; - s.last = today(); - store('streak', s); - } - tickSound(); - $('#menu-item').hidden = true; - $('#menu-actions').hidden = true; - paintStreak(); - }); - paintStreak(); - - // Restore menu time selection highlight on page load - if (currentMenuMins) { - $$('.menu-pick').forEach(function (b) { - b.classList.toggle('on', +b.dataset.min === currentMenuMins); - }); - } - - /* ---------- one thing ---------- */ - function nowRender() { - var nowSaved = store('now'); - var nextPrompt = $('#now-next'); - if (nextPrompt) nextPrompt.hidden = true; - - if (nowSaved && nowSaved.text) { - $('#now-text').textContent = nowSaved.text; - $('#now-form').hidden = true; - $('#now-view').hidden = false; - // Show source info if from breaker - var sourceEl = $('#now-source'); - if (sourceEl && nowSaved.fromBreaker) { - sourceEl.hidden = false; - var b = store(breakerKey); - if (b && typeof nowSaved.stepIndex === 'number') { - $('#now-step-num').textContent = nowSaved.stepIndex + 1; - $('#now-step-total').textContent = b.steps.length; - } - } else if (sourceEl) { - sourceEl.hidden = true; - } - } else { - $('#now-form').hidden = false; - $('#now-view').hidden = true; - } - } - - function nowShowNext(skipCelebration) { - var nextPrompt = $('#now-next'); - if (!nextPrompt) return; - var b = store(breakerKey); - if (!b) { - // No breaker data, just show "done" and reset form - nowRender(); - return; - } - var nextIdx = breakerFindNextStep(b); - nextPrompt.hidden = false; - $('#now-form').hidden = true; - $('#now-view').hidden = true; - - if (nextIdx >= 0) { - $('#now-next-step').hidden = false; - $('#now-all-done').hidden = true; - $('#now-next-text').textContent = b.steps[nextIdx].t; - // Wire up "Let's do it" - $('#now-next-go').onclick = function () { - store('now', { text: b.steps[nextIdx].t, fromBreaker: true, stepIndex: nextIdx }); - nowRender(); - }; - $('#now-next-skip').onclick = function () { - nextPrompt.hidden = true; - $('#now-form').hidden = false; - $('#now-view').hidden = true; - $('#now-input').value = ''; - $('#now-input').focus(); - }; - } else { - // All steps done - $('#now-next-step').hidden = true; - $('#now-all-done').hidden = false; - if (!skipCelebration) { - celebrateSound(); - confetti(); - } - } - } - - nowRender(); - - $('#now-form').addEventListener('submit', function (e) { - e.preventDefault(); - var t = $('#now-input').value.trim(); - if (!t) return; - store('now', { text: t }); - nowRender(); - }); - - $('#now-edit').addEventListener('click', function () { - $('#now-view').hidden = true; - $('#now-form').hidden = false; - $('#now-input').value = ''; - $('#now-input').focus(); - }); - - function handleNewDoneTasks(taskString) { - if (window.dbRecordTask && taskString) { - window.dbRecordTask(taskString).then(() => { if (window.renderDoneWall) window.renderDoneWall(); }).catch(() => {}); - } - } - - $('#now-done').addEventListener('click', function () { - var nowData = store('now'); - var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; - tickSound(); - // If from breaker, mark that step done - if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { - var b = store(breakerKey); - if (b && b.steps[nowData.stepIndex]) { - b.steps[nowData.stepIndex].done = true; - store(breakerKey, b); - breakerRender(); - } - } - handleNewDoneTasks(taskText); - localStorage.removeItem('myadhd.now'); - // Check if there's a next step from breaker - var b2 = store(breakerKey); - if (nowData && nowData.fromBreaker && b2) { - nowShowNext(); - } else { - nowRender(); - $('#now-input').focus(); - } - }); - - // "Start timer" button on One Thing - $('#now-timer').addEventListener('click', function () { - showTab('timer'); - // If timer isn't already running, pre-set 25 min - if (!timer.running) { - timer.total = timer.left = 25 * 60; - timer.phase = 'focus'; - $('#timer-start').textContent = 'start'; - timerPersist(); - timerPaint(); - } - }); - - // "Start something new" after all breaker steps done in now view - var nowFresh = $('#now-fresh'); - if (nowFresh) { - nowFresh.addEventListener('click', function () { - localStorage.removeItem('myadhd.now'); - $('#now-next').hidden = true; - showTab('breaker'); - localStorage.removeItem('myadhd.' + breakerKey); - $('#breaker-input').value = ''; - breakerRender(); - $('#breaker-input').focus(); - }); - } - - - /* ---------- inbox ---------- */ - var inboxItems = store('inbox') || []; - var $inboxForm = $('#inbox-form'), - $inboxInput = $('#inbox-input'), - $inboxOut = $('#inbox-out'), - $inboxCount = $('#inbox-count'), - $inboxList = $('#inbox-list'), - $inboxClear = $('#inbox-clear'); - - function saveInbox() { - store('inbox', inboxItems); - renderInbox(); - } - - function renderInbox() { - $inboxList.innerHTML = ''; - if (inboxItems.length === 0) { - $inboxOut.hidden = true; - return; - } - $inboxOut.hidden = false; - $inboxCount.textContent = inboxItems.length + ' item' + (inboxItems.length === 1 ? '' : 's'); - inboxItems.forEach(function (item, i) { - var li = document.createElement('li'); - li.className = 'step'; - - var textDiv = document.createElement('div'); - textDiv.className = 'step-text'; - textDiv.textContent = item; - - var editInput = document.createElement('input'); - editInput.type = 'text'; - editInput.className = 'step-edit-input sr-only'; - editInput.value = item; - - textDiv.addEventListener('click', function () { - textDiv.classList.add('sr-only'); - editInput.classList.remove('sr-only'); - editInput.focus(); - }); - - function commitEdit() { - var v = editInput.value.trim(); - if (!v) { inboxItems.splice(i, 1); } - else { inboxItems[i] = v; } - saveInbox(); - } - - editInput.addEventListener('blur', commitEdit); - editInput.addEventListener('keydown', function(e) { if (e.key === 'Enter') commitEdit(); }); - - var actionsDiv = document.createElement('div'); - actionsDiv.className = 'row gap'; - - var breakBtn = document.createElement('button'); - breakBtn.className = 'btn ghost small'; - breakBtn.textContent = 'break this down'; - breakBtn.addEventListener('click', function() { - inboxItems.splice(i, 1); - saveInbox(); - $('#breaker-input').value = item; - showTab('breaker'); - $('#breaker-form').dispatchEvent(new Event('submit')); - }); - - var delBtn = document.createElement('button'); - delBtn.className = 'btn ghost small'; - delBtn.textContent = 'Γ—'; - delBtn.addEventListener('click', function() { - inboxItems.splice(i, 1); - saveInbox(); - }); - - actionsDiv.appendChild(breakBtn); - actionsDiv.appendChild(delBtn); - - li.appendChild(textDiv); - li.appendChild(editInput); - li.appendChild(actionsDiv); - $inboxList.appendChild(li); - }); - } - - $inboxForm.addEventListener('submit', function (e) { - e.preventDefault(); - var val = $inboxInput.value.trim(); - if (!val) return; - inboxItems.unshift(val); - $inboxInput.value = ''; - saveInbox(); - }); - - $inboxClear.addEventListener('click', function () { - if (confirm('Clear entire inbox of dumps?')) { - inboxItems = []; - saveInbox(); - } - }); - - renderInbox(); - - /* ---------- morning sweep ---------- */ - var SWEEP_KEY = 'lastVisit'; - var SWEEP_THRESHOLD = 24 * 60 * 60 * 1000; // 24 hours - - function stampVisit() { store(SWEEP_KEY, Date.now()); } - - function sweepNeeded() { - var last = store(SWEEP_KEY); - if (!last) { stampVisit(); return false; } // first ever visit - return (Date.now() - last) > SWEEP_THRESHOLD; - } - - function openSweep(items, isManual) { - var modal = $('#sweep-modal'); - var list = $('#sweep-list'); - var keepAll = $('#sweep-keep-all'); - var relAll = $('#sweep-release-all'); - var doneBtn = $('#sweep-done'); - var closeBtn = $('#sweep-close'); - if (!modal || !list) return; - - list.innerHTML = ''; - var decisions = items.map(function () { return null; }); // null = undecided - - items.forEach(function (text, i) { - var li = document.createElement('li'); - - var span = document.createElement('span'); - span.className = 'sweep-text'; - span.textContent = text; - - var keep = document.createElement('button'); - keep.className = 'sweep-btn sweep-keep'; - keep.textContent = 'Keep'; - keep.type = 'button'; - - var release = document.createElement('button'); - release.className = 'sweep-btn sweep-release'; - release.textContent = 'Release 🌌'; - release.type = 'button'; - - keep.addEventListener('click', function () { - decisions[i] = 'keep'; - keep.classList.add('kept'); - keep.textContent = 'βœ“ Kept'; - release.style.display = 'none'; - }); - - release.addEventListener('click', function () { - decisions[i] = 'release'; - li.classList.add('sweep-dissolve'); - setTimeout(function () { li.classList.add('released'); }, 500); - }); - - li.appendChild(span); - li.appendChild(keep); - li.appendChild(release); - list.appendChild(li); - }); - - keepAll.onclick = function () { - items.forEach(function (_, i) { - if (decisions[i] !== 'release') { - decisions[i] = 'keep'; - var lis = list.children[i]; - if (lis) { - var kb = lis.querySelector('.sweep-keep'); - if (kb) { kb.classList.add('kept'); kb.textContent = 'βœ“ Kept'; } - var rb = lis.querySelector('.sweep-release'); - if (rb) rb.style.display = 'none'; - } - } - }); - }; - - relAll.onclick = function () { - items.forEach(function (_, i) { - if (decisions[i] !== 'keep') { - decisions[i] = 'release'; - var lis = list.children[i]; - if (lis) { - lis.classList.add('sweep-dissolve'); - setTimeout(function () { lis.classList.add('released'); }, 500); - } - } - }); - }; - - doneBtn.onclick = function () { - // Rebuild inbox: keep items that were kept or undecided - var kept = []; - items.forEach(function (text, i) { - if (decisions[i] !== 'release') kept.push(text); - }); - inboxItems = kept; - saveInbox(); - modal.hidden = true; - if (!isManual) stampVisit(); - }; - - if (closeBtn) { - closeBtn.onclick = function () { - modal.hidden = true; - } - } - - modal.hidden = false; - } - - // Auto-trigger on page load if stale - if (sweepNeeded() && inboxItems.length > 0) { - openSweep(inboxItems.slice(), false); - } else { - stampVisit(); - } - - // Manual "sweep stale" button in inbox - var $inboxSweep = $('#inbox-sweep'); - if ($inboxSweep) { - $inboxSweep.addEventListener('click', function () { - if (inboxItems.length === 0) return; - openSweep(inboxItems.slice(), true); - }); - } - - /* ---------- keyboard shortcuts ---------- */ - document.addEventListener('keydown', function (e) { - // Don't trigger shortcuts when typing in an input or contenteditable - var tag = e.target.tagName; - if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target.contentEditable === 'true') return; - - // Number keys 1-4 switch tabs - if (e.key === '1') { showTab('breaker'); e.preventDefault(); } - if (e.key === '2') { showTab('timer'); e.preventDefault(); } - if (e.key === '3') { showTab('dopamine'); e.preventDefault(); } - if (e.key === '4') { showTab('now'); e.preventDefault(); } - if (e.key === '5') { showTab('inbox'); e.preventDefault(); } - - // Space to start/pause timer when on timer tab - if (e.key === ' ' && !$('#timer').hidden) { - e.preventDefault(); - $('#timer-start').click(); - } - - // Escape to close completion overlay - if (e.key === 'Escape') { - var overlay = $('#timer-complete'); - if (overlay && !overlay.hidden) { - overlay.hidden = true; - } - } - }); - - - // ========================================== - // AMBIENT BODY DOUBLING (Feature C) - // ========================================== - var pill = $('#ambient-pill'); - var panel = $('#ambient-panel'); - var countEl = $('#pill-count'); - var feedEl = $('#ambient-feed'); - var cheerBtn = $('#ambient-cheer-btn'); - - var fakeBaseCount = 1400; // baseline - var feedEvents = [ - "A fellow brain just finished a 15m focus round", - "A fellow brain broke down an intimidating task", - "A fellow brain took a mindful breath", - "A fellow brain swept their inbox clean", - "A fellow brain just started a timer", - "A fellow brain released a stale task to the universe", - "A fellow brain decided to focus on just One Thing" - ]; - - function getCircadianOffset() { - // Generate a smooth hour-based wave offset so the fake count feels organic - var hour = new Date().getHours(); - var minute = new Date().getMinutes(); - var time = hour + (minute/60); - // peak at noon and 8pm roughly - return Math.floor((Math.sin(time * 0.5) * 300) + (Math.cos(time * 0.8) * 150)); - } - - function updateCount() { - if (!countEl) return; - var base = fakeBaseCount + getCircadianOffset(); - // small jitter - var jitter = Math.floor(Math.random() * 15) - 7; - var finalCount = base + jitter; - if (finalCount < 200) finalCount = 200; // min floor - countEl.textContent = finalCount.toLocaleString(); - } - - function addFeedItem(text) { - if (!feedEl) return; - var li = document.createElement('li'); - li.className = 'feed-item'; - li.textContent = text; - feedEl.prepend(li); - // keep only top 4 - if (feedEl.children.length > 4) { - feedEl.removeChild(feedEl.lastChild); - } - } - - function feedLoop() { - // random feed inject every 8-25 seconds - var delay = 8000 + Math.random() * 17000; - setTimeout(function() { - var evt = feedEvents[Math.floor(Math.random() * feedEvents.length)]; - addFeedItem(evt); - updateCount(); - feedLoop(); - }, delay); - } - - if (pill) { - updateCount(); - addFeedItem("You joined the focus room"); - feedLoop(); - - // click to toggle panel - pill.addEventListener('click', function(e) { - e.stopPropagation(); - var expanded = pill.getAttribute('aria-expanded') === 'true'; - pill.setAttribute('aria-expanded', !expanded); - panel.hidden = expanded; - }); - - // click outside to close - document.addEventListener('click', function(e) { - if (!panel.hidden && !panel.contains(e.target) && !pill.contains(e.target)) { - panel.hidden = true; - pill.setAttribute('aria-expanded', 'false'); - } - }); - - pill.addEventListener('keydown', function(e) { - if (e.key === 'Enter' || e.key === ' ') { - e.preventDefault(); - pill.click(); - } - }); - } - - if (cheerBtn) { - cheerBtn.addEventListener('click', function() { - addFeedItem("You sent a quiet cheer πŸŽ‰"); - cheerBtn.textContent = "Sent!"; - cheerBtn.style.pointerEvents = "none"; - setTimeout(function() { - cheerBtn.textContent = "Send a gentle nod πŸŽ‰"; - cheerBtn.style.pointerEvents = "auto"; - }, 3000); - confetti(); - }); - cheerBtn.addEventListener('keydown', function(e) { - if (e.key === 'Enter' || e.key === ' ') { - e.preventDefault(); - cheerBtn.click(); - } - }); - } - -})(); - - -// ========================================== -// UNSTUCK PROTOCOL (Task Paralysis Emergency) -// ========================================== -(function initUnstuck() { - const btnUnstuck = $('#btn-unstuck'); - const modal = $('#unstuck-modal'); - const closeBtn = $('#unstuck-close'); - const p1 = $('#unstuck-phase-1'); - const p2 = $('#unstuck-phase-2'); - const p3 = $('#unstuck-phase-3'); - const timerDisplay = $('#unstuck-timer'); - const startTimerBtn = $('#unstuck-start-3'); - const finishBtn = $('#unstuck-finish'); - - let breathInterval; - let unstuckInterval; - - if (!btnUnstuck || !modal) return; - - function resetUnstuckModal() { - p1.hidden = false; - p2.hidden = true; - p3.hidden = true; - startTimerBtn.hidden = false; - finishBtn.hidden = true; - timerDisplay.textContent = "03:00"; - $('#unstuck-micro-input').value = ""; - clearInterval(unstuckInterval); - clearInterval(breathInterval); - } - - function syncBreathText() { - const text = $('#breathe-text'); - if(!text) return; - clearInterval(breathInterval); - let cycle = 0; - - // Physiological Sigh timing matcher (approximate for the 8s CSS animation) - // 0-2s: Inhale - // 2-3.5s: 2nd Inhale - // 3.5-4s: Hold - // 4-8s: Long slow exhale - - const updateText = () => { - cycle = (cycle + 1) % 8; - if (cycle < 2) text.textContent = "Inhale..."; - else if (cycle < 3) text.textContent = "Sip more air..."; - else if (cycle < 4) text.textContent = "Hold..."; - else text.textContent = "Slooow Exhale..."; - }; - - updateText(); // immediate run - breathInterval = setInterval(() => { - if (modal.hidden || p1.hidden) { - clearInterval(breathInterval); - return; - } - updateText(); - }, 1000); - } - - btnUnstuck.addEventListener('click', () => { - resetUnstuckModal(); - modal.hidden = false; - syncBreathText(); - }); - - closeBtn.addEventListener('click', () => { - modal.hidden = true; - clearInterval(unstuckInterval); - clearInterval(breathInterval); - }); - - // Proceed from phase 1 to 2 - $('#unstuck-next-1').addEventListener('click', () => { - p1.hidden = true; - p2.hidden = false; - }); - - // Proceed from phase 2 to 3 - $('#unstuck-next-2').addEventListener('click', () => { - p2.hidden = true; - p3.hidden = false; - }); - - // Phase 3 Timer - startTimerBtn.addEventListener('click', () => { - startTimerBtn.hidden = true; - let timeLeft = 180; // 3 minutes - - unstuckInterval = setInterval(() => { - timeLeft--; - const m = Math.floor(timeLeft / 60).toString().padStart(2, '0'); - const s = (timeLeft % 60).toString().padStart(2, '0'); - timerDisplay.textContent = `${m}:${s}`; - - if (timeLeft <= 0) { - clearInterval(unstuckInterval); - timerDisplay.textContent = "Done!"; - finishBtn.hidden = false; - - // Play success tone if soundscapes/audio is available globally +1|/* myadhd.dev β€” client-side tools. No accounts, no network; everything in localStorage. */ +2|(function () { +3| 'use strict'; +4| var $ = function (s, r) { return (r || document).querySelector(s); }; +5| var $$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); }; +6| function store(k, v) { +7| if (v === undefined) { try { return JSON.parse(localStorage.getItem('myadhd.' + k)); } catch (e) { return null; } } +8| localStorage.setItem('myadhd.' + k, JSON.stringify(v)); +9| } +10| function today() { return new Date().toISOString().slice(0, 10); } +11| +12| /* ---------- register service worker ---------- */ +13| if ('serviceWorker' in navigator) { +14| navigator.serviceWorker.register('/sw.js').catch(function () {}); +15| } +16| +17| /* ---------- audio helpers ---------- */ +18| var audioCtx = null; +19| function getAudio() { +20| if (!audioCtx) { +21| try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) {} +22| } +23| return audioCtx; +24| } +25| +26| function beep() { +27| var ctx = getAudio(); if (!ctx) return; +28| [[660, 0], [880, 0.18]].forEach(function (n) { +29| var o = ctx.createOscillator(), g = ctx.createGain(); +30| o.frequency.value = n[0]; o.type = 'sine'; +31| g.gain.setValueAtTime(0.001, ctx.currentTime + n[1]); +32| g.gain.exponentialRampToValueAtTime(0.12, ctx.currentTime + n[1] + 0.02); +33| g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + n[1] + 0.4); +34| o.connect(g); g.connect(ctx.destination); +35| o.start(ctx.currentTime + n[1]); o.stop(ctx.currentTime + n[1] + 0.45); +36| }); +37| } +38| +39| function tickSound() { +40| var ctx = getAudio(); if (!ctx) return; +41| var o = ctx.createOscillator(), g = ctx.createGain(); +42| o.frequency.value = 520; o.type = 'sine'; +43| g.gain.setValueAtTime(0.001, ctx.currentTime); +44| g.gain.exponentialRampToValueAtTime(0.08, ctx.currentTime + 0.01); +45| g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15); +46| o.connect(g); g.connect(ctx.destination); +47| o.start(ctx.currentTime); o.stop(ctx.currentTime + 0.2); +48| } +49| +50| function celebrateSound() { +51| var ctx = getAudio(); if (!ctx) return; +52| var notes = [523, 659, 784, 1047]; +53| notes.forEach(function (freq, i) { +54| var o = ctx.createOscillator(), g = ctx.createGain(); +55| o.frequency.value = freq; o.type = 'sine'; +56| g.gain.setValueAtTime(0.001, ctx.currentTime + i * 0.12); +57| g.gain.exponentialRampToValueAtTime(0.1, ctx.currentTime + i * 0.12 + 0.02); +58| g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + i * 0.12 + 0.35); +59| o.connect(g); g.connect(ctx.destination); +60| o.start(ctx.currentTime + i * 0.12); o.stop(ctx.currentTime + i * 0.12 + 0.4); +61| }); +62| } +63| +64| /* ---------- confetti ---------- */ +65| function confetti() { +66| var canvas = $('#confetti'); +67| if (!canvas) return; +68| var ctx2d = canvas.getContext('2d'); +69| canvas.width = window.innerWidth; +70| canvas.height = window.innerHeight; +71| var colors = ['#a78bfa', '#7dd3a0', '#f9c846', '#f472b6', '#60a5fa', '#e6e6f0']; +72| var pieces = []; +73| for (var i = 0; i < 80; i++) { +74| pieces.push({ +75| x: Math.random() * canvas.width, +76| y: Math.random() * canvas.height - canvas.height, +77| w: Math.random() * 8 + 4, +78| h: Math.random() * 6 + 3, +79| r: Math.random() * 6.28, +80| dx: (Math.random() - 0.5) * 4, +81| dy: Math.random() * 3 + 2, +82| dr: (Math.random() - 0.5) * 0.2, +83| color: colors[Math.floor(Math.random() * colors.length)], +84| life: 1 +85| }); +86| } +87| var frame; +88| function draw() { +89| ctx2d.clearRect(0, 0, canvas.width, canvas.height); +90| var alive = 0; +91| pieces.forEach(function (p) { +92| if (p.life <= 0) return; +93| alive++; +94| p.x += p.dx; +95| p.y += p.dy; +96| p.r += p.dr; +97| p.dy += 0.08; +98| p.life -= 0.008; +99| ctx2d.save(); +100| ctx2d.translate(p.x, p.y); +101| ctx2d.rotate(p.r); +102| ctx2d.globalAlpha = Math.max(0, p.life); +103| ctx2d.fillStyle = p.color; +104| ctx2d.fillRect(-p.w / 2, -p.h / 2, p.w, p.h); +105| ctx2d.restore(); +106| }); +107| if (alive > 0) { frame = requestAnimationFrame(draw); } +108| else { ctx2d.clearRect(0, 0, canvas.width, canvas.height); } +109| } +110| if (frame) cancelAnimationFrame(frame); +111| draw(); +112| } +113| +114| /* ---------- tabs ---------- */ +115| function showTab(name) { +116| $$('.tool').forEach(function (t) { t.hidden = (t.id !== name); }); +117| $$('.tab').forEach(function (t) { +118| var isOn = t.dataset.tab === name; +119| t.classList.toggle('on', isOn); +120| t.setAttribute('aria-selected', isOn ? 'true' : 'false'); +121| }); +122| try { history.replaceState(null, '', '#' + name); } catch (e) {} +123| } +124| $$('.tab').forEach(function (t) { +125| t.addEventListener('click', function (e) { e.preventDefault(); showTab(t.dataset.tab); }); +126| }); +127| +128| /* ---------- welcome / first visit ---------- */ +129| var visited = store('visited'); +130| var initial = location.hash.slice(1); +131| if (!visited && !initial) { +132| showTab('welcome'); +133| store('visited', true); +134| } else { +135| showTab(['breaker', 'timer', 'dopamine', 'now', 'inbox'].indexOf(initial) !== -1 ? initial : 'breaker'); +136| } +137| +138| $$('.welcome-btn').forEach(function (b) { +139| b.addEventListener('click', function () { +140| var target = b.dataset.goto; +141| if (target === 'pick') { +142| var tabs = ['breaker', 'timer', 'dopamine', 'now']; +143| target = tabs[Math.floor(Math.random() * tabs.length)]; +144| } +145| showTab(target); +146| }); +147| }); +148| +149| /* ---------- session stats ---------- */ +150| function paintStats() { +151| var sessions = store('sessions') || 0; +152| var el = $('#session-stats'); +153| var text = $('#stats-text'); +154| if (sessions > 0 && el && text) { +155| el.hidden = false; +156| text.textContent = sessions + ' focus round' + (sessions !== 1 ? 's' : '') + ' completed β€” nice work.'; +157| } +158| } +159| paintStats(); +160| +161| /* ---------- task breaker ---------- */ +162| var breakerKey = 'breaker'; +163| function breakerTemplates(task) { +164| return [ +165| { t: 'Write down what "done" looks like for: ' + task + '.', mins: 2, done: false }, +166| { t: 'Gather everything you need for "' + task + '" in one spot.', mins: 5, done: false }, +167| { t: 'Do the ugliest possible first draft of "' + task + '". Rough is the goal.', mins: 5, done: false }, +168| { t: 'Set a 10-minute timer and start "' + task + '". Starting is the whole job.', mins: 10, done: false }, +169| { t: 'Momentum check: keep going, or park it with a note for next time.', mins: 2, done: false }, +170| { t: 'Close the loop: tidy up and write down the very next step.', mins: 2, done: false } +171| ]; +172| } +173| +174| function breakerFindNextStep(b) { +175| if (!b || !b.steps) return -1; +176| for (var i = 0; i < b.steps.length; i++) { +177| if (!b.steps[i].done) return i; +178| } +179| return -1; +180| } +181| +182| function breakerRender() { +183| var b = store(breakerKey); +184| $('#breaker-out').hidden = !b; +185| if (!b) return; +186| var ul = $('#breaker-steps'); +187| ul.innerHTML = ''; +188| var done = 0; +189| var allDone = true; +190| b.steps.forEach(function (s, i) { +191| if (s.done) done++; +192| else allDone = false; +193| var li = document.createElement('li'); +194| li.className = s.done ? 'done' : ''; +195| var tick = document.createElement('button'); +196| tick.className = 'tick'; tick.type = 'button'; +197| tick.setAttribute('aria-label', s.done ? 'Mark undone' : 'Mark done'); +198| tick.addEventListener('click', function () { +199| var wasDone = s.done; +200| s.done = !s.done; +201| store(breakerKey, b); +202| if (!wasDone) { +203| tickSound(); +204| li.classList.add('step-just-done'); +205| setTimeout(function () { li.classList.remove('step-just-done'); }, 300); +206| } +207| breakerRender(); +208| // If all done, celebrate! +209| if (!wasDone) { +210| var allNow = b.steps.every(function (st) { return st.done; }); +211| if (allNow) { +212| celebrateSound(); +213| confetti(); +214| } +215| } +216| }); +217| var txt = document.createElement('span'); +218| txt.className = 'txt'; txt.contentEditable = 'true'; txt.textContent = s.t; +219| txt.setAttribute('role', 'textbox'); +220| txt.setAttribute('aria-label', 'Step ' + (i + 1) + ' text'); +221| txt.addEventListener('blur', function () { s.t = txt.textContent.trim(); store(breakerKey, b); }); +222| var mins = document.createElement('span'); +223| mins.className = 'mins'; mins.textContent = s.mins ? s.mins + ' min' : ''; +224| +225| // "start this step" button for undone steps +226| var actions = document.createElement('span'); +227| actions.className = 'step-actions'; +228| if (!s.done) { +229| var goBtn = document.createElement('button'); +230| goBtn.className = 'step-go'; +231| goBtn.textContent = 'start β†’'; +232| goBtn.type = 'button'; +233| goBtn.setAttribute('aria-label', 'Start working on this step'); +234| goBtn.addEventListener('click', function () { +235| // Set this step as the One Thing +236| store('now', { text: s.t, fromBreaker: true, stepIndex: i }); +237| showTab('now'); +238| nowRender(); +239| }); +240| actions.appendChild(goBtn); +241| } +242| +243| li.appendChild(tick); li.appendChild(txt); li.appendChild(mins); li.appendChild(actions); +244| ul.appendChild(li); +245| }); +246| +247| $('#breaker-progress').style.width = b.steps.length ? (100 * done / b.steps.length) + '%' : '0'; +248| $('#breaker-count').textContent = done + ' of ' + b.steps.length + ' steps done'; +249| +250| // Show/hide done message +251| var doneMsg = $('#breaker-done-msg'); +252| var actionsRow = $('#breaker-actions'); +253| if (allDone && b.steps.length) { +254| doneMsg.hidden = false; +255| actionsRow.hidden = true; +256| } else { +257| doneMsg.hidden = true; +258| actionsRow.hidden = false; +259| } +260| } +261| +262| $('#breaker-form').addEventListener('submit', function (e) { +263| e.preventDefault(); +264| var task = $('#breaker-input').value.trim(); +265| if (!task) return; +266| store(breakerKey, { task: task, steps: breakerTemplates(task) }); +267| breakerRender(); +268| }); +269| $('#breaker-add').addEventListener('click', function () { +270| var b = store(breakerKey); if (!b) return; +271| b.steps.push({ t: 'Next step…', mins: 0, done: false }); +272| store(breakerKey, b); breakerRender(); +273| }); +274| $('#breaker-reset').addEventListener('click', function () { +275| localStorage.removeItem('myadhd.' + breakerKey); +276| $('#breaker-input').value = ''; +277| breakerRender(); +278| }); +279| $('#breaker-new').addEventListener('click', function () { +280| localStorage.removeItem('myadhd.' + breakerKey); +281| $('#breaker-input').value = ''; +282| breakerRender(); +283| $('#breaker-input').focus(); +284| }); +285| breakerRender(); +286| +287| /* ---------- focus timer ---------- */ +288| var CIRC = 628.3; +289| // Restore persisted timer state or default +290| var timerState = store('timer_state'); +291| var timer; +292| if (timerState && timerState.left > 0) { +293| timer = { total: timerState.total, left: timerState.left, running: false, phase: timerState.phase || 'focus', iv: null }; +294| } else { +295| timer = { total: 25 * 60, left: 25 * 60, running: false, phase: 'focus', iv: null }; +296| } +297| +298| function timerPersist() { +299| store('timer_state', { total: timer.total, left: timer.left, phase: timer.phase }); +300| } +301| +302| window.groundingIv = null; +303| window.setGroundingInterval = function() { +304| if (window.groundingIv) { clearInterval(window.groundingIv); window.groundingIv = null; } +305| var activeBtn = $('.grounding-chime.active'); +306| if (!activeBtn) return; +307| var mins = parseInt(activeBtn.dataset.interval, 10); +308| if (mins > 0 && timer.running) { +309| window.groundingIv = setInterval(function() { +310| if (window.playGroundingPing) window.playGroundingPing(); +311| }, mins * 60 * 1000); +312| } +313| }; +314| +315| function timerPaint() { +316| var m = Math.floor(timer.left / 60), s = timer.left % 60; +317| $('#timer-time').textContent = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s; +318| $('#ring-fg').style.strokeDashoffset = CIRC * (1 - timer.left / timer.total); +319| +320| var portion = timer.total > 0 ? (timer.left / timer.total) : 0; +321| var piePath = $('#ring-pie-path'); +322| var pieSvg = $('#ring-pie-svg'); +323| if (piePath && pieSvg) { +324| if (portion <= 0) { +325| piePath.setAttribute("d", "M110,110 Z"); +326| } else if (portion >= 1) { +327| piePath.setAttribute("d", "M110,110 L110,10 A100,100 0 1,1 109.99,10 Z"); +328| } else { +329| var angle = portion * 360; +330| var rad = (angle * Math.PI) / 180; +331| var x = 110 + 100 * Math.sin(rad); +332| var y = 110 - 100 * Math.cos(rad); +333| var largeArc = angle > 180 ? 1 : 0; +334| piePath.setAttribute("d", "M110,110 L110,10 A100,100 0 " + largeArc + ",1 " + x + "," + y + " Z"); +335| } +336| pieSvg.classList.toggle('alert-amber', timer.left < 120 && timer.running); +337| } +338| +339| // Ring color matches phase +340| var ringFg = $('#ring-fg'); +341| if (timer.phase === 'break') { ringFg.classList.add('break-ring'); } +342| else { ringFg.classList.remove('break-ring'); } +343| var ph = $('#timer-phase'); +344| ph.textContent = timer.running ? (timer.phase === 'focus' ? 'focus β€” you got this' : 'break β€” actually rest') : ph.textContent; +345| ph.className = 'timer-phase' + (timer.phase === 'break' ? ' break' : ''); +346| // Update context bar +347| var nowData = store('now'); +348| var ctxBar = $('#timer-context-bar'); +349| var ctxText = $('#timer-context-text'); +350| if (nowData && nowData.text && ctxBar && ctxText) { +351| ctxBar.hidden = false; +352| ctxText.textContent = nowData.text; +353| } else if (ctxBar) { +354| ctxBar.hidden = true; +355| } +356| } +357| +358| function timerStop() { clearInterval(timer.iv); timer.iv = null; timer.running = false; +359| timerPersist(); } +360| +361| function timerComplete() { +362| timerStop(); beep(); +363| if (timer.phase === 'focus') { +364| var sessions = (store('sessions') || 0) + 1; +365| store('sessions', sessions); +366| paintStats(); +367| // Show completion overlay +368| var overlay = $('#timer-complete'); +369| if (overlay) { +370| overlay.hidden = false; +371| $('#timer-complete-sessions').textContent = sessions + ' focus round' + (sessions !== 1 ? 's' : '') + ' completed.'; +372| // Show "mark step done" only if there's a linked one-thing from breaker +373| var nowData = store('now'); +374| var markBtn = $('#timer-mark-done'); +375| if (markBtn) { +376| markBtn.hidden = !(nowData && nowData.fromBreaker); +377| } +378| } +379| celebrateSound(); +380| confetti(); +381| } else { +382| // Break is over +383| timer.phase = 'focus'; +384| timer.total = timer.left = 25 * 60; +385| $('#timer-start').textContent = 'start'; +386| $('#timer-note').textContent = 'Break over. Pick a length and go again β€” or stop here, that is allowed too.'; +387| } +388| timerPersist(); +389| timerPaint(); +390| } +391| +392| // Pie Mode Toggle +393| var modeToggleBtn = $('#timer-mode-toggle'); +394| if (modeToggleBtn) { +395| modeToggleBtn.addEventListener('click', function() { +396| var pieSvg = $('#ring-pie-svg'); +397| var ringSvg = $('.timer-wrap > svg.ring:not(.pie-mode)'); +398| var isPie = pieSvg.style.display !== 'none'; +399| if (isPie) { +400| pieSvg.style.display = 'none'; +401| ringSvg.style.display = ''; +402| this.innerHTML = ' switch to visual pie mode'; +403| } else { +404| pieSvg.style.display = ''; +405| ringSvg.style.display = 'none'; +406| this.innerHTML = ' switch to ring mode'; +407| } +408| timerPaint(); +409| }); +410| } +411| +412| $('#timer-start').addEventListener('click', function () { +413| if (window.setGroundingInterval) window.setGroundingInterval(); +414| if (timer.running) { timerStop(); $('#timer-start').textContent = 'resume'; timerPaint(); return; } +415| timer.running = true; +416| if (window.setGroundingInterval) window.setGroundingInterval(); +417| $('#timer-start').textContent = 'pause'; +418| timer.iv = setInterval(function () { +419| timer.left--; +420| timerPersist(); +421| if (timer.left <= 0) { +422| timerComplete(); +423| return; +424| } +425| timerPaint(); +426| }, 1000); +427| timerPaint(); +428| }); +429| +430| function timerReset() { +431| timerStop(); timer.left = timer.total; $('#timer-start').textContent = 'start'; +432| timerPersist(); timerPaint(); +433| } +434| +435| /* ---------- AI Auto-Deconstruct Contract (Tier 1 & 2) ---------- */ +436| window.aiBreakdownTask = async function(taskText) { +437| // Shared Interface for Sibyl's Tier 3 +438| const prompt = `Break down this intimidating task into 3-5 tiny, actionable micro-steps: "${taskText}". Return only the list of steps.`; +439| +440| // Tier 3: WebLLM In-Browser (Advanced Opt-in) + // Checks if the user explicitly opted in to download the model + if (localStorage.getItem('ai_webllm_enabled') === 'true') { try { - if (window.AudioContext && !window.audioCtx) { - window.audioCtx = new window.AudioContext(); - } - if (window.audioCtx) { - const osc = audioCtx.createOscillator(); - const gain = audioCtx.createGain(); - osc.connect(gain); - gain.connect(audioCtx.destination); - osc.frequency.setValueAtTime(440, audioCtx.currentTime); // A4 - osc.frequency.exponentialRampToValueAtTime(880, audioCtx.currentTime + 0.1); // Jump to A5 - gain.gain.setValueAtTime(0, audioCtx.currentTime); - gain.gain.linearRampToValueAtTime(0.5, audioCtx.currentTime + 0.05); - gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 1); - osc.start(audioCtx.currentTime); - osc.stop(audioCtx.currentTime + 1); - } - } catch(e) { console.log(e); } - } - }, 1000); - }); + if (!window.webLLMEngine) { + // Initialize engine using the MLC WebLLM CDN + const { CreateMLCEngine } = await import('https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.46/+esm'); + // Use a 1B parameter model as decided: Llama-3.2-1B-Instruct + window.webLLMEngine = await CreateMLCEngine('Llama-3.2-1B-Instruct-q4f16_1-MLC', { + initProgressCallback: (progress) => { + // Hook this up to a UI later to show MB downloaded + console.log(`Downloading WebLLM model: ${progress.text}`); + } + }); + } + const reply = await window.webLLMEngine.chat.completions.create({ + messages: [{ role: 'user', content: prompt }] + }); + return reply.choices[0].message.content.split('\n').filter(s => s.trim().length > 0); + } catch (e) { + console.error('WebLLM Context Loss/OOM. Graded fallback to BYOK:', e); + // Graded fallback automatically drops through to Tier 2 + } + } - finishBtn.addEventListener('click', () => { - modal.hidden = true; - // Switch to Focus Timer using the main app's tab switching logic - const timerTabBtn = document.getElementById('tab-timer'); - if(timerTabBtn) timerTabBtn.click(); - }); - -})(); + // Tier 1: Browser Native (window.ai) +441| if (window.ai && window.ai.languageModel) { +442| try { +443| const caps = await window.ai.languageModel.capabilities(); +444| if (caps.available !== 'no') { +445| const session = await window.ai.languageModel.create(); +446| const result = await session.prompt(prompt); +447| return result.split('\n').filter(s => s.trim().length > 0); +448| } +449| } catch (e) { +450| console.warn("window.ai failed, falling back", e); +451| } +452| } +453| +454| // Tier 2: BYOK (Bring Your Own Key) Fallback +455| const key = store('byok_key'); +456| if (!key) { +457| throw new Error("NO_AI_AVAILABLE"); // Let UI prompt for key or let Tier 3 try +458| } +459| const resp = await fetch('https://api.openai.com/v1/chat/completions', { +460| method: 'POST', +461| headers: { +462| 'Content-Type': 'application/json', +463| 'Authorization': 'Bearer ' + key +464| }, +465| body: JSON.stringify({ +466| model: 'gpt-4o-mini', +467| messages: [{ role: 'user', content: prompt }] +468| }) +469| }); +470| if (!resp.ok) throw new Error("API_ERROR"); +471| const data = await resp.json(); +472| return data.choices[0].message.content.split('\n').filter(s => s.trim().length > 0); +473| }; +474| +475| $('#timer-reset').addEventListener('click', timerReset); +476| +477| $$('.preset').forEach(function (p) { +478| p.addEventListener('click', function () { +479| timerStop(); +480| timer.total = timer.left = (+p.dataset.min) * 60; +481| timer.phase = p.classList.contains('break') ? 'break' : 'focus'; +482| $('#timer-start').textContent = 'start'; +483| timerPersist(); timerPaint(); +484| }); +485| }); +486| +487| $$('.grounding-chime').forEach(function(btn) { +488| btn.addEventListener('click', function() { +489| $$('.grounding-chime').forEach(function(b) { b.classList.remove('active'); }); +490| btn.classList.add('active'); +491| if (window.setGroundingInterval) window.setGroundingInterval(); +492| }); +493| }); +494| +495| // Timer completion overlay actions +496| $('#timer-take-break').addEventListener('click', function () { +497| $('#timer-complete').hidden = true; +498| timer.phase = 'break'; +499| timer.total = timer.left = 5 * 60; +500| $('#timer-start').textContent = 'start'; +501| $('#timer-note').textContent = 'Focus round done. Stand up. Drink water. Actually take the break.'; +502| timerPersist(); timerPaint(); +503| }); +504| +505| $('#timer-mark-done').addEventListener('click', function () { +506| $('#timer-complete').hidden = true; +507| // Mark the current one-thing step as done in the breaker +508| var nowData = store('now'); +509| var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; +510| if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { +511| var b = store(breakerKey); +512| if (b && b.steps[nowData.stepIndex]) { +513| b.steps[nowData.stepIndex].done = true; +514| store(breakerKey, b); +515| breakerRender(); +516| } +517| } +518| handleNewDoneTasks(taskText); +519| // Reset timer so it's fresh for the next step +520| timerReset(); +521| // Clear one-thing and show next step prompt +522| localStorage.removeItem('myadhd.now'); +523| showTab('now'); +524| nowShowNext(true); +525| }); +526| +527| timerPaint(); +528| +529| /* ---------- dopamine menu ---------- */ +530| var MENU = { +531| 5: [ +532| 'Put on one song and tidy one single surface.', +533| 'Drink a big glass of water like it is a magic potion.', +534| 'Step outside for two minutes and name five sounds you hear.', +535| 'Stretch your arms and neck slowly β€” like a cat waking up.', +536| 'Text someone one true compliment. No context, no apology.', +537| 'Draw the nearest object as badly as you possibly can.', +538| 'Open the window and take ten slow breaths.', +539| 'Rearrange exactly three things on your desk.', +540| 'Do ten squats or one ridiculous dance move.', +541| 'Write down three things you can see right now that you like.' +542| ], +543| 15: [ +544| 'Walk once around the block β€” phone stays home or in pocket.', +545| 'Build the fanciest snack possible from what you already have.', +546| 'Write a short thank-you note to your future self.', +547| 'Doodle your current mood as a weather report.', +548| 'Do a ten-minute follow-along stretch video.', +549| 'Clean one drawer. One. Set a timer so it cannot grow.', +550| 'Read five pages of any book you own.', +551| 'Water (or rescue) one plant.', +552| 'Have a shower, but treat it like a whole concert.', +553| 'Learn three words in a language you do not speak.' +554| ], +555| 30: [ +556| 'Cook something new with a video recipe playing.', +557| 'Go for a 25-minute walk with one podcast episode.', +558| 'Call someone you like. With your voice. Wild, we know.', +559| 'Build something with zero rules: LEGO, blanket fort, collage.', +560| 'Brain-dump everything in your head onto paper for ten minutes.', +561| 'Deep-clean the one object that quietly bothers you most.', +562| 'Follow a 30-minute workout video at whatever intensity you like.', +563| 'Walk or bike to a spot nearby you have never actually been.', +564| 'Pack a small comfort bag for your worst brain days.', +565| 'Ten minutes journaling, ten minutes stretching, ten minutes staring.' +566| ], +567| 60: [ +568| 'Long walk or bike ride somewhere with trees.', +569| 'One-hour hobby sprint β€” make something terrible and be proud.', +570| 'Bake something from scratch. Eat evidence.', +571| 'One-room tidy: music loud, timer rules, no mercy.', +572| 'Wandering trip (thrift store, library) with a $10 budget.', +573| 'Digital reset: close twenty tabs, clear the inbox as far as you can.', +574| 'Follow a full workout or yoga class at home.', +575| 'Meal-prep one lunch so tomorrow-you says thanks.', +576| 'Take a notebook to a cafΓ© or library and people-watch or sketch.', +577| 'Watch a documentary about something absurd and become an expert.' +578| ] +579| }; +580| var lastPick = null; +581| var currentMenuMins = store('menu_mins') || null; +582| +583| function menuPick(mins) { +584| currentMenuMins = mins; +585| store('menu_mins', mins); +586| // Highlight the selected time button +587| $$('.menu-pick').forEach(function (b) { +588| b.classList.toggle('on', +b.dataset.min === mins); +589| }); +590| var pool = MENU[mins].filter(function (x) { return x !== lastPick; }); +591| var item = pool[Math.floor(Math.random() * pool.length)]; +592| lastPick = item; +593| $('#menu-text').textContent = item; +594| $('#menu-item').hidden = false; +595| $('#menu-actions').hidden = false; +596| } +597| +598| $$('.menu-pick').forEach(function (b) { +599| b.addEventListener('click', function () { menuPick(+b.dataset.min); }); +600| }); +601| +602| $('#menu-reroll').addEventListener('click', function () { +603| // Use tracked mins instead of .on class +604| menuPick(currentMenuMins || 5); +605| }); +606| +607| function paintStreak() { +608| var s = store('streak'); +609| $('#menu-streak').innerHTML = s && s.streak ? +610| 'Streak: ' + s.streak + ' day' + (s.streak > 1 ? 's' : '') + ' of healthy dopamine. ' + +611| (s.last === today() ? 'Today is already logged.' : '') : ''; +612| } +613| $('#menu-done').addEventListener('click', function () { +614| var s = store('streak') || { last: '', streak: 0 }; +615| if (s.last !== today()) { +616| var y = new Date(Date.now() - 86400000).toISOString().slice(0, 10); +617| s.streak = (s.last === y) ? s.streak + 1 : 1; +618| s.last = today(); +619| store('streak', s); +620| } +621| tickSound(); +622| $('#menu-item').hidden = true; +623| $('#menu-actions').hidden = true; +624| paintStreak(); +625| }); +626| paintStreak(); +627| +628| // Restore menu time selection highlight on page load +629| if (currentMenuMins) { +630| $$('.menu-pick').forEach(function (b) { +631| b.classList.toggle('on', +b.dataset.min === currentMenuMins); +632| }); +633| } +634| +635| /* ---------- one thing ---------- */ +636| function nowRender() { +637| var nowSaved = store('now'); +638| var nextPrompt = $('#now-next'); +639| if (nextPrompt) nextPrompt.hidden = true; +640| +641| if (nowSaved && nowSaved.text) { +642| $('#now-text').textContent = nowSaved.text; +643| $('#now-form').hidden = true; +644| $('#now-view').hidden = false; +645| // Show source info if from breaker +646| var sourceEl = $('#now-source'); +647| if (sourceEl && nowSaved.fromBreaker) { +648| sourceEl.hidden = false; +649| var b = store(breakerKey); +650| if (b && typeof nowSaved.stepIndex === 'number') { +651| $('#now-step-num').textContent = nowSaved.stepIndex + 1; +652| $('#now-step-total').textContent = b.steps.length; +653| } +654| } else if (sourceEl) { +655| sourceEl.hidden = true; +656| } +657| } else { +658| $('#now-form').hidden = false; +659| $('#now-view').hidden = true; +660| } +661| } +662| +663| function nowShowNext(skipCelebration) { +664| var nextPrompt = $('#now-next'); +665| if (!nextPrompt) return; +666| var b = store(breakerKey); +667| if (!b) { +668| // No breaker data, just show "done" and reset form +669| nowRender(); +670| return; +671| } +672| var nextIdx = breakerFindNextStep(b); +673| nextPrompt.hidden = false; +674| $('#now-form').hidden = true; +675| $('#now-view').hidden = true; +676| +677| if (nextIdx >= 0) { +678| $('#now-next-step').hidden = false; +679| $('#now-all-done').hidden = true; +680| $('#now-next-text').textContent = b.steps[nextIdx].t; +681| // Wire up "Let's do it" +682| $('#now-next-go').onclick = function () { +683| store('now', { text: b.steps[nextIdx].t, fromBreaker: true, stepIndex: nextIdx }); +684| nowRender(); +685| }; +686| $('#now-next-skip').onclick = function () { +687| nextPrompt.hidden = true; +688| $('#now-form').hidden = false; +689| $('#now-view').hidden = true; +690| $('#now-input').value = ''; +691| $('#now-input').focus(); +692| }; +693| } else { +694| // All steps done +695| $('#now-next-step').hidden = true; +696| $('#now-all-done').hidden = false; +697| if (!skipCelebration) { +698| celebrateSound(); +699| confetti(); +700| } +701| } +702| } +703| +704| nowRender(); +705| +706| $('#now-form').addEventListener('submit', function (e) { +707| e.preventDefault(); +708| var t = $('#now-input').value.trim(); +709| if (!t) return; +710| store('now', { text: t }); +711| nowRender(); +712| }); +713| +714| $('#now-edit').addEventListener('click', function () { +715| $('#now-view').hidden = true; +716| $('#now-form').hidden = false; +717| $('#now-input').value = ''; +718| $('#now-input').focus(); +719| }); +720| +721| function handleNewDoneTasks(taskString) { +722| if (window.dbRecordTask && taskString) { +723| window.dbRecordTask(taskString).then(() => { if (window.renderDoneWall) window.renderDoneWall(); }).catch(() => {}); +724| } +725| } +726| +727| $('#now-done').addEventListener('click', function () { +728| var nowData = store('now'); +729| var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; +730| tickSound(); +731| // If from breaker, mark that step done +732| if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { +733| var b = store(breakerKey); +734| if (b && b.steps[nowData.stepIndex]) { +735| b.steps[nowData.stepIndex].done = true; +736| store(breakerKey, b); +737| breakerRender(); +738| } +739| } +740| handleNewDoneTasks(taskText); +741| localStorage.removeItem('myadhd.now'); +742| // Check if there's a next step from breaker +743| var b2 = store(breakerKey); +744| if (nowData && nowData.fromBreaker && b2) { +745| nowShowNext(); +746| } else { +747| nowRender(); +748| $('#now-input').focus(); +749| } +750| }); +751| +752| // "Start timer" button on One Thing +753| $('#now-timer').addEventListener('click', function () { +754| showTab('timer'); +755| // If timer isn't already running, pre-set 25 min +756| if (!timer.running) { +757| timer.total = timer.left = 25 * 60; +758| timer.phase = 'focus'; +759| $('#timer-start').textContent = 'start'; +760| timerPersist(); +761| timerPaint(); +762| } +763| }); +764| +765| // "Start something new" after all breaker steps done in now view +766| var nowFresh = $('#now-fresh'); +767| if (nowFresh) { +768| nowFresh.addEventListener('click', function () { +769| localStorage.removeItem('myadhd.now'); +770| $('#now-next').hidden = true; +771| showTab('breaker'); +772| localStorage.removeItem('myadhd.' + breakerKey); +773| $('#breaker-input').value = ''; +774| breakerRender(); +775| $('#breaker-input').focus(); +776| }); +777| } +778| +779| +780| /* ---------- inbox ---------- */ +781| var inboxItems = store('inbox') || []; +782| var $inboxForm = $('#inbox-form'), +783| $inboxInput = $('#inbox-input'), +784| $inboxOut = $('#inbox-out'), +785| $inboxCount = $('#inbox-count'), +786| $inboxList = $('#inbox-list'), +787| $inboxClear = $('#inbox-clear'); +788| +789| function saveInbox() { +790| store('inbox', inboxItems); +791| renderInbox(); +792| } +793| +794| function renderInbox() { +795| $inboxList.innerHTML = ''; +796| if (inboxItems.length === 0) { +797| $inboxOut.hidden = true; +798| return; +799| } +800| $inboxOut.hidden = false; +801| $inboxCount.textContent = inboxItems.length + ' item' + (inboxItems.length === 1 ? '' : 's'); +802| inboxItems.forEach(function (item, i) { +803| var li = document.createElement('li'); +804| li.className = 'step'; +805| +806| var textDiv = document.createElement('div'); +807| textDiv.className = 'step-text'; +808| textDiv.textContent = item; +809| +810| var editInput = document.createElement('input'); +811| editInput.type = 'text'; +812| editInput.className = 'step-edit-input sr-only'; +813| editInput.value = item; +814| +815| textDiv.addEventListener('click', function () { +816| textDiv.classList.add('sr-only'); +817| editInput.classList.remove('sr-only'); +818| editInput.focus(); +819| }); +820| +821| function commitEdit() { +822| var v = editInput.value.trim(); +823| if (!v) { inboxItems.splice(i, 1); } +824| else { inboxItems[i] = v; } +825| saveInbox(); +826| } +827| +828| editInput.addEventListener('blur', commitEdit); +829| editInput.addEventListener('keydown', function(e) { if (e.key === 'Enter') commitEdit(); }); +830| +831| var actionsDiv = document.createElement('div'); +832| actionsDiv.className = 'row gap'; +833| +834| var breakBtn = document.createElement('button'); +835| breakBtn.className = 'btn ghost small'; +836| breakBtn.textContent = 'break this down'; +837| breakBtn.addEventListener('click', function() { +838| inboxItems.splice(i, 1); +839| saveInbox(); +840| $('#breaker-input').value = item; +841| showTab('breaker'); +842| $('#breaker-form').dispatchEvent(new Event('submit')); +843| }); +844| +845| var delBtn = document.createElement('button'); +846| delBtn.className = 'btn ghost small'; +847| delBtn.textContent = 'Γ—'; +848| delBtn.addEventListener('click', function() { +849| inboxItems.splice(i, 1); +850| saveInbox(); +851| }); +852| +853| actionsDiv.appendChild(breakBtn); +854| actionsDiv.appendChild(delBtn); +855| +856| li.appendChild(textDiv); +857| li.appendChild(editInput); +858| li.appendChild(actionsDiv); +859| $inboxList.appendChild(li); +860| }); +861| } +862| +863| $inboxForm.addEventListener('submit', function (e) { +864| e.preventDefault(); +865| var val = $inboxInput.value.trim(); +866| if (!val) return; +867| inboxItems.unshift(val); +868| $inboxInput.value = ''; +869| saveInbox(); +870| }); +871| +872| $inboxClear.addEventListener('click', function () { +873| if (confirm('Clear entire inbox of dumps?')) { +874| inboxItems = []; +875| saveInbox(); +876| } +877| }); +878| +879| renderInbox(); +880| +881| /* ---------- morning sweep ---------- */ +882| var SWEEP_KEY = 'lastVisit'; +883| var SWEEP_THRESHOLD = 24 * 60 * 60 * 1000; // 24 hours +884| +885| function stampVisit() { store(SWEEP_KEY, Date.now()); } +886| +887| function sweepNeeded() { +888| var last = store(SWEEP_KEY); +889| if (!last) { stampVisit(); return false; } // first ever visit +890| return (Date.now() - last) > SWEEP_THRESHOLD; +891| } +892| +893| function openSweep(items, isManual) { +894| var modal = $('#sweep-modal'); +895| var list = $('#sweep-list'); +896| var keepAll = $('#sweep-keep-all'); +897| var relAll = $('#sweep-release-all'); +898| var doneBtn = $('#sweep-done'); +899| var closeBtn = $('#sweep-close'); +900| if (!modal || !list) return; +901| +902| list.innerHTML = ''; +903| var decisions = items.map(function () { return null; }); // null = undecided +904| +905| items.forEach(function (text, i) { +906| var li = document.createElement('li'); +907| +908| var span = document.createElement('span'); +909| span.className = 'sweep-text'; +910| span.textContent = text; +911| +912| var keep = document.createElement('button'); +913| keep.className = 'sweep-btn sweep-keep'; +914| keep.textContent = 'Keep'; +915| keep.type = 'button'; +916| +917| var release = document.createElement('button'); +918| release.className = 'sweep-btn sweep-release'; +919| release.textContent = 'Release 🌌'; +920| release.type = 'button'; +921| +922| keep.addEventListener('click', function () { +923| decisions[i] = 'keep'; +924| keep.classList.add('kept'); +925| keep.textContent = 'βœ“ Kept'; +926| release.style.display = 'none'; +927| }); +928| +929| release.addEventListener('click', function () { +930| decisions[i] = 'release'; +931| li.classList.add('sweep-dissolve'); +932| setTimeout(function () { li.classList.add('released'); }, 500); +933| }); +934| +935| li.appendChild(span); +936| li.appendChild(keep); +937| li.appendChild(release); +938| list.appendChild(li); +939| }); +940| +941| keepAll.onclick = function () { +942| items.forEach(function (_, i) { +943| if (decisions[i] !== 'release') { +944| decisions[i] = 'keep'; +945| var lis = list.children[i]; +946| if (lis) { +947| var kb = lis.querySelector('.sweep-keep'); +948| if (kb) { kb.classList.add('kept'); kb.textContent = 'βœ“ Kept'; } +949| var rb = lis.querySelector('.sweep-release'); +950| if (rb) rb.style.display = 'none'; +951| } +952| } +953| }); +954| }; +955| +956| relAll.onclick = function () { +957| items.forEach(function (_, i) { +958| if (decisions[i] !== 'keep') { +959| decisions[i] = 'release'; +960| var lis = list.children[i]; +961| if (lis) { +962| lis.classList.add('sweep-dissolve'); +963| setTimeout(function () { lis.classList.add('released'); }, 500); +964| } +965| } +966| }); +967| }; +968| +969| doneBtn.onclick = function () { +970| // Rebuild inbox: keep items that were kept or undecided +971| var kept = []; +972| items.forEach(function (text, i) { +973| if (decisions[i] !== 'release') kept.push(text); +974| }); +975| inboxItems = kept; +976| saveInbox(); +977| modal.hidden = true; +978| if (!isManual) stampVisit(); +979| }; +980| +981| if (closeBtn) { +982| closeBtn.onclick = function () { +983| modal.hidden = true; +984| } +985| } +986| +987| modal.hidden = false; +988| } +989| +990| // Auto-trigger on page load if stale +991| if (sweepNeeded() && inboxItems.length > 0) { +992| openSweep(inboxItems.slice(), false); +993| } else { +994| stampVisit(); +995| } +996| +997| // Manual "sweep stale" button in inbox +998| var $inboxSweep = $('#inbox-sweep'); +999| if ($inboxSweep) { +1000| $inboxSweep.addEventListener('click', function () { +1001| if (inboxItems.length === 0) return; +1002| openSweep(inboxItems.slice(), true); +1003| }); +1004| } +1005| +1006| /* ---------- keyboard shortcuts ---------- */ +1007| document.addEventListener('keydown', function (e) { +1008| // Don't trigger shortcuts when typing in an input or contenteditable +1009| var tag = e.target.tagName; +1010| if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target.contentEditable === 'true') return; +1011| +1012| // Number keys 1-4 switch tabs +1013| if (e.key === '1') { showTab('breaker'); e.preventDefault(); } +1014| if (e.key === '2') { showTab('timer'); e.preventDefault(); } +1015| if (e.key === '3') { showTab('dopamine'); e.preventDefault(); } +1016| if (e.key === '4') { showTab('now'); e.preventDefault(); } +1017| if (e.key === '5') { showTab('inbox'); e.preventDefault(); } +1018| +1019| // Space to start/pause timer when on timer tab +1020| if (e.key === ' ' && !$('#timer').hidden) { +1021| e.preventDefault(); +1022| $('#timer-start').click(); +1023| } +1024| +1025| // Escape to close completion overlay +1026| if (e.key === 'Escape') { +1027| var overlay = $('#timer-complete'); +1028| if (overlay && !overlay.hidden) { +1029| overlay.hidden = true; +1030| } +1031| } +1032| }); +1033| +1034| +1035| // ========================================== +1036| // AMBIENT BODY DOUBLING (Feature C) +1037| // ========================================== +1038| var pill = $('#ambient-pill'); +1039| var panel = $('#ambient-panel'); +1040| var countEl = $('#pill-count'); +1041| var feedEl = $('#ambient-feed'); +1042| var cheerBtn = $('#ambient-cheer-btn'); +1043| +1044| var fakeBaseCount = 1400; // baseline +1045| var feedEvents = [ +1046| "A fellow brain just finished a 15m focus round", +1047| "A fellow brain broke down an intimidating task", +1048| "A fellow brain took a mindful breath", +1049| "A fellow brain swept their inbox clean", +1050| "A fellow brain just started a timer", +1051| "A fellow brain released a stale task to the universe", +1052| "A fellow brain decided to focus on just One Thing" +1053| ]; +1054| +1055| function getCircadianOffset() { +1056| // Generate a smooth hour-based wave offset so the fake count feels organic +1057| var hour = new Date().getHours(); +1058| var minute = new Date().getMinutes(); +1059| var time = hour + (minute/60); +1060| // peak at noon and 8pm roughly +1061| return Math.floor((Math.sin(time * 0.5) * 300) + (Math.cos(time * 0.8) * 150)); +1062| } +1063| +1064| function updateCount() { +1065| if (!countEl) return; +1066| var base = fakeBaseCount + getCircadianOffset(); +1067| // small jitter +1068| var jitter = Math.floor(Math.random() * 15) - 7; +1069| var finalCount = base + jitter; +1070| if (finalCount < 200) finalCount = 200; // min floor +1071| countEl.textContent = finalCount.toLocaleString(); +1072| } +1073| +1074| function addFeedItem(text) { +1075| if (!feedEl) return; +1076| var li = document.createElement('li'); +1077| li.className = 'feed-item'; +1078| li.textContent = text; +1079| feedEl.prepend(li); +1080| // keep only top 4 +1081| if (feedEl.children.length > 4) { +1082| feedEl.removeChild(feedEl.lastChild); +1083| } +1084| } +1085| +1086| function feedLoop() { +1087| // random feed inject every 8-25 seconds +1088| var delay = 8000 + Math.random() * 17000; +1089| setTimeout(function() { +1090| var evt = feedEvents[Math.floor(Math.random() * feedEvents.length)]; +1091| addFeedItem(evt); +1092| updateCount(); +1093| feedLoop(); +1094| }, delay); +1095| } +1096| +1097| if (pill) { +1098| updateCount(); +1099| addFeedItem("You joined the focus room"); +1100| feedLoop(); +1101| +1102| // click to toggle panel +1103| pill.addEventListener('click', function(e) { +1104| e.stopPropagation(); +1105| var expanded = pill.getAttribute('aria-expanded') === 'true'; +1106| pill.setAttribute('aria-expanded', !expanded); +1107| panel.hidden = expanded; +1108| }); +1109| +1110| // click outside to close +1111| document.addEventListener('click', function(e) { +1112| if (!panel.hidden && !panel.contains(e.target) && !pill.contains(e.target)) { +1113| panel.hidden = true; +1114| pill.setAttribute('aria-expanded', 'false'); +1115| } +1116| }); +1117| +1118| pill.addEventListener('keydown', function(e) { +1119| if (e.key === 'Enter' || e.key === ' ') { +1120| e.preventDefault(); +1121| pill.click(); +1122| } +1123| }); +1124| } +1125| +1126| if (cheerBtn) { +1127| cheerBtn.addEventListener('click', function() { +1128| addFeedItem("You sent a quiet cheer πŸŽ‰"); +1129| cheerBtn.textContent = "Sent!"; +1130| cheerBtn.style.pointerEvents = "none"; +1131| setTimeout(function() { +1132| cheerBtn.textContent = "Send a gentle nod πŸŽ‰"; +1133| cheerBtn.style.pointerEvents = "auto"; +1134| }, 3000); +1135| confetti(); +1136| }); +1137| cheerBtn.addEventListener('keydown', function(e) { +1138| if (e.key === 'Enter' || e.key === ' ') { +1139| e.preventDefault(); +1140| cheerBtn.click(); +1141| } +1142| }); +1143| } +1144| +1145|})(); +1146| +1147| +1148|// ========================================== +1149|// UNSTUCK PROTOCOL (Task Paralysis Emergency) +1150|// ========================================== +1151|(function initUnstuck() { +1152| const btnUnstuck = $('#btn-unstuck'); +1153| const modal = $('#unstuck-modal'); +1154| const closeBtn = $('#unstuck-close'); +1155| const p1 = $('#unstuck-phase-1'); +1156| const p2 = $('#unstuck-phase-2'); +1157| const p3 = $('#unstuck-phase-3'); +1158| const timerDisplay = $('#unstuck-timer'); +1159| const startTimerBtn = $('#unstuck-start-3'); +1160| const finishBtn = $('#unstuck-finish'); +1161| +1162| let breathInterval; +1163| let unstuckInterval; +1164| +1165| if (!btnUnstuck || !modal) return; +1166| +1167| function resetUnstuckModal() { +1168| p1.hidden = false; +1169| p2.hidden = true; +1170| p3.hidden = true; +1171| startTimerBtn.hidden = false; +1172| finishBtn.hidden = true; +1173| timerDisplay.textContent = "03:00"; +1174| $('#unstuck-micro-input').value = ""; +1175| clearInterval(unstuckInterval); +1176| clearInterval(breathInterval); +1177| } +1178| +1179| function syncBreathText() { +1180| const text = $('#breathe-text'); +1181| if(!text) return; +1182| clearInterval(breathInterval); +1183| let cycle = 0; +1184| +1185| // Physiological Sigh timing matcher (approximate for the 8s CSS animation) +1186| // 0-2s: Inhale +1187| // 2-3.5s: 2nd Inhale +1188| // 3.5-4s: Hold +1189| // 4-8s: Long slow exhale +1190| +1191| const updateText = () => { +1192| cycle = (cycle + 1) % 8; +1193| if (cycle < 2) text.textContent = "Inhale..."; +1194| else if (cycle < 3) text.textContent = "Sip more air..."; +1195| else if (cycle < 4) text.textContent = "Hold..."; +1196| else text.textContent = "Slooow Exhale..."; +1197| }; +1198| +1199| updateText(); // immediate run +1200| breathInterval = setInterval(() => { +1201| if (modal.hidden || p1.hidden) { +1202| clearInterval(breathInterval); +1203| return; +1204| } +1205| updateText(); +1206| }, 1000); +1207| } +1208| +1209| btnUnstuck.addEventListener('click', () => { +1210| resetUnstuckModal(); +1211| modal.hidden = false; +1212| syncBreathText(); +1213| }); +1214| +1215| closeBtn.addEventListener('click', () => { +1216| modal.hidden = true; +1217| clearInterval(unstuckInterval); +1218| clearInterval(breathInterval); +1219| }); +1220| +1221| // Proceed from phase 1 to 2 +1222| $('#unstuck-next-1').addEventListener('click', () => { +1223| p1.hidden = true; +1224| p2.hidden = false; +1225| }); +1226| +1227| // Proceed from phase 2 to 3 +1228| $('#unstuck-next-2').addEventListener('click', () => { +1229| p2.hidden = true; +1230| p3.hidden = false; +1231| }); +1232| +1233| // Phase 3 Timer +1234| startTimerBtn.addEventListener('click', () => { +1235| startTimerBtn.hidden = true; +1236| let timeLeft = 180; // 3 minutes +1237| +1238| unstuckInterval = setInterval(() => { +1239| timeLeft--; +1240| const m = Math.floor(timeLeft / 60).toString().padStart(2, '0'); +1241| const s = (timeLeft % 60).toString().padStart(2, '0'); +1242| timerDisplay.textContent = `${m}:${s}`; +1243| +1244| if (timeLeft <= 0) { +1245| clearInterval(unstuckInterval); +1246| timerDisplay.textContent = "Done!"; +1247| finishBtn.hidden = false; +1248| +1249| // Play success tone if soundscapes/audio is available globally +1250| try { +1251| if (window.AudioContext && !window.audioCtx) { +1252| window.audioCtx = new window.AudioContext(); +1253| } +1254| if (window.audioCtx) { +1255| const osc = audioCtx.createOscillator(); +1256| const gain = audioCtx.createGain(); +1257| osc.connect(gain); +1258| gain.connect(audioCtx.destination); +1259| osc.frequency.setValueAtTime(440, audioCtx.currentTime); // A4 +1260| osc.frequency.exponentialRampToValueAtTime(880, audioCtx.currentTime + 0.1); // Jump to A5 +1261| gain.gain.setValueAtTime(0, audioCtx.currentTime); +1262| gain.gain.linearRampToValueAtTime(0.5, audioCtx.currentTime + 0.05); +1263| gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 1); +1264| osc.start(audioCtx.currentTime); +1265| osc.stop(audioCtx.currentTime + 1); +1266| } +1267| } catch(e) { console.log(e); } +1268| } +1269| }, 1000); +1270| }); +1271| +1272| finishBtn.addEventListener('click', () => { +1273| modal.hidden = true; +1274| // Switch to Focus Timer using the main app's tab switching logic +1275| const timerTabBtn = document.getElementById('tab-timer'); +1276| if(timerTabBtn) timerTabBtn.click(); +1277| }); +1278| +1279|})(); \ No newline at end of file From 0d562fec39c22525d5f7c471f280f0986c7e5d35 Mon Sep 17 00:00:00 2001 From: djg Date: Wed, 23 Sep 2026 18:43:10 +0000 Subject: [PATCH 6/6] fix: remove errant line numbers injected by file patch tool --- site/static/app.js | 2558 ++++++++++++++++++++++---------------------- 1 file changed, 1279 insertions(+), 1279 deletions(-) diff --git a/site/static/app.js b/site/static/app.js index 329c7a9..8c82b43 100644 --- a/site/static/app.js +++ b/site/static/app.js @@ -1,443 +1,443 @@ -1|/* myadhd.dev β€” client-side tools. No accounts, no network; everything in localStorage. */ -2|(function () { -3| 'use strict'; -4| var $ = function (s, r) { return (r || document).querySelector(s); }; -5| var $$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); }; -6| function store(k, v) { -7| if (v === undefined) { try { return JSON.parse(localStorage.getItem('myadhd.' + k)); } catch (e) { return null; } } -8| localStorage.setItem('myadhd.' + k, JSON.stringify(v)); -9| } -10| function today() { return new Date().toISOString().slice(0, 10); } -11| -12| /* ---------- register service worker ---------- */ -13| if ('serviceWorker' in navigator) { -14| navigator.serviceWorker.register('/sw.js').catch(function () {}); -15| } -16| -17| /* ---------- audio helpers ---------- */ -18| var audioCtx = null; -19| function getAudio() { -20| if (!audioCtx) { -21| try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) {} -22| } -23| return audioCtx; -24| } -25| -26| function beep() { -27| var ctx = getAudio(); if (!ctx) return; -28| [[660, 0], [880, 0.18]].forEach(function (n) { -29| var o = ctx.createOscillator(), g = ctx.createGain(); -30| o.frequency.value = n[0]; o.type = 'sine'; -31| g.gain.setValueAtTime(0.001, ctx.currentTime + n[1]); -32| g.gain.exponentialRampToValueAtTime(0.12, ctx.currentTime + n[1] + 0.02); -33| g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + n[1] + 0.4); -34| o.connect(g); g.connect(ctx.destination); -35| o.start(ctx.currentTime + n[1]); o.stop(ctx.currentTime + n[1] + 0.45); -36| }); -37| } -38| -39| function tickSound() { -40| var ctx = getAudio(); if (!ctx) return; -41| var o = ctx.createOscillator(), g = ctx.createGain(); -42| o.frequency.value = 520; o.type = 'sine'; -43| g.gain.setValueAtTime(0.001, ctx.currentTime); -44| g.gain.exponentialRampToValueAtTime(0.08, ctx.currentTime + 0.01); -45| g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15); -46| o.connect(g); g.connect(ctx.destination); -47| o.start(ctx.currentTime); o.stop(ctx.currentTime + 0.2); -48| } -49| -50| function celebrateSound() { -51| var ctx = getAudio(); if (!ctx) return; -52| var notes = [523, 659, 784, 1047]; -53| notes.forEach(function (freq, i) { -54| var o = ctx.createOscillator(), g = ctx.createGain(); -55| o.frequency.value = freq; o.type = 'sine'; -56| g.gain.setValueAtTime(0.001, ctx.currentTime + i * 0.12); -57| g.gain.exponentialRampToValueAtTime(0.1, ctx.currentTime + i * 0.12 + 0.02); -58| g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + i * 0.12 + 0.35); -59| o.connect(g); g.connect(ctx.destination); -60| o.start(ctx.currentTime + i * 0.12); o.stop(ctx.currentTime + i * 0.12 + 0.4); -61| }); -62| } -63| -64| /* ---------- confetti ---------- */ -65| function confetti() { -66| var canvas = $('#confetti'); -67| if (!canvas) return; -68| var ctx2d = canvas.getContext('2d'); -69| canvas.width = window.innerWidth; -70| canvas.height = window.innerHeight; -71| var colors = ['#a78bfa', '#7dd3a0', '#f9c846', '#f472b6', '#60a5fa', '#e6e6f0']; -72| var pieces = []; -73| for (var i = 0; i < 80; i++) { -74| pieces.push({ -75| x: Math.random() * canvas.width, -76| y: Math.random() * canvas.height - canvas.height, -77| w: Math.random() * 8 + 4, -78| h: Math.random() * 6 + 3, -79| r: Math.random() * 6.28, -80| dx: (Math.random() - 0.5) * 4, -81| dy: Math.random() * 3 + 2, -82| dr: (Math.random() - 0.5) * 0.2, -83| color: colors[Math.floor(Math.random() * colors.length)], -84| life: 1 -85| }); -86| } -87| var frame; -88| function draw() { -89| ctx2d.clearRect(0, 0, canvas.width, canvas.height); -90| var alive = 0; -91| pieces.forEach(function (p) { -92| if (p.life <= 0) return; -93| alive++; -94| p.x += p.dx; -95| p.y += p.dy; -96| p.r += p.dr; -97| p.dy += 0.08; -98| p.life -= 0.008; -99| ctx2d.save(); -100| ctx2d.translate(p.x, p.y); -101| ctx2d.rotate(p.r); -102| ctx2d.globalAlpha = Math.max(0, p.life); -103| ctx2d.fillStyle = p.color; -104| ctx2d.fillRect(-p.w / 2, -p.h / 2, p.w, p.h); -105| ctx2d.restore(); -106| }); -107| if (alive > 0) { frame = requestAnimationFrame(draw); } -108| else { ctx2d.clearRect(0, 0, canvas.width, canvas.height); } -109| } -110| if (frame) cancelAnimationFrame(frame); -111| draw(); -112| } -113| -114| /* ---------- tabs ---------- */ -115| function showTab(name) { -116| $$('.tool').forEach(function (t) { t.hidden = (t.id !== name); }); -117| $$('.tab').forEach(function (t) { -118| var isOn = t.dataset.tab === name; -119| t.classList.toggle('on', isOn); -120| t.setAttribute('aria-selected', isOn ? 'true' : 'false'); -121| }); -122| try { history.replaceState(null, '', '#' + name); } catch (e) {} -123| } -124| $$('.tab').forEach(function (t) { -125| t.addEventListener('click', function (e) { e.preventDefault(); showTab(t.dataset.tab); }); -126| }); -127| -128| /* ---------- welcome / first visit ---------- */ -129| var visited = store('visited'); -130| var initial = location.hash.slice(1); -131| if (!visited && !initial) { -132| showTab('welcome'); -133| store('visited', true); -134| } else { -135| showTab(['breaker', 'timer', 'dopamine', 'now', 'inbox'].indexOf(initial) !== -1 ? initial : 'breaker'); -136| } -137| -138| $$('.welcome-btn').forEach(function (b) { -139| b.addEventListener('click', function () { -140| var target = b.dataset.goto; -141| if (target === 'pick') { -142| var tabs = ['breaker', 'timer', 'dopamine', 'now']; -143| target = tabs[Math.floor(Math.random() * tabs.length)]; -144| } -145| showTab(target); -146| }); -147| }); -148| -149| /* ---------- session stats ---------- */ -150| function paintStats() { -151| var sessions = store('sessions') || 0; -152| var el = $('#session-stats'); -153| var text = $('#stats-text'); -154| if (sessions > 0 && el && text) { -155| el.hidden = false; -156| text.textContent = sessions + ' focus round' + (sessions !== 1 ? 's' : '') + ' completed β€” nice work.'; -157| } -158| } -159| paintStats(); -160| -161| /* ---------- task breaker ---------- */ -162| var breakerKey = 'breaker'; -163| function breakerTemplates(task) { -164| return [ -165| { t: 'Write down what "done" looks like for: ' + task + '.', mins: 2, done: false }, -166| { t: 'Gather everything you need for "' + task + '" in one spot.', mins: 5, done: false }, -167| { t: 'Do the ugliest possible first draft of "' + task + '". Rough is the goal.', mins: 5, done: false }, -168| { t: 'Set a 10-minute timer and start "' + task + '". Starting is the whole job.', mins: 10, done: false }, -169| { t: 'Momentum check: keep going, or park it with a note for next time.', mins: 2, done: false }, -170| { t: 'Close the loop: tidy up and write down the very next step.', mins: 2, done: false } -171| ]; -172| } -173| -174| function breakerFindNextStep(b) { -175| if (!b || !b.steps) return -1; -176| for (var i = 0; i < b.steps.length; i++) { -177| if (!b.steps[i].done) return i; -178| } -179| return -1; -180| } -181| -182| function breakerRender() { -183| var b = store(breakerKey); -184| $('#breaker-out').hidden = !b; -185| if (!b) return; -186| var ul = $('#breaker-steps'); -187| ul.innerHTML = ''; -188| var done = 0; -189| var allDone = true; -190| b.steps.forEach(function (s, i) { -191| if (s.done) done++; -192| else allDone = false; -193| var li = document.createElement('li'); -194| li.className = s.done ? 'done' : ''; -195| var tick = document.createElement('button'); -196| tick.className = 'tick'; tick.type = 'button'; -197| tick.setAttribute('aria-label', s.done ? 'Mark undone' : 'Mark done'); -198| tick.addEventListener('click', function () { -199| var wasDone = s.done; -200| s.done = !s.done; -201| store(breakerKey, b); -202| if (!wasDone) { -203| tickSound(); -204| li.classList.add('step-just-done'); -205| setTimeout(function () { li.classList.remove('step-just-done'); }, 300); -206| } -207| breakerRender(); -208| // If all done, celebrate! -209| if (!wasDone) { -210| var allNow = b.steps.every(function (st) { return st.done; }); -211| if (allNow) { -212| celebrateSound(); -213| confetti(); -214| } -215| } -216| }); -217| var txt = document.createElement('span'); -218| txt.className = 'txt'; txt.contentEditable = 'true'; txt.textContent = s.t; -219| txt.setAttribute('role', 'textbox'); -220| txt.setAttribute('aria-label', 'Step ' + (i + 1) + ' text'); -221| txt.addEventListener('blur', function () { s.t = txt.textContent.trim(); store(breakerKey, b); }); -222| var mins = document.createElement('span'); -223| mins.className = 'mins'; mins.textContent = s.mins ? s.mins + ' min' : ''; -224| -225| // "start this step" button for undone steps -226| var actions = document.createElement('span'); -227| actions.className = 'step-actions'; -228| if (!s.done) { -229| var goBtn = document.createElement('button'); -230| goBtn.className = 'step-go'; -231| goBtn.textContent = 'start β†’'; -232| goBtn.type = 'button'; -233| goBtn.setAttribute('aria-label', 'Start working on this step'); -234| goBtn.addEventListener('click', function () { -235| // Set this step as the One Thing -236| store('now', { text: s.t, fromBreaker: true, stepIndex: i }); -237| showTab('now'); -238| nowRender(); -239| }); -240| actions.appendChild(goBtn); -241| } -242| -243| li.appendChild(tick); li.appendChild(txt); li.appendChild(mins); li.appendChild(actions); -244| ul.appendChild(li); -245| }); -246| -247| $('#breaker-progress').style.width = b.steps.length ? (100 * done / b.steps.length) + '%' : '0'; -248| $('#breaker-count').textContent = done + ' of ' + b.steps.length + ' steps done'; -249| -250| // Show/hide done message -251| var doneMsg = $('#breaker-done-msg'); -252| var actionsRow = $('#breaker-actions'); -253| if (allDone && b.steps.length) { -254| doneMsg.hidden = false; -255| actionsRow.hidden = true; -256| } else { -257| doneMsg.hidden = true; -258| actionsRow.hidden = false; -259| } -260| } -261| -262| $('#breaker-form').addEventListener('submit', function (e) { -263| e.preventDefault(); -264| var task = $('#breaker-input').value.trim(); -265| if (!task) return; -266| store(breakerKey, { task: task, steps: breakerTemplates(task) }); -267| breakerRender(); -268| }); -269| $('#breaker-add').addEventListener('click', function () { -270| var b = store(breakerKey); if (!b) return; -271| b.steps.push({ t: 'Next step…', mins: 0, done: false }); -272| store(breakerKey, b); breakerRender(); -273| }); -274| $('#breaker-reset').addEventListener('click', function () { -275| localStorage.removeItem('myadhd.' + breakerKey); -276| $('#breaker-input').value = ''; -277| breakerRender(); -278| }); -279| $('#breaker-new').addEventListener('click', function () { -280| localStorage.removeItem('myadhd.' + breakerKey); -281| $('#breaker-input').value = ''; -282| breakerRender(); -283| $('#breaker-input').focus(); -284| }); -285| breakerRender(); -286| -287| /* ---------- focus timer ---------- */ -288| var CIRC = 628.3; -289| // Restore persisted timer state or default -290| var timerState = store('timer_state'); -291| var timer; -292| if (timerState && timerState.left > 0) { -293| timer = { total: timerState.total, left: timerState.left, running: false, phase: timerState.phase || 'focus', iv: null }; -294| } else { -295| timer = { total: 25 * 60, left: 25 * 60, running: false, phase: 'focus', iv: null }; -296| } -297| -298| function timerPersist() { -299| store('timer_state', { total: timer.total, left: timer.left, phase: timer.phase }); -300| } -301| -302| window.groundingIv = null; -303| window.setGroundingInterval = function() { -304| if (window.groundingIv) { clearInterval(window.groundingIv); window.groundingIv = null; } -305| var activeBtn = $('.grounding-chime.active'); -306| if (!activeBtn) return; -307| var mins = parseInt(activeBtn.dataset.interval, 10); -308| if (mins > 0 && timer.running) { -309| window.groundingIv = setInterval(function() { -310| if (window.playGroundingPing) window.playGroundingPing(); -311| }, mins * 60 * 1000); -312| } -313| }; -314| -315| function timerPaint() { -316| var m = Math.floor(timer.left / 60), s = timer.left % 60; -317| $('#timer-time').textContent = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s; -318| $('#ring-fg').style.strokeDashoffset = CIRC * (1 - timer.left / timer.total); -319| -320| var portion = timer.total > 0 ? (timer.left / timer.total) : 0; -321| var piePath = $('#ring-pie-path'); -322| var pieSvg = $('#ring-pie-svg'); -323| if (piePath && pieSvg) { -324| if (portion <= 0) { -325| piePath.setAttribute("d", "M110,110 Z"); -326| } else if (portion >= 1) { -327| piePath.setAttribute("d", "M110,110 L110,10 A100,100 0 1,1 109.99,10 Z"); -328| } else { -329| var angle = portion * 360; -330| var rad = (angle * Math.PI) / 180; -331| var x = 110 + 100 * Math.sin(rad); -332| var y = 110 - 100 * Math.cos(rad); -333| var largeArc = angle > 180 ? 1 : 0; -334| piePath.setAttribute("d", "M110,110 L110,10 A100,100 0 " + largeArc + ",1 " + x + "," + y + " Z"); -335| } -336| pieSvg.classList.toggle('alert-amber', timer.left < 120 && timer.running); -337| } -338| -339| // Ring color matches phase -340| var ringFg = $('#ring-fg'); -341| if (timer.phase === 'break') { ringFg.classList.add('break-ring'); } -342| else { ringFg.classList.remove('break-ring'); } -343| var ph = $('#timer-phase'); -344| ph.textContent = timer.running ? (timer.phase === 'focus' ? 'focus β€” you got this' : 'break β€” actually rest') : ph.textContent; -345| ph.className = 'timer-phase' + (timer.phase === 'break' ? ' break' : ''); -346| // Update context bar -347| var nowData = store('now'); -348| var ctxBar = $('#timer-context-bar'); -349| var ctxText = $('#timer-context-text'); -350| if (nowData && nowData.text && ctxBar && ctxText) { -351| ctxBar.hidden = false; -352| ctxText.textContent = nowData.text; -353| } else if (ctxBar) { -354| ctxBar.hidden = true; -355| } -356| } -357| -358| function timerStop() { clearInterval(timer.iv); timer.iv = null; timer.running = false; -359| timerPersist(); } -360| -361| function timerComplete() { -362| timerStop(); beep(); -363| if (timer.phase === 'focus') { -364| var sessions = (store('sessions') || 0) + 1; -365| store('sessions', sessions); -366| paintStats(); -367| // Show completion overlay -368| var overlay = $('#timer-complete'); -369| if (overlay) { -370| overlay.hidden = false; -371| $('#timer-complete-sessions').textContent = sessions + ' focus round' + (sessions !== 1 ? 's' : '') + ' completed.'; -372| // Show "mark step done" only if there's a linked one-thing from breaker -373| var nowData = store('now'); -374| var markBtn = $('#timer-mark-done'); -375| if (markBtn) { -376| markBtn.hidden = !(nowData && nowData.fromBreaker); -377| } -378| } -379| celebrateSound(); -380| confetti(); -381| } else { -382| // Break is over -383| timer.phase = 'focus'; -384| timer.total = timer.left = 25 * 60; -385| $('#timer-start').textContent = 'start'; -386| $('#timer-note').textContent = 'Break over. Pick a length and go again β€” or stop here, that is allowed too.'; -387| } -388| timerPersist(); -389| timerPaint(); -390| } -391| -392| // Pie Mode Toggle -393| var modeToggleBtn = $('#timer-mode-toggle'); -394| if (modeToggleBtn) { -395| modeToggleBtn.addEventListener('click', function() { -396| var pieSvg = $('#ring-pie-svg'); -397| var ringSvg = $('.timer-wrap > svg.ring:not(.pie-mode)'); -398| var isPie = pieSvg.style.display !== 'none'; -399| if (isPie) { -400| pieSvg.style.display = 'none'; -401| ringSvg.style.display = ''; -402| this.innerHTML = ' switch to visual pie mode'; -403| } else { -404| pieSvg.style.display = ''; -405| ringSvg.style.display = 'none'; -406| this.innerHTML = ' switch to ring mode'; -407| } -408| timerPaint(); -409| }); -410| } -411| -412| $('#timer-start').addEventListener('click', function () { -413| if (window.setGroundingInterval) window.setGroundingInterval(); -414| if (timer.running) { timerStop(); $('#timer-start').textContent = 'resume'; timerPaint(); return; } -415| timer.running = true; -416| if (window.setGroundingInterval) window.setGroundingInterval(); -417| $('#timer-start').textContent = 'pause'; -418| timer.iv = setInterval(function () { -419| timer.left--; -420| timerPersist(); -421| if (timer.left <= 0) { -422| timerComplete(); -423| return; -424| } -425| timerPaint(); -426| }, 1000); -427| timerPaint(); -428| }); -429| -430| function timerReset() { -431| timerStop(); timer.left = timer.total; $('#timer-start').textContent = 'start'; -432| timerPersist(); timerPaint(); -433| } -434| -435| /* ---------- AI Auto-Deconstruct Contract (Tier 1 & 2) ---------- */ -436| window.aiBreakdownTask = async function(taskText) { -437| // Shared Interface for Sibyl's Tier 3 -438| const prompt = `Break down this intimidating task into 3-5 tiny, actionable micro-steps: "${taskText}". Return only the list of steps.`; -439| -440| // Tier 3: WebLLM In-Browser (Advanced Opt-in) +/* myadhd.dev β€” client-side tools. No accounts, no network; everything in localStorage. */ +(function () { + 'use strict'; + var $ = function (s, r) { return (r || document).querySelector(s); }; + var $$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); }; + function store(k, v) { + if (v === undefined) { try { return JSON.parse(localStorage.getItem('myadhd.' + k)); } catch (e) { return null; } } + localStorage.setItem('myadhd.' + k, JSON.stringify(v)); + } + function today() { return new Date().toISOString().slice(0, 10); } + + /* ---------- register service worker ---------- */ + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js').catch(function () {}); + } + + /* ---------- audio helpers ---------- */ + var audioCtx = null; + function getAudio() { + if (!audioCtx) { + try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) {} + } + return audioCtx; + } + + function beep() { + var ctx = getAudio(); if (!ctx) return; + [[660, 0], [880, 0.18]].forEach(function (n) { + var o = ctx.createOscillator(), g = ctx.createGain(); + o.frequency.value = n[0]; o.type = 'sine'; + g.gain.setValueAtTime(0.001, ctx.currentTime + n[1]); + g.gain.exponentialRampToValueAtTime(0.12, ctx.currentTime + n[1] + 0.02); + g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + n[1] + 0.4); + o.connect(g); g.connect(ctx.destination); + o.start(ctx.currentTime + n[1]); o.stop(ctx.currentTime + n[1] + 0.45); + }); + } + + function tickSound() { + var ctx = getAudio(); if (!ctx) return; + var o = ctx.createOscillator(), g = ctx.createGain(); + o.frequency.value = 520; o.type = 'sine'; + g.gain.setValueAtTime(0.001, ctx.currentTime); + g.gain.exponentialRampToValueAtTime(0.08, ctx.currentTime + 0.01); + g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15); + o.connect(g); g.connect(ctx.destination); + o.start(ctx.currentTime); o.stop(ctx.currentTime + 0.2); + } + + function celebrateSound() { + var ctx = getAudio(); if (!ctx) return; + var notes = [523, 659, 784, 1047]; + notes.forEach(function (freq, i) { + var o = ctx.createOscillator(), g = ctx.createGain(); + o.frequency.value = freq; o.type = 'sine'; + g.gain.setValueAtTime(0.001, ctx.currentTime + i * 0.12); + g.gain.exponentialRampToValueAtTime(0.1, ctx.currentTime + i * 0.12 + 0.02); + g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + i * 0.12 + 0.35); + o.connect(g); g.connect(ctx.destination); + o.start(ctx.currentTime + i * 0.12); o.stop(ctx.currentTime + i * 0.12 + 0.4); + }); + } + + /* ---------- confetti ---------- */ + function confetti() { + var canvas = $('#confetti'); + if (!canvas) return; + var ctx2d = canvas.getContext('2d'); + canvas.width = window.innerWidth; + canvas.height = window.innerHeight; + var colors = ['#a78bfa', '#7dd3a0', '#f9c846', '#f472b6', '#60a5fa', '#e6e6f0']; + var pieces = []; + for (var i = 0; i < 80; i++) { + pieces.push({ + x: Math.random() * canvas.width, + y: Math.random() * canvas.height - canvas.height, + w: Math.random() * 8 + 4, + h: Math.random() * 6 + 3, + r: Math.random() * 6.28, + dx: (Math.random() - 0.5) * 4, + dy: Math.random() * 3 + 2, + dr: (Math.random() - 0.5) * 0.2, + color: colors[Math.floor(Math.random() * colors.length)], + life: 1 + }); + } + var frame; + function draw() { + ctx2d.clearRect(0, 0, canvas.width, canvas.height); + var alive = 0; + pieces.forEach(function (p) { + if (p.life <= 0) return; + alive++; + p.x += p.dx; + p.y += p.dy; + p.r += p.dr; + p.dy += 0.08; + p.life -= 0.008; + ctx2d.save(); + ctx2d.translate(p.x, p.y); + ctx2d.rotate(p.r); + ctx2d.globalAlpha = Math.max(0, p.life); + ctx2d.fillStyle = p.color; + ctx2d.fillRect(-p.w / 2, -p.h / 2, p.w, p.h); + ctx2d.restore(); + }); + if (alive > 0) { frame = requestAnimationFrame(draw); } + else { ctx2d.clearRect(0, 0, canvas.width, canvas.height); } + } + if (frame) cancelAnimationFrame(frame); + draw(); + } + + /* ---------- tabs ---------- */ + function showTab(name) { + $$('.tool').forEach(function (t) { t.hidden = (t.id !== name); }); + $$('.tab').forEach(function (t) { + var isOn = t.dataset.tab === name; + t.classList.toggle('on', isOn); + t.setAttribute('aria-selected', isOn ? 'true' : 'false'); + }); + try { history.replaceState(null, '', '#' + name); } catch (e) {} + } + $$('.tab').forEach(function (t) { + t.addEventListener('click', function (e) { e.preventDefault(); showTab(t.dataset.tab); }); + }); + + /* ---------- welcome / first visit ---------- */ + var visited = store('visited'); + var initial = location.hash.slice(1); + if (!visited && !initial) { + showTab('welcome'); + store('visited', true); + } else { + showTab(['breaker', 'timer', 'dopamine', 'now', 'inbox'].indexOf(initial) !== -1 ? initial : 'breaker'); + } + + $$('.welcome-btn').forEach(function (b) { + b.addEventListener('click', function () { + var target = b.dataset.goto; + if (target === 'pick') { + var tabs = ['breaker', 'timer', 'dopamine', 'now']; + target = tabs[Math.floor(Math.random() * tabs.length)]; + } + showTab(target); + }); + }); + + /* ---------- session stats ---------- */ + function paintStats() { + var sessions = store('sessions') || 0; + var el = $('#session-stats'); + var text = $('#stats-text'); + if (sessions > 0 && el && text) { + el.hidden = false; + text.textContent = sessions + ' focus round' + (sessions !== 1 ? 's' : '') + ' completed β€” nice work.'; + } + } + paintStats(); + + /* ---------- task breaker ---------- */ + var breakerKey = 'breaker'; + function breakerTemplates(task) { + return [ + { t: 'Write down what "done" looks like for: ' + task + '.', mins: 2, done: false }, + { t: 'Gather everything you need for "' + task + '" in one spot.', mins: 5, done: false }, + { t: 'Do the ugliest possible first draft of "' + task + '". Rough is the goal.', mins: 5, done: false }, + { t: 'Set a 10-minute timer and start "' + task + '". Starting is the whole job.', mins: 10, done: false }, + { t: 'Momentum check: keep going, or park it with a note for next time.', mins: 2, done: false }, + { t: 'Close the loop: tidy up and write down the very next step.', mins: 2, done: false } + ]; + } + + function breakerFindNextStep(b) { + if (!b || !b.steps) return -1; + for (var i = 0; i < b.steps.length; i++) { + if (!b.steps[i].done) return i; + } + return -1; + } + + function breakerRender() { + var b = store(breakerKey); + $('#breaker-out').hidden = !b; + if (!b) return; + var ul = $('#breaker-steps'); + ul.innerHTML = ''; + var done = 0; + var allDone = true; + b.steps.forEach(function (s, i) { + if (s.done) done++; + else allDone = false; + var li = document.createElement('li'); + li.className = s.done ? 'done' : ''; + var tick = document.createElement('button'); + tick.className = 'tick'; tick.type = 'button'; + tick.setAttribute('aria-label', s.done ? 'Mark undone' : 'Mark done'); + tick.addEventListener('click', function () { + var wasDone = s.done; + s.done = !s.done; + store(breakerKey, b); + if (!wasDone) { + tickSound(); + li.classList.add('step-just-done'); + setTimeout(function () { li.classList.remove('step-just-done'); }, 300); + } + breakerRender(); + // If all done, celebrate! + if (!wasDone) { + var allNow = b.steps.every(function (st) { return st.done; }); + if (allNow) { + celebrateSound(); + confetti(); + } + } + }); + var txt = document.createElement('span'); + txt.className = 'txt'; txt.contentEditable = 'true'; txt.textContent = s.t; + txt.setAttribute('role', 'textbox'); + txt.setAttribute('aria-label', 'Step ' + (i + 1) + ' text'); + txt.addEventListener('blur', function () { s.t = txt.textContent.trim(); store(breakerKey, b); }); + var mins = document.createElement('span'); + mins.className = 'mins'; mins.textContent = s.mins ? s.mins + ' min' : ''; + + // "start this step" button for undone steps + var actions = document.createElement('span'); + actions.className = 'step-actions'; + if (!s.done) { + var goBtn = document.createElement('button'); + goBtn.className = 'step-go'; + goBtn.textContent = 'start β†’'; + goBtn.type = 'button'; + goBtn.setAttribute('aria-label', 'Start working on this step'); + goBtn.addEventListener('click', function () { + // Set this step as the One Thing + store('now', { text: s.t, fromBreaker: true, stepIndex: i }); + showTab('now'); + nowRender(); + }); + actions.appendChild(goBtn); + } + + li.appendChild(tick); li.appendChild(txt); li.appendChild(mins); li.appendChild(actions); + ul.appendChild(li); + }); + + $('#breaker-progress').style.width = b.steps.length ? (100 * done / b.steps.length) + '%' : '0'; + $('#breaker-count').textContent = done + ' of ' + b.steps.length + ' steps done'; + + // Show/hide done message + var doneMsg = $('#breaker-done-msg'); + var actionsRow = $('#breaker-actions'); + if (allDone && b.steps.length) { + doneMsg.hidden = false; + actionsRow.hidden = true; + } else { + doneMsg.hidden = true; + actionsRow.hidden = false; + } + } + + $('#breaker-form').addEventListener('submit', function (e) { + e.preventDefault(); + var task = $('#breaker-input').value.trim(); + if (!task) return; + store(breakerKey, { task: task, steps: breakerTemplates(task) }); + breakerRender(); + }); + $('#breaker-add').addEventListener('click', function () { + var b = store(breakerKey); if (!b) return; + b.steps.push({ t: 'Next step…', mins: 0, done: false }); + store(breakerKey, b); breakerRender(); + }); + $('#breaker-reset').addEventListener('click', function () { + localStorage.removeItem('myadhd.' + breakerKey); + $('#breaker-input').value = ''; + breakerRender(); + }); + $('#breaker-new').addEventListener('click', function () { + localStorage.removeItem('myadhd.' + breakerKey); + $('#breaker-input').value = ''; + breakerRender(); + $('#breaker-input').focus(); + }); + breakerRender(); + + /* ---------- focus timer ---------- */ + var CIRC = 628.3; + // Restore persisted timer state or default + var timerState = store('timer_state'); + var timer; + if (timerState && timerState.left > 0) { + timer = { total: timerState.total, left: timerState.left, running: false, phase: timerState.phase || 'focus', iv: null }; + } else { + timer = { total: 25 * 60, left: 25 * 60, running: false, phase: 'focus', iv: null }; + } + + function timerPersist() { + store('timer_state', { total: timer.total, left: timer.left, phase: timer.phase }); + } + + window.groundingIv = null; + window.setGroundingInterval = function() { + if (window.groundingIv) { clearInterval(window.groundingIv); window.groundingIv = null; } + var activeBtn = $('.grounding-chime.active'); + if (!activeBtn) return; + var mins = parseInt(activeBtn.dataset.interval, 10); + if (mins > 0 && timer.running) { + window.groundingIv = setInterval(function() { + if (window.playGroundingPing) window.playGroundingPing(); + }, mins * 60 * 1000); + } + }; + + function timerPaint() { + var m = Math.floor(timer.left / 60), s = timer.left % 60; + $('#timer-time').textContent = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s; + $('#ring-fg').style.strokeDashoffset = CIRC * (1 - timer.left / timer.total); + + var portion = timer.total > 0 ? (timer.left / timer.total) : 0; + var piePath = $('#ring-pie-path'); + var pieSvg = $('#ring-pie-svg'); + if (piePath && pieSvg) { + if (portion <= 0) { + piePath.setAttribute("d", "M110,110 Z"); + } else if (portion >= 1) { + piePath.setAttribute("d", "M110,110 L110,10 A100,100 0 1,1 109.99,10 Z"); + } else { + var angle = portion * 360; + var rad = (angle * Math.PI) / 180; + var x = 110 + 100 * Math.sin(rad); + var y = 110 - 100 * Math.cos(rad); + var largeArc = angle > 180 ? 1 : 0; + piePath.setAttribute("d", "M110,110 L110,10 A100,100 0 " + largeArc + ",1 " + x + "," + y + " Z"); + } + pieSvg.classList.toggle('alert-amber', timer.left < 120 && timer.running); + } + + // Ring color matches phase + var ringFg = $('#ring-fg'); + if (timer.phase === 'break') { ringFg.classList.add('break-ring'); } + else { ringFg.classList.remove('break-ring'); } + var ph = $('#timer-phase'); + ph.textContent = timer.running ? (timer.phase === 'focus' ? 'focus β€” you got this' : 'break β€” actually rest') : ph.textContent; + ph.className = 'timer-phase' + (timer.phase === 'break' ? ' break' : ''); + // Update context bar + var nowData = store('now'); + var ctxBar = $('#timer-context-bar'); + var ctxText = $('#timer-context-text'); + if (nowData && nowData.text && ctxBar && ctxText) { + ctxBar.hidden = false; + ctxText.textContent = nowData.text; + } else if (ctxBar) { + ctxBar.hidden = true; + } + } + + function timerStop() { clearInterval(timer.iv); timer.iv = null; timer.running = false; + timerPersist(); } + + function timerComplete() { + timerStop(); beep(); + if (timer.phase === 'focus') { + var sessions = (store('sessions') || 0) + 1; + store('sessions', sessions); + paintStats(); + // Show completion overlay + var overlay = $('#timer-complete'); + if (overlay) { + overlay.hidden = false; + $('#timer-complete-sessions').textContent = sessions + ' focus round' + (sessions !== 1 ? 's' : '') + ' completed.'; + // Show "mark step done" only if there's a linked one-thing from breaker + var nowData = store('now'); + var markBtn = $('#timer-mark-done'); + if (markBtn) { + markBtn.hidden = !(nowData && nowData.fromBreaker); + } + } + celebrateSound(); + confetti(); + } else { + // Break is over + timer.phase = 'focus'; + timer.total = timer.left = 25 * 60; + $('#timer-start').textContent = 'start'; + $('#timer-note').textContent = 'Break over. Pick a length and go again β€” or stop here, that is allowed too.'; + } + timerPersist(); + timerPaint(); + } + + // Pie Mode Toggle + var modeToggleBtn = $('#timer-mode-toggle'); + if (modeToggleBtn) { + modeToggleBtn.addEventListener('click', function() { + var pieSvg = $('#ring-pie-svg'); + var ringSvg = $('.timer-wrap > svg.ring:not(.pie-mode)'); + var isPie = pieSvg.style.display !== 'none'; + if (isPie) { + pieSvg.style.display = 'none'; + ringSvg.style.display = ''; + this.innerHTML = ' switch to visual pie mode'; + } else { + pieSvg.style.display = ''; + ringSvg.style.display = 'none'; + this.innerHTML = ' switch to ring mode'; + } + timerPaint(); + }); + } + + $('#timer-start').addEventListener('click', function () { + if (window.setGroundingInterval) window.setGroundingInterval(); + if (timer.running) { timerStop(); $('#timer-start').textContent = 'resume'; timerPaint(); return; } + timer.running = true; + if (window.setGroundingInterval) window.setGroundingInterval(); + $('#timer-start').textContent = 'pause'; + timer.iv = setInterval(function () { + timer.left--; + timerPersist(); + if (timer.left <= 0) { + timerComplete(); + return; + } + timerPaint(); + }, 1000); + timerPaint(); + }); + + function timerReset() { + timerStop(); timer.left = timer.total; $('#timer-start').textContent = 'start'; + timerPersist(); timerPaint(); + } + + /* ---------- AI Auto-Deconstruct Contract (Tier 1 & 2) ---------- */ + window.aiBreakdownTask = async function(taskText) { + // Shared Interface for Sibyl's Tier 3 + const prompt = `Break down this intimidating task into 3-5 tiny, actionable micro-steps: "${taskText}". Return only the list of steps.`; + + // Tier 3: WebLLM In-Browser (Advanced Opt-in) // Checks if the user explicitly opted in to download the model if (localStorage.getItem('ai_webllm_enabled') === 'true') { try { @@ -463,842 +463,842 @@ } // Tier 1: Browser Native (window.ai) -441| if (window.ai && window.ai.languageModel) { -442| try { -443| const caps = await window.ai.languageModel.capabilities(); -444| if (caps.available !== 'no') { -445| const session = await window.ai.languageModel.create(); -446| const result = await session.prompt(prompt); -447| return result.split('\n').filter(s => s.trim().length > 0); -448| } -449| } catch (e) { -450| console.warn("window.ai failed, falling back", e); -451| } -452| } -453| -454| // Tier 2: BYOK (Bring Your Own Key) Fallback -455| const key = store('byok_key'); -456| if (!key) { -457| throw new Error("NO_AI_AVAILABLE"); // Let UI prompt for key or let Tier 3 try -458| } -459| const resp = await fetch('https://api.openai.com/v1/chat/completions', { -460| method: 'POST', -461| headers: { -462| 'Content-Type': 'application/json', -463| 'Authorization': 'Bearer ' + key -464| }, -465| body: JSON.stringify({ -466| model: 'gpt-4o-mini', -467| messages: [{ role: 'user', content: prompt }] -468| }) -469| }); -470| if (!resp.ok) throw new Error("API_ERROR"); -471| const data = await resp.json(); -472| return data.choices[0].message.content.split('\n').filter(s => s.trim().length > 0); -473| }; -474| -475| $('#timer-reset').addEventListener('click', timerReset); -476| -477| $$('.preset').forEach(function (p) { -478| p.addEventListener('click', function () { -479| timerStop(); -480| timer.total = timer.left = (+p.dataset.min) * 60; -481| timer.phase = p.classList.contains('break') ? 'break' : 'focus'; -482| $('#timer-start').textContent = 'start'; -483| timerPersist(); timerPaint(); -484| }); -485| }); -486| -487| $$('.grounding-chime').forEach(function(btn) { -488| btn.addEventListener('click', function() { -489| $$('.grounding-chime').forEach(function(b) { b.classList.remove('active'); }); -490| btn.classList.add('active'); -491| if (window.setGroundingInterval) window.setGroundingInterval(); -492| }); -493| }); -494| -495| // Timer completion overlay actions -496| $('#timer-take-break').addEventListener('click', function () { -497| $('#timer-complete').hidden = true; -498| timer.phase = 'break'; -499| timer.total = timer.left = 5 * 60; -500| $('#timer-start').textContent = 'start'; -501| $('#timer-note').textContent = 'Focus round done. Stand up. Drink water. Actually take the break.'; -502| timerPersist(); timerPaint(); -503| }); -504| -505| $('#timer-mark-done').addEventListener('click', function () { -506| $('#timer-complete').hidden = true; -507| // Mark the current one-thing step as done in the breaker -508| var nowData = store('now'); -509| var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; -510| if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { -511| var b = store(breakerKey); -512| if (b && b.steps[nowData.stepIndex]) { -513| b.steps[nowData.stepIndex].done = true; -514| store(breakerKey, b); -515| breakerRender(); -516| } -517| } -518| handleNewDoneTasks(taskText); -519| // Reset timer so it's fresh for the next step -520| timerReset(); -521| // Clear one-thing and show next step prompt -522| localStorage.removeItem('myadhd.now'); -523| showTab('now'); -524| nowShowNext(true); -525| }); -526| -527| timerPaint(); -528| -529| /* ---------- dopamine menu ---------- */ -530| var MENU = { -531| 5: [ -532| 'Put on one song and tidy one single surface.', -533| 'Drink a big glass of water like it is a magic potion.', -534| 'Step outside for two minutes and name five sounds you hear.', -535| 'Stretch your arms and neck slowly β€” like a cat waking up.', -536| 'Text someone one true compliment. No context, no apology.', -537| 'Draw the nearest object as badly as you possibly can.', -538| 'Open the window and take ten slow breaths.', -539| 'Rearrange exactly three things on your desk.', -540| 'Do ten squats or one ridiculous dance move.', -541| 'Write down three things you can see right now that you like.' -542| ], -543| 15: [ -544| 'Walk once around the block β€” phone stays home or in pocket.', -545| 'Build the fanciest snack possible from what you already have.', -546| 'Write a short thank-you note to your future self.', -547| 'Doodle your current mood as a weather report.', -548| 'Do a ten-minute follow-along stretch video.', -549| 'Clean one drawer. One. Set a timer so it cannot grow.', -550| 'Read five pages of any book you own.', -551| 'Water (or rescue) one plant.', -552| 'Have a shower, but treat it like a whole concert.', -553| 'Learn three words in a language you do not speak.' -554| ], -555| 30: [ -556| 'Cook something new with a video recipe playing.', -557| 'Go for a 25-minute walk with one podcast episode.', -558| 'Call someone you like. With your voice. Wild, we know.', -559| 'Build something with zero rules: LEGO, blanket fort, collage.', -560| 'Brain-dump everything in your head onto paper for ten minutes.', -561| 'Deep-clean the one object that quietly bothers you most.', -562| 'Follow a 30-minute workout video at whatever intensity you like.', -563| 'Walk or bike to a spot nearby you have never actually been.', -564| 'Pack a small comfort bag for your worst brain days.', -565| 'Ten minutes journaling, ten minutes stretching, ten minutes staring.' -566| ], -567| 60: [ -568| 'Long walk or bike ride somewhere with trees.', -569| 'One-hour hobby sprint β€” make something terrible and be proud.', -570| 'Bake something from scratch. Eat evidence.', -571| 'One-room tidy: music loud, timer rules, no mercy.', -572| 'Wandering trip (thrift store, library) with a $10 budget.', -573| 'Digital reset: close twenty tabs, clear the inbox as far as you can.', -574| 'Follow a full workout or yoga class at home.', -575| 'Meal-prep one lunch so tomorrow-you says thanks.', -576| 'Take a notebook to a cafΓ© or library and people-watch or sketch.', -577| 'Watch a documentary about something absurd and become an expert.' -578| ] -579| }; -580| var lastPick = null; -581| var currentMenuMins = store('menu_mins') || null; -582| -583| function menuPick(mins) { -584| currentMenuMins = mins; -585| store('menu_mins', mins); -586| // Highlight the selected time button -587| $$('.menu-pick').forEach(function (b) { -588| b.classList.toggle('on', +b.dataset.min === mins); -589| }); -590| var pool = MENU[mins].filter(function (x) { return x !== lastPick; }); -591| var item = pool[Math.floor(Math.random() * pool.length)]; -592| lastPick = item; -593| $('#menu-text').textContent = item; -594| $('#menu-item').hidden = false; -595| $('#menu-actions').hidden = false; -596| } -597| -598| $$('.menu-pick').forEach(function (b) { -599| b.addEventListener('click', function () { menuPick(+b.dataset.min); }); -600| }); -601| -602| $('#menu-reroll').addEventListener('click', function () { -603| // Use tracked mins instead of .on class -604| menuPick(currentMenuMins || 5); -605| }); -606| -607| function paintStreak() { -608| var s = store('streak'); -609| $('#menu-streak').innerHTML = s && s.streak ? -610| 'Streak: ' + s.streak + ' day' + (s.streak > 1 ? 's' : '') + ' of healthy dopamine. ' + -611| (s.last === today() ? 'Today is already logged.' : '') : ''; -612| } -613| $('#menu-done').addEventListener('click', function () { -614| var s = store('streak') || { last: '', streak: 0 }; -615| if (s.last !== today()) { -616| var y = new Date(Date.now() - 86400000).toISOString().slice(0, 10); -617| s.streak = (s.last === y) ? s.streak + 1 : 1; -618| s.last = today(); -619| store('streak', s); -620| } -621| tickSound(); -622| $('#menu-item').hidden = true; -623| $('#menu-actions').hidden = true; -624| paintStreak(); -625| }); -626| paintStreak(); -627| -628| // Restore menu time selection highlight on page load -629| if (currentMenuMins) { -630| $$('.menu-pick').forEach(function (b) { -631| b.classList.toggle('on', +b.dataset.min === currentMenuMins); -632| }); -633| } -634| -635| /* ---------- one thing ---------- */ -636| function nowRender() { -637| var nowSaved = store('now'); -638| var nextPrompt = $('#now-next'); -639| if (nextPrompt) nextPrompt.hidden = true; -640| -641| if (nowSaved && nowSaved.text) { -642| $('#now-text').textContent = nowSaved.text; -643| $('#now-form').hidden = true; -644| $('#now-view').hidden = false; -645| // Show source info if from breaker -646| var sourceEl = $('#now-source'); -647| if (sourceEl && nowSaved.fromBreaker) { -648| sourceEl.hidden = false; -649| var b = store(breakerKey); -650| if (b && typeof nowSaved.stepIndex === 'number') { -651| $('#now-step-num').textContent = nowSaved.stepIndex + 1; -652| $('#now-step-total').textContent = b.steps.length; -653| } -654| } else if (sourceEl) { -655| sourceEl.hidden = true; -656| } -657| } else { -658| $('#now-form').hidden = false; -659| $('#now-view').hidden = true; -660| } -661| } -662| -663| function nowShowNext(skipCelebration) { -664| var nextPrompt = $('#now-next'); -665| if (!nextPrompt) return; -666| var b = store(breakerKey); -667| if (!b) { -668| // No breaker data, just show "done" and reset form -669| nowRender(); -670| return; -671| } -672| var nextIdx = breakerFindNextStep(b); -673| nextPrompt.hidden = false; -674| $('#now-form').hidden = true; -675| $('#now-view').hidden = true; -676| -677| if (nextIdx >= 0) { -678| $('#now-next-step').hidden = false; -679| $('#now-all-done').hidden = true; -680| $('#now-next-text').textContent = b.steps[nextIdx].t; -681| // Wire up "Let's do it" -682| $('#now-next-go').onclick = function () { -683| store('now', { text: b.steps[nextIdx].t, fromBreaker: true, stepIndex: nextIdx }); -684| nowRender(); -685| }; -686| $('#now-next-skip').onclick = function () { -687| nextPrompt.hidden = true; -688| $('#now-form').hidden = false; -689| $('#now-view').hidden = true; -690| $('#now-input').value = ''; -691| $('#now-input').focus(); -692| }; -693| } else { -694| // All steps done -695| $('#now-next-step').hidden = true; -696| $('#now-all-done').hidden = false; -697| if (!skipCelebration) { -698| celebrateSound(); -699| confetti(); -700| } -701| } -702| } -703| -704| nowRender(); -705| -706| $('#now-form').addEventListener('submit', function (e) { -707| e.preventDefault(); -708| var t = $('#now-input').value.trim(); -709| if (!t) return; -710| store('now', { text: t }); -711| nowRender(); -712| }); -713| -714| $('#now-edit').addEventListener('click', function () { -715| $('#now-view').hidden = true; -716| $('#now-form').hidden = false; -717| $('#now-input').value = ''; -718| $('#now-input').focus(); -719| }); -720| -721| function handleNewDoneTasks(taskString) { -722| if (window.dbRecordTask && taskString) { -723| window.dbRecordTask(taskString).then(() => { if (window.renderDoneWall) window.renderDoneWall(); }).catch(() => {}); -724| } -725| } -726| -727| $('#now-done').addEventListener('click', function () { -728| var nowData = store('now'); -729| var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; -730| tickSound(); -731| // If from breaker, mark that step done -732| if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { -733| var b = store(breakerKey); -734| if (b && b.steps[nowData.stepIndex]) { -735| b.steps[nowData.stepIndex].done = true; -736| store(breakerKey, b); -737| breakerRender(); -738| } -739| } -740| handleNewDoneTasks(taskText); -741| localStorage.removeItem('myadhd.now'); -742| // Check if there's a next step from breaker -743| var b2 = store(breakerKey); -744| if (nowData && nowData.fromBreaker && b2) { -745| nowShowNext(); -746| } else { -747| nowRender(); -748| $('#now-input').focus(); -749| } -750| }); -751| -752| // "Start timer" button on One Thing -753| $('#now-timer').addEventListener('click', function () { -754| showTab('timer'); -755| // If timer isn't already running, pre-set 25 min -756| if (!timer.running) { -757| timer.total = timer.left = 25 * 60; -758| timer.phase = 'focus'; -759| $('#timer-start').textContent = 'start'; -760| timerPersist(); -761| timerPaint(); -762| } -763| }); -764| -765| // "Start something new" after all breaker steps done in now view -766| var nowFresh = $('#now-fresh'); -767| if (nowFresh) { -768| nowFresh.addEventListener('click', function () { -769| localStorage.removeItem('myadhd.now'); -770| $('#now-next').hidden = true; -771| showTab('breaker'); -772| localStorage.removeItem('myadhd.' + breakerKey); -773| $('#breaker-input').value = ''; -774| breakerRender(); -775| $('#breaker-input').focus(); -776| }); -777| } -778| -779| -780| /* ---------- inbox ---------- */ -781| var inboxItems = store('inbox') || []; -782| var $inboxForm = $('#inbox-form'), -783| $inboxInput = $('#inbox-input'), -784| $inboxOut = $('#inbox-out'), -785| $inboxCount = $('#inbox-count'), -786| $inboxList = $('#inbox-list'), -787| $inboxClear = $('#inbox-clear'); -788| -789| function saveInbox() { -790| store('inbox', inboxItems); -791| renderInbox(); -792| } -793| -794| function renderInbox() { -795| $inboxList.innerHTML = ''; -796| if (inboxItems.length === 0) { -797| $inboxOut.hidden = true; -798| return; -799| } -800| $inboxOut.hidden = false; -801| $inboxCount.textContent = inboxItems.length + ' item' + (inboxItems.length === 1 ? '' : 's'); -802| inboxItems.forEach(function (item, i) { -803| var li = document.createElement('li'); -804| li.className = 'step'; -805| -806| var textDiv = document.createElement('div'); -807| textDiv.className = 'step-text'; -808| textDiv.textContent = item; -809| -810| var editInput = document.createElement('input'); -811| editInput.type = 'text'; -812| editInput.className = 'step-edit-input sr-only'; -813| editInput.value = item; -814| -815| textDiv.addEventListener('click', function () { -816| textDiv.classList.add('sr-only'); -817| editInput.classList.remove('sr-only'); -818| editInput.focus(); -819| }); -820| -821| function commitEdit() { -822| var v = editInput.value.trim(); -823| if (!v) { inboxItems.splice(i, 1); } -824| else { inboxItems[i] = v; } -825| saveInbox(); -826| } -827| -828| editInput.addEventListener('blur', commitEdit); -829| editInput.addEventListener('keydown', function(e) { if (e.key === 'Enter') commitEdit(); }); -830| -831| var actionsDiv = document.createElement('div'); -832| actionsDiv.className = 'row gap'; -833| -834| var breakBtn = document.createElement('button'); -835| breakBtn.className = 'btn ghost small'; -836| breakBtn.textContent = 'break this down'; -837| breakBtn.addEventListener('click', function() { -838| inboxItems.splice(i, 1); -839| saveInbox(); -840| $('#breaker-input').value = item; -841| showTab('breaker'); -842| $('#breaker-form').dispatchEvent(new Event('submit')); -843| }); -844| -845| var delBtn = document.createElement('button'); -846| delBtn.className = 'btn ghost small'; -847| delBtn.textContent = 'Γ—'; -848| delBtn.addEventListener('click', function() { -849| inboxItems.splice(i, 1); -850| saveInbox(); -851| }); -852| -853| actionsDiv.appendChild(breakBtn); -854| actionsDiv.appendChild(delBtn); -855| -856| li.appendChild(textDiv); -857| li.appendChild(editInput); -858| li.appendChild(actionsDiv); -859| $inboxList.appendChild(li); -860| }); -861| } -862| -863| $inboxForm.addEventListener('submit', function (e) { -864| e.preventDefault(); -865| var val = $inboxInput.value.trim(); -866| if (!val) return; -867| inboxItems.unshift(val); -868| $inboxInput.value = ''; -869| saveInbox(); -870| }); -871| -872| $inboxClear.addEventListener('click', function () { -873| if (confirm('Clear entire inbox of dumps?')) { -874| inboxItems = []; -875| saveInbox(); -876| } -877| }); -878| -879| renderInbox(); -880| -881| /* ---------- morning sweep ---------- */ -882| var SWEEP_KEY = 'lastVisit'; -883| var SWEEP_THRESHOLD = 24 * 60 * 60 * 1000; // 24 hours -884| -885| function stampVisit() { store(SWEEP_KEY, Date.now()); } -886| -887| function sweepNeeded() { -888| var last = store(SWEEP_KEY); -889| if (!last) { stampVisit(); return false; } // first ever visit -890| return (Date.now() - last) > SWEEP_THRESHOLD; -891| } -892| -893| function openSweep(items, isManual) { -894| var modal = $('#sweep-modal'); -895| var list = $('#sweep-list'); -896| var keepAll = $('#sweep-keep-all'); -897| var relAll = $('#sweep-release-all'); -898| var doneBtn = $('#sweep-done'); -899| var closeBtn = $('#sweep-close'); -900| if (!modal || !list) return; -901| -902| list.innerHTML = ''; -903| var decisions = items.map(function () { return null; }); // null = undecided -904| -905| items.forEach(function (text, i) { -906| var li = document.createElement('li'); -907| -908| var span = document.createElement('span'); -909| span.className = 'sweep-text'; -910| span.textContent = text; -911| -912| var keep = document.createElement('button'); -913| keep.className = 'sweep-btn sweep-keep'; -914| keep.textContent = 'Keep'; -915| keep.type = 'button'; -916| -917| var release = document.createElement('button'); -918| release.className = 'sweep-btn sweep-release'; -919| release.textContent = 'Release 🌌'; -920| release.type = 'button'; -921| -922| keep.addEventListener('click', function () { -923| decisions[i] = 'keep'; -924| keep.classList.add('kept'); -925| keep.textContent = 'βœ“ Kept'; -926| release.style.display = 'none'; -927| }); -928| -929| release.addEventListener('click', function () { -930| decisions[i] = 'release'; -931| li.classList.add('sweep-dissolve'); -932| setTimeout(function () { li.classList.add('released'); }, 500); -933| }); -934| -935| li.appendChild(span); -936| li.appendChild(keep); -937| li.appendChild(release); -938| list.appendChild(li); -939| }); -940| -941| keepAll.onclick = function () { -942| items.forEach(function (_, i) { -943| if (decisions[i] !== 'release') { -944| decisions[i] = 'keep'; -945| var lis = list.children[i]; -946| if (lis) { -947| var kb = lis.querySelector('.sweep-keep'); -948| if (kb) { kb.classList.add('kept'); kb.textContent = 'βœ“ Kept'; } -949| var rb = lis.querySelector('.sweep-release'); -950| if (rb) rb.style.display = 'none'; -951| } -952| } -953| }); -954| }; -955| -956| relAll.onclick = function () { -957| items.forEach(function (_, i) { -958| if (decisions[i] !== 'keep') { -959| decisions[i] = 'release'; -960| var lis = list.children[i]; -961| if (lis) { -962| lis.classList.add('sweep-dissolve'); -963| setTimeout(function () { lis.classList.add('released'); }, 500); -964| } -965| } -966| }); -967| }; -968| -969| doneBtn.onclick = function () { -970| // Rebuild inbox: keep items that were kept or undecided -971| var kept = []; -972| items.forEach(function (text, i) { -973| if (decisions[i] !== 'release') kept.push(text); -974| }); -975| inboxItems = kept; -976| saveInbox(); -977| modal.hidden = true; -978| if (!isManual) stampVisit(); -979| }; -980| -981| if (closeBtn) { -982| closeBtn.onclick = function () { -983| modal.hidden = true; -984| } -985| } -986| -987| modal.hidden = false; -988| } -989| -990| // Auto-trigger on page load if stale -991| if (sweepNeeded() && inboxItems.length > 0) { -992| openSweep(inboxItems.slice(), false); -993| } else { -994| stampVisit(); -995| } -996| -997| // Manual "sweep stale" button in inbox -998| var $inboxSweep = $('#inbox-sweep'); -999| if ($inboxSweep) { -1000| $inboxSweep.addEventListener('click', function () { -1001| if (inboxItems.length === 0) return; -1002| openSweep(inboxItems.slice(), true); -1003| }); -1004| } -1005| -1006| /* ---------- keyboard shortcuts ---------- */ -1007| document.addEventListener('keydown', function (e) { -1008| // Don't trigger shortcuts when typing in an input or contenteditable -1009| var tag = e.target.tagName; -1010| if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target.contentEditable === 'true') return; -1011| -1012| // Number keys 1-4 switch tabs -1013| if (e.key === '1') { showTab('breaker'); e.preventDefault(); } -1014| if (e.key === '2') { showTab('timer'); e.preventDefault(); } -1015| if (e.key === '3') { showTab('dopamine'); e.preventDefault(); } -1016| if (e.key === '4') { showTab('now'); e.preventDefault(); } -1017| if (e.key === '5') { showTab('inbox'); e.preventDefault(); } -1018| -1019| // Space to start/pause timer when on timer tab -1020| if (e.key === ' ' && !$('#timer').hidden) { -1021| e.preventDefault(); -1022| $('#timer-start').click(); -1023| } -1024| -1025| // Escape to close completion overlay -1026| if (e.key === 'Escape') { -1027| var overlay = $('#timer-complete'); -1028| if (overlay && !overlay.hidden) { -1029| overlay.hidden = true; -1030| } -1031| } -1032| }); -1033| -1034| -1035| // ========================================== -1036| // AMBIENT BODY DOUBLING (Feature C) -1037| // ========================================== -1038| var pill = $('#ambient-pill'); -1039| var panel = $('#ambient-panel'); -1040| var countEl = $('#pill-count'); -1041| var feedEl = $('#ambient-feed'); -1042| var cheerBtn = $('#ambient-cheer-btn'); -1043| -1044| var fakeBaseCount = 1400; // baseline -1045| var feedEvents = [ -1046| "A fellow brain just finished a 15m focus round", -1047| "A fellow brain broke down an intimidating task", -1048| "A fellow brain took a mindful breath", -1049| "A fellow brain swept their inbox clean", -1050| "A fellow brain just started a timer", -1051| "A fellow brain released a stale task to the universe", -1052| "A fellow brain decided to focus on just One Thing" -1053| ]; -1054| -1055| function getCircadianOffset() { -1056| // Generate a smooth hour-based wave offset so the fake count feels organic -1057| var hour = new Date().getHours(); -1058| var minute = new Date().getMinutes(); -1059| var time = hour + (minute/60); -1060| // peak at noon and 8pm roughly -1061| return Math.floor((Math.sin(time * 0.5) * 300) + (Math.cos(time * 0.8) * 150)); -1062| } -1063| -1064| function updateCount() { -1065| if (!countEl) return; -1066| var base = fakeBaseCount + getCircadianOffset(); -1067| // small jitter -1068| var jitter = Math.floor(Math.random() * 15) - 7; -1069| var finalCount = base + jitter; -1070| if (finalCount < 200) finalCount = 200; // min floor -1071| countEl.textContent = finalCount.toLocaleString(); -1072| } -1073| -1074| function addFeedItem(text) { -1075| if (!feedEl) return; -1076| var li = document.createElement('li'); -1077| li.className = 'feed-item'; -1078| li.textContent = text; -1079| feedEl.prepend(li); -1080| // keep only top 4 -1081| if (feedEl.children.length > 4) { -1082| feedEl.removeChild(feedEl.lastChild); -1083| } -1084| } -1085| -1086| function feedLoop() { -1087| // random feed inject every 8-25 seconds -1088| var delay = 8000 + Math.random() * 17000; -1089| setTimeout(function() { -1090| var evt = feedEvents[Math.floor(Math.random() * feedEvents.length)]; -1091| addFeedItem(evt); -1092| updateCount(); -1093| feedLoop(); -1094| }, delay); -1095| } -1096| -1097| if (pill) { -1098| updateCount(); -1099| addFeedItem("You joined the focus room"); -1100| feedLoop(); -1101| -1102| // click to toggle panel -1103| pill.addEventListener('click', function(e) { -1104| e.stopPropagation(); -1105| var expanded = pill.getAttribute('aria-expanded') === 'true'; -1106| pill.setAttribute('aria-expanded', !expanded); -1107| panel.hidden = expanded; -1108| }); -1109| -1110| // click outside to close -1111| document.addEventListener('click', function(e) { -1112| if (!panel.hidden && !panel.contains(e.target) && !pill.contains(e.target)) { -1113| panel.hidden = true; -1114| pill.setAttribute('aria-expanded', 'false'); -1115| } -1116| }); -1117| -1118| pill.addEventListener('keydown', function(e) { -1119| if (e.key === 'Enter' || e.key === ' ') { -1120| e.preventDefault(); -1121| pill.click(); -1122| } -1123| }); -1124| } -1125| -1126| if (cheerBtn) { -1127| cheerBtn.addEventListener('click', function() { -1128| addFeedItem("You sent a quiet cheer πŸŽ‰"); -1129| cheerBtn.textContent = "Sent!"; -1130| cheerBtn.style.pointerEvents = "none"; -1131| setTimeout(function() { -1132| cheerBtn.textContent = "Send a gentle nod πŸŽ‰"; -1133| cheerBtn.style.pointerEvents = "auto"; -1134| }, 3000); -1135| confetti(); -1136| }); -1137| cheerBtn.addEventListener('keydown', function(e) { -1138| if (e.key === 'Enter' || e.key === ' ') { -1139| e.preventDefault(); -1140| cheerBtn.click(); -1141| } -1142| }); -1143| } -1144| -1145|})(); -1146| -1147| -1148|// ========================================== -1149|// UNSTUCK PROTOCOL (Task Paralysis Emergency) -1150|// ========================================== -1151|(function initUnstuck() { -1152| const btnUnstuck = $('#btn-unstuck'); -1153| const modal = $('#unstuck-modal'); -1154| const closeBtn = $('#unstuck-close'); -1155| const p1 = $('#unstuck-phase-1'); -1156| const p2 = $('#unstuck-phase-2'); -1157| const p3 = $('#unstuck-phase-3'); -1158| const timerDisplay = $('#unstuck-timer'); -1159| const startTimerBtn = $('#unstuck-start-3'); -1160| const finishBtn = $('#unstuck-finish'); -1161| -1162| let breathInterval; -1163| let unstuckInterval; -1164| -1165| if (!btnUnstuck || !modal) return; -1166| -1167| function resetUnstuckModal() { -1168| p1.hidden = false; -1169| p2.hidden = true; -1170| p3.hidden = true; -1171| startTimerBtn.hidden = false; -1172| finishBtn.hidden = true; -1173| timerDisplay.textContent = "03:00"; -1174| $('#unstuck-micro-input').value = ""; -1175| clearInterval(unstuckInterval); -1176| clearInterval(breathInterval); -1177| } -1178| -1179| function syncBreathText() { -1180| const text = $('#breathe-text'); -1181| if(!text) return; -1182| clearInterval(breathInterval); -1183| let cycle = 0; -1184| -1185| // Physiological Sigh timing matcher (approximate for the 8s CSS animation) -1186| // 0-2s: Inhale -1187| // 2-3.5s: 2nd Inhale -1188| // 3.5-4s: Hold -1189| // 4-8s: Long slow exhale -1190| -1191| const updateText = () => { -1192| cycle = (cycle + 1) % 8; -1193| if (cycle < 2) text.textContent = "Inhale..."; -1194| else if (cycle < 3) text.textContent = "Sip more air..."; -1195| else if (cycle < 4) text.textContent = "Hold..."; -1196| else text.textContent = "Slooow Exhale..."; -1197| }; -1198| -1199| updateText(); // immediate run -1200| breathInterval = setInterval(() => { -1201| if (modal.hidden || p1.hidden) { -1202| clearInterval(breathInterval); -1203| return; -1204| } -1205| updateText(); -1206| }, 1000); -1207| } -1208| -1209| btnUnstuck.addEventListener('click', () => { -1210| resetUnstuckModal(); -1211| modal.hidden = false; -1212| syncBreathText(); -1213| }); -1214| -1215| closeBtn.addEventListener('click', () => { -1216| modal.hidden = true; -1217| clearInterval(unstuckInterval); -1218| clearInterval(breathInterval); -1219| }); -1220| -1221| // Proceed from phase 1 to 2 -1222| $('#unstuck-next-1').addEventListener('click', () => { -1223| p1.hidden = true; -1224| p2.hidden = false; -1225| }); -1226| -1227| // Proceed from phase 2 to 3 -1228| $('#unstuck-next-2').addEventListener('click', () => { -1229| p2.hidden = true; -1230| p3.hidden = false; -1231| }); -1232| -1233| // Phase 3 Timer -1234| startTimerBtn.addEventListener('click', () => { -1235| startTimerBtn.hidden = true; -1236| let timeLeft = 180; // 3 minutes -1237| -1238| unstuckInterval = setInterval(() => { -1239| timeLeft--; -1240| const m = Math.floor(timeLeft / 60).toString().padStart(2, '0'); -1241| const s = (timeLeft % 60).toString().padStart(2, '0'); -1242| timerDisplay.textContent = `${m}:${s}`; -1243| -1244| if (timeLeft <= 0) { -1245| clearInterval(unstuckInterval); -1246| timerDisplay.textContent = "Done!"; -1247| finishBtn.hidden = false; -1248| -1249| // Play success tone if soundscapes/audio is available globally -1250| try { -1251| if (window.AudioContext && !window.audioCtx) { -1252| window.audioCtx = new window.AudioContext(); -1253| } -1254| if (window.audioCtx) { -1255| const osc = audioCtx.createOscillator(); -1256| const gain = audioCtx.createGain(); -1257| osc.connect(gain); -1258| gain.connect(audioCtx.destination); -1259| osc.frequency.setValueAtTime(440, audioCtx.currentTime); // A4 -1260| osc.frequency.exponentialRampToValueAtTime(880, audioCtx.currentTime + 0.1); // Jump to A5 -1261| gain.gain.setValueAtTime(0, audioCtx.currentTime); -1262| gain.gain.linearRampToValueAtTime(0.5, audioCtx.currentTime + 0.05); -1263| gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 1); -1264| osc.start(audioCtx.currentTime); -1265| osc.stop(audioCtx.currentTime + 1); -1266| } -1267| } catch(e) { console.log(e); } -1268| } -1269| }, 1000); -1270| }); -1271| -1272| finishBtn.addEventListener('click', () => { -1273| modal.hidden = true; -1274| // Switch to Focus Timer using the main app's tab switching logic -1275| const timerTabBtn = document.getElementById('tab-timer'); -1276| if(timerTabBtn) timerTabBtn.click(); -1277| }); -1278| -1279|})(); \ No newline at end of file + if (window.ai && window.ai.languageModel) { + try { + const caps = await window.ai.languageModel.capabilities(); + if (caps.available !== 'no') { + const session = await window.ai.languageModel.create(); + const result = await session.prompt(prompt); + return result.split('\n').filter(s => s.trim().length > 0); + } + } catch (e) { + console.warn("window.ai failed, falling back", e); + } + } + + // Tier 2: BYOK (Bring Your Own Key) Fallback + const key = store('byok_key'); + if (!key) { + throw new Error("NO_AI_AVAILABLE"); // Let UI prompt for key or let Tier 3 try + } + const resp = await fetch('https://api.openai.com/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer ' + key + }, + body: JSON.stringify({ + model: 'gpt-4o-mini', + messages: [{ role: 'user', content: prompt }] + }) + }); + if (!resp.ok) throw new Error("API_ERROR"); + const data = await resp.json(); + return data.choices[0].message.content.split('\n').filter(s => s.trim().length > 0); + }; + + $('#timer-reset').addEventListener('click', timerReset); + + $$('.preset').forEach(function (p) { + p.addEventListener('click', function () { + timerStop(); + timer.total = timer.left = (+p.dataset.min) * 60; + timer.phase = p.classList.contains('break') ? 'break' : 'focus'; + $('#timer-start').textContent = 'start'; + timerPersist(); timerPaint(); + }); + }); + + $$('.grounding-chime').forEach(function(btn) { + btn.addEventListener('click', function() { + $$('.grounding-chime').forEach(function(b) { b.classList.remove('active'); }); + btn.classList.add('active'); + if (window.setGroundingInterval) window.setGroundingInterval(); + }); + }); + + // Timer completion overlay actions + $('#timer-take-break').addEventListener('click', function () { + $('#timer-complete').hidden = true; + timer.phase = 'break'; + timer.total = timer.left = 5 * 60; + $('#timer-start').textContent = 'start'; + $('#timer-note').textContent = 'Focus round done. Stand up. Drink water. Actually take the break.'; + timerPersist(); timerPaint(); + }); + + $('#timer-mark-done').addEventListener('click', function () { + $('#timer-complete').hidden = true; + // Mark the current one-thing step as done in the breaker + var nowData = store('now'); + var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; + if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { + var b = store(breakerKey); + if (b && b.steps[nowData.stepIndex]) { + b.steps[nowData.stepIndex].done = true; + store(breakerKey, b); + breakerRender(); + } + } + handleNewDoneTasks(taskText); + // Reset timer so it's fresh for the next step + timerReset(); + // Clear one-thing and show next step prompt + localStorage.removeItem('myadhd.now'); + showTab('now'); + nowShowNext(true); + }); + + timerPaint(); + + /* ---------- dopamine menu ---------- */ + var MENU = { + 5: [ + 'Put on one song and tidy one single surface.', + 'Drink a big glass of water like it is a magic potion.', + 'Step outside for two minutes and name five sounds you hear.', + 'Stretch your arms and neck slowly β€” like a cat waking up.', + 'Text someone one true compliment. No context, no apology.', + 'Draw the nearest object as badly as you possibly can.', + 'Open the window and take ten slow breaths.', + 'Rearrange exactly three things on your desk.', + 'Do ten squats or one ridiculous dance move.', + 'Write down three things you can see right now that you like.' + ], + 15: [ + 'Walk once around the block β€” phone stays home or in pocket.', + 'Build the fanciest snack possible from what you already have.', + 'Write a short thank-you note to your future self.', + 'Doodle your current mood as a weather report.', + 'Do a ten-minute follow-along stretch video.', + 'Clean one drawer. One. Set a timer so it cannot grow.', + 'Read five pages of any book you own.', + 'Water (or rescue) one plant.', + 'Have a shower, but treat it like a whole concert.', + 'Learn three words in a language you do not speak.' + ], + 30: [ + 'Cook something new with a video recipe playing.', + 'Go for a 25-minute walk with one podcast episode.', + 'Call someone you like. With your voice. Wild, we know.', + 'Build something with zero rules: LEGO, blanket fort, collage.', + 'Brain-dump everything in your head onto paper for ten minutes.', + 'Deep-clean the one object that quietly bothers you most.', + 'Follow a 30-minute workout video at whatever intensity you like.', + 'Walk or bike to a spot nearby you have never actually been.', + 'Pack a small comfort bag for your worst brain days.', + 'Ten minutes journaling, ten minutes stretching, ten minutes staring.' + ], + 60: [ + 'Long walk or bike ride somewhere with trees.', + 'One-hour hobby sprint β€” make something terrible and be proud.', + 'Bake something from scratch. Eat evidence.', + 'One-room tidy: music loud, timer rules, no mercy.', + 'Wandering trip (thrift store, library) with a $10 budget.', + 'Digital reset: close twenty tabs, clear the inbox as far as you can.', + 'Follow a full workout or yoga class at home.', + 'Meal-prep one lunch so tomorrow-you says thanks.', + 'Take a notebook to a cafΓ© or library and people-watch or sketch.', + 'Watch a documentary about something absurd and become an expert.' + ] + }; + var lastPick = null; + var currentMenuMins = store('menu_mins') || null; + + function menuPick(mins) { + currentMenuMins = mins; + store('menu_mins', mins); + // Highlight the selected time button + $$('.menu-pick').forEach(function (b) { + b.classList.toggle('on', +b.dataset.min === mins); + }); + var pool = MENU[mins].filter(function (x) { return x !== lastPick; }); + var item = pool[Math.floor(Math.random() * pool.length)]; + lastPick = item; + $('#menu-text').textContent = item; + $('#menu-item').hidden = false; + $('#menu-actions').hidden = false; + } + + $$('.menu-pick').forEach(function (b) { + b.addEventListener('click', function () { menuPick(+b.dataset.min); }); + }); + + $('#menu-reroll').addEventListener('click', function () { + // Use tracked mins instead of .on class + menuPick(currentMenuMins || 5); + }); + + function paintStreak() { + var s = store('streak'); + $('#menu-streak').innerHTML = s && s.streak ? + 'Streak: ' + s.streak + ' day' + (s.streak > 1 ? 's' : '') + ' of healthy dopamine. ' + + (s.last === today() ? 'Today is already logged.' : '') : ''; + } + $('#menu-done').addEventListener('click', function () { + var s = store('streak') || { last: '', streak: 0 }; + if (s.last !== today()) { + var y = new Date(Date.now() - 86400000).toISOString().slice(0, 10); + s.streak = (s.last === y) ? s.streak + 1 : 1; + s.last = today(); + store('streak', s); + } + tickSound(); + $('#menu-item').hidden = true; + $('#menu-actions').hidden = true; + paintStreak(); + }); + paintStreak(); + + // Restore menu time selection highlight on page load + if (currentMenuMins) { + $$('.menu-pick').forEach(function (b) { + b.classList.toggle('on', +b.dataset.min === currentMenuMins); + }); + } + + /* ---------- one thing ---------- */ + function nowRender() { + var nowSaved = store('now'); + var nextPrompt = $('#now-next'); + if (nextPrompt) nextPrompt.hidden = true; + + if (nowSaved && nowSaved.text) { + $('#now-text').textContent = nowSaved.text; + $('#now-form').hidden = true; + $('#now-view').hidden = false; + // Show source info if from breaker + var sourceEl = $('#now-source'); + if (sourceEl && nowSaved.fromBreaker) { + sourceEl.hidden = false; + var b = store(breakerKey); + if (b && typeof nowSaved.stepIndex === 'number') { + $('#now-step-num').textContent = nowSaved.stepIndex + 1; + $('#now-step-total').textContent = b.steps.length; + } + } else if (sourceEl) { + sourceEl.hidden = true; + } + } else { + $('#now-form').hidden = false; + $('#now-view').hidden = true; + } + } + + function nowShowNext(skipCelebration) { + var nextPrompt = $('#now-next'); + if (!nextPrompt) return; + var b = store(breakerKey); + if (!b) { + // No breaker data, just show "done" and reset form + nowRender(); + return; + } + var nextIdx = breakerFindNextStep(b); + nextPrompt.hidden = false; + $('#now-form').hidden = true; + $('#now-view').hidden = true; + + if (nextIdx >= 0) { + $('#now-next-step').hidden = false; + $('#now-all-done').hidden = true; + $('#now-next-text').textContent = b.steps[nextIdx].t; + // Wire up "Let's do it" + $('#now-next-go').onclick = function () { + store('now', { text: b.steps[nextIdx].t, fromBreaker: true, stepIndex: nextIdx }); + nowRender(); + }; + $('#now-next-skip').onclick = function () { + nextPrompt.hidden = true; + $('#now-form').hidden = false; + $('#now-view').hidden = true; + $('#now-input').value = ''; + $('#now-input').focus(); + }; + } else { + // All steps done + $('#now-next-step').hidden = true; + $('#now-all-done').hidden = false; + if (!skipCelebration) { + celebrateSound(); + confetti(); + } + } + } + + nowRender(); + + $('#now-form').addEventListener('submit', function (e) { + e.preventDefault(); + var t = $('#now-input').value.trim(); + if (!t) return; + store('now', { text: t }); + nowRender(); + }); + + $('#now-edit').addEventListener('click', function () { + $('#now-view').hidden = true; + $('#now-form').hidden = false; + $('#now-input').value = ''; + $('#now-input').focus(); + }); + + function handleNewDoneTasks(taskString) { + if (window.dbRecordTask && taskString) { + window.dbRecordTask(taskString).then(() => { if (window.renderDoneWall) window.renderDoneWall(); }).catch(() => {}); + } + } + + $('#now-done').addEventListener('click', function () { + var nowData = store('now'); + var taskText = $('#now-text').textContent || (nowData && nowData.text) || ''; + tickSound(); + // If from breaker, mark that step done + if (nowData && nowData.fromBreaker && typeof nowData.stepIndex === 'number') { + var b = store(breakerKey); + if (b && b.steps[nowData.stepIndex]) { + b.steps[nowData.stepIndex].done = true; + store(breakerKey, b); + breakerRender(); + } + } + handleNewDoneTasks(taskText); + localStorage.removeItem('myadhd.now'); + // Check if there's a next step from breaker + var b2 = store(breakerKey); + if (nowData && nowData.fromBreaker && b2) { + nowShowNext(); + } else { + nowRender(); + $('#now-input').focus(); + } + }); + + // "Start timer" button on One Thing + $('#now-timer').addEventListener('click', function () { + showTab('timer'); + // If timer isn't already running, pre-set 25 min + if (!timer.running) { + timer.total = timer.left = 25 * 60; + timer.phase = 'focus'; + $('#timer-start').textContent = 'start'; + timerPersist(); + timerPaint(); + } + }); + + // "Start something new" after all breaker steps done in now view + var nowFresh = $('#now-fresh'); + if (nowFresh) { + nowFresh.addEventListener('click', function () { + localStorage.removeItem('myadhd.now'); + $('#now-next').hidden = true; + showTab('breaker'); + localStorage.removeItem('myadhd.' + breakerKey); + $('#breaker-input').value = ''; + breakerRender(); + $('#breaker-input').focus(); + }); + } + + + /* ---------- inbox ---------- */ + var inboxItems = store('inbox') || []; + var $inboxForm = $('#inbox-form'), + $inboxInput = $('#inbox-input'), + $inboxOut = $('#inbox-out'), + $inboxCount = $('#inbox-count'), + $inboxList = $('#inbox-list'), + $inboxClear = $('#inbox-clear'); + + function saveInbox() { + store('inbox', inboxItems); + renderInbox(); + } + + function renderInbox() { + $inboxList.innerHTML = ''; + if (inboxItems.length === 0) { + $inboxOut.hidden = true; + return; + } + $inboxOut.hidden = false; + $inboxCount.textContent = inboxItems.length + ' item' + (inboxItems.length === 1 ? '' : 's'); + inboxItems.forEach(function (item, i) { + var li = document.createElement('li'); + li.className = 'step'; + + var textDiv = document.createElement('div'); + textDiv.className = 'step-text'; + textDiv.textContent = item; + + var editInput = document.createElement('input'); + editInput.type = 'text'; + editInput.className = 'step-edit-input sr-only'; + editInput.value = item; + + textDiv.addEventListener('click', function () { + textDiv.classList.add('sr-only'); + editInput.classList.remove('sr-only'); + editInput.focus(); + }); + + function commitEdit() { + var v = editInput.value.trim(); + if (!v) { inboxItems.splice(i, 1); } + else { inboxItems[i] = v; } + saveInbox(); + } + + editInput.addEventListener('blur', commitEdit); + editInput.addEventListener('keydown', function(e) { if (e.key === 'Enter') commitEdit(); }); + + var actionsDiv = document.createElement('div'); + actionsDiv.className = 'row gap'; + + var breakBtn = document.createElement('button'); + breakBtn.className = 'btn ghost small'; + breakBtn.textContent = 'break this down'; + breakBtn.addEventListener('click', function() { + inboxItems.splice(i, 1); + saveInbox(); + $('#breaker-input').value = item; + showTab('breaker'); + $('#breaker-form').dispatchEvent(new Event('submit')); + }); + + var delBtn = document.createElement('button'); + delBtn.className = 'btn ghost small'; + delBtn.textContent = 'Γ—'; + delBtn.addEventListener('click', function() { + inboxItems.splice(i, 1); + saveInbox(); + }); + + actionsDiv.appendChild(breakBtn); + actionsDiv.appendChild(delBtn); + + li.appendChild(textDiv); + li.appendChild(editInput); + li.appendChild(actionsDiv); + $inboxList.appendChild(li); + }); + } + + $inboxForm.addEventListener('submit', function (e) { + e.preventDefault(); + var val = $inboxInput.value.trim(); + if (!val) return; + inboxItems.unshift(val); + $inboxInput.value = ''; + saveInbox(); + }); + + $inboxClear.addEventListener('click', function () { + if (confirm('Clear entire inbox of dumps?')) { + inboxItems = []; + saveInbox(); + } + }); + + renderInbox(); + + /* ---------- morning sweep ---------- */ + var SWEEP_KEY = 'lastVisit'; + var SWEEP_THRESHOLD = 24 * 60 * 60 * 1000; // 24 hours + + function stampVisit() { store(SWEEP_KEY, Date.now()); } + + function sweepNeeded() { + var last = store(SWEEP_KEY); + if (!last) { stampVisit(); return false; } // first ever visit + return (Date.now() - last) > SWEEP_THRESHOLD; + } + + function openSweep(items, isManual) { + var modal = $('#sweep-modal'); + var list = $('#sweep-list'); + var keepAll = $('#sweep-keep-all'); + var relAll = $('#sweep-release-all'); + var doneBtn = $('#sweep-done'); + var closeBtn = $('#sweep-close'); + if (!modal || !list) return; + + list.innerHTML = ''; + var decisions = items.map(function () { return null; }); // null = undecided + + items.forEach(function (text, i) { + var li = document.createElement('li'); + + var span = document.createElement('span'); + span.className = 'sweep-text'; + span.textContent = text; + + var keep = document.createElement('button'); + keep.className = 'sweep-btn sweep-keep'; + keep.textContent = 'Keep'; + keep.type = 'button'; + + var release = document.createElement('button'); + release.className = 'sweep-btn sweep-release'; + release.textContent = 'Release 🌌'; + release.type = 'button'; + + keep.addEventListener('click', function () { + decisions[i] = 'keep'; + keep.classList.add('kept'); + keep.textContent = 'βœ“ Kept'; + release.style.display = 'none'; + }); + + release.addEventListener('click', function () { + decisions[i] = 'release'; + li.classList.add('sweep-dissolve'); + setTimeout(function () { li.classList.add('released'); }, 500); + }); + + li.appendChild(span); + li.appendChild(keep); + li.appendChild(release); + list.appendChild(li); + }); + + keepAll.onclick = function () { + items.forEach(function (_, i) { + if (decisions[i] !== 'release') { + decisions[i] = 'keep'; + var lis = list.children[i]; + if (lis) { + var kb = lis.querySelector('.sweep-keep'); + if (kb) { kb.classList.add('kept'); kb.textContent = 'βœ“ Kept'; } + var rb = lis.querySelector('.sweep-release'); + if (rb) rb.style.display = 'none'; + } + } + }); + }; + + relAll.onclick = function () { + items.forEach(function (_, i) { + if (decisions[i] !== 'keep') { + decisions[i] = 'release'; + var lis = list.children[i]; + if (lis) { + lis.classList.add('sweep-dissolve'); + setTimeout(function () { lis.classList.add('released'); }, 500); + } + } + }); + }; + + doneBtn.onclick = function () { + // Rebuild inbox: keep items that were kept or undecided + var kept = []; + items.forEach(function (text, i) { + if (decisions[i] !== 'release') kept.push(text); + }); + inboxItems = kept; + saveInbox(); + modal.hidden = true; + if (!isManual) stampVisit(); + }; + + if (closeBtn) { + closeBtn.onclick = function () { + modal.hidden = true; + } + } + + modal.hidden = false; + } + + // Auto-trigger on page load if stale + if (sweepNeeded() && inboxItems.length > 0) { + openSweep(inboxItems.slice(), false); + } else { + stampVisit(); + } + + // Manual "sweep stale" button in inbox + var $inboxSweep = $('#inbox-sweep'); + if ($inboxSweep) { + $inboxSweep.addEventListener('click', function () { + if (inboxItems.length === 0) return; + openSweep(inboxItems.slice(), true); + }); + } + + /* ---------- keyboard shortcuts ---------- */ + document.addEventListener('keydown', function (e) { + // Don't trigger shortcuts when typing in an input or contenteditable + var tag = e.target.tagName; + if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target.contentEditable === 'true') return; + + // Number keys 1-4 switch tabs + if (e.key === '1') { showTab('breaker'); e.preventDefault(); } + if (e.key === '2') { showTab('timer'); e.preventDefault(); } + if (e.key === '3') { showTab('dopamine'); e.preventDefault(); } + if (e.key === '4') { showTab('now'); e.preventDefault(); } + if (e.key === '5') { showTab('inbox'); e.preventDefault(); } + + // Space to start/pause timer when on timer tab + if (e.key === ' ' && !$('#timer').hidden) { + e.preventDefault(); + $('#timer-start').click(); + } + + // Escape to close completion overlay + if (e.key === 'Escape') { + var overlay = $('#timer-complete'); + if (overlay && !overlay.hidden) { + overlay.hidden = true; + } + } + }); + + + // ========================================== + // AMBIENT BODY DOUBLING (Feature C) + // ========================================== + var pill = $('#ambient-pill'); + var panel = $('#ambient-panel'); + var countEl = $('#pill-count'); + var feedEl = $('#ambient-feed'); + var cheerBtn = $('#ambient-cheer-btn'); + + var fakeBaseCount = 1400; // baseline + var feedEvents = [ + "A fellow brain just finished a 15m focus round", + "A fellow brain broke down an intimidating task", + "A fellow brain took a mindful breath", + "A fellow brain swept their inbox clean", + "A fellow brain just started a timer", + "A fellow brain released a stale task to the universe", + "A fellow brain decided to focus on just One Thing" + ]; + + function getCircadianOffset() { + // Generate a smooth hour-based wave offset so the fake count feels organic + var hour = new Date().getHours(); + var minute = new Date().getMinutes(); + var time = hour + (minute/60); + // peak at noon and 8pm roughly + return Math.floor((Math.sin(time * 0.5) * 300) + (Math.cos(time * 0.8) * 150)); + } + + function updateCount() { + if (!countEl) return; + var base = fakeBaseCount + getCircadianOffset(); + // small jitter + var jitter = Math.floor(Math.random() * 15) - 7; + var finalCount = base + jitter; + if (finalCount < 200) finalCount = 200; // min floor + countEl.textContent = finalCount.toLocaleString(); + } + + function addFeedItem(text) { + if (!feedEl) return; + var li = document.createElement('li'); + li.className = 'feed-item'; + li.textContent = text; + feedEl.prepend(li); + // keep only top 4 + if (feedEl.children.length > 4) { + feedEl.removeChild(feedEl.lastChild); + } + } + + function feedLoop() { + // random feed inject every 8-25 seconds + var delay = 8000 + Math.random() * 17000; + setTimeout(function() { + var evt = feedEvents[Math.floor(Math.random() * feedEvents.length)]; + addFeedItem(evt); + updateCount(); + feedLoop(); + }, delay); + } + + if (pill) { + updateCount(); + addFeedItem("You joined the focus room"); + feedLoop(); + + // click to toggle panel + pill.addEventListener('click', function(e) { + e.stopPropagation(); + var expanded = pill.getAttribute('aria-expanded') === 'true'; + pill.setAttribute('aria-expanded', !expanded); + panel.hidden = expanded; + }); + + // click outside to close + document.addEventListener('click', function(e) { + if (!panel.hidden && !panel.contains(e.target) && !pill.contains(e.target)) { + panel.hidden = true; + pill.setAttribute('aria-expanded', 'false'); + } + }); + + pill.addEventListener('keydown', function(e) { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + pill.click(); + } + }); + } + + if (cheerBtn) { + cheerBtn.addEventListener('click', function() { + addFeedItem("You sent a quiet cheer πŸŽ‰"); + cheerBtn.textContent = "Sent!"; + cheerBtn.style.pointerEvents = "none"; + setTimeout(function() { + cheerBtn.textContent = "Send a gentle nod πŸŽ‰"; + cheerBtn.style.pointerEvents = "auto"; + }, 3000); + confetti(); + }); + cheerBtn.addEventListener('keydown', function(e) { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + cheerBtn.click(); + } + }); + } + +})(); + + +// ========================================== +// UNSTUCK PROTOCOL (Task Paralysis Emergency) +// ========================================== +(function initUnstuck() { + const btnUnstuck = $('#btn-unstuck'); + const modal = $('#unstuck-modal'); + const closeBtn = $('#unstuck-close'); + const p1 = $('#unstuck-phase-1'); + const p2 = $('#unstuck-phase-2'); + const p3 = $('#unstuck-phase-3'); + const timerDisplay = $('#unstuck-timer'); + const startTimerBtn = $('#unstuck-start-3'); + const finishBtn = $('#unstuck-finish'); + + let breathInterval; + let unstuckInterval; + + if (!btnUnstuck || !modal) return; + + function resetUnstuckModal() { + p1.hidden = false; + p2.hidden = true; + p3.hidden = true; + startTimerBtn.hidden = false; + finishBtn.hidden = true; + timerDisplay.textContent = "03:00"; + $('#unstuck-micro-input').value = ""; + clearInterval(unstuckInterval); + clearInterval(breathInterval); + } + + function syncBreathText() { + const text = $('#breathe-text'); + if(!text) return; + clearInterval(breathInterval); + let cycle = 0; + + // Physiological Sigh timing matcher (approximate for the 8s CSS animation) + // 0-2s: Inhale + // 2-3.5s: 2nd Inhale + // 3.5-4s: Hold + // 4-8s: Long slow exhale + + const updateText = () => { + cycle = (cycle + 1) % 8; + if (cycle < 2) text.textContent = "Inhale..."; + else if (cycle < 3) text.textContent = "Sip more air..."; + else if (cycle < 4) text.textContent = "Hold..."; + else text.textContent = "Slooow Exhale..."; + }; + + updateText(); // immediate run + breathInterval = setInterval(() => { + if (modal.hidden || p1.hidden) { + clearInterval(breathInterval); + return; + } + updateText(); + }, 1000); + } + + btnUnstuck.addEventListener('click', () => { + resetUnstuckModal(); + modal.hidden = false; + syncBreathText(); + }); + + closeBtn.addEventListener('click', () => { + modal.hidden = true; + clearInterval(unstuckInterval); + clearInterval(breathInterval); + }); + + // Proceed from phase 1 to 2 + $('#unstuck-next-1').addEventListener('click', () => { + p1.hidden = true; + p2.hidden = false; + }); + + // Proceed from phase 2 to 3 + $('#unstuck-next-2').addEventListener('click', () => { + p2.hidden = true; + p3.hidden = false; + }); + + // Phase 3 Timer + startTimerBtn.addEventListener('click', () => { + startTimerBtn.hidden = true; + let timeLeft = 180; // 3 minutes + + unstuckInterval = setInterval(() => { + timeLeft--; + const m = Math.floor(timeLeft / 60).toString().padStart(2, '0'); + const s = (timeLeft % 60).toString().padStart(2, '0'); + timerDisplay.textContent = `${m}:${s}`; + + if (timeLeft <= 0) { + clearInterval(unstuckInterval); + timerDisplay.textContent = "Done!"; + finishBtn.hidden = false; + + // Play success tone if soundscapes/audio is available globally + try { + if (window.AudioContext && !window.audioCtx) { + window.audioCtx = new window.AudioContext(); + } + if (window.audioCtx) { + const osc = audioCtx.createOscillator(); + const gain = audioCtx.createGain(); + osc.connect(gain); + gain.connect(audioCtx.destination); + osc.frequency.setValueAtTime(440, audioCtx.currentTime); // A4 + osc.frequency.exponentialRampToValueAtTime(880, audioCtx.currentTime + 0.1); // Jump to A5 + gain.gain.setValueAtTime(0, audioCtx.currentTime); + gain.gain.linearRampToValueAtTime(0.5, audioCtx.currentTime + 0.05); + gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 1); + osc.start(audioCtx.currentTime); + osc.stop(audioCtx.currentTime + 1); + } + } catch(e) { console.log(e); } + } + }, 1000); + }); + + finishBtn.addEventListener('click', () => { + modal.hidden = true; + // Switch to Focus Timer using the main app's tab switching logic + const timerTabBtn = document.getElementById('tab-timer'); + if(timerTabBtn) timerTabBtn.click(); + }); + +})(); \ No newline at end of file