-
Notifications
You must be signed in to change notification settings - Fork 71
/
drag_and_drop.js
2086 lines (1904 loc) · 84.8 KB
/
drag_and_drop.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
function DragAndDropTemplates(configuration) {
"use strict";
var gettext;
var ngettext;
if ('DragAndDropI18N' in window) {
// Use DnDv2's local translations
gettext = function(string) {
var translated = window.DragAndDropI18N.gettext(string);
// if DnDv2's translation is the same as the input, check if global has a different value
// This is useful for overriding the XBlock's string by themes (only for English)
if (string === translated && 'gettext' in window) {
translated = window.gettext(string);
}
return translated;
};
ngettext = function(strA, strB, n) {
var translated = window.DragAndDropI18N.ngettext(strA, strB, n);
var string = n == 1 ? strA : strB;
if (string === translated && 'gettext' in window) {
translated = window.gettext(strA, strB, n);
}
return translated;
};
} else if ('gettext' in window) {
// Use edxapp's global translations
gettext = window.gettext;
ngettext = window.ngettext;
}
if (typeof gettext == "undefined") {
// No translations -- used by test environment
gettext = function(string) { return string; };
ngettext = function(strA, strB, n) { return n == 1 ? strA : strB; };
}
var h = virtualDom.h;
var isMobileScreen = function() {
return window.matchMedia('screen and (max-width: 480px)').matches;
};
var itemSpinnerTemplate = function(item) {
if (!item.xhr_active) {
return null;
}
return (
h("div.spinner-wrapper", {key: item.value + '-spinner'}, [
h("span.fa.fa-spin.fa-spinner", {attributes: {'aria-hidden': true}}),
h("span.sr", gettext('Submitting'))
])
);
};
var renderCollection = function(template, collection, ctx) {
return collection.map(function(item) {
return template(item, ctx);
});
};
var getZone = function(zoneUID, ctx) {
for (var i = 0; i < ctx.zones.length; i++) {
if (ctx.zones[i].uid === zoneUID) {
return ctx.zones[i];
}
}
};
var bankItemWidthStyles = function(item, ctx) {
var style = {};
if (item.widthPercent) {
// The item bank container is often wider than the background image, and the
// widthPercent is specified relative to the background image so we have to
// convert it to pixels. But if the browser window is not as wide as the image,
// then the background image will be scaled down and this pixel value would be too large,
// so we also specify it as a max-width percentage.
// On mobile, the image is never scaled down, so we don't specify the max-width.
style.width = (item.widthPercent / 100 * ctx.bg_image_width) + "px";
style.maxWidth = isMobileScreen() ? 'none' : item.widthPercent + "%";
}
return style;
};
var itemContentTemplate = function(item) {
var item_content_html = gettext(item.displayName);
if (item.imageURL) {
item_content_html = '<img src="' + item.imageURL + '" alt="' + item.imageDescription + '" />';
}
var key = item.value + '-content';
return h('div', { key: key, innerHTML: item_content_html, className: "item-content" });
};
var itemTemplate = function(item, ctx) {
// Define properties
var className = (item.class_name) ? item.class_name : "";
var zone = getZone(item.zone, ctx) || {};
if (item.has_image) {
className += " " + "option-with-image";
}
if (item.widthPercent) {
className += " specified-width"; // The author has specified a width for this item.
}
var attributes = {
'role': 'button',
'draggable': !item.drag_disabled,
'aria-grabbed': item.grabbed,
'data-value': item.value,
'tabindex': item.focusable ? 0 : undefined,
'aria-live': 'polite'
};
var style = {};
if (item.background_color) {
style['background-color'] = item.background_color;
}
if (item.color) {
style.color = item.color;
// Ensure contrast between outline-color and background color
// matches contrast between text color and background color:
style['outline-color'] = item.color;
}
if (item.is_dragged) {
style.position = 'absolute';
var left = Math.max(0, Math.min(item.max_left, item.drag_position.left));
var top = Math.max(0, Math.min(item.max_top, item.drag_position.top));
style.left = left + 'px';
style.top = top + 'px';
}
if (item.is_placed) {
var maxWidth = (item.widthPercent || 30) / 100;
var widthPercent = zone.width_percent / 100;
var possiblemaxWidth = ((1 / (widthPercent / maxWidth)) * 100);
style.maxWidth = (possiblemaxWidth < 100) ? possiblemaxWidth + '%' : '100%';
if (item.widthPercent) {
style.width = style.maxWidth;
}
// Finally, if the item is using automatic sizing and contains an image, we
// always prefer the natural width of the image (subject to the max-width):
if (item.imgNaturalWidth && !item.widthPercent && !item.noPadding) {
style.width = (item.imgNaturalWidth + 22) + "px"; // 22px is for 10px padding + 1px border each side
// ^ Hack to detect image width at runtime and make webkit consistent with Firefox
}
if (item.noPadding) {
style.width = item.imgNaturalWidth + "px";
style.padding = '0';
}
} else {
$.extend(style, bankItemWidthStyles(item, ctx));
}
if (item.grabbed_with) {
className += " grabbed-with-" + item.grabbed_with;
// Clear width and maxWidth styles and use the bankItemWidthStyles
// This prevents inconsistency in width for grabbed items
delete style.width
delete style.maxWidth
$.extend(style, bankItemWidthStyles(item, ctx));
}
// Define children
var item_content = itemContentTemplate(item);
var item_description = null;
// Insert information about zone in which this item has been placed
if (item.is_placed) {
var zone_title = (gettext(zone.title) || gettext("Unknown Zone"));
var description_content;
if (configuration.mode === DragAndDropBlock.ASSESSMENT_MODE && !ctx.showing_answer) {
// In assessment mode placed items will "stick" even when not in correct zone.
description_content = gettext('Placed in: {zone_title}').replace('{zone_title}', zone_title);
} else {
// In standard mode item is immediately returned back to the bank if dropped on a wrong zone,
// so all placed items are always in the correct zone.
description_content = gettext('Correctly placed in: {zone_title}').replace('{zone_title}', zone_title);
}
var item_description_id = configuration.url_name + '-item-' + item.value + '-description';
item_content.properties.attributes = { 'aria-describedby': item_description_id };
item_description = h(
'div.sr.description',
{ key: item_description_id, id: item_description_id},
description_content
);
}
var itemSRNote = h(
'span.sr.draggable',
(item.grabbed) ? gettext(", draggable, grabbed") : gettext(", draggable")
);
var children = [
itemSpinnerTemplate(item), item_content, itemSRNote, item_description
];
// Unique key for virtual dom change tracking. Key must be different for
// Placed vs Dragged vs Unplaced, or weird bugs can occur.
var key = item.value;
if (item.is_placed && item.is_dragged) {
key += '-pd';
} else if (item.is_placed) {
key += '-p';
} else if (item.is_dragged) {
key += '-d';
} else {
key += '-u';
}
return (
h(
'div.option',
{
key: key,
className: className,
attributes: attributes,
style: style
},
children
)
);
};
// When an item is dragged out of the bank, a hidden placeholder of the same width and height as
// the original item is rendered in the bank. The function of the placeholder is to take up the
// same amount of space as the original item so that the bank does not collapse when you've dragged
// all items out.
var itemPlaceholderTemplate = function(item, ctx) {
var className = "";
if (item.has_image) {
className += " " + "option-with-image";
}
if (item.widthPercent) {
className += " specified-width"; // The author has specified a width for this item.
}
var style = bankItemWidthStyles(item, ctx);
// Placeholder should never be visible.
style.visibility = 'hidden';
return (
h(
'div.option',
{
key: 'placeholder-' + item.value,
className: className,
attributes: {draggable: false},
style: style
},
itemContentTemplate(item)
)
);
};
var zoneTemplate = function(zone, ctx) {
var className = ctx.display_zone_labels ? 'zone-name' : 'zone-name sr';
var selector = ctx.display_zone_borders ? 'div.zone.zone-with-borders' : 'div.zone';
// Mark item alignment and render its placed items as children
var item_wrapper = 'div.item-wrapper.item-align.item-align-' + zone.align;
// In assessment mode already placed items can be dragged out of their current zone.
// Only render placed items that are not currently being dragged out of the zone.
var is_item_in_zone = function(i) { return i.is_placed && !i.is_dragged && (i.zone === zone.uid); };
var items_in_zone = $.grep(ctx.items, is_item_in_zone);
var zone_description_id = zone.prefixed_uid + '-description';
if (items_in_zone.length == 0) {
var zone_description = h(
'div',
{ id: zone_description_id, className: 'sr'},
gettext("No items placed here")
);
} else {
var zone_description = h(
'div',
{ id: zone_description_id, className: 'sr'},
gettext('Items placed here: ') + items_in_zone.map(function (item) { return item.displayName; }).join(", ")
);
}
return (
h(
selector,
{
key: zone.prefixed_uid,
id: zone.prefixed_uid,
attributes: {
'tabindex': 0,
'dropzone': 'move',
'aria-dropeffect': 'move',
'data-uid': zone.uid,
'data-zone_align': zone.align,
'role': 'button',
'aria-describedby': zone_description_id,
},
style: {
top: zone.y_percent + '%', left: zone.x_percent + "%",
width: zone.width_percent + '%', height: zone.height_percent + "%",
}
},
[
h(
'p',
{
className: className,
innerHTML: gettext(zone.title)
},
[
h('span.sr', gettext(', dropzone'))
]
),
h('p', { className: 'zone-description sr' }, gettext(zone.description) || gettext('droppable')),
h(item_wrapper, renderCollection(itemTemplate, items_in_zone, ctx)),
gettext(zone_description)
]
)
);
};
var feedbackTemplate = function(ctx) {
var messages = ctx.overall_feedback_messages || [];
var feedback_display = messages.length > 0 ? 'block' : 'none';
var feedback_messages = messages.map(function(message) {
var selector = "p.message";
if (message.message_class) {
selector += "."+message.message_class;
}
return h(selector, {innerHTML: gettext(message.message)}, []);
});
return (
h('div.feedback', {
attributes: {'role': 'group', 'aria-label': gettext('Feedback')},
style: { display: feedback_display }
}, [
h('div.feedback-content',[
h('h3.title1', gettext('Feedback')),
h('div.messages', gettext(feedback_messages)),
])
])
);
};
var explanationTemplate = function (ctx) {
var explanation_display = ctx.explanation ? 'block' : 'none';
return (
h('.solution-span', {
attributes: {'aria-label': gettext('Explanation')},
style: {display: explanation_display}
}, [
h('span', [
h('.detailed-solution', [
h('p', gettext('Explanation')),
h('p', {innerHTML: gettext(ctx.explanation)}),
])
])
])
);
};
var keyboardHelpPopupTemplate = function(ctx) {
var labelledby_id = 'modal-window-title-'+configuration.url_name;
return (
h('div.keyboard-help-dialog', [
h('div.modal-window-overlay'),
h('div.modal-window', {attributes: {role: 'dialog', 'aria-labelledby': labelledby_id, tabindex: -1}}, [
h('button.modal-dismiss-button.unbutton', [
h('span.fa.fa-remove', {attributes: {'aria-hidden': true}}),
h('span.sr', gettext('Close'))
]),
h('div.modal-header', [
h('h2.modal-window-title', {id: labelledby_id}, gettext('Keyboard Help'))
]),
h('div.modal-content', [
h('p.sr', gettext('This is a screen reader-friendly problem.')),
h('p.sr', gettext('Drag and Drop problems consist of draggable items and dropzones. Users should select a draggable item with their keyboard and then navigate to an appropriate dropzone to drop it.')),
h('p', gettext('You can complete this problem using only your keyboard by following the guidance below:')),
h('ul', [
h('li', gettext('Use only TAB and SHIFT+TAB to navigate between draggable items and drop zones.')),
h('li', gettext('Press CTRL+M to select a draggable item (effectively picking it up).')),
h('li', gettext('Navigate using TAB and SHIFT+TAB to the appropriate dropzone and press CTRL+M once more to drop it here.')),
h('li', gettext('Press ESC if you want to cancel the drop operation (for example, to select a different item).')),
h('li', gettext('TAB back to the list of draggable items and repeat this process until all of the draggable items have been placed on their respective dropzones.')),
])
])
])
])
);
};
var submitAnswerTemplate = function(ctx) {
var submitButtonProperties = {
disabled: ctx.disable_submit_button || ctx.submit_spinner,
attributes: {}
};
var attemptsUsedInfo = null;
if (ctx.max_attempts && ctx.max_attempts > 0) {
var attemptsUsedId = "attempts-used-" + configuration.url_name;
submitButtonProperties.attributes["aria-describedby"] = attemptsUsedId;
var attemptsUsedTemplate = gettext("You have used {used} of {total} attempts.");
var attemptsUsedText = attemptsUsedTemplate.
replace("{used}", ctx.attempts).replace("{total}", ctx.max_attempts);
attemptsUsedInfo = h("div.submission-feedback", {id: attemptsUsedId}, attemptsUsedText);
}
var submitSpinner = null;
if (ctx.submit_spinner) {
submitSpinner = h('span', [
h('span.fa.fa-spin.fa-spinner', {attributes: {'aria-hidden': true}}),
h('span.sr', gettext('Submitting'))
]);
}
return (
h("div.submit-attempt-container", {}, [
h(
"button.btn-brand.submit",
submitButtonProperties,
[
h("span.submit-label", [
submitSpinner,
' ', // whitespace between spinner icon and text
gettext("Submit")
])
]
),
attemptsUsedInfo
])
);
};
var sidebarButtonTemplate = function(buttonClass, iconClass, buttonText, options) {
options = options || {};
if (options.spinner) {
iconClass = 'fa-spin fa-spinner';
}
return (
h('span.problem-action-button-wrapper', {}, [
h(
'button.problem-action-btn.btn-default.btn-small',
{
className: buttonClass,
disabled: options.disabled || options.spinner || false
},
[
h("span.btn-icon.fa", {className: iconClass, attributes: {"aria-hidden": true}}),
buttonText
]
)
])
);
};
var sidebarTemplate = function(ctx) {
var showAnswerButton = null;
if (ctx.show_show_answer) {
var options = {
disabled: !!ctx.showing_answer,
spinner: ctx.show_answer_spinner
};
showAnswerButton = sidebarButtonTemplate(
"show",
"fa-info-circle",
gettext('Show Answer'),
options
);
}
var go_to_beginning_button_class = 'go-to-beginning-button';
if (!ctx.show_go_to_beginning_button) {
go_to_beginning_button_class += ' sr';
}
return(
h("div.problem-action-buttons-wrapper", {attributes: {'role': 'group', 'aria-label': gettext('Actions')}}, [
sidebarButtonTemplate(
go_to_beginning_button_class,
"fa-arrow-up",
gettext("Go to Beginning"),
{disabled: ctx.disable_go_to_beginning_button}
),
sidebarButtonTemplate(
"reset",
"fa-refresh",
gettext('Reset'),
{disabled: ctx.disable_reset_button}
),
showAnswerButton,
])
)
};
var itemFeedbackPopupTemplate = function(ctx) {
var popupSelector = 'div.popup.item-feedback-popup.popup-wrapper';
var msgs = ctx.feedback_messages || [];
var have_messages = msgs.length > 0;
var popup_content;
if (msgs.length > 0 && !ctx.last_action_correct) {
popupSelector += '.popup-incorrect';
}
if (ctx.mode == DragAndDropBlock.ASSESSMENT_MODE) {
var content_items;
// Check if we are dealing with feedback of limit of items in a zone
var limit_popup = msgs.reduce(
(previous, actualMessage) => previous || actualMessage.message_class === DragAndDropBlock.FEEDBACK_CLASS_ZONE_LIMIT,
false
);
if (limit_popup) {
content_items = [
msgs.map(function(message) {
return h("p", {innerHTML: gettext(message.message)});
})
];
} else {
content_items = [
(!ctx.last_action_correct) ? h("p", {}, gettext("Some of your answers were not correct.")) : null,
h("p.hints", {}, gettext("Hints:")),
h("ul", {}, msgs.map(function(message) {
return h("li", {innerHTML: gettext(message.message)});
}))
];
}
popup_content = h(
ctx.last_action_correct ? "div.popup-content" : "div.popup-content.popup-content-incorrect",
{},
have_messages ? content_items : []
);
} else {
popup_content = h(
ctx.last_action_correct ? "div.popup-content" : "div.popup-content.popup-content-incorrect",
{},
msgs.map(function(message) {
return h("p", {innerHTML: gettext(message.message)});
})
);
}
var popup_style = {};
if (!have_messages) {
popup_style.display = 'none';
}
return h(
popupSelector,
{
style: popup_style
},
[
h(
'button.unbutton.close-feedback-popup-button.close-feedback-popup-desktop-button',
{},
[
h(
'span.sr',
{
innerHTML: gettext("Close")
}
),
h(
'span.icon.fa.fa-times-circle',
{
attributes: {
'aria-hidden': true
}
}
)
]
),
h(
ctx.last_action_correct ? 'div.popup-header-icon' : 'div.popup-header-icon.popup-header-icon-incorrect',
{},
[
h(
ctx.last_action_correct ? 'span.icon.fa.fa-check-circle' : 'span.icon.fa.fa-exclamation-circle',
{
attributes: {
'aria-hidden': true
}
}
)
]
),
h(
'div.popup-header-text',
{},
ctx.last_action_correct ? gettext("Correct") : gettext("Incorrect")
),
popup_content
]
)
};
var forwardKeyboardHelpButtonTemplate = function(ctx) {
return h(
'button.unbutton.btn-link.keyboard-help-button',
[
h(
"span.btn-icon.fa.fa-keyboard-o",
{attributes: {"aria-hidden": true}}
),
// appending space is the simplest way to avoid sticking text to the button, but also to have
// them underlined together on hover. When margin was used there was a gap in underlining
" ",
gettext('Keyboard Help')
]
);
};
var progressTemplate = function(ctx) {
// Formats a number to 4 decimals without trailing zeros
// (1.00 -> '1'; 1.50 -> '1.5'; 1.333333333 -> '1.3333').
var formatNumber = function(n) { return n.toFixed(4).replace(/\.?0+$/, ''); };
var is_graded = ctx.graded && ctx.weighted_max_score > 0;
var progress_template;
if (ctx.grade !== null && ctx.weighted_max_score > 0) {
if (is_graded) {
progress_template = ngettext(
// Translators: {earned} is the number of points earned. {possible} is the total number of points (examples: 0/1, 1/1, 2/3, 5/10). The total number of points will always be at least 1. We pluralize based on the total number of points (example: 0/1 point; 1/2 points).
'{earned}/{possible} point (graded)',
'{earned}/{possible} points (graded)',
ctx.weighted_max_score
);
} else {
progress_template = ngettext(
// Translators: {earned} is the number of points earned. {possible} is the total number of points (examples: 0/1, 1/1, 2/3, 5/10). The total number of points will always be at least 1. We pluralize based on the total number of points (example: 0/1 point; 1/2 points).
'{earned}/{possible} point (ungraded)',
'{earned}/{possible} points (ungraded)',
ctx.weighted_max_score
);
}
progress_template = progress_template.replace('{earned}', formatNumber(ctx.grade));
} else {
if (is_graded) {
progress_template = ngettext(
// Translators: {possible} is the number of points possible (examples: 1, 3, 10).
'{possible} point possible (graded)',
'{possible} points possible (graded)',
ctx.weighted_max_score
);
} else {
progress_template = ngettext(
// Translators: {possible} is the number of points possible (examples: 1, 3, 10).
'{possible} point possible (ungraded)',
'{possible} points possible (ungraded)',
ctx.weighted_max_score
);
}
}
var progress_text = progress_template.replace('{possible}', formatNumber(ctx.weighted_max_score));
return h('div.problem-progress', {
id: configuration.url_name + '-problem-progress',
attributes: {role: 'status'}
}, progress_text);
};
var mainTemplate = function(ctx) {
var main_element_properties = {attributes: {role: 'group'}};
var problemProgress = progressTemplate(ctx);
var problemTitle = null;
if (ctx.show_title) {
var problem_title_id = configuration.url_name + '-problem-title';
problemTitle = h('h3.hd.hd-3.problem-header', {
id: problem_title_id,
innerHTML: gettext(ctx.title_html),
attributes: {'aria-describedby': problemProgress.properties.id}
});
main_element_properties.attributes['arial-labelledby'] = problem_title_id;
} else {
main_element_properties.attributes['aria-label'] = gettext('Drag and Drop Problem');
}
var problemHeader = ctx.show_problem_header ? h('h4.title1', gettext('Problem')) : null;
// Render only items in the bank here, including placeholders. Placed
// items will be rendered by zoneTemplate.
var items_in_bank = [];
var items_dragged = [];
var items_placed = [];
ctx.items.forEach(function(item) {
if (item.is_dragged) {
items_dragged.push(item);
// Dragged items require a placeholder in the bank.
// In assessment mode, already placed items can be dragged.
if (item.is_placed) {
items_placed.push(item)
} else {
items_in_bank.push(item);
}
} else if (item.is_placed) {
items_placed.push(item);
} else {
items_in_bank.push(item);
}
});
var item_bank_properties = {
attributes: {
'role': 'group',
'aria-label': gettext('Item Bank')
}
};
if (ctx.item_bank_focusable) {
item_bank_properties.attributes['tabindex'] = 0;
item_bank_properties.attributes['dropzone'] = 'move';
item_bank_properties.attributes['aria-dropeffect'] = 'move';
item_bank_properties.attributes['role'] = 'button';
}
// Render items in the bank. If the item is currently being dragged, it should be
// rendered as a placeholder. All already placed items should also be rendered as
// placedholders (as the last content in the bank) to maintain original bank dimensions.
var bank_children = [];
items_in_bank.forEach(function(item) {
if (item.is_dragged) {
bank_children.push(itemPlaceholderTemplate(item, ctx));
} else {
bank_children.push(itemTemplate(item, ctx));
}
});
bank_children = bank_children.concat(renderCollection(itemPlaceholderTemplate, items_placed, ctx));
var drag_container_style = {};
var target_img_style = {};
// If drag_container_max_width is null, we are going to measure the container width after this render.
// To be able to accurately measure the natural container width, we have to set max-width of the target
// image to 100%, so that it doesn't expand the container.
if (ctx.drag_container_max_width === null) {
target_img_style.maxWidth = '100%';
item_bank_properties.style = {display: 'none'};
} else {
drag_container_style.maxWidth = ctx.drag_container_max_width + 'px';
}
return (
h('div.themed-xblock.xblock--drag-and-drop', main_element_properties, [
h('object.resize-detector', {
attributes: {type: 'text/html', tabindex: -1, data: 'about:blank'}
}),
gettext(problemTitle),
gettext(problemProgress),
h('div', [forwardKeyboardHelpButtonTemplate(ctx)]),
h('div.problem', [
problemHeader,
h('p', {innerHTML: ctx.problem_html}),
h('div.drag-container', {style: drag_container_style}, [
h('div.item-bank', item_bank_properties, bank_children),
h('div.target', {attributes: {'role': 'group', 'arial-label': gettext('Drop Targets')}}, [
itemFeedbackPopupTemplate(ctx),
h('div.target-img-wrapper', [
h('img.target-img', {
src: ctx.target_img_src,
alt: ctx.target_img_description,
style: target_img_style
}),
renderCollection(zoneTemplate, ctx.zones, ctx)
]),
]),
h('div.dragged-items', renderCollection(itemTemplate, items_dragged, ctx)),
]),
explanationTemplate(ctx),
h('div.action', [
(ctx.show_submit_answer ? submitAnswerTemplate(ctx) : null),
sidebarTemplate(ctx)
]),
keyboardHelpPopupTemplate(ctx),
feedbackTemplate(ctx),
h('div.sr.reader-feedback-area', {
attributes: {'aria-live': 'polite', 'aria-atomic': true},
innerHTML: ctx.screen_reader_messages
}),
]),
])
);
};
return mainTemplate;
}
function DragAndDropBlock(runtime, element, configuration) {
"use strict";
DragAndDropBlock.STANDARD_MODE = 'standard';
DragAndDropBlock.ASSESSMENT_MODE = 'assessment';
DragAndDropBlock.FEEDBACK_CLASS_ZONE_LIMIT = 'limit';
var Selector = {
popup_box: '.popup',
close_button: '.popup .close-feedback-popup-button'
};
var gettext;
if ('DragAndDropI18N' in window) {
// Use DnDv2's local translations
gettext = window.DragAndDropI18N.gettext;
} else if ('gettext' in window) {
// Use edxapp's global translations
gettext = window.gettext;
}
if (typeof gettext == "undefined") {
// No translations -- used by test environment
gettext = function(string) { return string; };
}
var renderView = DragAndDropTemplates(configuration);
var $element = $(element);
// root: root node managed by the virtual DOM
var $root = $element.find('.xblock--drag-and-drop');
var root = $root[0];
var state = undefined;
var bgImgNaturalWidth = undefined; // pixel width of the background image (when not scaled)
var containerMaxWidth = null; // measured and set after first render
var fixedHeaderHeight = 0; // measured in checkForFixedHeader
var __vdom = virtualDom.h(); // blank virtual DOM
// Event string size limit.
var MAX_LENGTH = 255;
var DEFAULT_ZONE_ALIGN = 'center';
// Number of miliseconds the user has to keep their finger on the item
// without moving for drag to begin.
// This allows user to scroll the container without accidentally dragging the items.
var TOUCH_DRAG_DELAY = 250;
// Keyboard accessibility
var ESC = 27;
var RET = 13;
var SPC = 32;
var TAB = 9;
var M = 77;
var $selectedItem;
var init = function() {
// Load the current user state, and load the image, then render the block.
// We load the user state via AJAX rather than passing it in statically (like we do with
// configuration) due to how the LMS handles unit tabs. If you click on a unit with this
// block, make changes, click on the tab for another unit, then click back, this block
// would re-initialize with the old state. To avoid that, we always fetch the state
// using AJAX during initialization.
$.when(
$.ajax(runtime.handlerUrl(element, 'student_view_user_state'), {dataType: 'json'}),
loadBackgroundImage()
).done(function(stateResult, bgImg){
// Render problem
configuration.zones.forEach(function (zone) {
computeZoneDimension(zone, bgImg.width, bgImg.height);
});
state = stateResult[0]; // stateResult is an array of [data, statusText, jqXHR]
migrateConfiguration(bgImg.width);
migrateState();
markItemZoneAlign();
bgImgNaturalWidth = bgImg.width;
// Set up event handlers:
$element.on('click', '.item-feedback-popup .close-feedback-popup-button', closePopupEventHandler);
$element.on('keydown', '.item-feedback-popup .close-feedback-popup-button', closePopupKeydownHandler);
$element.on('keyup', '.item-feedback-popup .close-feedback-popup-button', preventFauxPopupCloseButtonClick);
$element.on('click', '.xblock--drag-and-drop .submit-attempt-container .submit', doAttempt);
$element.on('click', '.keyboard-help-button', showKeyboardHelp);
$element.on('keydown', '.keyboard-help-button', function(evt) {
runOnKey(evt, RET, showKeyboardHelp);
});
$element.on('click', '.xblock--drag-and-drop .problem-action-button-wrapper .reset', resetProblem);
$element.on('keydown', '.xblock--drag-and-drop .problem-action-button-wrapper .reset', function(evt) {
runOnKey(evt, RET, resetProblem);
});
$element.on('click', '.xblock--drag-and-drop .problem-action-button-wrapper .show', showAnswer);
$element.on('keydown', '.xblock--drag-and-drop .problem-action-button-wrapper .show', function(evt) {
runOnKey(evt, RET, showAnswer);
});
// We need to register both mousedown and click event handlers because in some browsers the blur
// event is emitted right after mousedown, hiding our button and preventing the click event from
// being emitted.
// We still need the click handler to catch keydown events (other than RET which is handled below),
// since in some browser/OS combinations some other keyboard button presses (for example space bar)
// are also treated as clicks,
$element.on('mousedown click', '.go-to-beginning-button', onGoToBeginningButtonClick);
$element.on('keydown', '.go-to-beginning-button', function(evt) {
runOnKey(evt, RET, onGoToBeginningButtonClick);
});
// Go to Beginning button should only be visible when it has focus.
$element.on('focus', '.go-to-beginning-button', showGoToBeginningButton);
$element.on('blur', '.go-to-beginning-button', hideGoToBeginningButton);
// For the next one, we need to use addEventListener with useCapture 'true' in order
// to watch for load events on any child element, since load events do not bubble.
$element.get(0).addEventListener('load', webkitFix, true);
// Whenever the container div resizes, re-render to take new available width into account.
$element.get(0).addEventListener('load', bindContainerResize, true);
// Re-render when window size changes.
$(window).on('resize', measureWidthAndRender);
// Remove the spinner and create a blank slate for virtualDom to take over.
$root.empty();
measureWidthAndRender();
checkForFixedHeader();
initDraggable();
initDroppable();
// Indicate that problem is done loading
publishEvent({event_type: 'edx.drag_and_drop_v2.loaded'});
}).fail(function() {
$root.text(gettext("An error occurred. Unable to load drag and drop problem."));
});
};
// Handler to react when the size of this XBlock changes:
var last_width = 0;
var last_height = 0;
var raf_id = null;
var handleResizeEvent = function(watchedObject) {
cancelAnimationFrame(raf_id);
raf_id = requestAnimationFrame(function() {
var new_width = watchedObject.width();
var new_height = watchedObject.height();
if (last_width !== new_width || last_height !== new_height) {
last_width = new_width;
last_height = new_height;
measureWidthAndRender();
}
});
}
// Listens to the 'resize' event of the object element, which is absolutely positioned
// and fit to the edges of the container, so that its size always equals the container size.
// This hack is needed because not all browsers support native 'resize' events on arbitrary
// DOM elements.
var bindContainerResize = function(evt) {
var object = evt.target;
var $object = $(object);
if ($object.is('.resize-detector')) {
if (object.contentDocument) {
object.contentDocument.defaultView.addEventListener('resize', handleResizeEvent.bind(null, $object));
} else {
// In an IFrame, we might not have permission to access object.contentDocument
// so just watch for window resize events instead, which should be good enough.
// It would just miss the case where surrounding HTML changes affect this element's
// size, but that should be rare in an IFrame.
window.addEventListener('resize', handleResizeEvent.bind(null, $(window)));
}
}
};
var measureWidthAndRender = function() {
// First set containerMaxWidth to null to hide the container.
containerMaxWidth = null;
// Render with container hidden to be able to measure max available width.
applyState();
// Mesure available width.
containerMaxWidth = $root.width();
// Re-render now that correct max-width is known.
applyState();
};
var checkForFixedHeader = function() {
// There might be a fixed header covering the upper part of the screen,
// which needs to be taken into account when scrolling while dragging.
var windowHeight = $(window).height();
var topElement = $(document.elementFromPoint(0, 0));
if (topElement) {
var topElementParents = topElement.parents();
for (var i = 0; i < topElementParents.length; i++) {
var parent = $(topElementParents[i]);
if (parent.css('position') === 'fixed') {
fixedHeaderHeight = parent.height();
break;
}
}
}
}
var runOnKey = function(evt, key, handler) {
if (evt.which === key) {
handler(evt);
}
};
var keyboardEventDispatcher = function(evt, focusId) {
if (evt.which === TAB) {
trapFocus(evt);
} else if (evt.which === ESC) {
hideKeyboardHelp(evt, focusId);
}
};
var trapFocus = function(evt) {
if (evt.which === TAB) {
evt.preventDefault();
focusModalButton();
}
};
var truncateField = function(data, fieldName){
if (data[fieldName].length > MAX_LENGTH) {
data[fieldName] = data[fieldName].substring(0, MAX_LENGTH);
data['truncated'] = true;
} else {
data['truncated'] = false;
}
};
var onGoToBeginningButtonClick = function(evt) {
evt.preventDefault();
// In theory the blur event handler should hide the button,