-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
668 lines (556 loc) · 21.8 KB
/
script.js
File metadata and controls
668 lines (556 loc) · 21.8 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// Version 0.0.75
// Configuration
function getTimerDuration() {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('testMode') === 'true') {
return 30;
}
const isLocalhost = window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1';
return isLocalhost
? 10
: 60 * 5;
}
function getCaptureWindowDuration() {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('testMode') === 'true') {
return 3;
}
return 10;
}
const TIMER_DURATION_SECONDS = getTimerDuration();
const CAPTURE_WINDOW_SECONDS = getCaptureWindowDuration();
class CounterApp {
constructor() {
this.version = '0.0.75';
this.isStarted = false;
this.counts = {
1: 0, 2: 0, 3: 0, 4: 0,
6: 0, 7: 0, 8: 0, 9: 0
};
this.actionHistory = [];
this.questionAnswers = {
daysPracticed: null,
didNotCollect: false,
ecbiScore: null,
didNotAdminister: false
};
this.finishPage = new URLSearchParams(window.location.search).get('finishPage') || 'finish_evaluation_self.html';
this.isSkipCoding = false;
this.isTeachingSession = null;
this.timer = {
startTime: null,
duration: TIMER_DURATION_SECONDS,
remaining: TIMER_DURATION_SECONDS,
isActive: false,
isExpired: false,
isCaptureWindow: false,
captureRemaining: 0,
captureIntervalId: null,
intervalId: null
};
this.defaultLabels = {
1: { code: 'TA', description: 'Neutral Talk' },
2: { code: 'BD', description: 'Behavior Description' },
3: { code: 'RF', description: 'Reflection' },
4: { code: 'LP', description: 'Labeled Praise' },
6: { code: 'UP', description: 'Unlabeled Praise' },
7: { code: 'QU', description: 'Question' },
8: { code: 'CM', description: 'Command' },
9: { code: 'NTA', description: 'Negative Talk' }
};
this.labels = this.parseCustomLabels() || this.defaultLabels;
// Debug: Show if custom labels were loaded
if (this.labels !== this.defaultLabels) {
console.log('Custom labels loaded successfully!');
}
this.init();
}
init() {
this.bindEvents();
this.bindKeyboardEvents();
this.updateTimerDisplay();
this.updateButtonState();
this.updateButtonLabels();
this.preventPullToRefresh();
this.setViewportHeight();
}
parseCustomLabels() {
const urlParams = new URLSearchParams(window.location.search);
console.log('URL search params:', window.location.search);
const customLabels = {};
let hasCustomLabels = false;
// Map btn1-btn8 to data-id values (1,2,3,4,6,7,8,9)
const buttonMapping = {
'btn1': 1, 'btn2': 2, 'btn3': 3, 'btn4': 4,
'btn5': 6, 'btn6': 7, 'btn7': 8, 'btn8': 9
};
for (const [param, dataId] of Object.entries(buttonMapping)) {
const value = urlParams.get(param);
console.log(`Checking ${param} (dataId ${dataId}):`, value);
if (value && value.includes(':')) {
const [code, ...descriptionParts] = value.split(':');
const description = descriptionParts.join(':').trim();
if (code && description) {
customLabels[dataId] = {
code: code.trim(),
description: description
};
hasCustomLabels = true;
console.log(`Added custom label for ${dataId}:`, customLabels[dataId]);
}
}
}
// Fill in missing labels with defaults
if (hasCustomLabels) {
for (const dataId of [1, 2, 3, 4, 6, 7, 8, 9]) {
if (!customLabels[dataId]) {
customLabels[dataId] = this.defaultLabels[dataId];
}
}
console.log('Final custom labels:', customLabels);
return customLabels;
}
console.log('No custom labels found, using defaults');
return null;
}
updateButtonLabels() {
const buttons = document.querySelectorAll('.count-button');
buttons.forEach(button => {
const dataId = parseInt(button.dataset.id);
const labelData = this.labels[dataId];
if (labelData) {
const labelElement = button.querySelector('.label');
const descriptionElement = button.querySelector('.description');
if (labelElement) {
labelElement.textContent = labelData.code;
}
if (descriptionElement) {
descriptionElement.textContent = labelData.description;
}
}
});
}
setViewportHeight() {
// Set the app container to the actual viewport height
const setHeight = () => {
const app = document.querySelector('.app');
if (app) {
app.style.height = `${window.innerHeight}px`;
}
};
// Set on load
setHeight();
// Update on resize or orientation change
window.addEventListener('resize', setHeight);
window.addEventListener('orientationchange', setHeight);
}
preventPullToRefresh() {
// Prevent all default touch behaviors on the document
document.body.addEventListener('touchmove', (e) => {
// Prevent the default behavior for all touch moves
// This will stop pull-to-refresh but also scrolling
e.preventDefault();
}, { passive: false });
}
bindEvents() {
const countButtons = document.querySelectorAll('.count-button');
countButtons.forEach(button => {
button.addEventListener('click', (e) => {
const id = parseInt(button.dataset.id);
this.incrementCount(id);
});
});
document.getElementById('config-btn').addEventListener('click', () => {
this.showConfigModal();
});
document.getElementById('undo-direct-btn').addEventListener('click', () => {
this.undoLastAction();
});
document.getElementById('return-btn').addEventListener('click', () => {
this.hideConfigModal();
});
document.getElementById('cancel-btn').addEventListener('click', () => {
this.cancelEvaluation();
});
document.getElementById('finish-btn').addEventListener('click', () => {
this.finishEvaluation();
});
document.getElementById('skip-coding-btn').addEventListener('click', () => {
this.startSkipCodingFlow();
});
}
incrementCount(id) {
if (this.timer.isExpired) return;
if (!this.timer.isActive && !this.timer.isCaptureWindow && this.isStarted) {
this.startTimer();
}
if (!this.isStarted) return;
this.counts[id]++;
this.actionHistory.push(id);
this.updateDisplay(id);
this.hapticFeedback();
}
updateDisplay(id) {
const button = document.querySelector(`[data-id="${id}"]`);
const countElement = button.querySelector('.count');
countElement.textContent = this.counts[id];
}
showConfigModal() {
document.getElementById('version-info').textContent = `Version ${this.version}`;
document.getElementById('config-modal').classList.add('show');
}
hideConfigModal() {
document.getElementById('config-modal').classList.remove('show');
}
undoLastAction() {
if (!this.isStarted) {
// Start button clicked
this.isStarted = true;
this.startTimer();
this.updateButtonState();
this.hapticFeedback(50);
return;
}
if (this.actionHistory.length === 0) return;
const lastAction = this.actionHistory.pop();
this.counts[lastAction]--;
this.updateDisplay(lastAction);
this.hideConfigModal();
this.hapticFeedback(50);
}
updateButtonState() {
const button = document.getElementById('undo-direct-btn');
const buttonText = document.getElementById('button-text');
const undoIcon = document.getElementById('undo-icon');
const playIcon = document.getElementById('play-icon');
if (!this.isStarted) {
// Start state
button.classList.add('start-state');
buttonText.textContent = 'Start';
undoIcon.style.display = 'none';
playIcon.style.display = 'block';
} else {
// Undo state
button.classList.remove('start-state');
buttonText.textContent = 'Undo';
undoIcon.style.display = 'block';
playIcon.style.display = 'none';
}
}
cancelEvaluation() {
this.counts = {
1: 0, 2: 0, 3: 0, 4: 0,
6: 0, 7: 0, 8: 0, 9: 0
};
this.actionHistory = [];
this.isStarted = false;
// Reset timer
this.resetTimer();
Object.keys(this.counts).forEach(id => {
this.updateDisplay(parseInt(id));
});
this.updateButtonState();
this.hideConfigModal();
}
finishEvaluation() {
this.redirectToFinishPage(false);
}
hapticFeedback(duration = 30) {
if ('vibrate' in navigator) {
navigator.vibrate(duration);
}
}
bindKeyboardEvents() {
document.addEventListener('keydown', (e) => {
// Only handle keyboard input on main screen (no modals open)
const modalsOpen = document.querySelector('.modal.show');
if (modalsOpen) return;
const keyMap = {
// Numpad mapping
'7': '1', // TA
'8': '2', // BD
'9': '3', // RF
'4': '4', // LP
'5': 'undo', // Undo
'6': '6', // UP
'1': '7', // QU
'2': '8', // CM
'3': '9', // NTA
// QWE mapping
'q': '1', 'Q': '1', // TA
'w': '2', 'W': '2', // BD
'e': '3', 'E': '3', // RF
'a': '4', 'A': '4', // LP
's': 'undo', 'S': 'undo', // Undo
'd': '6', 'D': '6', // UP
'z': '7', 'Z': '7', // QU
'x': '8', 'X': '8', // CM
'c': '9', 'C': '9' // NTA
};
const key = e.key;
if (keyMap[key]) {
e.preventDefault();
if (key === '5' || key === 's' || key === 'S') {
// Trigger start/undo
this.undoLastAction();
this.highlightButton('undo-direct-btn');
} else {
// Trigger count increment
const dataId = keyMap[key];
this.incrementCount(parseInt(dataId));
this.highlightButton(`[data-id="${dataId}"]`);
}
}
});
}
highlightButton(selector) {
const button = document.querySelector(selector);
if (button) {
button.style.transform = 'scale(0.95)';
button.style.transition = 'transform 0.1s ease';
setTimeout(() => {
button.style.transform = '';
button.style.transition = '';
}, 150);
}
}
startTimer() {
this.timer.startTime = Date.now();
this.timer.isActive = true;
this.timer.intervalId = setInterval(() => {
const elapsed = Math.floor((Date.now() - this.timer.startTime) / 1000);
this.timer.remaining = Math.max(0, this.timer.duration - elapsed);
this.updateTimerDisplay();
if (this.timer.remaining <= 0) {
this.expireTimer();
}
}, 1000);
}
resetTimer() {
if (this.timer.intervalId) {
clearInterval(this.timer.intervalId);
}
if (this.timer.captureIntervalId) {
clearInterval(this.timer.captureIntervalId);
}
this.timer.startTime = null;
this.timer.remaining = this.timer.duration;
this.timer.isActive = false;
this.timer.isExpired = false;
this.timer.isCaptureWindow = false;
this.timer.captureRemaining = 0;
this.timer.captureIntervalId = null;
this.timer.intervalId = null;
document.body.classList.remove('capture-window');
this.updateTimerDisplay();
this.enableCountingButtons();
}
expireTimer() {
clearInterval(this.timer.intervalId);
this.timer.isActive = false;
this.playEndOfSessionAlert();
this.startCaptureWindow();
}
startCaptureWindow() {
this.timer.isCaptureWindow = true;
this.timer.captureRemaining = CAPTURE_WINDOW_SECONDS;
document.body.classList.add('capture-window');
this.updateTimerDisplay();
this.timer.captureIntervalId = setInterval(() => {
this.timer.captureRemaining--;
this.updateTimerDisplay();
if (this.timer.captureRemaining <= 0) {
this.endCaptureWindow();
}
}, 1000);
}
endCaptureWindow() {
clearInterval(this.timer.captureIntervalId);
this.timer.isCaptureWindow = false;
this.timer.isExpired = true;
document.body.classList.remove('capture-window');
this.updateTimerDisplay();
this.redirectToFinishPage(false);
}
playEndOfSessionAlert() {
this.playChime();
this.playAlertVibration();
}
playChime() {
try {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const now = audioContext.currentTime;
const playNote = (frequency, startTime, duration) => {
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.type = 'sine';
oscillator.frequency.value = frequency;
gain.gain.setValueAtTime(0.3, startTime);
gain.gain.exponentialRampToValueAtTime(0.01, startTime + duration);
oscillator.start(startTime);
oscillator.stop(startTime + duration);
};
playNote(523.25, now, 0.3);
playNote(659.25, now + 0.15, 0.3);
playNote(783.99, now + 0.3, 0.5);
} catch (e) {
// Web Audio API not available — visual + vibration still work
}
}
playAlertVibration() {
if ('vibrate' in navigator) {
navigator.vibrate([200, 100, 200, 100, 200]);
}
}
updateTimerDisplay() {
const timerElement = document.getElementById('timer-display');
if (this.timer.isCaptureWindow) {
timerElement.textContent = `:${this.timer.captureRemaining.toString().padStart(2, '0')}`;
timerElement.classList.add('capture-window');
timerElement.classList.remove('expired');
return;
}
const minutes = Math.floor(this.timer.remaining / 60);
const seconds = this.timer.remaining % 60;
timerElement.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
timerElement.classList.remove('capture-window');
if (this.timer.isExpired) {
timerElement.classList.add('expired');
} else {
timerElement.classList.remove('expired');
}
}
disableCountingButtons() {
const countButtons = document.querySelectorAll('.count-button');
countButtons.forEach(button => {
button.style.opacity = '0.5';
button.style.pointerEvents = 'none';
});
}
enableCountingButtons() {
const countButtons = document.querySelectorAll('.count-button');
countButtons.forEach(button => {
button.style.opacity = '';
button.style.pointerEvents = '';
});
}
startSkipCodingFlow() {
this.redirectToFinishPage(true);
}
redirectToFinishPage(skipCoding) {
const params = new URLSearchParams();
// Add all counts
Object.keys(this.counts).forEach(id => {
params.append(`c${id}`, this.counts[id]);
});
// Add skip coding flag
params.append('skip', skipCoding);
// Pass through custom button labels if they exist
const currentParams = new URLSearchParams(window.location.search);
const buttonMapping = {
'btn1': 1, 'btn2': 2, 'btn3': 3, 'btn4': 4,
'btn5': 6, 'btn6': 7, 'btn7': 8, 'btn8': 9
};
for (const [param, dataId] of Object.entries(buttonMapping)) {
const value = currentParams.get(param);
if (value) {
params.append(param, value);
}
}
// Pass through testMode if present
if (currentParams.get('testMode') === 'true') {
params.append('testMode', 'true');
}
// Redirect to finish evaluation page
window.location.href = `${this.finishPage}?${params.toString()}`;
}
generateSessionData() {
const timestamp = new Date().toLocaleString();
const sessionDuration = this.timer.duration - this.timer.remaining;
const minutes = Math.floor(sessionDuration / 60);
const seconds = sessionDuration % 60;
const durationString = `${minutes}:${seconds.toString().padStart(2, '0')}`;
// Output just the behavioral counts, one per line
let data = '';
const countKeys = Object.keys(this.counts);
// Add all the behavioral counts in order
countKeys.forEach((id, index) => {
data += this.counts[id];
// Add newline after all counts
if (index < countKeys.length - 1) {
data += '\n';
}
});
// Add days practiced (number or blank line)
data += '\n';
if (this.questionAnswers.daysPracticed !== null && !this.questionAnswers.didNotCollect) {
data += this.questionAnswers.daysPracticed;
}
// Add ECBI/WACB score (number or blank line)
data += '\n';
if (this.questionAnswers.ecbiScore !== null && !this.questionAnswers.didNotAdminister) {
data += this.questionAnswers.ecbiScore;
}
return data;
}
showToast(message, isError = false) {
const toast = document.getElementById('toast');
if (!toast) return;
// Set message and style
toast.textContent = message;
toast.className = 'toast';
if (isError) {
toast.classList.add('error');
}
// Show the toast
setTimeout(() => toast.classList.add('show'), 10);
// Hide after 3 seconds
setTimeout(() => {
toast.classList.remove('show');
}, 3000);
}
async copySessionDataToClipboard() {
console.log('copySessionDataToClipboard called');
const sessionData = this.generateSessionData();
console.log('Session data generated:', sessionData);
try {
// Check if clipboard API is available
if (!navigator.clipboard) {
throw new Error('Clipboard API not available');
}
await navigator.clipboard.writeText(sessionData);
console.log('Successfully copied to clipboard');
this.showToast('Session data copied to clipboard!');
} catch (err) {
console.error('Clipboard copy failed:', err);
// Fallback: try older execCommand method
try {
const textArea = document.createElement('textarea');
textArea.value = sessionData;
textArea.style.position = 'fixed';
textArea.style.opacity = '0';
document.body.appendChild(textArea);
textArea.select();
const success = document.execCommand('copy');
document.body.removeChild(textArea);
if (success) {
console.log('Successfully copied using execCommand fallback');
this.showToast('Session data copied to clipboard!');
} else {
throw new Error('execCommand copy failed');
}
} catch (fallbackErr) {
console.error('Fallback copy also failed:', fallbackErr);
this.showToast('Failed to copy to clipboard', true);
// As a last resort, show the data in an alert
alert('Clipboard copy failed. Here is your session data:\n\n' + sessionData);
}
}
}
}
document.addEventListener('DOMContentLoaded', () => {
new CounterApp();
});