forked from jspsych/jsPsych
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jspsych.js
executable file
·2630 lines (2212 loc) · 76.5 KB
/
jspsych.js
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* jspsych.js
* Josh de Leeuw
*
* documentation: docs.jspsych.org
*
**/
window.jsPsych = (function() {
var core = {};
//
// private variables
//
// options
var opts = {};
// experiment timeline
var timeline;
// flow control
var global_trial_index = 0;
var current_trial = {};
var current_trial_finished = false;
// target DOM element
var DOM_container;
var DOM_target;
// time that the experiment began
var exp_start_time;
// is the experiment paused?
var paused = false;
var waiting = false;
// done loading?
var loaded = false;
var loadfail = false;
// storing a single webaudio context to prevent problems with multiple inits
// of jsPsych
core.webaudio_context = null;
// temporary patch for Safari
if (typeof window !== 'undefined' && window.hasOwnProperty('webkitAudioContext') && !window.hasOwnProperty('AudioContext')) {
window.AudioContext = webkitAudioContext;
}
// end patch
core.webaudio_context = (typeof window !== 'undefined' && typeof window.AudioContext !== 'undefined') ? new AudioContext() : null;
// enumerated variables for special parameter types
core.ALL_KEYS = 'allkeys';
core.NO_KEYS = 'none';
//
// public methods
//
core.init = function(options) {
if(typeof options.timeline === 'undefined'){
console.error('No timeline declared in jsPsych.init. Cannot start experiment.')
}
// reset variables
timeline = null;
global_trial_index = 0;
current_trial = {};
current_trial_finished = false;
paused = false;
waiting = false;
loaded = false;
loadfail = false;
jsPsych.data.reset();
var defaults = {
'display_element': undefined,
'on_finish': function(data) {
return undefined;
},
'on_trial_start': function(trial) {
return undefined;
},
'on_trial_finish': function() {
return undefined;
},
'on_data_update': function(data) {
return undefined;
},
'on_interaction_data_update': function(data){
return undefined;
},
'on_close': function(){
return undefined;
},
'preload_images': [],
'preload_audio': [],
'preload_video': [],
'use_webaudio': true,
'exclusions': {},
'show_progress_bar': false,
'message_progress_bar': 'Completion Progress',
'auto_update_progress_bar': true,
'auto_preload': true,
'show_preload_progress_bar': true,
'max_load_time': 60000,
'max_preload_attempts': 10,
'default_iti': 0
};
// override default options if user specifies an option
opts = Object.assign({}, defaults, options);
// set DOM element where jsPsych will render content
// if undefined, then jsPsych will use the <body> tag and the entire page
if(typeof opts.display_element == 'undefined'){
// check if there is a body element on the page
var body = document.querySelector('body');
if (body === null) {
document.documentElement.appendChild(document.createElement('body'));
}
// using the full page, so we need the HTML element to
// have 100% height, and body to be full width and height with
// no margin
document.querySelector('html').style.height = '100%';
document.querySelector('body').style.margin = '0px';
document.querySelector('body').style.height = '100%';
document.querySelector('body').style.width = '100%';
opts.display_element = document.querySelector('body');
} else {
// make sure that the display element exists on the page
var display;
if (opts.display_element instanceof Element) {
var display = opts.display_element;
} else {
var display = document.querySelector('#' + opts.display_element);
}
if(display === null) {
console.error('The display_element specified in jsPsych.init() does not exist in the DOM.');
} else {
opts.display_element = display;
}
}
opts.display_element.innerHTML = '<div class="jspsych-content-wrapper"><div id="jspsych-content"></div></div>';
DOM_container = opts.display_element;
DOM_target = document.querySelector('#jspsych-content');
// add tabIndex attribute to scope event listeners
opts.display_element.tabIndex = 0;
// add CSS class to DOM_target
if(opts.display_element.className.indexOf('jspsych-display-element') == -1){
opts.display_element.className += ' jspsych-display-element';
}
DOM_target.className += 'jspsych-content';
// create experiment timeline
timeline = new TimelineNode({
timeline: opts.timeline
});
// initialize audio context based on options and browser capabilities
jsPsych.pluginAPI.initAudio();
// below code resets event listeners that may have lingered from
// a previous incomplete experiment loaded in same DOM.
jsPsych.pluginAPI.reset(opts.display_element);
// create keyboard event listeners
jsPsych.pluginAPI.createKeyboardEventListeners(opts.display_element);
// create listeners for user browser interaction
jsPsych.data.createInteractionListeners();
// add event for closing window
window.addEventListener('beforeunload', opts.on_close);
// check exclusions before continuing
checkExclusions(opts.exclusions,
function(){
// success! user can continue...
// start experiment, with or without preloading
if(opts.auto_preload){
jsPsych.pluginAPI.autoPreload(timeline, startExperiment, opts.preload_images, opts.preload_audio, opts.preload_video, opts.show_preload_progress_bar);
if(opts.max_load_time > 0){
setTimeout(function(){
if(!loaded && !loadfail){
core.loadFail();
}
}, opts.max_load_time);
}
} else {
startExperiment();
}
},
function(){
// fail. incompatible user.
}
);
};
core.progress = function() {
var percent_complete = typeof timeline == 'undefined' ? 0 : timeline.percentComplete();
var obj = {
"total_trials": typeof timeline == 'undefined' ? undefined : timeline.length(),
"current_trial_global": global_trial_index,
"percent_complete": percent_complete
};
return obj;
};
core.startTime = function() {
return exp_start_time;
};
core.totalTime = function() {
if(typeof exp_start_time == 'undefined'){ return 0; }
return (new Date()).getTime() - exp_start_time.getTime();
};
core.getDisplayElement = function() {
return DOM_target;
};
core.getDisplayContainerElement = function(){
return DOM_container;
}
core.finishTrial = function(data) {
if(current_trial_finished){ return; }
current_trial_finished = true;
// write the data from the trial
data = typeof data == 'undefined' ? {} : data;
jsPsych.data.write(data);
// get back the data with all of the defaults in
var trial_data = jsPsych.data.get().filter({trial_index: global_trial_index});
// for trial-level callbacks, we just want to pass in a reference to the values
// of the DataCollection, for easy access and editing.
var trial_data_values = trial_data.values()[0];
// handle callback at plugin level
if (typeof current_trial.on_finish === 'function') {
current_trial.on_finish(trial_data_values);
}
// handle callback at whole-experiment level
opts.on_trial_finish(trial_data_values);
// after the above callbacks are complete, then the data should be finalized
// for this trial. call the on_data_update handler, passing in the same
// data object that just went through the trial's finish handlers.
opts.on_data_update(trial_data_values);
// wait for iti
if (typeof current_trial.post_trial_gap === null) {
if (opts.default_iti > 0) {
setTimeout(nextTrial, opts.default_iti);
} else {
nextTrial();
}
} else {
if (current_trial.post_trial_gap > 0) {
setTimeout(nextTrial, current_trial.post_trial_gap);
} else {
nextTrial();
}
}
}
core.endExperiment = function(end_message) {
timeline.end_message = end_message;
timeline.end();
jsPsych.pluginAPI.cancelAllKeyboardResponses();
jsPsych.pluginAPI.clearAllTimeouts();
core.finishTrial();
}
core.endCurrentTimeline = function() {
timeline.endActiveNode();
}
core.currentTrial = function() {
return current_trial;
};
core.initSettings = function() {
return opts;
};
core.currentTimelineNodeID = function() {
return timeline.activeID();
};
core.timelineVariable = function(varname, execute){
if(execute){
return timeline.timelineVariable(varname);
} else {
return function() { return timeline.timelineVariable(varname); }
}
}
core.addNodeToEndOfTimeline = function(new_timeline, preload_callback){
timeline.insert(new_timeline);
if(typeof preload_callback !== 'undefinded'){
if(opts.auto_preload){
jsPsych.pluginAPI.autoPreload(timeline, preload_callback);
} else {
preload_callback();
}
}
}
core.pauseExperiment = function(){
paused = true;
}
core.resumeExperiment = function(){
paused = false;
if(waiting){
waiting = false;
nextTrial();
}
}
core.loadFail = function(message){
message = message || '<p>The experiment failed to load.</p>';
loadfail = true;
DOM_target.innerHTML = message;
}
function TimelineNode(parameters, parent, relativeID) {
// a unique ID for this node, relative to the parent
var relative_id;
// store the parent for this node
var parent_node;
// parameters for the trial if the node contains a trial
var trial_parameters;
// parameters for nodes that contain timelines
var timeline_parameters;
// stores trial information on a node that contains a timeline
// used for adding new trials
var node_trial_data;
// track progress through the node
var progress = {
current_location: -1, // where on the timeline (which timelinenode)
current_variable_set: 0, // which set of variables to use from timeline_variables
current_repetition: 0, // how many times through the variable set on this run of the node
current_iteration: 0, // how many times this node has been revisited
done: false
}
// reference to self
var self = this;
// recursively get the next trial to run.
// if this node is a leaf (trial), then return the trial.
// otherwise, recursively find the next trial in the child timeline.
this.trial = function() {
if (typeof timeline_parameters == 'undefined') {
// returns a clone of the trial_parameters to
// protect functions.
return jsPsych.utils.deepCopy(trial_parameters);
} else {
if (progress.current_location >= timeline_parameters.timeline.length) {
return null;
} else {
return timeline_parameters.timeline[progress.current_location].trial();
}
}
}
this.markCurrentTrialComplete = function() {
if(typeof timeline_parameters == 'undefined'){
progress.done = true;
} else {
timeline_parameters.timeline[progress.current_location].markCurrentTrialComplete();
}
}
this.nextRepetiton = function() {
this.setTimelineVariablesOrder();
progress.current_location = -1;
progress.current_variable_set = 0;
progress.current_repetition++;
for (var i = 0; i < timeline_parameters.timeline.length; i++) {
timeline_parameters.timeline[i].reset();
}
}
// set the order for going through the timeline variables array
// TODO: this is where all the sampling options can be implemented
this.setTimelineVariablesOrder = function() {
// check to make sure this node has variables
if(typeof timeline_parameters === 'undefined' || typeof timeline_parameters.timeline_variables === 'undefined'){
return;
}
var order = [];
for(var i=0; i<timeline_parameters.timeline_variables.length; i++){
order.push(i);
}
if(typeof timeline_parameters.sample !== 'undefined'){
if(timeline_parameters.sample.type == 'custom'){
order = timeline_parameters.sample.fn(order);
} else if(timeline_parameters.sample.type == 'with-replacement'){
order = jsPsych.randomization.sampleWithReplacement(order, timeline_parameters.sample.size, timeline_parameters.sample.weights);
} else if(timeline_parameters.sample.type == 'without-replacement'){
order = jsPsych.randomization.sampleWithoutReplacement(order, timeline_parameters.sample.size);
} else if(timeline_parameters.sample.type == 'fixed-repetitions'){
order = jsPsych.randomization.repeat(order, timeline_parameters.sample.size, false);
}
}
if(timeline_parameters.randomize_order) {
order = jsPsych.randomization.shuffle(order);
}
progress.order = order;
}
// next variable set
this.nextSet = function() {
progress.current_location = -1;
progress.current_variable_set++;
for (var i = 0; i < timeline_parameters.timeline.length; i++) {
timeline_parameters.timeline[i].reset();
}
}
// update the current trial node to be completed
// returns true if the node is complete after advance (all subnodes are also complete)
// returns false otherwise
this.advance = function() {
// first check to see if done
if (progress.done) {
return true;
}
// if node has not started yet (progress.current_location == -1),
// then try to start the node.
if (progress.current_location == -1) {
// check for conditonal function on nodes with timelines
if (typeof timeline_parameters != 'undefined') {
if (typeof timeline_parameters.conditional_function !== 'undefined') {
var conditional_result = timeline_parameters.conditional_function();
// if the conditional_function() returns false, then the timeline
// doesn't run and is marked as complete.
if (conditional_result == false) {
progress.done = true;
return true;
}
// if the conditonal_function() returns true, then the node can start
else {
progress.current_location = 0;
}
}
// if there is no conditional_function, then the node can start
else {
progress.current_location = 0;
}
}
// if the node does not have a timeline, then it can start
progress.current_location = 0;
// call advance again on this node now that it is pointing to a new location
return this.advance();
}
// if this node has a timeline, propogate down to the current trial.
if (typeof timeline_parameters !== 'undefined') {
var have_node_to_run = false;
// keep incrementing the location in the timeline until one of the nodes reached is incomplete
while (progress.current_location < timeline_parameters.timeline.length && have_node_to_run == false) {
// check to see if the node currently pointed at is done
var target_complete = timeline_parameters.timeline[progress.current_location].advance();
if (!target_complete) {
have_node_to_run = true;
return false;
} else {
progress.current_location++;
}
}
// if we've reached the end of the timeline (which, if the code is here, we have)
// there are a few steps to see what to do next...
// first, check the timeline_variables to see if we need to loop through again
// with a new set of variables
if (progress.current_variable_set < progress.order.length - 1) {
// reset the progress of the node to be with the new set
this.nextSet();
// then try to advance this node again.
return this.advance();
}
// if we're all done with the timeline_variables, then check to see if there are more repetitions
else if (progress.current_repetition < timeline_parameters.repetitions - 1) {
this.nextRepetiton();
return this.advance();
}
// if we're all done with the repetitions, check if there is a loop function.
else if (typeof timeline_parameters.loop_function !== 'undefined') {
if (timeline_parameters.loop_function(this.generatedData())) {
this.reset();
return parent_node.advance();
} else {
progress.done = true;
return true;
}
}
// no more loops on this timeline, we're done!
else {
progress.done = true;
return true;
}
}
}
// check the status of the done flag
this.isComplete = function() {
return progress.done;
}
// getter method for timeline variables
this.getTimelineVariableValue = function(variable_name){
if(typeof timeline_parameters == 'undefined'){
return undefined;
}
var v = timeline_parameters.timeline_variables[progress.order[progress.current_variable_set]][variable_name];
return v;
}
// recursive upward search for timeline variables
this.findTimelineVariable = function(variable_name){
var v = this.getTimelineVariableValue(variable_name);
if(typeof v == 'undefined'){
if(typeof parent_node !== 'undefined'){
return parent_node.findTimelineVariable(variable_name);
} else {
return undefined;
}
} else {
return v;
}
}
// recursive downward search for active trial to extract timeline variable
this.timelineVariable = function(variable_name){
if(typeof timeline_parameters == 'undefined'){
return this.findTimelineVariable(variable_name);
} else {
return timeline_parameters.timeline[progress.current_location].timelineVariable(variable_name);
}
}
// recursively get the number of **trials** contained in the timeline
// assuming that while loops execute exactly once and if conditionals
// always run
this.length = function() {
var length = 0;
if (typeof timeline_parameters !== 'undefined') {
for (var i = 0; i < timeline_parameters.timeline.length; i++) {
length += timeline_parameters.timeline[i].length();
}
} else {
return 1;
}
return length;
}
// return the percentage of trials completed, grouped at the first child level
// counts a set of trials as complete when the child node is done
this.percentComplete = function() {
var total_trials = this.length();
var completed_trials = 0;
for (var i = 0; i < timeline_parameters.timeline.length; i++) {
if (timeline_parameters.timeline[i].isComplete()) {
completed_trials += timeline_parameters.timeline[i].length();
}
}
return (completed_trials / total_trials * 100)
}
// resets the node and all subnodes to original state
// but increments the current_iteration counter
this.reset = function() {
progress.current_location = -1;
progress.current_repetition = 0;
progress.current_variable_set = 0;
progress.current_iteration++;
progress.done = false;
this.setTimelineVariablesOrder();
if (typeof timeline_parameters != 'undefined') {
for (var i = 0; i < timeline_parameters.timeline.length; i++) {
timeline_parameters.timeline[i].reset();
}
}
}
// mark this node as finished
this.end = function() {
progress.done = true;
}
// recursively end whatever sub-node is running the current trial
this.endActiveNode = function() {
if (typeof timeline_parameters == 'undefined') {
this.end();
parent_node.end();
} else {
timeline_parameters.timeline[progress.current_location].endActiveNode();
}
}
// get a unique ID associated with this node
// the ID reflects the current iteration through this node.
this.ID = function() {
var id = "";
if (typeof parent_node == 'undefined') {
return "0." + progress.current_iteration;
} else {
id += parent_node.ID() + "-";
id += relative_id + "." + progress.current_iteration;
return id;
}
}
// get the ID of the active trial
this.activeID = function() {
if (typeof timeline_parameters == 'undefined') {
return this.ID();
} else {
return timeline_parameters.timeline[progress.current_location].activeID();
}
}
// get all the data generated within this node
this.generatedData = function() {
return jsPsych.data.getDataByTimelineNode(this.ID());
}
// get all the trials of a particular type
this.trialsOfType = function(type) {
if (typeof timeline_parameters == 'undefined'){
if (trial_parameters.type == type) {
return trial_parameters;
} else {
return [];
}
} else {
var trials = [];
for (var i = 0; i < timeline_parameters.timeline.length; i++) {
var t = timeline_parameters.timeline[i].trialsOfType(type);
trials = trials.concat(t);
}
return trials;
}
}
// add new trials to end of this timeline
this.insert = function(parameters){
if(typeof timeline_parameters == 'undefined'){
console.error('Cannot add new trials to a trial-level node.');
} else {
timeline_parameters.timeline.push(
new TimelineNode(Object.assign({}, node_trial_data, parameters), self, timeline_parameters.timeline.length)
);
}
}
// constructor
var _construct = function() {
// store a link to the parent of this node
parent_node = parent;
// create the ID for this node
if (typeof parent == 'undefined') {
relative_id = 0;
} else {
relative_id = relativeID;
}
// check if there is a timeline parameter
// if there is, then this node has its own timeline
if ((typeof parameters.timeline !== 'undefined') || (typeof jsPsych.plugins[trial_type] == 'function')) {
// create timeline properties
timeline_parameters = {
timeline: [],
loop_function: parameters.loop_function,
conditional_function: parameters.conditional_function,
sample: parameters.sample,
randomize_order: typeof parameters.randomize_order == 'undefined' ? false : parameters.randomize_order,
repetitions: typeof parameters.repetitions == 'undefined' ? 1 : parameters.repetitions,
timeline_variables: typeof parameters.timeline_variables == 'undefined' ? [{}] : parameters.timeline_variables
};
self.setTimelineVariablesOrder();
// extract all of the node level data and parameters
var node_data = Object.assign({}, parameters);
delete node_data.timeline;
delete node_data.conditional_function;
delete node_data.loop_function;
delete node_data.randomize_order;
delete node_data.repetitions;
delete node_data.timeline_variables;
delete node_data.sample;
node_trial_data = node_data; // store for later...
// create a TimelineNode for each element in the timeline
for (var i = 0; i < parameters.timeline.length; i++) {
timeline_parameters.timeline.push(new TimelineNode(Object.assign({}, node_data, parameters.timeline[i]), self, i));
}
}
// if there is no timeline parameter, then this node is a trial node
else {
// check to see if a valid trial type is defined
var trial_type = parameters.type;
if (typeof trial_type == 'undefined') {
console.error('Trial level node is missing the "type" parameter. The parameters for the node are: ' + JSON.stringify(parameters));
} else if ((typeof jsPsych.plugins[trial_type] == 'undefined') && (trial_type.toString().replace(/\s/g,'') != "function(){returntimeline.timelineVariable(varname);}")) {
console.error('No plugin loaded for trials of type "' + trial_type + '"');
}
// create a deep copy of the parameters for the trial
trial_parameters = Object.assign({}, parameters);
}
}();
}
function startExperiment() {
loaded = true;
// show progress bar if requested
if (opts.show_progress_bar === true) {
drawProgressBar(opts.message_progress_bar);
}
// record the start time
exp_start_time = new Date();
// begin!
timeline.advance();
doTrial(timeline.trial());
}
function finishExperiment() {
if(typeof timeline.end_message !== 'undefined'){
DOM_target.innerHTML = timeline.end_message;
}
opts.on_finish(jsPsych.data.get());
}
function nextTrial() {
// if experiment is paused, don't do anything.
if(paused) {
waiting = true;
return;
}
global_trial_index++;
// advance timeline
timeline.markCurrentTrialComplete();
var complete = timeline.advance();
// update progress bar if shown
if (opts.show_progress_bar === true && opts.auto_update_progress_bar == true) {
updateProgressBar();
}
// check if experiment is over
if (complete) {
finishExperiment();
return;
}
doTrial(timeline.trial());
}
function doTrial(trial) {
current_trial = trial;
current_trial_finished = false;
// process all timeline variables for this trial
evaluateTimelineVariables(trial);
// evaluate variables that are functions
evaluateFunctionParameters(trial);
// get default values for parameters
setDefaultValues(trial);
// call experiment wide callback
opts.on_trial_start(trial);
// call trial specific callback if it exists
if(typeof trial.on_start == 'function'){
trial.on_start(trial);
}
// apply the focus to the element containing the experiment.
DOM_container.focus();
// reset the scroll on the DOM target
DOM_target.scrollTop = 0;
// execute trial method
jsPsych.plugins[trial.type].trial(DOM_target, trial);
// call trial specific loaded callback if it exists
if(typeof trial.on_load == 'function'){
trial.on_load();
}
}
function evaluateTimelineVariables(trial){
var keys = Object.keys(trial);
for (var i = 0; i < keys.length; i++) {
// timeline variables on the root level
if (typeof trial[keys[i]] == "function" && trial[keys[i]].toString().replace(/\s/g,'') == "function(){returntimeline.timelineVariable(varname);}") {
trial[keys[i]] = trial[keys[i]].call();
}
// timeline variables that are nested in objects
if (typeof trial[keys[i]] == "object" && trial[keys[i]] !== null){
evaluateTimelineVariables(trial[keys[i]]);
}
}
}
function evaluateFunctionParameters(trial){
// first, eval the trial type if it is a function
// this lets users set the plugin type with a function
if(typeof trial.type === 'function'){
trial.type = trial.type.call();
}
// now eval the whole trial
// start by getting a list of the parameters
var keys = Object.keys(trial);
// iterate over each parameter
for (var i = 0; i < keys.length; i++) {
// check to make sure parameter is not "type", since that was eval'd above.
if(keys[i] !== 'type'){
// this if statement is checking to see if the parameter type is expected to be a function, in which case we should NOT evaluate it.
// the first line checks if the parameter is defined in the universalPluginParameters set
// the second line checks the plugin-specific parameters
if(
(typeof jsPsych.plugins.universalPluginParameters[keys[i]] !== 'undefined' && jsPsych.plugins.universalPluginParameters[keys[i]].type !== jsPsych.plugins.parameterType.FUNCTION ) ||
(typeof jsPsych.plugins[trial.type].info.parameters[keys[i]] !== 'undefined' && jsPsych.plugins[trial.type].info.parameters[keys[i]].type !== jsPsych.plugins.parameterType.FUNCTION)
) {
if (typeof trial[keys[i]] == "function") {
trial[keys[i]] = trial[keys[i]].call();
}
}
}
// add a special exception for the data parameter so we can evaluate functions. eventually this could be generalized so that any COMPLEX object type could
// be evaluated at the individual parameter level.
if(keys[i] == 'data'){
var data_params = Object.keys(trial[keys[i]]);
for(var j=0; j<data_params.length; j++){
if(typeof trial[keys[i]][data_params[j]] == "function") {
trial[keys[i]][data_params[j]] = trial[keys[i]][data_params[j]].call();
}
}
}
}
}
function setDefaultValues(trial){
var trial_parameters = Object.keys(jsPsych.plugins[trial.type].info.parameters);
for(var i=0; i<trial_parameters.length; i++){
if(typeof trial[trial_parameters[i]] == 'undefined' || trial[trial_parameters[i]] === null){
if(typeof jsPsych.plugins[trial.type].info.parameters[trial_parameters[i]].default == 'undefined'){
console.error('You must specify a value for the '+trial_parameters[i]+' parameter in the '+trial.type+' plugin.');
} else {
trial[trial_parameters[i]] = jsPsych.plugins[trial.type].info.parameters[trial_parameters[i]].default;
}
}
}
}
function checkExclusions(exclusions, success, fail){
var clear = true;
// MINIMUM SIZE
if(typeof exclusions.min_width !== 'undefined' || typeof exclusions.min_height !== 'undefined'){
var mw = typeof exclusions.min_width !== 'undefined' ? exclusions.min_width : 0;
var mh = typeof exclusions.min_height !== 'undefined' ? exclusions.min_height : 0;
var w = window.innerWidth;
var h = window.innerHeight;
if(w < mw || h < mh){
clear = false;
var interval = setInterval(function(){
var w = window.innerWidth;
var h = window.innerHeight;
if(w < mw || h < mh){
var msg = '<p>Your browser window is too small to complete this experiment. '+
'Please maximize the size of your browser window. If your browser window is already maximized, '+
'you will not be able to complete this experiment.</p>'+
'<p>The minimum width is '+mw+'px. Your current width is '+w+'px.</p>'+
'<p>The minimum height is '+mh+'px. Your current height is '+h+'px.</p>';
core.getDisplayElement().innerHTML = msg;
} else {
clearInterval(interval);
core.getDisplayElement().innerHTML = '';
checkExclusions(exclusions, success, fail);
}
}, 100);
return; // prevents checking other exclusions while this is being fixed
}
}
// WEB AUDIO API
if(typeof exclusions.audio !== 'undefined' && exclusions.audio) {
if(window.hasOwnProperty('AudioContext') || window.hasOwnProperty('webkitAudioContext')){
// clear
} else {
clear = false;
var msg = '<p>Your browser does not support the WebAudio API, which means that you will not '+
'be able to complete the experiment.</p><p>Browsers that support the WebAudio API include '+
'Chrome, Firefox, Safari, and Edge.</p>';
core.getDisplayElement().innerHTML = msg;
fail();
return;
}
}
// GO?
if(clear){ success(); }
}
function drawProgressBar(msg) {
document.querySelector('.jspsych-display-element').insertAdjacentHTML('afterbegin',
'<div id="jspsych-progressbar-container">'+
'<span>'+
msg+
'</span>'+
'<div id="jspsych-progressbar-outer">'+
'<div id="jspsych-progressbar-inner"></div>'+
'</div></div>');
}
function updateProgressBar() {
var progress = jsPsych.progress().percent_complete;
core.setProgressBar(progress / 100);
}
var progress_bar_amount = 0;
core.setProgressBar = function(proportion_complete){
proportion_complete = Math.max(Math.min(1,proportion_complete),0);
document.querySelector('#jspsych-progressbar-inner').style.width = (proportion_complete*100) + "%";
progress_bar_amount = proportion_complete;
}
core.getProgressBarCompleted = function(){
return progress_bar_amount;
}
//Leave a trace in the DOM that jspsych was loaded
document.documentElement.setAttribute('jspsych', 'present');
return core;
})();
jsPsych.plugins = (function() {
var module = {};
// enumerate possible parameter types for plugins