MDL-47739 form: Calendar widget causes unintentional focus and scroll
[moodle.git] / lib / form / yui / build / moodle-form-dateselector / moodle-form-dateselector-debug.js
blob6b4db96084a2ef87b75c604ccccab77865e30df1
1 YUI.add('moodle-form-dateselector', function (Y, NAME) {
3 /**
4  * Add some custom methods to the node class to make our lives a little
5  * easier within this module.
6  */
7 Y.mix(Y.Node.prototype, {
8     /**
9      * Gets the value of the first option in the select box
10      */
11     firstOptionValue: function() {
12         if (this.get('nodeName').toLowerCase() !== 'select') {
13             return false;
14         }
15         return this.one('option').get('value');
16     },
17     /**
18      * Gets the value of the last option in the select box
19      */
20     lastOptionValue: function() {
21         if (this.get('nodeName').toLowerCase() !== 'select') {
22             return false;
23         }
24         return this.all('option').item(this.optionSize()-1).get('value');
25     },
26     /**
27      * Gets the number of options in the select box
28      */
29     optionSize: function() {
30         if (this.get('nodeName').toLowerCase() !== 'select') {
31             return false;
32         }
33         return parseInt(this.all('option').size(), 10);
34     },
35     /**
36      * Gets the value of the selected option in the select box
37      */
38     selectedOptionValue: function() {
39         if (this.get('nodeName').toLowerCase() !== 'select') {
40             return false;
41         }
42         return this.all('option').item(this.get('selectedIndex')).get('value');
43     }
44 });
46 M.form = M.form || {};
47 M.form.dateselector = {
48     panel: null,
49     calendar: null,
50     currentowner: null,
51     hidetimeout: null,
52     repositiontimeout: null,
53     init_date_selectors: function(config) {
54         if (this.panel === null) {
55             this.initPanel(config);
56         }
57         Y.all('.fdate_time_selector').each(function() {
58             config.node = this;
59             new CALENDAR(config);
60         });
61         Y.all('.fdate_selector').each(function() {
62             config.node = this;
63             new CALENDAR(config);
64         });
65     },
66     initPanel: function(config) {
67         this.panel = new Y.Overlay({
68             visible: false,
69             bodyContent: Y.Node.create('<div id="dateselector-calendar-content"></div>'),
70             id: 'dateselector-calendar-panel'
71         });
72         this.panel.render(document.body);
73         // zIndex is added by panel.render() and is set to 0.
74         // Remove zIndex from panel, as this should be set by CSS. This can be done by removeAttr but
75         // ie8 fails and there is know issue for it.
76         Y.one('#dateselector-calendar-panel').setStyle('zIndex', null);
77         this.panel.on('heightChange', this.fix_position, this);
79         Y.one('#dateselector-calendar-panel').on('click', function(e){e.halt();});
80         Y.one(document.body).on('click', this.document_click, this);
82         this.calendar = new MOODLECALENDAR({
83             contentBox: "#dateselector-calendar-content",
84             width: "300px",
85             showPrevMonth: true,
86             showNextMonth: true,
87             firstdayofweek: config.firstdayofweek,
88             WEEKDAYS_MEDIUM: [
89                 config.sun,
90                 config.mon,
91                 config.tue,
92                 config.wed,
93                 config.thu,
94                 config.fri,
95                 config.sat ]
96         });
97     },
98     cancel_any_timeout: function() {
99         if (this.hidetimeout) {
100             clearTimeout(this.hidetimeout);
101             this.hidetimeout = null;
102         }
103         if (this.repositiontimeout) {
104             clearTimeout(this.repositiontimeout);
105             this.repositiontimeout = null;
106         }
107     },
108     delayed_reposition: function() {
109         if (this.repositiontimeout) {
110             clearTimeout(this.repositiontimeout);
111             this.repositiontimeout = null;
112         }
113         this.repositiontimeout = setTimeout(this.fix_position, 500);
114     },
115     fix_position: function() {
116         if (this.currentowner) {
117             var alignpoints = [
118                 Y.WidgetPositionAlign.BL,
119                 Y.WidgetPositionAlign.TL
120             ];
122             // Change the alignment if this is an RTL language.
123             if (right_to_left()) {
124                 alignpoints = [
125                     Y.WidgetPositionAlign.BR,
126                     Y.WidgetPositionAlign.TR
127                 ];
128             }
131             this.panel.set('align', {
132                 node: this.currentowner.get('node').one('select'),
133                 points: alignpoints
134             });
135         }
136     },
137     document_click: function(e) {
138         if (this.currentowner) {
139             if (this.currentowner.get('node').ancestor('div').contains(e.target)) {
140                 setTimeout(function() {
141                     M.form.dateselector.cancel_any_timeout();
142                 }, 100);
143             } else {
144                 this.currentowner.release_calendar(e);
145             }
146         }
147     }
150  * Provides the Moodle Calendar class.
152  * @module moodle-form-dateselector
153  */
156  * A class to overwrite the YUI3 Calendar in order to change the strings..
158  * @class M.form_moodlecalendar
159  * @constructor
160  * @extends Calendar
161  */
162 var MOODLECALENDAR = function() {
163     MOODLECALENDAR.superclass.constructor.apply(this, arguments);
166 Y.extend(MOODLECALENDAR, Y.Calendar, {
167         initializer: function(cfg) {
168             this.set("strings.very_short_weekdays", cfg.WEEKDAYS_MEDIUM);
169             this.set("strings.first_weekday", cfg.firstdayofweek);
170         }
171     }, {
172         NAME: 'Calendar',
173         ATTRS: {}
174     }
177 M.form_moodlecalendar = M.form_moodlecalendar || {};
178 M.form_moodlecalendar.initializer = function(params) {
179     return new MOODLECALENDAR(params);
182  * Provides the Calendar class.
184  * @module moodle-form-dateselector
185  */
188  * Calendar class
189  */
190 var CALENDAR = function() {
191     CALENDAR.superclass.constructor.apply(this, arguments);
193 CALENDAR.prototype = {
194     panel: null,
195     yearselect: null,
196     monthselect: null,
197     dayselect: null,
198     calendarimage: null,
199     enablecheckbox: null,
200     closepopup: true,
201     initializer: function() {
202         var controls = this.get('node').all('select');
203         controls.each(function(node){
204             if (node.get('name').match(/\[year\]/)) {
205                 this.yearselect = node;
206             } else if (node.get('name').match(/\[month\]/)) {
207                 this.monthselect = node;
208             } else if (node.get('name').match(/\[day\]/)) {
209                 this.dayselect = node;
210             }
211             node.after('change', this.handle_select_change, this);
212         }, this);
214         // Loop through the input fields.
215         var inputs = this.get('node').all('input, a');
216         inputs.each(function(node) {
217             // Check if the current node is a calendar image field.
218             if (node.get('name').match(/\[calendar\]/)) {
219                 // Set it so that when the image is clicked the pop-up displays.
220                 node.on('click', this.focus_event, this);
221                 // Set the node to the calendarimage variable.
222                 this.calendarimage = node;
223             } else { // Must be the enabled checkbox field.
224                 // If the enable checkbox is clicked we want to either disable/enable the calendar image.
225                 node.on('click', this.toggle_calendar_image, this);
226                 // Set the node to the enablecheckbox variable.
227                 this.enablecheckbox = node;
228             }
229             // Ensure that the calendarimage and enablecheckbox values have been set.
230             if (this.calendarimage && this.enablecheckbox) {
231                 // Set the calendar icon status depending on the value of the checkbox.
232                 this.toggle_calendar_image();
233             }
234         }, this);
235     },
236     focus_event: function(e) {
237         M.form.dateselector.cancel_any_timeout();
238         // If the current owner is set, then the pop-up is currently being displayed, so hide it.
239         if (M.form.dateselector.currentowner === this) {
240             this.release_calendar();
241         } else if ((this.enablecheckbox === null)
242             || (this.enablecheckbox.get('checked'))) { // Must be hidden. If the field is enabled display the pop-up.
243             this.claim_calendar();
244         }
245         // Stop the input image field from submitting the form.
246         e.preventDefault();
247     },
248     handle_select_change: function() {
249         // It may seem as if the following variable is not used, however any call to set_date_from_selects will trigger a
250         // call to set_selects_from_date if the calendar is open as the date has changed. Whenever the calendar is displayed
251         // the set_selects_from_date function is set to trigger on any date change (see function connect_handlers).
252         this.closepopup = false;
253         this.set_date_from_selects();
254         this.closepopup = true;
255     },
256     claim_calendar: function() {
257         M.form.dateselector.cancel_any_timeout();
258         if (M.form.dateselector.currentowner === this) {
259             return;
260         }
261         if (M.form.dateselector.currentowner) {
262             M.form.dateselector.currentowner.release_calendar();
263         }
264         if (M.form.dateselector.currentowner !== this) {
265             this.connect_handlers();
266             this.set_date_from_selects();
267         }
268         M.form.dateselector.currentowner = this;
269         M.form.dateselector.calendar.set('mindate', new Date(this.yearselect.firstOptionValue(), 0, 1));
270         M.form.dateselector.calendar.set('maxdate', new Date(this.yearselect.lastOptionValue(), 11, 31));
271         M.form.dateselector.panel.show();
272         M.form.dateselector.calendar.show();
273         M.form.dateselector.fix_position();
274         setTimeout(function() {
275             M.form.dateselector.cancel_any_timeout();
276         }, 100);
278         // Focus on the calendar.
279         M.form.dateselector.calendar.focus();
281         // When the user tab out the calendar, close it.
282         Y.one(document.body).on('keyup', function(e) {
283             // hide the calendar if we press a key and the calendar is not focussed, or if we press ESC in the calendar.
284             if ((M.form.dateselector.currentowner === this && !M.form.dateselector.calendar.get('focused')) ||
285                 ((e.keyCode === 27) && M.form.dateselector.calendar.get('focused'))) {
286                 // Focus back on the calendar button.
287                 this.calendarimage.focus();
288                 this.release_calendar();
289             }
290         }, this);
292     },
293     set_date_from_selects: function() {
294         var year = parseInt(this.yearselect.get('value'), 10);
295         var month = parseInt(this.monthselect.get('value'), 10) - 1;
296         var day = parseInt(this.dayselect.get('value'), 10);
297         var date = new Date(year, month, day);
298         M.form.dateselector.calendar.deselectDates();
299         M.form.dateselector.calendar.selectDates([date]);
300         M.form.dateselector.calendar.set("date", date);
301         M.form.dateselector.calendar.render();
302         if (date.getDate() !== day) {
303             // Must've selected the 29 to 31st of a month that doesn't have such dates.
304             this.dayselect.set('value', date.getDate());
305             this.monthselect.set('value', date.getMonth() + 1);
306         }
307     },
308     set_selects_from_date: function(ev) {
309         var date = ev.newSelection[0];
310         var newyear = Y.DataType.Date.format(date, {format: "%Y"});
311         var newindex = newyear - this.yearselect.firstOptionValue();
312         this.yearselect.set('selectedIndex', newindex);
313         this.monthselect.set('selectedIndex', Y.DataType.Date.format(date, {format: "%m"}) - this.monthselect.firstOptionValue());
314         this.dayselect.set('selectedIndex', Y.DataType.Date.format(date, {format: "%d"}) - this.dayselect.firstOptionValue());
315         if (M.form.dateselector.currentowner && this.closepopup) {
316             this.release_calendar();
317         }
318     },
319     connect_handlers: function() {
320         M.form.dateselector.calendar.on('selectionChange', this.set_selects_from_date, this, true);
321     },
322     release_calendar: function(e) {
323         var wasOwner = M.form.dateselector.currentowner === this;
324         M.form.dateselector.panel.hide();
325         M.form.dateselector.calendar.detach('selectionChange', this.set_selects_from_date);
326         M.form.dateselector.calendar.hide();
327         M.form.dateselector.currentowner = null;
329         // Put the focus back to the image calendar that we clicked, only if it was visible.
330         if (wasOwner && (e === null || typeof e === "undefined" || e.type !== "click")) {
331             this.calendarimage.focus();
332         }
333     },
334     toggle_calendar_image: function() {
335         // If the enable checkbox is det checked, disable the image.
336         if (!this.enablecheckbox.get('checked')) {
337             this.calendarimage.set('disabled', 'disabled');
338             this.calendarimage.setStyle('cursor', 'default');
339             this.release_calendar();
340         } else {
341             this.calendarimage.set('disabled', false);
342             this.calendarimage.setStyle('cursor', null);
343         }
344     }
346 Y.extend(CALENDAR, Y.Base, CALENDAR.prototype, {
347     NAME: 'Date Selector',
348     ATTRS: {
349         firstdayofweek : {
350             validator: Y.Lang.isString
351         },
352         node: {
353             setter: function(node) {
354                 return Y.one(node);
355             }
356         }
357     }
361 }, '@VERSION@', {"requires": ["base", "node", "overlay", "calendar"]});