myadhd/site/static/app.js
djg 242c855004
All checks were successful
Build and Deploy / deploy (push) Successful in 12s
Merge branch 'copy-pass-soundscapes'
2026-09-23 04:37:16 +00:00

928 lines
31 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* 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 });
}
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);
// 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();
}
$('#timer-start').addEventListener('click', function () {
if (timer.running) { timerStop(); $('#timer-start').textContent = 'resume'; timerPaint(); return; }
timer.running = true;
$('#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();
}
$('#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();
});
});
// 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');
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();
}
}
// 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: <span class="streak-num">' + s.streak + ' day' + (s.streak > 1 ? 's' : '') + '</span> 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();
});
$('#now-done').addEventListener('click', function () {
var nowData = store('now');
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();
}
}
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();
/* ---------- 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;
}
}
});
})();
// ==========================================
// 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();
});
})();