-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
432 lines (403 loc) · 14.4 KB
/
Copy pathscript.js
File metadata and controls
432 lines (403 loc) · 14.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
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
/**************** Global Variables & Configuration ****************/
let currentPageIndex = 0;
let pages = [];
let totalPages = 0;
// Read configuration from URL parameters (with defaults)
const urlParams = new URLSearchParams(window.location.search);
const config = {
identifier: urlParams.get('identifier') || 'defaultIdentifier',
// Test duration in seconds (default 5)
lengthOfTest: parseInt(urlParams.get('length_of_test')) || 5,
// Optional description string; fallback text if not provided
intendedUseDescription: urlParams.get('intendedUseDescription') || 'Welcome to the Custom Active Task Demo. Please follow the instructions below.'
};
// Global result object – the final JSON to be sent.
let result = {
rightHand: {},
image: null, // base64 image string
audio: null, // base64 audio string
location: { latitude: null, longitude: null }
};
// Test state variables
let testRunning = false;
let testStartTime = 0;
let tapCount = 0;
let samples = []; // Array to store tap samples
let accEvents = []; // Array to store accelerometer events
let testInterval = null;
let currentTestHand = "RIGHT";
// Variables for extra media capture
let videoStream = null;
let mediaRecorder = null;
let audioChunks = [];
/**************** Page Setup ****************/
function initPages() {
pages = [];
// Page 0: Common intro
pages.push({
type: 'intro',
title: 'Custom Active Task Demo',
instructions: [
config.intendedUseDescription,
'This test will measure your tapping speed using your RIGHT hand.'
]
});
// Right Hand Test Intro
pages.push({
type: 'intro',
hand: 'RIGHT',
title: 'Right Hand Test',
instructions: [`Tap the button using your RIGHT hand for ${config.lengthOfTest} seconds.`]
});
// Right Hand Tapping Test
pages.push({
type: 'test',
hand: 'RIGHT'
});
// Extra Step: Capture an Image (optional)
pages.push({
type: 'captureImage',
title: 'Capture Image (Optional)',
instructions: ['Capture an image using your camera, or skip this step.']
});
// Extra Step: Record Audio (optional)
pages.push({
type: 'recordAudio',
title: 'Record Audio (Optional)',
instructions: ['Record an audio clip using your microphone, or skip this step.']
});
// Extra Step: Capture Location
pages.push({
type: 'captureLocation',
title: 'Capture Location',
instructions: ['Allow location access to capture your latitude and longitude (optional).']
});
// Final Page: Completion
pages.push({
type: 'completion',
title: 'Completion',
instructions: ['Test complete. Thank you!']
});
totalPages = pages.length;
}
/**************** Rendering & Navigation ****************/
// Render the current page into the #app container
function renderPage(index) {
const page = pages[index];
let html = '';
// Top Bar with page count and Back button (if applicable)
html += `<div class="top-bar d-flex justify-content-between align-items-center">
<div>Page ${index + 1} of ${totalPages}</div>`;
if (index > 0 && page.type !== 'test' && page.type !== 'completion') {
html += `<button id="backButton" class="btn btn-secondary">Back</button>`;
}
html += `</div>`;
// Main Content based on page type
html += `<div class="content">`;
if (page.type === 'intro') {
html += `<h2>${page.title}</h2>`;
page.instructions.forEach(instr => {
html += `<p>${instr}</p>`;
});
if (index === 0) {
html += `<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">Received Parameters</h5>
<pre id="jsonDisplay">${JSON.stringify(config, null, 2)}</pre>
</div>
</div>`;
}
<!-- Replace the image below with your own if desired -->
html += `<img src="left_hand_tap.png" alt="Instruction Image" class="img-fluid my-3"/>`;
} else if (page.type === 'test') {
html += `<h2>Tapping Speed Test</h2>`;
html += `<p>Tap the button using your RIGHT hand.</p>`;
html += `<div id="progressContainer" class="progress mb-3">
<div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;"></div>
</div>`;
html += `<div>
<p>Total Taps: <span id="tapCount">0</span></p>
</div>`;
html += `<div class="d-flex justify-content-center">
<button id="rightButton" class="tap-button mx-3">Tap</button>
</div>`;
} else if (page.type === 'captureImage') {
html += `<h2>${page.title}</h2>`;
page.instructions.forEach(instr => {
html += `<p>${instr}</p>`;
});
html += `<video id="video" autoplay playsinline style="width: 100%; max-width: 400px;"></video>`;
html += `<canvas id="canvas" style="display:none;"></canvas>`;
html += `<div class="bottom-bar">
<button id="captureButton" class="btn btn-primary">Capture Image</button>
<button id="skipImage" class="btn btn-secondary ml-2">Skip</button>
</div>`;
} else if (page.type === 'recordAudio') {
html += `<h2>${page.title}</h2>`;
page.instructions.forEach(instr => {
html += `<p>${instr}</p>`;
});
html += `<div id="audioControls" class="mb-3">
<button id="startRecording" class="btn btn-primary">Start Recording</button>
<button id="stopRecording" class="btn btn-secondary" disabled>Stop Recording</button>
</div>`;
html += `<div class="bottom-bar">
<button id="skipAudio" class="btn btn-secondary">Skip</button>
</div>`;
} else if (page.type === 'captureLocation') {
html += `<h2>${page.title}</h2>`;
page.instructions.forEach(instr => {
html += `<p>${instr}</p>`;
});
html += `<p id="locationStatus">Attempting to get location...</p>`;
html += `<div class="bottom-bar"><button id="locationNextButton" class="btn btn-primary">Next</button></div>`;
} else if (page.type === 'completion') {
html += `<h2>${page.title}</h2>`;
page.instructions.forEach(instr => {
html += `<p>${instr}</p>`;
});
html += `<p>Submitting results...</p>`;
}
html += `</div>`;
// Bottom Bar for non-test pages (if not already provided)
if ((page.type === 'intro' || page.type === 'completion') && page.type !== 'test' && page.type !== 'captureImage' && page.type !== 'recordAudio' && page.type !== 'captureLocation') {
html += `<div class="bottom-bar">`;
if (index < totalPages - 1 && page.type !== 'completion') {
html += `<button id="nextButton" class="btn btn-primary">Next</button>`;
}
if (page.type === 'completion') {
html += `<button id="submitButton" class="btn btn-success">Submit</button>`;
}
html += `</div>`;
}
document.getElementById("app").innerHTML = html;
// Navigation button event listeners
const backBtn = document.getElementById("backButton");
if (backBtn) backBtn.addEventListener("click", prevPage);
const nextBtn = document.getElementById("nextButton");
if (nextBtn) nextBtn.addEventListener("click", nextPage);
const submitBtn = document.getElementById("submitButton");
if (submitBtn) submitBtn.addEventListener("click", submitResults);
// Test page: initialize test state and attach tap listener (right-hand only)
if (page.type === 'test') {
testRunning = false;
testStartTime = 0;
tapCount = 0;
samples = [];
accEvents = [];
currentTestHand = "RIGHT";
document.getElementById("tapCount").textContent = "0";
document.getElementById("rightButton").addEventListener("click", function(e) {
handleTap(e, "Right");
});
}
// Extra Step: Capture Image
if (page.type === 'captureImage') {
const video = document.getElementById("video");
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
videoStream = stream;
video.srcObject = stream;
})
.catch(err => {
console.error("Error accessing camera: ", err);
video.parentElement.innerHTML = "<p>Camera access denied or not available.</p>";
});
document.getElementById("captureButton").addEventListener("click", captureImage);
document.getElementById("skipImage").addEventListener("click", function() {
if (videoStream) {
videoStream.getTracks().forEach(track => track.stop());
}
nextPage();
});
}
// Extra Step: Record Audio
if (page.type === 'recordAudio') {
const startBtn = document.getElementById("startRecording");
const stopBtn = document.getElementById("stopRecording");
startBtn.addEventListener("click", startAudioRecording);
stopBtn.addEventListener("click", stopAudioRecording);
document.getElementById("skipAudio").addEventListener("click", nextPage);
}
// Extra Step: Capture Location
if (page.type === 'captureLocation') {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
result.location.latitude = position.coords.latitude;
result.location.longitude = position.coords.longitude;
document.getElementById("locationStatus").textContent =
`Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude}`;
},
(error) => {
console.error("Error obtaining location:", error);
result.location.latitude = null;
result.location.longitude = null;
document.getElementById("locationStatus").textContent = "Location not available.";
}
);
} else {
result.location.latitude = null;
result.location.longitude = null;
document.getElementById("locationStatus").textContent = "Geolocation not supported.";
}
document.getElementById("locationNextButton").addEventListener("click", nextPage);
}
}
function nextPage() {
if (currentPageIndex < totalPages - 1) {
currentPageIndex++;
renderPage(currentPageIndex);
} else {
submitResults();
}
}
function prevPage() {
if (currentPageIndex > 0) {
currentPageIndex--;
renderPage(currentPageIndex);
}
}
/**************** Test (Tapping) Logic ****************/
function handleTap(e, buttonSide) {
const x = e.clientX;
const y = e.clientY;
// Since only RIGHT-hand is used, start the test if not already running.
if (!testRunning) {
startTest();
}
tapCount++;
document.getElementById("tapCount").textContent = tapCount;
const timestamp = Date.now() - testStartTime;
samples.push({
locationX: x,
locationY: y,
buttonIdentifier: ".Right",
timestamp: timestamp
});
}
function startTest() {
testRunning = true;
testStartTime = Date.now();
testInterval = setInterval(function() {
const elapsed = Date.now() - testStartTime;
const progressPercent = Math.min((elapsed / (config.lengthOfTest * 1000)) * 100, 100);
document.getElementById("progressBar").style.width = progressPercent + "%";
if (elapsed >= config.lengthOfTest * 1000) {
stopTest();
}
}, 50);
window.addEventListener("devicemotion", deviceMotionHandler);
}
function stopTest() {
clearInterval(testInterval);
testRunning = false;
window.removeEventListener("devicemotion", deviceMotionHandler);
const rightBtn = document.getElementById("rightButton");
const rightRect = rightBtn.getBoundingClientRect();
const btnInfo = {
buttonRect: {
locationX: rightRect.left,
locationY: rightRect.top,
width: rightRect.width,
height: rightRect.height
},
stepViewSize: {
width: window.innerWidth,
height: window.innerHeight
},
samples: samples
};
result.rightHandAccData = accEvents;
result.rightHand = btnInfo;
setTimeout(nextPage, 500);
}
function deviceMotionHandler(event) {
const acceleration = event.acceleration;
const timestamp = Date.now() - testStartTime;
if (acceleration) {
accEvents.push({
x: acceleration.x,
y: acceleration.y,
z: acceleration.z,
timestamp: timestamp
});
}
}
/**************** Extra Step: Capture Image ****************/
function captureImage() {
const video = document.getElementById("video");
const canvas = document.getElementById("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob(function(blob) {
const reader = new FileReader();
reader.onloadend = function() {
result.image = reader.result;
if (videoStream) {
videoStream.getTracks().forEach(track => track.stop());
}
nextPage();
}
reader.readAsDataURL(blob);
}, 'image/png');
}
/**************** Extra Step: Record Audio ****************/
function startAudioRecording() {
const startBtn = document.getElementById("startRecording");
const stopBtn = document.getElementById("stopRecording");
startBtn.disabled = true;
stopBtn.disabled = false;
audioChunks = [];
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = function(e) {
if (e.data && e.data.size > 0) {
audioChunks.push(e.data);
}
};
mediaRecorder.onstop = function() {
const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
const reader = new FileReader();
reader.onloadend = function() {
result.audio = reader.result;
stream.getTracks().forEach(track => track.stop());
nextPage();
}
reader.readAsDataURL(audioBlob);
};
mediaRecorder.start();
})
.catch(err => {
console.error("Error accessing microphone: ", err);
startBtn.disabled = false;
stopBtn.disabled = true;
alert("Microphone access denied or not available.");
});
}
function stopAudioRecording() {
const stopBtn = document.getElementById("stopRecording");
stopBtn.disabled = true;
if (mediaRecorder && mediaRecorder.state !== "inactive") {
mediaRecorder.stop();
}
}
/**************** Submit Results ****************/
function submitResults() {
const jsonResult = JSON.stringify(result);
if (window.returnData && typeof window.returnData.postMessage === "function") {
window.returnData.postMessage(jsonResult);
console.log("Data sent successfully:", jsonResult);
} else {
console.log("JSON Result:", jsonResult);
}
setTimeout(function() {
window.close();
}, 500);
}
/**************** Initialization ****************/
initPages();
renderPage(currentPageIndex);