MDL-38367 course dndupload - various tweaks to the UI
[moodle.git] / course / dndupload.js
CommitLineData
32528f94
DS
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Javascript library for enableing a drag and drop upload to courses
18 *
a0a06d05 19 * @package core
32528f94
DS
20 * @subpackage course
21 * @copyright 2012 Davo Smith
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24M.course_dndupload = {
25 // YUI object.
26 Y: null,
27 // URL for upload requests
33b24bdd 28 url: M.cfg.wwwroot + '/course/dndupload.php',
32528f94
DS
29 // maximum size of files allowed in this form
30 maxbytes: 0,
31 // ID of the course we are on
32 courseid: null,
33 // Data about the different file/data handlers that are available
34 handlers: null,
35 // Nasty hack to distinguish between dragenter(first entry),
36 // dragenter+dragleave(moving between child elements) and dragleave (leaving element)
37 entercount: 0,
38 // Used to keep track of the section we are dragging across - to make
39 // spotting movement between sections more reliable
40 currentsection: null,
41 // Used to store the pending uploads whilst the user is being asked for further input
42 uploadqueue: null,
43 // True if the there is currently a dialog being shown (asking for a name, or giving a
44 // choice of file handlers)
45 uploaddialog: false,
46 // An array containing the last selected file handler for each file type
47 lastselected: null,
48
49 // The following are used to identify specific parts of the course page
50
51 // The type of HTML element that is a course section
52 sectiontypename: 'li',
53 // The classes that an element must have to be identified as a course section
54 sectionclasses: ['section', 'main'],
55 // The ID of the main content area of the page (for adding the 'status' div)
6c0ae99b 56 pagecontentid: 'page',
32528f94
DS
57 // The selector identifying the list of modules within a section (note changing this may require
58 // changes to the get_mods_element function)
59 modslistselector: 'ul.section',
60
61 /**
62 * Initalise the drag and drop upload interface
63 * Note: one and only one of options.filemanager and options.formcallback must be defined
64 *
65 * @param Y the YUI object
66 * @param object options {
67 * courseid: ID of the course we are on
68 * maxbytes: maximum size of files allowed in this form
69 * handlers: Data about the different file/data handlers that are available
70 * }
71 */
72 init: function(Y, options) {
73 this.Y = Y;
74
75 if (!this.browser_supported()) {
76 return; // Browser does not support the required functionality
77 }
78
79 this.maxbytes = options.maxbytes;
80 this.courseid = options.courseid;
81 this.handlers = options.handlers;
82 this.uploadqueue = new Array();
83 this.lastselected = new Array();
84
85 var sectionselector = this.sectiontypename + '.' + this.sectionclasses.join('.');
86 var sections = this.Y.all(sectionselector);
87 if (sections.isEmpty()) {
88 return; // No sections - incompatible course format or front page.
89 }
90 sections.each( function(el) {
91 this.add_preview_element(el);
92 this.init_events(el);
93 }, this);
94
6c0ae99b
DS
95 if (options.showstatus) {
96 this.add_status_div();
97 }
32528f94
DS
98 },
99
100 /**
101 * Add a div element to tell the user that drag and drop upload
102 * is available (or to explain why it is not available)
32528f94
DS
103 */
104 add_status_div: function() {
32528f94 105 var coursecontents = document.getElementById(this.pagecontentid);
6c0ae99b
DS
106 if (!coursecontents) {
107 return;
32528f94 108 }
b64300fc 109
6c0ae99b
DS
110 var div = document.createElement('div');
111 div.id = 'dndupload-status';
112 div.style.opacity = 0.0;
113 coursecontents.insertBefore(div, coursecontents.firstChild);
114
115 var Y = this.Y;
116 div = Y.one(div);
b64300fc
DS
117 var handlefile = (this.handlers.filehandlers.length > 0);
118 var handletext = false;
119 var handlelink = false;
120 var i;
121 for (i=0; i<this.handlers.types.length; i++) {
122 switch (this.handlers.types[i].identifier) {
123 case 'text':
124 case 'text/html':
125 handletext = true;
126 break;
127 case 'url':
128 handlelink = true;
129 break;
130 }
131 }
132 $msgident = 'dndworking';
133 if (handlefile) {
134 $msgident += 'file';
135 }
136 if (handletext) {
137 $msgident += 'text';
138 }
139 if (handlelink) {
140 $msgident += 'link';
141 }
142 div.setContent(M.util.get_string($msgident, 'moodle'));
6c0ae99b
DS
143
144 var fadeanim = new Y.Anim({
145 node: '#dndupload-status',
146 from: {
147 opacity: 0.0,
148 top: '-30px'
149 },
150
151 to: {
152 opacity: 1.0,
153 top: '0px'
154 },
155 duration: 0.5
156 });
157 fadeanim.once('end', function(e) {
158 this.set('reverse', 1);
159 Y.later(3000, this, 'run', null, false);
160 });
161 fadeanim.run();
32528f94
DS
162 },
163
164 /**
165 * Check the browser has the required functionality
166 * @return true if browser supports drag/drop upload
167 */
168 browser_supported: function() {
32528f94
DS
169 if (typeof FileReader == 'undefined') {
170 return false;
171 }
172 if (typeof FormData == 'undefined') {
173 return false;
174 }
175 return true;
176 },
177
178 /**
179 * Initialise drag events on node container, all events need
180 * to be processed for drag and drop to work
181 * @param el the element to add events to
182 */
183 init_events: function(el) {
184 this.Y.on('dragenter', this.drag_enter, el, this);
185 this.Y.on('dragleave', this.drag_leave, el, this);
186 this.Y.on('dragover', this.drag_over, el, this);
187 this.Y.on('drop', this.drop, el, this);
188 },
189
190 /**
191 * Work out which course section a given element is in
192 * @param el the child DOM element within the section
193 * @return the DOM element representing the section
194 */
195 get_section: function(el) {
196 var sectionclasses = this.sectionclasses;
197 return el.ancestor( function(test) {
198 var i;
199 for (i=0; i<sectionclasses.length; i++) {
200 if (!test.hasClass(sectionclasses[i])) {
201 return false;
202 }
203 return true;
204 }
205 }, true);
206 },
207
208 /**
209 * Work out the number of the section we have been dropped on to, from the section element
210 * @param DOMElement section the selected section
211 * @return int the section number
212 */
213 get_section_number: function(section) {
214 var sectionid = section.get('id').split('-');
215 if (sectionid.length < 2 || sectionid[0] != 'section') {
216 return false;
217 }
218 return parseInt(sectionid[1]);
219 },
220
221 /**
222 * Check if the event includes data of the given type
223 * @param e the event details
224 * @param type the data type to check for
225 * @return true if the data type is found in the event data
226 */
227 types_includes: function(e, type) {
228 var i;
229 var types = e._event.dataTransfer.types;
230 for (i=0; i<types.length; i++) {
231 if (types[i] == type) {
232 return true;
233 }
234 }
235 return false;
236 },
237
238 /**
239 * Look through the event data, checking it against the registered data types
240 * (in order of priority) and return details of the first matching data type
241 * @param e the event details
66079e28 242 * @return object|false - false if not found or an object {
32528f94
DS
243 * realtype: the type as given by the browser
244 * addmessage: the message to show to the user during dragging
245 * namemessage: the message for requesting a name for the resource from the user
246 * type: the identifier of the type (may match several 'realtype's)
247 * }
248 */
249 drag_type: function(e) {
b64300fc
DS
250 // Check there is some data attached.
251 if (e._event.dataTransfer === null) {
252 return false;
253 }
254 if (e._event.dataTransfer.types === null) {
255 return false;
256 }
257 if (e._event.dataTransfer.types.length == 0) {
258 return false;
259 }
260
261 // Check for files first.
32528f94 262 if (this.types_includes(e, 'Files')) {
5a4decbc
DS
263 if (e.type != 'drop' || e._event.dataTransfer.files.length != 0) {
264 if (this.handlers.filehandlers.length == 0) {
265 return false; // No available file handlers - ignore this drag.
266 }
267 return {
268 realtype: 'Files',
269 addmessage: M.util.get_string('addfilehere', 'moodle'),
270 namemessage: null, // Should not be asked for anyway
271 type: 'Files'
272 };
5103b5e6 273 }
32528f94
DS
274 }
275
b64300fc 276 // Check each of the registered types.
32528f94
DS
277 var types = this.handlers.types;
278 for (var i=0; i<types.length; i++) {
279 // Check each of the different identifiers for this type
280 var dttypes = types[i].datatransfertypes;
281 for (var j=0; j<dttypes.length; j++) {
282 if (this.types_includes(e, dttypes[j])) {
283 return {
284 realtype: dttypes[j],
285 addmessage: types[i].addmessage,
286 namemessage: types[i].namemessage,
66079e28 287 handlermessage: types[i].handlermessage,
32528f94
DS
288 type: types[i].identifier,
289 handlers: types[i].handlers
290 };
291 }
292 }
293 }
294 return false; // No types we can handle
295 },
296
297 /**
298 * Check the content of the drag/drop includes a type we can handle, then, if
299 * it is, notify the browser that we want to handle it
300 * @param event e
301 * @return string type of the event or false
302 */
303 check_drag: function(e) {
304 var type = this.drag_type(e);
305 if (type) {
306 // Notify browser that we will handle this drag/drop
307 e.stopPropagation();
308 e.preventDefault();
309 }
310 return type;
311 },
312
313 /**
314 * Handle a dragenter event: add a suitable 'add here' message
315 * when a drag event occurs, containing a registered data type
316 * @param e event data
317 * @return false to prevent the event from continuing to be processed
318 */
319 drag_enter: function(e) {
320 if (!(type = this.check_drag(e))) {
321 return false;
322 }
323
324 var section = this.get_section(e.currentTarget);
325 if (!section) {
326 return false;
327 }
328
329 if (this.currentsection && this.currentsection != section) {
330 this.currentsection = section;
331 this.entercount = 1;
332 } else {
333 this.entercount++;
334 if (this.entercount > 2) {
335 this.entercount = 2;
336 return false;
337 }
338 }
339
340 this.show_preview_element(section, type);
341
342 return false;
343 },
344
345 /**
346 * Handle a dragleave event: remove the 'add here' message (if present)
347 * @param e event data
348 * @return false to prevent the event from continuing to be processed
349 */
350 drag_leave: function(e) {
351 if (!this.check_drag(e)) {
352 return false;
353 }
354
355 this.entercount--;
356 if (this.entercount == 1) {
357 return false;
358 }
359 this.entercount = 0;
360 this.currentsection = null;
361
362 this.hide_preview_element();
363 return false;
364 },
365
366 /**
367 * Handle a dragover event: just prevent the browser default (necessary
368 * to allow drag and drop handling to work)
369 * @param e event data
370 * @return false to prevent the event from continuing to be processed
371 */
372 drag_over: function(e) {
373 this.check_drag(e);
374 return false;
375 },
376
377 /**
378 * Handle a drop event: hide the 'add here' message, check the attached
379 * data type and start the upload process
380 * @param e event data
381 * @return false to prevent the event from continuing to be processed
382 */
383 drop: function(e) {
384 if (!(type = this.check_drag(e))) {
385 return false;
386 }
387
388 this.hide_preview_element();
389
390 // Work out the number of the section we are on (from its id)
391 var section = this.get_section(e.currentTarget);
392 var sectionnumber = this.get_section_number(section);
393
394 // Process the file or the included data
395 if (type.type == 'Files') {
396 var files = e._event.dataTransfer.files;
397 for (var i=0, f; f=files[i]; i++) {
398 this.handle_file(f, section, sectionnumber);
399 }
400 } else {
401 var contents = e._event.dataTransfer.getData(type.realtype);
402 if (contents) {
403 this.handle_item(type, contents, section, sectionnumber);
404 }
405 }
406
407 return false;
408 },
409
410 /**
411 * Find or create the 'ul' element that contains all of the module
412 * instances in this section
413 * @param section the DOM element representing the section
414 * @return false to prevent the event from continuing to be processed
415 */
416 get_mods_element: function(section) {
417 // Find the 'ul' containing the list of mods
418 var modsel = section.one(this.modslistselector);
419 if (!modsel) {
420 // Create the above 'ul' if it doesn't exist
66079e28 421 modsel = document.createElement('ul');
32528f94
DS
422 modsel.className = 'section img-text';
423 var contentel = section.get('children').pop();
424 var brel = contentel.get('children').pop();
425 contentel.insertBefore(modsel, brel);
426 modsel = this.Y.one(modsel);
427 }
428
429 return modsel;
430 },
431
432 /**
433 * Add a new dummy item to the list of mods, to be replaced by a real
434 * item & link once the AJAX upload call has completed
435 * @param name the label to show in the element
436 * @param section the DOM element reperesenting the course section
437 * @return DOM element containing the new item
438 */
785e09a7 439 add_resource_element: function(name, section, module) {
32528f94
DS
440 var modsel = this.get_mods_element(section);
441
442 var resel = {
443 parent: modsel,
444 li: document.createElement('li'),
445 div: document.createElement('div'),
eacc63ab 446 indentdiv: document.createElement('div'),
32528f94
DS
447 a: document.createElement('a'),
448 icon: document.createElement('img'),
449 namespan: document.createElement('span'),
bc3f5bca 450 groupingspan: document.createElement('span'),
32528f94
DS
451 progressouter: document.createElement('span'),
452 progress: document.createElement('span')
453 };
454
785e09a7 455 resel.li.className = 'activity ' + module + ' modtype_' + module;
32528f94 456
eacc63ab
FM
457 resel.indentdiv.className = 'mod-indent';
458 resel.li.appendChild(resel.indentdiv);
459
460 resel.div.className = 'activityinstance';
461 resel.indentdiv.appendChild(resel.div);
32528f94
DS
462
463 resel.a.href = '#';
464 resel.div.appendChild(resel.a);
465
466 resel.icon.src = M.util.image_url('i/ajaxloader');
eacc63ab 467 resel.icon.className = 'activityicon iconlarge';
32528f94
DS
468 resel.a.appendChild(resel.icon);
469
32528f94
DS
470 resel.namespan.className = 'instancename';
471 resel.namespan.innerHTML = name;
472 resel.a.appendChild(resel.namespan);
473
bc3f5bca
RL
474 resel.groupingspan.className = 'groupinglabel';
475 resel.div.appendChild(resel.groupingspan);
476
32528f94
DS
477 resel.progressouter.className = 'dndupload-progress-outer';
478 resel.progress.className = 'dndupload-progress-inner';
479 resel.progress.innerHTML = '&nbsp;';
480 resel.progressouter.appendChild(resel.progress);
481 resel.div.appendChild(resel.progressouter);
482
483 modsel.insertBefore(resel.li, modsel.get('children').pop()); // Leave the 'preview element' at the bottom
484
485 return resel;
486 },
487
488 /**
489 * Hide any visible dndupload-preview elements on the page
490 */
491 hide_preview_element: function() {
492 this.Y.all('li.dndupload-preview').addClass('dndupload-hidden');
66079e28 493 this.Y.all('.dndupload-over').removeClass('dndupload-over');
32528f94
DS
494 },
495
496 /**
497 * Unhide the preview element for the given section and set it to display
498 * the correct message
499 * @param section the YUI node representing the selected course section
500 * @param type the details of the data type detected in the drag (including the message to display)
501 */
502 show_preview_element: function(section, type) {
503 this.hide_preview_element();
504 var preview = section.one('li.dndupload-preview').removeClass('dndupload-hidden');
66079e28 505 section.addClass('dndupload-over');
32528f94
DS
506 preview.one('span').setContent(type.addmessage);
507 },
508
509 /**
510 * Add the preview element to a course section. Note: this needs to be done before 'addEventListener'
511 * is called, otherwise Firefox will ignore events generated when the mouse is over the preview
512 * element (instead of passing them up to the parent element)
513 * @param section the YUI node representing the selected course section
514 */
515 add_preview_element: function(section) {
516 var modsel = this.get_mods_element(section);
517 var preview = {
518 li: document.createElement('li'),
519 div: document.createElement('div'),
520 icon: document.createElement('img'),
521 namespan: document.createElement('span')
522 };
523
4d40dc92 524 preview.li.className = 'dndupload-preview dndupload-hidden';
32528f94
DS
525
526 preview.div.className = 'mod-indent';
527 preview.li.appendChild(preview.div);
528
529 preview.icon.src = M.util.image_url('t/addfile');
8a3b8918 530 preview.icon.className = 'icon';
32528f94
DS
531 preview.div.appendChild(preview.icon);
532
533 preview.div.appendChild(document.createTextNode(' '));
534
535 preview.namespan.className = 'instancename';
33b24bdd 536 preview.namespan.innerHTML = M.util.get_string('addfilehere', 'moodle');
32528f94
DS
537 preview.div.appendChild(preview.namespan);
538
539 modsel.appendChild(preview.li);
540 },
541
542 /**
543 * Find the registered handler for the given file type. If there is more than one, ask the
544 * user which one to use. Then upload the file to the server
545 * @param file the details of the file, taken from the FileList in the drop event
546 * @param section the DOM element representing the selected course section
547 * @param sectionnumber the number of the selected course section
548 */
549 handle_file: function(file, section, sectionnumber) {
550 var handlers = new Array();
551 var filehandlers = this.handlers.filehandlers;
552 var extension = '';
553 var dotpos = file.name.lastIndexOf('.');
554 if (dotpos != -1) {
04a38bd3 555 extension = file.name.substr(dotpos+1, file.name.length).toLowerCase();
32528f94
DS
556 }
557
558 for (var i=0; i<filehandlers.length; i++) {
559 if (filehandlers[i].extension == '*' || filehandlers[i].extension == extension) {
560 handlers.push(filehandlers[i]);
561 }
562 }
563
564 if (handlers.length == 0) {
565 // No handlers at all (not even 'resource'?)
566 return;
567 }
568
569 if (handlers.length == 1) {
570 this.upload_file(file, section, sectionnumber, handlers[0].module);
571 return;
572 }
573
574 this.file_handler_dialog(handlers, extension, file, section, sectionnumber);
575 },
576
577 /**
578 * Show a dialog box, allowing the user to choose what to do with the file they are uploading
579 * @param handlers the available handlers to choose between
580 * @param extension the extension of the file being uploaded
581 * @param file the File object being uploaded
582 * @param section the DOM element of the section being uploaded to
583 * @param sectionnumber the number of the selected course section
584 */
585 file_handler_dialog: function(handlers, extension, file, section, sectionnumber) {
586 if (this.uploaddialog) {
587 var details = new Object();
588 details.isfile = true;
589 details.handlers = handlers;
590 details.extension = extension;
591 details.file = file;
592 details.section = section;
593 details.sectionnumber = sectionnumber;
594 this.uploadqueue.push(details);
595 return;
596 }
597 this.uploaddialog = true;
598
599 var timestamp = new Date().getTime();
600 var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
601 var content = '';
602 var sel;
603 if (extension in this.lastselected) {
604 sel = this.lastselected[extension];
605 } else {
606 sel = handlers[0].module;
607 }
33b24bdd 608 content += '<p>'+M.util.get_string('actionchoice', 'moodle', file.name)+'</p>';
32528f94
DS
609 content += '<div id="dndupload_handlers'+uploadid+'">';
610 for (var i=0; i<handlers.length; i++) {
611 var id = 'dndupload_handler'+uploadid+handlers[i].module;
612 var checked = (handlers[i].module == sel) ? 'checked="checked" ' : '';
613 content += '<input type="radio" name="handler" value="'+handlers[i].module+'" id="'+id+'" '+checked+'/>';
614 content += ' <label for="'+id+'">';
615 content += handlers[i].message;
616 content += '</label><br/>';
617 }
618 content += '</div>';
619
620 var Y = this.Y;
621 var self = this;
66079e28 622 var panel = new M.core.dialogue({
32528f94 623 bodyContent: content,
66079e28 624 width: '350px',
32528f94
DS
625 modal: true,
626 visible: true,
627 render: true,
66079e28
DS
628 align: {
629 node: null,
630 points: [Y.WidgetPositionAlign.CC, Y.WidgetPositionAlign.CC]
631 }
32528f94
DS
632 });
633 // When the panel is hidden - destroy it and then check for other pending uploads
634 panel.after("visibleChange", function(e) {
635 if (!panel.get('visible')) {
636 panel.destroy(true);
637 self.check_upload_queue();
638 }
639 });
66079e28
DS
640
641 // Add the submit/cancel buttons to the bottom of the dialog.
642 panel.addButton({
643 label: M.util.get_string('upload', 'moodle'),
644 action: function(e) {
645 e.preventDefault();
646 // Find out which module was selected
647 var module = false;
648 var div = Y.one('#dndupload_handlers'+uploadid);
649 div.all('input').each(function(input) {
650 if (input.get('checked')) {
651 module = input.get('value');
652 }
653 });
654 if (!module) {
655 return;
656 }
657 panel.hide();
658 // Remember this selection for next time
659 self.lastselected[extension] = module;
660 // Do the upload
661 self.upload_file(file, section, sectionnumber, module);
662 },
663 section: Y.WidgetStdMod.FOOTER
664 });
665 panel.addButton({
666 label: M.util.get_string('cancel', 'moodle'),
667 action: function(e) {
668 e.preventDefault();
669 panel.hide();
670 },
671 section: Y.WidgetStdMod.FOOTER
672 });
32528f94
DS
673 },
674
675 /**
676 * Check to see if there are any other dialog boxes to show, now that the current one has
677 * been dealt with
678 */
679 check_upload_queue: function() {
680 this.uploaddialog = false;
681 if (this.uploadqueue.length == 0) {
682 return;
683 }
684
685 var details = this.uploadqueue.shift();
686 if (details.isfile) {
687 this.file_handler_dialog(details.handlers, details.extension, details.file, details.section, details.sectionnumber);
688 } else {
689 this.handle_item(details.type, details.contents, details.section, details.sectionnumber);
690 }
691 },
692
693 /**
694 * Do the file upload: show the dummy element, use an AJAX call to send the data
695 * to the server, update the progress bar for the file, then replace the dummy
696 * element with the real information once the AJAX call completes
697 * @param file the details of the file, taken from the FileList in the drop event
698 * @param section the DOM element representing the selected course section
699 * @param sectionnumber the number of the selected course section
700 */
701 upload_file: function(file, section, sectionnumber, module) {
702
703 // This would be an ideal place to use the Y.io function
704 // however, this does not support data encoded using the
705 // FormData object, which is needed to transfer data from
706 // the DataTransfer object into an XMLHTTPRequest
707 // This can be converted when the YUI issue has been integrated:
708 // http://yuilibrary.com/projects/yui3/ticket/2531274
709 var xhr = new XMLHttpRequest();
710 var self = this;
711
712 if (file.size > this.maxbytes) {
33b24bdd 713 alert("'"+file.name+"' "+M.util.get_string('filetoolarge', 'moodle'));
32528f94
DS
714 return;
715 }
716
717 // Add the file to the display
785e09a7 718 var resel = this.add_resource_element(file.name, section, module);
32528f94
DS
719
720 // Update the progress bar as the file is uploaded
721 xhr.upload.addEventListener('progress', function(e) {
722 if (e.lengthComputable) {
723 var percentage = Math.round((e.loaded * 100) / e.total);
724 resel.progress.style.width = percentage + '%';
725 }
726 }, false);
727
728 // Wait for the AJAX call to complete, then update the
729 // dummy element with the returned details
730 xhr.onreadystatechange = function() {
731 if (xhr.readyState == 4) {
732 if (xhr.status == 200) {
733 var result = JSON.parse(xhr.responseText);
734 if (result) {
735 if (result.error == 0) {
736 // All OK - update the dummy element
785e09a7
DS
737 if (result.content) {
738 // A label
739 resel.indentdiv.innerHTML = '<div class="activityinstance" ></div>' + result.content + result.commands;
bc3f5bca 740 } else {
785e09a7
DS
741 // Not a label
742 resel.icon.src = result.icon;
743 resel.a.href = result.link;
744 resel.namespan.innerHTML = result.name;
745
746 if (!parseInt(result.visible, 10)) {
747 resel.a.className = 'dimmed';
748 }
749
750 if (result.groupingname) {
751 resel.groupingspan.innerHTML = '(' + result.groupingname + ')';
752 } else {
753 resel.div.removeChild(resel.groupingspan);
754 }
755
756 resel.div.removeChild(resel.progressouter);
757 resel.indentdiv.innerHTML += result.commands;
758 if (result.onclick) {
759 resel.a.onclick = result.onclick;
760 }
761 if (self.Y.UA.gecko > 0) {
762 // Fix a Firefox bug which makes sites with a '~' in their wwwroot
763 // log the user out when clicking on the link (before refreshing the page).
764 resel.div.innerHTML = unescape(resel.div.innerHTML);
765 }
bc3f5bca 766 }
32528f94 767 resel.li.id = result.elementid;
32528f94
DS
768 self.add_editing(result.elementid);
769 } else {
770 // Error - remove the dummy element
771 resel.parent.removeChild(resel.li);
772 alert(result.error);
773 }
774 }
775 } else {
33b24bdd 776 alert(M.util.get_string('servererror', 'moodle'));
32528f94
DS
777 }
778 }
779 };
780
781 // Prepare the data to send
782 var formData = new FormData();
783 formData.append('repo_upload_file', file);
784 formData.append('sesskey', M.cfg.sesskey);
785 formData.append('course', this.courseid);
786 formData.append('section', sectionnumber);
787 formData.append('module', module);
788 formData.append('type', 'Files');
789
790 // Send the AJAX call
791 xhr.open("POST", this.url, true);
792 xhr.send(formData);
793 },
794
795 /**
796 * Show a dialog box to gather the name of the resource / activity to be created
797 * from the uploaded content
798 * @param type the details of the type of content
799 * @param contents the contents to be uploaded
800 * @section the DOM element for the section being uploaded to
801 * @sectionnumber the number of the section being uploaded to
802 */
803 handle_item: function(type, contents, section, sectionnumber) {
804 if (type.handlers.length == 0) {
805 // Nothing to handle this - should not have got here
806 return;
807 }
808
2748d8ef
DS
809 if (type.handlers.length == 1 && type.handlers[0].noname) {
810 // Only one handler and it doesn't need a name (i.e. a label).
811 this.upload_item('', type.type, contents, section, sectionnumber, type.handlers[0].module);
812 this.check_upload_queue();
813 return;
814 }
815
32528f94
DS
816 if (this.uploaddialog) {
817 var details = new Object();
818 details.isfile = false;
819 details.type = type;
820 details.contents = contents;
821 details.section = section;
822 details.setcionnumber = sectionnumber;
823 this.uploadqueue.push(details);
824 return;
825 }
826 this.uploaddialog = true;
827
828 var timestamp = new Date().getTime();
829 var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
830 var nameid = 'dndupload_handler_name'+uploadid;
831 var content = '';
32528f94 832 if (type.handlers.length > 1) {
66079e28 833 content += '<p>'+type.handlermessage+'</p>';
32528f94
DS
834 content += '<div id="dndupload_handlers'+uploadid+'">';
835 var sel = type.handlers[0].module;
836 for (var i=0; i<type.handlers.length; i++) {
2748d8ef 837 var id = 'dndupload_handler'+uploadid+type.handlers[i].module;
32528f94 838 var checked = (type.handlers[i].module == sel) ? 'checked="checked" ' : '';
2748d8ef 839 content += '<input type="radio" name="handler" value="'+i+'" id="'+id+'" '+checked+'/>';
32528f94
DS
840 content += ' <label for="'+id+'">';
841 content += type.handlers[i].message;
842 content += '</label><br/>';
843 }
844 content += '</div>';
845 }
2748d8ef
DS
846 var disabled = (type.handlers[0].noname) ? ' disabled = "disabled" ' : '';
847 content += '<label for="'+nameid+'">'+type.namemessage+'</label>';
848 content += ' <input type="text" id="'+nameid+'" value="" '+disabled+' />';
32528f94
DS
849
850 var Y = this.Y;
851 var self = this;
66079e28 852 var panel = new M.core.dialogue({
32528f94 853 bodyContent: content,
66079e28 854 width: '350px',
32528f94
DS
855 modal: true,
856 visible: true,
857 render: true,
66079e28
DS
858 align: {
859 node: null,
860 points: [Y.WidgetPositionAlign.CC, Y.WidgetPositionAlign.CC]
861 }
32528f94 862 });
66079e28 863
32528f94
DS
864 // When the panel is hidden - destroy it and then check for other pending uploads
865 panel.after("visibleChange", function(e) {
866 if (!panel.get('visible')) {
867 panel.destroy(true);
868 self.check_upload_queue();
869 }
870 });
66079e28
DS
871
872 var namefield = Y.one('#'+nameid);
873 var submit = function(e) {
874 e.preventDefault();
875 var name = Y.Lang.trim(namefield.get('value'));
876 var module = false;
877 var noname = false;
878 if (type.handlers.length > 1) {
879 // Find out which module was selected
880 var div = Y.one('#dndupload_handlers'+uploadid);
881 div.all('input').each(function(input) {
882 if (input.get('checked')) {
883 var idx = input.get('value');
884 module = type.handlers[idx].module;
885 noname = type.handlers[idx].noname;
886 }
887 });
888 if (!module) {
889 return;
890 }
891 } else {
892 module = type.handlers[0].module;
893 noname = type.handlers[0].noname;
894 }
895 if (name == '' && !noname) {
896 return;
897 }
898 if (noname) {
899 name = '';
900 }
901 panel.hide();
902 // Do the upload
903 self.upload_item(name, type.type, contents, section, sectionnumber, module);
904 };
905
906 // Add the submit/cancel buttons to the bottom of the dialog.
907 panel.addButton({
908 label: M.util.get_string('upload', 'moodle'),
909 action: submit,
910 section: Y.WidgetStdMod.FOOTER,
911 name: 'submit'
912 });
913 panel.addButton({
914 label: M.util.get_string('cancel', 'moodle'),
915 action: function(e) {
916 e.preventDefault();
917 panel.hide();
918 },
919 section: Y.WidgetStdMod.FOOTER
920 });
921 var submitbutton = panel.getButton('submit').button;
922 namefield.on('key', submit, 'enter'); // Submit the form if 'enter' pressed
923 namefield.after('keyup', function() {
924 if (Y.Lang.trim(namefield.get('value')) == '') {
925 submitbutton.disable();
926 } else {
927 submitbutton.enable();
928 }
929 });
930
931 // Enable / disable the 'name' box, depending on the handler selected.
2748d8ef
DS
932 for (i=0; i<type.handlers.length; i++) {
933 if (type.handlers[i].noname) {
934 Y.one('#dndupload_handler'+uploadid+type.handlers[i].module).on('click', function (e) {
66079e28
DS
935 namefield.set('disabled', 'disabled');
936 submitbutton.enable();
2748d8ef
DS
937 });
938 } else {
939 Y.one('#dndupload_handler'+uploadid+type.handlers[i].module).on('click', function (e) {
66079e28
DS
940 namefield.removeAttribute('disabled');
941 namefield.focus();
942 if (Y.Lang.trim(namefield.get('value')) == '') {
943 submitbutton.disable();
944 }
2748d8ef
DS
945 });
946 }
947 }
66079e28
DS
948
949 // Focus on the 'name' box
950 Y.one('#'+nameid).focus();
32528f94
DS
951 },
952
953 /**
954 * Upload any data types that are not files: display a dummy resource element, send
955 * the data to the server, update the progress bar for the file, then replace the
956 * dummy element with the real information once the AJAX call completes
957 * @param name the display name for the resource / activity to create
958 * @param type the details of the data type found in the drop event
959 * @param contents the actual data that was dropped
960 * @param section the DOM element representing the selected course section
961 * @param sectionnumber the number of the selected course section
5a4decbc 962 * @param module the module chosen to handle this upload
32528f94
DS
963 */
964 upload_item: function(name, type, contents, section, sectionnumber, module) {
965
966 // This would be an ideal place to use the Y.io function
967 // however, this does not support data encoded using the
968 // FormData object, which is needed to transfer data from
969 // the DataTransfer object into an XMLHTTPRequest
970 // This can be converted when the YUI issue has been integrated:
971 // http://yuilibrary.com/projects/yui3/ticket/2531274
972 var xhr = new XMLHttpRequest();
973 var self = this;
974
975 // Add the item to the display
785e09a7 976 var resel = this.add_resource_element(name, section, module);
32528f94
DS
977
978 // Wait for the AJAX call to complete, then update the
979 // dummy element with the returned details
980 xhr.onreadystatechange = function() {
981 if (xhr.readyState == 4) {
982 if (xhr.status == 200) {
983 var result = JSON.parse(xhr.responseText);
984 if (result) {
985 if (result.error == 0) {
986 // All OK - update the dummy element
785e09a7
DS
987 if (result.content) {
988 // A label
989 resel.indentdiv.innerHTML = '<div class="activityinstance" ></div>' + result.content + result.commands;
bc3f5bca 990 } else {
785e09a7
DS
991 // Not a label
992 resel.icon.src = result.icon;
993 resel.a.href = result.link;
994 resel.namespan.innerHTML = result.name;
995
996 if (!parseInt(result.visible, 10)) {
997 resel.a.className = 'dimmed';
998 }
999
1000 if (result.groupingname) {
1001 resel.groupingspan.innerHTML = '(' + result.groupingname + ')';
1002 } else {
1003 resel.div.removeChild(resel.groupingspan);
1004 }
1005
1006 resel.div.removeChild(resel.progressouter);
1007 resel.div.innerHTML += result.commands;
1008 if (result.onclick) {
1009 resel.a.onclick = result.onclick;
1010 }
1011 if (self.Y.UA.gecko > 0) {
1012 // Fix a Firefox bug which makes sites with a '~' in their wwwroot
1013 // log the user out when clicking on the link (before refreshing the page).
1014 resel.div.innerHTML = unescape(resel.div.innerHTML);
1015 }
d022f632 1016 }
32528f94 1017 resel.li.id = result.elementid;
32528f94
DS
1018 self.add_editing(result.elementid, sectionnumber);
1019 } else {
1020 // Error - remove the dummy element
1021 resel.parent.removeChild(resel.li);
1022 alert(result.error);
1023 }
1024 }
1025 } else {
33b24bdd 1026 alert(M.util.get_string('servererror', 'moodle'));
32528f94
DS
1027 }
1028 }
1029 };
1030
1031 // Prepare the data to send
1032 var formData = new FormData();
1033 formData.append('contents', contents);
1034 formData.append('displayname', name);
1035 formData.append('sesskey', M.cfg.sesskey);
1036 formData.append('course', this.courseid);
1037 formData.append('section', sectionnumber);
1038 formData.append('type', type);
1039 formData.append('module', module);
1040
1041 // Send the data
1042 xhr.open("POST", this.url, true);
1043 xhr.send(formData);
1044 },
1045
1046 /**
1047 * Call the AJAX course editing initialisation to add the editing tools
1048 * to the newly-created resource link
1049 * @param elementid the id of the DOM element containing the new resource link
1050 * @param sectionnumber the number of the selected course section
1051 */
1052 add_editing: function(elementid) {
1053 YUI().use('moodle-course-coursebase', function(Y) {
1054 M.course.coursebase.invoke_function('setup_for_resource', '#' + elementid);
1055 });
1056 }
1057};