jspsych 6.3.0 → 7.1.1

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 (397) 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 +3164 -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 +3158 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +11 -0
  12. package/dist/index.js +3152 -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 +129 -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 +158 -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 -734
  59. package/docs/core_library/jspsych-data.md +0 -589
  60. package/docs/core_library/jspsych-pluginAPI.md +0 -610
  61. package/docs/core_library/jspsych-randomization.md +0 -397
  62. package/docs/core_library/jspsych-turk.md +0 -102
  63. package/docs/extensions/extensions.md +0 -83
  64. package/docs/extensions/jspsych-ext-webgazer.md +0 -106
  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 -184
  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 -237
  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 -60
  145. package/docs/plugins/jspsych-webgazer-init-camera.md +0 -31
  146. package/docs/plugins/jspsych-webgazer-validate.md +0 -43
  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.js +0 -88886
  216. package/examples/jspsych-RDK.html +0 -58
  217. package/examples/jspsych-animation.html +0 -39
  218. package/examples/jspsych-audio-button-response.html +0 -58
  219. package/examples/jspsych-audio-keyboard-response.html +0 -68
  220. package/examples/jspsych-audio-slider-response.html +0 -61
  221. package/examples/jspsych-call-function.html +0 -32
  222. package/examples/jspsych-canvas-button-response.html +0 -95
  223. package/examples/jspsych-canvas-keyboard-response.html +0 -78
  224. package/examples/jspsych-canvas-slider-response.html +0 -67
  225. package/examples/jspsych-categorize-animation.html +0 -49
  226. package/examples/jspsych-categorize-html.html +0 -33
  227. package/examples/jspsych-categorize-image.html +0 -44
  228. package/examples/jspsych-cloze.html +0 -37
  229. package/examples/jspsych-free-sort.html +0 -109
  230. package/examples/jspsych-fullscreen.html +0 -45
  231. package/examples/jspsych-html-button-response.html +0 -43
  232. package/examples/jspsych-html-keyboard-response.html +0 -42
  233. package/examples/jspsych-html-slider-response.html +0 -53
  234. package/examples/jspsych-iat.html +0 -520
  235. package/examples/jspsych-image-button-response.html +0 -91
  236. package/examples/jspsych-image-keyboard-response.html +0 -85
  237. package/examples/jspsych-image-slider-response.html +0 -85
  238. package/examples/jspsych-instructions.html +0 -37
  239. package/examples/jspsych-maxdiff.html +0 -33
  240. package/examples/jspsych-preload.html +0 -140
  241. package/examples/jspsych-reconstruction.html +0 -43
  242. package/examples/jspsych-resize.html +0 -34
  243. package/examples/jspsych-same-different-html.html +0 -28
  244. package/examples/jspsych-same-different-image.html +0 -39
  245. package/examples/jspsych-serial-reaction-time-mouse.html +0 -98
  246. package/examples/jspsych-serial-reaction-time.html +0 -54
  247. package/examples/jspsych-survey-html-form.html +0 -33
  248. package/examples/jspsych-survey-likert.html +0 -42
  249. package/examples/jspsych-survey-multi-choice.html +0 -40
  250. package/examples/jspsych-survey-multi-select.html +0 -42
  251. package/examples/jspsych-survey-text.html +0 -34
  252. package/examples/jspsych-video-button-response.html +0 -65
  253. package/examples/jspsych-video-keyboard-response.html +0 -61
  254. package/examples/jspsych-video-slider-response.html +0 -63
  255. package/examples/jspsych-virtual-chinrest.html +0 -69
  256. package/examples/jspsych-visual-search-circle.html +0 -64
  257. package/examples/jspsych-vsl-animate-occlusion.html +0 -35
  258. package/examples/jspsych-vsl-grid-scene.html +0 -47
  259. package/examples/lexical-decision.html +0 -134
  260. package/examples/manual-preloading.html +0 -59
  261. package/examples/pause-unpause.html +0 -33
  262. package/examples/progress-bar.html +0 -68
  263. package/examples/save-trial-parameters.html +0 -98
  264. package/examples/sound/hammer.mp3 +0 -0
  265. package/examples/sound/sound.mp3 +0 -0
  266. package/examples/sound/speech_blue.mp3 +0 -0
  267. package/examples/sound/speech_green.mp3 +0 -0
  268. package/examples/sound/speech_joke.mp3 +0 -0
  269. package/examples/sound/speech_red.mp3 +0 -0
  270. package/examples/sound/tone.mp3 +0 -0
  271. package/examples/timeline-variables-sampling.html +0 -50
  272. package/examples/timeline-variables.html +0 -64
  273. package/examples/video/sample_video.mp4 +0 -0
  274. package/examples/webgazer.html +0 -162
  275. package/examples/webgazer_image.html +0 -60
  276. package/extensions/jspsych-ext-webgazer.js +0 -185
  277. package/jspsych.js +0 -3015
  278. package/license.txt +0 -21
  279. package/mkdocs.yml +0 -118
  280. package/plugins/jspsych-animation.js +0 -189
  281. package/plugins/jspsych-audio-button-response.js +0 -269
  282. package/plugins/jspsych-audio-keyboard-response.js +0 -212
  283. package/plugins/jspsych-audio-slider-response.js +0 -278
  284. package/plugins/jspsych-call-function.js +0 -58
  285. package/plugins/jspsych-canvas-button-response.js +0 -199
  286. package/plugins/jspsych-canvas-keyboard-response.js +0 -155
  287. package/plugins/jspsych-canvas-slider-response.js +0 -207
  288. package/plugins/jspsych-categorize-animation.js +0 -266
  289. package/plugins/jspsych-categorize-html.js +0 -220
  290. package/plugins/jspsych-categorize-image.js +0 -222
  291. package/plugins/jspsych-cloze.js +0 -112
  292. package/plugins/jspsych-external-html.js +0 -112
  293. package/plugins/jspsych-free-sort.js +0 -478
  294. package/plugins/jspsych-fullscreen.js +0 -106
  295. package/plugins/jspsych-html-button-response.js +0 -188
  296. package/plugins/jspsych-html-keyboard-response.js +0 -149
  297. package/plugins/jspsych-html-slider-response.js +0 -202
  298. package/plugins/jspsych-iat-html.js +0 -284
  299. package/plugins/jspsych-iat-image.js +0 -286
  300. package/plugins/jspsych-image-button-response.js +0 -327
  301. package/plugins/jspsych-image-keyboard-response.js +0 -263
  302. package/plugins/jspsych-image-slider-response.js +0 -369
  303. package/plugins/jspsych-instructions.js +0 -237
  304. package/plugins/jspsych-maxdiff.js +0 -173
  305. package/plugins/jspsych-preload.js +0 -345
  306. package/plugins/jspsych-rdk.js +0 -1373
  307. package/plugins/jspsych-reconstruction.js +0 -134
  308. package/plugins/jspsych-resize.js +0 -166
  309. package/plugins/jspsych-same-different-html.js +0 -168
  310. package/plugins/jspsych-same-different-image.js +0 -169
  311. package/plugins/jspsych-serial-reaction-time-mouse.js +0 -212
  312. package/plugins/jspsych-serial-reaction-time.js +0 -247
  313. package/plugins/jspsych-survey-html-form.js +0 -171
  314. package/plugins/jspsych-survey-likert.js +0 -195
  315. package/plugins/jspsych-survey-multi-choice.js +0 -208
  316. package/plugins/jspsych-survey-multi-select.js +0 -232
  317. package/plugins/jspsych-survey-text.js +0 -185
  318. package/plugins/jspsych-video-button-response.js +0 -335
  319. package/plugins/jspsych-video-keyboard-response.js +0 -279
  320. package/plugins/jspsych-video-slider-response.js +0 -351
  321. package/plugins/jspsych-virtual-chinrest.js +0 -471
  322. package/plugins/jspsych-visual-search-circle.js +0 -259
  323. package/plugins/jspsych-vsl-animate-occlusion.js +0 -196
  324. package/plugins/jspsych-vsl-grid-scene.js +0 -103
  325. package/plugins/jspsych-webgazer-calibrate.js +0 -166
  326. package/plugins/jspsych-webgazer-init-camera.js +0 -95
  327. package/plugins/jspsych-webgazer-validate.js +0 -304
  328. package/plugins/template/jspsych-plugin-template.js +0 -35
  329. package/tests/README.md +0 -7
  330. package/tests/jsPsych/case-sensitive-responses.test.js +0 -53
  331. package/tests/jsPsych/css-classes-parameter.test.js +0 -107
  332. package/tests/jsPsych/default-iti.test.js +0 -51
  333. package/tests/jsPsych/default-parameters.test.js +0 -58
  334. package/tests/jsPsych/endexperiment.test.js +0 -49
  335. package/tests/jsPsych/events.test.js +0 -606
  336. package/tests/jsPsych/functions-as-parameters.test.js +0 -210
  337. package/tests/jsPsych/init.test.js +0 -48
  338. package/tests/jsPsych/loads.test.js +0 -7
  339. package/tests/jsPsych/min-rt.test.js +0 -58
  340. package/tests/jsPsych/progressbar.test.js +0 -202
  341. package/tests/jsPsych/timeline-variables.test.js +0 -531
  342. package/tests/jsPsych/timelines.test.js +0 -569
  343. package/tests/jsPsych.data/data-csv-conversion.test.js +0 -85
  344. package/tests/jsPsych.data/data-json-conversion.test.js +0 -120
  345. package/tests/jsPsych.data/datacollection.test.js +0 -117
  346. package/tests/jsPsych.data/datacolumn.test.js +0 -50
  347. package/tests/jsPsych.data/datamodule.test.js +0 -152
  348. package/tests/jsPsych.data/dataparameter.test.js +0 -251
  349. package/tests/jsPsych.data/interactions.test.js +0 -109
  350. package/tests/jsPsych.data/trialparameters.test.js +0 -175
  351. package/tests/jsPsych.extensions/extensions.test.js +0 -207
  352. package/tests/jsPsych.extensions/test-extension.js +0 -42
  353. package/tests/jsPsych.pluginAPI/pluginapi.test.js +0 -341
  354. package/tests/jsPsych.pluginAPI/preloads.test.js +0 -43
  355. package/tests/jsPsych.randomization/randomziation.test.js +0 -27
  356. package/tests/jsPsych.utils/utils.test.js +0 -58
  357. package/tests/plugins/plugin-animation.test.js +0 -34
  358. package/tests/plugins/plugin-audio-button-response.test.js +0 -15
  359. package/tests/plugins/plugin-audio-keyboard-response.test.js +0 -15
  360. package/tests/plugins/plugin-audio-slider-response.test.js +0 -15
  361. package/tests/plugins/plugin-call-function.test.js +0 -49
  362. package/tests/plugins/plugin-categorize-animation.test.js +0 -263
  363. package/tests/plugins/plugin-categorize-html.test.js +0 -17
  364. package/tests/plugins/plugin-categorize-image.test.js +0 -17
  365. package/tests/plugins/plugin-cloze.test.js +0 -157
  366. package/tests/plugins/plugin-free-sort.test.js +0 -106
  367. package/tests/plugins/plugin-fullscreen.test.js +0 -41
  368. package/tests/plugins/plugin-html-button-response.test.js +0 -161
  369. package/tests/plugins/plugin-html-keyboard-response.test.js +0 -139
  370. package/tests/plugins/plugin-html-slider-response.test.js +0 -155
  371. package/tests/plugins/plugin-iat-html.test.js +0 -299
  372. package/tests/plugins/plugin-iat-image.test.js +0 -298
  373. package/tests/plugins/plugin-image-button-response.test.js +0 -174
  374. package/tests/plugins/plugin-image-keyboard-response.test.js +0 -147
  375. package/tests/plugins/plugin-image-slider-response.test.js +0 -174
  376. package/tests/plugins/plugin-instructions.test.js +0 -85
  377. package/tests/plugins/plugin-maxdiff.test.js +0 -39
  378. package/tests/plugins/plugin-preload.test.js +0 -916
  379. package/tests/plugins/plugin-rdk.test.js +0 -61
  380. package/tests/plugins/plugin-reconstruction.test.js +0 -16
  381. package/tests/plugins/plugin-resize.test.js +0 -16
  382. package/tests/plugins/plugin-same-different-html.test.js +0 -17
  383. package/tests/plugins/plugin-same-different-image.test.js +0 -17
  384. package/tests/plugins/plugin-serial-reaction-time-mouse.test.js +0 -42
  385. package/tests/plugins/plugin-serial-reaction-time.test.js +0 -109
  386. package/tests/plugins/plugin-survey-html-form.test.js +0 -44
  387. package/tests/plugins/plugin-survey-likert.test.js +0 -48
  388. package/tests/plugins/plugin-survey-multi-choice.test.js +0 -47
  389. package/tests/plugins/plugin-survey-multi-select.test.js +0 -71
  390. package/tests/plugins/plugin-survey-text.test.js +0 -115
  391. package/tests/plugins/plugin-video-button-response.test.js +0 -32
  392. package/tests/plugins/plugin-video-keyboard-response.test.js +0 -32
  393. package/tests/plugins/plugin-video-slider-response.test.js +0 -31
  394. package/tests/plugins/plugin-visual-search-circle.test.js +0 -16
  395. package/tests/plugins/plugin-vsl-animate-occlusion.test.js +0 -16
  396. package/tests/plugins/plugin-vsl-grid-scene.test.js +0 -16
  397. package/tests/testing-utils.js +0 -13
@@ -0,0 +1,3164 @@
1
+ var jsPsychModule = (function (exports) {
2
+ 'use strict';
3
+
4
+ /*! *****************************************************************************
5
+ Copyright (c) Microsoft Corporation.
6
+
7
+ Permission to use, copy, modify, and/or distribute this software for any
8
+ purpose with or without fee is hereby granted.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
11
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
15
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16
+ PERFORMANCE OF THIS SOFTWARE.
17
+ ***************************************************************************** */
18
+
19
+ function __awaiter(thisArg, _arguments, P, generator) {
20
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
21
+ return new (P || (P = Promise))(function (resolve, reject) {
22
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
23
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
24
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
25
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
26
+ });
27
+ }
28
+
29
+ // Gets all non-builtin properties up the prototype chain
30
+ const getAllProperties = object => {
31
+ const properties = new Set();
32
+
33
+ do {
34
+ for (const key of Reflect.ownKeys(object)) {
35
+ properties.add([object, key]);
36
+ }
37
+ } while ((object = Reflect.getPrototypeOf(object)) && object !== Object.prototype);
38
+
39
+ return properties;
40
+ };
41
+
42
+ var autoBind = (self, {include, exclude} = {}) => {
43
+ const filter = key => {
44
+ const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);
45
+
46
+ if (include) {
47
+ return include.some(match);
48
+ }
49
+
50
+ if (exclude) {
51
+ return !exclude.some(match);
52
+ }
53
+
54
+ return true;
55
+ };
56
+
57
+ for (const [object, key] of getAllProperties(self.constructor.prototype)) {
58
+ if (key === 'constructor' || !filter(key)) {
59
+ continue;
60
+ }
61
+
62
+ const descriptor = Reflect.getOwnPropertyDescriptor(object, key);
63
+ if (descriptor && typeof descriptor.value === 'function') {
64
+ self[key] = self[key].bind(self);
65
+ }
66
+ }
67
+
68
+ return self;
69
+ };
70
+
71
+ var version = "7.1.1";
72
+
73
+ class MigrationError extends Error {
74
+ constructor(message = "The global `jsPsych` variable is no longer available in jsPsych v7.") {
75
+ super(`${message} Please follow the migration guide at https://www.jspsych.org/7.0/support/migration-v7/ to update your experiment.`);
76
+ this.name = "MigrationError";
77
+ }
78
+ }
79
+ // Define a global jsPsych object to handle invocations on it with migration errors
80
+ window.jsPsych = {
81
+ get init() {
82
+ throw new MigrationError("`jsPsych.init()` was replaced by `initJsPsych()` in jsPsych v7.");
83
+ },
84
+ get data() {
85
+ throw new MigrationError();
86
+ },
87
+ get randomization() {
88
+ throw new MigrationError();
89
+ },
90
+ get turk() {
91
+ throw new MigrationError();
92
+ },
93
+ get pluginAPI() {
94
+ throw new MigrationError();
95
+ },
96
+ get ALL_KEYS() {
97
+ throw new MigrationError('jsPsych.ALL_KEYS was replaced by the "ALL_KEYS" string in jsPsych v7.');
98
+ },
99
+ get NO_KEYS() {
100
+ throw new MigrationError('jsPsych.NO_KEYS was replaced by the "NO_KEYS" string in jsPsych v7.');
101
+ },
102
+ };
103
+
104
+ /**
105
+ * Finds all of the unique items in an array.
106
+ * @param arr The array to extract unique values from
107
+ * @returns An array with one copy of each unique item in `arr`
108
+ */
109
+ function unique(arr) {
110
+ return [...new Set(arr)];
111
+ }
112
+ function deepCopy(obj) {
113
+ if (!obj)
114
+ return obj;
115
+ let out;
116
+ if (Array.isArray(obj)) {
117
+ out = [];
118
+ for (const x of obj) {
119
+ out.push(deepCopy(x));
120
+ }
121
+ return out;
122
+ }
123
+ else if (typeof obj === "object" && obj !== null) {
124
+ out = {};
125
+ for (const key in obj) {
126
+ if (obj.hasOwnProperty(key)) {
127
+ out[key] = deepCopy(obj[key]);
128
+ }
129
+ }
130
+ return out;
131
+ }
132
+ else {
133
+ return obj;
134
+ }
135
+ }
136
+
137
+ var utils = /*#__PURE__*/Object.freeze({
138
+ __proto__: null,
139
+ unique: unique,
140
+ deepCopy: deepCopy
141
+ });
142
+
143
+ class DataColumn {
144
+ constructor(values = []) {
145
+ this.values = values;
146
+ }
147
+ sum() {
148
+ let s = 0;
149
+ for (const v of this.values) {
150
+ s += v;
151
+ }
152
+ return s;
153
+ }
154
+ mean() {
155
+ return this.sum() / this.count();
156
+ }
157
+ median() {
158
+ if (this.values.length === 0) {
159
+ return undefined;
160
+ }
161
+ const numbers = this.values.slice(0).sort(function (a, b) {
162
+ return a - b;
163
+ });
164
+ const middle = Math.floor(numbers.length / 2);
165
+ const isEven = numbers.length % 2 === 0;
166
+ return isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle];
167
+ }
168
+ min() {
169
+ return Math.min.apply(null, this.values);
170
+ }
171
+ max() {
172
+ return Math.max.apply(null, this.values);
173
+ }
174
+ count() {
175
+ return this.values.length;
176
+ }
177
+ variance() {
178
+ const mean = this.mean();
179
+ let sum_square_error = 0;
180
+ for (const x of this.values) {
181
+ sum_square_error += Math.pow(x - mean, 2);
182
+ }
183
+ const mse = sum_square_error / (this.values.length - 1);
184
+ return mse;
185
+ }
186
+ sd() {
187
+ const mse = this.variance();
188
+ const rmse = Math.sqrt(mse);
189
+ return rmse;
190
+ }
191
+ frequencies() {
192
+ const unique = {};
193
+ for (const x of this.values) {
194
+ if (typeof unique[x] === "undefined") {
195
+ unique[x] = 1;
196
+ }
197
+ else {
198
+ unique[x]++;
199
+ }
200
+ }
201
+ return unique;
202
+ }
203
+ all(eval_fn) {
204
+ for (const x of this.values) {
205
+ if (!eval_fn(x)) {
206
+ return false;
207
+ }
208
+ }
209
+ return true;
210
+ }
211
+ subset(eval_fn) {
212
+ const out = [];
213
+ for (const x of this.values) {
214
+ if (eval_fn(x)) {
215
+ out.push(x);
216
+ }
217
+ }
218
+ return new DataColumn(out);
219
+ }
220
+ }
221
+
222
+ // private function to save text file on local drive
223
+ function saveTextToFile(textstr, filename) {
224
+ const blobToSave = new Blob([textstr], {
225
+ type: "text/plain",
226
+ });
227
+ let blobURL = "";
228
+ if (typeof window.webkitURL !== "undefined") {
229
+ blobURL = window.webkitURL.createObjectURL(blobToSave);
230
+ }
231
+ else {
232
+ blobURL = window.URL.createObjectURL(blobToSave);
233
+ }
234
+ const link = document.createElement("a");
235
+ link.id = "jspsych-download-as-text-link";
236
+ link.style.display = "none";
237
+ link.download = filename;
238
+ link.href = blobURL;
239
+ link.click();
240
+ }
241
+ // this function based on code suggested by StackOverflow users:
242
+ // http://stackoverflow.com/users/64741/zachary
243
+ // http://stackoverflow.com/users/317/joseph-sturtevant
244
+ function JSON2CSV(objArray) {
245
+ const array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
246
+ let line = "";
247
+ let result = "";
248
+ const columns = [];
249
+ for (const row of array) {
250
+ for (const key in row) {
251
+ let keyString = key + "";
252
+ keyString = '"' + keyString.replace(/"/g, '""') + '",';
253
+ if (!columns.includes(key)) {
254
+ columns.push(key);
255
+ line += keyString;
256
+ }
257
+ }
258
+ }
259
+ line = line.slice(0, -1); // removes last comma
260
+ result += line + "\r\n";
261
+ for (const row of array) {
262
+ line = "";
263
+ for (const col of columns) {
264
+ let value = typeof row[col] === "undefined" ? "" : row[col];
265
+ if (typeof value == "object") {
266
+ value = JSON.stringify(value);
267
+ }
268
+ const valueString = value + "";
269
+ line += '"' + valueString.replace(/"/g, '""') + '",';
270
+ }
271
+ line = line.slice(0, -1);
272
+ result += line + "\r\n";
273
+ }
274
+ return result;
275
+ }
276
+ // this function is modified from StackOverflow:
277
+ // http://stackoverflow.com/posts/3855394
278
+ function getQueryString() {
279
+ const a = window.location.search.substr(1).split("&");
280
+ const b = {};
281
+ for (let i = 0; i < a.length; ++i) {
282
+ const p = a[i].split("=", 2);
283
+ if (p.length == 1)
284
+ b[p[0]] = "";
285
+ else
286
+ b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
287
+ }
288
+ return b;
289
+ }
290
+
291
+ class DataCollection {
292
+ constructor(data = []) {
293
+ this.trials = data;
294
+ }
295
+ push(new_data) {
296
+ this.trials.push(new_data);
297
+ return this;
298
+ }
299
+ join(other_data_collection) {
300
+ this.trials = this.trials.concat(other_data_collection.values());
301
+ return this;
302
+ }
303
+ top() {
304
+ if (this.trials.length <= 1) {
305
+ return this;
306
+ }
307
+ else {
308
+ return new DataCollection([this.trials[this.trials.length - 1]]);
309
+ }
310
+ }
311
+ /**
312
+ * Queries the first n elements in a collection of trials.
313
+ *
314
+ * @param n A positive integer of elements to return. A value of
315
+ * n that is less than 1 will throw an error.
316
+ *
317
+ * @return First n objects of a collection of trials. If fewer than
318
+ * n trials are available, the trials.length elements will
319
+ * be returned.
320
+ *
321
+ */
322
+ first(n = 1) {
323
+ if (n < 1) {
324
+ throw `You must query with a positive nonzero integer. Please use a
325
+ different value for n.`;
326
+ }
327
+ if (this.trials.length === 0)
328
+ return new DataCollection();
329
+ if (n > this.trials.length)
330
+ n = this.trials.length;
331
+ return new DataCollection(this.trials.slice(0, n));
332
+ }
333
+ /**
334
+ * Queries the last n elements in a collection of trials.
335
+ *
336
+ * @param n A positive integer of elements to return. A value of
337
+ * n that is less than 1 will throw an error.
338
+ *
339
+ * @return Last n objects of a collection of trials. If fewer than
340
+ * n trials are available, the trials.length elements will
341
+ * be returned.
342
+ *
343
+ */
344
+ last(n = 1) {
345
+ if (n < 1) {
346
+ throw `You must query with a positive nonzero integer. Please use a
347
+ different value for n.`;
348
+ }
349
+ if (this.trials.length === 0)
350
+ return new DataCollection();
351
+ if (n > this.trials.length)
352
+ n = this.trials.length;
353
+ return new DataCollection(this.trials.slice(this.trials.length - n, this.trials.length));
354
+ }
355
+ values() {
356
+ return this.trials;
357
+ }
358
+ count() {
359
+ return this.trials.length;
360
+ }
361
+ readOnly() {
362
+ return new DataCollection(deepCopy(this.trials));
363
+ }
364
+ addToAll(properties) {
365
+ for (const trial of this.trials) {
366
+ Object.assign(trial, properties);
367
+ }
368
+ return this;
369
+ }
370
+ addToLast(properties) {
371
+ if (this.trials.length != 0) {
372
+ Object.assign(this.trials[this.trials.length - 1], properties);
373
+ }
374
+ return this;
375
+ }
376
+ filter(filters) {
377
+ // [{p1: v1, p2:v2}, {p1:v2}]
378
+ // {p1: v1}
379
+ let f;
380
+ if (!Array.isArray(filters)) {
381
+ f = deepCopy([filters]);
382
+ }
383
+ else {
384
+ f = deepCopy(filters);
385
+ }
386
+ const filtered_data = [];
387
+ for (const trial of this.trials) {
388
+ let keep = false;
389
+ for (const filter of f) {
390
+ let match = true;
391
+ for (const key of Object.keys(filter)) {
392
+ if (typeof trial[key] !== "undefined" && trial[key] === filter[key]) ;
393
+ else {
394
+ match = false;
395
+ }
396
+ }
397
+ if (match) {
398
+ keep = true;
399
+ break;
400
+ } // can break because each filter is OR.
401
+ }
402
+ if (keep) {
403
+ filtered_data.push(trial);
404
+ }
405
+ }
406
+ return new DataCollection(filtered_data);
407
+ }
408
+ filterCustom(fn) {
409
+ return new DataCollection(this.trials.filter(fn));
410
+ }
411
+ select(column) {
412
+ const values = [];
413
+ for (const trial of this.trials) {
414
+ if (typeof trial[column] !== "undefined") {
415
+ values.push(trial[column]);
416
+ }
417
+ }
418
+ return new DataColumn(values);
419
+ }
420
+ ignore(columns) {
421
+ if (!Array.isArray(columns)) {
422
+ columns = [columns];
423
+ }
424
+ const o = deepCopy(this.trials);
425
+ for (const trial of o) {
426
+ for (const delete_key of columns) {
427
+ delete trial[delete_key];
428
+ }
429
+ }
430
+ return new DataCollection(o);
431
+ }
432
+ uniqueNames() {
433
+ const names = [];
434
+ for (const trial of this.trials) {
435
+ for (const key of Object.keys(trial)) {
436
+ if (!names.includes(key)) {
437
+ names.push(key);
438
+ }
439
+ }
440
+ }
441
+ return names;
442
+ }
443
+ csv() {
444
+ return JSON2CSV(this.trials);
445
+ }
446
+ json(pretty = false) {
447
+ if (pretty) {
448
+ return JSON.stringify(this.trials, null, "\t");
449
+ }
450
+ return JSON.stringify(this.trials);
451
+ }
452
+ localSave(format, filename) {
453
+ format = format.toLowerCase();
454
+ let data_string;
455
+ if (format === "json") {
456
+ data_string = this.json();
457
+ }
458
+ else if (format === "csv") {
459
+ data_string = this.csv();
460
+ }
461
+ else {
462
+ throw new Error('Invalid format specified for localSave. Must be "json" or "csv".');
463
+ }
464
+ saveTextToFile(data_string, filename);
465
+ }
466
+ }
467
+
468
+ class JsPsychData {
469
+ constructor(jsPsych) {
470
+ this.jsPsych = jsPsych;
471
+ // data properties for all trials
472
+ this.dataProperties = {};
473
+ this.reset();
474
+ }
475
+ reset() {
476
+ this.allData = new DataCollection();
477
+ this.interactionData = new DataCollection();
478
+ }
479
+ get() {
480
+ return this.allData;
481
+ }
482
+ getInteractionData() {
483
+ return this.interactionData;
484
+ }
485
+ write(data_object) {
486
+ const progress = this.jsPsych.getProgress();
487
+ const trial = this.jsPsych.getCurrentTrial();
488
+ //var trial_opt_data = typeof trial.data == 'function' ? trial.data() : trial.data;
489
+ const default_data = {
490
+ trial_type: trial.type.info.name,
491
+ trial_index: progress.current_trial_global,
492
+ time_elapsed: this.jsPsych.getTotalTime(),
493
+ internal_node_id: this.jsPsych.getCurrentTimelineNodeID(),
494
+ };
495
+ this.allData.push(Object.assign(Object.assign(Object.assign(Object.assign({}, data_object), trial.data), default_data), this.dataProperties));
496
+ }
497
+ addProperties(properties) {
498
+ // first, add the properties to all data that's already stored
499
+ this.allData.addToAll(properties);
500
+ // now add to list so that it gets appended to all future data
501
+ this.dataProperties = Object.assign({}, this.dataProperties, properties);
502
+ }
503
+ addDataToLastTrial(data) {
504
+ this.allData.addToLast(data);
505
+ }
506
+ getDataByTimelineNode(node_id) {
507
+ return this.allData.filterCustom((x) => x.internal_node_id.slice(0, node_id.length) === node_id);
508
+ }
509
+ getLastTrialData() {
510
+ return this.allData.top();
511
+ }
512
+ getLastTimelineData() {
513
+ const lasttrial = this.getLastTrialData();
514
+ const node_id = lasttrial.select("internal_node_id").values[0];
515
+ if (typeof node_id === "undefined") {
516
+ return new DataCollection();
517
+ }
518
+ else {
519
+ const parent_node_id = node_id.substr(0, node_id.lastIndexOf("-"));
520
+ const lastnodedata = this.getDataByTimelineNode(parent_node_id);
521
+ return lastnodedata;
522
+ }
523
+ }
524
+ displayData(format = "json") {
525
+ format = format.toLowerCase();
526
+ if (format != "json" && format != "csv") {
527
+ console.log("Invalid format declared for displayData function. Using json as default.");
528
+ format = "json";
529
+ }
530
+ const data_string = format === "json" ? this.allData.json(true) : this.allData.csv();
531
+ const display_element = this.jsPsych.getDisplayElement();
532
+ display_element.innerHTML = '<pre id="jspsych-data-display"></pre>';
533
+ document.getElementById("jspsych-data-display").textContent = data_string;
534
+ }
535
+ urlVariables() {
536
+ if (typeof this.query_string == "undefined") {
537
+ this.query_string = getQueryString();
538
+ }
539
+ return this.query_string;
540
+ }
541
+ getURLVariable(whichvar) {
542
+ return this.urlVariables()[whichvar];
543
+ }
544
+ createInteractionListeners() {
545
+ // blur event capture
546
+ window.addEventListener("blur", () => {
547
+ const data = {
548
+ event: "blur",
549
+ trial: this.jsPsych.getProgress().current_trial_global,
550
+ time: this.jsPsych.getTotalTime(),
551
+ };
552
+ this.interactionData.push(data);
553
+ this.jsPsych.getInitSettings().on_interaction_data_update(data);
554
+ });
555
+ // focus event capture
556
+ window.addEventListener("focus", () => {
557
+ const data = {
558
+ event: "focus",
559
+ trial: this.jsPsych.getProgress().current_trial_global,
560
+ time: this.jsPsych.getTotalTime(),
561
+ };
562
+ this.interactionData.push(data);
563
+ this.jsPsych.getInitSettings().on_interaction_data_update(data);
564
+ });
565
+ // fullscreen change capture
566
+ const fullscreenchange = () => {
567
+ const data = {
568
+ event:
569
+ // @ts-expect-error
570
+ document.isFullScreen ||
571
+ // @ts-expect-error
572
+ document.webkitIsFullScreen ||
573
+ // @ts-expect-error
574
+ document.mozIsFullScreen ||
575
+ document.fullscreenElement
576
+ ? "fullscreenenter"
577
+ : "fullscreenexit",
578
+ trial: this.jsPsych.getProgress().current_trial_global,
579
+ time: this.jsPsych.getTotalTime(),
580
+ };
581
+ this.interactionData.push(data);
582
+ this.jsPsych.getInitSettings().on_interaction_data_update(data);
583
+ };
584
+ document.addEventListener("fullscreenchange", fullscreenchange);
585
+ document.addEventListener("mozfullscreenchange", fullscreenchange);
586
+ document.addEventListener("webkitfullscreenchange", fullscreenchange);
587
+ }
588
+ // public methods for testing purposes. not recommended for use.
589
+ _customInsert(data) {
590
+ this.allData = new DataCollection(data);
591
+ }
592
+ _fullreset() {
593
+ this.reset();
594
+ this.dataProperties = {};
595
+ }
596
+ }
597
+
598
+ class HardwareAPI {
599
+ constructor() {
600
+ /**
601
+ * Indicates whether this instance of jspsych has opened a hardware connection through our browser
602
+ * extension
603
+ **/
604
+ this.hardwareConnected = false;
605
+ //it might be useful to open up a line of communication from the extension back to this page
606
+ //script, again, this will have to pass through DOM events. For now speed is of no concern so I
607
+ //will use jQuery
608
+ document.addEventListener("jspsych-activate", (evt) => {
609
+ this.hardwareConnected = true;
610
+ });
611
+ }
612
+ /**
613
+ * Allows communication with user hardware through our custom Google Chrome extension + native C++ program
614
+ * @param mess The message to be passed to our extension, see its documentation for the expected members of this object.
615
+ * @author Daniel Rivas
616
+ *
617
+ */
618
+ hardware(mess) {
619
+ //since Chrome extension content-scripts do not share the javascript environment with the page
620
+ //script that loaded jspsych, we will need to use hacky methods like communicating through DOM
621
+ //events.
622
+ const jspsychEvt = new CustomEvent("jspsych", { detail: mess });
623
+ document.dispatchEvent(jspsychEvt);
624
+ //And voila! it will be the job of the content script injected by the extension to listen for
625
+ //the event and do the appropriate actions.
626
+ }
627
+ }
628
+
629
+ class KeyboardListenerAPI {
630
+ constructor(getRootElement, areResponsesCaseSensitive = false, minimumValidRt = 0) {
631
+ this.getRootElement = getRootElement;
632
+ this.areResponsesCaseSensitive = areResponsesCaseSensitive;
633
+ this.minimumValidRt = minimumValidRt;
634
+ this.listeners = new Set();
635
+ this.heldKeys = new Set();
636
+ this.areRootListenersRegistered = false;
637
+ autoBind(this);
638
+ this.registerRootListeners();
639
+ }
640
+ /**
641
+ * If not previously done and `this.getRootElement()` returns an element, adds the root key
642
+ * listeners to that element.
643
+ */
644
+ registerRootListeners() {
645
+ if (!this.areRootListenersRegistered) {
646
+ const rootElement = this.getRootElement();
647
+ if (rootElement) {
648
+ rootElement.addEventListener("keydown", this.rootKeydownListener);
649
+ rootElement.addEventListener("keyup", this.rootKeyupListener);
650
+ this.areRootListenersRegistered = true;
651
+ }
652
+ }
653
+ }
654
+ rootKeydownListener(e) {
655
+ // Iterate over a static copy of the listeners set because listeners might add other listeners
656
+ // that we do not want to be included in the loop
657
+ for (const listener of Array.from(this.listeners)) {
658
+ listener(e);
659
+ }
660
+ this.heldKeys.add(this.toLowerCaseIfInsensitive(e.key));
661
+ }
662
+ toLowerCaseIfInsensitive(string) {
663
+ return this.areResponsesCaseSensitive ? string : string.toLowerCase();
664
+ }
665
+ rootKeyupListener(e) {
666
+ this.heldKeys.delete(this.toLowerCaseIfInsensitive(e.key));
667
+ }
668
+ isResponseValid(validResponses, allowHeldKey, key) {
669
+ // check if key was already held down
670
+ if (!allowHeldKey && this.heldKeys.has(key)) {
671
+ return false;
672
+ }
673
+ if (validResponses === "ALL_KEYS") {
674
+ return true;
675
+ }
676
+ if (validResponses === "NO_KEYS") {
677
+ return false;
678
+ }
679
+ return validResponses.includes(key);
680
+ }
681
+ getKeyboardResponse({ callback_function, valid_responses = "ALL_KEYS", rt_method = "performance", persist, audio_context, audio_context_start_time, allow_held_key = false, minimum_valid_rt = this.minimumValidRt, }) {
682
+ if (rt_method !== "performance" && rt_method !== "audio") {
683
+ console.log('Invalid RT method specified in getKeyboardResponse. Defaulting to "performance" method.');
684
+ rt_method = "performance";
685
+ }
686
+ const usePerformanceRt = rt_method === "performance";
687
+ const startTime = usePerformanceRt ? performance.now() : audio_context_start_time * 1000;
688
+ this.registerRootListeners();
689
+ if (!this.areResponsesCaseSensitive && typeof valid_responses !== "string") {
690
+ valid_responses = valid_responses.map((r) => r.toLowerCase());
691
+ }
692
+ const listener = (e) => {
693
+ const rt = Math.round((rt_method == "performance" ? performance.now() : audio_context.currentTime * 1000) -
694
+ startTime);
695
+ if (rt < minimum_valid_rt) {
696
+ return;
697
+ }
698
+ const key = this.toLowerCaseIfInsensitive(e.key);
699
+ if (this.isResponseValid(valid_responses, allow_held_key, key)) {
700
+ // if this is a valid response, then we don't want the key event to trigger other actions
701
+ // like scrolling via the spacebar.
702
+ e.preventDefault();
703
+ if (!persist) {
704
+ // remove keyboard listener if it exists
705
+ this.cancelKeyboardResponse(listener);
706
+ }
707
+ callback_function({ key, rt });
708
+ }
709
+ };
710
+ this.listeners.add(listener);
711
+ return listener;
712
+ }
713
+ cancelKeyboardResponse(listener) {
714
+ // remove the listener from the set of listeners if it is contained
715
+ this.listeners.delete(listener);
716
+ }
717
+ cancelAllKeyboardResponses() {
718
+ this.listeners.clear();
719
+ }
720
+ compareKeys(key1, key2) {
721
+ if ((typeof key1 !== "string" && key1 !== null) ||
722
+ (typeof key2 !== "string" && key2 !== null)) {
723
+ console.error("Error in jsPsych.pluginAPI.compareKeys: arguments must be key strings or null.");
724
+ return undefined;
725
+ }
726
+ if (typeof key1 === "string" && typeof key2 === "string") {
727
+ // if both values are strings, then check whether or not letter case should be converted before comparing (case_sensitive_responses in initJsPsych)
728
+ return this.areResponsesCaseSensitive
729
+ ? key1 === key2
730
+ : key1.toLowerCase() === key2.toLowerCase();
731
+ }
732
+ return key1 === null && key2 === null;
733
+ }
734
+ }
735
+
736
+ /**
737
+ * Parameter types for plugins
738
+ */
739
+ exports.ParameterType = void 0;
740
+ (function (ParameterType) {
741
+ ParameterType[ParameterType["BOOL"] = 0] = "BOOL";
742
+ ParameterType[ParameterType["STRING"] = 1] = "STRING";
743
+ ParameterType[ParameterType["INT"] = 2] = "INT";
744
+ ParameterType[ParameterType["FLOAT"] = 3] = "FLOAT";
745
+ ParameterType[ParameterType["FUNCTION"] = 4] = "FUNCTION";
746
+ ParameterType[ParameterType["KEY"] = 5] = "KEY";
747
+ ParameterType[ParameterType["KEYS"] = 6] = "KEYS";
748
+ ParameterType[ParameterType["SELECT"] = 7] = "SELECT";
749
+ ParameterType[ParameterType["HTML_STRING"] = 8] = "HTML_STRING";
750
+ ParameterType[ParameterType["IMAGE"] = 9] = "IMAGE";
751
+ ParameterType[ParameterType["AUDIO"] = 10] = "AUDIO";
752
+ ParameterType[ParameterType["VIDEO"] = 11] = "VIDEO";
753
+ ParameterType[ParameterType["OBJECT"] = 12] = "OBJECT";
754
+ ParameterType[ParameterType["COMPLEX"] = 13] = "COMPLEX";
755
+ ParameterType[ParameterType["TIMELINE"] = 14] = "TIMELINE";
756
+ })(exports.ParameterType || (exports.ParameterType = {}));
757
+ const universalPluginParameters = {
758
+ /**
759
+ * Data to add to this trial (key-value pairs)
760
+ */
761
+ data: {
762
+ type: exports.ParameterType.OBJECT,
763
+ pretty_name: "Data",
764
+ default: {},
765
+ },
766
+ /**
767
+ * Function to execute when trial begins
768
+ */
769
+ on_start: {
770
+ type: exports.ParameterType.FUNCTION,
771
+ pretty_name: "On start",
772
+ default: function () {
773
+ return;
774
+ },
775
+ },
776
+ /**
777
+ * Function to execute when trial is finished
778
+ */
779
+ on_finish: {
780
+ type: exports.ParameterType.FUNCTION,
781
+ pretty_name: "On finish",
782
+ default: function () {
783
+ return;
784
+ },
785
+ },
786
+ /**
787
+ * Function to execute after the trial has loaded
788
+ */
789
+ on_load: {
790
+ type: exports.ParameterType.FUNCTION,
791
+ pretty_name: "On load",
792
+ default: function () {
793
+ return;
794
+ },
795
+ },
796
+ /**
797
+ * Length of gap between the end of this trial and the start of the next trial
798
+ */
799
+ post_trial_gap: {
800
+ type: exports.ParameterType.INT,
801
+ pretty_name: "Post trial gap",
802
+ default: null,
803
+ },
804
+ /**
805
+ * A list of CSS classes to add to the jsPsych display element for the duration of this trial
806
+ */
807
+ css_classes: {
808
+ type: exports.ParameterType.STRING,
809
+ pretty_name: "Custom CSS classes",
810
+ default: null,
811
+ },
812
+ };
813
+
814
+ const preloadParameterTypes = [
815
+ exports.ParameterType.AUDIO,
816
+ exports.ParameterType.IMAGE,
817
+ exports.ParameterType.VIDEO,
818
+ ];
819
+ class MediaAPI {
820
+ constructor(useWebaudio, webaudioContext) {
821
+ this.useWebaudio = useWebaudio;
822
+ this.webaudioContext = webaudioContext;
823
+ // video //
824
+ this.video_buffers = {};
825
+ // audio //
826
+ this.context = null;
827
+ this.audio_buffers = [];
828
+ // preloading stimuli //
829
+ this.preload_requests = [];
830
+ this.img_cache = {};
831
+ this.preloadMap = new Map();
832
+ this.microphone_recorder = null;
833
+ }
834
+ getVideoBuffer(videoID) {
835
+ return this.video_buffers[videoID];
836
+ }
837
+ initAudio() {
838
+ this.context = this.useWebaudio ? this.webaudioContext : null;
839
+ }
840
+ audioContext() {
841
+ if (this.context !== null) {
842
+ if (this.context.state !== "running") {
843
+ this.context.resume();
844
+ }
845
+ }
846
+ return this.context;
847
+ }
848
+ getAudioBuffer(audioID) {
849
+ return new Promise((resolve, reject) => {
850
+ // check whether audio file already preloaded
851
+ if (typeof this.audio_buffers[audioID] == "undefined" ||
852
+ this.audio_buffers[audioID] == "tmp") {
853
+ // if audio is not already loaded, try to load it
854
+ this.preloadAudio([audioID], () => {
855
+ resolve(this.audio_buffers[audioID]);
856
+ }, () => { }, (e) => {
857
+ reject(e.error);
858
+ });
859
+ }
860
+ else {
861
+ // audio is already loaded
862
+ resolve(this.audio_buffers[audioID]);
863
+ }
864
+ });
865
+ }
866
+ preloadAudio(files, callback_complete = () => { }, callback_load = (filepath) => { }, callback_error = (error_msg) => { }) {
867
+ files = unique(files.flat());
868
+ let n_loaded = 0;
869
+ if (files.length == 0) {
870
+ callback_complete();
871
+ return;
872
+ }
873
+ const load_audio_file_webaudio = (source, count = 1) => {
874
+ const request = new XMLHttpRequest();
875
+ request.open("GET", source, true);
876
+ request.responseType = "arraybuffer";
877
+ request.onload = () => {
878
+ this.context.decodeAudioData(request.response, (buffer) => {
879
+ this.audio_buffers[source] = buffer;
880
+ n_loaded++;
881
+ callback_load(source);
882
+ if (n_loaded == files.length) {
883
+ callback_complete();
884
+ }
885
+ }, (e) => {
886
+ callback_error({ source: source, error: e });
887
+ });
888
+ };
889
+ request.onerror = function (e) {
890
+ let err = e;
891
+ if (this.status == 404) {
892
+ err = "404";
893
+ }
894
+ callback_error({ source: source, error: err });
895
+ };
896
+ request.onloadend = function (e) {
897
+ if (this.status == 404) {
898
+ callback_error({ source: source, error: "404" });
899
+ }
900
+ };
901
+ request.send();
902
+ this.preload_requests.push(request);
903
+ };
904
+ const load_audio_file_html5audio = (source, count = 1) => {
905
+ const audio = new Audio();
906
+ const handleCanPlayThrough = () => {
907
+ this.audio_buffers[source] = audio;
908
+ n_loaded++;
909
+ callback_load(source);
910
+ if (n_loaded == files.length) {
911
+ callback_complete();
912
+ }
913
+ audio.removeEventListener("canplaythrough", handleCanPlayThrough);
914
+ };
915
+ audio.addEventListener("canplaythrough", handleCanPlayThrough);
916
+ audio.addEventListener("error", function handleError(e) {
917
+ callback_error({ source: audio.src, error: e });
918
+ audio.removeEventListener("error", handleError);
919
+ });
920
+ audio.addEventListener("abort", function handleAbort(e) {
921
+ callback_error({ source: audio.src, error: e });
922
+ audio.removeEventListener("abort", handleAbort);
923
+ });
924
+ audio.src = source;
925
+ this.preload_requests.push(audio);
926
+ };
927
+ for (const file of files) {
928
+ if (typeof this.audio_buffers[file] !== "undefined") {
929
+ n_loaded++;
930
+ callback_load(file);
931
+ if (n_loaded == files.length) {
932
+ callback_complete();
933
+ }
934
+ }
935
+ else {
936
+ this.audio_buffers[file] = "tmp";
937
+ if (this.audioContext() !== null) {
938
+ load_audio_file_webaudio(file);
939
+ }
940
+ else {
941
+ load_audio_file_html5audio(file);
942
+ }
943
+ }
944
+ }
945
+ }
946
+ preloadImages(images, callback_complete = () => { }, callback_load = (filepath) => { }, callback_error = (error_msg) => { }) {
947
+ // flatten the images array
948
+ images = unique(images.flat());
949
+ var n_loaded = 0;
950
+ if (images.length === 0) {
951
+ callback_complete();
952
+ return;
953
+ }
954
+ for (var i = 0; i < images.length; i++) {
955
+ var img = new Image();
956
+ img.onload = function () {
957
+ n_loaded++;
958
+ callback_load(img.src);
959
+ if (n_loaded === images.length) {
960
+ callback_complete();
961
+ }
962
+ };
963
+ img.onerror = function (e) {
964
+ callback_error({ source: img.src, error: e });
965
+ };
966
+ img.src = images[i];
967
+ this.img_cache[images[i]] = img;
968
+ this.preload_requests.push(img);
969
+ }
970
+ }
971
+ preloadVideo(videos, callback_complete = () => { }, callback_load = (filepath) => { }, callback_error = (error_msg) => { }) {
972
+ // flatten the video array
973
+ videos = unique(videos.flat());
974
+ let n_loaded = 0;
975
+ if (videos.length === 0) {
976
+ callback_complete();
977
+ return;
978
+ }
979
+ for (const video of videos) {
980
+ const video_buffers = this.video_buffers;
981
+ //based on option 4 here: http://dinbror.dk/blog/how-to-preload-entire-html5-video-before-play-solved/
982
+ const request = new XMLHttpRequest();
983
+ request.open("GET", video, true);
984
+ request.responseType = "blob";
985
+ request.onload = function () {
986
+ if (this.status === 200 || this.status === 0) {
987
+ const videoBlob = this.response;
988
+ video_buffers[video] = URL.createObjectURL(videoBlob); // IE10+
989
+ n_loaded++;
990
+ callback_load(video);
991
+ if (n_loaded === videos.length) {
992
+ callback_complete();
993
+ }
994
+ }
995
+ };
996
+ request.onerror = function (e) {
997
+ let err = e;
998
+ if (this.status == 404) {
999
+ err = "404";
1000
+ }
1001
+ callback_error({ source: video, error: err });
1002
+ };
1003
+ request.onloadend = function (e) {
1004
+ if (this.status == 404) {
1005
+ callback_error({ source: video, error: "404" });
1006
+ }
1007
+ };
1008
+ request.send();
1009
+ this.preload_requests.push(request);
1010
+ }
1011
+ }
1012
+ getAutoPreloadList(timeline_description) {
1013
+ /** Map each preload parameter type to a set of paths to be preloaded */
1014
+ const preloadPaths = Object.fromEntries(preloadParameterTypes.map((type) => [type, new Set()]));
1015
+ const traverseTimeline = (node, inheritedTrialType) => {
1016
+ var _a, _b, _c, _d;
1017
+ const isTimeline = typeof node.timeline !== "undefined";
1018
+ if (isTimeline) {
1019
+ for (const childNode of node.timeline) {
1020
+ traverseTimeline(childNode, (_a = node.type) !== null && _a !== void 0 ? _a : inheritedTrialType);
1021
+ }
1022
+ }
1023
+ else if ((_c = ((_b = node.type) !== null && _b !== void 0 ? _b : inheritedTrialType)) === null || _c === void 0 ? void 0 : _c.info) {
1024
+ // node is a trial with type.info set
1025
+ // Get the plugin name and parameters object from the info object
1026
+ const { name: pluginName, parameters } = ((_d = node.type) !== null && _d !== void 0 ? _d : inheritedTrialType).info;
1027
+ // Extract parameters to be preloaded and their types from parameter info if this has not
1028
+ // yet been done for `pluginName`
1029
+ if (!this.preloadMap.has(pluginName)) {
1030
+ this.preloadMap.set(pluginName, Object.fromEntries(Object.entries(parameters)
1031
+ // Filter out parameter entries with media types and a non-false `preload` option
1032
+ .filter(([_name, { type, preload }]) => preloadParameterTypes.includes(type) && (preload !== null && preload !== void 0 ? preload : true))
1033
+ // Map each entry's value to its parameter type
1034
+ .map(([name, { type }]) => [name, type])));
1035
+ }
1036
+ // Add preload paths from this trial
1037
+ for (const [parameterName, parameterType] of Object.entries(this.preloadMap.get(pluginName))) {
1038
+ const parameterValue = node[parameterName];
1039
+ const elements = preloadPaths[parameterType];
1040
+ if (typeof parameterValue === "string") {
1041
+ elements.add(parameterValue);
1042
+ }
1043
+ else if (Array.isArray(parameterValue)) {
1044
+ for (const element of parameterValue.flat()) {
1045
+ if (typeof element === "string") {
1046
+ elements.add(element);
1047
+ }
1048
+ }
1049
+ }
1050
+ }
1051
+ }
1052
+ };
1053
+ traverseTimeline({ timeline: timeline_description });
1054
+ return {
1055
+ images: [...preloadPaths[exports.ParameterType.IMAGE]],
1056
+ audio: [...preloadPaths[exports.ParameterType.AUDIO]],
1057
+ video: [...preloadPaths[exports.ParameterType.VIDEO]],
1058
+ };
1059
+ }
1060
+ cancelPreloads() {
1061
+ for (const request of this.preload_requests) {
1062
+ request.onload = () => { };
1063
+ request.onerror = () => { };
1064
+ request.oncanplaythrough = () => { };
1065
+ request.onabort = () => { };
1066
+ }
1067
+ this.preload_requests = [];
1068
+ }
1069
+ initializeMicrophoneRecorder(stream) {
1070
+ const recorder = new MediaRecorder(stream);
1071
+ this.microphone_recorder = recorder;
1072
+ }
1073
+ getMicrophoneRecorder() {
1074
+ return this.microphone_recorder;
1075
+ }
1076
+ }
1077
+
1078
+ class SimulationAPI {
1079
+ dispatchEvent(event) {
1080
+ document.body.dispatchEvent(event);
1081
+ }
1082
+ /**
1083
+ * Dispatches a `keydown` event for the specified key
1084
+ * @param key Character code (`.key` property) for the key to press.
1085
+ */
1086
+ keyDown(key) {
1087
+ this.dispatchEvent(new KeyboardEvent("keydown", { key }));
1088
+ }
1089
+ /**
1090
+ * Dispatches a `keyup` event for the specified key
1091
+ * @param key Character code (`.key` property) for the key to press.
1092
+ */
1093
+ keyUp(key) {
1094
+ this.dispatchEvent(new KeyboardEvent("keyup", { key }));
1095
+ }
1096
+ /**
1097
+ * Dispatches a `keydown` and `keyup` event in sequence to simulate pressing a key.
1098
+ * @param key Character code (`.key` property) for the key to press.
1099
+ * @param delay Length of time to wait (ms) before executing action
1100
+ */
1101
+ pressKey(key, delay = 0) {
1102
+ if (delay > 0) {
1103
+ setTimeout(() => {
1104
+ this.keyDown(key);
1105
+ this.keyUp(key);
1106
+ }, delay);
1107
+ }
1108
+ else {
1109
+ this.keyDown(key);
1110
+ this.keyUp(key);
1111
+ }
1112
+ }
1113
+ /**
1114
+ * Dispatches `mousedown`, `mouseup`, and `click` events on the target element
1115
+ * @param target The element to click
1116
+ * @param delay Length of time to wait (ms) before executing action
1117
+ */
1118
+ clickTarget(target, delay = 0) {
1119
+ if (delay > 0) {
1120
+ setTimeout(() => {
1121
+ target.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
1122
+ target.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
1123
+ target.dispatchEvent(new MouseEvent("click", { bubbles: true }));
1124
+ }, delay);
1125
+ }
1126
+ else {
1127
+ target.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
1128
+ target.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
1129
+ target.dispatchEvent(new MouseEvent("click", { bubbles: true }));
1130
+ }
1131
+ }
1132
+ /**
1133
+ * Sets the value of a target text input
1134
+ * @param target A text input element to fill in
1135
+ * @param text Text to input
1136
+ * @param delay Length of time to wait (ms) before executing action
1137
+ */
1138
+ fillTextInput(target, text, delay = 0) {
1139
+ if (delay > 0) {
1140
+ setTimeout(() => {
1141
+ target.value = text;
1142
+ }, delay);
1143
+ }
1144
+ else {
1145
+ target.value = text;
1146
+ }
1147
+ }
1148
+ /**
1149
+ * Picks a valid key from `choices`, taking into account jsPsych-specific
1150
+ * identifiers like "NO_KEYS" and "ALL_KEYS".
1151
+ * @param choices Which keys are valid.
1152
+ * @returns A key selected at random from the valid keys.
1153
+ */
1154
+ getValidKey(choices) {
1155
+ const possible_keys = [
1156
+ "a",
1157
+ "b",
1158
+ "c",
1159
+ "d",
1160
+ "e",
1161
+ "f",
1162
+ "g",
1163
+ "h",
1164
+ "i",
1165
+ "j",
1166
+ "k",
1167
+ "l",
1168
+ "m",
1169
+ "n",
1170
+ "o",
1171
+ "p",
1172
+ "q",
1173
+ "r",
1174
+ "s",
1175
+ "t",
1176
+ "u",
1177
+ "v",
1178
+ "w",
1179
+ "x",
1180
+ "y",
1181
+ "z",
1182
+ "0",
1183
+ "1",
1184
+ "2",
1185
+ "3",
1186
+ "4",
1187
+ "5",
1188
+ "6",
1189
+ "7",
1190
+ "8",
1191
+ "9",
1192
+ " ",
1193
+ ];
1194
+ let key;
1195
+ if (choices == "NO_KEYS") {
1196
+ key = null;
1197
+ }
1198
+ else if (choices == "ALL_KEYS") {
1199
+ key = possible_keys[Math.floor(Math.random() * possible_keys.length)];
1200
+ }
1201
+ else {
1202
+ const flat_choices = choices.flat();
1203
+ key = flat_choices[Math.floor(Math.random() * flat_choices.length)];
1204
+ }
1205
+ return key;
1206
+ }
1207
+ mergeSimulationData(default_data, simulation_options) {
1208
+ // override any data with data from simulation object
1209
+ return Object.assign(Object.assign({}, default_data), simulation_options === null || simulation_options === void 0 ? void 0 : simulation_options.data);
1210
+ }
1211
+ ensureSimulationDataConsistency(trial, data) {
1212
+ // All RTs must be rounded
1213
+ if (data.rt) {
1214
+ data.rt = Math.round(data.rt);
1215
+ }
1216
+ // If a trial_duration and rt exist, make sure that the RT is not longer than the trial.
1217
+ if (trial.trial_duration && data.rt && data.rt > trial.trial_duration) {
1218
+ data.rt = null;
1219
+ if (data.response) {
1220
+ data.response = null;
1221
+ }
1222
+ if (data.correct) {
1223
+ data.correct = false;
1224
+ }
1225
+ }
1226
+ // If trial.choices is NO_KEYS make sure that response and RT are null
1227
+ if (trial.choices && trial.choices == "NO_KEYS") {
1228
+ if (data.rt) {
1229
+ data.rt = null;
1230
+ }
1231
+ if (data.response) {
1232
+ data.response = null;
1233
+ }
1234
+ }
1235
+ // If response is not allowed before stimulus display complete, ensure RT
1236
+ // is longer than display time.
1237
+ if (trial.allow_response_before_complete) {
1238
+ if (trial.sequence_reps && trial.frame_time) {
1239
+ const min_time = trial.sequence_reps * trial.frame_time * trial.stimuli.length;
1240
+ if (data.rt < min_time) {
1241
+ data.rt = null;
1242
+ data.response = null;
1243
+ }
1244
+ }
1245
+ }
1246
+ }
1247
+ }
1248
+
1249
+ class TimeoutAPI {
1250
+ constructor() {
1251
+ this.timeout_handlers = [];
1252
+ }
1253
+ setTimeout(callback, delay) {
1254
+ const handle = window.setTimeout(callback, delay);
1255
+ this.timeout_handlers.push(handle);
1256
+ return handle;
1257
+ }
1258
+ clearAllTimeouts() {
1259
+ for (const handler of this.timeout_handlers) {
1260
+ clearTimeout(handler);
1261
+ }
1262
+ this.timeout_handlers = [];
1263
+ }
1264
+ }
1265
+
1266
+ function createJointPluginAPIObject(jsPsych) {
1267
+ const settings = jsPsych.getInitSettings();
1268
+ return Object.assign({}, ...[
1269
+ new KeyboardListenerAPI(jsPsych.getDisplayContainerElement, settings.case_sensitive_responses, settings.minimum_valid_rt),
1270
+ new TimeoutAPI(),
1271
+ new MediaAPI(settings.use_webaudio, jsPsych.webaudio_context),
1272
+ new HardwareAPI(),
1273
+ new SimulationAPI(),
1274
+ ].map((object) => autoBind(object)));
1275
+ }
1276
+
1277
+ var wordList = [
1278
+ // Borrowed from xkcd password generator which borrowed it from wherever
1279
+ "ability","able","aboard","about","above","accept","accident","according",
1280
+ "account","accurate","acres","across","act","action","active","activity",
1281
+ "actual","actually","add","addition","additional","adjective","adult","adventure",
1282
+ "advice","affect","afraid","after","afternoon","again","against","age",
1283
+ "ago","agree","ahead","aid","air","airplane","alike","alive",
1284
+ "all","allow","almost","alone","along","aloud","alphabet","already",
1285
+ "also","although","am","among","amount","ancient","angle","angry",
1286
+ "animal","announced","another","answer","ants","any","anybody","anyone",
1287
+ "anything","anyway","anywhere","apart","apartment","appearance","apple","applied",
1288
+ "appropriate","are","area","arm","army","around","arrange","arrangement",
1289
+ "arrive","arrow","art","article","as","aside","ask","asleep",
1290
+ "at","ate","atmosphere","atom","atomic","attached","attack","attempt",
1291
+ "attention","audience","author","automobile","available","average","avoid","aware",
1292
+ "away","baby","back","bad","badly","bag","balance","ball",
1293
+ "balloon","band","bank","bar","bare","bark","barn","base",
1294
+ "baseball","basic","basis","basket","bat","battle","be","bean",
1295
+ "bear","beat","beautiful","beauty","became","because","become","becoming",
1296
+ "bee","been","before","began","beginning","begun","behavior","behind",
1297
+ "being","believed","bell","belong","below","belt","bend","beneath",
1298
+ "bent","beside","best","bet","better","between","beyond","bicycle",
1299
+ "bigger","biggest","bill","birds","birth","birthday","bit","bite",
1300
+ "black","blank","blanket","blew","blind","block","blood","blow",
1301
+ "blue","board","boat","body","bone","book","border","born",
1302
+ "both","bottle","bottom","bound","bow","bowl","box","boy",
1303
+ "brain","branch","brass","brave","bread","break","breakfast","breath",
1304
+ "breathe","breathing","breeze","brick","bridge","brief","bright","bring",
1305
+ "broad","broke","broken","brother","brought","brown","brush","buffalo",
1306
+ "build","building","built","buried","burn","burst","bus","bush",
1307
+ "business","busy","but","butter","buy","by","cabin","cage",
1308
+ "cake","call","calm","came","camera","camp","can","canal",
1309
+ "cannot","cap","capital","captain","captured","car","carbon","card",
1310
+ "care","careful","carefully","carried","carry","case","cast","castle",
1311
+ "cat","catch","cattle","caught","cause","cave","cell","cent",
1312
+ "center","central","century","certain","certainly","chain","chair","chamber",
1313
+ "chance","change","changing","chapter","character","characteristic","charge","chart",
1314
+ "check","cheese","chemical","chest","chicken","chief","child","children",
1315
+ "choice","choose","chose","chosen","church","circle","circus","citizen",
1316
+ "city","class","classroom","claws","clay","clean","clear","clearly",
1317
+ "climate","climb","clock","close","closely","closer","cloth","clothes",
1318
+ "clothing","cloud","club","coach","coal","coast","coat","coffee",
1319
+ "cold","collect","college","colony","color","column","combination","combine",
1320
+ "come","comfortable","coming","command","common","community","company","compare",
1321
+ "compass","complete","completely","complex","composed","composition","compound","concerned",
1322
+ "condition","congress","connected","consider","consist","consonant","constantly","construction",
1323
+ "contain","continent","continued","contrast","control","conversation","cook","cookies",
1324
+ "cool","copper","copy","corn","corner","correct","correctly","cost",
1325
+ "cotton","could","count","country","couple","courage","course","court",
1326
+ "cover","cow","cowboy","crack","cream","create","creature","crew",
1327
+ "crop","cross","crowd","cry","cup","curious","current","curve",
1328
+ "customs","cut","cutting","daily","damage","dance","danger","dangerous",
1329
+ "dark","darkness","date","daughter","dawn","day","dead","deal",
1330
+ "dear","death","decide","declared","deep","deeply","deer","definition",
1331
+ "degree","depend","depth","describe","desert","design","desk","detail",
1332
+ "determine","develop","development","diagram","diameter","did","die","differ",
1333
+ "difference","different","difficult","difficulty","dig","dinner","direct","direction",
1334
+ "directly","dirt","dirty","disappear","discover","discovery","discuss","discussion",
1335
+ "disease","dish","distance","distant","divide","division","do","doctor",
1336
+ "does","dog","doing","doll","dollar","done","donkey","door",
1337
+ "dot","double","doubt","down","dozen","draw","drawn","dream",
1338
+ "dress","drew","dried","drink","drive","driven","driver","driving",
1339
+ "drop","dropped","drove","dry","duck","due","dug","dull",
1340
+ "during","dust","duty","each","eager","ear","earlier","early",
1341
+ "earn","earth","easier","easily","east","easy","eat","eaten",
1342
+ "edge","education","effect","effort","egg","eight","either","electric",
1343
+ "electricity","element","elephant","eleven","else","empty","end","enemy",
1344
+ "energy","engine","engineer","enjoy","enough","enter","entire","entirely",
1345
+ "environment","equal","equally","equator","equipment","escape","especially","essential",
1346
+ "establish","even","evening","event","eventually","ever","every","everybody",
1347
+ "everyone","everything","everywhere","evidence","exact","exactly","examine","example",
1348
+ "excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise",
1349
+ "exist","expect","experience","experiment","explain","explanation","explore","express",
1350
+ "expression","extra","eye","face","facing","fact","factor","factory",
1351
+ "failed","fair","fairly","fall","fallen","familiar","family","famous",
1352
+ "far","farm","farmer","farther","fast","fastened","faster","fat",
1353
+ "father","favorite","fear","feathers","feature","fed","feed","feel",
1354
+ "feet","fell","fellow","felt","fence","few","fewer","field",
1355
+ "fierce","fifteen","fifth","fifty","fight","fighting","figure","fill",
1356
+ "film","final","finally","find","fine","finest","finger","finish",
1357
+ "fire","fireplace","firm","first","fish","five","fix","flag",
1358
+ "flame","flat","flew","flies","flight","floating","floor","flow",
1359
+ "flower","fly","fog","folks","follow","food","foot","football",
1360
+ "for","force","foreign","forest","forget","forgot","forgotten","form",
1361
+ "former","fort","forth","forty","forward","fought","found","four",
1362
+ "fourth","fox","frame","free","freedom","frequently","fresh","friend",
1363
+ "friendly","frighten","frog","from","front","frozen","fruit","fuel",
1364
+ "full","fully","fun","function","funny","fur","furniture","further",
1365
+ "future","gain","game","garage","garden","gas","gasoline","gate",
1366
+ "gather","gave","general","generally","gentle","gently","get","getting",
1367
+ "giant","gift","girl","give","given","giving","glad","glass",
1368
+ "globe","go","goes","gold","golden","gone","good","goose",
1369
+ "got","government","grabbed","grade","gradually","grain","grandfather","grandmother",
1370
+ "graph","grass","gravity","gray","great","greater","greatest","greatly",
1371
+ "green","grew","ground","group","grow","grown","growth","guard",
1372
+ "guess","guide","gulf","gun","habit","had","hair","half",
1373
+ "halfway","hall","hand","handle","handsome","hang","happen","happened",
1374
+ "happily","happy","harbor","hard","harder","hardly","has","hat",
1375
+ "have","having","hay","he","headed","heading","health","heard",
1376
+ "hearing","heart","heat","heavy","height","held","hello","help",
1377
+ "helpful","her","herd","here","herself","hidden","hide","high",
1378
+ "higher","highest","highway","hill","him","himself","his","history",
1379
+ "hit","hold","hole","hollow","home","honor","hope","horn",
1380
+ "horse","hospital","hot","hour","house","how","however","huge",
1381
+ "human","hundred","hung","hungry","hunt","hunter","hurried","hurry",
1382
+ "hurt","husband","ice","idea","identity","if","ill","image",
1383
+ "imagine","immediately","importance","important","impossible","improve","in","inch",
1384
+ "include","including","income","increase","indeed","independent","indicate","individual",
1385
+ "industrial","industry","influence","information","inside","instance","instant","instead",
1386
+ "instrument","interest","interior","into","introduced","invented","involved","iron",
1387
+ "is","island","it","its","itself","jack","jar","jet",
1388
+ "job","join","joined","journey","joy","judge","jump","jungle",
1389
+ "just","keep","kept","key","kids","kill","kind","kitchen",
1390
+ "knew","knife","know","knowledge","known","label","labor","lack",
1391
+ "lady","laid","lake","lamp","land","language","large","larger",
1392
+ "largest","last","late","later","laugh","law","lay","layers",
1393
+ "lead","leader","leaf","learn","least","leather","leave","leaving",
1394
+ "led","left","leg","length","lesson","let","letter","level",
1395
+ "library","lie","life","lift","light","like","likely","limited",
1396
+ "line","lion","lips","liquid","list","listen","little","live",
1397
+ "living","load","local","locate","location","log","lonely","long",
1398
+ "longer","look","loose","lose","loss","lost","lot","loud",
1399
+ "love","lovely","low","lower","luck","lucky","lunch","lungs",
1400
+ "lying","machine","machinery","mad","made","magic","magnet","mail",
1401
+ "main","mainly","major","make","making","man","managed","manner",
1402
+ "manufacturing","many","map","mark","market","married","mass","massage",
1403
+ "master","material","mathematics","matter","may","maybe","me","meal",
1404
+ "mean","means","meant","measure","meat","medicine","meet","melted",
1405
+ "member","memory","men","mental","merely","met","metal","method",
1406
+ "mice","middle","might","mighty","mile","military","milk","mill",
1407
+ "mind","mine","minerals","minute","mirror","missing","mission","mistake",
1408
+ "mix","mixture","model","modern","molecular","moment","money","monkey",
1409
+ "month","mood","moon","more","morning","most","mostly","mother",
1410
+ "motion","motor","mountain","mouse","mouth","move","movement","movie",
1411
+ "moving","mud","muscle","music","musical","must","my","myself",
1412
+ "mysterious","nails","name","nation","national","native","natural","naturally",
1413
+ "nature","near","nearby","nearer","nearest","nearly","necessary","neck",
1414
+ "needed","needle","needs","negative","neighbor","neighborhood","nervous","nest",
1415
+ "never","new","news","newspaper","next","nice","night","nine",
1416
+ "no","nobody","nodded","noise","none","noon","nor","north",
1417
+ "nose","not","note","noted","nothing","notice","noun","now",
1418
+ "number","numeral","nuts","object","observe","obtain","occasionally","occur",
1419
+ "ocean","of","off","offer","office","officer","official","oil",
1420
+ "old","older","oldest","on","once","one","only","onto",
1421
+ "open","operation","opinion","opportunity","opposite","or","orange","orbit",
1422
+ "order","ordinary","organization","organized","origin","original","other","ought",
1423
+ "our","ourselves","out","outer","outline","outside","over","own",
1424
+ "owner","oxygen","pack","package","page","paid","pain","paint",
1425
+ "pair","palace","pale","pan","paper","paragraph","parallel","parent",
1426
+ "park","part","particles","particular","particularly","partly","parts","party",
1427
+ "pass","passage","past","path","pattern","pay","peace","pen",
1428
+ "pencil","people","per","percent","perfect","perfectly","perhaps","period",
1429
+ "person","personal","pet","phrase","physical","piano","pick","picture",
1430
+ "pictured","pie","piece","pig","pile","pilot","pine","pink",
1431
+ "pipe","pitch","place","plain","plan","plane","planet","planned",
1432
+ "planning","plant","plastic","plate","plates","play","pleasant","please",
1433
+ "pleasure","plenty","plural","plus","pocket","poem","poet","poetry",
1434
+ "point","pole","police","policeman","political","pond","pony","pool",
1435
+ "poor","popular","population","porch","port","position","positive","possible",
1436
+ "possibly","post","pot","potatoes","pound","pour","powder","power",
1437
+ "powerful","practical","practice","prepare","present","president","press","pressure",
1438
+ "pretty","prevent","previous","price","pride","primitive","principal","principle",
1439
+ "printed","private","prize","probably","problem","process","produce","product",
1440
+ "production","program","progress","promised","proper","properly","property","protection",
1441
+ "proud","prove","provide","public","pull","pupil","pure","purple",
1442
+ "purpose","push","put","putting","quarter","queen","question","quick",
1443
+ "quickly","quiet","quietly","quite","rabbit","race","radio","railroad",
1444
+ "rain","raise","ran","ranch","range","rapidly","rate","rather",
1445
+ "raw","rays","reach","read","reader","ready","real","realize",
1446
+ "rear","reason","recall","receive","recent","recently","recognize","record",
1447
+ "red","refer","refused","region","regular","related","relationship","religious",
1448
+ "remain","remarkable","remember","remove","repeat","replace","replied","report",
1449
+ "represent","require","research","respect","rest","result","return","review",
1450
+ "rhyme","rhythm","rice","rich","ride","riding","right","ring",
1451
+ "rise","rising","river","road","roar","rock","rocket","rocky",
1452
+ "rod","roll","roof","room","root","rope","rose","rough",
1453
+ "round","route","row","rubbed","rubber","rule","ruler","run",
1454
+ "running","rush","sad","saddle","safe","safety","said","sail",
1455
+ "sale","salmon","salt","same","sand","sang","sat","satellites",
1456
+ "satisfied","save","saved","saw","say","scale","scared","scene",
1457
+ "school","science","scientific","scientist","score","screen","sea","search",
1458
+ "season","seat","second","secret","section","see","seed","seeing",
1459
+ "seems","seen","seldom","select","selection","sell","send","sense",
1460
+ "sent","sentence","separate","series","serious","serve","service","sets",
1461
+ "setting","settle","settlers","seven","several","shade","shadow","shake",
1462
+ "shaking","shall","shallow","shape","share","sharp","she","sheep",
1463
+ "sheet","shelf","shells","shelter","shine","shinning","ship","shirt",
1464
+ "shoe","shoot","shop","shore","short","shorter","shot","should",
1465
+ "shoulder","shout","show","shown","shut","sick","sides","sight",
1466
+ "sign","signal","silence","silent","silk","silly","silver","similar",
1467
+ "simple","simplest","simply","since","sing","single","sink","sister",
1468
+ "sit","sitting","situation","six","size","skill","skin","sky",
1469
+ "slabs","slave","sleep","slept","slide","slight","slightly","slip",
1470
+ "slipped","slope","slow","slowly","small","smaller","smallest","smell",
1471
+ "smile","smoke","smooth","snake","snow","so","soap","social",
1472
+ "society","soft","softly","soil","solar","sold","soldier","solid",
1473
+ "solution","solve","some","somebody","somehow","someone","something","sometime",
1474
+ "somewhere","son","song","soon","sort","sound","source","south",
1475
+ "southern","space","speak","special","species","specific","speech","speed",
1476
+ "spell","spend","spent","spider","spin","spirit","spite","split",
1477
+ "spoken","sport","spread","spring","square","stage","stairs","stand",
1478
+ "standard","star","stared","start","state","statement","station","stay",
1479
+ "steady","steam","steel","steep","stems","step","stepped","stick",
1480
+ "stiff","still","stock","stomach","stone","stood","stop","stopped",
1481
+ "store","storm","story","stove","straight","strange","stranger","straw",
1482
+ "stream","street","strength","stretch","strike","string","strip","strong",
1483
+ "stronger","struck","structure","struggle","stuck","student","studied","studying",
1484
+ "subject","substance","success","successful","such","sudden","suddenly","sugar",
1485
+ "suggest","suit","sum","summer","sun","sunlight","supper","supply",
1486
+ "support","suppose","sure","surface","surprise","surrounded","swam","sweet",
1487
+ "swept","swim","swimming","swing","swung","syllable","symbol","system",
1488
+ "table","tail","take","taken","tales","talk","tall","tank",
1489
+ "tape","task","taste","taught","tax","tea","teach","teacher",
1490
+ "team","tears","teeth","telephone","television","tell","temperature","ten",
1491
+ "tent","term","terrible","test","than","thank","that","thee",
1492
+ "them","themselves","then","theory","there","therefore","these","they",
1493
+ "thick","thin","thing","think","third","thirty","this","those",
1494
+ "thou","though","thought","thousand","thread","three","threw","throat",
1495
+ "through","throughout","throw","thrown","thumb","thus","thy","tide",
1496
+ "tie","tight","tightly","till","time","tin","tiny","tip",
1497
+ "tired","title","to","tobacco","today","together","told","tomorrow",
1498
+ "tone","tongue","tonight","too","took","tool","top","topic",
1499
+ "torn","total","touch","toward","tower","town","toy","trace",
1500
+ "track","trade","traffic","trail","train","transportation","trap","travel",
1501
+ "treated","tree","triangle","tribe","trick","tried","trip","troops",
1502
+ "tropical","trouble","truck","trunk","truth","try","tube","tune",
1503
+ "turn","twelve","twenty","twice","two","type","typical","uncle",
1504
+ "under","underline","understanding","unhappy","union","unit","universe","unknown",
1505
+ "unless","until","unusual","up","upon","upper","upward","us",
1506
+ "use","useful","using","usual","usually","valley","valuable","value",
1507
+ "vapor","variety","various","vast","vegetable","verb","vertical","very",
1508
+ "vessels","victory","view","village","visit","visitor","voice","volume",
1509
+ "vote","vowel","voyage","wagon","wait","walk","wall","want",
1510
+ "war","warm","warn","was","wash","waste","watch","water",
1511
+ "wave","way","we","weak","wealth","wear","weather","week",
1512
+ "weigh","weight","welcome","well","went","were","west","western",
1513
+ "wet","whale","what","whatever","wheat","wheel","when","whenever",
1514
+ "where","wherever","whether","which","while","whispered","whistle","white",
1515
+ "who","whole","whom","whose","why","wide","widely","wife",
1516
+ "wild","will","willing","win","wind","window","wing","winter",
1517
+ "wire","wise","wish","with","within","without","wolf","women",
1518
+ "won","wonder","wonderful","wood","wooden","wool","word","wore",
1519
+ "work","worker","world","worried","worry","worse","worth","would",
1520
+ "wrapped","write","writer","writing","written","wrong","wrote","yard",
1521
+ "year","yellow","yes","yesterday","yet","you","young","younger",
1522
+ "your","yourself","youth","zero","zebra","zipper","zoo","zulu"
1523
+ ];
1524
+
1525
+ function words(options) {
1526
+
1527
+ function word() {
1528
+ if (options && options.maxLength > 1) {
1529
+ return generateWordWithMaxLength();
1530
+ } else {
1531
+ return generateRandomWord();
1532
+ }
1533
+ }
1534
+
1535
+ function generateWordWithMaxLength() {
1536
+ var rightSize = false;
1537
+ var wordUsed;
1538
+ while (!rightSize) {
1539
+ wordUsed = generateRandomWord();
1540
+ if(wordUsed.length <= options.maxLength) {
1541
+ rightSize = true;
1542
+ }
1543
+
1544
+ }
1545
+ return wordUsed;
1546
+ }
1547
+
1548
+ function generateRandomWord() {
1549
+ return wordList[randInt(wordList.length)];
1550
+ }
1551
+
1552
+ function randInt(lessThan) {
1553
+ return Math.floor(Math.random() * lessThan);
1554
+ }
1555
+
1556
+ // No arguments = generate one word
1557
+ if (typeof(options) === 'undefined') {
1558
+ return word();
1559
+ }
1560
+
1561
+ // Just a number = return that many words
1562
+ if (typeof(options) === 'number') {
1563
+ options = { exactly: options };
1564
+ }
1565
+
1566
+ // options supported: exactly, min, max, join
1567
+ if (options.exactly) {
1568
+ options.min = options.exactly;
1569
+ options.max = options.exactly;
1570
+ }
1571
+
1572
+ // not a number = one word par string
1573
+ if (typeof(options.wordsPerString) !== 'number') {
1574
+ options.wordsPerString = 1;
1575
+ }
1576
+
1577
+ //not a function = returns the raw word
1578
+ if (typeof(options.formatter) !== 'function') {
1579
+ options.formatter = (word) => word;
1580
+ }
1581
+
1582
+ //not a string = separator is a space
1583
+ if (typeof(options.separator) !== 'string') {
1584
+ options.separator = ' ';
1585
+ }
1586
+
1587
+ var total = options.min + randInt(options.max + 1 - options.min);
1588
+ var results = [];
1589
+ var token = '';
1590
+ var relativeIndex = 0;
1591
+
1592
+ for (var i = 0; (i < total * options.wordsPerString); i++) {
1593
+ if (relativeIndex === options.wordsPerString - 1) {
1594
+ token += options.formatter(word(), relativeIndex);
1595
+ }
1596
+ else {
1597
+ token += options.formatter(word(), relativeIndex) + options.separator;
1598
+ }
1599
+ relativeIndex++;
1600
+ if ((i + 1) % options.wordsPerString === 0) {
1601
+ results.push(token);
1602
+ token = '';
1603
+ relativeIndex = 0;
1604
+ }
1605
+
1606
+ }
1607
+ if (typeof options.join === 'string') {
1608
+ results = results.join(options.join);
1609
+ }
1610
+
1611
+ return results;
1612
+ }
1613
+
1614
+ var randomWords$1 = words;
1615
+ // Export the word list as it is often useful
1616
+ words.wordList = wordList;
1617
+
1618
+ function repeat(array, repetitions, unpack = false) {
1619
+ const arr_isArray = Array.isArray(array);
1620
+ const rep_isArray = Array.isArray(repetitions);
1621
+ // if array is not an array, then we just repeat the item
1622
+ if (!arr_isArray) {
1623
+ if (!rep_isArray) {
1624
+ array = [array];
1625
+ repetitions = [repetitions];
1626
+ }
1627
+ else {
1628
+ repetitions = [repetitions[0]];
1629
+ 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.");
1630
+ }
1631
+ }
1632
+ else {
1633
+ // if repetitions is not an array, but array is, then we
1634
+ // repeat repetitions for each entry in array
1635
+ if (!rep_isArray) {
1636
+ let reps = [];
1637
+ for (let i = 0; i < array.length; i++) {
1638
+ reps.push(repetitions);
1639
+ }
1640
+ repetitions = reps;
1641
+ }
1642
+ else {
1643
+ if (array.length != repetitions.length) {
1644
+ console.warn("Unclear parameters given to randomization.repeat. Items and repetitions are unequal lengths. Behavior may not be as expected.");
1645
+ // throw warning if repetitions is too short, use first rep ONLY.
1646
+ if (repetitions.length < array.length) {
1647
+ let reps = [];
1648
+ for (let i = 0; i < array.length; i++) {
1649
+ reps.push(repetitions);
1650
+ }
1651
+ repetitions = reps;
1652
+ }
1653
+ else {
1654
+ // throw warning if too long, and then use the first N
1655
+ repetitions = repetitions.slice(0, array.length);
1656
+ }
1657
+ }
1658
+ }
1659
+ }
1660
+ // should be clear at this point to assume that array and repetitions are arrays with == length
1661
+ let allsamples = [];
1662
+ for (let i = 0; i < array.length; i++) {
1663
+ for (let j = 0; j < repetitions[i]; j++) {
1664
+ if (array[i] == null || typeof array[i] != "object") {
1665
+ allsamples.push(array[i]);
1666
+ }
1667
+ else {
1668
+ allsamples.push(Object.assign({}, array[i]));
1669
+ }
1670
+ }
1671
+ }
1672
+ let out = shuffle(allsamples);
1673
+ if (unpack) {
1674
+ out = unpackArray(out);
1675
+ }
1676
+ return out;
1677
+ }
1678
+ function shuffle(array) {
1679
+ if (!Array.isArray(array)) {
1680
+ console.error("Argument to shuffle() must be an array.");
1681
+ }
1682
+ const copy_array = array.slice(0);
1683
+ let m = copy_array.length, t, i;
1684
+ // While there remain elements to shuffle…
1685
+ while (m) {
1686
+ // Pick a remaining element…
1687
+ i = Math.floor(Math.random() * m--);
1688
+ // And swap it with the current element.
1689
+ t = copy_array[m];
1690
+ copy_array[m] = copy_array[i];
1691
+ copy_array[i] = t;
1692
+ }
1693
+ return copy_array;
1694
+ }
1695
+ function shuffleNoRepeats(arr, equalityTest) {
1696
+ if (!Array.isArray(arr)) {
1697
+ console.error("First argument to shuffleNoRepeats() must be an array.");
1698
+ }
1699
+ if (typeof equalityTest !== "undefined" && typeof equalityTest !== "function") {
1700
+ console.error("Second argument to shuffleNoRepeats() must be a function.");
1701
+ }
1702
+ // define a default equalityTest
1703
+ if (typeof equalityTest == "undefined") {
1704
+ equalityTest = function (a, b) {
1705
+ if (a === b) {
1706
+ return true;
1707
+ }
1708
+ else {
1709
+ return false;
1710
+ }
1711
+ };
1712
+ }
1713
+ const random_shuffle = shuffle(arr);
1714
+ for (let i = 0; i < random_shuffle.length - 1; i++) {
1715
+ if (equalityTest(random_shuffle[i], random_shuffle[i + 1])) {
1716
+ // neighbors are equal, pick a new random neighbor to swap (not the first or last element, to avoid edge cases)
1717
+ let random_pick = Math.floor(Math.random() * (random_shuffle.length - 2)) + 1;
1718
+ // test to make sure the new neighbor isn't equal to the old one
1719
+ while (equalityTest(random_shuffle[i + 1], random_shuffle[random_pick]) ||
1720
+ equalityTest(random_shuffle[i + 1], random_shuffle[random_pick + 1]) ||
1721
+ equalityTest(random_shuffle[i + 1], random_shuffle[random_pick - 1])) {
1722
+ random_pick = Math.floor(Math.random() * (random_shuffle.length - 2)) + 1;
1723
+ }
1724
+ const new_neighbor = random_shuffle[random_pick];
1725
+ random_shuffle[random_pick] = random_shuffle[i + 1];
1726
+ random_shuffle[i + 1] = new_neighbor;
1727
+ }
1728
+ }
1729
+ return random_shuffle;
1730
+ }
1731
+ function shuffleAlternateGroups(arr_groups, random_group_order = false) {
1732
+ const n_groups = arr_groups.length;
1733
+ if (n_groups == 1) {
1734
+ console.warn("shuffleAlternateGroups() was called with only one group. Defaulting to simple shuffle.");
1735
+ return shuffle(arr_groups[0]);
1736
+ }
1737
+ let group_order = [];
1738
+ for (let i = 0; i < n_groups; i++) {
1739
+ group_order.push(i);
1740
+ }
1741
+ if (random_group_order) {
1742
+ group_order = shuffle(group_order);
1743
+ }
1744
+ const randomized_groups = [];
1745
+ let min_length = null;
1746
+ for (let i = 0; i < n_groups; i++) {
1747
+ min_length =
1748
+ min_length === null ? arr_groups[i].length : Math.min(min_length, arr_groups[i].length);
1749
+ randomized_groups.push(shuffle(arr_groups[i]));
1750
+ }
1751
+ const out = [];
1752
+ for (let i = 0; i < min_length; i++) {
1753
+ for (let j = 0; j < group_order.length; j++) {
1754
+ out.push(randomized_groups[group_order[j]][i]);
1755
+ }
1756
+ }
1757
+ return out;
1758
+ }
1759
+ function sampleWithoutReplacement(arr, size) {
1760
+ if (!Array.isArray(arr)) {
1761
+ console.error("First argument to sampleWithoutReplacement() must be an array");
1762
+ }
1763
+ if (size > arr.length) {
1764
+ console.error("Cannot take a sample larger than the size of the set of items to sample.");
1765
+ }
1766
+ return shuffle(arr).slice(0, size);
1767
+ }
1768
+ function sampleWithReplacement(arr, size, weights) {
1769
+ if (!Array.isArray(arr)) {
1770
+ console.error("First argument to sampleWithReplacement() must be an array");
1771
+ }
1772
+ const normalized_weights = [];
1773
+ if (typeof weights !== "undefined") {
1774
+ if (weights.length !== arr.length) {
1775
+ console.error("The length of the weights array must equal the length of the array " +
1776
+ "to be sampled from.");
1777
+ }
1778
+ let weight_sum = 0;
1779
+ for (const weight of weights) {
1780
+ weight_sum += weight;
1781
+ }
1782
+ for (const weight of weights) {
1783
+ normalized_weights.push(weight / weight_sum);
1784
+ }
1785
+ }
1786
+ else {
1787
+ for (let i = 0; i < arr.length; i++) {
1788
+ normalized_weights.push(1 / arr.length);
1789
+ }
1790
+ }
1791
+ const cumulative_weights = [normalized_weights[0]];
1792
+ for (let i = 1; i < normalized_weights.length; i++) {
1793
+ cumulative_weights.push(normalized_weights[i] + cumulative_weights[i - 1]);
1794
+ }
1795
+ const samp = [];
1796
+ for (let i = 0; i < size; i++) {
1797
+ const rnd = Math.random();
1798
+ let index = 0;
1799
+ while (rnd > cumulative_weights[index]) {
1800
+ index++;
1801
+ }
1802
+ samp.push(arr[index]);
1803
+ }
1804
+ return samp;
1805
+ }
1806
+ function factorial(factors, repetitions = 1, unpack = false) {
1807
+ let design = [{}];
1808
+ for (const [factorName, factor] of Object.entries(factors)) {
1809
+ const new_design = [];
1810
+ for (const level of factor) {
1811
+ for (const cell of design) {
1812
+ new_design.push(Object.assign(Object.assign({}, cell), { [factorName]: level }));
1813
+ }
1814
+ }
1815
+ design = new_design;
1816
+ }
1817
+ return repeat(design, repetitions, unpack);
1818
+ }
1819
+ function randomID(length = 32) {
1820
+ let result = "";
1821
+ const chars = "0123456789abcdefghjklmnopqrstuvwxyz";
1822
+ for (let i = 0; i < length; i++) {
1823
+ result += chars[Math.floor(Math.random() * chars.length)];
1824
+ }
1825
+ return result;
1826
+ }
1827
+ /**
1828
+ * Generate a random integer from `lower` to `upper`, inclusive of both end points.
1829
+ * @param lower The lowest value it is possible to generate
1830
+ * @param upper The highest value it is possible to generate
1831
+ * @returns A random integer
1832
+ */
1833
+ function randomInt(lower, upper) {
1834
+ if (upper < lower) {
1835
+ throw new Error("Upper boundary must be less than or equal to lower boundary");
1836
+ }
1837
+ return lower + Math.floor(Math.random() * (upper - lower + 1));
1838
+ }
1839
+ /**
1840
+ * Generates a random sample from a Bernoulli distribution.
1841
+ * @param p The probability of sampling 1.
1842
+ * @returns 0, with probability 1-p, or 1, with probability p.
1843
+ */
1844
+ function sampleBernoulli(p) {
1845
+ return Math.random() <= p ? 1 : 0;
1846
+ }
1847
+ function sampleNormal(mean, standard_deviation) {
1848
+ return randn_bm() * standard_deviation + mean;
1849
+ }
1850
+ function sampleExponential(rate) {
1851
+ return -Math.log(Math.random()) / rate;
1852
+ }
1853
+ function sampleExGaussian(mean, standard_deviation, rate, positive = false) {
1854
+ let s = sampleNormal(mean, standard_deviation) + sampleExponential(rate);
1855
+ if (positive) {
1856
+ while (s <= 0) {
1857
+ s = sampleNormal(mean, standard_deviation) + sampleExponential(rate);
1858
+ }
1859
+ }
1860
+ return s;
1861
+ }
1862
+ /**
1863
+ * Generate one or more random words.
1864
+ *
1865
+ * This is a wrapper function for the {@link https://www.npmjs.com/package/random-words `random-words` npm package}.
1866
+ *
1867
+ * @param opts An object with optional properties `min`, `max`, `exactly`,
1868
+ * `join`, `maxLength`, `wordsPerString`, `separator`, and `formatter`.
1869
+ *
1870
+ * @returns An array of words or a single string, depending on parameter choices.
1871
+ */
1872
+ function randomWords(opts) {
1873
+ return randomWords$1(opts);
1874
+ }
1875
+ // Box-Muller transformation for a random sample from normal distribution with mean = 0, std = 1
1876
+ // https://stackoverflow.com/a/36481059/3726673
1877
+ function randn_bm() {
1878
+ var u = 0, v = 0;
1879
+ while (u === 0)
1880
+ u = Math.random(); //Converting [0,1) to (0,1)
1881
+ while (v === 0)
1882
+ v = Math.random();
1883
+ return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
1884
+ }
1885
+ function unpackArray(array) {
1886
+ const out = {};
1887
+ for (const x of array) {
1888
+ for (const key of Object.keys(x)) {
1889
+ if (typeof out[key] === "undefined") {
1890
+ out[key] = [];
1891
+ }
1892
+ out[key].push(x[key]);
1893
+ }
1894
+ }
1895
+ return out;
1896
+ }
1897
+
1898
+ var randomization = /*#__PURE__*/Object.freeze({
1899
+ __proto__: null,
1900
+ repeat: repeat,
1901
+ shuffle: shuffle,
1902
+ shuffleNoRepeats: shuffleNoRepeats,
1903
+ shuffleAlternateGroups: shuffleAlternateGroups,
1904
+ sampleWithoutReplacement: sampleWithoutReplacement,
1905
+ sampleWithReplacement: sampleWithReplacement,
1906
+ factorial: factorial,
1907
+ randomID: randomID,
1908
+ randomInt: randomInt,
1909
+ sampleBernoulli: sampleBernoulli,
1910
+ sampleNormal: sampleNormal,
1911
+ sampleExponential: sampleExponential,
1912
+ sampleExGaussian: sampleExGaussian,
1913
+ randomWords: randomWords
1914
+ });
1915
+
1916
+ /**
1917
+ * Gets information about the Mechanical Turk Environment, HIT, Assignment, and Worker
1918
+ * by parsing the URL variables that Mechanical Turk generates.
1919
+ * @returns An object containing information about the Mechanical Turk Environment, HIT, Assignment, and Worker.
1920
+ */
1921
+ function turkInfo() {
1922
+ const turk = {
1923
+ previewMode: false,
1924
+ outsideTurk: false,
1925
+ hitId: "INVALID_URL_PARAMETER",
1926
+ assignmentId: "INVALID_URL_PARAMETER",
1927
+ workerId: "INVALID_URL_PARAMETER",
1928
+ turkSubmitTo: "INVALID_URL_PARAMETER",
1929
+ };
1930
+ const param = function (url, name) {
1931
+ name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
1932
+ const regexS = "[\\?&]" + name + "=([^&#]*)";
1933
+ const regex = new RegExp(regexS);
1934
+ const results = regex.exec(url);
1935
+ return results == null ? "" : results[1];
1936
+ };
1937
+ const src = param(window.location.href, "assignmentId")
1938
+ ? window.location.href
1939
+ : document.referrer;
1940
+ const keys = ["assignmentId", "hitId", "workerId", "turkSubmitTo"];
1941
+ keys.map(function (key) {
1942
+ turk[key] = unescape(param(src, key));
1943
+ });
1944
+ turk.previewMode = turk.assignmentId == "ASSIGNMENT_ID_NOT_AVAILABLE";
1945
+ turk.outsideTurk =
1946
+ !turk.previewMode && turk.hitId === "" && turk.assignmentId == "" && turk.workerId == "";
1947
+ return turk;
1948
+ }
1949
+ /**
1950
+ * Send data to Mechnical Turk for storage.
1951
+ * @param data An object containing `key:value` pairs to send to Mechanical Turk. Values
1952
+ * cannot contain nested objects, arrays, or functions.
1953
+ * @returns Nothing
1954
+ */
1955
+ function submitToTurk(data) {
1956
+ const turk = turkInfo();
1957
+ const assignmentId = turk.assignmentId;
1958
+ const turkSubmitTo = turk.turkSubmitTo;
1959
+ if (!assignmentId || !turkSubmitTo)
1960
+ return;
1961
+ const form = document.createElement("form");
1962
+ form.method = "POST";
1963
+ form.action = turkSubmitTo + "/mturk/externalSubmit?assignmentId=" + assignmentId;
1964
+ for (const key in data) {
1965
+ if (data.hasOwnProperty(key)) {
1966
+ const hiddenField = document.createElement("input");
1967
+ hiddenField.type = "hidden";
1968
+ hiddenField.name = key;
1969
+ hiddenField.id = key;
1970
+ hiddenField.value = data[key];
1971
+ form.appendChild(hiddenField);
1972
+ }
1973
+ }
1974
+ document.body.appendChild(form);
1975
+ form.submit();
1976
+ }
1977
+
1978
+ var turk = /*#__PURE__*/Object.freeze({
1979
+ __proto__: null,
1980
+ turkInfo: turkInfo,
1981
+ submitToTurk: submitToTurk
1982
+ });
1983
+
1984
+ class TimelineNode {
1985
+ // constructor
1986
+ constructor(jsPsych, parameters, parent, relativeID) {
1987
+ this.jsPsych = jsPsych;
1988
+ // track progress through the node
1989
+ this.progress = {
1990
+ current_location: -1,
1991
+ current_variable_set: 0,
1992
+ current_repetition: 0,
1993
+ current_iteration: 0,
1994
+ done: false,
1995
+ };
1996
+ // store a link to the parent of this node
1997
+ this.parent_node = parent;
1998
+ // create the ID for this node
1999
+ this.relative_id = typeof parent === "undefined" ? 0 : relativeID;
2000
+ // check if there is a timeline parameter
2001
+ // if there is, then this node has its own timeline
2002
+ if (typeof parameters.timeline !== "undefined") {
2003
+ // create timeline properties
2004
+ this.timeline_parameters = {
2005
+ timeline: [],
2006
+ loop_function: parameters.loop_function,
2007
+ conditional_function: parameters.conditional_function,
2008
+ sample: parameters.sample,
2009
+ randomize_order: typeof parameters.randomize_order == "undefined" ? false : parameters.randomize_order,
2010
+ repetitions: typeof parameters.repetitions == "undefined" ? 1 : parameters.repetitions,
2011
+ timeline_variables: typeof parameters.timeline_variables == "undefined"
2012
+ ? [{}]
2013
+ : parameters.timeline_variables,
2014
+ on_timeline_finish: parameters.on_timeline_finish,
2015
+ on_timeline_start: parameters.on_timeline_start,
2016
+ };
2017
+ this.setTimelineVariablesOrder();
2018
+ // extract all of the node level data and parameters
2019
+ // but remove all of the timeline-level specific information
2020
+ // since this will be used to copy things down hierarchically
2021
+ var node_data = Object.assign({}, parameters);
2022
+ delete node_data.timeline;
2023
+ delete node_data.conditional_function;
2024
+ delete node_data.loop_function;
2025
+ delete node_data.randomize_order;
2026
+ delete node_data.repetitions;
2027
+ delete node_data.timeline_variables;
2028
+ delete node_data.sample;
2029
+ delete node_data.on_timeline_start;
2030
+ delete node_data.on_timeline_finish;
2031
+ this.node_trial_data = node_data; // store for later...
2032
+ // create a TimelineNode for each element in the timeline
2033
+ for (var i = 0; i < parameters.timeline.length; i++) {
2034
+ // merge parameters
2035
+ var merged_parameters = Object.assign({}, node_data, parameters.timeline[i]);
2036
+ // merge any data from the parent node into child nodes
2037
+ if (typeof node_data.data == "object" && typeof parameters.timeline[i].data == "object") {
2038
+ var merged_data = Object.assign({}, node_data.data, parameters.timeline[i].data);
2039
+ merged_parameters.data = merged_data;
2040
+ }
2041
+ this.timeline_parameters.timeline.push(new TimelineNode(this.jsPsych, merged_parameters, this, i));
2042
+ }
2043
+ }
2044
+ // if there is no timeline parameter, then this node is a trial node
2045
+ else {
2046
+ // check to see if a valid trial type is defined
2047
+ if (typeof parameters.type === "undefined") {
2048
+ console.error('Trial level node is missing the "type" parameter. The parameters for the node are: ' +
2049
+ JSON.stringify(parameters));
2050
+ }
2051
+ // create a deep copy of the parameters for the trial
2052
+ this.trial_parameters = Object.assign({}, parameters);
2053
+ }
2054
+ }
2055
+ // recursively get the next trial to run.
2056
+ // if this node is a leaf (trial), then return the trial.
2057
+ // otherwise, recursively find the next trial in the child timeline.
2058
+ trial() {
2059
+ if (typeof this.timeline_parameters == "undefined") {
2060
+ // returns a clone of the trial_parameters to
2061
+ // protect functions.
2062
+ return deepCopy(this.trial_parameters);
2063
+ }
2064
+ else {
2065
+ if (this.progress.current_location >= this.timeline_parameters.timeline.length) {
2066
+ return null;
2067
+ }
2068
+ else {
2069
+ return this.timeline_parameters.timeline[this.progress.current_location].trial();
2070
+ }
2071
+ }
2072
+ }
2073
+ markCurrentTrialComplete() {
2074
+ if (typeof this.timeline_parameters === "undefined") {
2075
+ this.progress.done = true;
2076
+ }
2077
+ else {
2078
+ this.timeline_parameters.timeline[this.progress.current_location].markCurrentTrialComplete();
2079
+ }
2080
+ }
2081
+ nextRepetiton() {
2082
+ this.setTimelineVariablesOrder();
2083
+ this.progress.current_location = -1;
2084
+ this.progress.current_variable_set = 0;
2085
+ this.progress.current_repetition++;
2086
+ for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
2087
+ this.timeline_parameters.timeline[i].reset();
2088
+ }
2089
+ }
2090
+ // set the order for going through the timeline variables array
2091
+ setTimelineVariablesOrder() {
2092
+ const timeline_parameters = this.timeline_parameters;
2093
+ // check to make sure this node has variables
2094
+ if (typeof timeline_parameters === "undefined" ||
2095
+ typeof timeline_parameters.timeline_variables === "undefined") {
2096
+ return;
2097
+ }
2098
+ var order = [];
2099
+ for (var i = 0; i < timeline_parameters.timeline_variables.length; i++) {
2100
+ order.push(i);
2101
+ }
2102
+ if (typeof timeline_parameters.sample !== "undefined") {
2103
+ if (timeline_parameters.sample.type == "custom") {
2104
+ order = timeline_parameters.sample.fn(order);
2105
+ }
2106
+ else if (timeline_parameters.sample.type == "with-replacement") {
2107
+ order = sampleWithReplacement(order, timeline_parameters.sample.size, timeline_parameters.sample.weights);
2108
+ }
2109
+ else if (timeline_parameters.sample.type == "without-replacement") {
2110
+ order = sampleWithoutReplacement(order, timeline_parameters.sample.size);
2111
+ }
2112
+ else if (timeline_parameters.sample.type == "fixed-repetitions") {
2113
+ order = repeat(order, timeline_parameters.sample.size, false);
2114
+ }
2115
+ else if (timeline_parameters.sample.type == "alternate-groups") {
2116
+ order = shuffleAlternateGroups(timeline_parameters.sample.groups, timeline_parameters.sample.randomize_group_order);
2117
+ }
2118
+ else {
2119
+ console.error('Invalid type in timeline sample parameters. Valid options for type are "custom", "with-replacement", "without-replacement", "fixed-repetitions", and "alternate-groups"');
2120
+ }
2121
+ }
2122
+ if (timeline_parameters.randomize_order) {
2123
+ order = shuffle(order);
2124
+ }
2125
+ this.progress.order = order;
2126
+ }
2127
+ // next variable set
2128
+ nextSet() {
2129
+ this.progress.current_location = -1;
2130
+ this.progress.current_variable_set++;
2131
+ for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
2132
+ this.timeline_parameters.timeline[i].reset();
2133
+ }
2134
+ }
2135
+ // update the current trial node to be completed
2136
+ // returns true if the node is complete after advance (all subnodes are also complete)
2137
+ // returns false otherwise
2138
+ advance() {
2139
+ const progress = this.progress;
2140
+ const timeline_parameters = this.timeline_parameters;
2141
+ const internal = this.jsPsych.internal;
2142
+ // first check to see if done
2143
+ if (progress.done) {
2144
+ return true;
2145
+ }
2146
+ // if node has not started yet (progress.current_location == -1),
2147
+ // then try to start the node.
2148
+ if (progress.current_location == -1) {
2149
+ // check for on_timeline_start and conditonal function on nodes with timelines
2150
+ if (typeof timeline_parameters !== "undefined") {
2151
+ // only run the conditional function if this is the first repetition of the timeline when
2152
+ // repetitions > 1, and only when on the first variable set
2153
+ if (typeof timeline_parameters.conditional_function !== "undefined" &&
2154
+ progress.current_repetition == 0 &&
2155
+ progress.current_variable_set == 0) {
2156
+ internal.call_immediate = true;
2157
+ var conditional_result = timeline_parameters.conditional_function();
2158
+ internal.call_immediate = false;
2159
+ // if the conditional_function() returns false, then the timeline
2160
+ // doesn't run and is marked as complete.
2161
+ if (conditional_result == false) {
2162
+ progress.done = true;
2163
+ return true;
2164
+ }
2165
+ }
2166
+ // if we reach this point then the node has its own timeline and will start
2167
+ // so we need to check if there is an on_timeline_start function if we are on the first variable set
2168
+ if (typeof timeline_parameters.on_timeline_start !== "undefined" &&
2169
+ progress.current_variable_set == 0) {
2170
+ timeline_parameters.on_timeline_start();
2171
+ }
2172
+ }
2173
+ // if we reach this point, then either the node doesn't have a timeline of the
2174
+ // conditional function returned true and it can start
2175
+ progress.current_location = 0;
2176
+ // call advance again on this node now that it is pointing to a new location
2177
+ return this.advance();
2178
+ }
2179
+ // if this node has a timeline, propogate down to the current trial.
2180
+ if (typeof timeline_parameters !== "undefined") {
2181
+ var have_node_to_run = false;
2182
+ // keep incrementing the location in the timeline until one of the nodes reached is incomplete
2183
+ while (progress.current_location < timeline_parameters.timeline.length &&
2184
+ have_node_to_run == false) {
2185
+ // check to see if the node currently pointed at is done
2186
+ var target_complete = timeline_parameters.timeline[progress.current_location].advance();
2187
+ if (!target_complete) {
2188
+ have_node_to_run = true;
2189
+ return false;
2190
+ }
2191
+ else {
2192
+ progress.current_location++;
2193
+ }
2194
+ }
2195
+ // if we've reached the end of the timeline (which, if the code is here, we have)
2196
+ // there are a few steps to see what to do next...
2197
+ // first, check the timeline_variables to see if we need to loop through again
2198
+ // with a new set of variables
2199
+ if (progress.current_variable_set < progress.order.length - 1) {
2200
+ // reset the progress of the node to be with the new set
2201
+ this.nextSet();
2202
+ // then try to advance this node again.
2203
+ return this.advance();
2204
+ }
2205
+ // if we're all done with the timeline_variables, then check to see if there are more repetitions
2206
+ else if (progress.current_repetition < timeline_parameters.repetitions - 1) {
2207
+ this.nextRepetiton();
2208
+ // check to see if there is an on_timeline_finish function
2209
+ if (typeof timeline_parameters.on_timeline_finish !== "undefined") {
2210
+ timeline_parameters.on_timeline_finish();
2211
+ }
2212
+ return this.advance();
2213
+ }
2214
+ // if we're all done with the repetitions...
2215
+ else {
2216
+ // check to see if there is an on_timeline_finish function
2217
+ if (typeof timeline_parameters.on_timeline_finish !== "undefined") {
2218
+ timeline_parameters.on_timeline_finish();
2219
+ }
2220
+ // if we're all done with the repetitions, check if there is a loop function.
2221
+ if (typeof timeline_parameters.loop_function !== "undefined") {
2222
+ internal.call_immediate = true;
2223
+ if (timeline_parameters.loop_function(this.generatedData())) {
2224
+ this.reset();
2225
+ internal.call_immediate = false;
2226
+ return this.parent_node.advance();
2227
+ }
2228
+ else {
2229
+ progress.done = true;
2230
+ internal.call_immediate = false;
2231
+ return true;
2232
+ }
2233
+ }
2234
+ }
2235
+ // no more loops on this timeline, we're done!
2236
+ progress.done = true;
2237
+ return true;
2238
+ }
2239
+ }
2240
+ // check the status of the done flag
2241
+ isComplete() {
2242
+ return this.progress.done;
2243
+ }
2244
+ // getter method for timeline variables
2245
+ getTimelineVariableValue(variable_name) {
2246
+ if (typeof this.timeline_parameters == "undefined") {
2247
+ return undefined;
2248
+ }
2249
+ var v = this.timeline_parameters.timeline_variables[this.progress.order[this.progress.current_variable_set]][variable_name];
2250
+ return v;
2251
+ }
2252
+ // recursive upward search for timeline variables
2253
+ findTimelineVariable(variable_name) {
2254
+ var v = this.getTimelineVariableValue(variable_name);
2255
+ if (typeof v == "undefined") {
2256
+ if (typeof this.parent_node !== "undefined") {
2257
+ return this.parent_node.findTimelineVariable(variable_name);
2258
+ }
2259
+ else {
2260
+ return undefined;
2261
+ }
2262
+ }
2263
+ else {
2264
+ return v;
2265
+ }
2266
+ }
2267
+ // recursive downward search for active trial to extract timeline variable
2268
+ timelineVariable(variable_name) {
2269
+ if (typeof this.timeline_parameters == "undefined") {
2270
+ return this.findTimelineVariable(variable_name);
2271
+ }
2272
+ else {
2273
+ // if progress.current_location is -1, then the timeline variable is being evaluated
2274
+ // in a function that runs prior to the trial starting, so we should treat that trial
2275
+ // as being the active trial for purposes of finding the value of the timeline variable
2276
+ var loc = Math.max(0, this.progress.current_location);
2277
+ // if loc is greater than the number of elements on this timeline, then the timeline
2278
+ // variable is being evaluated in a function that runs after the trial on the timeline
2279
+ // are complete but before advancing to the next (like a loop_function).
2280
+ // treat the last active trial as the active trial for this purpose.
2281
+ if (loc == this.timeline_parameters.timeline.length) {
2282
+ loc = loc - 1;
2283
+ }
2284
+ // now find the variable
2285
+ return this.timeline_parameters.timeline[loc].timelineVariable(variable_name);
2286
+ }
2287
+ }
2288
+ // recursively get all the timeline variables for this trial
2289
+ allTimelineVariables() {
2290
+ var all_tvs = this.allTimelineVariablesNames();
2291
+ var all_tvs_vals = {};
2292
+ for (var i = 0; i < all_tvs.length; i++) {
2293
+ all_tvs_vals[all_tvs[i]] = this.timelineVariable(all_tvs[i]);
2294
+ }
2295
+ return all_tvs_vals;
2296
+ }
2297
+ // helper to get all the names at this stage.
2298
+ allTimelineVariablesNames(so_far = []) {
2299
+ if (typeof this.timeline_parameters !== "undefined") {
2300
+ so_far = so_far.concat(Object.keys(this.timeline_parameters.timeline_variables[this.progress.order[this.progress.current_variable_set]]));
2301
+ // if progress.current_location is -1, then the timeline variable is being evaluated
2302
+ // in a function that runs prior to the trial starting, so we should treat that trial
2303
+ // as being the active trial for purposes of finding the value of the timeline variable
2304
+ var loc = Math.max(0, this.progress.current_location);
2305
+ // if loc is greater than the number of elements on this timeline, then the timeline
2306
+ // variable is being evaluated in a function that runs after the trial on the timeline
2307
+ // are complete but before advancing to the next (like a loop_function).
2308
+ // treat the last active trial as the active trial for this purpose.
2309
+ if (loc == this.timeline_parameters.timeline.length) {
2310
+ loc = loc - 1;
2311
+ }
2312
+ // now find the variable
2313
+ return this.timeline_parameters.timeline[loc].allTimelineVariablesNames(so_far);
2314
+ }
2315
+ if (typeof this.timeline_parameters == "undefined") {
2316
+ return so_far;
2317
+ }
2318
+ }
2319
+ // recursively get the number of **trials** contained in the timeline
2320
+ // assuming that while loops execute exactly once and if conditionals
2321
+ // always run
2322
+ length() {
2323
+ var length = 0;
2324
+ if (typeof this.timeline_parameters !== "undefined") {
2325
+ for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
2326
+ length += this.timeline_parameters.timeline[i].length();
2327
+ }
2328
+ }
2329
+ else {
2330
+ return 1;
2331
+ }
2332
+ return length;
2333
+ }
2334
+ // return the percentage of trials completed, grouped at the first child level
2335
+ // counts a set of trials as complete when the child node is done
2336
+ percentComplete() {
2337
+ var total_trials = this.length();
2338
+ var completed_trials = 0;
2339
+ for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
2340
+ if (this.timeline_parameters.timeline[i].isComplete()) {
2341
+ completed_trials += this.timeline_parameters.timeline[i].length();
2342
+ }
2343
+ }
2344
+ return (completed_trials / total_trials) * 100;
2345
+ }
2346
+ // resets the node and all subnodes to original state
2347
+ // but increments the current_iteration counter
2348
+ reset() {
2349
+ this.progress.current_location = -1;
2350
+ this.progress.current_repetition = 0;
2351
+ this.progress.current_variable_set = 0;
2352
+ this.progress.current_iteration++;
2353
+ this.progress.done = false;
2354
+ this.setTimelineVariablesOrder();
2355
+ if (typeof this.timeline_parameters != "undefined") {
2356
+ for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
2357
+ this.timeline_parameters.timeline[i].reset();
2358
+ }
2359
+ }
2360
+ }
2361
+ // mark this node as finished
2362
+ end() {
2363
+ this.progress.done = true;
2364
+ }
2365
+ // recursively end whatever sub-node is running the current trial
2366
+ endActiveNode() {
2367
+ if (typeof this.timeline_parameters == "undefined") {
2368
+ this.end();
2369
+ this.parent_node.end();
2370
+ }
2371
+ else {
2372
+ this.timeline_parameters.timeline[this.progress.current_location].endActiveNode();
2373
+ }
2374
+ }
2375
+ // get a unique ID associated with this node
2376
+ // the ID reflects the current iteration through this node.
2377
+ ID() {
2378
+ var id = "";
2379
+ if (typeof this.parent_node == "undefined") {
2380
+ return "0." + this.progress.current_iteration;
2381
+ }
2382
+ else {
2383
+ id += this.parent_node.ID() + "-";
2384
+ id += this.relative_id + "." + this.progress.current_iteration;
2385
+ return id;
2386
+ }
2387
+ }
2388
+ // get the ID of the active trial
2389
+ activeID() {
2390
+ if (typeof this.timeline_parameters == "undefined") {
2391
+ return this.ID();
2392
+ }
2393
+ else {
2394
+ return this.timeline_parameters.timeline[this.progress.current_location].activeID();
2395
+ }
2396
+ }
2397
+ // get all the data generated within this node
2398
+ generatedData() {
2399
+ return this.jsPsych.data.getDataByTimelineNode(this.ID());
2400
+ }
2401
+ // get all the trials of a particular type
2402
+ trialsOfType(type) {
2403
+ if (typeof this.timeline_parameters == "undefined") {
2404
+ if (this.trial_parameters.type == type) {
2405
+ return this.trial_parameters;
2406
+ }
2407
+ else {
2408
+ return [];
2409
+ }
2410
+ }
2411
+ else {
2412
+ var trials = [];
2413
+ for (var i = 0; i < this.timeline_parameters.timeline.length; i++) {
2414
+ var t = this.timeline_parameters.timeline[i].trialsOfType(type);
2415
+ trials = trials.concat(t);
2416
+ }
2417
+ return trials;
2418
+ }
2419
+ }
2420
+ // add new trials to end of this timeline
2421
+ insert(parameters) {
2422
+ if (typeof this.timeline_parameters === "undefined") {
2423
+ console.error("Cannot add new trials to a trial-level node.");
2424
+ }
2425
+ else {
2426
+ this.timeline_parameters.timeline.push(new TimelineNode(this.jsPsych, Object.assign(Object.assign({}, this.node_trial_data), parameters), this, this.timeline_parameters.timeline.length));
2427
+ }
2428
+ }
2429
+ }
2430
+
2431
+ function delay(ms) {
2432
+ return new Promise((resolve) => setTimeout(resolve, ms));
2433
+ }
2434
+ class JsPsych {
2435
+ constructor(options) {
2436
+ this.extensions = {};
2437
+ this.turk = turk;
2438
+ this.randomization = randomization;
2439
+ this.utils = utils;
2440
+ //
2441
+ // private variables
2442
+ //
2443
+ /**
2444
+ * options
2445
+ */
2446
+ this.opts = {};
2447
+ // flow control
2448
+ this.global_trial_index = 0;
2449
+ this.current_trial = {};
2450
+ this.current_trial_finished = false;
2451
+ /**
2452
+ * is the experiment paused?
2453
+ */
2454
+ this.paused = false;
2455
+ this.waiting = false;
2456
+ /**
2457
+ * is the page retrieved directly via file:// protocol (true) or hosted on a server (false)?
2458
+ */
2459
+ this.file_protocol = false;
2460
+ /**
2461
+ * is the experiment running in `simulate()` mode
2462
+ */
2463
+ this.simulation_mode = null;
2464
+ // storing a single webaudio context to prevent problems with multiple inits
2465
+ // of jsPsych
2466
+ this.webaudio_context = null;
2467
+ this.internal = {
2468
+ /**
2469
+ * this flag is used to determine whether we are in a scope where
2470
+ * jsPsych.timelineVariable() should be executed immediately or
2471
+ * whether it should return a function to access the variable later.
2472
+ *
2473
+ **/
2474
+ call_immediate: false,
2475
+ };
2476
+ this.progress_bar_amount = 0;
2477
+ // override default options if user specifies an option
2478
+ options = Object.assign({ display_element: undefined, on_finish: () => { }, on_trial_start: () => { }, on_trial_finish: () => { }, on_data_update: () => { }, on_interaction_data_update: () => { }, on_close: () => { }, use_webaudio: true, exclusions: {}, show_progress_bar: false, message_progress_bar: "Completion Progress", auto_update_progress_bar: true, default_iti: 0, minimum_valid_rt: 0, experiment_width: null, override_safe_mode: false, case_sensitive_responses: false, extensions: [] }, options);
2479
+ this.opts = options;
2480
+ autoBind(this); // so we can pass JsPsych methods as callbacks and `this` remains the JsPsych instance
2481
+ this.webaudio_context =
2482
+ typeof window !== "undefined" && typeof window.AudioContext !== "undefined"
2483
+ ? new AudioContext()
2484
+ : null;
2485
+ // detect whether page is running in browser as a local file, and if so, disable web audio and video preloading to prevent CORS issues
2486
+ if (window.location.protocol == "file:" &&
2487
+ (options.override_safe_mode === false || typeof options.override_safe_mode === "undefined")) {
2488
+ options.use_webaudio = false;
2489
+ this.file_protocol = true;
2490
+ console.warn("jsPsych detected that it is running via the file:// protocol and not on a web server. " +
2491
+ "To prevent issues with cross-origin requests, Web Audio and video preloading have been disabled. " +
2492
+ "If you would like to override this setting, you can set 'override_safe_mode' to 'true' in initJsPsych. " +
2493
+ "For more information, see: https://www.jspsych.org/overview/running-experiments");
2494
+ }
2495
+ // initialize modules
2496
+ this.data = new JsPsychData(this);
2497
+ this.pluginAPI = createJointPluginAPIObject(this);
2498
+ // create instances of extensions
2499
+ for (const extension of options.extensions) {
2500
+ this.extensions[extension.type.info.name] = new extension.type(this);
2501
+ }
2502
+ // initialize audio context based on options and browser capabilities
2503
+ this.pluginAPI.initAudio();
2504
+ }
2505
+ version() {
2506
+ return version;
2507
+ }
2508
+ /**
2509
+ * Starts an experiment using the provided timeline and returns a promise that is resolved when
2510
+ * the experiment is finished.
2511
+ *
2512
+ * @param timeline The timeline to be run
2513
+ */
2514
+ run(timeline) {
2515
+ return __awaiter(this, void 0, void 0, function* () {
2516
+ if (typeof timeline === "undefined") {
2517
+ console.error("No timeline declared in jsPsych.run. Cannot start experiment.");
2518
+ }
2519
+ if (timeline.length === 0) {
2520
+ console.error("No trials have been added to the timeline (the timeline is an empty array). Cannot start experiment.");
2521
+ }
2522
+ // create experiment timeline
2523
+ this.timelineDescription = timeline;
2524
+ this.timeline = new TimelineNode(this, { timeline });
2525
+ yield this.prepareDom();
2526
+ yield this.checkExclusions(this.opts.exclusions);
2527
+ yield this.loadExtensions(this.opts.extensions);
2528
+ document.documentElement.setAttribute("jspsych", "present");
2529
+ this.startExperiment();
2530
+ yield this.finished;
2531
+ });
2532
+ }
2533
+ simulate(timeline, simulation_mode = "data-only", simulation_options = {}) {
2534
+ return __awaiter(this, void 0, void 0, function* () {
2535
+ this.simulation_mode = simulation_mode;
2536
+ this.simulation_options = simulation_options;
2537
+ yield this.run(timeline);
2538
+ });
2539
+ }
2540
+ getProgress() {
2541
+ return {
2542
+ total_trials: typeof this.timeline === "undefined" ? undefined : this.timeline.length(),
2543
+ current_trial_global: this.global_trial_index,
2544
+ percent_complete: typeof this.timeline === "undefined" ? 0 : this.timeline.percentComplete(),
2545
+ };
2546
+ }
2547
+ getStartTime() {
2548
+ return this.exp_start_time;
2549
+ }
2550
+ getTotalTime() {
2551
+ if (typeof this.exp_start_time === "undefined") {
2552
+ return 0;
2553
+ }
2554
+ return new Date().getTime() - this.exp_start_time.getTime();
2555
+ }
2556
+ getDisplayElement() {
2557
+ return this.DOM_target;
2558
+ }
2559
+ getDisplayContainerElement() {
2560
+ return this.DOM_container;
2561
+ }
2562
+ finishTrial(data = {}) {
2563
+ if (this.current_trial_finished) {
2564
+ return;
2565
+ }
2566
+ this.current_trial_finished = true;
2567
+ // remove any CSS classes that were added to the DOM via css_classes parameter
2568
+ if (typeof this.current_trial.css_classes !== "undefined" &&
2569
+ Array.isArray(this.current_trial.css_classes)) {
2570
+ this.DOM_target.classList.remove(...this.current_trial.css_classes);
2571
+ }
2572
+ // write the data from the trial
2573
+ this.data.write(data);
2574
+ // get back the data with all of the defaults in
2575
+ const trial_data = this.data.get().filter({ trial_index: this.global_trial_index });
2576
+ // for trial-level callbacks, we just want to pass in a reference to the values
2577
+ // of the DataCollection, for easy access and editing.
2578
+ const trial_data_values = trial_data.values()[0];
2579
+ const current_trial = this.current_trial;
2580
+ if (typeof current_trial.save_trial_parameters === "object") {
2581
+ for (const key of Object.keys(current_trial.save_trial_parameters)) {
2582
+ const key_val = current_trial.save_trial_parameters[key];
2583
+ if (key_val === true) {
2584
+ if (typeof current_trial[key] === "undefined") {
2585
+ console.warn(`Invalid parameter specified in save_trial_parameters. Trial has no property called "${key}".`);
2586
+ }
2587
+ else if (typeof current_trial[key] === "function") {
2588
+ trial_data_values[key] = current_trial[key].toString();
2589
+ }
2590
+ else {
2591
+ trial_data_values[key] = current_trial[key];
2592
+ }
2593
+ }
2594
+ if (key_val === false) {
2595
+ // we don't allow internal_node_id or trial_index to be deleted because it would break other things
2596
+ if (key !== "internal_node_id" && key !== "trial_index") {
2597
+ delete trial_data_values[key];
2598
+ }
2599
+ }
2600
+ }
2601
+ }
2602
+ // handle extension callbacks
2603
+ if (Array.isArray(current_trial.extensions)) {
2604
+ for (const extension of current_trial.extensions) {
2605
+ const ext_data_values = this.extensions[extension.type.info.name].on_finish(extension.params);
2606
+ Object.assign(trial_data_values, ext_data_values);
2607
+ }
2608
+ }
2609
+ // about to execute lots of callbacks, so switch context.
2610
+ this.internal.call_immediate = true;
2611
+ // handle callback at plugin level
2612
+ if (typeof current_trial.on_finish === "function") {
2613
+ current_trial.on_finish(trial_data_values);
2614
+ }
2615
+ // handle callback at whole-experiment level
2616
+ this.opts.on_trial_finish(trial_data_values);
2617
+ // after the above callbacks are complete, then the data should be finalized
2618
+ // for this trial. call the on_data_update handler, passing in the same
2619
+ // data object that just went through the trial's finish handlers.
2620
+ this.opts.on_data_update(trial_data_values);
2621
+ // done with callbacks
2622
+ this.internal.call_immediate = false;
2623
+ // wait for iti
2624
+ if (typeof current_trial.post_trial_gap === null ||
2625
+ typeof current_trial.post_trial_gap === "undefined") {
2626
+ if (this.opts.default_iti > 0) {
2627
+ setTimeout(this.nextTrial, this.opts.default_iti);
2628
+ }
2629
+ else {
2630
+ this.nextTrial();
2631
+ }
2632
+ }
2633
+ else {
2634
+ if (current_trial.post_trial_gap > 0) {
2635
+ setTimeout(this.nextTrial, current_trial.post_trial_gap);
2636
+ }
2637
+ else {
2638
+ this.nextTrial();
2639
+ }
2640
+ }
2641
+ }
2642
+ endExperiment(end_message = "", data = {}) {
2643
+ this.timeline.end_message = end_message;
2644
+ this.timeline.end();
2645
+ this.pluginAPI.cancelAllKeyboardResponses();
2646
+ this.pluginAPI.clearAllTimeouts();
2647
+ this.finishTrial(data);
2648
+ }
2649
+ endCurrentTimeline() {
2650
+ this.timeline.endActiveNode();
2651
+ }
2652
+ getCurrentTrial() {
2653
+ return this.current_trial;
2654
+ }
2655
+ getInitSettings() {
2656
+ return this.opts;
2657
+ }
2658
+ getCurrentTimelineNodeID() {
2659
+ return this.timeline.activeID();
2660
+ }
2661
+ timelineVariable(varname, immediate = false) {
2662
+ if (this.internal.call_immediate || immediate === true) {
2663
+ return this.timeline.timelineVariable(varname);
2664
+ }
2665
+ else {
2666
+ return {
2667
+ timelineVariablePlaceholder: true,
2668
+ timelineVariableFunction: () => this.timeline.timelineVariable(varname),
2669
+ };
2670
+ }
2671
+ }
2672
+ getAllTimelineVariables() {
2673
+ return this.timeline.allTimelineVariables();
2674
+ }
2675
+ addNodeToEndOfTimeline(new_timeline, preload_callback) {
2676
+ this.timeline.insert(new_timeline);
2677
+ }
2678
+ pauseExperiment() {
2679
+ this.paused = true;
2680
+ }
2681
+ resumeExperiment() {
2682
+ this.paused = false;
2683
+ if (this.waiting) {
2684
+ this.waiting = false;
2685
+ this.nextTrial();
2686
+ }
2687
+ }
2688
+ loadFail(message) {
2689
+ message = message || "<p>The experiment failed to load.</p>";
2690
+ this.DOM_target.innerHTML = message;
2691
+ }
2692
+ getSafeModeStatus() {
2693
+ return this.file_protocol;
2694
+ }
2695
+ getTimeline() {
2696
+ return this.timelineDescription;
2697
+ }
2698
+ prepareDom() {
2699
+ return __awaiter(this, void 0, void 0, function* () {
2700
+ // Wait until the document is ready
2701
+ if (document.readyState !== "complete") {
2702
+ yield new Promise((resolve) => {
2703
+ window.addEventListener("load", resolve);
2704
+ });
2705
+ }
2706
+ const options = this.opts;
2707
+ // set DOM element where jsPsych will render content
2708
+ // if undefined, then jsPsych will use the <body> tag and the entire page
2709
+ if (typeof options.display_element === "undefined") {
2710
+ // check if there is a body element on the page
2711
+ const body = document.querySelector("body");
2712
+ if (body === null) {
2713
+ document.documentElement.appendChild(document.createElement("body"));
2714
+ }
2715
+ // using the full page, so we need the HTML element to
2716
+ // have 100% height, and body to be full width and height with
2717
+ // no margin
2718
+ document.querySelector("html").style.height = "100%";
2719
+ document.querySelector("body").style.margin = "0px";
2720
+ document.querySelector("body").style.height = "100%";
2721
+ document.querySelector("body").style.width = "100%";
2722
+ options.display_element = document.querySelector("body");
2723
+ }
2724
+ else {
2725
+ // make sure that the display element exists on the page
2726
+ const display = options.display_element instanceof Element
2727
+ ? options.display_element
2728
+ : document.querySelector("#" + options.display_element);
2729
+ if (display === null) {
2730
+ console.error("The display_element specified in initJsPsych() does not exist in the DOM.");
2731
+ }
2732
+ else {
2733
+ options.display_element = display;
2734
+ }
2735
+ }
2736
+ options.display_element.innerHTML =
2737
+ '<div class="jspsych-content-wrapper"><div id="jspsych-content"></div></div>';
2738
+ this.DOM_container = options.display_element;
2739
+ this.DOM_target = document.querySelector("#jspsych-content");
2740
+ // set experiment_width if not null
2741
+ if (options.experiment_width !== null) {
2742
+ this.DOM_target.style.width = options.experiment_width + "px";
2743
+ }
2744
+ // add tabIndex attribute to scope event listeners
2745
+ options.display_element.tabIndex = 0;
2746
+ // add CSS class to DOM_target
2747
+ if (options.display_element.className.indexOf("jspsych-display-element") === -1) {
2748
+ options.display_element.className += " jspsych-display-element";
2749
+ }
2750
+ this.DOM_target.className += "jspsych-content";
2751
+ // create listeners for user browser interaction
2752
+ this.data.createInteractionListeners();
2753
+ // add event for closing window
2754
+ window.addEventListener("beforeunload", options.on_close);
2755
+ });
2756
+ }
2757
+ loadExtensions(extensions) {
2758
+ return __awaiter(this, void 0, void 0, function* () {
2759
+ // run the .initialize method of any extensions that are in use
2760
+ // these should return a Promise to indicate when loading is complete
2761
+ try {
2762
+ yield Promise.all(extensions.map((extension) => this.extensions[extension.type.info.name].initialize(extension.params || {})));
2763
+ }
2764
+ catch (error_message) {
2765
+ console.error(error_message);
2766
+ throw new Error(error_message);
2767
+ }
2768
+ });
2769
+ }
2770
+ startExperiment() {
2771
+ this.finished = new Promise((resolve) => {
2772
+ this.resolveFinishedPromise = resolve;
2773
+ });
2774
+ // show progress bar if requested
2775
+ if (this.opts.show_progress_bar === true) {
2776
+ this.drawProgressBar(this.opts.message_progress_bar);
2777
+ }
2778
+ // record the start time
2779
+ this.exp_start_time = new Date();
2780
+ // begin!
2781
+ this.timeline.advance();
2782
+ this.doTrial(this.timeline.trial());
2783
+ }
2784
+ finishExperiment() {
2785
+ const finish_result = this.opts.on_finish(this.data.get());
2786
+ const done_handler = () => {
2787
+ if (typeof this.timeline.end_message !== "undefined") {
2788
+ this.DOM_target.innerHTML = this.timeline.end_message;
2789
+ }
2790
+ this.resolveFinishedPromise();
2791
+ };
2792
+ if (finish_result) {
2793
+ Promise.resolve(finish_result).then(done_handler);
2794
+ }
2795
+ else {
2796
+ done_handler();
2797
+ }
2798
+ }
2799
+ nextTrial() {
2800
+ // if experiment is paused, don't do anything.
2801
+ if (this.paused) {
2802
+ this.waiting = true;
2803
+ return;
2804
+ }
2805
+ this.global_trial_index++;
2806
+ // advance timeline
2807
+ this.timeline.markCurrentTrialComplete();
2808
+ const complete = this.timeline.advance();
2809
+ // update progress bar if shown
2810
+ if (this.opts.show_progress_bar === true && this.opts.auto_update_progress_bar === true) {
2811
+ this.updateProgressBar();
2812
+ }
2813
+ // check if experiment is over
2814
+ if (complete) {
2815
+ this.finishExperiment();
2816
+ return;
2817
+ }
2818
+ this.doTrial(this.timeline.trial());
2819
+ }
2820
+ doTrial(trial) {
2821
+ this.current_trial = trial;
2822
+ this.current_trial_finished = false;
2823
+ // process all timeline variables for this trial
2824
+ this.evaluateTimelineVariables(trial);
2825
+ if (typeof trial.type === "string") {
2826
+ throw new MigrationError("A string was provided as the trial's `type` parameter. Since jsPsych v7, the `type` parameter needs to be a plugin object.");
2827
+ }
2828
+ // instantiate the plugin for this trial
2829
+ trial.type = Object.assign(Object.assign({}, autoBind(new trial.type(this))), { info: trial.type.info });
2830
+ // evaluate variables that are functions
2831
+ this.evaluateFunctionParameters(trial);
2832
+ // get default values for parameters
2833
+ this.setDefaultValues(trial);
2834
+ // about to execute callbacks
2835
+ this.internal.call_immediate = true;
2836
+ // call experiment wide callback
2837
+ this.opts.on_trial_start(trial);
2838
+ // call trial specific callback if it exists
2839
+ if (typeof trial.on_start === "function") {
2840
+ trial.on_start(trial);
2841
+ }
2842
+ // call any on_start functions for extensions
2843
+ if (Array.isArray(trial.extensions)) {
2844
+ for (const extension of trial.extensions) {
2845
+ this.extensions[extension.type.info.name].on_start(extension.params);
2846
+ }
2847
+ }
2848
+ // apply the focus to the element containing the experiment.
2849
+ this.DOM_container.focus();
2850
+ // reset the scroll on the DOM target
2851
+ this.DOM_target.scrollTop = 0;
2852
+ // add CSS classes to the DOM_target if they exist in trial.css_classes
2853
+ if (typeof trial.css_classes !== "undefined") {
2854
+ if (!Array.isArray(trial.css_classes) && typeof trial.css_classes === "string") {
2855
+ trial.css_classes = [trial.css_classes];
2856
+ }
2857
+ if (Array.isArray(trial.css_classes)) {
2858
+ this.DOM_target.classList.add(...trial.css_classes);
2859
+ }
2860
+ }
2861
+ // setup on_load event callback
2862
+ const load_callback = () => {
2863
+ if (typeof trial.on_load === "function") {
2864
+ trial.on_load();
2865
+ }
2866
+ // call any on_load functions for extensions
2867
+ if (Array.isArray(trial.extensions)) {
2868
+ for (const extension of trial.extensions) {
2869
+ this.extensions[extension.type.info.name].on_load(extension.params);
2870
+ }
2871
+ }
2872
+ };
2873
+ let trial_complete;
2874
+ if (!this.simulation_mode) {
2875
+ trial_complete = trial.type.trial(this.DOM_target, trial, load_callback);
2876
+ }
2877
+ if (this.simulation_mode) {
2878
+ // check if the trial supports simulation
2879
+ if (trial.type.simulate) {
2880
+ let trial_sim_opts;
2881
+ if (!trial.simulation_options) {
2882
+ trial_sim_opts = this.simulation_options.default;
2883
+ }
2884
+ if (trial.simulation_options) {
2885
+ if (typeof trial.simulation_options == "string") {
2886
+ if (this.simulation_options[trial.simulation_options]) {
2887
+ trial_sim_opts = this.simulation_options[trial.simulation_options];
2888
+ }
2889
+ else if (this.simulation_options.default) {
2890
+ console.log(`No matching simulation options found for "${trial.simulation_options}". Using "default" options.`);
2891
+ trial_sim_opts = this.simulation_options.default;
2892
+ }
2893
+ else {
2894
+ console.log(`No matching simulation options found for "${trial.simulation_options}" and no "default" options provided. Using the default values provided by the plugin.`);
2895
+ trial_sim_opts = {};
2896
+ }
2897
+ }
2898
+ else {
2899
+ trial_sim_opts = trial.simulation_options;
2900
+ }
2901
+ }
2902
+ trial_sim_opts = this.utils.deepCopy(trial_sim_opts);
2903
+ trial_sim_opts = this.replaceFunctionsWithValues(trial_sim_opts, null);
2904
+ if ((trial_sim_opts === null || trial_sim_opts === void 0 ? void 0 : trial_sim_opts.simulate) === false) {
2905
+ trial_complete = trial.type.trial(this.DOM_target, trial, load_callback);
2906
+ }
2907
+ else {
2908
+ trial_complete = trial.type.simulate(trial, (trial_sim_opts === null || trial_sim_opts === void 0 ? void 0 : trial_sim_opts.mode) || this.simulation_mode, trial_sim_opts, load_callback);
2909
+ }
2910
+ }
2911
+ else {
2912
+ // trial doesn't have a simulate method, so just run as usual
2913
+ trial_complete = trial.type.trial(this.DOM_target, trial, load_callback);
2914
+ }
2915
+ }
2916
+ // see if trial_complete is a Promise by looking for .then() function
2917
+ const is_promise = trial_complete && typeof trial_complete.then == "function";
2918
+ // in simulation mode we let the simulate function call the load_callback always.
2919
+ if (!is_promise && !this.simulation_mode) {
2920
+ load_callback();
2921
+ }
2922
+ // done with callbacks
2923
+ this.internal.call_immediate = false;
2924
+ }
2925
+ evaluateTimelineVariables(trial) {
2926
+ for (const key of Object.keys(trial)) {
2927
+ // timeline variables on the root level
2928
+ if (typeof trial[key] === "object" &&
2929
+ trial[key] !== null &&
2930
+ typeof trial[key].timelineVariablePlaceholder !== "undefined") {
2931
+ /*trial[key].toString().replace(/\s/g, "") ==
2932
+ "function(){returntimeline.timelineVariable(varname);}"
2933
+ )*/ trial[key] = trial[key].timelineVariableFunction();
2934
+ }
2935
+ // timeline variables that are nested in objects
2936
+ if (typeof trial[key] === "object" && trial[key] !== null) {
2937
+ this.evaluateTimelineVariables(trial[key]);
2938
+ }
2939
+ }
2940
+ }
2941
+ evaluateFunctionParameters(trial) {
2942
+ // set a flag so that jsPsych.timelineVariable() is immediately executed in this context
2943
+ this.internal.call_immediate = true;
2944
+ // iterate over each parameter
2945
+ for (const key of Object.keys(trial)) {
2946
+ // check to make sure parameter is not "type", since that was eval'd above.
2947
+ if (key !== "type") {
2948
+ // 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.
2949
+ // the first line checks if the parameter is defined in the universalPluginParameters set
2950
+ // the second line checks the plugin-specific parameters
2951
+ if (typeof universalPluginParameters[key] !== "undefined" &&
2952
+ universalPluginParameters[key].type !== exports.ParameterType.FUNCTION) {
2953
+ trial[key] = this.replaceFunctionsWithValues(trial[key], null);
2954
+ }
2955
+ if (typeof trial.type.info.parameters[key] !== "undefined" &&
2956
+ trial.type.info.parameters[key].type !== exports.ParameterType.FUNCTION) {
2957
+ trial[key] = this.replaceFunctionsWithValues(trial[key], trial.type.info.parameters[key]);
2958
+ }
2959
+ }
2960
+ }
2961
+ // reset so jsPsych.timelineVariable() is no longer immediately executed
2962
+ this.internal.call_immediate = false;
2963
+ }
2964
+ replaceFunctionsWithValues(obj, info) {
2965
+ // null typeof is 'object' (?!?!), so need to run this first!
2966
+ if (obj === null) {
2967
+ return obj;
2968
+ }
2969
+ // arrays
2970
+ else if (Array.isArray(obj)) {
2971
+ for (let i = 0; i < obj.length; i++) {
2972
+ obj[i] = this.replaceFunctionsWithValues(obj[i], info);
2973
+ }
2974
+ }
2975
+ // objects
2976
+ else if (typeof obj === "object") {
2977
+ if (info === null || !info.nested) {
2978
+ for (const key of Object.keys(obj)) {
2979
+ if (key === "type") {
2980
+ // Ignore the object's `type` field because it contains a plugin and we do not want to
2981
+ // call plugin functions
2982
+ continue;
2983
+ }
2984
+ obj[key] = this.replaceFunctionsWithValues(obj[key], null);
2985
+ }
2986
+ }
2987
+ else {
2988
+ for (const key of Object.keys(obj)) {
2989
+ if (typeof info.nested[key] === "object" &&
2990
+ info.nested[key].type !== exports.ParameterType.FUNCTION) {
2991
+ obj[key] = this.replaceFunctionsWithValues(obj[key], info.nested[key]);
2992
+ }
2993
+ }
2994
+ }
2995
+ }
2996
+ else if (typeof obj === "function") {
2997
+ return obj();
2998
+ }
2999
+ return obj;
3000
+ }
3001
+ setDefaultValues(trial) {
3002
+ for (const param in trial.type.info.parameters) {
3003
+ // check if parameter is complex with nested defaults
3004
+ if (trial.type.info.parameters[param].type === exports.ParameterType.COMPLEX) {
3005
+ if (trial.type.info.parameters[param].array === true) {
3006
+ // iterate over each entry in the array
3007
+ trial[param].forEach(function (ip, i) {
3008
+ // check each parameter in the plugin description
3009
+ for (const p in trial.type.info.parameters[param].nested) {
3010
+ if (typeof trial[param][i][p] === "undefined" || trial[param][i][p] === null) {
3011
+ if (typeof trial.type.info.parameters[param].nested[p].default === "undefined") {
3012
+ console.error("You must specify a value for the " +
3013
+ p +
3014
+ " parameter (nested in the " +
3015
+ param +
3016
+ " parameter) in the " +
3017
+ trial.type +
3018
+ " plugin.");
3019
+ }
3020
+ else {
3021
+ trial[param][i][p] = trial.type.info.parameters[param].nested[p].default;
3022
+ }
3023
+ }
3024
+ }
3025
+ });
3026
+ }
3027
+ }
3028
+ // if it's not nested, checking is much easier and do that here:
3029
+ else if (typeof trial[param] === "undefined" || trial[param] === null) {
3030
+ if (typeof trial.type.info.parameters[param].default === "undefined") {
3031
+ console.error("You must specify a value for the " +
3032
+ param +
3033
+ " parameter in the " +
3034
+ trial.type.info.name +
3035
+ " plugin.");
3036
+ }
3037
+ else {
3038
+ trial[param] = trial.type.info.parameters[param].default;
3039
+ }
3040
+ }
3041
+ }
3042
+ }
3043
+ checkExclusions(exclusions) {
3044
+ return __awaiter(this, void 0, void 0, function* () {
3045
+ if (exclusions.min_width || exclusions.min_height || exclusions.audio) {
3046
+ console.warn("The exclusions option in `initJsPsych()` is deprecated and will be removed in a future version. We recommend using the browser-check plugin instead. See https://www.jspsych.org/latest/plugins/browser-check/.");
3047
+ }
3048
+ // MINIMUM SIZE
3049
+ if (exclusions.min_width || exclusions.min_height) {
3050
+ const mw = exclusions.min_width || 0;
3051
+ const mh = exclusions.min_height || 0;
3052
+ if (window.innerWidth < mw || window.innerHeight < mh) {
3053
+ this.getDisplayElement().innerHTML =
3054
+ "<p>Your browser window is too small to complete this experiment. " +
3055
+ "Please maximize the size of your browser window. If your browser window is already maximized, " +
3056
+ "you will not be able to complete this experiment.</p>" +
3057
+ "<p>The minimum width is " +
3058
+ mw +
3059
+ "px. Your current width is " +
3060
+ window.innerWidth +
3061
+ "px.</p>" +
3062
+ "<p>The minimum height is " +
3063
+ mh +
3064
+ "px. Your current height is " +
3065
+ window.innerHeight +
3066
+ "px.</p>";
3067
+ // Wait for window size to increase
3068
+ while (window.innerWidth < mw || window.innerHeight < mh) {
3069
+ yield delay(100);
3070
+ }
3071
+ this.getDisplayElement().innerHTML = "";
3072
+ }
3073
+ }
3074
+ // WEB AUDIO API
3075
+ if (typeof exclusions.audio !== "undefined" && exclusions.audio) {
3076
+ if (!window.hasOwnProperty("AudioContext") && !window.hasOwnProperty("webkitAudioContext")) {
3077
+ this.getDisplayElement().innerHTML =
3078
+ "<p>Your browser does not support the WebAudio API, which means that you will not " +
3079
+ "be able to complete the experiment.</p><p>Browsers that support the WebAudio API include " +
3080
+ "Chrome, Firefox, Safari, and Edge.</p>";
3081
+ throw new Error();
3082
+ }
3083
+ }
3084
+ });
3085
+ }
3086
+ drawProgressBar(msg) {
3087
+ document
3088
+ .querySelector(".jspsych-display-element")
3089
+ .insertAdjacentHTML("afterbegin", '<div id="jspsych-progressbar-container">' +
3090
+ "<span>" +
3091
+ msg +
3092
+ "</span>" +
3093
+ '<div id="jspsych-progressbar-outer">' +
3094
+ '<div id="jspsych-progressbar-inner"></div>' +
3095
+ "</div></div>");
3096
+ }
3097
+ updateProgressBar() {
3098
+ this.setProgressBar(this.getProgress().percent_complete / 100);
3099
+ }
3100
+ setProgressBar(proportion_complete) {
3101
+ proportion_complete = Math.max(Math.min(1, proportion_complete), 0);
3102
+ document.querySelector("#jspsych-progressbar-inner").style.width =
3103
+ proportion_complete * 100 + "%";
3104
+ this.progress_bar_amount = proportion_complete;
3105
+ }
3106
+ getProgressBarCompleted() {
3107
+ return this.progress_bar_amount;
3108
+ }
3109
+ }
3110
+
3111
+ // temporary patch for Safari
3112
+ if (typeof window !== "undefined" &&
3113
+ window.hasOwnProperty("webkitAudioContext") &&
3114
+ !window.hasOwnProperty("AudioContext")) {
3115
+ // @ts-expect-error
3116
+ window.AudioContext = webkitAudioContext;
3117
+ }
3118
+ // end patch
3119
+ // The following function provides a uniform interface to initialize jsPsych, no matter whether a
3120
+ // browser supports ES6 classes or not (and whether the ES6 build or the Babel build is used).
3121
+ /**
3122
+ * Creates a new JsPsych instance using the provided options.
3123
+ *
3124
+ * @param options The options to pass to the JsPsych constructor
3125
+ * @returns A new JsPsych instance
3126
+ */
3127
+ function initJsPsych(options) {
3128
+ const jsPsych = new JsPsych(options);
3129
+ // Handle invocations of non-existent v6 methods with migration errors
3130
+ const migrationMessages = {
3131
+ init: "`jsPsych.init()` was replaced by `initJsPsych()` in jsPsych v7.",
3132
+ ALL_KEYS: 'jsPsych.ALL_KEYS was replaced by the "ALL_KEYS" string in jsPsych v7.',
3133
+ NO_KEYS: 'jsPsych.NO_KEYS was replaced by the "NO_KEYS" string in jsPsych v7.',
3134
+ // Getter functions that were renamed
3135
+ currentTimelineNodeID: "`currentTimelineNodeID()` was renamed to `getCurrentTimelineNodeID()` in jsPsych v7.",
3136
+ progress: "`progress()` was renamed to `getProgress()` in jsPsych v7.",
3137
+ startTime: "`startTime()` was renamed to `getStartTime()` in jsPsych v7.",
3138
+ totalTime: "`totalTime()` was renamed to `getTotalTime()` in jsPsych v7.",
3139
+ currentTrial: "`currentTrial()` was renamed to `getCurrentTrial()` in jsPsych v7.",
3140
+ initSettings: "`initSettings()` was renamed to `getInitSettings()` in jsPsych v7.",
3141
+ allTimelineVariables: "`allTimelineVariables()` was renamed to `getAllTimelineVariables()` in jsPsych v7.",
3142
+ };
3143
+ Object.defineProperties(jsPsych, Object.fromEntries(Object.entries(migrationMessages).map(([key, message]) => [
3144
+ key,
3145
+ {
3146
+ get() {
3147
+ throw new MigrationError(message);
3148
+ },
3149
+ },
3150
+ ])));
3151
+ return jsPsych;
3152
+ }
3153
+
3154
+ exports.JsPsych = JsPsych;
3155
+ exports.initJsPsych = initJsPsych;
3156
+ exports.universalPluginParameters = universalPluginParameters;
3157
+
3158
+ Object.defineProperty(exports, '__esModule', { value: true });
3159
+
3160
+ return exports;
3161
+
3162
+ })({});
3163
+ var initJsPsych = jsPsychModule.initJsPsych;
3164
+ //# sourceMappingURL=index.browser.js.map