jspsych 6.3.1 → 7.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/README.md +36 -37
  2. package/css/jspsych.css +39 -39
  3. package/dist/JsPsych.d.ts +112 -0
  4. package/dist/TimelineNode.d.ts +34 -0
  5. package/dist/index.browser.js +3171 -0
  6. package/dist/index.browser.js.map +1 -0
  7. package/dist/index.browser.min.js +2 -0
  8. package/dist/index.browser.min.js.map +1 -0
  9. package/dist/index.cjs +3165 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +11 -0
  12. package/dist/index.js +3159 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/migration.d.ts +3 -0
  15. package/dist/modules/data/DataCollection.d.ts +45 -0
  16. package/dist/modules/data/DataColumn.d.ts +15 -0
  17. package/dist/modules/data/index.d.ts +25 -0
  18. package/dist/modules/data/utils.d.ts +3 -0
  19. package/dist/modules/extensions.d.ts +22 -0
  20. package/dist/modules/plugin-api/HardwareAPI.d.ts +15 -0
  21. package/dist/modules/plugin-api/KeyboardListenerAPI.d.ts +34 -0
  22. package/dist/modules/plugin-api/MediaAPI.d.ts +27 -0
  23. package/dist/modules/plugin-api/SimulationAPI.d.ts +41 -0
  24. package/dist/modules/plugin-api/TimeoutAPI.d.ts +5 -0
  25. package/dist/modules/plugin-api/index.d.ts +8 -0
  26. package/dist/modules/plugins.d.ts +136 -0
  27. package/dist/modules/randomization.d.ts +35 -0
  28. package/dist/modules/turk.d.ts +40 -0
  29. package/dist/modules/utils.d.ts +7 -0
  30. package/package.json +32 -15
  31. package/src/JsPsych.ts +884 -0
  32. package/src/TimelineNode.ts +536 -0
  33. package/src/index.ts +71 -0
  34. package/src/migration.ts +37 -0
  35. package/src/modules/data/DataCollection.ts +198 -0
  36. package/src/modules/data/DataColumn.ts +86 -0
  37. package/src/modules/data/index.ts +174 -0
  38. package/src/modules/data/utils.ts +75 -0
  39. package/src/modules/extensions.ts +23 -0
  40. package/src/modules/plugin-api/HardwareAPI.ts +32 -0
  41. package/src/modules/plugin-api/KeyboardListenerAPI.ts +165 -0
  42. package/src/modules/plugin-api/MediaAPI.ts +337 -0
  43. package/src/modules/plugin-api/SimulationAPI.ts +181 -0
  44. package/src/modules/plugin-api/TimeoutAPI.ts +16 -0
  45. package/src/modules/plugin-api/index.ts +28 -0
  46. package/src/modules/plugins.ts +165 -0
  47. package/src/modules/randomization.ts +327 -0
  48. package/src/modules/turk.ts +99 -0
  49. package/src/modules/utils.ts +30 -0
  50. package/.github/workflows/jest.yml +0 -20
  51. package/code-of-conduct.md +0 -56
  52. package/contributors.md +0 -61
  53. package/docs/CNAME +0 -1
  54. package/docs/about/about.md +0 -18
  55. package/docs/about/contributing.md +0 -43
  56. package/docs/about/license.md +0 -25
  57. package/docs/about/support.md +0 -7
  58. package/docs/core_library/jspsych-core.md +0 -719
  59. package/docs/core_library/jspsych-data.md +0 -587
  60. package/docs/core_library/jspsych-pluginAPI.md +0 -624
  61. package/docs/core_library/jspsych-randomization.md +0 -389
  62. package/docs/core_library/jspsych-turk.md +0 -98
  63. package/docs/extensions/extensions.md +0 -83
  64. package/docs/extensions/jspsych-ext-webgazer.md +0 -137
  65. package/docs/img/blue.png +0 -0
  66. package/docs/img/devtools-change-css.png +0 -0
  67. package/docs/img/devtools-css-errors.png +0 -0
  68. package/docs/img/devtools-inspect-element.png +0 -0
  69. package/docs/img/folder-setup.png +0 -0
  70. package/docs/img/folder-with-html.png +0 -0
  71. package/docs/img/githubreleases.jpg +0 -0
  72. package/docs/img/jspsych-favicon.png +0 -0
  73. package/docs/img/jspsych-logo-no-text-mono.svg +0 -493
  74. package/docs/img/jspsych-logo.jpg +0 -0
  75. package/docs/img/orange.png +0 -0
  76. package/docs/img/palmer_stim.png +0 -0
  77. package/docs/img/progress_bar.png +0 -0
  78. package/docs/img/prolific-study-completion.png +0 -0
  79. package/docs/img/prolific-study-link.png +0 -0
  80. package/docs/img/visual_search_example.jpg +0 -0
  81. package/docs/index.md +0 -9
  82. package/docs/overview/browser-device-support.md +0 -35
  83. package/docs/overview/callbacks.md +0 -180
  84. package/docs/overview/data.md +0 -281
  85. package/docs/overview/dynamic-parameters.md +0 -147
  86. package/docs/overview/exclude-browser.md +0 -32
  87. package/docs/overview/experiment-options.md +0 -149
  88. package/docs/overview/eye-tracking.md +0 -271
  89. package/docs/overview/fullscreen.md +0 -36
  90. package/docs/overview/media-preloading.md +0 -369
  91. package/docs/overview/mturk.md +0 -77
  92. package/docs/overview/plugins.md +0 -320
  93. package/docs/overview/progress-bar.md +0 -110
  94. package/docs/overview/prolific.md +0 -78
  95. package/docs/overview/record-browser-interactions.md +0 -23
  96. package/docs/overview/running-experiments.md +0 -95
  97. package/docs/overview/style.md +0 -293
  98. package/docs/overview/timeline.md +0 -457
  99. package/docs/plugins/jspsych-animation.md +0 -40
  100. package/docs/plugins/jspsych-audio-button-response.md +0 -60
  101. package/docs/plugins/jspsych-audio-keyboard-response.md +0 -58
  102. package/docs/plugins/jspsych-audio-slider-response.md +0 -53
  103. package/docs/plugins/jspsych-call-function.md +0 -81
  104. package/docs/plugins/jspsych-canvas-button-response.md +0 -66
  105. package/docs/plugins/jspsych-canvas-keyboard-response.md +0 -68
  106. package/docs/plugins/jspsych-canvas-slider-response.md +0 -89
  107. package/docs/plugins/jspsych-categorize-animation.md +0 -60
  108. package/docs/plugins/jspsych-categorize-html.md +0 -53
  109. package/docs/plugins/jspsych-categorize-image.md +0 -53
  110. package/docs/plugins/jspsych-cloze.md +0 -45
  111. package/docs/plugins/jspsych-external-html.md +0 -70
  112. package/docs/plugins/jspsych-free-sort.md +0 -56
  113. package/docs/plugins/jspsych-fullscreen.md +0 -57
  114. package/docs/plugins/jspsych-html-button-response.md +0 -42
  115. package/docs/plugins/jspsych-html-keyboard-response.md +0 -51
  116. package/docs/plugins/jspsych-html-slider-response.md +0 -45
  117. package/docs/plugins/jspsych-iat-html.md +0 -64
  118. package/docs/plugins/jspsych-iat-image.md +0 -64
  119. package/docs/plugins/jspsych-image-button-response.md +0 -48
  120. package/docs/plugins/jspsych-image-keyboard-response.md +0 -58
  121. package/docs/plugins/jspsych-image-slider-response.md +0 -54
  122. package/docs/plugins/jspsych-instructions.md +0 -58
  123. package/docs/plugins/jspsych-maxdiff.md +0 -41
  124. package/docs/plugins/jspsych-preload.md +0 -128
  125. package/docs/plugins/jspsych-rdk.md +0 -119
  126. package/docs/plugins/jspsych-reconstruction.md +0 -48
  127. package/docs/plugins/jspsych-resize.md +0 -39
  128. package/docs/plugins/jspsych-same-different-html.md +0 -53
  129. package/docs/plugins/jspsych-same-different-image.md +0 -66
  130. package/docs/plugins/jspsych-serial-reaction-time-mouse.md +0 -52
  131. package/docs/plugins/jspsych-serial-reaction-time.md +0 -57
  132. package/docs/plugins/jspsych-survey-html-form.md +0 -50
  133. package/docs/plugins/jspsych-survey-likert.md +0 -70
  134. package/docs/plugins/jspsych-survey-multi-choice.md +0 -48
  135. package/docs/plugins/jspsych-survey-multi-select.md +0 -53
  136. package/docs/plugins/jspsych-survey-text.md +0 -63
  137. package/docs/plugins/jspsych-video-button-response.md +0 -54
  138. package/docs/plugins/jspsych-video-keyboard-response.md +0 -50
  139. package/docs/plugins/jspsych-video-slider-response.md +0 -60
  140. package/docs/plugins/jspsych-virtual-chinrest.md +0 -105
  141. package/docs/plugins/jspsych-visual-search-circle.md +0 -52
  142. package/docs/plugins/jspsych-vsl-animate-occlusion.md +0 -55
  143. package/docs/plugins/jspsych-vsl-grid-scene.md +0 -62
  144. package/docs/plugins/jspsych-webgazer-calibrate.md +0 -61
  145. package/docs/plugins/jspsych-webgazer-init-camera.md +0 -30
  146. package/docs/plugins/jspsych-webgazer-validate.md +0 -44
  147. package/docs/plugins/list-of-plugins.md +0 -54
  148. package/docs/tutorials/hello-world.md +0 -162
  149. package/docs/tutorials/rt-task.md +0 -1334
  150. package/docs/tutorials/video-tutorials.md +0 -11
  151. package/examples/add-to-end-of-timeline.html +0 -38
  152. package/examples/case-sensitive-responses.html +0 -45
  153. package/examples/conditional-and-loop-functions.html +0 -64
  154. package/examples/css/jquery-ui.css +0 -1225
  155. package/examples/css-classes-parameter.html +0 -145
  156. package/examples/data-add-properties.html +0 -44
  157. package/examples/data-as-function.html +0 -39
  158. package/examples/data-from-timeline.html +0 -52
  159. package/examples/data-from-url.html +0 -21
  160. package/examples/demo-flanker.html +0 -117
  161. package/examples/demo-simple-rt-task.html +0 -120
  162. package/examples/demos/demo_1.html +0 -35
  163. package/examples/demos/demo_2.html +0 -50
  164. package/examples/demos/demo_3.html +0 -63
  165. package/examples/display-element-to-embed-experiment.html +0 -79
  166. package/examples/end-active-node.html +0 -52
  167. package/examples/end-experiment.html +0 -45
  168. package/examples/exclusions.html +0 -32
  169. package/examples/external_html/simple_consent.html +0 -4
  170. package/examples/img/1.gif +0 -0
  171. package/examples/img/10.gif +0 -0
  172. package/examples/img/11.gif +0 -0
  173. package/examples/img/12.gif +0 -0
  174. package/examples/img/2.gif +0 -0
  175. package/examples/img/3.gif +0 -0
  176. package/examples/img/4.gif +0 -0
  177. package/examples/img/5.gif +0 -0
  178. package/examples/img/6.gif +0 -0
  179. package/examples/img/7.gif +0 -0
  180. package/examples/img/8.gif +0 -0
  181. package/examples/img/9.gif +0 -0
  182. package/examples/img/age/of1.jpg +0 -0
  183. package/examples/img/age/of2.jpg +0 -0
  184. package/examples/img/age/of3.jpg +0 -0
  185. package/examples/img/age/om1.jpg +0 -0
  186. package/examples/img/age/om2.jpg +0 -0
  187. package/examples/img/age/om3.jpg +0 -0
  188. package/examples/img/age/yf1.jpg +0 -0
  189. package/examples/img/age/yf4.jpg +0 -0
  190. package/examples/img/age/yf5.jpg +0 -0
  191. package/examples/img/age/ym2.jpg +0 -0
  192. package/examples/img/age/ym3.jpg +0 -0
  193. package/examples/img/age/ym5.jpg +0 -0
  194. package/examples/img/backwardN.gif +0 -0
  195. package/examples/img/blue.png +0 -0
  196. package/examples/img/card.png +0 -0
  197. package/examples/img/con1.png +0 -0
  198. package/examples/img/con2.png +0 -0
  199. package/examples/img/fixation.gif +0 -0
  200. package/examples/img/happy_face_1.jpg +0 -0
  201. package/examples/img/happy_face_2.jpg +0 -0
  202. package/examples/img/happy_face_3.jpg +0 -0
  203. package/examples/img/happy_face_4.jpg +0 -0
  204. package/examples/img/inc1.png +0 -0
  205. package/examples/img/inc2.png +0 -0
  206. package/examples/img/normalN.gif +0 -0
  207. package/examples/img/orange.png +0 -0
  208. package/examples/img/redX.png +0 -0
  209. package/examples/img/ribbon.jpg +0 -0
  210. package/examples/img/sad_face_1.jpg +0 -0
  211. package/examples/img/sad_face_2.jpg +0 -0
  212. package/examples/img/sad_face_3.jpg +0 -0
  213. package/examples/img/sad_face_4.jpg +0 -0
  214. package/examples/js/snap.svg-min.js +0 -21
  215. package/examples/js/webgazer/ridgeWorker.mjs +0 -135
  216. package/examples/js/webgazer/webgazer.js +0 -88909
  217. package/examples/js/webgazer/worker_scripts/mat.js +0 -306
  218. package/examples/js/webgazer/worker_scripts/util.js +0 -398
  219. package/examples/jspsych-RDK.html +0 -58
  220. package/examples/jspsych-animation.html +0 -39
  221. package/examples/jspsych-audio-button-response.html +0 -58
  222. package/examples/jspsych-audio-keyboard-response.html +0 -68
  223. package/examples/jspsych-audio-slider-response.html +0 -61
  224. package/examples/jspsych-call-function.html +0 -32
  225. package/examples/jspsych-canvas-button-response.html +0 -95
  226. package/examples/jspsych-canvas-keyboard-response.html +0 -78
  227. package/examples/jspsych-canvas-slider-response.html +0 -67
  228. package/examples/jspsych-categorize-animation.html +0 -49
  229. package/examples/jspsych-categorize-html.html +0 -33
  230. package/examples/jspsych-categorize-image.html +0 -44
  231. package/examples/jspsych-cloze.html +0 -37
  232. package/examples/jspsych-free-sort.html +0 -109
  233. package/examples/jspsych-fullscreen.html +0 -45
  234. package/examples/jspsych-html-button-response.html +0 -43
  235. package/examples/jspsych-html-keyboard-response.html +0 -42
  236. package/examples/jspsych-html-slider-response.html +0 -53
  237. package/examples/jspsych-iat.html +0 -520
  238. package/examples/jspsych-image-button-response.html +0 -91
  239. package/examples/jspsych-image-keyboard-response.html +0 -85
  240. package/examples/jspsych-image-slider-response.html +0 -85
  241. package/examples/jspsych-instructions.html +0 -37
  242. package/examples/jspsych-maxdiff.html +0 -33
  243. package/examples/jspsych-preload.html +0 -140
  244. package/examples/jspsych-reconstruction.html +0 -43
  245. package/examples/jspsych-resize.html +0 -34
  246. package/examples/jspsych-same-different-html.html +0 -28
  247. package/examples/jspsych-same-different-image.html +0 -39
  248. package/examples/jspsych-serial-reaction-time-mouse.html +0 -98
  249. package/examples/jspsych-serial-reaction-time.html +0 -54
  250. package/examples/jspsych-survey-html-form.html +0 -33
  251. package/examples/jspsych-survey-likert.html +0 -42
  252. package/examples/jspsych-survey-multi-choice.html +0 -40
  253. package/examples/jspsych-survey-multi-select.html +0 -42
  254. package/examples/jspsych-survey-text.html +0 -34
  255. package/examples/jspsych-video-button-response.html +0 -65
  256. package/examples/jspsych-video-keyboard-response.html +0 -61
  257. package/examples/jspsych-video-slider-response.html +0 -63
  258. package/examples/jspsych-virtual-chinrest.html +0 -69
  259. package/examples/jspsych-visual-search-circle.html +0 -64
  260. package/examples/jspsych-vsl-animate-occlusion.html +0 -35
  261. package/examples/jspsych-vsl-grid-scene.html +0 -47
  262. package/examples/lexical-decision.html +0 -134
  263. package/examples/manual-preloading.html +0 -59
  264. package/examples/pause-unpause.html +0 -33
  265. package/examples/progress-bar.html +0 -68
  266. package/examples/save-trial-parameters.html +0 -98
  267. package/examples/sound/hammer.mp3 +0 -0
  268. package/examples/sound/sound.mp3 +0 -0
  269. package/examples/sound/speech_blue.mp3 +0 -0
  270. package/examples/sound/speech_green.mp3 +0 -0
  271. package/examples/sound/speech_joke.mp3 +0 -0
  272. package/examples/sound/speech_red.mp3 +0 -0
  273. package/examples/sound/tone.mp3 +0 -0
  274. package/examples/timeline-variables-sampling.html +0 -50
  275. package/examples/timeline-variables.html +0 -64
  276. package/examples/video/sample_video.mp4 +0 -0
  277. package/examples/webgazer.html +0 -174
  278. package/examples/webgazer_audio.html +0 -90
  279. package/examples/webgazer_image.html +0 -60
  280. package/extensions/jspsych-ext-webgazer.js +0 -265
  281. package/jspsych.js +0 -3023
  282. package/license.txt +0 -21
  283. package/mkdocs.yml +0 -118
  284. package/plugins/jspsych-animation.js +0 -189
  285. package/plugins/jspsych-audio-button-response.js +0 -269
  286. package/plugins/jspsych-audio-keyboard-response.js +0 -209
  287. package/plugins/jspsych-audio-slider-response.js +0 -278
  288. package/plugins/jspsych-call-function.js +0 -58
  289. package/plugins/jspsych-canvas-button-response.js +0 -199
  290. package/plugins/jspsych-canvas-keyboard-response.js +0 -155
  291. package/plugins/jspsych-canvas-slider-response.js +0 -207
  292. package/plugins/jspsych-categorize-animation.js +0 -266
  293. package/plugins/jspsych-categorize-html.js +0 -220
  294. package/plugins/jspsych-categorize-image.js +0 -222
  295. package/plugins/jspsych-cloze.js +0 -112
  296. package/plugins/jspsych-external-html.js +0 -112
  297. package/plugins/jspsych-free-sort.js +0 -478
  298. package/plugins/jspsych-fullscreen.js +0 -106
  299. package/plugins/jspsych-html-button-response.js +0 -188
  300. package/plugins/jspsych-html-keyboard-response.js +0 -149
  301. package/plugins/jspsych-html-slider-response.js +0 -202
  302. package/plugins/jspsych-iat-html.js +0 -284
  303. package/plugins/jspsych-iat-image.js +0 -286
  304. package/plugins/jspsych-image-button-response.js +0 -327
  305. package/plugins/jspsych-image-keyboard-response.js +0 -263
  306. package/plugins/jspsych-image-slider-response.js +0 -369
  307. package/plugins/jspsych-instructions.js +0 -237
  308. package/plugins/jspsych-maxdiff.js +0 -173
  309. package/plugins/jspsych-preload.js +0 -345
  310. package/plugins/jspsych-rdk.js +0 -1373
  311. package/plugins/jspsych-reconstruction.js +0 -134
  312. package/plugins/jspsych-resize.js +0 -166
  313. package/plugins/jspsych-same-different-html.js +0 -168
  314. package/plugins/jspsych-same-different-image.js +0 -169
  315. package/plugins/jspsych-serial-reaction-time-mouse.js +0 -212
  316. package/plugins/jspsych-serial-reaction-time.js +0 -247
  317. package/plugins/jspsych-survey-html-form.js +0 -171
  318. package/plugins/jspsych-survey-likert.js +0 -195
  319. package/plugins/jspsych-survey-multi-choice.js +0 -208
  320. package/plugins/jspsych-survey-multi-select.js +0 -232
  321. package/plugins/jspsych-survey-text.js +0 -185
  322. package/plugins/jspsych-video-button-response.js +0 -335
  323. package/plugins/jspsych-video-keyboard-response.js +0 -279
  324. package/plugins/jspsych-video-slider-response.js +0 -351
  325. package/plugins/jspsych-virtual-chinrest.js +0 -471
  326. package/plugins/jspsych-visual-search-circle.js +0 -259
  327. package/plugins/jspsych-vsl-animate-occlusion.js +0 -196
  328. package/plugins/jspsych-vsl-grid-scene.js +0 -103
  329. package/plugins/jspsych-webgazer-calibrate.js +0 -161
  330. package/plugins/jspsych-webgazer-init-camera.js +0 -139
  331. package/plugins/jspsych-webgazer-validate.js +0 -314
  332. package/plugins/template/jspsych-plugin-template.js +0 -35
  333. package/tests/README.md +0 -7
  334. package/tests/jsPsych/case-sensitive-responses.test.js +0 -53
  335. package/tests/jsPsych/css-classes-parameter.test.js +0 -107
  336. package/tests/jsPsych/default-iti.test.js +0 -51
  337. package/tests/jsPsych/default-parameters.test.js +0 -58
  338. package/tests/jsPsych/endexperiment.test.js +0 -49
  339. package/tests/jsPsych/events.test.js +0 -606
  340. package/tests/jsPsych/functions-as-parameters.test.js +0 -210
  341. package/tests/jsPsych/init.test.js +0 -48
  342. package/tests/jsPsych/loads.test.js +0 -7
  343. package/tests/jsPsych/min-rt.test.js +0 -58
  344. package/tests/jsPsych/progressbar.test.js +0 -202
  345. package/tests/jsPsych/timeline-variables.test.js +0 -531
  346. package/tests/jsPsych/timelines.test.js +0 -569
  347. package/tests/jsPsych.data/data-csv-conversion.test.js +0 -85
  348. package/tests/jsPsych.data/data-json-conversion.test.js +0 -120
  349. package/tests/jsPsych.data/datacollection.test.js +0 -117
  350. package/tests/jsPsych.data/datacolumn.test.js +0 -50
  351. package/tests/jsPsych.data/datamodule.test.js +0 -152
  352. package/tests/jsPsych.data/dataparameter.test.js +0 -251
  353. package/tests/jsPsych.data/interactions.test.js +0 -109
  354. package/tests/jsPsych.data/trialparameters.test.js +0 -175
  355. package/tests/jsPsych.extensions/extensions.test.js +0 -207
  356. package/tests/jsPsych.extensions/test-extension.js +0 -42
  357. package/tests/jsPsych.pluginAPI/pluginapi.test.js +0 -365
  358. package/tests/jsPsych.pluginAPI/preloads.test.js +0 -43
  359. package/tests/jsPsych.randomization/randomziation.test.js +0 -27
  360. package/tests/jsPsych.utils/utils.test.js +0 -58
  361. package/tests/plugins/plugin-animation.test.js +0 -34
  362. package/tests/plugins/plugin-audio-button-response.test.js +0 -15
  363. package/tests/plugins/plugin-audio-keyboard-response.test.js +0 -15
  364. package/tests/plugins/plugin-audio-slider-response.test.js +0 -15
  365. package/tests/plugins/plugin-call-function.test.js +0 -49
  366. package/tests/plugins/plugin-categorize-animation.test.js +0 -263
  367. package/tests/plugins/plugin-categorize-html.test.js +0 -17
  368. package/tests/plugins/plugin-categorize-image.test.js +0 -17
  369. package/tests/plugins/plugin-cloze.test.js +0 -157
  370. package/tests/plugins/plugin-free-sort.test.js +0 -106
  371. package/tests/plugins/plugin-fullscreen.test.js +0 -41
  372. package/tests/plugins/plugin-html-button-response.test.js +0 -161
  373. package/tests/plugins/plugin-html-keyboard-response.test.js +0 -139
  374. package/tests/plugins/plugin-html-slider-response.test.js +0 -155
  375. package/tests/plugins/plugin-iat-html.test.js +0 -299
  376. package/tests/plugins/plugin-iat-image.test.js +0 -298
  377. package/tests/plugins/plugin-image-button-response.test.js +0 -174
  378. package/tests/plugins/plugin-image-keyboard-response.test.js +0 -147
  379. package/tests/plugins/plugin-image-slider-response.test.js +0 -174
  380. package/tests/plugins/plugin-instructions.test.js +0 -85
  381. package/tests/plugins/plugin-maxdiff.test.js +0 -39
  382. package/tests/plugins/plugin-preload.test.js +0 -916
  383. package/tests/plugins/plugin-rdk.test.js +0 -61
  384. package/tests/plugins/plugin-reconstruction.test.js +0 -16
  385. package/tests/plugins/plugin-resize.test.js +0 -16
  386. package/tests/plugins/plugin-same-different-html.test.js +0 -17
  387. package/tests/plugins/plugin-same-different-image.test.js +0 -17
  388. package/tests/plugins/plugin-serial-reaction-time-mouse.test.js +0 -42
  389. package/tests/plugins/plugin-serial-reaction-time.test.js +0 -109
  390. package/tests/plugins/plugin-survey-html-form.test.js +0 -44
  391. package/tests/plugins/plugin-survey-likert.test.js +0 -48
  392. package/tests/plugins/plugin-survey-multi-choice.test.js +0 -47
  393. package/tests/plugins/plugin-survey-multi-select.test.js +0 -71
  394. package/tests/plugins/plugin-survey-text.test.js +0 -115
  395. package/tests/plugins/plugin-video-button-response.test.js +0 -32
  396. package/tests/plugins/plugin-video-keyboard-response.test.js +0 -32
  397. package/tests/plugins/plugin-video-slider-response.test.js +0 -31
  398. package/tests/plugins/plugin-visual-search-circle.test.js +0 -16
  399. package/tests/plugins/plugin-vsl-animate-occlusion.test.js +0 -16
  400. package/tests/plugins/plugin-vsl-grid-scene.test.js +0 -16
  401. package/tests/testing-utils.js +0 -13
package/jspsych.js DELETED
@@ -1,3023 +0,0 @@
1
- window.jsPsych = (function() {
2
-
3
- var core = {};
4
-
5
- core.version = function() { return "6.3.0" };
6
-
7
- //
8
- // private variables
9
- //
10
-
11
- // options
12
- var opts = {};
13
- // experiment timeline
14
- var timeline;
15
- // flow control
16
- var global_trial_index = 0;
17
- var current_trial = {};
18
- var current_trial_finished = false;
19
- // target DOM element
20
- var DOM_container;
21
- var DOM_target;
22
- // time that the experiment began
23
- var exp_start_time;
24
- // is the experiment paused?
25
- var paused = false;
26
- var waiting = false;
27
- // done loading?
28
- var loaded = false;
29
- var loadfail = false;
30
- // is the page retrieved directly via file:// protocol (true) or hosted on a server (false)?
31
- var file_protocol = false;
32
-
33
- // storing a single webaudio context to prevent problems with multiple inits
34
- // of jsPsych
35
- core.webaudio_context = null;
36
- // temporary patch for Safari
37
- if (typeof window !== 'undefined' && window.hasOwnProperty('webkitAudioContext') && !window.hasOwnProperty('AudioContext')) {
38
- window.AudioContext = webkitAudioContext;
39
- }
40
- // end patch
41
- core.webaudio_context = (typeof window !== 'undefined' && typeof window.AudioContext !== 'undefined') ? new AudioContext() : null;
42
-
43
- // enumerated variables for special parameter types
44
- core.ALL_KEYS = 'allkeys';
45
- core.NO_KEYS = 'none';
46
-
47
- //
48
- // public methods
49
- //
50
-
51
- core.init = function(options) {
52
- function init() {
53
- if(typeof options.timeline === 'undefined'){
54
- console.error('No timeline declared in jsPsych.init. Cannot start experiment.')
55
- }
56
-
57
- if(options.timeline.length == 0){
58
- console.error('No trials have been added to the timeline (the timeline is an empty array). Cannot start experiment.')
59
- }
60
-
61
- // reset variables
62
- timeline = null;
63
- global_trial_index = 0;
64
- current_trial = {};
65
- current_trial_finished = false;
66
- paused = false;
67
- waiting = false;
68
- loaded = false;
69
- loadfail = false;
70
- file_protocol = false;
71
- jsPsych.data.reset();
72
-
73
- var defaults = {
74
- 'display_element': undefined,
75
- 'on_finish': function(data) {
76
- return undefined;
77
- },
78
- 'on_trial_start': function(trial) {
79
- return undefined;
80
- },
81
- 'on_trial_finish': function() {
82
- return undefined;
83
- },
84
- 'on_data_update': function(data) {
85
- return undefined;
86
- },
87
- 'on_interaction_data_update': function(data){
88
- return undefined;
89
- },
90
- 'on_close': function(){
91
- return undefined;
92
- },
93
- 'use_webaudio': true,
94
- 'exclusions': {},
95
- 'show_progress_bar': false,
96
- 'message_progress_bar': 'Completion Progress',
97
- 'auto_update_progress_bar': true,
98
- 'default_iti': 0,
99
- 'minimum_valid_rt': 0,
100
- 'experiment_width': null,
101
- 'override_safe_mode': false,
102
- 'case_sensitive_responses': false,
103
- 'extensions': []
104
- };
105
-
106
- // detect whether page is running in browser as a local file, and if so, disable web audio and video preloading to prevent CORS issues
107
- if (window.location.protocol == 'file:' && (options.override_safe_mode === false || typeof options.override_safe_mode == 'undefined')) {
108
- options.use_webaudio = false;
109
- file_protocol = true;
110
- console.warn("jsPsych detected that it is running via the file:// protocol and not on a web server. "+
111
- "To prevent issues with cross-origin requests, Web Audio and video preloading have been disabled. "+
112
- "If you would like to override this setting, you can set 'override_safe_mode' to 'true' in jsPsych.init. "+
113
- "For more information, see: https://www.jspsych.org/overview/running-experiments");
114
- }
115
-
116
- // override default options if user specifies an option
117
- opts = Object.assign({}, defaults, options);
118
-
119
- // set DOM element where jsPsych will render content
120
- // if undefined, then jsPsych will use the <body> tag and the entire page
121
- if(typeof opts.display_element == 'undefined'){
122
- // check if there is a body element on the page
123
- var body = document.querySelector('body');
124
- if (body === null) {
125
- document.documentElement.appendChild(document.createElement('body'));
126
- }
127
- // using the full page, so we need the HTML element to
128
- // have 100% height, and body to be full width and height with
129
- // no margin
130
- document.querySelector('html').style.height = '100%';
131
- document.querySelector('body').style.margin = '0px';
132
- document.querySelector('body').style.height = '100%';
133
- document.querySelector('body').style.width = '100%';
134
- opts.display_element = document.querySelector('body');
135
- } else {
136
- // make sure that the display element exists on the page
137
- var display;
138
- if (opts.display_element instanceof Element) {
139
- var display = opts.display_element;
140
- } else {
141
- var display = document.querySelector('#' + opts.display_element);
142
- }
143
- if(display === null) {
144
- console.error('The display_element specified in jsPsych.init() does not exist in the DOM.');
145
- } else {
146
- opts.display_element = display;
147
- }
148
- }
149
- opts.display_element.innerHTML = '<div class="jspsych-content-wrapper"><div id="jspsych-content"></div></div>';
150
- DOM_container = opts.display_element;
151
- DOM_target = document.querySelector('#jspsych-content');
152
-
153
-
154
- // add tabIndex attribute to scope event listeners
155
- opts.display_element.tabIndex = 0;
156
-
157
- // add CSS class to DOM_target
158
- if(opts.display_element.className.indexOf('jspsych-display-element') == -1){
159
- opts.display_element.className += ' jspsych-display-element';
160
- }
161
- DOM_target.className += 'jspsych-content';
162
-
163
- // set experiment_width if not null
164
- if(opts.experiment_width !== null){
165
- DOM_target.style.width = opts.experiment_width + "px";
166
- }
167
-
168
- // create experiment timeline
169
- timeline = new TimelineNode({
170
- timeline: opts.timeline
171
- });
172
-
173
- // initialize audio context based on options and browser capabilities
174
- jsPsych.pluginAPI.initAudio();
175
-
176
- // below code resets event listeners that may have lingered from
177
- // a previous incomplete experiment loaded in same DOM.
178
- jsPsych.pluginAPI.reset(opts.display_element);
179
- // create keyboard event listeners
180
- jsPsych.pluginAPI.createKeyboardEventListeners(opts.display_element);
181
- // create listeners for user browser interaction
182
- jsPsych.data.createInteractionListeners();
183
-
184
- // add event for closing window
185
- window.addEventListener('beforeunload', opts.on_close);
186
-
187
- // check exclusions before continuing
188
- checkExclusions(opts.exclusions,
189
- function(){
190
- // success! user can continue...
191
- // start experiment
192
- loadExtensions();
193
- },
194
- function(){
195
- // fail. incompatible user.
196
- }
197
- );
198
-
199
- function loadExtensions() {
200
- // run the .initialize method of any extensions that are in use
201
- // these should return a Promise to indicate when loading is complete
202
- if (opts.extensions.length == 0) {
203
- startExperiment();
204
- } else {
205
- var loaded_extensions = 0;
206
- for (var i = 0; i < opts.extensions.length; i++) {
207
- var ext_params = opts.extensions[i].params;
208
- if (!ext_params) {
209
- ext_params = {}
210
- }
211
- jsPsych.extensions[opts.extensions[i].type].initialize(ext_params)
212
- .then(() => {
213
- loaded_extensions++;
214
- if (loaded_extensions == opts.extensions.length) {
215
- startExperiment();
216
- }
217
- })
218
- .catch((error_message) => {
219
- console.error(error_message);
220
- })
221
- }
222
- }
223
- }
224
-
225
- };
226
-
227
- // execute init() when the document is ready
228
- if (document.readyState === "complete") {
229
- init();
230
- } else {
231
- window.addEventListener("load", init);
232
- }
233
- }
234
-
235
- core.progress = function() {
236
-
237
- var percent_complete = typeof timeline == 'undefined' ? 0 : timeline.percentComplete();
238
-
239
- var obj = {
240
- "total_trials": typeof timeline == 'undefined' ? undefined : timeline.length(),
241
- "current_trial_global": global_trial_index,
242
- "percent_complete": percent_complete
243
- };
244
-
245
- return obj;
246
- };
247
-
248
- core.startTime = function() {
249
- return exp_start_time;
250
- };
251
-
252
- core.totalTime = function() {
253
- if(typeof exp_start_time == 'undefined'){ return 0; }
254
- return (new Date()).getTime() - exp_start_time.getTime();
255
- };
256
-
257
- core.getDisplayElement = function() {
258
- return DOM_target;
259
- };
260
-
261
- core.getDisplayContainerElement = function(){
262
- return DOM_container;
263
- }
264
-
265
- core.finishTrial = function(data) {
266
-
267
- if(current_trial_finished){ return; }
268
- current_trial_finished = true;
269
-
270
- // remove any CSS classes that were added to the DOM via css_classes parameter
271
- if(typeof current_trial.css_classes !== 'undefined' && Array.isArray(current_trial.css_classes)){
272
- DOM_target.classList.remove(...current_trial.css_classes);
273
- }
274
-
275
- // write the data from the trial
276
- data = typeof data == 'undefined' ? {} : data;
277
- jsPsych.data.write(data);
278
-
279
- // get back the data with all of the defaults in
280
- var trial_data = jsPsych.data.get().filter({trial_index: global_trial_index});
281
-
282
- // for trial-level callbacks, we just want to pass in a reference to the values
283
- // of the DataCollection, for easy access and editing.
284
- var trial_data_values = trial_data.values()[0];
285
-
286
- if(typeof current_trial.save_trial_parameters == 'object'){
287
- var keys = Object.keys(current_trial.save_trial_parameters);
288
- for(var i=0; i<keys.length; i++){
289
- var key_val = current_trial.save_trial_parameters[keys[i]];
290
- if(key_val === true){
291
- if(typeof current_trial[keys[i]] == 'undefined'){
292
- console.warn(`Invalid parameter specified in save_trial_parameters. Trial has no property called "${keys[i]}".`)
293
- } else if(typeof current_trial[keys[i]] == 'function'){
294
- trial_data_values[keys[i]] = current_trial[keys[i]].toString();
295
- } else {
296
- trial_data_values[keys[i]] = current_trial[keys[i]];
297
- }
298
- }
299
- if(key_val === false){
300
- // we don't allow internal_node_id or trial_index to be deleted because it would break other things
301
- if(keys[i] !== 'internal_node_id' && keys[i] !== 'trial_index'){
302
- delete trial_data_values[keys[i]];
303
- }
304
- }
305
- }
306
- }
307
- // handle extension callbacks
308
- if(Array.isArray(current_trial.extensions)){
309
- for(var i=0; i<current_trial.extensions.length; i++){
310
- var ext_data_values = jsPsych.extensions[current_trial.extensions[i].type].on_finish(current_trial.extensions[i].params);
311
- Object.assign(trial_data_values, ext_data_values);
312
- }
313
- }
314
-
315
- // about to execute lots of callbacks, so switch context.
316
- jsPsych.internal.call_immediate = true;
317
-
318
- // handle callback at plugin level
319
- if (typeof current_trial.on_finish === 'function') {
320
- current_trial.on_finish(trial_data_values);
321
- }
322
-
323
- // handle callback at whole-experiment level
324
- opts.on_trial_finish(trial_data_values);
325
-
326
- // after the above callbacks are complete, then the data should be finalized
327
- // for this trial. call the on_data_update handler, passing in the same
328
- // data object that just went through the trial's finish handlers.
329
- opts.on_data_update(trial_data_values);
330
-
331
- // done with callbacks
332
- jsPsych.internal.call_immediate = false;
333
-
334
- // wait for iti
335
- if (typeof current_trial.post_trial_gap === null || typeof current_trial.post_trial_gap === 'undefined') {
336
- if (opts.default_iti > 0) {
337
- setTimeout(nextTrial, opts.default_iti);
338
- } else {
339
- nextTrial();
340
- }
341
- } else {
342
- if (current_trial.post_trial_gap > 0) {
343
- setTimeout(nextTrial, current_trial.post_trial_gap);
344
- } else {
345
- nextTrial();
346
- }
347
- }
348
- }
349
-
350
- core.endExperiment = function(end_message) {
351
- timeline.end_message = end_message;
352
- timeline.end();
353
- jsPsych.pluginAPI.cancelAllKeyboardResponses();
354
- jsPsych.pluginAPI.clearAllTimeouts();
355
- core.finishTrial();
356
- }
357
-
358
- core.endCurrentTimeline = function() {
359
- timeline.endActiveNode();
360
- }
361
-
362
- core.currentTrial = function() {
363
- return current_trial;
364
- };
365
-
366
- core.initSettings = function() {
367
- return opts;
368
- };
369
-
370
- core.currentTimelineNodeID = function() {
371
- return timeline.activeID();
372
- };
373
-
374
- core.timelineVariable = function(varname, immediate){
375
- if(typeof immediate == 'undefined'){ immediate = false; }
376
- if(jsPsych.internal.call_immediate || immediate === true){
377
- return timeline.timelineVariable(varname);
378
- } else {
379
- return function() { return timeline.timelineVariable(varname); }
380
- }
381
- }
382
-
383
- core.allTimelineVariables = function(){
384
- return timeline.allTimelineVariables();
385
- }
386
-
387
- core.addNodeToEndOfTimeline = function(new_timeline, preload_callback){
388
- timeline.insert(new_timeline);
389
- }
390
-
391
- core.pauseExperiment = function(){
392
- paused = true;
393
- }
394
-
395
- core.resumeExperiment = function(){
396
- paused = false;
397
- if(waiting){
398
- waiting = false;
399
- nextTrial();
400
- }
401
- }
402
-
403
- core.loadFail = function(message){
404
- message = message || '<p>The experiment failed to load.</p>';
405
- loadfail = true;
406
- DOM_target.innerHTML = message;
407
- }
408
-
409
- core.getSafeModeStatus = function() {
410
- return file_protocol;
411
- }
412
-
413
- function TimelineNode(parameters, parent, relativeID) {
414
-
415
- // a unique ID for this node, relative to the parent
416
- var relative_id;
417
-
418
- // store the parent for this node
419
- var parent_node;
420
-
421
- // parameters for the trial if the node contains a trial
422
- var trial_parameters;
423
-
424
- // parameters for nodes that contain timelines
425
- var timeline_parameters;
426
-
427
- // stores trial information on a node that contains a timeline
428
- // used for adding new trials
429
- var node_trial_data;
430
-
431
- // track progress through the node
432
- var progress = {
433
- current_location: -1, // where on the timeline (which timelinenode)
434
- current_variable_set: 0, // which set of variables to use from timeline_variables
435
- current_repetition: 0, // how many times through the variable set on this run of the node
436
- current_iteration: 0, // how many times this node has been revisited
437
- done: false
438
- }
439
-
440
- // reference to self
441
- var self = this;
442
-
443
- // recursively get the next trial to run.
444
- // if this node is a leaf (trial), then return the trial.
445
- // otherwise, recursively find the next trial in the child timeline.
446
- this.trial = function() {
447
- if (typeof timeline_parameters == 'undefined') {
448
- // returns a clone of the trial_parameters to
449
- // protect functions.
450
- return jsPsych.utils.deepCopy(trial_parameters);
451
- } else {
452
- if (progress.current_location >= timeline_parameters.timeline.length) {
453
- return null;
454
- } else {
455
- return timeline_parameters.timeline[progress.current_location].trial();
456
- }
457
- }
458
- }
459
-
460
- this.markCurrentTrialComplete = function() {
461
- if(typeof timeline_parameters == 'undefined'){
462
- progress.done = true;
463
- } else {
464
- timeline_parameters.timeline[progress.current_location].markCurrentTrialComplete();
465
- }
466
- }
467
-
468
- this.nextRepetiton = function() {
469
- this.setTimelineVariablesOrder();
470
- progress.current_location = -1;
471
- progress.current_variable_set = 0;
472
- progress.current_repetition++;
473
- for (var i = 0; i < timeline_parameters.timeline.length; i++) {
474
- timeline_parameters.timeline[i].reset();
475
- }
476
- }
477
-
478
- // set the order for going through the timeline variables array
479
- this.setTimelineVariablesOrder = function() {
480
-
481
- // check to make sure this node has variables
482
- if(typeof timeline_parameters === 'undefined' || typeof timeline_parameters.timeline_variables === 'undefined'){
483
- return;
484
- }
485
-
486
- var order = [];
487
- for(var i=0; i<timeline_parameters.timeline_variables.length; i++){
488
- order.push(i);
489
- }
490
-
491
- if(typeof timeline_parameters.sample !== 'undefined'){
492
- if(timeline_parameters.sample.type == 'custom'){
493
- order = timeline_parameters.sample.fn(order);
494
- } else if(timeline_parameters.sample.type == 'with-replacement'){
495
- order = jsPsych.randomization.sampleWithReplacement(order, timeline_parameters.sample.size, timeline_parameters.sample.weights);
496
- } else if(timeline_parameters.sample.type == 'without-replacement'){
497
- order = jsPsych.randomization.sampleWithoutReplacement(order, timeline_parameters.sample.size);
498
- } else if(timeline_parameters.sample.type == 'fixed-repetitions'){
499
- order = jsPsych.randomization.repeat(order, timeline_parameters.sample.size, false);
500
- } else if(timeline_parameters.sample.type == 'alternate-groups'){
501
- order = jsPsych.randomization.shuffleAlternateGroups(timeline_parameters.sample.groups, timeline_parameters.sample.randomize_group_order);
502
- } else {
503
- console.error('Invalid type in timeline sample parameters. Valid options for type are "custom", "with-replacement", "without-replacement", "fixed-repetitions", and "alternate-groups"');
504
- }
505
- }
506
-
507
- if(timeline_parameters.randomize_order) {
508
- order = jsPsych.randomization.shuffle(order);
509
- }
510
-
511
- progress.order = order;
512
- }
513
-
514
- // next variable set
515
- this.nextSet = function() {
516
- progress.current_location = -1;
517
- progress.current_variable_set++;
518
- for (var i = 0; i < timeline_parameters.timeline.length; i++) {
519
- timeline_parameters.timeline[i].reset();
520
- }
521
- }
522
-
523
- // update the current trial node to be completed
524
- // returns true if the node is complete after advance (all subnodes are also complete)
525
- // returns false otherwise
526
- this.advance = function () {
527
-
528
- // first check to see if done
529
- if (progress.done) {
530
- return true;
531
- }
532
-
533
- // if node has not started yet (progress.current_location == -1),
534
- // then try to start the node.
535
- if (progress.current_location == -1) {
536
- // check for on_timeline_start and conditonal function on nodes with timelines
537
- if (typeof timeline_parameters !== 'undefined') {
538
- // only run the conditional function if this is the first repetition of the timeline when
539
- // repetitions > 1, and only when on the first variable set
540
- if (typeof timeline_parameters.conditional_function !== 'undefined' && progress.current_repetition == 0 && progress.current_variable_set == 0) {
541
- jsPsych.internal.call_immediate = true;
542
- var conditional_result = timeline_parameters.conditional_function();
543
- jsPsych.internal.call_immediate = false;
544
- // if the conditional_function() returns false, then the timeline
545
- // doesn't run and is marked as complete.
546
- if (conditional_result == false) {
547
- progress.done = true;
548
- return true;
549
- }
550
- }
551
-
552
- // if we reach this point then the node has its own timeline and will start
553
- // so we need to check if there is an on_timeline_start function if we are on the first variable set
554
- if (typeof timeline_parameters.on_timeline_start !== 'undefined' && progress.current_variable_set == 0) {
555
- timeline_parameters.on_timeline_start();
556
- }
557
-
558
-
559
- }
560
- // if we reach this point, then either the node doesn't have a timeline of the
561
- // conditional function returned true and it can start
562
- progress.current_location = 0;
563
- // call advance again on this node now that it is pointing to a new location
564
- return this.advance();
565
- }
566
-
567
- // if this node has a timeline, propogate down to the current trial.
568
- if (typeof timeline_parameters !== 'undefined') {
569
-
570
- var have_node_to_run = false;
571
- // keep incrementing the location in the timeline until one of the nodes reached is incomplete
572
- while (progress.current_location < timeline_parameters.timeline.length && have_node_to_run == false) {
573
-
574
- // check to see if the node currently pointed at is done
575
- var target_complete = timeline_parameters.timeline[progress.current_location].advance();
576
- if (!target_complete) {
577
- have_node_to_run = true;
578
- return false;
579
- } else {
580
- progress.current_location++;
581
- }
582
-
583
- }
584
-
585
- // if we've reached the end of the timeline (which, if the code is here, we have)
586
-
587
- // there are a few steps to see what to do next...
588
-
589
- // first, check the timeline_variables to see if we need to loop through again
590
- // with a new set of variables
591
- if (progress.current_variable_set < progress.order.length - 1) {
592
- // reset the progress of the node to be with the new set
593
- this.nextSet();
594
- // then try to advance this node again.
595
- return this.advance();
596
- }
597
-
598
- // if we're all done with the timeline_variables, then check to see if there are more repetitions
599
- else if (progress.current_repetition < timeline_parameters.repetitions - 1) {
600
- this.nextRepetiton();
601
- // check to see if there is an on_timeline_finish function
602
- if (typeof timeline_parameters.on_timeline_finish !== 'undefined') {
603
- timeline_parameters.on_timeline_finish();
604
- }
605
- return this.advance();
606
- }
607
-
608
-
609
- // if we're all done with the repetitions...
610
- else {
611
- // check to see if there is an on_timeline_finish function
612
- if (typeof timeline_parameters.on_timeline_finish !== 'undefined') {
613
- timeline_parameters.on_timeline_finish();
614
- }
615
-
616
- // if we're all done with the repetitions, check if there is a loop function.
617
- if (typeof timeline_parameters.loop_function !== 'undefined') {
618
- jsPsych.internal.call_immediate = true;
619
- if (timeline_parameters.loop_function(this.generatedData())) {
620
- this.reset();
621
- jsPsych.internal.call_immediate = false;
622
- return parent_node.advance();
623
- } else {
624
- progress.done = true;
625
- jsPsych.internal.call_immediate = false;
626
- return true;
627
- }
628
- }
629
-
630
-
631
- }
632
-
633
- // no more loops on this timeline, we're done!
634
- progress.done = true;
635
- return true;
636
- }
637
- }
638
-
639
- // check the status of the done flag
640
- this.isComplete = function() {
641
- return progress.done;
642
- }
643
-
644
- // getter method for timeline variables
645
- this.getTimelineVariableValue = function(variable_name){
646
- if(typeof timeline_parameters == 'undefined'){
647
- return undefined;
648
- }
649
- var v = timeline_parameters.timeline_variables[progress.order[progress.current_variable_set]][variable_name];
650
- return v;
651
- }
652
-
653
- // recursive upward search for timeline variables
654
- this.findTimelineVariable = function(variable_name){
655
- var v = this.getTimelineVariableValue(variable_name);
656
- if(typeof v == 'undefined'){
657
- if(typeof parent_node !== 'undefined'){
658
- return parent_node.findTimelineVariable(variable_name);
659
- } else {
660
- return undefined;
661
- }
662
- } else {
663
- return v;
664
- }
665
- }
666
-
667
- // recursive downward search for active trial to extract timeline variable
668
- this.timelineVariable = function(variable_name){
669
- if(typeof timeline_parameters == 'undefined'){
670
- return this.findTimelineVariable(variable_name);
671
- } else {
672
- // if progress.current_location is -1, then the timeline variable is being evaluated
673
- // in a function that runs prior to the trial starting, so we should treat that trial
674
- // as being the active trial for purposes of finding the value of the timeline variable
675
- var loc = Math.max(0, progress.current_location);
676
- // if loc is greater than the number of elements on this timeline, then the timeline
677
- // variable is being evaluated in a function that runs after the trial on the timeline
678
- // are complete but before advancing to the next (like a loop_function).
679
- // treat the last active trial as the active trial for this purpose.
680
- if(loc == timeline_parameters.timeline.length){
681
- loc = loc - 1;
682
- }
683
- // now find the variable
684
- return timeline_parameters.timeline[loc].timelineVariable(variable_name);
685
- }
686
- }
687
-
688
- // recursively get all the timeline variables for this trial
689
- this.allTimelineVariables = function(){
690
- var all_tvs = this.allTimelineVariablesNames();
691
- var all_tvs_vals = {};
692
- for(var i=0; i<all_tvs.length; i++){
693
- all_tvs_vals[all_tvs[i]] = this.timelineVariable(all_tvs[i])
694
- }
695
- return all_tvs_vals;
696
- }
697
-
698
- // helper to get all the names at this stage.
699
- this.allTimelineVariablesNames = function(so_far){
700
- if(typeof so_far == 'undefined'){
701
- so_far = [];
702
- }
703
- if(typeof timeline_parameters !== 'undefined'){
704
- so_far = so_far.concat(Object.keys(timeline_parameters.timeline_variables[progress.order[progress.current_variable_set]]));
705
- // if progress.current_location is -1, then the timeline variable is being evaluated
706
- // in a function that runs prior to the trial starting, so we should treat that trial
707
- // as being the active trial for purposes of finding the value of the timeline variable
708
- var loc = Math.max(0, progress.current_location);
709
- // if loc is greater than the number of elements on this timeline, then the timeline
710
- // variable is being evaluated in a function that runs after the trial on the timeline
711
- // are complete but before advancing to the next (like a loop_function).
712
- // treat the last active trial as the active trial for this purpose.
713
- if(loc == timeline_parameters.timeline.length){
714
- loc = loc - 1;
715
- }
716
- // now find the variable
717
- return timeline_parameters.timeline[loc].allTimelineVariablesNames(so_far);
718
- }
719
- if(typeof timeline_parameters == 'undefined'){
720
- return so_far;
721
- }
722
- }
723
-
724
- // recursively get the number of **trials** contained in the timeline
725
- // assuming that while loops execute exactly once and if conditionals
726
- // always run
727
- this.length = function() {
728
- var length = 0;
729
- if (typeof timeline_parameters !== 'undefined') {
730
- for (var i = 0; i < timeline_parameters.timeline.length; i++) {
731
- length += timeline_parameters.timeline[i].length();
732
- }
733
- } else {
734
- return 1;
735
- }
736
- return length;
737
- }
738
-
739
- // return the percentage of trials completed, grouped at the first child level
740
- // counts a set of trials as complete when the child node is done
741
- this.percentComplete = function() {
742
- var total_trials = this.length();
743
- var completed_trials = 0;
744
- for (var i = 0; i < timeline_parameters.timeline.length; i++) {
745
- if (timeline_parameters.timeline[i].isComplete()) {
746
- completed_trials += timeline_parameters.timeline[i].length();
747
- }
748
- }
749
- return (completed_trials / total_trials * 100)
750
- }
751
-
752
- // resets the node and all subnodes to original state
753
- // but increments the current_iteration counter
754
- this.reset = function() {
755
- progress.current_location = -1;
756
- progress.current_repetition = 0;
757
- progress.current_variable_set = 0;
758
- progress.current_iteration++;
759
- progress.done = false;
760
- this.setTimelineVariablesOrder();
761
- if (typeof timeline_parameters != 'undefined') {
762
- for (var i = 0; i < timeline_parameters.timeline.length; i++) {
763
- timeline_parameters.timeline[i].reset();
764
- }
765
- }
766
-
767
- }
768
-
769
- // mark this node as finished
770
- this.end = function() {
771
- progress.done = true;
772
- }
773
-
774
- // recursively end whatever sub-node is running the current trial
775
- this.endActiveNode = function() {
776
- if (typeof timeline_parameters == 'undefined') {
777
- this.end();
778
- parent_node.end();
779
- } else {
780
- timeline_parameters.timeline[progress.current_location].endActiveNode();
781
- }
782
- }
783
-
784
- // get a unique ID associated with this node
785
- // the ID reflects the current iteration through this node.
786
- this.ID = function() {
787
- var id = "";
788
- if (typeof parent_node == 'undefined') {
789
- return "0." + progress.current_iteration;
790
- } else {
791
- id += parent_node.ID() + "-";
792
- id += relative_id + "." + progress.current_iteration;
793
- return id;
794
- }
795
- }
796
-
797
- // get the ID of the active trial
798
- this.activeID = function() {
799
- if (typeof timeline_parameters == 'undefined') {
800
- return this.ID();
801
- } else {
802
- return timeline_parameters.timeline[progress.current_location].activeID();
803
- }
804
- }
805
-
806
- // get all the data generated within this node
807
- this.generatedData = function() {
808
- return jsPsych.data.getDataByTimelineNode(this.ID());
809
- }
810
-
811
- // get all the trials of a particular type
812
- this.trialsOfType = function(type) {
813
- if (typeof timeline_parameters == 'undefined'){
814
- if (trial_parameters.type == type) {
815
- return trial_parameters;
816
- } else {
817
- return [];
818
- }
819
- } else {
820
- var trials = [];
821
- for (var i = 0; i < timeline_parameters.timeline.length; i++) {
822
- var t = timeline_parameters.timeline[i].trialsOfType(type);
823
- trials = trials.concat(t);
824
- }
825
- return trials;
826
- }
827
- }
828
-
829
- // add new trials to end of this timeline
830
- this.insert = function(parameters){
831
- if(typeof timeline_parameters == 'undefined'){
832
- console.error('Cannot add new trials to a trial-level node.');
833
- } else {
834
- timeline_parameters.timeline.push(
835
- new TimelineNode(Object.assign({}, node_trial_data, parameters), self, timeline_parameters.timeline.length)
836
- );
837
- }
838
- }
839
-
840
- // constructor
841
- var _construct = function() {
842
-
843
- // store a link to the parent of this node
844
- parent_node = parent;
845
-
846
- // create the ID for this node
847
- if (typeof parent == 'undefined') {
848
- relative_id = 0;
849
- } else {
850
- relative_id = relativeID;
851
- }
852
-
853
- // check if there is a timeline parameter
854
- // if there is, then this node has its own timeline
855
- if ((typeof parameters.timeline !== 'undefined') || (typeof jsPsych.plugins[trial_type] == 'function')) {
856
-
857
- // create timeline properties
858
- timeline_parameters = {
859
- timeline: [],
860
- loop_function: parameters.loop_function,
861
- conditional_function: parameters.conditional_function,
862
- sample: parameters.sample,
863
- randomize_order: typeof parameters.randomize_order == 'undefined' ? false : parameters.randomize_order,
864
- repetitions: typeof parameters.repetitions == 'undefined' ? 1 : parameters.repetitions,
865
- timeline_variables: typeof parameters.timeline_variables == 'undefined' ? [{}] : parameters.timeline_variables,
866
- on_timeline_finish: parameters.on_timeline_finish,
867
- on_timeline_start: parameters.on_timeline_start,
868
- };
869
-
870
- self.setTimelineVariablesOrder();
871
-
872
- // extract all of the node level data and parameters
873
- // but remove all of the timeline-level specific information
874
- // since this will be used to copy things down hierarchically
875
- var node_data = Object.assign({}, parameters);
876
- delete node_data.timeline;
877
- delete node_data.conditional_function;
878
- delete node_data.loop_function;
879
- delete node_data.randomize_order;
880
- delete node_data.repetitions;
881
- delete node_data.timeline_variables;
882
- delete node_data.sample;
883
- delete node_data.on_timeline_start;
884
- delete node_data.on_timeline_finish;
885
- node_trial_data = node_data; // store for later...
886
-
887
- // create a TimelineNode for each element in the timeline
888
- for (var i = 0; i < parameters.timeline.length; i++) {
889
- // merge parameters
890
- var merged_parameters = Object.assign({}, node_data, parameters.timeline[i]);
891
- // merge any data from the parent node into child nodes
892
- if(typeof node_data.data == 'object' && typeof parameters.timeline[i].data == 'object'){
893
- var merged_data = Object.assign({}, node_data.data, parameters.timeline[i].data);
894
- merged_parameters.data = merged_data;
895
- }
896
- timeline_parameters.timeline.push(new TimelineNode(merged_parameters, self, i));
897
- }
898
- }
899
- // if there is no timeline parameter, then this node is a trial node
900
- else {
901
- // check to see if a valid trial type is defined
902
- var trial_type = parameters.type;
903
- if (typeof trial_type == 'undefined') {
904
- console.error('Trial level node is missing the "type" parameter. The parameters for the node are: ' + JSON.stringify(parameters));
905
- } else if ((typeof jsPsych.plugins[trial_type] == 'undefined') && (trial_type.toString().replace(/\s/g,'') != "function(){returntimeline.timelineVariable(varname);}")) {
906
- console.error('No plugin loaded for trials of type "' + trial_type + '"');
907
- }
908
- // create a deep copy of the parameters for the trial
909
- trial_parameters = Object.assign({}, parameters);
910
- }
911
-
912
- }();
913
- }
914
-
915
- function startExperiment() {
916
-
917
- loaded = true;
918
-
919
- // show progress bar if requested
920
- if (opts.show_progress_bar === true) {
921
- drawProgressBar(opts.message_progress_bar);
922
- }
923
-
924
- // record the start time
925
- exp_start_time = new Date();
926
-
927
- // begin!
928
- timeline.advance();
929
- doTrial(timeline.trial());
930
-
931
- }
932
-
933
- function finishExperiment() {
934
-
935
- if(typeof timeline.end_message !== 'undefined'){
936
- DOM_target.innerHTML = timeline.end_message;
937
- }
938
-
939
- opts.on_finish(jsPsych.data.get());
940
-
941
- }
942
-
943
- function nextTrial() {
944
- // if experiment is paused, don't do anything.
945
- if(paused) {
946
- waiting = true;
947
- return;
948
- }
949
-
950
- global_trial_index++;
951
-
952
- // advance timeline
953
- timeline.markCurrentTrialComplete();
954
- var complete = timeline.advance();
955
-
956
- // update progress bar if shown
957
- if (opts.show_progress_bar === true && opts.auto_update_progress_bar == true) {
958
- updateProgressBar();
959
- }
960
-
961
- // check if experiment is over
962
- if (complete) {
963
- finishExperiment();
964
- return;
965
- }
966
-
967
- doTrial(timeline.trial());
968
- }
969
-
970
- function doTrial(trial) {
971
-
972
- current_trial = trial;
973
- current_trial_finished = false;
974
-
975
- // process all timeline variables for this trial
976
- evaluateTimelineVariables(trial);
977
-
978
- // evaluate variables that are functions
979
- evaluateFunctionParameters(trial);
980
-
981
- // get default values for parameters
982
- setDefaultValues(trial);
983
-
984
- // about to execute callbacks
985
- jsPsych.internal.call_immediate = true;
986
-
987
- // call experiment wide callback
988
- opts.on_trial_start(trial);
989
-
990
- // call trial specific callback if it exists
991
- if(typeof trial.on_start == 'function'){
992
- trial.on_start(trial);
993
- }
994
-
995
- // call any on_start functions for extensions
996
- if(Array.isArray(trial.extensions)){
997
- for(var i=0; i<trial.extensions.length; i++){
998
- jsPsych.extensions[trial.extensions[i].type].on_start(current_trial.extensions[i].params);
999
- }
1000
- }
1001
-
1002
- // apply the focus to the element containing the experiment.
1003
- DOM_container.focus();
1004
-
1005
- // reset the scroll on the DOM target
1006
- DOM_target.scrollTop = 0;
1007
-
1008
- // add CSS classes to the DOM_target if they exist in trial.css_classes
1009
- if(typeof trial.css_classes !== 'undefined'){
1010
- if(!Array.isArray(trial.css_classes) && typeof trial.css_classes == 'string'){
1011
- trial.css_classes = [trial.css_classes];
1012
- }
1013
- if(Array.isArray(trial.css_classes)){
1014
- DOM_target.classList.add(...trial.css_classes)
1015
- }
1016
- }
1017
-
1018
- // execute trial method
1019
- jsPsych.plugins[trial.type].trial(DOM_target, trial);
1020
-
1021
- // call trial specific loaded callback if it exists
1022
- if(typeof trial.on_load == 'function'){
1023
- trial.on_load();
1024
- }
1025
-
1026
- // call any on_load functions for extensions
1027
- if(Array.isArray(trial.extensions)){
1028
- for(var i=0; i<trial.extensions.length; i++){
1029
- jsPsych.extensions[trial.extensions[i].type].on_load(current_trial.extensions[i].params);
1030
- }
1031
- }
1032
-
1033
- // done with callbacks
1034
- jsPsych.internal.call_immediate = false;
1035
- }
1036
-
1037
- function evaluateTimelineVariables(trial){
1038
- var keys = Object.keys(trial);
1039
-
1040
- for (var i = 0; i < keys.length; i++) {
1041
- // timeline variables on the root level
1042
- if (typeof trial[keys[i]] == "function" && trial[keys[i]].toString().replace(/\s/g,'') == "function(){returntimeline.timelineVariable(varname);}") {
1043
- trial[keys[i]] = trial[keys[i]].call();
1044
- }
1045
- // timeline variables that are nested in objects
1046
- if (typeof trial[keys[i]] == "object" && trial[keys[i]] !== null){
1047
- evaluateTimelineVariables(trial[keys[i]]);
1048
- }
1049
- }
1050
- }
1051
-
1052
- function evaluateFunctionParameters(trial){
1053
-
1054
- // set a flag so that jsPsych.timelineVariable() is immediately executed in this context
1055
- jsPsych.internal.call_immediate = true;
1056
-
1057
- // first, eval the trial type if it is a function
1058
- // this lets users set the plugin type with a function
1059
- if(typeof trial.type === 'function'){
1060
- trial.type = trial.type.call();
1061
- }
1062
-
1063
- // now eval the whole trial
1064
-
1065
- // start by getting a list of the parameters
1066
- var keys = Object.keys(trial);
1067
-
1068
- // iterate over each parameter
1069
- for (var i = 0; i < keys.length; i++) {
1070
- // check to make sure parameter is not "type", since that was eval'd above.
1071
- if(keys[i] !== 'type'){
1072
- // 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.
1073
- // the first line checks if the parameter is defined in the universalPluginParameters set
1074
- // the second line checks the plugin-specific parameters
1075
- if(typeof jsPsych.plugins.universalPluginParameters[keys[i]] !== 'undefined' &&
1076
- jsPsych.plugins.universalPluginParameters[keys[i]].type !== jsPsych.plugins.parameterType.FUNCTION ){
1077
- trial[keys[i]] = replaceFunctionsWithValues(trial[keys[i]], null);
1078
- }
1079
- if(typeof jsPsych.plugins[trial.type].info.parameters[keys[i]] !== 'undefined' &&
1080
- jsPsych.plugins[trial.type].info.parameters[keys[i]].type !== jsPsych.plugins.parameterType.FUNCTION){
1081
- trial[keys[i]] = replaceFunctionsWithValues(trial[keys[i]], jsPsych.plugins[trial.type].info.parameters[keys[i]]);
1082
- }
1083
- }
1084
- }
1085
- // reset so jsPsych.timelineVariable() is no longer immediately executed
1086
- jsPsych.internal.call_immediate = false;
1087
- }
1088
-
1089
- function replaceFunctionsWithValues(obj, info){
1090
- // null typeof is 'object' (?!?!), so need to run this first!
1091
- if(obj === null){
1092
- return obj;
1093
- }
1094
- // arrays
1095
- else if(Array.isArray(obj)){
1096
- for(var i=0; i<obj.length; i++){
1097
- obj[i] = replaceFunctionsWithValues(obj[i], info);
1098
- }
1099
- }
1100
- // objects
1101
- else if(typeof obj === 'object'){
1102
- var keys = Object.keys(obj);
1103
- if(info == null || !info.nested){
1104
- for(var i=0; i<keys.length; i++){
1105
- obj[keys[i]] = replaceFunctionsWithValues(obj[keys[i]], null)
1106
- }
1107
- } else {
1108
- for(var i=0; i<keys.length; i++){
1109
- if(typeof info.nested[keys[i]] == 'object' && info.nested[keys[i]].type !== jsPsych.plugins.parameterType.FUNCTION){
1110
- obj[keys[i]] = replaceFunctionsWithValues(obj[keys[i]], info.nested[keys[i]])
1111
- }
1112
- }
1113
- }
1114
- }
1115
- else if(typeof obj === 'function'){
1116
- return obj();
1117
- }
1118
- return obj;
1119
- }
1120
-
1121
- function setDefaultValues(trial){
1122
- for(var param in jsPsych.plugins[trial.type].info.parameters){
1123
- // check if parameter is complex with nested defaults
1124
- if(jsPsych.plugins[trial.type].info.parameters[param].type == jsPsych.plugins.parameterType.COMPLEX){
1125
- if(jsPsych.plugins[trial.type].info.parameters[param].array == true){
1126
- // iterate over each entry in the array
1127
- trial[param].forEach(function(ip, i){
1128
- // check each parameter in the plugin description
1129
- for(var p in jsPsych.plugins[trial.type].info.parameters[param].nested){
1130
- if(typeof trial[param][i][p] == 'undefined' || trial[param][i][p] === null){
1131
- if(typeof jsPsych.plugins[trial.type].info.parameters[param].nested[p].default == 'undefined'){
1132
- console.error('You must specify a value for the '+p+' parameter (nested in the '+param+' parameter) in the '+trial.type+' plugin.');
1133
- } else {
1134
- trial[param][i][p] = jsPsych.plugins[trial.type].info.parameters[param].nested[p].default;
1135
- }
1136
- }
1137
- }
1138
- });
1139
- }
1140
- }
1141
- // if it's not nested, checking is much easier and do that here:
1142
- else if(typeof trial[param] == 'undefined' || trial[param] === null){
1143
- if(typeof jsPsych.plugins[trial.type].info.parameters[param].default == 'undefined'){
1144
- console.error('You must specify a value for the '+param+' parameter in the '+trial.type+' plugin.');
1145
- } else {
1146
- trial[param] = jsPsych.plugins[trial.type].info.parameters[param].default;
1147
- }
1148
- }
1149
- }
1150
- }
1151
-
1152
- function checkExclusions(exclusions, success, fail){
1153
- var clear = true;
1154
-
1155
- // MINIMUM SIZE
1156
- if(typeof exclusions.min_width !== 'undefined' || typeof exclusions.min_height !== 'undefined'){
1157
- var mw = typeof exclusions.min_width !== 'undefined' ? exclusions.min_width : 0;
1158
- var mh = typeof exclusions.min_height !== 'undefined' ? exclusions.min_height : 0;
1159
- var w = window.innerWidth;
1160
- var h = window.innerHeight;
1161
- if(w < mw || h < mh){
1162
- clear = false;
1163
- var interval = setInterval(function(){
1164
- var w = window.innerWidth;
1165
- var h = window.innerHeight;
1166
- if(w < mw || h < mh){
1167
- var msg = '<p>Your browser window is too small to complete this experiment. '+
1168
- 'Please maximize the size of your browser window. If your browser window is already maximized, '+
1169
- 'you will not be able to complete this experiment.</p>'+
1170
- '<p>The minimum width is '+mw+'px. Your current width is '+w+'px.</p>'+
1171
- '<p>The minimum height is '+mh+'px. Your current height is '+h+'px.</p>';
1172
- core.getDisplayElement().innerHTML = msg;
1173
- } else {
1174
- clearInterval(interval);
1175
- core.getDisplayElement().innerHTML = '';
1176
- checkExclusions(exclusions, success, fail);
1177
- }
1178
- }, 100);
1179
- return; // prevents checking other exclusions while this is being fixed
1180
- }
1181
- }
1182
-
1183
- // WEB AUDIO API
1184
- if(typeof exclusions.audio !== 'undefined' && exclusions.audio) {
1185
- if(window.hasOwnProperty('AudioContext') || window.hasOwnProperty('webkitAudioContext')){
1186
- // clear
1187
- } else {
1188
- clear = false;
1189
- var msg = '<p>Your browser does not support the WebAudio API, which means that you will not '+
1190
- 'be able to complete the experiment.</p><p>Browsers that support the WebAudio API include '+
1191
- 'Chrome, Firefox, Safari, and Edge.</p>';
1192
- core.getDisplayElement().innerHTML = msg;
1193
- fail();
1194
- return;
1195
- }
1196
- }
1197
-
1198
- // GO?
1199
- if(clear){ success(); }
1200
- }
1201
-
1202
- function drawProgressBar(msg) {
1203
- document.querySelector('.jspsych-display-element').insertAdjacentHTML('afterbegin',
1204
- '<div id="jspsych-progressbar-container">'+
1205
- '<span>'+
1206
- msg+
1207
- '</span>'+
1208
- '<div id="jspsych-progressbar-outer">'+
1209
- '<div id="jspsych-progressbar-inner"></div>'+
1210
- '</div></div>');
1211
- }
1212
-
1213
- function updateProgressBar() {
1214
- var progress = jsPsych.progress().percent_complete;
1215
- core.setProgressBar(progress / 100);
1216
- }
1217
-
1218
- var progress_bar_amount = 0;
1219
-
1220
- core.setProgressBar = function(proportion_complete){
1221
- proportion_complete = Math.max(Math.min(1,proportion_complete),0);
1222
- document.querySelector('#jspsych-progressbar-inner').style.width = (proportion_complete*100) + "%";
1223
- progress_bar_amount = proportion_complete;
1224
- }
1225
-
1226
- core.getProgressBarCompleted = function(){
1227
- return progress_bar_amount;
1228
- }
1229
-
1230
- //Leave a trace in the DOM that jspsych was loaded
1231
- document.documentElement.setAttribute('jspsych', 'present');
1232
-
1233
- return core;
1234
- })();
1235
-
1236
- jsPsych.internal = (function() {
1237
- var module = {};
1238
-
1239
- // this flag is used to determine whether we are in a scope where
1240
- // jsPsych.timelineVariable() should be executed immediately or
1241
- // whether it should return a function to access the variable later.
1242
- module.call_immediate = false;
1243
-
1244
- return module;
1245
- })();
1246
-
1247
- jsPsych.plugins = (function() {
1248
-
1249
- var module = {};
1250
-
1251
- // enumerate possible parameter types for plugins
1252
- module.parameterType = {
1253
- BOOL: 0,
1254
- STRING: 1,
1255
- INT: 2,
1256
- FLOAT: 3,
1257
- FUNCTION: 4,
1258
- KEY: 5,
1259
- SELECT: 6,
1260
- HTML_STRING: 7,
1261
- IMAGE: 8,
1262
- AUDIO: 9,
1263
- VIDEO: 10,
1264
- OBJECT: 11,
1265
- COMPLEX: 12,
1266
- TIMELINE: 13
1267
- }
1268
-
1269
- module.universalPluginParameters = {
1270
- data: {
1271
- type: module.parameterType.OBJECT,
1272
- pretty_name: 'Data',
1273
- default: {},
1274
- description: 'Data to add to this trial (key-value pairs)'
1275
- },
1276
- on_start: {
1277
- type: module.parameterType.FUNCTION,
1278
- pretty_name: 'On start',
1279
- default: function() { return; },
1280
- description: 'Function to execute when trial begins'
1281
- },
1282
- on_finish: {
1283
- type: module.parameterType.FUNCTION,
1284
- pretty_name: 'On finish',
1285
- default: function() { return; },
1286
- description: 'Function to execute when trial is finished'
1287
- },
1288
- on_load: {
1289
- type: module.parameterType.FUNCTION,
1290
- pretty_name: 'On load',
1291
- default: function() { return; },
1292
- description: 'Function to execute after the trial has loaded'
1293
- },
1294
- post_trial_gap: {
1295
- type: module.parameterType.INT,
1296
- pretty_name: 'Post trial gap',
1297
- default: null,
1298
- description: 'Length of gap between the end of this trial and the start of the next trial'
1299
- },
1300
- css_classes: {
1301
- type: module.parameterType.STRING,
1302
- pretty_name: 'Custom CSS classes',
1303
- default: null,
1304
- description: 'A list of CSS classes to add to the jsPsych display element for the duration of this trial'
1305
- }
1306
- }
1307
-
1308
- return module;
1309
- })();
1310
-
1311
- jsPsych.extensions = (function(){
1312
- return {};
1313
- })();
1314
-
1315
- jsPsych.data = (function() {
1316
-
1317
- var module = {};
1318
-
1319
- // data storage object
1320
- var allData = DataCollection();
1321
-
1322
- // browser interaction event data
1323
- var interactionData = DataCollection();
1324
-
1325
- // data properties for all trials
1326
- var dataProperties = {};
1327
-
1328
- // cache the query_string
1329
- var query_string;
1330
-
1331
- // DataCollection
1332
- function DataCollection(data){
1333
-
1334
- var data_collection = {};
1335
-
1336
- var trials = typeof data === 'undefined' ? [] : data;
1337
-
1338
- data_collection.push = function(new_data){
1339
- trials.push(new_data);
1340
- return data_collection;
1341
- }
1342
-
1343
- data_collection.join = function(other_data_collection){
1344
- trials = trials.concat(other_data_collection.values());
1345
- return data_collection;
1346
- }
1347
-
1348
- data_collection.top = function(){
1349
- if(trials.length <= 1){
1350
- return data_collection;
1351
- } else {
1352
- return DataCollection([trials[trials.length-1]]);
1353
- }
1354
- }
1355
-
1356
- /**
1357
- * Queries the first n elements in a collection of trials.
1358
- *
1359
- * @param {number} n A positive integer of elements to return. A value of
1360
- * n that is less than 1 will throw an error.
1361
- *
1362
- * @return {Array} First n objects of a collection of trials. If fewer than
1363
- * n trials are available, the trials.length elements will
1364
- * be returned.
1365
- *
1366
- */
1367
- data_collection.first = function(n){
1368
- if (typeof n == 'undefined') { n = 1 }
1369
- if (n < 1) {
1370
- throw `You must query with a positive nonzero integer. Please use a
1371
- different value for n.`;
1372
- }
1373
- if (trials.length == 0) return DataCollection([]);
1374
- if (n > trials.length) n = trials.length;
1375
- return DataCollection(trials.slice(0, n));
1376
- }
1377
-
1378
- /**
1379
- * Queries the last n elements in a collection of trials.
1380
- *
1381
- * @param {number} n A positive integer of elements to return. A value of
1382
- * n that is less than 1 will throw an error.
1383
- *
1384
- * @return {Array} Last n objects of a collection of trials. If fewer than
1385
- * n trials are available, the trials.length elements will
1386
- * be returned.
1387
- *
1388
- */
1389
- data_collection.last = function(n) {
1390
- if (typeof n == 'undefined') { n = 1 }
1391
- if (n < 1) {
1392
- throw `You must query with a positive nonzero integer. Please use a
1393
- different value for n.`;
1394
- }
1395
- if (trials.length == 0) return DataCollection([]);
1396
- if (n > trials.length) n = trials.length;
1397
- return DataCollection(trials.slice(trials.length - n, trials.length));
1398
- }
1399
-
1400
- data_collection.values = function(){
1401
- return trials;
1402
- }
1403
-
1404
- data_collection.count = function(){
1405
- return trials.length;
1406
- }
1407
-
1408
- data_collection.readOnly = function(){
1409
- return DataCollection(jsPsych.utils.deepCopy(trials));
1410
- }
1411
-
1412
- data_collection.addToAll = function(properties){
1413
- for (var i = 0; i < trials.length; i++) {
1414
- for (var key in properties) {
1415
- trials[i][key] = properties[key];
1416
- }
1417
- }
1418
- return data_collection;
1419
- }
1420
-
1421
- data_collection.addToLast = function(properties){
1422
- if(trials.length != 0){
1423
- for (var key in properties) {
1424
- trials[trials.length-1][key] = properties[key];
1425
- }
1426
- }
1427
- return data_collection;
1428
- }
1429
-
1430
- data_collection.filter = function(filters){
1431
- // [{p1: v1, p2:v2}, {p1:v2}]
1432
- // {p1: v1}
1433
- if(!Array.isArray(filters)){
1434
- var f = jsPsych.utils.deepCopy([filters]);
1435
- } else {
1436
- var f = jsPsych.utils.deepCopy(filters);
1437
- }
1438
-
1439
- var filtered_data = [];
1440
- for(var x=0; x < trials.length; x++){
1441
- var keep = false;
1442
- for(var i=0; i<f.length; i++){
1443
- var match = true;
1444
- var keys = Object.keys(f[i]);
1445
- for(var k=0; k<keys.length; k++){
1446
- if(typeof trials[x][keys[k]] !== 'undefined' && trials[x][keys[k]] == f[i][keys[k]]){
1447
- // matches on this key!
1448
- } else {
1449
- match = false;
1450
- }
1451
- }
1452
- if(match) { keep = true; break; } // can break because each filter is OR.
1453
- }
1454
- if(keep){
1455
- filtered_data.push(trials[x]);
1456
- }
1457
- }
1458
-
1459
- var out = DataCollection(filtered_data);
1460
-
1461
- return out;
1462
- }
1463
-
1464
- data_collection.filterCustom = function(fn){
1465
- var included = [];
1466
- for(var i=0; i<trials.length; i++){
1467
- if(fn(trials[i])){
1468
- included.push(trials[i]);
1469
- }
1470
- }
1471
- return DataCollection(included);
1472
- }
1473
-
1474
- data_collection.select = function(column){
1475
- var values = [];
1476
- for(var i=0; i<trials.length; i++){
1477
- if(typeof trials[i][column] !== 'undefined'){
1478
- values.push(trials[i][column]);
1479
- }
1480
- }
1481
- var out = DataColumn();
1482
- out.values = values;
1483
- return out;
1484
- }
1485
-
1486
- data_collection.ignore = function(columns){
1487
- if(!Array.isArray(columns)){
1488
- columns = [columns];
1489
- }
1490
- var o = jsPsych.utils.deepCopy(trials);
1491
- for (var i = 0; i < o.length; i++) {
1492
- for (var j in columns) {
1493
- delete o[i][columns[j]];
1494
- }
1495
- }
1496
- return DataCollection(o);
1497
- }
1498
-
1499
- data_collection.uniqueNames = function(){
1500
- var names = [];
1501
-
1502
- for(var i=0; i<trials.length; i++){
1503
- var keys = Object.keys(trials[i]);
1504
- for(var j=0; j<keys.length; j++){
1505
- if(!names.includes(keys[j])){
1506
- names.push(keys[j]);
1507
- }
1508
- }
1509
- }
1510
-
1511
- return names;
1512
- }
1513
-
1514
- data_collection.csv = function(){
1515
- return JSON2CSV(trials);
1516
- }
1517
-
1518
- data_collection.json = function(pretty){
1519
- if(pretty){
1520
- return JSON.stringify(trials, null, '\t');
1521
- }
1522
- return JSON.stringify(trials);
1523
- }
1524
-
1525
- data_collection.localSave = function(format, filename){
1526
- var data_string;
1527
-
1528
- if (format == 'JSON' || format == 'json') {
1529
- data_string = data_collection.json();
1530
- } else if (format == 'CSV' || format == 'csv') {
1531
- data_string = data_collection.csv();
1532
- } else {
1533
- throw new Error('Invalid format specified for localSave. Must be "JSON" or "CSV".');
1534
- }
1535
-
1536
- saveTextToFile(data_string, filename);
1537
- }
1538
-
1539
- return data_collection;
1540
- }
1541
-
1542
- // DataColumn class
1543
- function DataColumn(){
1544
- var data_column = {};
1545
-
1546
- data_column.values = [];
1547
-
1548
- data_column.sum = function(){
1549
- var s = 0;
1550
- for(var i=0; i<data_column.values.length; i++){
1551
- s += data_column.values[i];
1552
- }
1553
- return s;
1554
- }
1555
-
1556
- data_column.mean = function(){
1557
- return data_column.sum() / data_column.count();
1558
- }
1559
-
1560
- data_column.median = function(){
1561
- if (data_column.values.length == 0) {return undefined};
1562
- var numbers = data_column.values.slice(0).sort(function(a,b){ return a - b; });
1563
- var middle = Math.floor(numbers.length / 2);
1564
- var isEven = numbers.length % 2 === 0;
1565
- return isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle];
1566
- }
1567
-
1568
- data_column.min = function(){
1569
- return Math.min.apply(null, data_column.values);
1570
- }
1571
-
1572
- data_column.max = function(){
1573
- return Math.max.apply(null, data_column.values);
1574
- }
1575
-
1576
- data_column.count = function(){
1577
- return data_column.values.length;
1578
- }
1579
-
1580
- data_column.variance = function(){
1581
- var mean = data_column.mean();
1582
- var sum_square_error = 0;
1583
- for(var i=0; i<data_column.values.length; i++){
1584
- sum_square_error += Math.pow(data_column.values[i] - mean,2);
1585
- }
1586
- var mse = sum_square_error / (data_column.values.length - 1);
1587
- return mse;
1588
- }
1589
-
1590
- data_column.sd = function(){
1591
- var mse = data_column.variance();
1592
- var rmse = Math.sqrt(mse);
1593
- return rmse;
1594
- }
1595
-
1596
- data_column.frequencies = function(){
1597
- var unique = {}
1598
- for(var i=0; i<data_column.values.length; i++){
1599
- var v = data_column.values[i];
1600
- if(typeof unique[v] == 'undefined'){
1601
- unique[v] = 1;
1602
- } else {
1603
- unique[v]++;
1604
- }
1605
- }
1606
- return unique;
1607
- }
1608
-
1609
- data_column.all = function(eval_fn){
1610
- for(var i=0; i<data_column.values.length; i++){
1611
- if(!eval_fn(data_column.values[i])){
1612
- return false;
1613
- }
1614
- }
1615
- return true;
1616
- }
1617
-
1618
- data_column.subset = function(eval_fn){
1619
- var out = [];
1620
- for(var i=0; i<data_column.values.length; i++){
1621
- if(eval_fn(data_column.values[i])){
1622
- out.push(data_column.values[i]);
1623
- }
1624
- }
1625
- var o = DataColumn();
1626
- o.values = out;
1627
- return o;
1628
- }
1629
-
1630
- return data_column;
1631
- }
1632
-
1633
- module.reset = function(){
1634
- allData = DataCollection();
1635
- interactionData = DataCollection();
1636
- }
1637
-
1638
- module.get = function() {
1639
- return allData;
1640
- };
1641
-
1642
- module.getInteractionData = function() {
1643
- return interactionData;
1644
- }
1645
-
1646
- module.write = function(data_object) {
1647
-
1648
- var progress = jsPsych.progress();
1649
- var trial = jsPsych.currentTrial();
1650
-
1651
- //var trial_opt_data = typeof trial.data == 'function' ? trial.data() : trial.data;
1652
-
1653
- var default_data = {
1654
- 'trial_type': trial.type,
1655
- 'trial_index': progress.current_trial_global,
1656
- 'time_elapsed': jsPsych.totalTime(),
1657
- 'internal_node_id': jsPsych.currentTimelineNodeID()
1658
- };
1659
-
1660
- var ext_data_object = Object.assign({}, data_object, trial.data, default_data, dataProperties);
1661
-
1662
- allData.push(ext_data_object);
1663
- };
1664
-
1665
- module.addProperties = function(properties) {
1666
-
1667
- // first, add the properties to all data that's already stored
1668
- allData.addToAll(properties);
1669
-
1670
- // now add to list so that it gets appended to all future data
1671
- dataProperties = Object.assign({}, dataProperties, properties);
1672
-
1673
- };
1674
-
1675
- module.addDataToLastTrial = function(data) {
1676
- allData.addToLast(data);
1677
- }
1678
-
1679
- module.getDataByTimelineNode = function(node_id) {
1680
- var data = allData.filterCustom(function(x){
1681
- return x.internal_node_id.slice(0, node_id.length) === node_id;
1682
- });
1683
-
1684
- return data;
1685
- };
1686
-
1687
- module.getLastTrialData = function() {
1688
- return allData.top();
1689
- };
1690
-
1691
- module.getLastTimelineData = function() {
1692
- var lasttrial = module.getLastTrialData();
1693
- var node_id = lasttrial.select('internal_node_id').values[0];
1694
- if (typeof node_id === 'undefined') {
1695
- return DataCollection();
1696
- } else {
1697
- var parent_node_id = node_id.substr(0,node_id.lastIndexOf('-'));
1698
- var lastnodedata = module.getDataByTimelineNode(parent_node_id);
1699
- return lastnodedata;
1700
- }
1701
- }
1702
-
1703
- module.displayData = function(format) {
1704
- format = (typeof format === 'undefined') ? "json" : format.toLowerCase();
1705
- if (format != "json" && format != "csv") {
1706
- console.log('Invalid format declared for displayData function. Using json as default.');
1707
- format = "json";
1708
- }
1709
-
1710
- var data_string;
1711
-
1712
- if (format == 'json') {
1713
- data_string = allData.json(true); // true = pretty print with tabs
1714
- } else {
1715
- data_string = allData.csv();
1716
- }
1717
-
1718
- var display_element = jsPsych.getDisplayElement();
1719
-
1720
- display_element.innerHTML = '<pre id="jspsych-data-display"></pre>';
1721
-
1722
- document.getElementById('jspsych-data-display').textContent = data_string;
1723
- };
1724
-
1725
- module.urlVariables = function() {
1726
- if(typeof query_string == 'undefined'){
1727
- query_string = getQueryString();
1728
- }
1729
- return query_string;
1730
- }
1731
-
1732
- module.getURLVariable = function(whichvar){
1733
- if(typeof query_string == 'undefined'){
1734
- query_string = getQueryString();
1735
- }
1736
- return query_string[whichvar];
1737
- }
1738
-
1739
- module.createInteractionListeners = function(){
1740
- // blur event capture
1741
- window.addEventListener('blur', function(){
1742
- var data = {
1743
- event: 'blur',
1744
- trial: jsPsych.progress().current_trial_global,
1745
- time: jsPsych.totalTime()
1746
- };
1747
- interactionData.push(data);
1748
- jsPsych.initSettings().on_interaction_data_update(data);
1749
- });
1750
-
1751
- // focus event capture
1752
- window.addEventListener('focus', function(){
1753
- var data = {
1754
- event: 'focus',
1755
- trial: jsPsych.progress().current_trial_global,
1756
- time: jsPsych.totalTime()
1757
- };
1758
- interactionData.push(data);
1759
- jsPsych.initSettings().on_interaction_data_update(data);
1760
- });
1761
-
1762
- // fullscreen change capture
1763
- function fullscreenchange(){
1764
- var type = (document.isFullScreen || document.webkitIsFullScreen || document.mozIsFullScreen || document.fullscreenElement) ? 'fullscreenenter' : 'fullscreenexit';
1765
- var data = {
1766
- event: type,
1767
- trial: jsPsych.progress().current_trial_global,
1768
- time: jsPsych.totalTime()
1769
- };
1770
- interactionData.push(data);
1771
- jsPsych.initSettings().on_interaction_data_update(data);
1772
- }
1773
-
1774
- document.addEventListener('fullscreenchange', fullscreenchange);
1775
- document.addEventListener('mozfullscreenchange', fullscreenchange);
1776
- document.addEventListener('webkitfullscreenchange', fullscreenchange);
1777
- }
1778
-
1779
- // public methods for testing purposes. not recommended for use.
1780
- module._customInsert = function(data){
1781
- allData = DataCollection(data);
1782
- }
1783
-
1784
- module._fullreset = function(){
1785
- module.reset();
1786
- dataProperties = {};
1787
- }
1788
-
1789
- // private function to save text file on local drive
1790
- function saveTextToFile(textstr, filename) {
1791
- var blobToSave = new Blob([textstr], {
1792
- type: 'text/plain'
1793
- });
1794
- var blobURL = "";
1795
- if (typeof window.webkitURL !== 'undefined') {
1796
- blobURL = window.webkitURL.createObjectURL(blobToSave);
1797
- } else {
1798
- blobURL = window.URL.createObjectURL(blobToSave);
1799
- }
1800
-
1801
- var display_element = jsPsych.getDisplayElement();
1802
-
1803
- display_element.insertAdjacentHTML('beforeend','<a id="jspsych-download-as-text-link" style="display:none;" download="'+filename+'" href="'+blobURL+'">click to download</a>');
1804
- document.getElementById('jspsych-download-as-text-link').click();
1805
- }
1806
-
1807
- //
1808
- // A few helper functions to handle data format conversion
1809
- //
1810
-
1811
- // this function based on code suggested by StackOverflow users:
1812
- // http://stackoverflow.com/users/64741/zachary
1813
- // http://stackoverflow.com/users/317/joseph-sturtevant
1814
-
1815
- function JSON2CSV(objArray) {
1816
- var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
1817
- var line = '';
1818
- var result = '';
1819
- var columns = [];
1820
-
1821
- var i = 0;
1822
- for (var j = 0; j < array.length; j++) {
1823
- for (var key in array[j]) {
1824
- var keyString = key + "";
1825
- keyString = '"' + keyString.replace(/"/g, '""') + '",';
1826
- if (!columns.includes(key)) {
1827
- columns[i] = key;
1828
- line += keyString;
1829
- i++;
1830
- }
1831
- }
1832
- }
1833
-
1834
- line = line.slice(0, -1);
1835
- result += line + '\r\n';
1836
-
1837
- for (var i = 0; i < array.length; i++) {
1838
- var line = '';
1839
- for (var j = 0; j < columns.length; j++) {
1840
- var value = (typeof array[i][columns[j]] === 'undefined') ? '' : array[i][columns[j]];
1841
- if(typeof value == 'object') {
1842
- value = JSON.stringify(value);
1843
- }
1844
- var valueString = value + "";
1845
- line += '"' + valueString.replace(/"/g, '""') + '",';
1846
- }
1847
-
1848
- line = line.slice(0, -1);
1849
- result += line + '\r\n';
1850
- }
1851
-
1852
- return result;
1853
- }
1854
-
1855
- // this function is modified from StackOverflow:
1856
- // http://stackoverflow.com/posts/3855394
1857
-
1858
- function getQueryString() {
1859
- var a = window.location.search.substr(1).split('&');
1860
- if (a == "") return {};
1861
- var b = {};
1862
- for (var i = 0; i < a.length; ++i)
1863
- {
1864
- var p=a[i].split('=', 2);
1865
- if (p.length == 1)
1866
- b[p[0]] = "";
1867
- else
1868
- b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
1869
- }
1870
- return b;
1871
- }
1872
-
1873
- return module;
1874
-
1875
- })();
1876
-
1877
- jsPsych.turk = (function() {
1878
-
1879
- var module = {};
1880
-
1881
- // core.turkInfo gets information relevant to mechanical turk experiments. returns an object
1882
- // containing the workerID, assignmentID, and hitID, and whether or not the HIT is in
1883
- // preview mode, meaning that they haven't accepted the HIT yet.
1884
- module.turkInfo = function() {
1885
-
1886
- var turk = {};
1887
-
1888
- var param = function(url, name) {
1889
- name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
1890
- var regexS = "[\\?&]" + name + "=([^&#]*)";
1891
- var regex = new RegExp(regexS);
1892
- var results = regex.exec(url);
1893
- return (results == null) ? "" : results[1];
1894
- };
1895
-
1896
- var src = param(window.location.href, "assignmentId") ? window.location.href : document.referrer;
1897
-
1898
- var keys = ["assignmentId", "hitId", "workerId", "turkSubmitTo"];
1899
- keys.map(
1900
-
1901
- function(key) {
1902
- turk[key] = unescape(param(src, key));
1903
- });
1904
-
1905
- turk.previewMode = (turk.assignmentId == "ASSIGNMENT_ID_NOT_AVAILABLE");
1906
-
1907
- turk.outsideTurk = (!turk.previewMode && turk.hitId === "" && turk.assignmentId == "" && turk.workerId == "")
1908
-
1909
- turk_info = turk;
1910
-
1911
- return turk;
1912
-
1913
- };
1914
-
1915
- // core.submitToTurk will submit a MechanicalTurk ExternalHIT type
1916
- module.submitToTurk = function(data) {
1917
-
1918
- var turkInfo = jsPsych.turk.turkInfo();
1919
- var assignmentId = turkInfo.assignmentId;
1920
- var turkSubmitTo = turkInfo.turkSubmitTo;
1921
-
1922
- if (!assignmentId || !turkSubmitTo) return;
1923
-
1924
- var dataString = [];
1925
-
1926
- for (var key in data) {
1927
-
1928
- if (data.hasOwnProperty(key)) {
1929
- dataString.push(key + "=" + escape(data[key]));
1930
- }
1931
- }
1932
-
1933
- dataString.push("assignmentId=" + assignmentId);
1934
-
1935
- var url = turkSubmitTo + "/mturk/externalSubmit?" + dataString.join("&");
1936
-
1937
- window.location.href = url;
1938
- };
1939
-
1940
- return module;
1941
-
1942
- })();
1943
-
1944
- jsPsych.randomization = (function() {
1945
-
1946
- var module = {};
1947
-
1948
- module.repeat = function(array, repetitions, unpack) {
1949
-
1950
- var arr_isArray = Array.isArray(array);
1951
- var rep_isArray = Array.isArray(repetitions);
1952
-
1953
- // if array is not an array, then we just repeat the item
1954
- if (!arr_isArray) {
1955
- if (!rep_isArray) {
1956
- array = [array];
1957
- repetitions = [repetitions];
1958
- } else {
1959
- repetitions = [repetitions[0]];
1960
- console.log('Unclear parameters given to randomization.repeat. Multiple set sizes specified, but only one item exists to sample. Proceeding using the first set size.');
1961
- }
1962
- } else {
1963
- if (!rep_isArray) {
1964
- var reps = [];
1965
- for (var i = 0; i < array.length; i++) {
1966
- reps.push(repetitions);
1967
- }
1968
- repetitions = reps;
1969
- } else {
1970
- if (array.length != repetitions.length) {
1971
- console.warning('Unclear parameters given to randomization.repeat. Items and repetitions are unequal lengths. Behavior may not be as expected.');
1972
- // throw warning if repetitions is too short, use first rep ONLY.
1973
- if (repetitions.length < array.length) {
1974
- var reps = [];
1975
- for (var i = 0; i < array.length; i++) {
1976
- reps.push(repetitions);
1977
- }
1978
- repetitions = reps;
1979
- } else {
1980
- // throw warning if too long, and then use the first N
1981
- repetitions = repetitions.slice(0, array.length);
1982
- }
1983
- }
1984
- }
1985
- }
1986
-
1987
- // should be clear at this point to assume that array and repetitions are arrays with == length
1988
- var allsamples = [];
1989
- for (var i = 0; i < array.length; i++) {
1990
- for (var j = 0; j < repetitions[i]; j++) {
1991
- if(array[i] == null || typeof array[i] != 'object'){
1992
- allsamples.push(array[i]);
1993
- } else {
1994
- allsamples.push(Object.assign({}, array[i]));
1995
- }
1996
-
1997
- }
1998
- }
1999
-
2000
- var out = shuffle(allsamples);
2001
-
2002
- if (unpack) {
2003
- out = unpackArray(out);
2004
- }
2005
-
2006
- return out;
2007
- }
2008
-
2009
- module.shuffle = function(arr) {
2010
- if(!Array.isArray(arr)){
2011
- console.error('Argument to jsPsych.randomization.shuffle() must be an array.')
2012
- }
2013
- return shuffle(arr);
2014
- }
2015
-
2016
- module.shuffleNoRepeats = function(arr, equalityTest) {
2017
- if(!Array.isArray(arr)){
2018
- console.error('First argument to jsPsych.randomization.shuffleNoRepeats() must be an array.')
2019
- }
2020
- if(typeof equalityTest !== 'undefined' && typeof equalityTest !== 'function'){
2021
- console.error('Second argument to jsPsych.randomization.shuffleNoRepeats() must be a function.')
2022
- }
2023
- // define a default equalityTest
2024
- if (typeof equalityTest == 'undefined') {
2025
- equalityTest = function(a, b) {
2026
- if (a === b) {
2027
- return true;
2028
- } else {
2029
- return false;
2030
- }
2031
- }
2032
- }
2033
-
2034
- var random_shuffle = shuffle(arr);
2035
- for (var i = 0; i < random_shuffle.length - 1; i++) {
2036
- if (equalityTest(random_shuffle[i], random_shuffle[i + 1])) {
2037
- // neighbors are equal, pick a new random neighbor to swap (not the first or last element, to avoid edge cases)
2038
- var random_pick = Math.floor(Math.random() * (random_shuffle.length - 2)) + 1;
2039
- // test to make sure the new neighbor isn't equal to the old one
2040
- while (
2041
- equalityTest(random_shuffle[i + 1], random_shuffle[random_pick]) ||
2042
- (equalityTest(random_shuffle[i + 1], random_shuffle[random_pick + 1]) || equalityTest(random_shuffle[i + 1], random_shuffle[random_pick - 1]))
2043
- ) {
2044
- random_pick = Math.floor(Math.random() * (random_shuffle.length - 2)) + 1;
2045
- }
2046
- var new_neighbor = random_shuffle[random_pick];
2047
- random_shuffle[random_pick] = random_shuffle[i + 1];
2048
- random_shuffle[i + 1] = new_neighbor;
2049
- }
2050
- }
2051
-
2052
- return random_shuffle;
2053
- }
2054
-
2055
- module.shuffleAlternateGroups = function(arr_groups, random_group_order){
2056
- if(typeof random_group_order == 'undefined'){
2057
- random_group_order = false;
2058
- }
2059
-
2060
- var n_groups = arr_groups.length;
2061
- if(n_groups == 1){
2062
- console.warn('jsPsych.randomization.shuffleAlternateGroups was called with only one group. Defaulting to simple shuffle.');
2063
- return(module.shuffle(arr_groups[0]));
2064
- }
2065
-
2066
- var group_order = [];
2067
- for(var i=0; i<n_groups; i++){
2068
- group_order.push(i);
2069
- }
2070
- if(random_group_order){
2071
- group_order = module.shuffle(group_order);
2072
- }
2073
-
2074
- var randomized_groups = [];
2075
- var min_length = null;
2076
- for(var i=0; i<n_groups; i++){
2077
- min_length = min_length === null ? arr_groups[i].length : Math.min(min_length, arr_groups[i].length);
2078
- randomized_groups.push(module.shuffle(arr_groups[i]));
2079
- }
2080
-
2081
- var out = [];
2082
- for(var i=0; i<min_length; i++){
2083
- for(var j=0; j<group_order.length; j++){
2084
- out.push(randomized_groups[group_order[j]][i])
2085
- }
2086
- }
2087
-
2088
- return out;
2089
- }
2090
-
2091
- module.sampleWithoutReplacement = function(arr, size){
2092
- if(!Array.isArray(arr)){
2093
- console.error("First argument to jsPsych.randomization.sampleWithoutReplacement() must be an array")
2094
- }
2095
-
2096
- if (size > arr.length) {
2097
- console.error("Cannot take a sample " +
2098
- "larger than the size of the set of items to sample.");
2099
- }
2100
- return jsPsych.randomization.shuffle(arr).slice(0,size);
2101
- }
2102
-
2103
- module.sampleWithReplacement = function(arr, size, weights) {
2104
- if(!Array.isArray(arr)){
2105
- console.error("First argument to jsPsych.randomization.sampleWithReplacement() must be an array")
2106
- }
2107
-
2108
- var normalized_weights = [];
2109
- if(typeof weights !== 'undefined'){
2110
- if(weights.length !== arr.length){
2111
- console.error('The length of the weights array must equal the length of the array '+
2112
- 'to be sampled from.');
2113
- }
2114
- var weight_sum = 0;
2115
- for(var i=0; i<weights.length; i++){
2116
- weight_sum += weights[i];
2117
- }
2118
- for(var i=0; i<weights.length; i++){
2119
- normalized_weights.push( weights[i] / weight_sum );
2120
- }
2121
- } else {
2122
- for(var i=0; i<arr.length; i++){
2123
- normalized_weights.push( 1 / arr.length );
2124
- }
2125
- }
2126
-
2127
- var cumulative_weights = [normalized_weights[0]];
2128
- for(var i=1; i<normalized_weights.length; i++){
2129
- cumulative_weights.push(normalized_weights[i] + cumulative_weights[i-1]);
2130
- }
2131
-
2132
- var samp = [];
2133
- for (var i = 0; i < size; i++) {
2134
- var rnd = Math.random();
2135
- var index = 0;
2136
- while(rnd > cumulative_weights[index]) { index++; }
2137
- samp.push(arr[index]);
2138
- }
2139
- return samp;
2140
- }
2141
-
2142
- module.factorial = function(factors, repetitions, unpack) {
2143
-
2144
- var factorNames = Object.keys(factors);
2145
-
2146
- var factor_combinations = [];
2147
-
2148
- for (var i = 0; i < factors[factorNames[0]].length; i++) {
2149
- factor_combinations.push({});
2150
- factor_combinations[i][factorNames[0]] = factors[factorNames[0]][i];
2151
- }
2152
-
2153
- for (var i = 1; i < factorNames.length; i++) {
2154
- var toAdd = factors[factorNames[i]];
2155
- var n = factor_combinations.length;
2156
- for (var j = 0; j < n; j++) {
2157
- var base = factor_combinations[j];
2158
- for (var k = 0; k < toAdd.length; k++) {
2159
- var newpiece = {};
2160
- newpiece[factorNames[i]] = toAdd[k];
2161
- factor_combinations.push(Object.assign({}, base, newpiece));
2162
- }
2163
- }
2164
- factor_combinations.splice(0, n);
2165
- }
2166
-
2167
- repetitions = (typeof repetitions === 'undefined') ? 1 : repetitions;
2168
- var with_repetitions = module.repeat(factor_combinations, repetitions, unpack);
2169
-
2170
- return with_repetitions;
2171
- }
2172
-
2173
- module.randomID = function(length){
2174
- var result = '';
2175
- var length = (typeof length == 'undefined') ? 32 : length;
2176
- var chars = '0123456789abcdefghjklmnopqrstuvwxyz';
2177
- for(var i = 0; i<length; i++){
2178
- result += chars[Math.floor(Math.random() * chars.length)];
2179
- }
2180
- return result;
2181
- }
2182
-
2183
- function unpackArray(array) {
2184
-
2185
- var out = {};
2186
-
2187
- for (var i = 0; i < array.length; i++) {
2188
- var keys = Object.keys(array[i]);
2189
- for (var k = 0; k < keys.length; k++) {
2190
- if (typeof out[keys[k]] === 'undefined') {
2191
- out[keys[k]] = [];
2192
- }
2193
- out[keys[k]].push(array[i][keys[k]]);
2194
- }
2195
- }
2196
-
2197
- return out;
2198
- }
2199
-
2200
- function shuffle(array) {
2201
- var copy_array = array.slice(0);
2202
- var m = copy_array.length,
2203
- t, i;
2204
-
2205
- // While there remain elements to shuffle…
2206
- while (m) {
2207
-
2208
- // Pick a remaining element…
2209
- i = Math.floor(Math.random() * m--);
2210
-
2211
- // And swap it with the current element.
2212
- t = copy_array[m];
2213
- copy_array[m] = copy_array[i];
2214
- copy_array[i] = t;
2215
- }
2216
-
2217
- return copy_array;
2218
- }
2219
-
2220
- return module;
2221
-
2222
- })();
2223
-
2224
- jsPsych.pluginAPI = (function() {
2225
-
2226
- var module = {};
2227
-
2228
- // keyboard listeners //
2229
-
2230
- var keyboard_listeners = [];
2231
-
2232
- var held_keys = {};
2233
-
2234
- var root_keydown_listener = function(e){
2235
- for(var i=0; i<keyboard_listeners.length; i++){
2236
- keyboard_listeners[i].fn(e);
2237
- }
2238
- held_keys[e.key] = true;
2239
- }
2240
- var root_keyup_listener = function(e){
2241
- held_keys[e.key] = false;
2242
- }
2243
-
2244
- module.reset = function(root_element){
2245
- keyboard_listeners = [];
2246
- held_keys = {};
2247
- root_element.removeEventListener('keydown', root_keydown_listener);
2248
- root_element.removeEventListener('keyup', root_keyup_listener);
2249
- }
2250
-
2251
- module.createKeyboardEventListeners = function(root_element){
2252
- root_element.addEventListener('keydown', root_keydown_listener);
2253
- root_element.addEventListener('keyup', root_keyup_listener);
2254
- }
2255
-
2256
- module.getKeyboardResponse = function(parameters) {
2257
-
2258
- //parameters are: callback_function, valid_responses, rt_method, persist, audio_context, audio_context_start_time, allow_held_key
2259
-
2260
- parameters.rt_method = (typeof parameters.rt_method === 'undefined') ? 'performance' : parameters.rt_method;
2261
- if (parameters.rt_method != 'performance' && parameters.rt_method != 'audio') {
2262
- console.log('Invalid RT method specified in getKeyboardResponse. Defaulting to "performance" method.');
2263
- parameters.rt_method = 'performance';
2264
- }
2265
-
2266
- var start_time;
2267
- if (parameters.rt_method == 'performance') {
2268
- start_time = performance.now();
2269
- } else if (parameters.rt_method === 'audio') {
2270
- start_time = parameters.audio_context_start_time;
2271
- }
2272
-
2273
- var case_sensitive = (typeof jsPsych.initSettings().case_sensitive_responses === 'undefined') ? false : jsPsych.initSettings().case_sensitive_responses;
2274
-
2275
- var listener_id;
2276
-
2277
- var listener_function = function(e) {
2278
- var key_time;
2279
- if (parameters.rt_method == 'performance') {
2280
- key_time = performance.now();
2281
- } else if (parameters.rt_method === 'audio') {
2282
- key_time = parameters.audio_context.currentTime
2283
- }
2284
- var rt = key_time - start_time;
2285
-
2286
- // overiding via parameters for testing purposes.
2287
- var minimum_valid_rt = parameters.minimum_valid_rt;
2288
- if(!minimum_valid_rt){
2289
- minimum_valid_rt = jsPsych.initSettings().minimum_valid_rt || 0;
2290
- }
2291
-
2292
- var rt_ms = rt;
2293
- if (parameters.rt_method == 'audio') {
2294
- rt_ms = rt_ms * 1000;
2295
- }
2296
- if(rt_ms < minimum_valid_rt) {
2297
- return;
2298
- }
2299
-
2300
- var valid_response = false;
2301
- if (typeof parameters.valid_responses === 'undefined'){
2302
- valid_response = true;
2303
- }
2304
- else if(parameters.valid_responses == jsPsych.ALL_KEYS) {
2305
- valid_response = true;
2306
- }
2307
- else if(parameters.valid_responses != jsPsych.NO_KEYS){
2308
- if(parameters.valid_responses.includes(e.key)){
2309
- valid_response = true;
2310
- }
2311
- if(!case_sensitive) {
2312
- var valid_lower = parameters.valid_responses.map(function(v) {return v.toLowerCase();});
2313
- var key_lower = e.key.toLowerCase();
2314
- if (valid_lower.includes(key_lower)) {
2315
- valid_response = true;
2316
- }
2317
- }
2318
- }
2319
-
2320
- // check if key was already held down
2321
- if (((typeof parameters.allow_held_key === 'undefined') || !parameters.allow_held_key) && valid_response) {
2322
- if (typeof held_keys[e.key] !== 'undefined' && held_keys[e.key] == true) {
2323
- valid_response = false;
2324
- }
2325
- if (!case_sensitive && typeof held_keys[e.key.toLowerCase()] !== 'undefined' && held_keys[e.key.toLowerCase()] == true) {
2326
- valid_response = false;
2327
- }
2328
- }
2329
-
2330
- if (valid_response) {
2331
- // if this is a valid response, then we don't want the key event to trigger other actions
2332
- // like scrolling via the spacebar.
2333
- e.preventDefault();
2334
- var key = e.key;
2335
- if (!case_sensitive) {
2336
- key = key.toLowerCase();
2337
- }
2338
- parameters.callback_function({
2339
- key: key,
2340
- rt: rt_ms,
2341
- });
2342
-
2343
- if (keyboard_listeners.includes(listener_id)) {
2344
-
2345
- if (!parameters.persist) {
2346
- // remove keyboard listener
2347
- module.cancelKeyboardResponse(listener_id);
2348
- }
2349
- }
2350
- }
2351
- };
2352
-
2353
- // create listener id object
2354
- listener_id = {
2355
- type: 'keydown',
2356
- fn: listener_function
2357
- };
2358
-
2359
- // add this keyboard listener to the list of listeners
2360
- keyboard_listeners.push(listener_id);
2361
-
2362
- return listener_id;
2363
-
2364
- };
2365
-
2366
- module.cancelKeyboardResponse = function(listener) {
2367
- // remove the listener from the list of listeners
2368
- if (keyboard_listeners.includes(listener)) {
2369
- keyboard_listeners.splice(keyboard_listeners.indexOf(listener), 1);
2370
- }
2371
- };
2372
-
2373
- module.cancelAllKeyboardResponses = function() {
2374
- keyboard_listeners = [];
2375
- };
2376
-
2377
- module.convertKeyCharacterToKeyCode = function(character) {
2378
- console.warn('Warning: The jsPsych.pluginAPI.convertKeyCharacterToKeyCode function will be removed in future jsPsych releases. '+
2379
- 'We recommend removing this function and using strings to identify/compare keys.');
2380
- var code;
2381
- character = character.toLowerCase();
2382
- if (typeof keylookup[character] !== 'undefined') {
2383
- code = keylookup[character];
2384
- }
2385
- return code;
2386
- }
2387
-
2388
- module.convertKeyCodeToKeyCharacter = function(code){
2389
- console.warn('Warning: The jsPsych.pluginAPI.convertKeyCodeToKeyCharacter function will be removed in future jsPsych releases. '+
2390
- 'We recommend removing this function and using strings to identify/compare keys.');
2391
- for(var i in Object.keys(keylookup)){
2392
- if(keylookup[Object.keys(keylookup)[i]] == code){
2393
- return Object.keys(keylookup)[i];
2394
- }
2395
- }
2396
- return undefined;
2397
- }
2398
-
2399
- module.compareKeys = function(key1, key2){
2400
- if (Number.isFinite(key1) || Number.isFinite(key2)) {
2401
- // if either value is a numeric keyCode, then convert both to numeric keyCode values and compare (maintained for backwards compatibility)
2402
- if(typeof key1 == 'string') {
2403
- key1 = module.convertKeyCharacterToKeyCode(key1);
2404
- }
2405
- if(typeof key2 == 'string') {
2406
- key2 = module.convertKeyCharacterToKeyCode(key2);
2407
- }
2408
- return key1 == key2;
2409
- } else if (typeof key1 === 'string' && typeof key2 === 'string') {
2410
- // if both values are strings, then check whether or not letter case should be converted before comparing (case_sensitive_responses in jsPsych.init)
2411
- var case_sensitive = (typeof jsPsych.initSettings().case_sensitive_responses === 'undefined') ? false : jsPsych.initSettings().case_sensitive_responses;
2412
- if (case_sensitive) {
2413
- return key1 == key2;
2414
- } else {
2415
- return key1.toLowerCase() == key2.toLowerCase();
2416
- }
2417
- } else if (key1 === null && (typeof key2 === 'string' || Number.isFinite(key2)) || key2 === null && (typeof key1 === 'string' || Number.isFinite(key1))) {
2418
- return false;
2419
- } else if (key1 === null && key2 === null) {
2420
- return true;
2421
- } else {
2422
- console.error('Error in jsPsych.pluginAPI.compareKeys: arguments must be numeric key codes, key strings, or null.');
2423
- return undefined;
2424
- }
2425
- }
2426
-
2427
- var keylookup = {
2428
- 'backspace': 8,
2429
- 'tab': 9,
2430
- 'enter': 13,
2431
- 'shift': 16,
2432
- 'ctrl': 17,
2433
- 'alt': 18,
2434
- 'pause': 19,
2435
- 'capslock': 20,
2436
- 'esc': 27,
2437
- 'space': 32,
2438
- 'spacebar': 32,
2439
- ' ': 32,
2440
- 'pageup': 33,
2441
- 'pagedown': 34,
2442
- 'end': 35,
2443
- 'home': 36,
2444
- 'leftarrow': 37,
2445
- 'uparrow': 38,
2446
- 'rightarrow': 39,
2447
- 'downarrow': 40,
2448
- 'insert': 45,
2449
- 'delete': 46,
2450
- '0': 48,
2451
- '1': 49,
2452
- '2': 50,
2453
- '3': 51,
2454
- '4': 52,
2455
- '5': 53,
2456
- '6': 54,
2457
- '7': 55,
2458
- '8': 56,
2459
- '9': 57,
2460
- 'a': 65,
2461
- 'b': 66,
2462
- 'c': 67,
2463
- 'd': 68,
2464
- 'e': 69,
2465
- 'f': 70,
2466
- 'g': 71,
2467
- 'h': 72,
2468
- 'i': 73,
2469
- 'j': 74,
2470
- 'k': 75,
2471
- 'l': 76,
2472
- 'm': 77,
2473
- 'n': 78,
2474
- 'o': 79,
2475
- 'p': 80,
2476
- 'q': 81,
2477
- 'r': 82,
2478
- 's': 83,
2479
- 't': 84,
2480
- 'u': 85,
2481
- 'v': 86,
2482
- 'w': 87,
2483
- 'x': 88,
2484
- 'y': 89,
2485
- 'z': 90,
2486
- '0numpad': 96,
2487
- '1numpad': 97,
2488
- '2numpad': 98,
2489
- '3numpad': 99,
2490
- '4numpad': 100,
2491
- '5numpad': 101,
2492
- '6numpad': 102,
2493
- '7numpad': 103,
2494
- '8numpad': 104,
2495
- '9numpad': 105,
2496
- 'multiply': 106,
2497
- 'plus': 107,
2498
- 'minus': 109,
2499
- 'decimal': 110,
2500
- 'divide': 111,
2501
- 'f1': 112,
2502
- 'f2': 113,
2503
- 'f3': 114,
2504
- 'f4': 115,
2505
- 'f5': 116,
2506
- 'f6': 117,
2507
- 'f7': 118,
2508
- 'f8': 119,
2509
- 'f9': 120,
2510
- 'f10': 121,
2511
- 'f11': 122,
2512
- 'f12': 123,
2513
- '=': 187,
2514
- ',': 188,
2515
- '.': 190,
2516
- '/': 191,
2517
- '`': 192,
2518
- '[': 219,
2519
- '\\': 220,
2520
- ']': 221
2521
- };
2522
-
2523
- // timeout registration
2524
-
2525
- var timeout_handlers = [];
2526
-
2527
- module.setTimeout = function(callback, delay){
2528
- var handle = setTimeout(callback, delay);
2529
- timeout_handlers.push(handle);
2530
- return handle;
2531
- }
2532
-
2533
- module.clearAllTimeouts = function(){
2534
- for(var i=0;i<timeout_handlers.length; i++){
2535
- clearTimeout(timeout_handlers[i]);
2536
- }
2537
- timeout_handlers = [];
2538
- }
2539
-
2540
- // video //
2541
- var video_buffers = {}
2542
- module.getVideoBuffer = function(videoID) {
2543
- return video_buffers[videoID]
2544
- }
2545
-
2546
- // audio //
2547
- var context = null;
2548
- var audio_buffers = [];
2549
-
2550
- module.initAudio = function(){
2551
- context = (jsPsych.initSettings().use_webaudio === true) ? jsPsych.webaudio_context : null;
2552
- }
2553
-
2554
- module.audioContext = function(){
2555
- if(context !== null){
2556
- if(context.state !== 'running'){
2557
- context.resume();
2558
- }
2559
- }
2560
- return context;
2561
- }
2562
-
2563
- module.getAudioBuffer = function(audioID) {
2564
-
2565
- return new Promise(function(resolve, reject){
2566
- // check whether audio file already preloaded
2567
- if(typeof audio_buffers[audioID] == 'undefined' || audio_buffers[audioID] == 'tmp'){
2568
- // if audio is not already loaded, try to load it
2569
- function complete(){
2570
- resolve(audio_buffers[audioID])
2571
- }
2572
- function error(e){
2573
- reject(e.error);
2574
- }
2575
- module.preloadAudio([audioID], complete, function(){}, error)
2576
- } else {
2577
- // audio is already loaded
2578
- resolve(audio_buffers[audioID]);
2579
- }
2580
- });
2581
-
2582
- }
2583
-
2584
- // preloading stimuli //
2585
-
2586
- var preloads = [];
2587
- var preload_requests = [];
2588
-
2589
- var img_cache = {};
2590
-
2591
- module.preloadAudio = function(files, callback_complete, callback_load, callback_error) {
2592
-
2593
- files = jsPsych.utils.flatten(files);
2594
- files = jsPsych.utils.unique(files);
2595
-
2596
- var n_loaded = 0;
2597
- var loadfn = (typeof callback_load === 'undefined') ? function() {} : callback_load;
2598
- var finishfn = (typeof callback_complete === 'undefined') ? function() {} : callback_complete;
2599
- var errorfn = (typeof callback_error === 'undefined') ? function() {} : callback_error;
2600
-
2601
- if(files.length==0){
2602
- finishfn();
2603
- return;
2604
- }
2605
-
2606
- function load_audio_file_webaudio(source, count){
2607
- count = count || 1;
2608
- var request = new XMLHttpRequest();
2609
- request.open('GET', source, true);
2610
- request.responseType = 'arraybuffer';
2611
- request.onload = function() {
2612
- context.decodeAudioData(request.response, function(buffer) {
2613
- audio_buffers[source] = buffer;
2614
- n_loaded++;
2615
- loadfn(source);
2616
- if(n_loaded == files.length) {
2617
- finishfn();
2618
- }
2619
- }, function(e) {
2620
- errorfn({source: source, error: e});
2621
- });
2622
- }
2623
- request.onerror = function(e){
2624
- var err = e;
2625
- if(this.status == 404) {
2626
- err = "404";
2627
- }
2628
- errorfn({source: source, error: err});
2629
- }
2630
- request.onloadend = function(e){
2631
- if(this.status == 404) {
2632
- errorfn({source: source, error: "404"});
2633
- }
2634
- }
2635
- request.send();
2636
- preload_requests.push(request);
2637
- }
2638
-
2639
- function load_audio_file_html5audio(source, count){
2640
- count = count || 1;
2641
- var audio = new Audio();
2642
- audio.addEventListener('canplaythrough', function handleCanPlayThrough(){
2643
- audio_buffers[source] = audio;
2644
- n_loaded++;
2645
- loadfn(source);
2646
- if(n_loaded == files.length){
2647
- finishfn();
2648
- }
2649
- audio.removeEventListener('canplaythrough', handleCanPlayThrough);
2650
- });
2651
- audio.addEventListener('error', function handleError(e){
2652
- errorfn({source: audio.src, error: e});
2653
- audio.removeEventListener('error', handleError);
2654
- });
2655
- audio.addEventListener('abort', function handleAbort(e){
2656
- errorfn({source: audio.src, error: e});
2657
- audio.removeEventListener('abort', handleAbort);
2658
- });
2659
- audio.src = source;
2660
- preload_requests.push(audio);
2661
- }
2662
-
2663
- for (var i = 0; i < files.length; i++) {
2664
- var bufferID = files[i];
2665
- if (typeof audio_buffers[bufferID] !== 'undefined') {
2666
- n_loaded++;
2667
- loadfn(bufferID);
2668
- if(n_loaded == files.length) {
2669
- finishfn();
2670
- }
2671
- } else {
2672
- audio_buffers[bufferID] = 'tmp';
2673
- if(module.audioContext() !== null){
2674
- load_audio_file_webaudio(bufferID);
2675
- } else {
2676
- load_audio_file_html5audio(bufferID);
2677
- }
2678
- }
2679
- }
2680
-
2681
- }
2682
-
2683
- module.preloadImages = function(images, callback_complete, callback_load, callback_error) {
2684
-
2685
- // flatten the images array
2686
- images = jsPsych.utils.flatten(images);
2687
- images = jsPsych.utils.unique(images);
2688
-
2689
- var n_loaded = 0;
2690
- var finishfn = (typeof callback_complete === 'undefined') ? function() {} : callback_complete;
2691
- var loadfn = (typeof callback_load === 'undefined') ? function() {} : callback_load;
2692
- var errorfn = (typeof callback_error === 'undefined') ? function() {} : callback_error;
2693
-
2694
- if(images.length === 0){
2695
- finishfn();
2696
- return;
2697
- }
2698
-
2699
- function preload_image(source){
2700
- var img = new Image();
2701
-
2702
- img.onload = function() {
2703
- n_loaded++;
2704
- loadfn(img.src);
2705
- if (n_loaded === images.length) {
2706
- finishfn();
2707
- }
2708
- };
2709
-
2710
- img.onerror = function(e) {
2711
- errorfn({source: img.src, error: e});
2712
- }
2713
-
2714
- img.src = source;
2715
-
2716
- img_cache[source] = img;
2717
- preload_requests.push(img);
2718
- }
2719
-
2720
- for (var i = 0; i < images.length; i++) {
2721
- preload_image(images[i]);
2722
- }
2723
-
2724
- };
2725
-
2726
- module.preloadVideo = function(video, callback_complete, callback_load, callback_error) {
2727
-
2728
- // flatten the video array
2729
- video = jsPsych.utils.flatten(video);
2730
- video = jsPsych.utils.unique(video);
2731
-
2732
- var n_loaded = 0;
2733
- var finishfn = !callback_complete ? function() {} : callback_complete;
2734
- var loadfn = !callback_load ? function() {} : callback_load;
2735
- var errorfn = (typeof callback_error === 'undefined') ? function() {} : callback_error;
2736
-
2737
- if(video.length===0){
2738
- finishfn();
2739
- return;
2740
- }
2741
-
2742
- function preload_video(source, count){
2743
- count = count || 1;
2744
- //based on option 4 here: http://dinbror.dk/blog/how-to-preload-entire-html5-video-before-play-solved/
2745
- var request = new XMLHttpRequest();
2746
- request.open('GET', source, true);
2747
- request.responseType = 'blob';
2748
- request.onload = function() {
2749
- if (this.status === 200 || this.status === 0) {
2750
- var videoBlob = this.response;
2751
- video_buffers[source] = URL.createObjectURL(videoBlob); // IE10+
2752
- n_loaded++;
2753
- loadfn(source);
2754
- if (n_loaded === video.length) {
2755
- finishfn();
2756
- }
2757
- }
2758
- };
2759
- request.onerror = function(e){
2760
- var err = e;
2761
- if(this.status == 404) {
2762
- err = "404";
2763
- }
2764
- errorfn({source: source, error: err});
2765
- }
2766
- request.onloadend = function(e){
2767
- if(this.status == 404) {
2768
- errorfn({source: source, error: "404"});
2769
- }
2770
- }
2771
- request.send();
2772
- preload_requests.push(request);
2773
- }
2774
-
2775
- for (var i = 0; i < video.length; i++) {
2776
- preload_video(video[i]);
2777
- }
2778
-
2779
- };
2780
-
2781
- module.registerPreload = function(plugin_name, parameter, media_type) {
2782
- if (['audio', 'image', 'video'].indexOf(media_type)===-1) {
2783
- console.error('Invalid media_type parameter for jsPsych.pluginAPI.registerPreload. Please check the plugin file.');
2784
- }
2785
-
2786
- var preload = {
2787
- plugin: plugin_name,
2788
- parameter: parameter,
2789
- media_type: media_type
2790
- }
2791
-
2792
- preloads.push(preload);
2793
- }
2794
-
2795
- module.getAutoPreloadList = function(timeline_description){
2796
-
2797
- function getTrialsOfTypeFromTimelineDescription(td, target_type, inherited_type){
2798
- var trials = [];
2799
-
2800
- for(var i=0; i<td.length; i++){
2801
- var node = td[i];
2802
- if(Array.isArray(node.timeline)){
2803
- if(typeof node.type !== 'undefined'){
2804
- inherited_type = node.type;
2805
- }
2806
- trials = trials.concat(getTrialsOfTypeFromTimelineDescription(node.timeline, target_type, inherited_type));
2807
- } else {
2808
- if(typeof node.type !== 'undefined' && node.type == target_type){
2809
- trials.push(node);
2810
- }
2811
- if(typeof node.type == 'undefined' && inherited_type == target_type){
2812
- trials.push(Object.assign({}, {type: target_type}, node));
2813
- }
2814
- }
2815
- }
2816
-
2817
- return trials;
2818
- }
2819
-
2820
- if(typeof timeline_description == 'undefined'){
2821
- timeline_description = jsPsych.initSettings().timeline;
2822
- }
2823
-
2824
- // list of items to preload
2825
- var images = [];
2826
- var audio = [];
2827
- var video = [];
2828
-
2829
- // construct list
2830
- for (var i = 0; i < preloads.length; i++) {
2831
- var type = preloads[i].plugin;
2832
- var param = preloads[i].parameter;
2833
- var media = preloads[i].media_type;
2834
-
2835
- var trials = getTrialsOfTypeFromTimelineDescription(timeline_description, type);
2836
- for (var j = 0; j < trials.length; j++) {
2837
-
2838
- if (typeof trials[j][param] == 'undefined') {
2839
- console.warn("jsPsych failed to auto preload one or more files:");
2840
- console.warn("no parameter called "+param+" in plugin "+type);
2841
- } else if (typeof trials[j][param] !== 'function') {
2842
- if (media === 'image') {
2843
- images = images.concat(jsPsych.utils.flatten([trials[j][param]]));
2844
- } else if (media === 'audio') {
2845
- audio = audio.concat(jsPsych.utils.flatten([trials[j][param]]));
2846
- } else if (media === 'video') {
2847
- video = video.concat(jsPsych.utils.flatten([trials[j][param]]));
2848
- }
2849
- }
2850
- }
2851
- }
2852
-
2853
- images = jsPsych.utils.unique(jsPsych.utils.flatten(images));
2854
- audio = jsPsych.utils.unique(jsPsych.utils.flatten(audio));
2855
- video = jsPsych.utils.unique(jsPsych.utils.flatten(video));
2856
-
2857
- // remove any nulls false values
2858
- images = images.filter(function(x) { return x != false && x != null})
2859
- audio = audio.filter(function(x) { return x != false && x != null})
2860
- video = video.filter(function(x) { return x != false && x != null})
2861
-
2862
- return {
2863
- images, audio, video
2864
- }
2865
- }
2866
-
2867
- module.cancelPreloads = function() {
2868
- for(var i=0;i<preload_requests.length; i++){
2869
- preload_requests[i].onload = function() {};
2870
- preload_requests[i].onerror = function() {};
2871
- preload_requests[i].oncanplaythrough = function() {};
2872
- preload_requests[i].onabort = function() {};
2873
- }
2874
- preload_requests = [];
2875
- }
2876
-
2877
- /**
2878
- * Allows communication with user hardware through our custom Google Chrome extension + native C++ program
2879
- * @param {object} mess The message to be passed to our extension, see its documentation for the expected members of this object.
2880
- * @author Daniel Rivas
2881
- *
2882
- */
2883
- module.hardware = function hardware(mess){
2884
- //since Chrome extension content-scripts do not share the javascript environment with the page script that loaded jspsych,
2885
- //we will need to use hacky methods like communicating through DOM events.
2886
- var jspsychEvt = new CustomEvent('jspsych', {detail: mess});
2887
- document.dispatchEvent(jspsychEvt);
2888
- //And voila! it will be the job of the content script injected by the extension to listen for the event and do the appropriate actions.
2889
- };
2890
-
2891
- /** {boolean} Indicates whether this instance of jspsych has opened a hardware connection through our browser extension */
2892
- module.hardwareConnected = false;
2893
-
2894
-
2895
- //it might be useful to open up a line of communication from the extension back to this page script,
2896
- //again, this will have to pass through DOM events. For now speed is of no concern so I will use jQuery
2897
- document.addEventListener("jspsych-activate", function(evt){
2898
- module.hardwareConnected = true;
2899
- })
2900
-
2901
-
2902
-
2903
- return module;
2904
- })();
2905
-
2906
- // methods used in multiple modules //
2907
- jsPsych.utils = (function() {
2908
-
2909
- var module = {};
2910
-
2911
- module.flatten = function(arr, out) {
2912
- out = (typeof out === 'undefined') ? [] : out;
2913
- for (var i = 0; i < arr.length; i++) {
2914
- if (Array.isArray(arr[i])) {
2915
- module.flatten(arr[i], out);
2916
- } else {
2917
- out.push(arr[i]);
2918
- }
2919
- }
2920
- return out;
2921
- }
2922
-
2923
- module.unique = function(arr) {
2924
- var out = [];
2925
- for (var i = 0; i < arr.length; i++) {
2926
- if (arr.indexOf(arr[i]) == i) {
2927
- out.push(arr[i]);
2928
- }
2929
- }
2930
- return out;
2931
- }
2932
-
2933
- module.deepCopy = function(obj) {
2934
- if(!obj) return obj;
2935
- var out;
2936
- if(Array.isArray(obj)){
2937
- out = [];
2938
- for(var i = 0; i<obj.length; i++){
2939
- out.push(module.deepCopy(obj[i]));
2940
- }
2941
- return out;
2942
- } else if(typeof obj === 'object'){
2943
- out = {};
2944
- for(var key in obj){
2945
- if(obj.hasOwnProperty(key)){
2946
- out[key] = module.deepCopy(obj[key]);
2947
- }
2948
- }
2949
- return out;
2950
- } else {
2951
- return obj;
2952
- }
2953
- }
2954
-
2955
- return module;
2956
- })();
2957
-
2958
- // polyfill for Object.assign to support IE
2959
- if (typeof Object.assign != 'function') {
2960
- Object.assign = function (target, varArgs) { // .length of function is 2
2961
- 'use strict';
2962
- if (target == null) { // TypeError if undefined or null
2963
- throw new TypeError('Cannot convert undefined or null to object');
2964
- }
2965
-
2966
- var to = Object(target);
2967
-
2968
- for (var index = 1; index < arguments.length; index++) {
2969
- var nextSource = arguments[index];
2970
-
2971
- if (nextSource != null) { // Skip over if undefined or null
2972
- for (var nextKey in nextSource) {
2973
- // Avoid bugs when hasOwnProperty is shadowed
2974
- if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
2975
- to[nextKey] = nextSource[nextKey];
2976
- }
2977
- }
2978
- }
2979
- }
2980
- return to;
2981
- };
2982
- }
2983
-
2984
- // polyfill for Array.includes to support IE
2985
- if (!Array.prototype.includes) {
2986
- Array.prototype.includes = function(searchElement /*, fromIndex*/) {
2987
- 'use strict';
2988
- if (this == null) {
2989
- throw new TypeError('Array.prototype.includes called on null or undefined');
2990
- }
2991
-
2992
- var O = Object(this);
2993
- var len = parseInt(O.length, 10) || 0;
2994
- if (len === 0) {
2995
- return false;
2996
- }
2997
- var n = parseInt(arguments[1], 10) || 0;
2998
- var k;
2999
- if (n >= 0) {
3000
- k = n;
3001
- } else {
3002
- k = len + n;
3003
- if (k < 0) {k = 0;}
3004
- }
3005
- var currentElement;
3006
- while (k < len) {
3007
- currentElement = O[k];
3008
- if (searchElement === currentElement ||
3009
- (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
3010
- return true;
3011
- }
3012
- k++;
3013
- }
3014
- return false;
3015
- };
3016
- }
3017
-
3018
- // polyfill for Array.isArray
3019
- if (!Array.isArray) {
3020
- Array.isArray = function(arg) {
3021
- return Object.prototype.toString.call(arg) === '[object Array]';
3022
- };
3023
- }