jspsych 6.2.0 → 7.1.0

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