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