MDL-22504 Drag and drop upload course - enables upload of files, text and urls to...
[moodle.git] / lib / ajax / 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 *
19 * @package moodlecore
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
28 url: M.cfg.wwwroot + '/lib/ajax/dndupload.php',
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)
56 pagecontentid: 'page-content',
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
95 var div = this.add_status_div();
96 div.setContent(M.util.get_string('dndworking', 'core_dndupload'));
97 },
98
99 /**
100 * Add a div element to tell the user that drag and drop upload
101 * is available (or to explain why it is not available)
102 * @return the DOM element to add messages to
103 */
104 add_status_div: function() {
105 var div = document.createElement('div');
106 div.id = 'dndupload-status';
107 var coursecontents = document.getElementById(this.pagecontentid);
108 if (coursecontents) {
109 coursecontents.insertBefore(div, coursecontents.firstChild);
110 }
111 return this.Y.one(div);
112 },
113
114 /**
115 * Check the browser has the required functionality
116 * @return true if browser supports drag/drop upload
117 */
118 browser_supported: function() {
119
120 if (typeof FileReader == 'undefined') {
121 return false;
122 }
123 if (typeof FormData == 'undefined') {
124 return false;
125 }
126 return true;
127 },
128
129 /**
130 * Initialise drag events on node container, all events need
131 * to be processed for drag and drop to work
132 * @param el the element to add events to
133 */
134 init_events: function(el) {
135 this.Y.on('dragenter', this.drag_enter, el, this);
136 this.Y.on('dragleave', this.drag_leave, el, this);
137 this.Y.on('dragover', this.drag_over, el, this);
138 this.Y.on('drop', this.drop, el, this);
139 },
140
141 /**
142 * Work out which course section a given element is in
143 * @param el the child DOM element within the section
144 * @return the DOM element representing the section
145 */
146 get_section: function(el) {
147 var sectionclasses = this.sectionclasses;
148 return el.ancestor( function(test) {
149 var i;
150 for (i=0; i<sectionclasses.length; i++) {
151 if (!test.hasClass(sectionclasses[i])) {
152 return false;
153 }
154 return true;
155 }
156 }, true);
157 },
158
159 /**
160 * Work out the number of the section we have been dropped on to, from the section element
161 * @param DOMElement section the selected section
162 * @return int the section number
163 */
164 get_section_number: function(section) {
165 var sectionid = section.get('id').split('-');
166 if (sectionid.length < 2 || sectionid[0] != 'section') {
167 return false;
168 }
169 return parseInt(sectionid[1]);
170 },
171
172 /**
173 * Check if the event includes data of the given type
174 * @param e the event details
175 * @param type the data type to check for
176 * @return true if the data type is found in the event data
177 */
178 types_includes: function(e, type) {
179 var i;
180 var types = e._event.dataTransfer.types;
181 for (i=0; i<types.length; i++) {
182 if (types[i] == type) {
183 return true;
184 }
185 }
186 return false;
187 },
188
189 /**
190 * Look through the event data, checking it against the registered data types
191 * (in order of priority) and return details of the first matching data type
192 * @param e the event details
193 * @return mixed false if not found or an object {
194 * realtype: the type as given by the browser
195 * addmessage: the message to show to the user during dragging
196 * namemessage: the message for requesting a name for the resource from the user
197 * type: the identifier of the type (may match several 'realtype's)
198 * }
199 */
200 drag_type: function(e) {
201 if (this.types_includes(e, 'Files')) {
202 return {
203 realtype: 'Files',
204 addmessage: M.util.get_string('addfilehere', 'core_dndupload'),
205 namemessage: null, // Should not be asked for anyway
206 type: 'Files'
207 };
208 }
209
210 // Check each of the registered types
211 var types = this.handlers.types;
212 for (var i=0; i<types.length; i++) {
213 // Check each of the different identifiers for this type
214 var dttypes = types[i].datatransfertypes;
215 for (var j=0; j<dttypes.length; j++) {
216 if (this.types_includes(e, dttypes[j])) {
217 return {
218 realtype: dttypes[j],
219 addmessage: types[i].addmessage,
220 namemessage: types[i].namemessage,
221 type: types[i].identifier,
222 handlers: types[i].handlers
223 };
224 }
225 }
226 }
227 return false; // No types we can handle
228 },
229
230 /**
231 * Check the content of the drag/drop includes a type we can handle, then, if
232 * it is, notify the browser that we want to handle it
233 * @param event e
234 * @return string type of the event or false
235 */
236 check_drag: function(e) {
237 var type = this.drag_type(e);
238 if (type) {
239 // Notify browser that we will handle this drag/drop
240 e.stopPropagation();
241 e.preventDefault();
242 }
243 return type;
244 },
245
246 /**
247 * Handle a dragenter event: add a suitable 'add here' message
248 * when a drag event occurs, containing a registered data type
249 * @param e event data
250 * @return false to prevent the event from continuing to be processed
251 */
252 drag_enter: function(e) {
253 if (!(type = this.check_drag(e))) {
254 return false;
255 }
256
257 var section = this.get_section(e.currentTarget);
258 if (!section) {
259 return false;
260 }
261
262 if (this.currentsection && this.currentsection != section) {
263 this.currentsection = section;
264 this.entercount = 1;
265 } else {
266 this.entercount++;
267 if (this.entercount > 2) {
268 this.entercount = 2;
269 return false;
270 }
271 }
272
273 this.show_preview_element(section, type);
274
275 return false;
276 },
277
278 /**
279 * Handle a dragleave event: remove the 'add here' message (if present)
280 * @param e event data
281 * @return false to prevent the event from continuing to be processed
282 */
283 drag_leave: function(e) {
284 if (!this.check_drag(e)) {
285 return false;
286 }
287
288 this.entercount--;
289 if (this.entercount == 1) {
290 return false;
291 }
292 this.entercount = 0;
293 this.currentsection = null;
294
295 this.hide_preview_element();
296 return false;
297 },
298
299 /**
300 * Handle a dragover event: just prevent the browser default (necessary
301 * to allow drag and drop handling to work)
302 * @param e event data
303 * @return false to prevent the event from continuing to be processed
304 */
305 drag_over: function(e) {
306 this.check_drag(e);
307 return false;
308 },
309
310 /**
311 * Handle a drop event: hide the 'add here' message, check the attached
312 * data type and start the upload process
313 * @param e event data
314 * @return false to prevent the event from continuing to be processed
315 */
316 drop: function(e) {
317 if (!(type = this.check_drag(e))) {
318 return false;
319 }
320
321 this.hide_preview_element();
322
323 // Work out the number of the section we are on (from its id)
324 var section = this.get_section(e.currentTarget);
325 var sectionnumber = this.get_section_number(section);
326
327 // Process the file or the included data
328 if (type.type == 'Files') {
329 var files = e._event.dataTransfer.files;
330 for (var i=0, f; f=files[i]; i++) {
331 this.handle_file(f, section, sectionnumber);
332 }
333 } else {
334 var contents = e._event.dataTransfer.getData(type.realtype);
335 if (contents) {
336 this.handle_item(type, contents, section, sectionnumber);
337 }
338 }
339
340 return false;
341 },
342
343 /**
344 * Find or create the 'ul' element that contains all of the module
345 * instances in this section
346 * @param section the DOM element representing the section
347 * @return false to prevent the event from continuing to be processed
348 */
349 get_mods_element: function(section) {
350 // Find the 'ul' containing the list of mods
351 var modsel = section.one(this.modslistselector);
352 if (!modsel) {
353 // Create the above 'ul' if it doesn't exist
354 var modsel = document.createElement('ul');
355 modsel.className = 'section img-text';
356 var contentel = section.get('children').pop();
357 var brel = contentel.get('children').pop();
358 contentel.insertBefore(modsel, brel);
359 modsel = this.Y.one(modsel);
360 }
361
362 return modsel;
363 },
364
365 /**
366 * Add a new dummy item to the list of mods, to be replaced by a real
367 * item & link once the AJAX upload call has completed
368 * @param name the label to show in the element
369 * @param section the DOM element reperesenting the course section
370 * @return DOM element containing the new item
371 */
372 add_resource_element: function(name, section) {
373 var modsel = this.get_mods_element(section);
374
375 var resel = {
376 parent: modsel,
377 li: document.createElement('li'),
378 div: document.createElement('div'),
379 a: document.createElement('a'),
380 icon: document.createElement('img'),
381 namespan: document.createElement('span'),
382 progressouter: document.createElement('span'),
383 progress: document.createElement('span')
384 };
385
386 resel.li.className = 'activity resource modtype_resource';
387
388 resel.div.className = 'mod-indent';
389 resel.li.appendChild(resel.div);
390
391 resel.a.href = '#';
392 resel.div.appendChild(resel.a);
393
394 resel.icon.src = M.util.image_url('i/ajaxloader');
395 resel.a.appendChild(resel.icon);
396
397 resel.a.appendChild(document.createTextNode(' '));
398
399 resel.namespan.className = 'instancename';
400 resel.namespan.innerHTML = name;
401 resel.a.appendChild(resel.namespan);
402
403 resel.div.appendChild(document.createTextNode(' '));
404
405 resel.progressouter.className = 'dndupload-progress-outer';
406 resel.progress.className = 'dndupload-progress-inner';
407 resel.progress.innerHTML = '&nbsp;';
408 resel.progressouter.appendChild(resel.progress);
409 resel.div.appendChild(resel.progressouter);
410
411 modsel.insertBefore(resel.li, modsel.get('children').pop()); // Leave the 'preview element' at the bottom
412
413 return resel;
414 },
415
416 /**
417 * Hide any visible dndupload-preview elements on the page
418 */
419 hide_preview_element: function() {
420 this.Y.all('li.dndupload-preview').addClass('dndupload-hidden');
421 },
422
423 /**
424 * Unhide the preview element for the given section and set it to display
425 * the correct message
426 * @param section the YUI node representing the selected course section
427 * @param type the details of the data type detected in the drag (including the message to display)
428 */
429 show_preview_element: function(section, type) {
430 this.hide_preview_element();
431 var preview = section.one('li.dndupload-preview').removeClass('dndupload-hidden');
432 preview.one('span').setContent(type.addmessage);
433 },
434
435 /**
436 * Add the preview element to a course section. Note: this needs to be done before 'addEventListener'
437 * is called, otherwise Firefox will ignore events generated when the mouse is over the preview
438 * element (instead of passing them up to the parent element)
439 * @param section the YUI node representing the selected course section
440 */
441 add_preview_element: function(section) {
442 var modsel = this.get_mods_element(section);
443 var preview = {
444 li: document.createElement('li'),
445 div: document.createElement('div'),
446 icon: document.createElement('img'),
447 namespan: document.createElement('span')
448 };
449
450 preview.li.className = 'dndupload-preview activity resource modtype_resource dndupload-hidden';
451
452 preview.div.className = 'mod-indent';
453 preview.li.appendChild(preview.div);
454
455 preview.icon.src = M.util.image_url('t/addfile');
456 preview.div.appendChild(preview.icon);
457
458 preview.div.appendChild(document.createTextNode(' '));
459
460 preview.namespan.className = 'instancename';
461 preview.namespan.innerHTML = M.util.get_string('addfilehere', 'core_dndupload');
462 preview.div.appendChild(preview.namespan);
463
464 modsel.appendChild(preview.li);
465 },
466
467 /**
468 * Find the registered handler for the given file type. If there is more than one, ask the
469 * user which one to use. Then upload the file to the server
470 * @param file the details of the file, taken from the FileList in the drop event
471 * @param section the DOM element representing the selected course section
472 * @param sectionnumber the number of the selected course section
473 */
474 handle_file: function(file, section, sectionnumber) {
475 var handlers = new Array();
476 var filehandlers = this.handlers.filehandlers;
477 var extension = '';
478 var dotpos = file.name.lastIndexOf('.');
479 if (dotpos != -1) {
480 extension = file.name.substr(dotpos+1, file.name.length);
481 }
482
483 for (var i=0; i<filehandlers.length; i++) {
484 if (filehandlers[i].extension == '*' || filehandlers[i].extension == extension) {
485 handlers.push(filehandlers[i]);
486 }
487 }
488
489 if (handlers.length == 0) {
490 // No handlers at all (not even 'resource'?)
491 return;
492 }
493
494 if (handlers.length == 1) {
495 this.upload_file(file, section, sectionnumber, handlers[0].module);
496 return;
497 }
498
499 this.file_handler_dialog(handlers, extension, file, section, sectionnumber);
500 },
501
502 /**
503 * Show a dialog box, allowing the user to choose what to do with the file they are uploading
504 * @param handlers the available handlers to choose between
505 * @param extension the extension of the file being uploaded
506 * @param file the File object being uploaded
507 * @param section the DOM element of the section being uploaded to
508 * @param sectionnumber the number of the selected course section
509 */
510 file_handler_dialog: function(handlers, extension, file, section, sectionnumber) {
511 if (this.uploaddialog) {
512 var details = new Object();
513 details.isfile = true;
514 details.handlers = handlers;
515 details.extension = extension;
516 details.file = file;
517 details.section = section;
518 details.sectionnumber = sectionnumber;
519 this.uploadqueue.push(details);
520 return;
521 }
522 this.uploaddialog = true;
523
524 var timestamp = new Date().getTime();
525 var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
526 var content = '';
527 var sel;
528 if (extension in this.lastselected) {
529 sel = this.lastselected[extension];
530 } else {
531 sel = handlers[0].module;
532 }
533 content += '<p>'+M.util.get_string('actionchoice', 'core_dndupload', file.name)+'</p>';
534 content += '<div id="dndupload_handlers'+uploadid+'">';
535 for (var i=0; i<handlers.length; i++) {
536 var id = 'dndupload_handler'+uploadid+handlers[i].module;
537 var checked = (handlers[i].module == sel) ? 'checked="checked" ' : '';
538 content += '<input type="radio" name="handler" value="'+handlers[i].module+'" id="'+id+'" '+checked+'/>';
539 content += ' <label for="'+id+'">';
540 content += handlers[i].message;
541 content += '</label><br/>';
542 }
543 content += '</div>';
544
545 var Y = this.Y;
546 var self = this;
547 var panel = new Y.Panel({
548 bodyContent: content,
549 width: 350,
550 zIndex: 5,
551 centered: true,
552 modal: true,
553 visible: true,
554 render: true,
555 buttons: [{
556 value: M.util.get_string('upload', 'core'),
557 action: function(e) {
558 e.preventDefault();
559 // Find out which module was selected
560 var module = false;
561 var div = Y.one('#dndupload_handlers'+uploadid);
562 div.all('input').each(function(input) {
563 if (input.get('checked')) {
564 module = input.get('value');
565 }
566 });
567 if (!module) {
568 return;
569 }
570 panel.hide();
571 // Remember this selection for next time
572 self.lastselected[extension] = module;
573 // Do the upload
574 self.upload_file(file, section, sectionnumber, module);
575 },
576 section: Y.WidgetStdMod.FOOTER
577 },{
578 value: M.util.get_string('cancel', 'core'),
579 action: function(e) {
580 e.preventDefault();
581 panel.hide();
582 },
583 section: Y.WidgetStdMod.FOOTER
584 }]
585 });
586 // When the panel is hidden - destroy it and then check for other pending uploads
587 panel.after("visibleChange", function(e) {
588 if (!panel.get('visible')) {
589 panel.destroy(true);
590 self.check_upload_queue();
591 }
592 });
593 },
594
595 /**
596 * Check to see if there are any other dialog boxes to show, now that the current one has
597 * been dealt with
598 */
599 check_upload_queue: function() {
600 this.uploaddialog = false;
601 if (this.uploadqueue.length == 0) {
602 return;
603 }
604
605 var details = this.uploadqueue.shift();
606 if (details.isfile) {
607 this.file_handler_dialog(details.handlers, details.extension, details.file, details.section, details.sectionnumber);
608 } else {
609 this.handle_item(details.type, details.contents, details.section, details.sectionnumber);
610 }
611 },
612
613 /**
614 * Do the file upload: show the dummy element, use an AJAX call to send the data
615 * to the server, update the progress bar for the file, then replace the dummy
616 * element with the real information once the AJAX call completes
617 * @param file the details of the file, taken from the FileList in the drop event
618 * @param section the DOM element representing the selected course section
619 * @param sectionnumber the number of the selected course section
620 */
621 upload_file: function(file, section, sectionnumber, module) {
622
623 // This would be an ideal place to use the Y.io function
624 // however, this does not support data encoded using the
625 // FormData object, which is needed to transfer data from
626 // the DataTransfer object into an XMLHTTPRequest
627 // This can be converted when the YUI issue has been integrated:
628 // http://yuilibrary.com/projects/yui3/ticket/2531274
629 var xhr = new XMLHttpRequest();
630 var self = this;
631
632 if (file.size > this.maxbytes) {
633 alert("'"+file.name+"' "+M.util.get_string('filetoolarge', 'core_dndupload'));
634 return;
635 }
636
637 // Add the file to the display
638 var resel = this.add_resource_element(file.name, section);
639
640 // Update the progress bar as the file is uploaded
641 xhr.upload.addEventListener('progress', function(e) {
642 if (e.lengthComputable) {
643 var percentage = Math.round((e.loaded * 100) / e.total);
644 resel.progress.style.width = percentage + '%';
645 }
646 }, false);
647
648 // Wait for the AJAX call to complete, then update the
649 // dummy element with the returned details
650 xhr.onreadystatechange = function() {
651 if (xhr.readyState == 4) {
652 if (xhr.status == 200) {
653 var result = JSON.parse(xhr.responseText);
654 if (result) {
655 if (result.error == 0) {
656 // All OK - update the dummy element
657 resel.icon.src = result.icon;
658 resel.a.href = result.link;
659 resel.namespan.innerHTML = result.name;
660 resel.div.removeChild(resel.progressouter);
661 resel.li.id = result.elementid;
662 resel.div.innerHTML += result.commands;
663 if (result.onclick) {
664 resel.a.onclick = result.onclick;
665 }
666 self.add_editing(result.elementid);
667 } else {
668 // Error - remove the dummy element
669 resel.parent.removeChild(resel.li);
670 alert(result.error);
671 }
672 }
673 } else {
674 alert(M.util.get_string('servererror', 'core_dndupload'));
675 }
676 }
677 };
678
679 // Prepare the data to send
680 var formData = new FormData();
681 formData.append('repo_upload_file', file);
682 formData.append('sesskey', M.cfg.sesskey);
683 formData.append('course', this.courseid);
684 formData.append('section', sectionnumber);
685 formData.append('module', module);
686 formData.append('type', 'Files');
687
688 // Send the AJAX call
689 xhr.open("POST", this.url, true);
690 xhr.send(formData);
691 },
692
693 /**
694 * Show a dialog box to gather the name of the resource / activity to be created
695 * from the uploaded content
696 * @param type the details of the type of content
697 * @param contents the contents to be uploaded
698 * @section the DOM element for the section being uploaded to
699 * @sectionnumber the number of the section being uploaded to
700 */
701 handle_item: function(type, contents, section, sectionnumber) {
702 if (type.handlers.length == 0) {
703 // Nothing to handle this - should not have got here
704 return;
705 }
706
707 if (this.uploaddialog) {
708 var details = new Object();
709 details.isfile = false;
710 details.type = type;
711 details.contents = contents;
712 details.section = section;
713 details.setcionnumber = sectionnumber;
714 this.uploadqueue.push(details);
715 return;
716 }
717 this.uploaddialog = true;
718
719 var timestamp = new Date().getTime();
720 var uploadid = Math.round(Math.random()*100000)+'-'+timestamp;
721 var nameid = 'dndupload_handler_name'+uploadid;
722 var content = '';
723 content += '<label for="'+nameid+'">'+type.namemessage+'</label>';
724 content += ' <input type="text" id="'+nameid+'" value="" />';
725 if (type.handlers.length > 1) {
726 content += '<div id="dndupload_handlers'+uploadid+'">';
727 var sel = type.handlers[0].module;
728 for (var i=0; i<type.handlers.length; i++) {
729 var id = 'dndupload_handler'+uploadid;
730 var checked = (type.handlers[i].module == sel) ? 'checked="checked" ' : '';
731 content += '<input type="radio" name="handler" value="'+type.handlers[i].module+'" id="'+id+'" '+checked+'/>';
732 content += ' <label for="'+id+'">';
733 content += type.handlers[i].message;
734 content += '</label><br/>';
735 }
736 content += '</div>';
737 }
738
739 var Y = this.Y;
740 var self = this;
741 var panel = new Y.Panel({
742 bodyContent: content,
743 width: 350,
744 zIndex: 5,
745 centered: true,
746 modal: true,
747 visible: true,
748 render: true,
749 buttons: [{
750 value: M.util.get_string('upload', 'core'),
751 action: function(e) {
752 e.preventDefault();
753 var name = Y.one('#dndupload_handler_name'+uploadid).get('value');
754 name = name.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // Trim
755 if (name == '') {
756 return;
757 }
758 var module = false;
759 if (type.handlers.length > 1) {
760 // Find out which module was selected
761 var div = Y.one('#dndupload_handlers'+uploadid);
762 div.all('input').each(function(input) {
763 if (input.get('checked')) {
764 module = input.get('value');
765 }
766 });
767 if (!module) {
768 return;
769 }
770 } else {
771 module = type.handlers[0].module;
772 }
773 panel.hide();
774 // Do the upload
775 self.upload_item(name, type.type, contents, section, sectionnumber, module);
776 },
777 section: Y.WidgetStdMod.FOOTER
778 },{
779 value: M.util.get_string('cancel', 'core'),
780 action: function(e) {
781 e.preventDefault();
782 panel.hide();
783 },
784 section: Y.WidgetStdMod.FOOTER
785 }]
786 });
787 // When the panel is hidden - destroy it and then check for other pending uploads
788 panel.after("visibleChange", function(e) {
789 if (!panel.get('visible')) {
790 panel.destroy(true);
791 self.check_upload_queue();
792 }
793 });
794 // Focus on the 'name' box
795 Y.one('#'+nameid).focus();
796 },
797
798 /**
799 * Upload any data types that are not files: display a dummy resource element, send
800 * the data to the server, update the progress bar for the file, then replace the
801 * dummy element with the real information once the AJAX call completes
802 * @param name the display name for the resource / activity to create
803 * @param type the details of the data type found in the drop event
804 * @param contents the actual data that was dropped
805 * @param section the DOM element representing the selected course section
806 * @param sectionnumber the number of the selected course section
807 */
808 upload_item: function(name, type, contents, section, sectionnumber, module) {
809
810 // This would be an ideal place to use the Y.io function
811 // however, this does not support data encoded using the
812 // FormData object, which is needed to transfer data from
813 // the DataTransfer object into an XMLHTTPRequest
814 // This can be converted when the YUI issue has been integrated:
815 // http://yuilibrary.com/projects/yui3/ticket/2531274
816 var xhr = new XMLHttpRequest();
817 var self = this;
818
819 // Add the item to the display
820 var resel = this.add_resource_element(name, section);
821
822 // Wait for the AJAX call to complete, then update the
823 // dummy element with the returned details
824 xhr.onreadystatechange = function() {
825 if (xhr.readyState == 4) {
826 if (xhr.status == 200) {
827 var result = JSON.parse(xhr.responseText);
828 if (result) {
829 if (result.error == 0) {
830 // All OK - update the dummy element
831 resel.icon.src = result.icon;
832 resel.a.href = result.link;
833 resel.namespan.innerHTML = result.name;
834 resel.div.removeChild(resel.progressouter);
835 resel.li.id = result.elementid;
836 resel.div.innerHTML += result.commands;
837 if (result.onclick) {
838 resel.a.onclick = result.onclick;
839 }
840 self.add_editing(result.elementid, sectionnumber);
841 } else {
842 // Error - remove the dummy element
843 resel.parent.removeChild(resel.li);
844 alert(result.error);
845 }
846 }
847 } else {
848 alert(M.util.get_string('servererror', 'core_dndupload'));
849 }
850 }
851 };
852
853 // Prepare the data to send
854 var formData = new FormData();
855 formData.append('contents', contents);
856 formData.append('displayname', name);
857 formData.append('sesskey', M.cfg.sesskey);
858 formData.append('course', this.courseid);
859 formData.append('section', sectionnumber);
860 formData.append('type', type);
861 formData.append('module', module);
862
863 // Send the data
864 xhr.open("POST", this.url, true);
865 xhr.send(formData);
866 },
867
868 /**
869 * Call the AJAX course editing initialisation to add the editing tools
870 * to the newly-created resource link
871 * @param elementid the id of the DOM element containing the new resource link
872 * @param sectionnumber the number of the selected course section
873 */
874 add_editing: function(elementid) {
875 YUI().use('moodle-course-coursebase', function(Y) {
876 M.course.coursebase.invoke_function('setup_for_resource', '#' + elementid);
877 });
878 }
879};