forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
javascript-static.js
1909 lines (1741 loc) · 66.9 KB
/
javascript-static.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
// Miscellaneous core Javascript functions for Moodle
// Global M object is initilised in inline javascript
/**
* Add module to list of available modules that can be loaded from YUI.
* @param {Array} modules
*/
M.yui.add_module = function(modules) {
for (var modname in modules) {
YUI_config.modules[modname] = modules[modname];
}
};
/**
* The gallery version to use when loading YUI modules from the gallery.
* Will be changed every time when using local galleries.
*/
M.yui.galleryversion = '2010.04.21-21-51';
/**
* Various utility functions
*/
M.util = M.util || {};
/**
* Language strings - initialised from page footer.
*/
M.str = M.str || {};
/**
* Returns url for images.
* @param {String} imagename
* @param {String} component
* @return {String}
*/
M.util.image_url = function(imagename, component) {
if (!component || component == '' || component == 'moodle' || component == 'core') {
component = 'core';
}
var url = M.cfg.wwwroot + '/theme/image.php';
if (M.cfg.themerev > 0 && M.cfg.slasharguments == 1) {
if (!M.cfg.svgicons) {
url += '/_s';
}
url += '/' + M.cfg.theme + '/' + component + '/' + M.cfg.themerev + '/' + imagename;
} else {
url += '?theme=' + M.cfg.theme + '&component=' + component + '&rev=' + M.cfg.themerev + '&image=' + imagename;
if (!M.cfg.svgicons) {
url += '&svg=0';
}
}
return url;
};
M.util.in_array = function(item, array){
for( var i = 0; i<array.length; i++){
if(item==array[i]){
return true;
}
}
return false;
};
/**
* Init a collapsible region, see print_collapsible_region in weblib.php
* @param {YUI} Y YUI3 instance with all libraries loaded
* @param {String} id the HTML id for the div.
* @param {String} userpref the user preference that records the state of this box. false if none.
* @param {String} strtooltip
*/
M.util.init_collapsible_region = function(Y, id, userpref, strtooltip) {
Y.use('anim', function(Y) {
new M.util.CollapsibleRegion(Y, id, userpref, strtooltip);
});
};
/**
* Object to handle a collapsible region : instantiate and forget styled object
*
* @class
* @constructor
* @param {YUI} Y YUI3 instance with all libraries loaded
* @param {String} id The HTML id for the div.
* @param {String} userpref The user preference that records the state of this box. false if none.
* @param {String} strtooltip
*/
M.util.CollapsibleRegion = function(Y, id, userpref, strtooltip) {
// Record the pref name
this.userpref = userpref;
// Find the divs in the document.
this.div = Y.one('#'+id);
// Get the caption for the collapsible region
var caption = this.div.one('#'+id + '_caption');
// Create a link
var a = Y.Node.create('<a href="#"></a>');
a.setAttribute('title', strtooltip);
// Get all the nodes from caption, remove them and append them to <a>
while (caption.hasChildNodes()) {
child = caption.get('firstChild');
child.remove();
a.append(child);
}
caption.append(a);
// Get the height of the div at this point before we shrink it if required
var height = this.div.get('offsetHeight');
var collapsedimage = 't/collapsed'; // ltr mode
if (right_to_left()) {
collapsedimage = 't/collapsed_rtl';
} else {
collapsedimage = 't/collapsed';
}
if (this.div.hasClass('collapsed')) {
// Add the correct image and record the YUI node created in the process
this.icon = Y.Node.create('<img src="'+M.util.image_url(collapsedimage, 'moodle')+'" alt="" />');
// Shrink the div as it is collapsed by default
this.div.setStyle('height', caption.get('offsetHeight')+'px');
} else {
// Add the correct image and record the YUI node created in the process
this.icon = Y.Node.create('<img src="'+M.util.image_url('t/expanded', 'moodle')+'" alt="" />');
}
a.append(this.icon);
// Create the animation.
var animation = new Y.Anim({
node: this.div,
duration: 0.3,
easing: Y.Easing.easeBoth,
to: {height:caption.get('offsetHeight')},
from: {height:height}
});
// Handler for the animation finishing.
animation.on('end', function() {
this.div.toggleClass('collapsed');
var collapsedimage = 't/collapsed'; // ltr mode
if (right_to_left()) {
collapsedimage = 't/collapsed_rtl';
} else {
collapsedimage = 't/collapsed';
}
if (this.div.hasClass('collapsed')) {
this.icon.set('src', M.util.image_url(collapsedimage, 'moodle'));
} else {
this.icon.set('src', M.util.image_url('t/expanded', 'moodle'));
}
}, this);
// Hook up the event handler.
a.on('click', function(e, animation) {
e.preventDefault();
// Animate to the appropriate size.
if (animation.get('running')) {
animation.stop();
}
animation.set('reverse', this.div.hasClass('collapsed'));
// Update the user preference.
if (this.userpref) {
M.util.set_user_preference(this.userpref, !this.div.hasClass('collapsed'));
}
animation.run();
}, this, animation);
};
/**
* The user preference that stores the state of this box.
* @property userpref
* @type String
*/
M.util.CollapsibleRegion.prototype.userpref = null;
/**
* The key divs that make up this
* @property div
* @type Y.Node
*/
M.util.CollapsibleRegion.prototype.div = null;
/**
* The key divs that make up this
* @property icon
* @type Y.Node
*/
M.util.CollapsibleRegion.prototype.icon = null;
/**
* Makes a best effort to connect back to Moodle to update a user preference,
* however, there is no mechanism for finding out if the update succeeded.
*
* Before you can use this function in your JavsScript, you must have called
* user_preference_allow_ajax_update from moodlelib.php to tell Moodle that
* the udpate is allowed, and how to safely clean and submitted values.
*
* @param String name the name of the setting to udpate.
* @param String the value to set it to.
*/
M.util.set_user_preference = function(name, value) {
YUI().use('io', function(Y) {
var url = M.cfg.wwwroot + '/lib/ajax/setuserpref.php?sesskey=' +
M.cfg.sesskey + '&pref=' + encodeURI(name) + '&value=' + encodeURI(value);
// If we are a developer, ensure that failures are reported.
var cfg = {
method: 'get',
on: {}
};
if (M.cfg.developerdebug) {
cfg.on.failure = function(id, o, args) {
alert("Error updating user preference '" + name + "' using ajax. Clicking this link will repeat the Ajax call that failed so you can see the error: ");
}
}
// Make the request.
Y.io(url, cfg);
});
};
/**
* Prints a confirmation dialog in the style of DOM.confirm().
*
* @method show_confirm_dialog
* @param {EventFacade} e
* @param {Object} args
* @param {String} args.message The question to ask the user
* @param {Function} [args.callback] A callback to apply on confirmation.
* @param {Object} [args.scope] The scope to use when calling the callback.
* @param {Object} [args.callbackargs] Any arguments to pass to the callback.
* @param {String} [args.cancellabel] The label to use on the cancel button.
* @param {String} [args.continuelabel] The label to use on the continue button.
*/
M.util.show_confirm_dialog = function(e, args) {
var target = e.target;
if (e.preventDefault) {
e.preventDefault();
}
YUI().use('moodle-core-notification-confirm', function(Y) {
var confirmationDialogue = new M.core.confirm({
width: '300px',
center: true,
modal: true,
visible: false,
draggable: false,
title: M.util.get_string('confirmation', 'admin'),
noLabel: M.util.get_string('cancel', 'moodle'),
question: args.message
});
// The dialogue was submitted with a positive value indication.
confirmationDialogue.on('complete-yes', function(e) {
// Handle any callbacks.
if (args.callback) {
if (!Y.Lang.isFunction(args.callback)) {
Y.log('Callbacks to show_confirm_dialog must now be functions. Please update your code to pass in a function instead.',
'warn', 'M.util.show_confirm_dialog');
return;
}
var scope = e.target;
if (Y.Lang.isObject(args.scope)) {
scope = args.scope;
}
var callbackargs = args.callbackargs || [];
args.callback.apply(scope, callbackargs);
return;
}
var targetancestor = null,
targetform = null;
if (target.test('a')) {
window.location = target.get('href');
} else if ((targetancestor = target.ancestor('a')) !== null) {
window.location = targetancestor.get('href');
} else if (target.test('input')) {
targetform = target.ancestor('form', true);
if (!targetform) {
return;
}
if (target.get('name') && target.get('value')) {
targetform.append('<input type="hidden" name="' + target.get('name') +
'" value="' + target.get('value') + '">');
}
targetform.submit();
} else if (target.test('form')) {
target.submit();
} else {
Y.log("Element of type " + target.get('tagName') +
" is not supported by the M.util.show_confirm_dialog function. Use A, INPUT, or FORM",
'warn', 'javascript-static');
}
}, this);
if (args.cancellabel) {
confirmationDialogue.set('noLabel', args.cancellabel);
}
if (args.continuelabel) {
confirmationDialogue.set('yesLabel', args.continuelabel);
}
confirmationDialogue.render()
.show();
});
};
/** Useful for full embedding of various stuff */
M.util.init_maximised_embed = function(Y, id) {
var obj = Y.one('#'+id);
if (!obj) {
return;
}
var get_htmlelement_size = function(el, prop) {
if (Y.Lang.isString(el)) {
el = Y.one('#' + el);
}
// Ensure element exists.
if (el) {
var val = el.getStyle(prop);
if (val == 'auto') {
val = el.getComputedStyle(prop);
}
val = parseInt(val);
if (isNaN(val)) {
return 0;
}
return val;
} else {
return 0;
}
};
var resize_object = function() {
obj.setStyle('width', '0px');
obj.setStyle('height', '0px');
var newwidth = get_htmlelement_size('maincontent', 'width') - 35;
if (newwidth > 500) {
obj.setStyle('width', newwidth + 'px');
} else {
obj.setStyle('width', '500px');
}
var headerheight = get_htmlelement_size('page-header', 'height');
var footerheight = get_htmlelement_size('page-footer', 'height');
var newheight = parseInt(Y.one('body').get('docHeight')) - footerheight - headerheight - 100;
if (newheight < 400) {
newheight = 400;
}
obj.setStyle('height', newheight+'px');
};
resize_object();
// fix layout if window resized too
window.onresize = function() {
resize_object();
};
};
/**
* Breaks out all links to the top frame - used in frametop page layout.
*/
M.util.init_frametop = function(Y) {
Y.all('a').each(function(node) {
node.set('target', '_top');
});
Y.all('form').each(function(node) {
node.set('target', '_top');
});
};
/**
* Finds all nodes that match the given CSS selector and attaches events to them
* so that they toggle a given classname when clicked.
*
* @param {YUI} Y
* @param {string} id An id containing elements to target
* @param {string} cssselector A selector to use to find targets
* @param {string} toggleclassname A classname to toggle
*/
M.util.init_toggle_class_on_click = function(Y, id, cssselector, toggleclassname, togglecssselector) {
if (togglecssselector == '') {
togglecssselector = cssselector;
}
var node = Y.one('#'+id);
node.all(cssselector).each(function(n){
n.on('click', function(e){
e.stopPropagation();
if (e.target.test(cssselector) && !e.target.test('a') && !e.target.test('img')) {
if (this.test(togglecssselector)) {
this.toggleClass(toggleclassname);
} else {
this.ancestor(togglecssselector).toggleClass(toggleclassname);
}
}
}, n);
});
// Attach this click event to the node rather than all selectors... will be much better
// for performance
node.on('click', function(e){
if (e.target.hasClass('addtoall')) {
this.all(togglecssselector).addClass(toggleclassname);
} else if (e.target.hasClass('removefromall')) {
this.all(togglecssselector+'.'+toggleclassname).removeClass(toggleclassname);
}
}, node);
};
/**
* Initialises a colour picker
*
* Designed to be used with admin_setting_configcolourpicker although could be used
* anywhere, just give a text input an id and insert a div with the class admin_colourpicker
* above or below the input (must have the same parent) and then call this with the
* id.
*
* This code was mostly taken from my [Sam Hemelryk] css theme tool available in
* contrib/blocks. For better docs refer to that.
*
* @param {YUI} Y
* @param {int} id
* @param {object} previewconf
*/
M.util.init_colour_picker = function(Y, id, previewconf) {
/**
* We need node and event-mouseenter
*/
Y.use('node', 'event-mouseenter', function(){
/**
* The colour picker object
*/
var colourpicker = {
box : null,
input : null,
image : null,
preview : null,
current : null,
eventClick : null,
eventMouseEnter : null,
eventMouseLeave : null,
eventMouseMove : null,
width : 300,
height : 100,
factor : 5,
/**
* Initalises the colour picker by putting everything together and wiring the events
*/
init : function() {
this.input = Y.one('#'+id);
this.box = this.input.ancestor().one('.admin_colourpicker');
this.image = Y.Node.create('<img alt="" class="colourdialogue" />');
this.image.setAttribute('src', M.util.image_url('i/colourpicker', 'moodle'));
this.preview = Y.Node.create('<div class="previewcolour"></div>');
this.preview.setStyle('width', this.height/2).setStyle('height', this.height/2).setStyle('backgroundColor', this.input.get('value'));
this.current = Y.Node.create('<div class="currentcolour"></div>');
this.current.setStyle('width', this.height/2).setStyle('height', this.height/2 -1).setStyle('backgroundColor', this.input.get('value'));
this.box.setContent('').append(this.image).append(this.preview).append(this.current);
if (typeof(previewconf) === 'object' && previewconf !== null) {
Y.one('#'+id+'_preview').on('click', function(e){
if (Y.Lang.isString(previewconf.selector)) {
Y.all(previewconf.selector).setStyle(previewconf.style, this.input.get('value'));
} else {
for (var i in previewconf.selector) {
Y.all(previewconf.selector[i]).setStyle(previewconf.style, this.input.get('value'));
}
}
}, this);
}
this.eventClick = this.image.on('click', this.pickColour, this);
this.eventMouseEnter = Y.on('mouseenter', this.startFollow, this.image, this);
},
/**
* Starts to follow the mouse once it enter the image
*/
startFollow : function(e) {
this.eventMouseEnter.detach();
this.eventMouseLeave = Y.on('mouseleave', this.endFollow, this.image, this);
this.eventMouseMove = this.image.on('mousemove', function(e){
this.preview.setStyle('backgroundColor', this.determineColour(e));
}, this);
},
/**
* Stops following the mouse
*/
endFollow : function(e) {
this.eventMouseMove.detach();
this.eventMouseLeave.detach();
this.eventMouseEnter = Y.on('mouseenter', this.startFollow, this.image, this);
},
/**
* Picks the colour the was clicked on
*/
pickColour : function(e) {
var colour = this.determineColour(e);
this.input.set('value', colour);
this.current.setStyle('backgroundColor', colour);
},
/**
* Calculates the colour fromthe given co-ordinates
*/
determineColour : function(e) {
var eventx = Math.floor(e.pageX-e.target.getX());
var eventy = Math.floor(e.pageY-e.target.getY());
var imagewidth = this.width;
var imageheight = this.height;
var factor = this.factor;
var colour = [255,0,0];
var matrices = [
[ 0, 1, 0],
[ -1, 0, 0],
[ 0, 0, 1],
[ 0, -1, 0],
[ 1, 0, 0],
[ 0, 0, -1]
];
var matrixcount = matrices.length;
var limit = Math.round(imagewidth/matrixcount);
var heightbreak = Math.round(imageheight/2);
for (var x = 0; x < imagewidth; x++) {
var divisor = Math.floor(x / limit);
var matrix = matrices[divisor];
colour[0] += matrix[0]*factor;
colour[1] += matrix[1]*factor;
colour[2] += matrix[2]*factor;
if (eventx==x) {
break;
}
}
var pixel = [colour[0], colour[1], colour[2]];
if (eventy < heightbreak) {
pixel[0] += Math.floor(((255-pixel[0])/heightbreak) * (heightbreak - eventy));
pixel[1] += Math.floor(((255-pixel[1])/heightbreak) * (heightbreak - eventy));
pixel[2] += Math.floor(((255-pixel[2])/heightbreak) * (heightbreak - eventy));
} else if (eventy > heightbreak) {
pixel[0] = Math.floor((imageheight-eventy)*(pixel[0]/heightbreak));
pixel[1] = Math.floor((imageheight-eventy)*(pixel[1]/heightbreak));
pixel[2] = Math.floor((imageheight-eventy)*(pixel[2]/heightbreak));
}
return this.convert_rgb_to_hex(pixel);
},
/**
* Converts an RGB value to Hex
*/
convert_rgb_to_hex : function(rgb) {
var hex = '#';
var hexchars = "0123456789ABCDEF";
for (var i=0; i<3; i++) {
var number = Math.abs(rgb[i]);
if (number == 0 || isNaN(number)) {
hex += '00';
} else {
hex += hexchars.charAt((number-number%16)/16)+hexchars.charAt(number%16);
}
}
return hex;
}
};
/**
* Initialise the colour picker :) Hoorah
*/
colourpicker.init();
});
};
M.util.init_block_hider = function(Y, config) {
Y.use('base', 'node', function(Y) {
M.util.block_hider = M.util.block_hider || (function(){
var blockhider = function() {
blockhider.superclass.constructor.apply(this, arguments);
};
blockhider.prototype = {
initializer : function(config) {
this.set('block', '#'+this.get('id'));
var b = this.get('block'),
t = b.one('.title'),
a = null;
if (t && (a = t.one('.block_action'))) {
var hide = Y.Node.create('<img class="block-hider-hide" tabindex="0" alt="'+config.tooltipVisible+'" title="'+config.tooltipVisible+'" />');
hide.setAttribute('src', this.get('iconVisible')).on('click', this.updateState, this, true);
hide.on('keypress', this.updateStateKey, this, true);
var show = Y.Node.create('<img class="block-hider-show" tabindex="0" alt="'+config.tooltipHidden+'" title="'+config.tooltipHidden+'" />');
show.setAttribute('src', this.get('iconHidden')).on('click', this.updateState, this, false);
show.on('keypress', this.updateStateKey, this, false);
a.insert(show, 0).insert(hide, 0);
}
},
updateState : function(e, hide) {
M.util.set_user_preference(this.get('preference'), hide);
if (hide) {
this.get('block').addClass('hidden');
} else {
this.get('block').removeClass('hidden');
}
},
updateStateKey : function(e, hide) {
if (e.keyCode == 13) { //allow hide/show via enter key
this.updateState(this, hide);
}
}
};
Y.extend(blockhider, Y.Base, blockhider.prototype, {
NAME : 'blockhider',
ATTRS : {
id : {},
preference : {},
iconVisible : {
value : M.util.image_url('t/switch_minus', 'moodle')
},
iconHidden : {
value : M.util.image_url('t/switch_plus', 'moodle')
},
block : {
setter : function(node) {
return Y.one(node);
}
}
}
});
return blockhider;
})();
new M.util.block_hider(config);
});
};
/**
* @var pending_js - The keys are the list of all pending js actions.
* @type Object
*/
M.util.pending_js = [];
M.util.complete_js = [];
/**
* Register any long running javascript code with a unique identifier.
* Should be followed with a call to js_complete with a matching
* idenfitier when the code is complete. May also be called with no arguments
* to test if there is any js calls pending. This is relied on by behat so that
* it can wait for all pending updates before interacting with a page.
* @param String uniqid - optional, if provided,
* registers this identifier until js_complete is called.
* @return boolean - True if there is any pending js.
*/
M.util.js_pending = function(uniqid) {
if (uniqid !== false) {
M.util.pending_js.push(uniqid);
}
return M.util.pending_js.length;
};
// Start this asap.
M.util.js_pending('init');
/**
* Register listeners for Y.io start/end so we can wait for them in behat.
*/
YUI.add('moodle-core-io', function(Y) {
Y.on('io:start', function(id) {
M.util.js_pending('io:' + id);
});
Y.on('io:end', function(id) {
M.util.js_complete('io:' + id);
});
}, '@VERSION@', {
condition: {
trigger: 'io-base',
when: 'after'
}
});
/**
* Unregister any long running javascript code by unique identifier.
* This function should form a matching pair with js_pending
*
* @param String uniqid - required, unregisters this identifier
* @return boolean - True if there is any pending js.
*/
M.util.js_complete = function(uniqid) {
// Use the Y.Array.indexOf instead of the native because some older browsers do not support
// the native function. Y.Array polyfills the native function if it does not exist.
var index = Y.Array.indexOf(M.util.pending_js, uniqid);
if (index >= 0) {
M.util.complete_js.push(M.util.pending_js.splice(index, 1));
}
return M.util.pending_js.length;
};
/**
* Returns a string registered in advance for usage in JavaScript
*
* If you do not pass the third parameter, the function will just return
* the corresponding value from the M.str object. If the third parameter is
* provided, the function performs {$a} placeholder substitution in the
* same way as PHP get_string() in Moodle does.
*
* @param {String} identifier string identifier
* @param {String} component the component providing the string
* @param {Object|String} a optional variable to populate placeholder with
*/
M.util.get_string = function(identifier, component, a) {
var stringvalue;
if (M.cfg.developerdebug) {
// creating new instance if YUI is not optimal but it seems to be better way then
// require the instance via the function API - note that it is used in rare cases
// for debugging only anyway
// To ensure we don't kill browser performance if hundreds of get_string requests
// are made we cache the instance we generate within the M.util namespace.
// We don't publicly define the variable so that it doesn't get abused.
if (typeof M.util.get_string_yui_instance === 'undefined') {
M.util.get_string_yui_instance = new YUI({ debug : true });
}
var Y = M.util.get_string_yui_instance;
}
if (!M.str.hasOwnProperty(component) || !M.str[component].hasOwnProperty(identifier)) {
stringvalue = '[[' + identifier + ',' + component + ']]';
if (M.cfg.developerdebug) {
Y.log('undefined string ' + stringvalue, 'warn', 'M.util.get_string');
}
return stringvalue;
}
stringvalue = M.str[component][identifier];
if (typeof a == 'undefined') {
// no placeholder substitution requested
return stringvalue;
}
if (typeof a == 'number' || typeof a == 'string') {
// replace all occurrences of {$a} with the placeholder value
stringvalue = stringvalue.replace(/\{\$a\}/g, a);
return stringvalue;
}
if (typeof a == 'object') {
// replace {$a->key} placeholders
for (var key in a) {
if (typeof a[key] != 'number' && typeof a[key] != 'string') {
if (M.cfg.developerdebug) {
Y.log('invalid value type for $a->' + key, 'warn', 'M.util.get_string');
}
continue;
}
var search = '{$a->' + key + '}';
search = search.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
search = new RegExp(search, 'g');
stringvalue = stringvalue.replace(search, a[key]);
}
return stringvalue;
}
if (M.cfg.developerdebug) {
Y.log('incorrect placeholder type', 'warn', 'M.util.get_string');
}
return stringvalue;
};
/**
* Set focus on username or password field of the login form
*/
M.util.focus_login_form = function(Y) {
var username = Y.one('#username');
var password = Y.one('#password');
if (username == null || password == null) {
// something is wrong here
return;
}
var curElement = document.activeElement
if (curElement == 'undefined') {
// legacy browser - skip refocus protection
} else if (curElement.tagName == 'INPUT') {
// user was probably faster to focus something, do not mess with focus
return;
}
if (username.get('value') == '') {
username.focus();
} else {
password.focus();
}
}
/**
* Set focus on login error message
*/
M.util.focus_login_error = function(Y) {
var errorlog = Y.one('#loginerrormessage');
if (errorlog) {
errorlog.focus();
}
}
/**
* Adds lightbox hidden element that covers the whole node.
*
* @param {YUI} Y
* @param {Node} the node lightbox should be added to
* @retun {Node} created lightbox node
*/
M.util.add_lightbox = function(Y, node) {
var WAITICON = {'pix':"i/loading_small",'component':'moodle'};
// Check if lightbox is already there
if (node.one('.lightbox')) {
return node.one('.lightbox');
}
node.setStyle('position', 'relative');
var waiticon = Y.Node.create('<img />')
.setAttrs({
'src' : M.util.image_url(WAITICON.pix, WAITICON.component)
})
.setStyles({
'position' : 'relative',
'top' : '50%'
});
var lightbox = Y.Node.create('<div></div>')
.setStyles({
'opacity' : '.75',
'position' : 'absolute',
'width' : '100%',
'height' : '100%',
'top' : 0,
'left' : 0,
'backgroundColor' : 'white',
'textAlign' : 'center'
})
.setAttribute('class', 'lightbox')
.hide();
lightbox.appendChild(waiticon);
node.append(lightbox);
return lightbox;
}
/**
* Appends a hidden spinner element to the specified node.
*
* @param {YUI} Y
* @param {Node} the node the spinner should be added to
* @return {Node} created spinner node
*/
M.util.add_spinner = function(Y, node) {
var WAITICON = {'pix':"i/loading_small",'component':'moodle'};
// Check if spinner is already there
if (node.one('.spinner')) {
return node.one('.spinner');
}
var spinner = Y.Node.create('<img />')
.setAttribute('src', M.util.image_url(WAITICON.pix, WAITICON.component))
.addClass('spinner')
.addClass('iconsmall')
.hide();
node.append(spinner);
return spinner;
}
//=== old legacy JS code, hopefully to be replaced soon by M.xx.yy and YUI3 code ===
function checkall() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].disabled || inputs[i].readOnly) {
continue;
}
inputs[i].checked = true;
}
}
}
function checknone() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].disabled || inputs[i].readOnly) {
continue;
}
inputs[i].checked = false;
}
}
}
/**
* Either check, or uncheck, all checkboxes inside the element with id is
* @param id the id of the container
* @param checked the new state, either '' or 'checked'.
*/
function select_all_in_element_with_id(id, checked) {
var container = document.getElementById(id);
if (!container) {
return;
}
var inputs = container.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'checkbox' || inputs[i].type == 'radio') {
inputs[i].checked = checked;
}
}
}
function select_all_in(elTagName, elClass, elId) {
var inputs = document.getElementsByTagName('input');
inputs = filterByParent(inputs, function(el) {return findParentNode(el, elTagName, elClass, elId);});
for(var i = 0; i < inputs.length; ++i) {
if(inputs[i].type == 'checkbox' || inputs[i].type == 'radio') {
inputs[i].checked = 'checked';
}
}
}
function deselect_all_in(elTagName, elClass, elId) {
var inputs = document.getElementsByTagName('INPUT');
inputs = filterByParent(inputs, function(el) {return findParentNode(el, elTagName, elClass, elId);});
for(var i = 0; i < inputs.length; ++i) {
if(inputs[i].type == 'checkbox' || inputs[i].type == 'radio') {
inputs[i].checked = '';
}
}
}
function confirm_if(expr, message) {
if(!expr) {
return true;
}
return confirm(message);
}
/*
findParentNode (start, elementName, elementClass, elementID)
Travels up the DOM hierarchy to find a parent element with the
specified tag name, class, and id. All conditions must be met,
but any can be ommitted. Returns the BODY element if no match
found.
*/
function findParentNode(el, elName, elClass, elId) {
while (el.nodeName.toUpperCase() != 'BODY') {
if ((!elName || el.nodeName.toUpperCase() == elName) &&
(!elClass || el.className.indexOf(elClass) != -1) &&
(!elId || el.id == elId)) {
break;
}
el = el.parentNode;
}
return el;
}
/*
findChildNode (start, elementName, elementClass, elementID)
Travels down the DOM hierarchy to find all child elements with the
specified tag name, class, and id. All conditions must be met,
but any can be ommitted.
Doesn't examine children of matches.
@deprecated since Moodle 2.7 - please do not use this function any more.
@todo MDL-43242 This will be deleted in Moodle 2.9.
@see Y.all
*/
function findChildNodes(start, tagName, elementClass, elementID, elementName) {
Y.log("findChildNodes() is deprecated. Please use Y.all instead.",
"warn", "javascript-static.js");
var children = new Array();
for (var i = 0; i < start.childNodes.length; i++) {
var classfound = false;
var child = start.childNodes[i];
if((child.nodeType == 1) &&//element node type