-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
309 lines (280 loc) · 10.2 KB
/
Copy pathapp.js
File metadata and controls
309 lines (280 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/* Breathwork Timer — vanilla JS, no dependencies.
* Phases: inhale -> holdIn -> exhale -> holdOut (holds of 0s are skipped).
* Liquid Breathwork · https://www.liquidbreathwork.com
*/
(function () {
"use strict";
var PRESETS = [
{ id: "box", name: "Box", sub: "4-4-4-4", pattern: [4, 4, 4, 4],
desc: "Equal inhale, hold, exhale, hold. Steadies the nervous system and sharpens focus." },
{ id: "478", name: "4-7-8", sub: "Relaxing", pattern: [4, 7, 8, 0],
desc: "A long, slow exhale that leans into the rest state. A favorite before sleep." },
{ id: "coherent", name: "Coherent", sub: "5-5", pattern: [5, 0, 5, 0],
desc: "About six breaths per minute, the pace linked with heart-rate variability." },
{ id: "calming", name: "Calming", sub: "4-6", pattern: [4, 0, 6, 0],
desc: "A gentle extended exhale to downshift, with no breath-holding." },
{ id: "custom", name: "Custom", sub: "Your timing", pattern: null,
desc: "Set your own inhale, hold, exhale, and hold below." }
];
var PHASE_LABELS = ["Inhale", "Hold", "Exhale", "Hold"];
// ---- State ----
var current = PRESETS[0];
var running = false; // actively ticking
var startedSession = false; // session has begun (may be paused)
var rafId = null;
var phaseIndex = 0;
var phaseStart = 0;
var phaseDuration = 0;
var cycleCount = 0;
var sessionElapsedMs = 0; // accumulated active time
var segmentStart = 0; // start of current active segment
var sessionLimitMs = 300000;
var lastWholeSecond = -1;
// ---- Elements ----
var $ = function (id) { return document.getElementById(id); };
var orb = $("orb");
var phaseLabel = $("phaseLabel");
var phaseCount = $("phaseCount");
var cycleMeta = $("cycleMeta");
var timeMeta = $("timeMeta");
var startBtn = $("startBtn");
var resetBtn = $("resetBtn");
var presetGrid = $("presetGrid");
var presetDesc = $("presetDesc");
var customFields = $("customFields");
var soundToggle = $("soundToggle");
var vibrateToggle = $("vibrateToggle");
var durationSelect = $("durationSelect");
var prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// ---- Audio (soft sine chime, created on demand) ----
var audioCtx = null;
function chime() {
if (!soundToggle.checked) return;
try {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var osc = audioCtx.createOscillator();
var gain = audioCtx.createGain();
osc.type = "sine";
osc.frequency.value = 432;
gain.gain.setValueAtTime(0.0001, audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.15, audioCtx.currentTime + 0.04);
gain.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + 0.6);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start();
osc.stop(audioCtx.currentTime + 0.62);
} catch (e) { /* audio not available, ignore */ }
}
function buzz() {
if (vibrateToggle.checked && navigator.vibrate) navigator.vibrate(30);
}
// ---- Settings persistence ----
function saveSettings() {
try {
localStorage.setItem("bwt", JSON.stringify({
preset: current.id,
custom: getCustomPattern(),
sound: soundToggle.checked,
vibrate: vibrateToggle.checked,
limit: durationSelect.value
}));
} catch (e) {}
}
function loadSettings() {
try {
var s = JSON.parse(localStorage.getItem("bwt") || "{}");
if (s.sound) soundToggle.checked = true;
if (s.vibrate) vibrateToggle.checked = true;
if (s.limit != null) durationSelect.value = s.limit;
if (s.custom && s.custom.length === 4) {
$("inhale").value = s.custom[0];
$("holdIn").value = s.custom[1];
$("exhale").value = s.custom[2];
$("holdOut").value = s.custom[3];
}
if (s.preset) {
var found = PRESETS.filter(function (p) { return p.id === s.preset; })[0];
if (found) current = found;
}
} catch (e) {}
}
function getCustomPattern() {
var clamp = function (v, lo, hi) { v = parseInt(v, 10); if (isNaN(v)) v = lo; return Math.max(lo, Math.min(hi, v)); };
return [
clamp($("inhale").value, 1, 20),
clamp($("holdIn").value, 0, 20),
clamp($("exhale").value, 1, 20),
clamp($("holdOut").value, 0, 20)
];
}
function activePattern() {
return current.id === "custom" ? getCustomPattern() : current.pattern;
}
// ---- Build preset buttons ----
PRESETS.forEach(function (p) {
var b = document.createElement("button");
b.type = "button";
b.className = "preset";
b.setAttribute("role", "radio");
b.setAttribute("aria-checked", p.id === current.id ? "true" : "false");
b.dataset.id = p.id;
b.innerHTML = "<span>" + p.name + "</span><small>" + p.sub + "</small>";
b.addEventListener("click", function () { selectPreset(p.id); });
presetGrid.appendChild(b);
});
function selectPreset(id) {
current = PRESETS.filter(function (p) { return p.id === id; })[0] || PRESETS[0];
Array.prototype.forEach.call(presetGrid.children, function (btn) {
btn.setAttribute("aria-checked", btn.dataset.id === id ? "true" : "false");
});
presetDesc.textContent = current.desc;
customFields.hidden = current.id !== "custom";
saveSettings();
if (startedSession) reset();
}
// ---- Phase engine ----
function phaseDurations() {
return activePattern().map(function (s) { return s * 1000; });
}
function nextActivePhase(from) {
var durs = phaseDurations();
for (var i = 0; i < 4; i++) {
var idx = (from + i) % 4;
if (durs[idx] > 0) return idx;
}
return 0;
}
function enterPhase(idx) {
var durs = phaseDurations();
phaseIndex = idx;
phaseDuration = durs[idx];
phaseStart = performance.now();
lastWholeSecond = -1;
if (idx === 0) cycleCount++;
phaseLabel.textContent = PHASE_LABELS[idx];
animateOrb(idx, phaseDuration);
chime();
buzz();
}
function animateOrb(idx, durationMs) {
var sec = durationMs / 1000;
if (prefersReduced) { orb.style.transition = "none"; }
else { orb.style.transition = "transform " + sec + "s ease-in-out, box-shadow " + sec + "s ease-in-out"; }
// Inhale grows, exhale shrinks, holds keep size.
if (idx === 0) { orb.style.transform = "scale(1)"; orb.classList.add("is-bright"); }
else if (idx === 2) { orb.style.transform = "scale(0.55)"; orb.classList.remove("is-bright"); }
// holds (idx 1, 3): leave transform as-is
}
function tick(now) {
if (!running) return;
var elapsed = now - phaseStart;
var remainMs = Math.max(0, phaseDuration - elapsed);
var remainSec = Math.ceil(remainMs / 1000);
if (remainSec !== lastWholeSecond) {
phaseCount.textContent = remainSec;
lastWholeSecond = remainSec;
}
var sessionTotal = sessionElapsedMs + (now - segmentStart);
timeMeta.textContent = fmt(sessionTotal);
cycleMeta.textContent = "Cycle " + cycleCount;
if (sessionLimitMs > 0 && sessionTotal >= sessionLimitMs) {
finish();
return;
}
if (elapsed >= phaseDuration) {
enterPhase(nextActivePhase(phaseIndex + 1));
}
rafId = requestAnimationFrame(tick);
}
function fmt(ms) {
var total = Math.floor(ms / 1000);
var m = Math.floor(total / 60);
var s = total % 60;
return (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s;
}
// ---- Controls: start / pause / resume / reset ----
function start() {
running = true;
startedSession = true;
cycleCount = 0;
sessionElapsedMs = 0;
segmentStart = performance.now();
sessionLimitMs = parseInt(durationSelect.value, 10) * 1000;
startBtn.textContent = "Pause";
resetBtn.disabled = false;
if (audioCtx && audioCtx.state === "suspended") audioCtx.resume();
enterPhase(nextActivePhase(0));
rafId = requestAnimationFrame(tick);
}
function pause() {
if (!running) return;
running = false;
sessionElapsedMs += performance.now() - segmentStart;
if (rafId) cancelAnimationFrame(rafId);
startBtn.textContent = "Resume";
// freeze orb at its current rendered size
var computed = getComputedStyle(orb).transform;
orb.style.transition = "none";
if (computed && computed !== "none") orb.style.transform = computed;
}
function resume() {
running = true;
segmentStart = performance.now();
startBtn.textContent = "Pause";
if (audioCtx && audioCtx.state === "suspended") audioCtx.resume();
enterPhase(phaseIndex); // restart current phase from full count
rafId = requestAnimationFrame(tick);
}
function reset() {
running = false;
startedSession = false;
if (rafId) cancelAnimationFrame(rafId);
cycleCount = 0;
phaseIndex = 0;
sessionElapsedMs = 0;
startBtn.textContent = "Start";
resetBtn.disabled = true;
phaseLabel.textContent = "Ready";
phaseCount.textContent = "—";
cycleMeta.textContent = "Cycle 0";
timeMeta.textContent = "00:00";
orb.style.transition = "transform 0.6s ease";
orb.style.transform = "scale(0.55)";
orb.classList.remove("is-bright");
}
function finish() {
running = false;
if (rafId) cancelAnimationFrame(rafId);
startBtn.textContent = "Start";
startedSession = false;
resetBtn.disabled = false;
phaseLabel.textContent = "Complete";
phaseCount.textContent = "✓";
timeMeta.textContent = fmt(sessionLimitMs);
chime();
}
startBtn.addEventListener("click", function () {
if (running) pause();
else if (startedSession) resume();
else start();
});
resetBtn.addEventListener("click", reset);
[soundToggle, vibrateToggle, durationSelect].forEach(function (el) {
el.addEventListener("change", saveSettings);
});
["inhale", "holdIn", "exhale", "holdOut"].forEach(function (id) {
$(id).addEventListener("change", saveSettings);
});
// spacebar = start/pause
document.addEventListener("keydown", function (e) {
var t = e.target.tagName;
if (e.code === "Space" && t !== "INPUT" && t !== "SELECT" && t !== "BUTTON") {
e.preventDefault();
startBtn.click();
}
});
// ---- Init ----
loadSettings();
selectPreset(current.id);
reset();
})();