Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
170 lines (138 loc) · 5.1 KB
/
Copy pathmain.js
File metadata and controls
170 lines (138 loc) · 5.1 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
// main.js
//PPPP AAAAA Y Y TTTTTT OOOO N N
//P P A A Y Y TT O O NN N
//PPPP AAAAA Y TT O O N N N
//P A A Y TT O O N NN
//P A A Y TT OOOO N N
// Notes:
// Assembles the experiment timeline and starts jsPsych
console.log('main.js loaded');
const timeline = [];
// --- Run/session identifiers ---
const run_id = `${Date.now()}_${Math.random().toString(16).slice(2)}`;
const params = new URLSearchParams(window.location.search);
// Store these on every row automatically
// (this is huge for Prolific + MySQL later)
jsPsych.data.addProperties({
run_id: run_id,
prolific_pid: params.get("PROLIFIC_PID"),
study_id: params.get("STUDY_ID"),
session_id: params.get("SESSION_ID")
});
// --- Save-as-you-go queue (POST batches) ---
const SAVE_ENDPOINT = "save_data.php"; // later: your server route that writes to MySQL
let sendQueue = [];
let flushInProgress = false;
// Local crash-backup key
const BACKUP_KEY = `jspsych_backup_${run_id}`;
// Minimal backup: store the whole dataset every N important trials
let importantCount = 0;
function backupToLocalStorage() {
try {
const payload = {
run_id,
time: Date.now(),
data: jsPsych.data.get().values()
};
localStorage.setItem(BACKUP_KEY, JSON.stringify(payload));
} catch (e) {
console.warn("localStorage backup failed:", e);
}
}
async function flushQueue() {
if (flushInProgress) return;
if (sendQueue.length === 0) return;
flushInProgress = true;
// Send a copy, keep original until confirmed
const batch = sendQueue.slice();
try {
const res = await fetch(SAVE_ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
run_id,
prolific_pid: params.get("PROLIFIC_PID"),
study_id: params.get("STUDY_ID"),
session_id: params.get("SESSION_ID"),
rows: batch
})
});
if (!res.ok) {
throw new Error(`Save failed: HTTP ${res.status}`);
}
// On success, remove sent items
sendQueue = sendQueue.slice(batch.length);
} catch (err) {
console.warn("Save-as-you-go flush failed (will retry):", err);
// Keep queue for retry, and also keep local backup
backupToLocalStorage();
} finally {
flushInProgress = false;
}
}
//Instructions and Practice
if (INCLUDE.instructions && !DEBUG_SKIP.instructions && typeof Modules !== 'undefined' && typeof Modules.instructions === 'function') {
timeline.push(...Modules.instructions());
}
// Main Grid task
if (INCLUDE.brockmole && !DEBUG_SKIP.brockmole && typeof Modules !== 'undefined' && typeof Modules.task_brockmole === 'function') {
timeline.push(...Modules.task_brockmole(BROCKMOLE_DEFAULTS));
} else {
console.warn('Brockmole module not available or disabled.');
}
//VVIQ
if (INCLUDE.vviq && !DEBUG_SKIP.vviq && typeof Modules !== 'undefined' && typeof Modules.vviq === 'function') {
timeline.push(...Modules.vviq());
}
jsPsych.init({
display_element: 'jspsych-target',
timeline: timeline,
on_data_update: function (data) {
// Only save the important stuff incrementally
const isImportant =
data.phase === "brockmole_response" ||
data.phase === "vviq";
if (!isImportant) return;
sendQueue.push(data);
importantCount += 1;
// backup every 5 important rows
if (importantCount % 5 === 0) {
backupToLocalStorage();
}
// flush when queue reaches 5 rows
if (sendQueue.length >= 5) {
flushQueue();
}
},
on_finish: async function () {
console.log('Experiment finished');
// Final backup and best-effort send
backupToLocalStorage();
await flushQueue();
const data = jsPsych.data.get();
// --- Download JSON ---
const json = data.json();
const jsonBlob = new Blob([json], { type: 'application/json' });
const jsonUrl = URL.createObjectURL(jsonBlob);
const jsonLink = document.createElement('a');
jsonLink.href = jsonUrl;
jsonLink.download = `grid_integration_${Date.now()}.json`;
document.body.appendChild(jsonLink);
jsonLink.click();
document.body.removeChild(jsonLink);
URL.revokeObjectURL(jsonUrl);
// --- Download CSV ---
const csv = data.csv();
const csvBlob = new Blob([csv], { type: 'text/csv' });
const csvUrl = URL.createObjectURL(csvBlob);
const csvLink = document.createElement('a');
csvLink.href = csvUrl;
csvLink.download = `grid_integration_${Date.now()}.csv`;
document.body.appendChild(csvLink);
csvLink.click();
document.body.removeChild(csvLink);
URL.revokeObjectURL(csvUrl);
// Redirect to debrief (preserve Prolific params)
window.location.href = "consent_and_debriefing/debriefing.html" + window.location.search;
}
});