-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
342 lines (286 loc) · 10.4 KB
/
script.js
File metadata and controls
342 lines (286 loc) · 10.4 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// DOM Elements
const app = document.getElementById('app');
const setupScreen = document.getElementById('setup-screen');
const timerScreen = document.getElementById('timer-screen');
const timerBackground = document.getElementById('timer-background');
const intervalsContainer = document.getElementById('intervals-container');
const numSetsInput = document.getElementById('num-sets');
const btnStart = document.getElementById('btn-start-timer');
// Timer Display Elements
const statusText = document.getElementById('interval-status');
const timeDisplay = document.getElementById('time-display');
const currentIntervalSpan = document.getElementById('current-interval');
const totalIntervalsSpan = document.getElementById('total-intervals');
const btnPause = document.getElementById('btn-pause');
const pausedControls = document.getElementById('paused-controls');
const btnResume = document.getElementById('btn-resume');
const btnReset = document.getElementById('btn-reset');
const btnStop = document.getElementById('btn-stop');
// State
let state = {
sets: 1,
intervals: [], // Array of objects { work: 30, rest: 30 }
currentIntervalIndex: 0,
isWorkPhase: true, // true = work, false = rest
timeRemaining: 0,
isRunning: false,
intervalId: null,
audioCtx: null
};
// --- Initialization & Setup Logic ---
function init() {
loadState();
renderRows();
// Event Listeners
numSetsInput.addEventListener('input', handleSetsChange);
intervalsContainer.addEventListener('input', handleIntervalInputChange);
btnStart.addEventListener('click', startWorkout);
btnPause.addEventListener('click', pauseTimer);
btnResume.addEventListener('click', resumeTimer);
btnReset.addEventListener('click', resetCurrentInterval);
btnStop.addEventListener('click', stopWorkout);
}
function loadState() {
const saved = localStorage.getItem('timerSetup');
if (saved) {
const parsed = JSON.parse(saved);
state.sets = parsed.sets || 1;
state.intervals = parsed.intervals || [{work: 30, rest: 30}];
// Ensure intervals array matches sets count
if (state.intervals.length < state.sets) {
// Fill missing with last known
const last = state.intervals[state.intervals.length - 1] || {work: 30, rest: 30};
while(state.intervals.length < state.sets) {
state.intervals.push({...last});
}
}
} else {
// Default
state.sets = 1;
state.intervals = [{work: 30, rest: 30}];
}
numSetsInput.value = state.sets;
}
function saveState() {
const dataToSave = {
sets: state.sets,
intervals: state.intervals
};
localStorage.setItem('timerSetup', JSON.stringify(dataToSave));
}
function handleSetsChange(e) {
const newSets = parseInt(e.target.value) || 1;
if (newSets < 1) return;
const oldSets = state.sets;
state.sets = newSets;
// Adjust intervals array
if (newSets > oldSets) {
// Add rows
const template = state.intervals.length > 0 ? state.intervals[0] : {work: 30, rest: 30};
for (let i = oldSets; i < newSets; i++) {
state.intervals.push({...template});
}
} else {
// Remove rows
state.intervals = state.intervals.slice(0, newSets);
}
renderRows();
saveState();
}
function handleIntervalInputChange(e) {
if (!e.target.matches('input')) return;
const row = e.target.closest('.input-row');
const index = parseInt(row.dataset.index);
const type = e.target.dataset.type; // 'work' or 'rest'
const value = parseInt(e.target.value) || 0;
// Update state
state.intervals[index][type] = value;
// "When someone fills in the first row, all rows duplicate immediately"
// Interpretation: If editing row 1 (index 0), update all other rows IF they matched row 0 previously?
// Or just strictly overwrite everything? User said: "duplicate immediately, but can be over written."
// Simple approach: If Row 0 changes, update ALL rows. This is aggressive but fits the description.
if (index === 0) {
for (let i = 1; i < state.intervals.length; i++) {
state.intervals[i][type] = value;
// Update inputs in DOM without full re-render to keep focus
const rowEl = document.querySelector(`.input-row[data-index="${i}"]`);
if (rowEl) {
const input = rowEl.querySelector(`input[data-type="${type}"]`);
if (input) input.value = value;
}
}
}
saveState();
}
function renderRows() {
intervalsContainer.innerHTML = '';
state.intervals.forEach((interval, index) => {
const row = document.createElement('div');
row.className = 'input-row';
row.dataset.index = index;
row.innerHTML = `
<div>${index + 1}</div>
<div><input type="number" value="${interval.work}" min="0" data-type="work"></div>
<div><input type="number" value="${interval.rest}" min="0" data-type="rest"></div>
`;
intervalsContainer.appendChild(row);
});
}
// --- Audio System ---
function initAudio() {
if (!state.audioCtx) {
const AudioContext = window.AudioContext || window.webkitAudioContext;
state.audioCtx = new AudioContext();
}
if (state.audioCtx.state === 'suspended') {
state.audioCtx.resume();
}
}
function playBeep(frequency = 800, duration = 0.1, type = 'sine') {
if (!state.audioCtx) return;
const osc = state.audioCtx.createOscillator();
const gain = state.audioCtx.createGain();
osc.type = type;
osc.frequency.setValueAtTime(frequency, state.audioCtx.currentTime);
gain.gain.setValueAtTime(0.5, state.audioCtx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, state.audioCtx.currentTime + duration);
osc.connect(gain);
gain.connect(state.audioCtx.destination);
osc.start();
osc.stop(state.audioCtx.currentTime + duration);
}
// --- Timer Logic ---
function startWorkout() {
initAudio();
// Prepare timer state
state.currentIntervalIndex = 0;
state.isWorkPhase = true;
state.intervals = state.intervals; // Already updated in state
// Load first interval
setupInterval();
// Switch Screens
setupScreen.classList.add('hidden');
timerScreen.classList.remove('hidden');
startTimerLoop();
}
function setupInterval() {
const current = state.intervals[state.currentIntervalIndex];
if (state.isWorkPhase) {
state.timeRemaining = current.work;
statusText.innerText = 'WORK';
timerBackground.className = 'fullscreen-bg mode-work';
} else {
state.timeRemaining = current.rest;
statusText.innerText = 'REST';
timerBackground.className = 'fullscreen-bg mode-rest';
}
currentIntervalSpan.innerText = state.currentIntervalIndex + 1;
totalIntervalsSpan.innerText = state.sets;
updateTimeDisplay();
}
function updateTimeDisplay() {
// Format mm:ss or just seconds? User asked for "countown of minutes / seconds in large print"
const mins = Math.floor(state.timeRemaining / 60);
const secs = state.timeRemaining % 60;
const timeStr = `${mins}:${secs.toString().padStart(2, '0')}`;
timeDisplay.innerText = timeStr;
}
function startTimerLoop() {
if (state.isRunning) return;
state.isRunning = true;
// Hide paused controls, show pause button
btnPause.classList.remove('hidden');
pausedControls.classList.add('hidden');
// Use setInterval for 1 second ticks
state.intervalId = setInterval(tick, 1000);
}
function tick() {
if (state.timeRemaining > 0) {
// Check for beeps (5, 4, 3, 2, 1)
if (state.timeRemaining <= 5) {
playBeep(1000, 0.2); // High pitch for countdown
}
state.timeRemaining--;
updateTimeDisplay();
} else {
// Time is up
handlePhaseComplete();
}
}
function handlePhaseComplete() {
playBeep(600, 0.8, 'square'); // Longer, different tone for complete
if (state.isWorkPhase) {
// Work finished
const currentRest = state.intervals[state.currentIntervalIndex].rest;
if (currentRest > 0) {
// Switch to Rest
state.isWorkPhase = false;
setupInterval();
} else {
// No rest, go straight to next work if exists
nextInterval();
}
} else {
// Rest finished
nextInterval();
}
}
function nextInterval() {
state.currentIntervalIndex++;
if (state.currentIntervalIndex < state.sets) {
state.isWorkPhase = true;
setupInterval();
} else {
// Workout Complete
finishWorkout();
}
}
function finishWorkout() {
clearInterval(state.intervalId);
state.isRunning = false;
statusText.innerText = 'DONE';
timerBackground.className = 'fullscreen-bg'; // Neutral
timeDisplay.innerText = "DONE";
playBeep(1200, 0.1);
setTimeout(() => playBeep(1200, 0.1), 150);
setTimeout(() => playBeep(1200, 0.1), 300);
// Show reset options
btnPause.classList.add('hidden');
pausedControls.classList.remove('hidden');
btnResume.classList.add('hidden'); // Cannot resume finished workout
btnReset.innerText = "RESTART WORKOUT";
btnReset.onclick = startWorkout;
}
function pauseTimer() {
clearInterval(state.intervalId);
state.isRunning = false;
btnPause.classList.add('hidden');
pausedControls.classList.remove('hidden');
btnResume.classList.remove('hidden');
btnReset.innerText = "RESET INTERVAL";
btnReset.onclick = resetCurrentInterval;
}
function resumeTimer() {
startTimerLoop();
}
function resetCurrentInterval() {
clearInterval(state.intervalId);
state.isRunning = false;
// Reload current interval start
setupInterval();
// Auto-resume? Or wait?
// "if the pause is hit, there is a reset, and start button" -> Start implies Resume or Start Over.
// I implemented Resume. Reset logic here just resets time.
// Let's assume user wants to click Start/Resume to go again.
btnResume.classList.remove('hidden');
// We are still in paused state visually
updateTimeDisplay();
}
function stopWorkout() {
clearInterval(state.intervalId);
state.isRunning = false;
timerScreen.classList.add('hidden');
setupScreen.classList.remove('hidden');
}
// Initialize
init();