/** * 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; }, 'preload_images': [], 'preload_audio': [], 'use_webaudio': true, 'exclusions': {}, 'show_progress_bar': false, '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 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 = '
'; 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(); // 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.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 || '

The experiment failed to load.

'; 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'+ '

The minimum width is '+mw+'px. Your current width is '+w+'px.

'+ '

The minimum height is '+mh+'px. Your current height is '+h+'px.

'; 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 = '

Your browser does not support the WebAudio API, which means that you will not '+ 'be able to complete the experiment.

Browsers that support the WebAudio API include '+ 'Chrome, Firefox, Safari, and Edge.

'; core.getDisplayElement().innerHTML = msg; fail(); return; } } // GO? if(clear){ success(); } } function drawProgressBar() { document.querySelector('.jspsych-display-element').insertAdjacentHTML('afterbegin', '
'+ 'Completion Progress'+ '
'+ '
'+ '
'); } function updateProgressBar() { var progress = jsPsych.progress(); document.querySelector('#jspsych-progressbar-inner').style.width = progress.percent_complete + "%"; } 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) + "%"; } //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 module.parameterType = { BOOL: 0, STRING: 1, INT: 2, FLOAT: 3, FUNCTION: 4, KEYCODE: 5, SELECT: 6, HTML_STRING: 7, IMAGE: 8, AUDIO: 9, VIDEO: 10, OBJECT: 11, COMPLEX: 12 } module.universalPluginParameters = { data: { type: module.parameterType.OBJECT, pretty_name: 'Data', default: {}, description: 'Data to add to this trial (key-value pairs)' }, on_start: { type: module.parameterType.FUNCTION, pretty_name: 'On start', default: function() { return; }, description: 'Function to execute when trial begins' }, on_finish: { type: module.parameterType.FUNCTION, pretty_name: 'On finish', default: function() { return; }, description: 'Function to execute when trial is finished' }, on_load: { type: module.parameterType.FUNCTION, pretty_name: 'On load', default: function() { return; }, description: 'Function to execute after the trial has loaded' }, post_trial_gap: { type: module.parameterType.INT, pretty_name: 'Post trial gap', default: null, description: 'Length of gap between the end of this trial and the start of the next trial' } } return module; })(); jsPsych.data = (function() { var module = {}; // data storage object var allData = DataCollection(); // browser interaction event data var interactionData = DataCollection(); // data properties for all trials var dataProperties = {}; // cache the query_string var query_string; // DataCollection function DataCollection(data){ var data_collection = {}; var trials = typeof data === 'undefined' ? [] : data; data_collection.push = function(new_data){ trials.push(new_data); return data_collection; } data_collection.join = function(other_data_collection){ trials = trials.concat(other_data_collection.values()); return data_collection; } data_collection.top = function(){ if(trials.length <= 1){ return data_collection; } else { return DataCollection([trials[trials.length-1]]); } } data_collection.first = function(n){ if(typeof n=='undefined'){ n = 1 } var out = []; for(var i=0; i