-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmagpie.js
2473 lines (2199 loc) · 95.3 KB
/
magpie.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const magpieDrawShapes = function(trialInfo) {
// applies user's setting if there are such
const canvasHeight =
trialInfo.canvasSettings === undefined ||
trialInfo.canvasSettings.height === undefined
? 300
: trialInfo.canvasSettings.height;
const canvasWidth =
trialInfo.canvasSettings === undefined ||
trialInfo.canvasSettings.width === undefined
? 500
: trialInfo.canvasSettings.width;
const canvasBg =
trialInfo.canvasSettings === undefined ||
trialInfo.canvasSettings.background === undefined
? "white"
: trialInfo.canvasSettings.background;
const createCanvas = function(height, width, bg) {
const canvas = {};
const canvasElem = document.createElement("canvas");
const context = canvasElem.getContext("2d");
canvasElem.classList.add("magpie-view-canvas");
canvasElem.height = height;
canvasElem.width = width;
canvasElem.style.backgroundColor = bg;
$(".magpie-view-stimulus").prepend(canvasElem);
// draws a SHAPE of SIZE and COLOR in the position X and Y
canvas.draw = function(shape, size, x, y, color) {
context.beginPath();
if (shape === "circle") {
context.arc(x, y, size / 2, 0, 2 * Math.PI);
} else if (shape === "square") {
context.rect(x - size / 2, y - size / 2, size, size);
} else if (shape === "triangle") {
var delta = size / (Math.sqrt(3) * 2);
context.moveTo(x - size / 2, y + delta);
context.lineTo(x + size / 2, y + delta);
context.lineTo(x, y - 2 * delta);
}
// sets better base colours
if (color === "blue") {
context.fillStyle = "#2c89df";
} else if (color === "green") {
context.fillStyle = "#22ce59";
} else if (color === "red") {
context.fillStyle = "#ff6347";
} else if (color === "yellow") {
context.fillStyle = "#ecd70b";
} else {
context.fillStyle = color;
}
context.closePath();
context.fill();
};
// generates two sided coordinates
canvas.getTwoSidedCoords = function(
rows,
gap,
number,
size,
direction = "row"
) {
// a list of coords
var coords = [];
var tempCoords = [];
// the space between the elems
var margin = size / 2;
var columns, xStart, yStart;
// reset the rows if not passed or more than the total elems
rows = rows === 0 || rows === undefined ? 1 : rows;
rows = rows > number ? number : rows;
// sets a gap if not specified
gap =
gap <= size + margin || gap === undefined ? margin + size : gap;
// calculates the total number of columns per side
columns = Math.ceil(number / rows);
// gets the first coordinate so that the elems are centered on the canvas
xStart =
(canvasElem.width - (columns * size + (columns - 2) * margin)) /
2 +
margin / 2 -
gap / 2;
yStart =
(canvasElem.height - (rows * size + (rows - 2) * margin)) / 2 +
margin;
// expands the canvas if needed
if (xStart < margin) {
canvasElem.width += -2 * xStart;
xStart = margin;
}
// expands the canvas if needed
if (yStart < margin) {
canvasElem.height += -2 * yStart;
yStart = margin;
}
// generates the coords
// for each row
for (var i = 0; i < rows; i++) {
// for each elem
for (var j = 0; j < number; j++) {
// x position, y position
var xPos, yPos;
// position on the right
if (
Math.floor(j / columns) === i &&
j % columns >= Math.ceil(columns / 2)
) {
xPos =
xStart +
(j % columns) * size +
(j % columns) * margin +
gap;
yPos = yStart + i * size + i * margin;
tempCoords.push({ x: xPos, y: yPos });
// position on the left
} else if (Math.floor(j / columns) === i) {
xPos =
xStart +
(j % columns) * size +
(j % columns) * margin;
yPos = yStart + i * size + i * margin;
tempCoords.push({ x: xPos, y: yPos });
}
}
}
// coords' position on the canvas
/*
----------------
| |
| 000 00x |
| xxx xxx |
| xxx xxx |
| |
----------------
*/
if (direction === "row") {
coords = tempCoords;
/*
----------------
| |
| 000 xxx |
| 00x xxx |
| xxx xxx |
| |
----------------
*/
} else if (direction === "side_row") {
var leftPart = [];
var rightPart = [];
for (var i = 0; i < tempCoords.length; i++) {
if (i % columns < columns / 2) {
leftPart.push(tempCoords[i]);
} else {
rightPart.push(tempCoords[i]);
}
}
coords = leftPart.concat(rightPart);
/*
----------------
| |
| 00x xxx |
| 00x xxx |
| 0xx xxx |
| |
----------------
*/
} else if (direction === "column") {
var idx;
for (var i = 0; i < tempCoords.length; i++) {
idx = (i % rows) * columns + Math.floor(i / rows);
coords.push(tempCoords[idx]);
}
}
return coords;
};
// generates random coords
canvas.getRandomCoords = function(number, size) {
let coords = [];
const margin = size / 2;
// increases the canvas if to small to fit all the elems
(function() {
// get the default dimetions of the canvas
let height = canvasElem.height;
let width = canvasElem.width;
// calculate the area of the elements
let elementsArea = size * size * number;
let stimContainerElem = $(".magpie-view-stimulus-container");
// keep increasing the canvas until the elementsArea is smaller than 10% of the overall canvas area
const increaseCanvas = function(height, width) {
if ((height * width) / 10 < elementsArea) {
return increaseCanvas(
height + height / 10,
width + width / 10
);
} else {
return [height, width];
}
};
// get the height and width
let [newHeight, newWidth] = increaseCanvas(height, width);
// apply the new height and width to the canvas elem
canvasElem.height = newHeight;
canvasElem.width = newWidth;
// increase the stimulus container as well to fit the canvas
stimContainerElem.css("height", newHeight + 20);
})();
// generates random x and y coordinates on the canvas for one element
const generateCoords = function() {
const maxWidth = canvasElem.width - size;
const maxHeight = canvasElem.height - size;
const xPos =
Math.floor(Math.random() * (maxWidth - size)) + size;
const yPos =
Math.floor(Math.random() * (maxHeight - size)) + size;
return { x: xPos, y: yPos };
};
// ensures no elements overlap or are too close
const checkCoords = function(xPos, yPos) {
for (var i = 0; i < coords.length; i++) {
if (
xPos + size + margin > coords[i]["x"] &&
xPos - size - margin < coords[i]["x"] &&
yPos + size + margin > coords[i]["y"] &&
yPos - size - margin < coords[i]["y"]
) {
return false;
}
}
return true;
};
// generates x and y positions on the canvas for one element
// checks whether the coord is valid
const findValidCoords = function() {
let tempCoords = generateCoords();
if (checkCoords(tempCoords.x, tempCoords.y)) {
coords.push(tempCoords);
} else {
findValidCoords();
}
};
// finds valid coordinates for each element
for (i = 0; i < number; i++) {
findValidCoords();
}
return coords;
};
// generates grid coordinates
canvas.getGridCoords = function(rows, number, size) {
var coords = [];
var margin = size / 2;
var columns, xStart, yStart;
// sets the rows to 1 if not passed
if (rows === 0 || rows === undefined) {
rows = 1;
} else if (rows > number) {
rows = number;
}
// calculates the number of columns
columns = Math.ceil(number / rows);
// finds the starting point for the x axis so that the image ends up centered
xStart =
(canvasElem.width - (columns * size + (columns - 2) * margin)) /
2 +
margin / 2;
// finds the starting point for the y axis so that the image ends up centered
yStart =
(canvasElem.height - (rows * size + (rows - 2) * margin)) / 2 +
margin;
// increases the canvas's width if needed
if (xStart < margin) {
canvasElem.width += -2 * xStart;
xStart = margin;
}
// increases the canvas's height if needed
if (yStart < margin) {
canvasElem.height += -2 * yStart;
yStart = margin;
}
// generates all the coords
for (var i = 0; i < rows; i++) {
for (var j = 0; j < number; j++) {
if (Math.floor(j / columns) === i) {
coords.push({
x:
xStart +
(j % columns) * size +
(j % columns) * margin,
y: yStart + i * size + i * margin
});
} else {
continue;
}
}
}
return coords;
};
return canvas;
};
const canvas = createCanvas(canvasHeight, canvasWidth, canvasBg);
const coords =
trialInfo.sort == "grid"
? canvas.getGridCoords(
trialInfo.rows,
trialInfo.total,
trialInfo.elemSize
)
: trialInfo.sort == "split_grid"
? canvas.getTwoSidedCoords(
trialInfo.rows,
trialInfo.gap,
trialInfo.total,
trialInfo.elemSize,
trialInfo.direction
)
: canvas.getRandomCoords(trialInfo.total, trialInfo.elemSize);
if (trialInfo.start_with === "other") {
for (let i = 0; i < trialInfo.total; i++) {
if (i < trialInfo.total - trialInfo.focalNumber) {
canvas.draw(
trialInfo.otherShape,
trialInfo.elemSize,
coords[i].x,
coords[i].y,
trialInfo.otherColor
);
} else {
canvas.draw(
trialInfo.focalShape,
trialInfo.elemSize,
coords[i].x,
coords[i].y,
trialInfo.focalColor
);
}
}
} else {
for (let i = 0; i < trialInfo.total; i++) {
if (i < trialInfo.focalNumber) {
canvas.draw(
trialInfo.focalShape,
trialInfo.elemSize,
coords[i].x,
coords[i].y,
trialInfo.focalColor
);
} else {
canvas.draw(
trialInfo.otherShape,
trialInfo.elemSize,
coords[i].x,
coords[i].y,
trialInfo.otherColor
);
}
}
}
};
const errors = {
contactEmail: `There is no contact_email given. Please give a contact_email to the magpieInit function,
for example:
magpieInit({
...
deploy: {
...
contact_email: '[email protected]',
...
},
...
});`,
prolificURL: `There is no prolificURL given. Please give a prolificURL to the magpieInit function,
for example:
magpieInit({
...
deploy: {
...
prolificURL: 'https://app.prolific.ac/submissions/complete?cc=SAMPLE',
...
},
...
});`,
noTrials: `No trials given. Each _magpie view takes an object with an obligatory 'trial' property.
for example:
const introView = intro({
...
trials: 1,
...
});
You can find more information at https://github.com/magpie-ea/magpie-modules#views-in-_magpie`,
noName: `No name given. Each _magpie view takes an object with an obligatory 'name' property
for example:
const introView = intro({
...
name: 'introView',
...
});
You can find more information at https://github.com/magpie-ea/magpie-modules#views-in-_magpie`,
noData: `No data given. Each _magpie view takes an object with an obligatory 'data' property
for example:
const mainTrials = forcedChoice({
...
data: my_main_trials,
...
});
The data is a list of objects defined in your local js file.
_magpie's trial views expect each trial object to have specific properties. Here is an example of a forcedCoice view trial:
{
question: 'How are you today?',
option1: 'fine',
option2: 'good'
}
You can find more information at https://github.com/magpie-ea/magpie-modules#views-in-_magpie`,
notAnArray: `The data is not an array. Trial views get an array of objects.
for example:
const mainTrials = forcedChoice({
...
data: [
{
prop: val,
prop: val
},
{
prop: val,
prop:val
}
],
...
});`,
noSuchViewName: `The view name listed in progress_bar.in does not exist. Use the view names to reference the views in progress_bar.in.
for example:
const mainView = forcedChoice({
...
name: 'myMainView',
...
});
const introView = intro({
...
name: 'intro',
...
});
magpieInit({
...
progress_bar: {
in: [
"myMainView"
],
style: "chunks"
width: 100
},
...
});
`,
canvasSort: `No such 'canvas.sort' value. canvas.sort can be 'grid', 'split_grid' or 'random'.
for example:
const myTrials = [
{
question: 'Are there circles on the picture',
option1: 'yes',
option2: 'yes',
canvas: {
...
sort: 'split_grid'
...
}
}
];`
};
const info = {
canvasTooSmall: `The canvas size was increased because the default canvas size was too small to fit all the elements.
Btw, you can manually change the canvas size by passing 'canvasSettings' to the canvas object,
however, your canvas settings might be overridden if needed.
For example:
const myTrials = [
...
{
question: 'Are there circles on the picture',
option1: 'yes',
option2: 'no',
canvas: {
canvasSettings: {
height: int,
width: int
},
...
}
},
...
];
See https://github.com/magpie-ea/magpie-modules/blob/master/docs/canvas.md for more information.
`
};
const magpieInit = function(config) {
const magpie = {};
// views handler
magpie.views_seq = _.flatten(config.views_seq);
magpie.currentViewCounter = 0;
magpie.currentTrialCounter = 0;
magpie.currentTrialInViewCounter = 0;
// progress bar information
magpie.progress_bar = config.progress_bar;
// results collection
// --
// general data
magpie.global_data = {
startDate: Date(),
startTime: Date.now()
};
// data from trial views
magpie.trial_data = [];
// more deploy information added
magpie.deploy = config.deploy;
magpie.deploy.MTurk_server =
magpie.deploy.deployMethod === "MTurkSandbox"
? "https://workersandbox.mturk.com/mturk/externalSubmit" // URL for MTurk sandbox
: magpie.deploy.deployMethod === "MTurk"
? "https://www.mturk.com/mturk/externalSubmit" // URL for live HITs on MTurk
: ""; // blank if deployment is not via MTurk
// if the config_deploy.deployMethod is not debug, then liveExperiment is true
magpie.deploy.liveExperiment = magpie.deploy.deployMethod !== "debug";
magpie.deploy.is_MTurk = magpie.deploy.MTurk_server !== "";
magpie.deploy.submissionURL =
magpie.deploy.deployMethod === "localServer"
? "http://localhost:4000/api/submit_experiment/" +
magpie.deploy.experimentID
: magpie.deploy.serverAppURL + magpie.deploy.experimentID;
// This is not ideal. Should have specified the "serverAppURL" as the base URL, instead of the full URL including "submit_experiment". That naming can be misleading.
const regex = "/submit_experiment/";
magpie.deploy.checkExperimentURL = magpie.deploy.submissionURL.replace(
regex,
"/check_experiment/"
);
if (typeof config.timer === 'undefined') {
magpie.timer = "";
} else {
magpie.timer = config.timer;
magpieTimer(magpie);
}
// adds progress bars to the views
magpie.progress = magpieProgress(magpie);
// makes the submit available
magpie.submission = magpieSubmit(magpie);
// handles the views rendering
magpie.findNextView = function() {
let currentView = magpie.views_seq[magpie.currentViewCounter];
if (magpie.currentTrialInViewCounter < currentView.trials) {
currentView.render(currentView.CT, magpie);
} else {
magpie.currentViewCounter++;
currentView = magpie.views_seq[magpie.currentViewCounter];
magpie.currentTrialInViewCounter = 0;
if (currentView !== undefined) {
currentView.render(currentView.CT, magpie);
} else {
$("#main").html(
`<div class='magpie-view'>
<h1 class="title">Nothing more to show</h1>
</div>`
);
return;
}
}
// increment counter for how many trials we have seen of THIS view during THIS occurrence of it
magpie.currentTrialInViewCounter++;
// increment counter for how many trials we have seen in the whole experiment
magpie.currentTrialCounter++;
// increment counter for how many trials we have seen of THIS view during the whole experiment
currentView.CT++;
// updates the progress bar if the view has one
if (currentView.hasProgressBar) {
magpie.progress.update();
}
};
// checks the deployMethod
(function() {
if (
magpie.deploy.deployMethod === "MTurk" ||
magpie.deploy.deployMethod === "MTurkSandbox"
) {
console.info(
`The experiment runs on MTurk (or MTurk's sandbox)
----------------------------
The ID of your experiment is ${magpie.deploy.experimentID}
The results will be submitted ${magpie.deploy.submissionURL}
and
MTurk's server: ${magpie.deploy.MTurk_server}`
);
} else if (magpie.deploy.deployMethod === "Prolific") {
console.info(
`The experiment runs on Prolific
-------------------------------
The ID of your experiment is ${magpie.deploy.experimentID}
The results will be submitted to ${magpie.deploy.submissionURL}
with
Prolific URL (must be the same as in the website): ${magpie.deploy.prolificURL}`
);
} else if (magpie.deploy.deployMethod === "directLink") {
console.info(
`The experiment uses Direct Link
-------------------------------
The ID of your experiment is ${magpie.deploy.experimentID}
The results will be submitted to ${magpie.deploy.submissionURL}`
);
} else if (magpie.deploy.deployMethod === "debug") {
console.info(
`The experiment is in Debug Mode
-------------------------------
The results will be displayed in a table at the end of the experiment and available to download in CSV format.`
);
} else if (magpie.deploy.deployMethod !== "localServer") {
throw new Error(
`There is no such deployMethod.
Please use 'debug', 'directLink', 'Mturk', 'MTurkSandbox', 'localServer' or 'Prolific'.
The deploy method you provided is '${magpie.deploy.deployMethod}'.
You can find more information at https://github.com/magpie-ea/magpie-modules`
);
}
if (
magpie.deploy.deployMethod === "Prolific" &&
(magpie.deploy.prolificURL === undefined ||
magpie.deploy.prolificURL === "")
) {
throw new Error(errors.prolificURL);
}
if (
magpie.deploy.contact_email === undefined ||
magpie.deploy.contact_email === ""
) {
throw new Error(errors.contactEmail);
}
})();
// Checks whether the experiment is valid and reachable on the server before proceeding.
if (magpie.deploy.deployMethod !== "debug") {
$.ajax({
type: "GET",
url: magpie.deploy.checkExperimentURL,
crossDomain: true,
success: function(responseData, textStatus, jqXHR) {
// adds progress bars
magpie.progress.add();
// renders the first view
magpie.findNextView();
},
error: function(jqXHR, textStatus, error) {
alert(
`Sorry, there is an error communicating with our server and the experiment cannot proceed. Please return the HIT immediately and contact the author at ${
magpie.deploy.contact_email
}. Please include the following error message: "${
jqXHR.responseText
}". Thank you for your understanding.`
);
}
});
} else {
// adds progress bars
magpie.progress.add();
// renders the first view
magpie.findNextView();
}
// return the magpie-object in debug mode to make debugging easier
if (magpie.deploy.deployMethod === 'debug'){
return magpie;
} else {
return null;
}
};
const magpieMousetracking = function (config, data) {
var $view = $('body')
var listener = function (evt) {
data.mousetrackingX.push(evt.originalEvent.clientX - data.mousetracking.x)
data.mousetrackingY.push(evt.originalEvent.clientY - data.mousetracking.y)
data.mousetrackingTime.push(Date.now() - data.mousetrackingStartTime)
}
var rate = config && config.rate ? config.rate : 15
// cleanup function
data.mousetracking = {
x: 0,
y: 0,
cleanup: function () {
$view.off('mousemove', listener)
if (!data.mousetrackingTime) {
return;
}
data.mousetrackingDuration = data.mousetrackingTime[data.mousetrackingTime.length - 1]
interpolate(rate)
},
start: function (origin) {
if (!origin || !origin.x || !origin.y) {
const rect = $view.getBoundingClientRect()
origin = {x: (rect.left+rect.right)/2, y: (rect.top+rect.bottom)/2}
}
$view.on('mousemove', listener)
data.mousetrackingStartTime = Date.now()
data.mousetracking.x = origin.x
data.mousetracking.y = origin.y
data.mousetrackingX = [0]
data.mousetrackingY = [0]
data.mousetrackingTime = [0]
}
}
if (config && config.autostart) {
data.mousetracking.start()
}
function interpolate(rate) {
const interpolated = {time: [], x: [], y: []}
for (let i = 0; i < data.mousetrackingTime.length; i++) {
interpolated.time.push(data.mousetrackingTime[i])
interpolated.x.push(data.mousetrackingX[i])
interpolated.y.push(data.mousetrackingY[i])
if (i < data.mousetrackingTime.length - 1 &&
data.mousetrackingTime[i + 1] - data.mousetrackingTime[i] > rate) {
const steps = ((data.mousetrackingTime[i + 1] - data.mousetrackingTime[i]) / rate) - 1;
const xDelta = (data.mousetrackingX[i + 1] - data.mousetrackingX[i]) / (steps + 1)
const yDelta = (data.mousetrackingY[i + 1] - data.mousetrackingY[i]) / (steps + 1)
const index = interpolated.time.length-1
for (let j = 0; j < steps; j++) {
interpolated.time.push(interpolated.time[index + j] + rate)
interpolated.x.push(Math.round(interpolated.x[index + j] + xDelta))
interpolated.y.push(Math.round(interpolated.y[index + j] + yDelta))
}
}
}
data.mousetrackingTime = interpolated.time
data.mousetrackingX = interpolated.x
data.mousetrackingY = interpolated.y
}
};
const magpieProgress = function(magpie) {
let totalProgressParts = 0;
let progressTrials = 0;
// customize.progress_bar_style is "chunks" or "separate" {
let totalProgressChunks = 0;
let filledChunks = 0;
let fillChunk = false;
const progress = {
// adds progress bar(s) to the views specified experiment.js
add: function() {
magpie.views_seq.map((view) => {
for (let j = 0; j < magpie.progress_bar.in.length; j++) {
if (view.name === magpie.progress_bar.in[j]) {
totalProgressChunks++;
totalProgressParts += view.trials;
view.hasProgressBar = true;
}
}
});
},
// updates the progress of the progress bar
// creates a new progress bar(s) for each view that has it and updates it
update: function() {
try {
addToDOM();
} catch (e) {
console.error(e.message);
}
const progressBars = $(".progress-bar");
let div, filledPart;
if (magpie.progress_bar.style === "default") {
div = $(".progress-bar").width() / totalProgressParts;
filledPart = progressTrials * div;
} else {
div =
$(".progress-bar").width() /
magpie.views_seq[magpie.currentViewCounter].trials;
filledPart = (
(magpie.currentTrialInViewCounter - 1) *
div
).toFixed(4);
}
const filledElem = jQuery("<span/>", {
id: "filled"
}).appendTo(progressBars[filledChunks]);
$("#filled").css("width", filledPart);
progressTrials++;
if (magpie.progress_bar.style === "chunks") {
if (fillChunk === true) {
filledChunks++;
fillChunk = false;
}
if (
filledElem.width().toFixed(4) ===
($(".progress-bar").width() - div).toFixed(4)
) {
fillChunk = true;
}
for (var i = 0; i < filledChunks; i++) {
progressBars[i].style.backgroundColor = "#5187BA";
}
}
}
};
// creates progress bar element(s) and add(s) it(them) to the view
const addToDOM = function() {
var bar;
var i;
var view = $(".magpie-view");
var barWidth = magpie.progress_bar.width;
var clearfix = jQuery("<div/>", {
class: "clearfix"
});
var container = jQuery("<div/>", {
class: "progress-bar-container"
});
view.css("padding-top", 30);
view.prepend(clearfix);
view.prepend(container);
if (magpie.progress_bar.style === "chunks") {
for (i = 0; i < totalProgressChunks; i++) {
bar = jQuery("<div/>", {
class: "progress-bar"
});
bar.css("width", barWidth);
container.append(bar);
}
} else if (magpie.progress_bar.style === "separate") {
bar = jQuery("<div/>", {
class: "progress-bar"
});
bar.css("width", barWidth);
container.append(bar);
} else if (magpie.progress_bar.style === "default") {
bar = jQuery("<div/>", {
class: "progress-bar"
});
bar.css("width", barWidth);
container.append(bar);
} else {
throw new Error(
'Progress_bar.style can be set to "default", "separate" or "chunks" in experiment.js'
);
}
};
return progress;
};
function magpieSubmit(magpie) {
const submit = {
// submits the data
// trials - the data collected from the experiment
// global_data - other data (start date, user agent, etc.)
// config - information about the deploy method and URLs
submit: function(magpie) {
// construct data object for output
let data = {
experiment_id: magpie.deploy.experimentID,
trials: addEmptyColumns(magpie.trial_data)
};
// merge in global_data accummulated so far
// this could be unsafe if 'global_data' contains keys used in 'trials'!!
data = _.merge(magpie.global_data, data);
// add more fields depending on the deploy method
if (magpie.deploy.is_MTurk) {
const HITData = getHITData();
data["assignment_id"] = HITData["assignmentId"];
data["worker_id"] = HITData["workerId"];
data["hit_id"] = HITData["hitId"];
// creates a form with assignmentId input for the submission ot MTurk
var form = jQuery("<form/>", {
id: "mturk-submission-form",
action: magpie.deploy.MTurk_server,
method: "POST"
}).appendTo(".magpie-thanks-view");
jQuery("<input/>", {
type: "hidden",
name: "trials",
value: JSON.stringify(data)
}).appendTo(form);
// MTurk expects a key 'assignmentId' for the submission to work,
// that is why is it not consistent with the snake case that the other keys have
jQuery("<input/>", {
type: "hidden",
name: "assignmentId",
value: HITData["assignmentId"]
}).appendTo(form);
}