MDL-68344 filepicker: File Picker focus lost on upload
[moodle.git] / repository / filepicker.js
CommitLineData
99eaca9d
DC
1// YUI3 File Picker module for moodle
2// Author: Dongsheng Cai <dongsheng@moodle.com>
3
4/**
5 *
6 * File Picker UI
7 * =====
b5e7b638 8 * this.fpnode, contains reference to filepicker Node, non-empty if and only if rendered
99eaca9d 9 * this.api, stores the URL to make ajax request
99eaca9d 10 * this.mainui, YUI Panel
55089a9d 11 * this.selectnode, contains reference to select-file Node
b5e7b638
MG
12 * this.selectui, YUI Panel for selecting particular file
13 * this.msg_dlg, YUI Panel for error or info message
14 * this.process_dlg, YUI Panel for processing existing filename
99eaca9d 15 * this.treeview, YUI Treeview
99eaca9d 16 * this.viewmode, store current view mode
b5e7b638
MG
17 * this.pathbar, reference to the Node with path bar
18 * this.pathnode, a Node element representing one folder in a path bar (not attached anywhere, just used for template)
7dab27b3 19 * this.currentpath, the current path in the repository (or last requested path)
99eaca9d
DC
20 *
21 * Filepicker options:
22 * =====
99eaca9d
DC
23 * this.options.client_id, the instance id
24 * this.options.contextid
25 * this.options.itemid
fa4fb786 26 * this.options.repositories, stores all repositories displayed in file picker
99eaca9d
DC
27 * this.options.formcallback
28 *
29 * Active repository options
30 * =====
31 * this.active_repo.id
989e14fe 32 * this.active_repo.defaultreturntype
99eaca9d
DC
33 * this.active_repo.nosearch
34 * this.active_repo.norefresh
35 * this.active_repo.nologin
36 * this.active_repo.help
37 * this.active_repo.manage
8cbef19e 38 *
99eaca9d
DC
39 * Server responses
40 * =====
41 * this.filelist, cached filelist
42 * this.pages
43 * this.page
7dab27b3 44 * this.filepath, current path (each element of the array is a part of the breadcrumb)
99eaca9d
DC
45 * this.logindata, cached login form
46 */
47
e709ddd2
MG
48YUI.add('moodle-core_filepicker', function(Y) {
49 /** help function to extract width/height style as a number, not as a string */
50 Y.Node.prototype.getStylePx = function(attr) {
51 var style = this.getStyle(attr);
52 if (''+style == '0' || ''+style == '0px') {
53 return 0;
54 }
55 var matches = style.match(/^([\d\.]+)px$/)
56 if (matches && parseFloat(matches[1])) {
57 return parseFloat(matches[1]);
58 }
59 return null;
60 }
61
62 /** if condition is met, the class is added to the node, otherwise - removed */
63 Y.Node.prototype.addClassIf = function(className, condition) {
64 if (condition) {
65 this.addClass(className);
66 } else {
67 this.removeClass(className);
68 }
69 return this;
70 }
71
72 /** sets the width(height) of the node considering existing minWidth(minHeight) */
73 Y.Node.prototype.setStyleAdv = function(stylename, value) {
74 var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
75 this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
76 return this;
77 }
78
9213f547
MG
79 /** set image source to src, if there is preview, remember it in lazyloading.
80 * If there is a preview and it was already loaded, use it. */
81 Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
82 if (realsrc) {
83 if (M.core_filepicker.loadedpreviews[realsrc]) {
84 this.set('src', realsrc).addClass('realpreview');
85 return this;
86 } else {
87 if (!this.get('id')) {
88 this.generateID();
89 }
90 lazyloading[this.get('id')] = realsrc;
91 }
92 }
93 this.set('src', src);
94 return this;
95 }
96
97 /**
98 * Replaces the image source with preview. If the image is inside the treeview, we need
99 * also to update the html property of corresponding YAHOO.widget.HTMLNode
100 * @param array lazyloading array containing associations of imgnodeid->realsrc
101 */
102 Y.Node.prototype.setImgRealSrc = function(lazyloading) {
103 if (this.get('id') && lazyloading[this.get('id')]) {
104 var newsrc = lazyloading[this.get('id')];
105 M.core_filepicker.loadedpreviews[newsrc] = true;
106 this.set('src', newsrc).addClass('realpreview');
107 delete lazyloading[this.get('id')];
108 var treenode = this.ancestor('.fp-treeview')
109 if (treenode && treenode.get('parentNode').treeview) {
110 treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
111 }
112 }
113 return this;
114 }
115
116 /** scan TreeView to find which node contains image with id=imgid and replace it's html
117 * with the new image source. */
3b715c5f 118 Y.YUI2.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
9213f547
MG
119 if (!regex) {
120 regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
121 }
122 if (this.expanded || this.isLeaf) {
123 var html = this.getContentHtml();
124 if (html && this.setHtml && regex.test(html)) {
125 var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
126 this.setHtml(newhtml);
127 return true;
128 }
129 if (!this.isLeaf && this.children) {
130 for(var c in this.children) {
131 if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
132 return true;
133 }
134 }
135 }
136 }
137 return false;
138 }
139
e709ddd2
MG
140 /**
141 * Displays a list of files (used by filepicker, filemanager) inside the Node
142 *
143 * @param array options
144 * viewmode : 1 - icons, 2 - tree, 3 - table
145 * appendonly : whether fileslist need to be appended instead of replacing the existing content
146 * filenode : Node element that contains template for displaying one file
147 * callback : On click callback. The element of the fileslist array will be passed as argument
148 * rightclickcallback : On right click callback (optional).
149 * callbackcontext : context where callbacks are executed
150 * sortable : whether content may be sortable (in table mode)
151 * dynload : allow dynamic load for tree view
152 * filepath : for pre-building of tree view - the path to the current directory in filepicker format
6c2367cc
MG
153 * treeview_dynload : callback to function to dynamically load the folder in tree view
154 * classnamecallback : callback to function that returns the class name for an element
e709ddd2
MG
155 * @param array fileslist array of files to show, each array element may have attributes:
156 * title or fullname : file name
157 * shorttitle (optional) : display file name
158 * thumbnail : url of image
159 * icon : url of icon image
160 * thumbnail_width : width of thumbnail, default 90
161 * thumbnail_height : height of thumbnail, default 90
162 * thumbnail_alt : TODO not needed!
163 * description or thumbnail_title : alt text
164 * @param array lazyloading : reference to the array with lazy loading images
165 */
166 Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
167 var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
168 var classname = viewmodeclassnames[options.viewmode];
169 var scope = this;
170 /** return whether file is a folder (different attributes in FileManager and FilePicker) */
171 var file_is_folder = function(node) {
172 if (node.children) {return true;}
173 if (node.type && node.type == 'folder') {return true;}
174 return false;
175 };
176 /** return the name of the file (different attributes in FileManager and FilePicker) */
177 var file_get_filename = function(node) {
178 return node.title ? node.title : node.fullname;
954b3545 179 };
e709ddd2
MG
180 /** return display name of the file (different attributes in FileManager and FilePicker) */
181 var file_get_displayname = function(node) {
954b3545
FM
182 var displayname = node.shorttitle ? node.shorttitle : file_get_filename(node);
183 return Y.Escape.html(displayname);
184 };
e709ddd2
MG
185 /** return file description (different attributes in FileManager and FilePicker) */
186 var file_get_description = function(node) {
954b3545
FM
187 var description = '';
188 if (node.description) {
189 description = node.description;
190 } else if (node.thumbnail_title) {
191 description = node.thumbnail_title;
192 } else {
193 description = file_get_filename(node);
194 }
195 return Y.Escape.html(description);
196 };
e709ddd2
MG
197 /** help funciton for tree view */
198 var build_tree = function(node, level) {
199 // prepare file name with icon
200 var el = Y.Node.create('<div/>');
201 el.appendChild(options.filenode.cloneNode(true));
202
203 el.one('.fp-filename').setContent(file_get_displayname(node));
204 // TODO add tooltip with node.title or node.thumbnail_title
6c2367cc
MG
205 var tmpnodedata = {className:options.classnamecallback(node)};
206 el.get('children').addClass(tmpnodedata.className);
e709ddd2 207 if (node.icon) {
9213f547
MG
208 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
209 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
e709ddd2
MG
210 }
211 // create node
23b83009 212 tmpnodedata.html = el.getContent();
3b715c5f 213 var tmpNode = new Y.YUI2.widget.HTMLNode(tmpnodedata, level, false);
e709ddd2
MG
214 if (node.dynamicLoadComplete) {
215 tmpNode.dynamicLoadComplete = true;
216 }
217 tmpNode.fileinfo = node;
218 tmpNode.isLeaf = !file_is_folder(node);
219 if (!tmpNode.isLeaf) {
220 if(node.expanded) {
221 tmpNode.expand();
222 }
223 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
224 for(var c in node.children) {
225 build_tree(node.children[c], tmpNode);
226 }
227 }
228 };
229 /** initialize tree view */
230 var initialize_tree_view = function() {
231 var parentid = scope.one('.'+classname).get('id');
23b83009 232 // TODO MDL-32736 use YUI3 gallery TreeView
3b715c5f 233 scope.treeview = new Y.YUI2.widget.TreeView(parentid);
e709ddd2
MG
234 if (options.dynload) {
235 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
236 }
237 scope.treeview.singleNodeHighlight = true;
238 if (options.filepath && options.filepath.length) {
239 // we just jumped from icon/details view, we need to show all parents
240 // we extract as much information as possible from filepath and filelist
241 // and send additional requests to retrieve siblings for parent folders
242 var mytree = {};
243 var mytreeel = null;
244 for (var i in options.filepath) {
245 if (mytreeel == null) {
246 mytreeel = mytree;
247 } else {
248 mytreeel.children = [{}];
249 mytreeel = mytreeel.children[0];
250 }
251 var pathelement = options.filepath[i];
252 mytreeel.path = pathelement.path;
253 mytreeel.title = pathelement.name;
9213f547 254 mytreeel.icon = pathelement.icon;
e709ddd2
MG
255 mytreeel.dynamicLoadComplete = true; // we will call it manually
256 mytreeel.expanded = true;
257 }
258 mytreeel.children = fileslist;
259 build_tree(mytree, scope.treeview.getRoot());
260 // manually call dynload for parent elements in the tree so we can load other siblings
261 if (options.dynload) {
262 var root = scope.treeview.getRoot();
5e62e4b2
MG
263 // Whether search results are currently displayed in the active repository in the filepicker.
264 // We do not want to load siblings of parent elements when displaying search tree results.
265 var isSearchResult = typeof options.callbackcontext.active_repo !== 'undefined' &&
266 options.callbackcontext.active_repo.issearchresult;
e709ddd2
MG
267 while (root && root.children && root.children.length) {
268 root = root.children[0];
269 if (root.path == mytreeel.path) {
270 root.origpath = options.filepath;
271 root.origlist = fileslist;
5e62e4b2
MG
272 } else if (!root.isLeaf && root.expanded && !isSearchResult) {
273 Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
e709ddd2
MG
274 }
275 }
276 }
277 } else {
278 // there is no path information, just display all elements as a list, without hierarchy
279 for(k in fileslist) {
280 build_tree(fileslist[k], scope.treeview.getRoot());
281 }
282 }
283 scope.treeview.subscribe('clickEvent', function(e){
284 e.node.highlight(false);
23b83009
MG
285 var callback = options.callback;
286 if (options.rightclickcallback && e.event.target &&
287 Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
288 callback = options.rightclickcallback;
289 }
290 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
3b715c5f 291 Y.YUI2.util.Event.stopEvent(e.event)
e709ddd2 292 });
23b83009
MG
293 // TODO MDL-32736 support right click
294 /*if (options.rightclickcallback) {
295 scope.treeview.subscribe('dblClickEvent', function(e){
e709ddd2 296 e.node.highlight(false);
23b83009 297 Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
e709ddd2 298 });
23b83009 299 }*/
e709ddd2
MG
300 scope.treeview.draw();
301 };
302 /** formatting function for table view */
303 var formatValue = function (o){
304 if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
305 else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
306 else if (o.value) {return o.value;}
307 else {return '';}
308 };
309 /** formatting function for table view */
310 var formatTitle = function(o) {
311 var el = Y.Node.create('<div/>');
312 el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
6c2367cc 313 el.get('children').addClass(o.data['classname']);
e709ddd2
MG
314 el.one('.fp-filename').setContent(o.value);
315 if (o.data['icon']) {
9213f547
MG
316 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
317 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
e709ddd2 318 }
23b83009
MG
319 if (options.rightclickcallback) {
320 el.get('children').addClass('fp-hascontextmenu');
321 }
e709ddd2
MG
322 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
323 return el.getContent();
324 }
a216d86c
P
325
326 /**
327 * Generate slave checkboxes based on toggleall's specification
328 * @param {object} o An object reprsenting the record for the current row.
329 * @return {html} The checkbox html
330 */
2f039236
P
331 var formatCheckbox = function(o) {
332 var el = Y.Node.create('<div/>');
06dc3a6c
PD
333
334 var checkbox = Y.Node.create('<input/>')
335 .setAttribute('type', 'checkbox')
336 .setAttribute('data-fieldtype', 'checkbox')
a216d86c
P
337 .setAttribute('data-fullname', o.data.fullname)
338 .setAttribute('data-action', 'toggle')
339 .setAttribute('data-toggle', 'slave')
340 .setAttribute('data-togglegroup', 'file-selections')
06dc3a6c
PD
341 .setAttribute('data-toggle-selectall', M.util.get_string('selectall', 'moodle'))
342 .setAttribute('data-toggle-deselectall', M.util.get_string('deselectall', 'moodle'));
343
344 var checkboxLabel = Y.Node.create('<label>')
345 .setHTML("Select file '" + o.data.fullname + "'")
346 .addClass('sr-only')
347 .setAttrs({
348 for: checkbox.generateID(),
349 });
2f039236
P
350
351 el.appendChild(checkbox);
06dc3a6c 352 el.appendChild(checkboxLabel);
2f039236
P
353 return el.getContent();
354 };
e709ddd2
MG
355 /** sorting function for table view */
356 var sortFoldersFirst = function(a, b, desc) {
6a0d7194
DP
357 if (a.get('isfolder') && !b.get('isfolder')) {
358 return -1;
359 }
360 if (!a.get('isfolder') && b.get('isfolder')) {
361 return 1;
362 }
363 var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
e709ddd2
MG
364 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
365 }
366 /** initialize table view */
367 var initialize_table_view = function() {
e709ddd2 368 var cols = [
64e7aa4d 369 {key: "displayname", label: M.util.get_string('name', 'moodle'), allowHTML: true, formatter: formatTitle,
e709ddd2 370 sortable: true, sortFn: sortFoldersFirst},
64e7aa4d 371 {key: "datemodified", label: M.util.get_string('lastmodified', 'moodle'), allowHTML: true, formatter: formatValue,
e709ddd2 372 sortable: true, sortFn: sortFoldersFirst},
64e7aa4d 373 {key: "size", label: M.util.get_string('size', 'repository'), allowHTML: true, formatter: formatValue,
e709ddd2 374 sortable: true, sortFn: sortFoldersFirst},
64e7aa4d 375 {key: "mimetype", label: M.util.get_string('type', 'repository'), allowHTML: true,
e709ddd2
MG
376 sortable: true, sortFn: sortFoldersFirst}
377 ];
5c567c14 378
a216d86c 379 // Generate a checkbox based on toggleall's specification
a216d86c 380 var div = Y.Node.create('<div/>');
06dc3a6c
PD
381 var checkbox = Y.Node.create('<input/>')
382 .setAttribute('type', 'checkbox')
383 // .setAttribute('title', M.util.get_string('selectallornone', 'form'))
a216d86c
P
384 .setAttribute('data-action', 'toggle')
385 .setAttribute('data-toggle', 'master')
386 .setAttribute('data-togglegroup', 'file-selections');
06dc3a6c
PD
387
388 var checkboxLabel = Y.Node.create('<label>')
389 .setHTML(M.util.get_string('selectallornone', 'form'))
390 .addClass('sr-only')
391 .setAttrs({
392 for: checkbox.generateID(),
393 });
394
395 div.appendChild(checkboxLabel);
a216d86c
P
396 div.appendChild(checkbox);
397
1de1fc58
MG
398 // Define the selector for the click event handler.
399 var clickEventSelector = 'tr';
5c567c14
P
400 // Enable the selectable checkboxes
401 if (options.disablecheckboxes != undefined && !options.disablecheckboxes) {
1de1fc58 402 clickEventSelector = 'tr td:not(:first-child)';
5c567c14 403 cols.unshift({
06dc3a6c
PD
404 key: "",
405 label: div.getContent(),
406 allowHTML: true,
407 formatter: formatCheckbox,
5c567c14
P
408 sortable: false
409 });
410 }
80d92db9 411 scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
e709ddd2
MG
412 scope.tableview.delegate('click', function (e, tableview) {
413 var record = tableview.getRecord(e.currentTarget.get('id'));
23b83009
MG
414 if (record) {
415 var callback = options.callback;
416 if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
417 callback = options.rightclickcallback;
418 }
419 Y.bind(callback, this)(e, record.getAttrs());
420 }
1de1fc58 421 }, clickEventSelector, options.callbackcontext, scope.tableview);
a216d86c 422
e709ddd2
MG
423 if (options.rightclickcallback) {
424 scope.tableview.delegate('contextmenu', function (e, tableview) {
425 var record = tableview.getRecord(e.currentTarget.get('id'));
426 if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
427 }, 'tr', options.callbackcontext, scope.tableview);
428 }
429 }
430 /** append items in table view mode */
431 var append_files_table = function() {
1c027ffa
FW
432 if (options.appendonly) {
433 fileslist.forEach(function(el) {
434 this.tableview.data.add(el);
435 },scope);
436 }
437 scope.tableview.render(scope.one('.'+classname));
e709ddd2
MG
438 scope.tableview.sortable = options.sortable ? true : false;
439 };
440 /** append items in tree view mode */
441 var append_files_tree = function() {
442 if (options.appendonly) {
443 var parentnode = scope.treeview.getRoot();
444 if (scope.treeview.getHighlightedNode()) {
445 parentnode = scope.treeview.getHighlightedNode();
446 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
447 }
448 for (var k in fileslist) {
449 build_tree(fileslist[k], parentnode);
450 }
451 scope.treeview.draw();
452 } else {
453 // otherwise files were already added in initialize_tree_view()
454 }
455 }
456 /** append items in icon view mode */
457 var append_files_icons = function() {
458 parent = scope.one('.'+classname);
459 for (var k in fileslist) {
460 var node = fileslist[k];
461 var element = options.filenode.cloneNode(true);
462 parent.appendChild(element);
6c2367cc 463 element.addClass(options.classnamecallback(node));
e709ddd2
MG
464 var filenamediv = element.one('.fp-filename');
465 filenamediv.setContent(file_get_displayname(node));
466 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
467 if (node.thumbnail) {
468 width = node.thumbnail_width ? node.thumbnail_width : 90;
469 height = node.thumbnail_height ? node.thumbnail_height : 90;
470 src = node.thumbnail;
471 } else {
472 width = 16;
473 height = 16;
474 src = node.icon;
475 }
476 filenamediv.setStyleAdv('width', width);
477 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
478 var img = Y.Node.create('<img/>').setAttrs({
e709ddd2 479 title: file_get_description(node),
954b3545 480 alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}).
e709ddd2
MG
481 setStyle('maxWidth', ''+width+'px').
482 setStyle('maxHeight', ''+height+'px');
9213f547 483 img.setImgSrc(src, node.realthumbnail, lazyloading);
e709ddd2 484 imgdiv.appendChild(img);
23b83009
MG
485 element.on('click', function(e, nd) {
486 if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
487 Y.bind(options.rightclickcallback, this)(e, nd);
488 } else {
489 Y.bind(options.callback, this)(e, nd);
490 }
491 }, options.callbackcontext, node);
e709ddd2
MG
492 if (options.rightclickcallback) {
493 element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
494 }
495 }
496 }
497
7a170fad
JD
498 // Notify the user if any of the files has a problem status.
499 var problemFiles = [];
500 fileslist.forEach(function(file) {
501 if (!file_is_folder(file) && file.hasOwnProperty('status') && file.status != 0) {
502 problemFiles.push(file);
503 }
504 });
505 if (problemFiles.length > 0) {
506 require(["core/notification", "core/str"], function(Notification, Str) {
507 problemFiles.forEach(function(problemFile) {
508 Str.get_string('storedfilecannotreadfile', 'error', problemFile.fullname).then(function(string) {
509 Notification.addNotification({
510 message: string,
511 type: "error"
512 });
513 return;
514 }).catch(Notification.exception);
515 });
516 });
517 }
518
1c027ffa
FW
519 // If table view, need some additional properties
520 // before passing fileslist to the YUI tableview
521 if (options.viewmode == 3) {
522 fileslist.forEach(function(el) {
523 el.displayname = file_get_displayname(el);
524 el.isfolder = file_is_folder(el);
525 el.classname = options.classnamecallback(el);
526 }, scope);
527 }
528
e709ddd2
MG
529 // initialize files view
530 if (!options.appendonly) {
531 var parent = Y.Node.create('<div/>').addClass(classname);
532 this.setContent('').appendChild(parent);
533 parent.generateID();
534 if (options.viewmode == 2) {
535 initialize_tree_view();
536 } else if (options.viewmode == 3) {
537 initialize_table_view();
538 } else {
539 // nothing to initialize for icon view
540 }
541 }
542
543 // append files to the list
544 if (options.viewmode == 2) {
545 append_files_tree();
546 } else if (options.viewmode == 3) {
547 append_files_table();
548 } else {
549 append_files_icons();
550 }
551
552 }
553}, '@VERSION@', {
4325db53 554 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
e709ddd2
MG
555});
556
4c508047 557M.core_filepicker = M.core_filepicker || {};
99eaca9d 558
4c508047
PS
559/**
560 * instances of file pickers used on page
561 */
562M.core_filepicker.instances = M.core_filepicker.instances || {};
539d4041 563M.core_filepicker.active_filepicker = null;
4c508047 564
b5e7b638
MG
565/**
566 * HTML Templates to use in FilePicker
567 */
568M.core_filepicker.templates = M.core_filepicker.templates || {};
569
9213f547
MG
570/**
571 * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
572 */
573M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
574
5cf44c1f
MG
575/**
576* Set selected file info
577*
50900389 578* @param object file info
5cf44c1f
MG
579*/
580M.core_filepicker.select_file = function(file) {
581 M.core_filepicker.active_filepicker.select_file(file);
582}
583
4c508047
PS
584/**
585 * Init and show file picker
586 */
587M.core_filepicker.show = function(Y, options) {
588 if (!M.core_filepicker.instances[options.client_id]) {
8cbef19e 589 M.core_filepicker.init(Y, options);
99eaca9d 590 }
a60a98d9 591 M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback;
4c508047
PS
592 M.core_filepicker.instances[options.client_id].show();
593};
594
d1d18691
MG
595M.core_filepicker.set_templates = function(Y, templates) {
596 for (var templid in templates) {
597 M.core_filepicker.templates[templid] = templates[templid];
598 }
599}
b92241f2 600
4c508047
PS
601/**
602 * Add new file picker to current instances
603 */
604M.core_filepicker.init = function(Y, options) {
605 var FilePickerHelper = function(options) {
606 FilePickerHelper.superclass.constructor.apply(this, arguments);
8cbef19e 607 };
4c508047
PS
608
609 FilePickerHelper.NAME = "FilePickerHelper";
610 FilePickerHelper.ATTRS = {
99eaca9d
DC
611 options: {},
612 lang: {}
613 };
4c508047
PS
614
615 Y.extend(FilePickerHelper, Y.Base, {
9598d578 616 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
7f9358fc 617 cached_responses: {},
2e7ce603 618 waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
4c508047
PS
619 initializer: function(options) {
620 this.options = options;
392d5fd4
DC
621 if (!this.options.savepath) {
622 this.options.savepath = '/';
623 }
99eaca9d 624 },
4c508047 625
99eaca9d
DC
626 destructor: function() {
627 },
4c508047 628
99eaca9d 629 request: function(args, redraw) {
6a0d7194 630 var api = (args.api ? args.api : this.api) + '?action='+args.action;
99eaca9d 631 var params = {};
6a0d7194 632 var scope = args['scope'] ? args['scope'] : this;
99eaca9d
DC
633 params['repo_id']=args.repository_id;
634 params['p'] = args.path?args.path:'';
635 params['page'] = args.page?args.page:'';
636 params['env']=this.options.env;
637 // the form element only accept certain file types
638 params['accepted_types']=this.options.accepted_types;
e35194be 639 params['sesskey'] = M.cfg.sesskey;
99eaca9d 640 params['client_id'] = args.client_id;
0c4edaa2 641 params['itemid'] = this.options.itemid?this.options.itemid:0;
8a3e6a56 642 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
68acd115 643 // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
21e3ea77 644 params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
be85f7ab
DC
645 if (this.options.context && this.options.context.id) {
646 params['ctx_id'] = this.options.context.id;
647 }
99eaca9d
DC
648 if (args['params']) {
649 for (i in args['params']) {
650 params[i] = args['params'][i];
651 }
652 }
64654e78
DC
653 if (args.action == 'upload') {
654 var list = [];
655 for(var k in params) {
656 var value = params[k];
657 if(value instanceof Array) {
658 for(var i in value) {
659 list.push(k+'[]='+value[i]);
660 }
661 } else {
662 list.push(k+'='+value);
663 }
664 }
665 params = list.join('&');
666 } else {
667 params = build_querystring(params);
668 }
99eaca9d
DC
669 var cfg = {
670 method: 'POST',
671 on: {
672 complete: function(id,o,p) {
4c508047
PS
673 var data = null;
674 try {
675 data = Y.JSON.parse(o.responseText);
676 } catch(e) {
5329506f
AN
677 if (o && o.status && o.status > 0) {
678 Y.use('moodle-core-notification-exception', function() {
679 return new M.core.exception(e);
680 });
681 return;
682 }
4c508047 683 }
1dce6261 684 // error checking
e35194be 685 if (data && data.error) {
0e7367a5 686 Y.use('moodle-core-notification-ajaxexception', function () {
5329506f
AN
687 return new M.core.ajaxException(data);
688 });
689 this.fpnode.one('.fp-content').setContent('');
1dce6261
DC
690 return;
691 } else {
879b4f9a
DC
692 if (data.msg) {
693 scope.print_msg(data.msg, 'info');
694 }
7f9358fc
MG
695 // cache result if applicable
696 if (args.action != 'upload' && data.allowcaching) {
697 scope.cached_responses[params] = data;
698 }
699 // invoke callback
1dce6261
DC
700 args.callback(id,data,p);
701 }
99eaca9d
DC
702 }
703 },
704 arguments: {
705 scope: scope
706 },
707 headers: {
bd2db41a 708 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
99eaca9d 709 },
64654e78 710 data: params,
4c508047 711 context: this
99eaca9d
DC
712 };
713 if (args.form) {
714 cfg.form = args.form;
715 }
7f9358fc
MG
716 // check if result of the same request has been already cached. If not, request it
717 // (never applicable in case of form submission and/or upload action):
718 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
719 args.callback(null, scope.cached_responses[params], {scope: scope})
720 } else {
721 Y.io(api, cfg);
722 if (redraw) {
b5e7b638 723 this.wait();
7f9358fc 724 }
99eaca9d
DC
725 }
726 },
b5e7b638 727 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
f392caba
DC
728 process_existing_file: function(data) {
729 var scope = this;
b5e7b638 730 var handleOverwrite = function(e) {
f392caba 731 // overwrite
b5e7b638
MG
732 e.preventDefault();
733 var data = this.process_dlg.dialogdata;
f392caba
DC
734 var params = {}
735 params['existingfilename'] = data.existingfile.filename;
736 params['existingfilepath'] = data.existingfile.filepath;
737 params['newfilename'] = data.newfile.filename;
738 params['newfilepath'] = data.newfile.filepath;
b5e7b638
MG
739 this.hide_header();
740 this.request({
f392caba 741 'params': params,
b5e7b638 742 'scope': this,
f392caba
DC
743 'action':'overwrite',
744 'path': '',
b5e7b638
MG
745 'client_id': this.options.client_id,
746 'repository_id': this.active_repo.id,
f392caba 747 'callback': function(id, o, args) {
f392caba 748 scope.hide();
4dbc8c30 749 // Add an arbitrary parameter to the URL to force browsers to re-load the new image even
750 // if the file name has not changed.
751 var urlimage = data.existingfile.url + "?time=" + (new Date()).getTime();
c8ad2c12 752 if (scope.options.editor_target && scope.options.env == 'editor') {
c9b4b8d8 753 // editor needs to update url
4dbc8c30 754 scope.options.editor_target.value = urlimage;
5b54a1c7 755 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
f392caba 756 }
c9b4b8d8 757 var fileinfo = {'client_id':scope.options.client_id,
4dbc8c30 758 'url': urlimage,
759 'file': data.existingfile.filename};
c9b4b8d8
MG
760 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
761 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
f392caba
DC
762 }
763 }, true);
764 }
b5e7b638
MG
765 var handleRename = function(e) {
766 // inserts file with the new name
767 e.preventDefault();
768 var scope = this;
769 var data = this.process_dlg.dialogdata;
c8ad2c12
SH
770 if (scope.options.editor_target && scope.options.env == 'editor') {
771 scope.options.editor_target.value = data.newfile.url;
5b54a1c7 772 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
f392caba 773 }
f392caba 774 scope.hide();
dd1f051e 775 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
b5e7b638 776 var fileinfo = {'client_id':scope.options.client_id,
794cc7e1
JP
777 'url':data.newfile.url,
778 'file':data.newfile.filename};
779 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
f392caba 780 }
b5e7b638 781 var handleCancel = function(e) {
f392caba 782 // Delete tmp file
b5e7b638 783 e.preventDefault();
f392caba 784 var params = {};
b5e7b638
MG
785 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
786 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
787 this.request({
f392caba 788 'params': params,
b5e7b638 789 'scope': this,
f392caba
DC
790 'action':'deletetmpfile',
791 'path': '',
b5e7b638
MG
792 'client_id': this.options.client_id,
793 'repository_id': this.active_repo.id,
f392caba 794 'callback': function(id, o, args) {
b5e7b638 795 // let it be in background, from user point of view nothing is happenning
f392caba 796 }
b5e7b638
MG
797 }, false);
798 this.process_dlg.hide();
799 this.selectui.hide();
f392caba 800 }
b5e7b638 801 if (!this.process_dlg) {
88af0208 802 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
dd1f051e
MG
803 var node = this.process_dlg_node;
804 node.generateID();
d61c96b6
DW
805 this.process_dlg = new M.core.dialogue({
806 draggable : true,
fd782261 807 bodyContent : node,
64e7aa4d 808 headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
b5e7b638
MG
809 centered : true,
810 modal : true,
811 visible : false,
bf7c86cf 812 zIndex : this.options.zIndex
b5e7b638
MG
813 });
814 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
815 node.one('.fp-dlg-butrename').on('click', handleRename, this);
816 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
817 if (this.options.env == 'editor') {
64e7aa4d 818 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository'));
b5e7b638 819 } else {
64e7aa4d 820 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository'));
b5e7b638 821 }
f392caba 822 }
55089a9d 823 this.selectnode.removeClass('loading');
b5e7b638 824 this.process_dlg.dialogdata = data;
dd1f051e 825 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
b5e7b638
MG
826 this.process_dlg.show();
827 },
828 /** displays error instead of filepicker contents */
829 display_error: function(errortext, errorcode) {
830 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
831 this.fpnode.one('.fp-content .fp-error').
832 addClass(errorcode).
954b3545 833 setContent(Y.Escape.html(errortext));
f392caba 834 },
b5e7b638 835 /** displays message in a popup */
879b4f9a 836 print_msg: function(msg, type) {
64e7aa4d 837 var header = M.util.get_string('error', 'moodle');
b5e7b638
MG
838 if (type != 'error') {
839 type = 'info'; // one of only two types excepted
64e7aa4d 840 header = M.util.get_string('info', 'moodle');
879b4f9a
DC
841 }
842 if (!this.msg_dlg) {
88af0208 843 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
dd1f051e 844 this.msg_dlg_node.generateID();
b5e7b638 845
d61c96b6
DW
846 this.msg_dlg = new M.core.dialogue({
847 draggable : true,
bf7c86cf 848 bodyContent : this.msg_dlg_node,
b5e7b638
MG
849 centered : true,
850 modal : true,
bf7c86cf
DW
851 visible : false,
852 zIndex : this.options.zIndex
b5e7b638 853 });
dd1f051e 854 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
b5e7b638
MG
855 e.preventDefault();
856 this.msg_dlg.hide();
857 }, this);
879b4f9a 858 }
b5e7b638
MG
859
860 this.msg_dlg.set('headerContent', header);
dd1f051e 861 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
954b3545 862 this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
879b4f9a 863 this.msg_dlg.show();
879b4f9a 864 },
7ccf18a6 865 view_files: function(appenditems) {
b92241f2
MG
866 this.viewbar_set_enabled(true);
867 this.print_path();
e709ddd2
MG
868 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
869 // TODO do it via classes and adjust for each view mode!
870 // If there are no items and no next page, just display status message and quit
64e7aa4d 871 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
e709ddd2
MG
872 return;
873 }*/
b92241f2 874 if (this.viewmode == 2) {
7ccf18a6 875 this.view_as_list(appenditems);
b92241f2 876 } else if (this.viewmode == 3) {
7ccf18a6 877 this.view_as_table(appenditems);
99eaca9d 878 } else {
7ccf18a6
MG
879 this.view_as_icons(appenditems);
880 }
3f0d3a7e 881 this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
3f0d3a7e 882 this.fpnode.one('.fp-content').focus();
7ccf18a6
MG
883 // display/hide the link for requesting next page
884 if (!appenditems && this.active_repo.hasmorepages) {
885 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
886 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
887 }
888 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
889 e.preventDefault();
890 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
891 this.request_next_page();
892 }, this);
893 }
894 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
895 this.fpnode.one('.fp-content .fp-nextpage').remove();
896 }
897 if (this.fpnode.one('.fp-content .fp-nextpage')) {
898 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
99eaca9d 899 }
ce3eeb98
MG
900 this.content_scrolled();
901 },
902 content_scrolled: function(e) {
903 setTimeout(Y.bind(function() {
6a0d7194
DP
904 if (this.processingimages) {
905 return;
906 }
ce3eeb98
MG
907 this.processingimages = true;
908 var scope = this,
909 fpcontent = this.fpnode.one('.fp-content'),
910 fpcontenty = fpcontent.getY(),
911 fpcontentheight = fpcontent.getStylePx('height'),
912 nextpage = fpcontent.one('.fp-nextpage'),
913 is_node_visible = function(node) {
914 var offset = node.getY()-fpcontenty;
915 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
916 return true;
917 }
918 return false;
919 };
920 // automatically load next page when 'more' link becomes visible
921 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
922 nextpage.one('a,button').simulate('click');
923 }
924 // replace src for visible images that need to be lazy-loaded
925 if (scope.lazyloading) {
926 fpcontent.all('img').each( function(node) {
927 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
9213f547 928 node.setImgRealSrc(scope.lazyloading);
ce3eeb98
MG
929 }
930 });
931 }
932 this.processingimages = false;
933 }, this), 200)
99eaca9d 934 },
1fb0173e 935 treeview_dynload: function(node, cb) {
2f6749f4
MG
936 var retrieved_children = {};
937 if (node.children) {
938 for (var i in node.children) {
939 retrieved_children[node.children[i].path] = node.children[i];
940 }
941 }
e709ddd2 942 this.request({
1fb0173e 943 action:'list',
e709ddd2
MG
944 client_id: this.options.client_id,
945 repository_id: this.active_repo.id,
1fb0173e
DC
946 path:node.path?node.path:'',
947 page:node.page?args.page:'',
e709ddd2 948 scope:this,
1fb0173e 949 callback: function(id, obj, args) {
1fb0173e 950 var list = obj.list;
e709ddd2 951 var scope = args.scope;
2f6749f4
MG
952 // check that user did not leave the view mode before recieving this response
953 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
954 return;
955 }
956 if (cb != null) { // (in manual mode do not update current path)
957 scope.viewbar_set_enabled(true);
958 scope.parse_repository_options(obj);
959 }
e709ddd2 960 node.highlight(false);
6a0d7194
DP
961 node.origlist = obj.list ? obj.list : null;
962 node.origpath = obj.path ? obj.path : null;
2f6749f4 963 node.children = [];
1fb0173e 964 for(k in list) {
2f6749f4
MG
965 if (list[k].children && retrieved_children[list[k].path]) {
966 // if this child is a folder and has already been retrieved
967 node.children[node.children.length] = retrieved_children[list[k].path];
968 } else {
e709ddd2
MG
969 // append new file to the list
970 scope.view_as_list([list[k]]);
2f6749f4
MG
971 }
972 }
973 if (cb == null) {
974 node.refresh();
975 } else {
e709ddd2 976 // invoke callback requested by TreeView component
2f6749f4 977 cb();
1fb0173e 978 }
ce3eeb98 979 scope.content_scrolled();
1fb0173e
DC
980 }
981 }, false);
982 },
1778f310
MG
983 classnamecallback : function(node) {
984 var classname = '';
985 if (node.children) {
986 classname = classname + ' fp-folder';
987 }
988 if (node.isref) {
989 classname = classname + ' fp-isreference';
990 }
151b0f94
DW
991 if (node.iscontrolledlink) {
992 classname = classname + ' fp-iscontrolledlink';
993 }
1778f310
MG
994 if (node.refcount) {
995 classname = classname + ' fp-hasreferences';
996 }
997 if (node.originalmissing) {
998 classname = classname + ' fp-originalmissing';
999 }
1000 return Y.Lang.trim(classname);
1001 },
7ccf18a6
MG
1002 /** displays list of files in tree (list) view mode. If param appenditems is specified,
1003 * appends those items to the end of the list. Otherwise (default behaviour)
1004 * clears the contents and displays the items from this.filelist */
1005 view_as_list: function(appenditems) {
e709ddd2
MG
1006 var list = (appenditems != null) ? appenditems : this.filelist;
1007 this.viewmode = 2;
1008 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
64e7aa4d 1009 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
4adecd7b
MG
1010 return;
1011 }
879b4f9a 1012
e709ddd2
MG
1013 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1014 var options = {
1015 viewmode : this.viewmode,
1016 appendonly : (appenditems != null),
1017 filenode : element_template,
1018 callbackcontext : this,
1019 callback : function(e, node) {
23b83009 1020 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
e709ddd2
MG
1021 if (!node.children) {
1022 if (e.node.parent && e.node.parent.origpath) {
1023 // set the current path
1024 this.filepath = e.node.parent.origpath;
1025 this.filelist = e.node.parent.origlist;
1026 this.print_path();
2f6749f4 1027 }
e709ddd2
MG
1028 this.select_file(node);
1029 } else {
1030 // save current path and filelist (in case we want to jump to other viewmode)
1031 this.filepath = e.node.origpath;
1032 this.filelist = e.node.origlist;
7dab27b3 1033 this.currentpath = e.node.path;
e709ddd2
MG
1034 this.print_path();
1035 this.content_scrolled();
2f6749f4 1036 }
e709ddd2 1037 },
1778f310 1038 classnamecallback : this.classnamecallback,
e709ddd2
MG
1039 dynload : this.active_repo.dynload,
1040 filepath : this.filepath,
1041 treeview_dynload : this.treeview_dynload
1042 };
1043 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
99eaca9d 1044 },
7ccf18a6
MG
1045 /** displays list of files in icon view mode. If param appenditems is specified,
1046 * appends those items to the end of the list. Otherwise (default behaviour)
1047 * clears the contents and displays the items from this.filelist */
1048 view_as_icons: function(appenditems) {
99eaca9d 1049 this.viewmode = 1;
e709ddd2
MG
1050 var list = (appenditems != null) ? appenditems : this.filelist;
1051 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
1052 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
64e7aa4d 1053 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
e709ddd2 1054 return;
879b4f9a 1055 }
e709ddd2
MG
1056 var options = {
1057 viewmode : this.viewmode,
1058 appendonly : (appenditems != null),
1059 filenode : element_template,
1060 callbackcontext : this,
1061 callback : function(e, node) {
6a0d7194
DP
1062 if (e.preventDefault) {
1063 e.preventDefault();
1064 }
e709ddd2
MG
1065 if(node.children) {
1066 if (this.active_repo.dynload) {
1067 this.list({'path':node.path});
1068 } else {
e709ddd2 1069 this.filelist = node.children;
99eaca9d
DC
1070 this.view_files();
1071 }
e709ddd2
MG
1072 } else {
1073 this.select_file(node);
1074 }
6c2367cc 1075 },
1778f310 1076 classnamecallback : this.classnamecallback
e709ddd2
MG
1077 };
1078 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
99eaca9d 1079 },
7ccf18a6
MG
1080 /** displays list of files in table view mode. If param appenditems is specified,
1081 * appends those items to the end of the list. Otherwise (default behaviour)
1082 * clears the contents and displays the items from this.filelist */
1083 view_as_table: function(appenditems) {
5bdf63cc 1084 this.viewmode = 3;
e709ddd2
MG
1085 var list = (appenditems != null) ? appenditems : this.filelist;
1086 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
64e7aa4d 1087 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
5bdf63cc
MG
1088 return;
1089 }
e709ddd2
MG
1090 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1091 var options = {
1092 viewmode : this.viewmode,
1093 appendonly : (appenditems != null),
1094 filenode : element_template,
1095 callbackcontext : this,
1096 sortable : !this.active_repo.hasmorepages,
1097 callback : function(e, node) {
23b83009 1098 if (e.preventDefault) {e.preventDefault();}
e709ddd2 1099 if (node.children) {
7ccf18a6 1100 if (this.active_repo.dynload) {
e709ddd2 1101 this.list({'path':node.path});
7ccf18a6 1102 } else {
e709ddd2 1103 this.filelist = node.children;
7ccf18a6 1104 this.view_files();
5bdf63cc 1105 }
7ccf18a6 1106 } else {
e709ddd2 1107 this.select_file(node);
5bdf63cc 1108 }
6c2367cc 1109 },
1778f310 1110 classnamecallback : this.classnamecallback
e709ddd2
MG
1111 };
1112 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
7ccf18a6
MG
1113 },
1114 /** If more than one page available, requests and displays the files from the next page */
1115 request_next_page: function() {
1116 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1117 // nothing to load
1118 return;
1119 }
1120 this.active_repo.nextpagerequested = true;
1121 var nextpage = this.active_repo.page+1;
7dab27b3
FM
1122 var args = {
1123 page: nextpage,
e13b330d 1124 repo_id: this.active_repo.id
7dab27b3 1125 };
7ccf18a6
MG
1126 var action = this.active_repo.issearchresult ? 'search' : 'list';
1127 this.request({
7dab27b3 1128 path: this.currentpath,
7ccf18a6
MG
1129 scope: this,
1130 action: action,
1131 client_id: this.options.client_id,
1132 repository_id: args.repo_id,
1133 params: args,
1134 callback: function(id, obj, args) {
1135 var scope = args.scope;
7dab27b3
FM
1136 // Check that we are still in the same repository and are expecting this page. We have no way
1137 // to compare the requested page and the one returned, so we assume that if the last chunk
1138 // of the breadcrumb is similar, then we probably are on the same page.
1139 var samepage = true;
1140 if (obj.path && scope.filepath) {
1141 var pathbefore = scope.filepath[scope.filepath.length-1];
1142 var pathafter = obj.path[obj.path.length-1];
1143 if (pathbefore.path != pathafter.path) {
1144 samepage = false;
1145 }
1146 }
7ccf18a6
MG
1147 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1148 obj.repo_id == scope.active_repo.id &&
7dab27b3 1149 obj.page == scope.active_repo.page+1 && samepage) {
7ccf18a6
MG
1150 scope.parse_repository_options(obj, true);
1151 scope.view_files(obj.list)
1152 }
1153 }
1154 }, false);
5bdf63cc 1155 },
99eaca9d 1156 select_file: function(args) {
67e3378c 1157 var argstitle = args.shorttitle ? args.shorttitle : args.title;
0a5c86dd 1158 // Limit the string length so it fits nicely on mobile devices
d8817b4a 1159 var titlelength = 30;
0a5c86dd
RW
1160 if (argstitle.length > titlelength) {
1161 argstitle = argstitle.substring(0, titlelength) + '...';
1162 }
64e7aa4d 1163 Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.util.get_string('select', 'repository')+' '+argstitle));
b5e7b638 1164 this.selectui.show();
f2e4da68 1165 Y.one('#'+this.selectnode.get('id')).focus();
99eaca9d 1166 var client_id = this.options.client_id;
55089a9d 1167 var selectnode = this.selectnode;
b92241f2 1168 var return_types = this.options.repositories[this.active_repo.id].return_types;
3a1e425b 1169 selectnode.removeClass('loading');
b92241f2 1170 selectnode.one('.fp-saveas input').set('value', args.title);
99eaca9d 1171
ce3eeb98
MG
1172 var imgnode = Y.Node.create('<img/>').
1173 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1174 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1175 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
b92241f2 1176 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
b5e7b638 1177
5cf44c1f 1178 // filelink is the array of file-link-types available for this repository in this env
151b0f94 1179 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/,8/*FILE_CONTROLLED_LINK*/];
5cf44c1f
MG
1180 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1181 for (var i in filelinktypes) {
1182 var allowed = (return_types & filelinktypes[i]) &&
1183 (this.options.return_types & filelinktypes[i]);
1184 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1185 // special configuration setting 'repositoryallowexternallinks' may prevent
1186 // using external links in editor environment
1187 allowed = false;
b5e7b638 1188 }
5cf44c1f
MG
1189 filelink[filelinktypes[i]] = allowed;
1190 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1191 filelinkcount += allowed ? 1 : 0;
99eaca9d 1192 }
989e14fe
DW
1193 var defaultreturntype = this.options.repositories[this.active_repo.id].defaultreturntype;
1194 if (defaultreturntype) {
1195 if (filelink[defaultreturntype]) {
1196 firstfilelink = defaultreturntype;
1197 }
1198 }
5cf44c1f
MG
1199 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1200 // check the first available file-link-type option
1201 for (var linktype in filelink) {
1202 var el = selectnode.one('.fp-linktype-'+linktype);
1203 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
4e366336 1204 el.one('input').set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change');
1dce6261 1205 }
b92241f2 1206
5cf44c1f 1207 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
6a0d7194 1208 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
4399e475 1209 this.populateLicensesSelect(selectnode.one('.fp-setlicense select'), args);
b5e7b638 1210 selectnode.one('form #filesource-'+client_id).set('value', args.source);
f1d1a60e 1211 selectnode.one('form #filesourcekey-'+client_id).set('value', args.sourcekey);
b92241f2
MG
1212
1213 // display static information about a file (when known)
1214 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1215 for (var i in attrs) {
1216 if (selectnode.one('.fp-'+attrs[i])) {
1217 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1218 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
954b3545 1219 .one('.fp-value').setContent(Y.Escape.html(value));
b92241f2
MG
1220 }
1221 }
b5e7b638
MG
1222 },
1223 setup_select_file: function() {
1224 var client_id = this.options.client_id;
55089a9d 1225 var selectnode = this.selectnode;
b92241f2
MG
1226 var getfile = selectnode.one('.fp-select-confirm');
1227 // bind labels with corresponding inputs
151b0f94 1228 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,fp-linktype-8,.fp-setauthor,.fp-setlicense').each(function (node) {
b92241f2
MG
1229 node.all('label').set('for', node.one('input,select').generateID());
1230 });
5cf44c1f
MG
1231 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1232 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1233 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
151b0f94 1234 selectnode.one('.fp-linktype-8 input').setAttrs({value: 8, name: 'linktype'});
5cf44c1f
MG
1235 var changelinktype = function(e) {
1236 if (e.currentTarget.get('checked')) {
1237 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1238 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1239 node.addClassIf('uneditable', !allowinputs);
1240 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1241 });
1242 }
1243 };
151b0f94 1244 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-linktype-8').each(function (node) {
5cf44c1f
MG
1245 node.one('input').on('change', changelinktype, this);
1246 });
b92241f2 1247 // register event on clicking submit button
99eaca9d 1248 getfile.on('click', function(e) {
b5e7b638 1249 e.preventDefault();
99eaca9d
DC
1250 var client_id = this.options.client_id;
1251 var scope = this;
1252 var repository_id = this.active_repo.id;
b92241f2 1253 var title = selectnode.one('.fp-saveas input').get('value');
b5e7b638 1254 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
f1d1a60e
AG
1255 var filesourcekey = selectnode.one('form #filesourcekey-'+client_id).get('value');
1256 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath, sourcekey: filesourcekey};
b92241f2 1257 var license = selectnode.one('.fp-setlicense select');
1dce6261
DC
1258 if (license) {
1259 params['license'] = license.get('value');
5cf44c1f 1260 var origlicense = selectnode.one('.fp-license .fp-value');
6a0d7194
DP
1261 if (origlicense) {
1262 origlicense = origlicense.getContent();
1263 }
4399e475
TD
1264 if (this.options.rememberuserlicensepref) {
1265 this.set_preference('recentlicense', license.get('value'));
1266 }
1dce6261 1267 }
b92241f2 1268 params['author'] = selectnode.one('.fp-setauthor input').get('value');
99eaca9d 1269
5cf44c1f
MG
1270 var return_types = this.options.repositories[this.active_repo.id].return_types;
1271 if (this.options.env == 'editor') {
392d5fd4
DC
1272 // in editor, images are stored in '/' only
1273 params.savepath = '/';
766514a0 1274 }
5cf44c1f
MG
1275 if ((this.options.externallink || this.options.env != 'editor') &&
1276 (return_types & 1/*FILE_EXTERNAL*/) &&
1277 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1278 selectnode.one('.fp-linktype-1 input').get('checked')) {
99eaca9d 1279 params['linkexternal'] = 'yes';
5cf44c1f
MG
1280 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1281 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1282 selectnode.one('.fp-linktype-4 input').get('checked')) {
f8e74b20 1283 params['usefilereference'] = '1';
151b0f94
DW
1284 } else if ((return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1285 (this.options.return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1286 selectnode.one('.fp-linktype-8 input').get('checked')) {
1287 params['usecontrolledlink'] = '1';
99eaca9d
DC
1288 }
1289
3a1e425b 1290 selectnode.addClass('loading');
99eaca9d 1291 this.request({
840912d5
DC
1292 action:'download',
1293 client_id: client_id,
1294 repository_id: repository_id,
1295 'params': params,
a5159b86 1296 onerror: function(id, obj, args) {
3a1e425b 1297 selectnode.removeClass('loading');
b5e7b638 1298 scope.selectui.hide();
a5159b86 1299 },
840912d5 1300 callback: function(id, obj, args) {
3a1e425b 1301 selectnode.removeClass('loading');
16dfd717
MG
1302 if (obj.event == 'fileexists') {
1303 scope.process_existing_file(obj);
1304 return;
1305 }
e0b85db4 1306 if (scope.options.editor_target && scope.options.env=='editor') {
840912d5 1307 scope.options.editor_target.value=obj.url;
5b54a1c7 1308 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
840912d5
DC
1309 }
1310 scope.hide();
1311 obj.client_id = client_id;
dd1f051e 1312 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
840912d5
DC
1313 scope.options.formcallback.apply(formcallback_scope, [obj]);
1314 }
b5e7b638 1315 }, false);
99eaca9d 1316 }, this);
b5e7b638 1317 var elform = selectnode.one('form');
3a1e425b
MG
1318 elform.appendChild(Y.Node.create('<input/>').
1319 setAttrs({type:'hidden',id:'filesource-'+client_id}));
f1d1a60e
AG
1320 elform.appendChild(Y.Node.create('<input/>').
1321 setAttrs({type:'hidden',id:'filesourcekey-'+client_id}));
e0b85db4
DC
1322 elform.on('keydown', function(e) {
1323 if (e.keyCode == 13) {
1324 getfile.simulate('click');
8cbef19e 1325 e.preventDefault();
e0b85db4
DC
1326 }
1327 }, this);
b92241f2 1328 var cancel = selectnode.one('.fp-select-cancel');
99eaca9d 1329 cancel.on('click', function(e) {
b5e7b638
MG
1330 e.preventDefault();
1331 this.selectui.hide();
99eaca9d 1332 }, this);
99eaca9d 1333 },
b5e7b638 1334 wait: function() {
2e7ce603
SH
1335 // First check there isn't already an interval in play, and if there is kill it now.
1336 if (this.waitinterval != null) {
1337 clearInterval(this.waitinterval);
1338 }
1339 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1340 var root = this.fpnode.one('.fp-content');
9d7d2b03 1341 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
2e7ce603
SH
1342 var count = 0;
1343 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1344 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1345 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1346 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1347 // Count 16 - The interval will be cancelled.
1348 var interval = setInterval(function(){
1349 if (!content || !root.contains(content) || count >= 15) {
1350 clearInterval(interval);
1351 return true;
1352 }
1353 if (count == 5) {
9d7d2b03 1354 content.removeClass('fp-content-hidden');
2e7ce603
SH
1355 } else if (count > 5) {
1356 var opacity = parseFloat(content.getStyle('opacity'));
1357 content.setStyle('opacity', opacity + 0.1);
1358 }
1359 count++;
1360 return false;
1361 }, 100);
1362 // Store the wait interval so that we can check it in the future.
1363 this.waitinterval = interval;
1364 // Set the content to the loading template.
1365 root.setContent(content);
b5e7b638
MG
1366 },
1367 viewbar_set_enabled: function(mode) {
1368 var viewbar = this.fpnode.one('.fp-viewbar')
1369 if (viewbar) {
1370 if (mode) {
a34f0a43
JF
1371 viewbar.addClass('enabled').removeClass('disabled');
1372 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false");
1373 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "");
b5e7b638 1374 } else {
a34f0a43
JF
1375 viewbar.removeClass('enabled').addClass('disabled');
1376 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true");
1377 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1");
b5e7b638 1378 }
99eaca9d 1379 }
a34f0a43 1380 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
b5e7b638
MG
1381 var modes = {1:'icons', 2:'tree', 3:'details'};
1382 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1383 },
1384 viewbar_clicked: function(e) {
1385 e.preventDefault();
1386 var viewbar = this.fpnode.one('.fp-viewbar')
1387 if (!viewbar || !viewbar.hasClass('disabled')) {
1388 if (e.currentTarget.hasClass('fp-vb-tree')) {
1389 this.viewmode = 2;
1390 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1391 this.viewmode = 3;
1392 } else {
1393 this.viewmode = 1;
1394 }
1395 this.viewbar_set_enabled(true)
1396 this.view_files();
837eef2e 1397 this.set_preference('recentviewmode', this.viewmode);
99eaca9d
DC
1398 }
1399 },
1400 render: function() {
1401 var client_id = this.options.client_id;
2eaaae00
JF
1402 var fpid = "filepicker-"+ client_id;
1403 var labelid = 'fp-dialog-label_'+ client_id;
d3065a36
RW
1404 var width = 873;
1405 var draggable = true;
88af0208 1406 this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
2eaaae00 1407 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
d3065a36
RW
1408
1409 if (this.in_iframe()) {
1410 width = Math.floor(window.innerWidth * 0.95);
1411 draggable = false;
1412 }
1413
d61c96b6 1414 this.mainui = new M.core.dialogue({
bf7c86cf 1415 extraClasses : ['filepicker'],
d3065a36 1416 draggable : draggable,
bf7c86cf 1417 bodyContent : this.fpnode,
64e7aa4d 1418 headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>',
b5e7b638
MG
1419 centered : true,
1420 modal : true,
1421 visible : false,
d3065a36 1422 width : width+'px',
48296457 1423 responsiveWidth : 768,
bf7c86cf 1424 height : '558px',
fb75fd03
TB
1425 zIndex : this.options.zIndex,
1426 focusOnPreviousTargetAfterHide: true,
1427 focusAfterHide: this.options.previousActiveElement
99eaca9d 1428 });
d61c96b6 1429
b92241f2 1430 // create panel for selecting a file (initially hidden)
88af0208 1431 this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
f2e4da68
RW
1432 set('id', 'filepicker-select-'+client_id).
1433 set('aria-live', 'assertive').
1434 set('role', 'dialog');
1435
1436 var fplabel = 'fp-file_label_'+ client_id;
d61c96b6 1437 this.selectui = new M.core.dialogue({
64e7aa4d 1438 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
d61c96b6 1439 draggable : true,
fd782261 1440 width : '450px',
bf7c86cf 1441 bodyContent : this.selectnode,
b5e7b638
MG
1442 centered : true,
1443 modal : true,
d61c96b6 1444 visible : false,
bf7c86cf 1445 zIndex : this.options.zIndex
99eaca9d 1446 });
f2e4da68 1447 Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
ce3eeb98
MG
1448 // event handler for lazy loading of thumbnails and next page
1449 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
b5e7b638
MG
1450 // save template for one path element and location of path bar
1451 if (this.fpnode.one('.fp-path-folder')) {
1452 this.pathnode = this.fpnode.one('.fp-path-folder');
1453 this.pathbar = this.pathnode.get('parentNode');
1454 this.pathbar.removeChild(this.pathnode);
1455 }
1456 // assign callbacks for view mode switch buttons
039677df
DS
1457 this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1458 this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1459 this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1460
b5e7b638
MG
1461 // assign callbacks for toolbar links
1462 this.setup_toolbar();
1463 this.setup_select_file();
3a1e425b 1464 this.hide_header();
934291d6 1465
99eaca9d 1466 // processing repository listing
b5e7b638 1467 // Resort the repositories by sortorder
6a0d7194 1468 var sorted_repositories = [];
5aeadf0b
AG
1469 var i;
1470 for (i in this.options.repositories) {
6a0d7194 1471 sorted_repositories[i] = this.options.repositories[i];
b5e7b638 1472 }
6a0d7194 1473 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
b5e7b638
MG
1474 // extract one repository template and repeat it for all repositories available,
1475 // set name and icon and assign callbacks
1476 var reponode = this.fpnode.one('.fp-repo');
1477 if (reponode) {
1478 var list = reponode.get('parentNode');
1479 list.removeChild(reponode);
1480 for (i in sorted_repositories) {
6a0d7194 1481 var repository = sorted_repositories[i];
5aeadf0b
AG
1482 var h = (parseInt(i) == 0) ? parseInt(i) : parseInt(i) - 1,
1483 j = (parseInt(i) == Object.keys(sorted_repositories).length - 1) ? parseInt(i) : parseInt(i) + 1;
1484 var previousrepository = sorted_repositories[h];
1485 var nextrepository = sorted_repositories[j];
b5e7b638
MG
1486 var node = reponode.cloneNode(true);
1487 list.appendChild(node);
1488 node.
1489 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1490 on('click', function(e, repository_id) {
1491 e.preventDefault();
837eef2e 1492 this.set_preference('recentrepository', repository_id);
b5e7b638
MG
1493 this.hide_header();
1494 this.list({'repo_id':repository_id});
1495 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
5aeadf0b
AG
1496 node.on('key', function(e, previousrepositoryid, nextrepositoryid, clientid, repositoryid) {
1497 this.changeHighlightedRepository(e, clientid, repositoryid, previousrepositoryid, nextrepositoryid);
1498 }, 'down:38,40', this, previousrepository.id, nextrepository.id, client_id, repository.id);
1499 node.on('key', function(e, repositoryid) {
1500 e.preventDefault();
1501 this.set_preference('recentrepository', repositoryid);
1502 this.hide_header();
1503 this.list({'repo_id': repositoryid});
1504 }, 'enter', this, repository.id);
954b3545 1505 node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
6a0d7194
DP
1506 node.one('.fp-repo-icon').set('src', repository.icon);
1507 if (i==0) {
1508 node.addClass('first');
1509 }
1510 if (i==sorted_repositories.length-1) {
1511 node.addClass('last');
1512 }
1513 if (i%2) {
1514 node.addClass('even');
1515 } else {
1516 node.addClass('odd');
1517 }
99eaca9d 1518 }
b5e7b638
MG
1519 }
1520 // display error if no repositories found
1521 if (sorted_repositories.length==0) {
64e7aa4d 1522 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
b5e7b638
MG
1523 }
1524 // display repository that was used last time
bf7c86cf 1525 this.mainui.show();
b5e7b638 1526 this.show_recent_repository();
99eaca9d 1527 },
5aeadf0b
AG
1528 /**
1529 * Change the highlighted repository to a new one.
1530 *
1531 * @param {object} event The key event
1532 * @param {integer} clientid The client id to identify the repo class.
1533 * @param {integer} oldrepositoryid The repository id that we are removing the highlight for
1534 * @param {integer} previousrepositoryid The previous repository id.
1535 * @param {integer} nextrepositoryid The next repository id.
1536 */
1537 changeHighlightedRepository: function(event, clientid, oldrepositoryid, previousrepositoryid, nextrepositoryid) {
1538 event.preventDefault();
1539 var newrepositoryid = (event.keyCode == '40') ? nextrepositoryid : previousrepositoryid;
1540 this.fpnode.one('#fp-repo-' + clientid + '-' + oldrepositoryid).setAttribute('tabindex', '-1');
1541 this.fpnode.one('#fp-repo-' + clientid + '-' + newrepositoryid)
1542 .setAttribute('tabindex', '0')
1543 .focus();
1544 },
7ccf18a6
MG
1545 parse_repository_options: function(data, appendtolist) {
1546 if (appendtolist) {
1547 if (data.list) {
6a0d7194
DP
1548 if (!this.filelist) {
1549 this.filelist = [];
1550 }
7ccf18a6
MG
1551 for (var i in data.list) {
1552 this.filelist[this.filelist.length] = data.list[i];
1553 }
1554 }
1555 } else {
1556 this.filelist = data.list?data.list:null;
ce3eeb98 1557 this.lazyloading = {};
7ccf18a6 1558 }
99eaca9d 1559 this.filepath = data.path?data.path:null;
5cf44c1f 1560 this.objecttag = data.object?data.object:null;
99eaca9d 1561 this.active_repo = {};
6a0d7194 1562 this.active_repo.issearchresult = data.issearchresult ? true : false;
989e14fe 1563 this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
98b15580 1564 this.active_repo.dynload = data.dynload?data.dynload:false;
99eaca9d
DC
1565 this.active_repo.pages = Number(data.pages?data.pages:null);
1566 this.active_repo.page = Number(data.page?data.page:null);
7ccf18a6 1567 this.active_repo.hasmorepages = (this.active_repo.pages && this.active_repo.page && (this.active_repo.page < this.active_repo.pages || this.active_repo.pages == -1))
99eaca9d 1568 this.active_repo.id = data.repo_id?data.repo_id:null;
b5e7b638
MG
1569 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1570 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1571 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
fdfb9cbe 1572 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
a3433213
RW
1573 this.active_repo.logouturl = (data.logouturl || '');
1574 this.active_repo.message = (data.message || '');
99eaca9d
DC
1575 this.active_repo.help = data.help?data.help:null;
1576 this.active_repo.manage = data.manage?data.manage:null;
b5e7b638 1577 this.print_header();
99eaca9d
DC
1578 },
1579 print_login: function(data) {
97b151ea 1580 this.parse_repository_options(data);
99eaca9d
DC
1581 var client_id = this.options.client_id;
1582 var repository_id = data.repo_id;
1583 var l = this.logindata = data.login;
1584 var loginurl = '';
3a1e425b 1585 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
99eaca9d 1586 var form_id = 'fp-form-'+client_id;
99eaca9d 1587
5ce13292
MG
1588 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1589 loginform_node.one('form').set('id', form_id);
1590 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1591 var templates = {
1592 'popup' : loginform_node.one('.fp-login-popup'),
1593 'textarea' : loginform_node.one('.fp-login-textarea'),
1594 'select' : loginform_node.one('.fp-login-select'),
1595 'text' : loginform_node.one('.fp-login-text'),
3a1e425b 1596 'radio' : loginform_node.one('.fp-login-radiogroup'),
5ce13292
MG
1597 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1598 'input' : loginform_node.one('.fp-login-input')
1599 };
1600 var container;
1601 for (var i in templates) {
1602 if (templates[i]) {
1603 container = templates[i].get('parentNode');
6a0d7194 1604 container.removeChild(templates[i]);
5ce13292
MG
1605 }
1606 }
1607
1608 for(var k in l) {
1609 if (templates[l[k].type]) {
1610 var node = templates[l[k].type].cloneNode(true);
1611 } else {
1612 node = templates['input'].cloneNode(true);
1613 }
1614 if (l[k].type == 'popup') {
3a1e425b 1615 // submit button
2f6749f4 1616 loginurl = l[k].url;
3a1e425b
MG
1617 var popupbutton = node.one('button');
1618 popupbutton.on('click', function(e){
1619 M.core_filepicker.active_filepicker = this;
1620 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1621 e.preventDefault();
1622 }, this);
1623 loginform_node.one('form').on('keydown', function(e) {
1624 if (e.keyCode == 13) {
1625 popupbutton.simulate('click');
1626 e.preventDefault();
1627 }
1628 }, this);
5ce13292
MG
1629 loginform_node.all('.fp-login-submit').remove();
1630 action = 'popup';
6a0d7194 1631 } else if(l[k].type=='textarea') {
5ce13292 1632 // textarea element
6a0d7194
DP
1633 if (node.one('label')) {
1634 node.one('label').set('for', l[k].id).setContent(l[k].label);
1635 }
3a1e425b 1636 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
6a0d7194 1637 } else if(l[k].type=='select') {
5ce13292 1638 // select element
6a0d7194
DP
1639 if (node.one('label')) {
1640 node.one('label').set('for', l[k].id).setContent(l[k].label);
1641 }
3a1e425b 1642 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
5ce13292
MG
1643 for (i in l[k].options) {
1644 node.one('select').appendChild(
1645 Y.Node.create('<option/>').
1646 set('value', l[k].options[i].value).
6a0d7194 1647 setContent(l[k].options[i].label));
5ce13292 1648 }
6a0d7194 1649 } else if(l[k].type=='radio') {
5ce13292 1650 // radio input element
3a1e425b
MG
1651 node.all('label').setContent(l[k].label);
1652 var list = l[k].value.split('|');
1653 var labels = l[k].value_label.split('|');
1654 var radionode = null;
1655 for(var item in list) {
1656 if (radionode == null) {
1657 radionode = node.one('.fp-login-radio');
1658 radionode.one('input').set('checked', 'checked');
1659 } else {
1660 var x = radionode.cloneNode(true);
1661 radionode.insert(x, 'after');
1662 radionode = x;
1663 radionode.one('input').set('checked', '');
1664 }
1665 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1666 type:l[k].type, value:list[item]});
1667 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1668 }
1669 if (radionode == null) {
1670 node.one('.fp-login-radio').remove();
1671 }
6a0d7194 1672 } else {
5ce13292
MG
1673 // input element
1674 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1675 node.one('input').
1676 set('type', l[k].type).
1677 set('id', l[k].id).
1678 set('name', l[k].name).
1679 set('value', l[k].value?l[k].value:'')
1680 }
1681 container.appendChild(node);
1682 }
3a1e425b
MG
1683 // custom label text for submit button
1684 if (data['login_btn_label']) {
1685 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
99eaca9d 1686 }
3a1e425b
MG
1687 // register button action for login and search
1688 if (action == 'login' || action == 'search') {
1689 loginform_node.one('.fp-login-submit').on('click', function(e){
5ce13292 1690 e.preventDefault();
b5e7b638 1691 this.hide_header();
99eaca9d 1692 this.request({
3a1e425b
MG
1693 'scope': this,
1694 'action':(action == 'search') ? 'search' : 'signin',
99eaca9d
DC
1695 'path': '',
1696 'client_id': client_id,
1697 'repository_id': repository_id,
3a1e425b 1698 'form': {id:form_id, upload:false, useDisabled:true},
4adecd7b 1699 'callback': this.display_response
99eaca9d
DC
1700 }, true);
1701 }, this);
1702 }
3a1e425b
MG
1703 // if 'Enter' is pressed in the form, simulate the button click
1704 if (loginform_node.one('.fp-login-submit')) {
1705 loginform_node.one('form').on('keydown', function(e) {
1706 if (e.keyCode == 13) {
1707 loginform_node.one('.fp-login-submit').simulate('click')
1708 e.preventDefault();
99eaca9d 1709 }
99eaca9d
DC
1710 }, this);
1711 }
99eaca9d 1712 },
4adecd7b 1713 display_response: function(id, obj, args) {
ee4ab975 1714 var scope = args.scope;
4adecd7b 1715 // highlight the current repository in repositories list
5aeadf0b
AG
1716 scope.fpnode.all('.fp-repo.active')
1717 .removeClass('active')
1718 .setAttribute('aria-selected', 'false')
1719 .setAttribute('tabindex', '-1');
dcf42541
AG
1720 scope.fpnode.all('.nav-link')
1721 .removeClass('active')
1722 .setAttribute('aria-selected', 'false')
1723 .setAttribute('tabindex', '-1');
1724 var activenode = scope.fpnode.one('#fp-repo-' + scope.options.client_id + '-' + obj.repo_id);
1725 activenode.addClass('active')
5aeadf0b
AG
1726 .setAttribute('aria-selected', 'true')
1727 .setAttribute('tabindex', '0');
dcf42541 1728 activenode.all('.nav-link').addClass('active');
5ce13292
MG
1729 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1730 for (var i in scope.options.repositories) {
1731 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1732 }
1733 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1734 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1735 }
ee4ab975 1736 Y.one('.file-picker .fp-repo-items').focus();
3ad7a71e 1737
4adecd7b
MG
1738 // display response
1739 if (obj.login) {
b5e7b638 1740 scope.viewbar_set_enabled(false);
4adecd7b
MG
1741 scope.print_login(obj);
1742 } else if (obj.upload) {
b5e7b638 1743 scope.viewbar_set_enabled(false);
4adecd7b
MG
1744 scope.parse_repository_options(obj);
1745 scope.create_upload_form(obj);
5cf44c1f
MG
1746 } else if (obj.object) {
1747 M.core_filepicker.active_filepicker = scope;
1748 scope.viewbar_set_enabled(false);
1749 scope.parse_repository_options(obj);
1750 scope.create_object_container(obj.object);
4adecd7b 1751 } else if (obj.list) {
b5e7b638 1752 scope.viewbar_set_enabled(true);
4adecd7b
MG
1753 scope.parse_repository_options(obj);
1754 scope.view_files();
99eaca9d 1755 }
99eaca9d
DC
1756 },
1757 list: function(args) {
99eaca9d
DC
1758 if (!args) {
1759 args = {};
1760 }
1761 if (!args.repo_id) {
4adecd7b 1762 args.repo_id = this.active_repo.id;
99eaca9d 1763 }
7dab27b3
FM
1764 if (!args.path) {
1765 args.path = '';
1766 }
1767 this.currentpath = args.path;
4adecd7b
MG
1768 this.request({
1769 action: 'list',
1770 client_id: this.options.client_id,
99eaca9d 1771 repository_id: args.repo_id,
4adecd7b
MG
1772 path: args.path,
1773 page: args.page,
1774 scope: this,
1775 callback: this.display_response
99eaca9d
DC
1776 }, true);
1777 },
4399e475
TD
1778 populateLicensesSelect: function(licensenode, filenode) {
1779 if (!licensenode) {
b5e7b638 1780 return;
e35194be 1781 }
4399e475
TD
1782 licensenode.setContent('');
1783 var selectedlicense = this.options.defaultlicense;
1784 if (filenode) {
1785 // File has a license already, use it.
1786 selectedlicense = filenode.license;
1787 } else if (this.options.rememberuserlicensepref) {
1788 selectedlicense = this.get_preference('recentlicense');
a756cb37 1789 }
4399e475 1790 var licenses = this.options.licenses;
1dce6261 1791 for (var i in licenses) {
4399e475
TD
1792 // Include the file's current license, even if not enabled, to prevent displaying
1793 // misleading information about which license the file currently has assigned to it.
1794 if (licenses[i].enabled == true || (filenode !== undefined && licenses[i].shortname === filenode.license)) {
1795 var option = Y.Node.create('<option/>').
1796 set('selected', (licenses[i].shortname == selectedlicense)).
b5e7b638 1797 set('value', licenses[i].shortname).
954b3545 1798 setContent(Y.Escape.html(licenses[i].fullname));
4399e475 1799 licensenode.appendChild(option);
5cf44c1f 1800 }
5cf44c1f
MG
1801 }
1802 },
1803 create_object_container: function(data) {
1804 var content = this.fpnode.one('.fp-content');
1805 content.setContent('');
1806 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1807 var container = Y.Node.create('<object/>').
1808 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1809 addClass('fp-object-container');
1810 content.setContent('').appendChild(container);
1811 },
b5e7b638
MG
1812 create_upload_form: function(data) {
1813 var client_id = this.options.client_id;
1814 var id = data.upload.id+'_'+client_id;
b92241f2 1815 var content = this.fpnode.one('.fp-content');
ec3eaa2c
PN
1816 var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1817 var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1818 content.setContent(template);
b5e7b638 1819
b92241f2
MG
1820 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1821 node.all('label').set('for', node.one('input,select').generateID());
1822 });
1823 content.one('form').set('id', id);
1824 content.one('.fp-file input').set('name', 'repo_upload_file');
6133c2ea
MG
1825 if (data.upload.label && content.one('.fp-file label')) {
1826 content.one('.fp-file label').setContent(data.upload.label);
1827 }
b92241f2
MG
1828 content.one('.fp-saveas input').set('name', 'title');
1829 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1830 content.one('.fp-setlicense select').set('name', 'license');
4399e475 1831 this.populateLicensesSelect(content.one('.fp-setlicense select'));
b92241f2
MG
1832 // append hidden inputs to the upload form
1833 content.one('form').appendChild(Y.Node.create('<input/>').
3a1e425b 1834 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
b5e7b638
MG
1835 var types = this.options.accepted_types;
1836 for (var i in types) {
b92241f2 1837 content.one('form').appendChild(Y.Node.create('<input/>').
3a1e425b 1838 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
b5e7b638
MG
1839 }
1840
99eaca9d 1841 var scope = this;
b92241f2 1842 content.one('.fp-upload-btn').on('click', function(e) {
8cbef19e 1843 e.preventDefault();
b92241f2 1844 var license = content.one('.fp-setlicense select');
837eef2e 1845
4399e475
TD
1846 if (this.options.rememberuserlicensepref) {
1847 this.set_preference('recentlicense', license.get('value'));
1848 }
b92241f2 1849 if (!content.one('.fp-file input').get('value')) {
64e7aa4d 1850 scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
2a03b97b
DC
1851 return false;
1852 }
b5e7b638 1853 this.hide_header();
9d753c38
PS
1854 scope.request({
1855 scope: scope,
1856 action:'upload',
1857 client_id: client_id,
1858 params: {'savepath':scope.options.savepath},
1859 repository_id: scope.active_repo.id,
1860 form: {id: id, upload:true},
a5159b86
MG
1861 onerror: function(id, o, args) {
1862 scope.create_upload_form(data);
1863 },
9d753c38 1864 callback: function(id, o, args) {
dd1f051e
MG
1865 if (o.event == 'fileexists') {
1866 scope.create_upload_form(data);
1867 scope.process_existing_file(o);
1868 return;
1869 }
9d753c38
PS
1870 if (scope.options.editor_target&&scope.options.env=='editor') {
1871 scope.options.editor_target.value=o.url;
5b54a1c7 1872 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
0c4edaa2 1873 }
9d753c38
PS
1874 scope.hide();
1875 o.client_id = client_id;
dd1f051e 1876 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
9d753c38
PS
1877 scope.options.formcallback.apply(formcallback_scope, [o]);
1878 }
1879 }, true);
99eaca9d
DC
1880 }, this);
1881 },
b5e7b638
MG
1882 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1883 setup_toolbar: function() {
99eaca9d 1884 var client_id = this.options.client_id;
b92241f2
MG
1885 var toolbar = this.fpnode.one('.fp-toolbar');
1886 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
b5e7b638
MG
1887 e.preventDefault();
1888 if (!this.active_repo.nologin) {
1889 this.hide_header();
1890 this.request({
1891 action:'logout',
1892 client_id: this.options.client_id,
1893 repository_id: this.active_repo.id,
1894 path:'',
1895 callback: this.display_response
1896 }, true);
1897 }
a3433213
RW
1898 if (this.active_repo.logouturl) {
1899 window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1900 }
b5e7b638 1901 }, this);
b92241f2 1902 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
b5e7b638
MG
1903 e.preventDefault();
1904 if (!this.active_repo.norefresh) {
7dab27b3 1905 this.list({ path: this.currentpath });
b5e7b638
MG
1906 }
1907 }, this);
b92241f2 1908 toolbar.one('.fp-tb-search form').
b5e7b638 1909 set('method', 'POST').
b92241f2 1910 set('id', 'fp-tb-search-'+client_id).
b5e7b638 1911 on('submit', function(e) {
4adecd7b 1912 e.preventDefault();
b5e7b638
MG
1913 if (!this.active_repo.nosearch) {
1914 this.request({
1915 scope: this,
1916 action:'search',
1917 client_id: this.options.client_id,
1918 repository_id: this.active_repo.id,
1919 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1920 callback: this.display_response
1921 }, true);
1922 }
a3433213 1923 }, this);
99eaca9d 1924
b92241f2 1925 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
b5e7b638 1926 // element and use it to open url on click event
3a1e425b
MG
1927 var managelnk = Y.Node.create('<a/>').
1928 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1929 setStyle('display', 'none');
b92241f2
MG
1930 toolbar.append(managelnk);
1931 toolbar.one('.fp-tb-manage').one('a,button').
1932 on('click', function(e) {
1933 e.preventDefault();
1934 managelnk.simulate('click')
1935 });
99eaca9d 1936
b92241f2 1937 // same with .fp-tb-help
3a1e425b
MG
1938 var helplnk = Y.Node.create('<a/>').
1939 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1940 setStyle('display', 'none');
b92241f2 1941 toolbar.append(helplnk);
0c2fe3aa 1942 toolbar.one('.fp-tb-help').one('a,button').
b92241f2
MG
1943 on('click', function(e) {
1944 e.preventDefault();
1945 helplnk.simulate('click')
1946 });
b5e7b638
MG
1947 },
1948 hide_header: function() {
b92241f2
MG
1949 if (this.fpnode.one('.fp-toolbar')) {
1950 this.fpnode.one('.fp-toolbar').addClass('empty');
b5e7b638 1951 }
3a1e425b
MG
1952 if (this.pathbar) {
1953 this.pathbar.setContent('').addClass('empty');
1954 }
b5e7b638
MG
1955 },
1956 print_header: function() {
1957 var r = this.active_repo;
1958 var scope = this;
1959 var client_id = this.options.client_id;
2f6749f4 1960 this.hide_header();
b92241f2
MG
1961 this.print_path();
1962 var toolbar = this.fpnode.one('.fp-toolbar');
1963 if (!toolbar) { return; }
99eaca9d 1964
b92241f2
MG
1965 var enable_tb_control = function(node, enabled) {
1966 if (!node) { return; }
1967 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1968 if (enabled) {
1969 toolbar.removeClass('empty');
b5e7b638
MG
1970 }
1971 }
99eaca9d 1972
b5e7b638 1973 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
b92241f2 1974 enable_tb_control(toolbar.one('.fp-tb-back'), false);
99eaca9d 1975
b5e7b638 1976 // search form
b92241f2 1977 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
b5e7b638 1978 if(!r.nosearch) {
b92241f2
MG
1979 var searchform = toolbar.one('.fp-tb-search form');
1980 searchform.setContent('');
b5e7b638
MG
1981 this.request({
1982 scope: this,
1983 action:'searchform',
1984 repository_id: this.active_repo.id,
1985 callback: function(id, obj, args) {
1986 if (obj.repo_id == scope.active_repo.id && obj.form) {
1987 // if we did not jump to another repository meanwhile
b92241f2 1988 searchform.setContent(obj.form);
d01ebb94
RT
1989 // Highlight search text when user click for search.
1990 var searchnode = searchform.one('input[name="s"]');
1991 if (searchnode) {
1992 searchnode.once('click', function(e) {
1993 e.preventDefault();
1994 this.select();
1995 });
1996 }
99eaca9d 1997 }
b5e7b638
MG
1998 }
1999 }, false);
99eaca9d 2000 }
b5e7b638
MG
2001
2002 // refresh button
99eaca9d 2003 // weather we use cache for this instance, this button will reload listing anyway
b92241f2 2004 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
b5e7b638
MG
2005
2006 // login button
b92241f2 2007 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
99eaca9d 2008
b5e7b638 2009 // manage url
b92241f2 2010 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
b5e7b638
MG
2011 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
2012
2013 // help url
b92241f2 2014 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
b5e7b638 2015 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
a3433213
RW
2016
2017 // message
2018 enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
2019 toolbar.one('.fp-tb-message').setContent(r.message);
99eaca9d 2020 },
99eaca9d 2021 print_path: function() {
6a0d7194
DP
2022 if (!this.pathbar) {
2023 return;
2024 }
3a1e425b 2025 this.pathbar.setContent('').addClass('empty');
99eaca9d 2026 var p = this.filepath;
2f6749f4 2027 if (p && p.length!=0 && this.viewmode != 2) {
99eaca9d 2028 for(var i = 0; i < p.length; i++) {
b5e7b638
MG
2029 var el = this.pathnode.cloneNode(true);
2030 this.pathbar.appendChild(el);
6a0d7194
DP
2031 if (i == 0) {
2032 el.addClass('first');
2033 }
2034 if (i == p.length-1) {
2035 el.addClass('last');
2036 }
2037 if (i%2) {
2038 el.addClass('even');
2039 } else {
2040 el.addClass('odd');
2041 }
954b3545 2042 el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
b5e7b638
MG
2043 el.on('click',
2044 function(e, path) {
2045 e.preventDefault();
2046 this.list({'path':path});
2047 },
2048 this, p[i].path);
99eaca9d 2049 }
b5e7b638 2050 this.pathbar.removeClass('empty');
99eaca9d
DC
2051 }
2052 },
2053 hide: function() {
b5e7b638
MG
2054 this.selectui.hide();
2055 if (this.process_dlg) {
2056 this.process_dlg.hide();
2057 }
2058 if (this.msg_dlg) {
2059 this.msg_dlg.hide();
2060 }
99eaca9d
DC
2061 this.mainui.hide();
2062 },
2063 show: function() {
b5e7b638
MG
2064 if (this.fpnode) {
2065 this.hide();
99eaca9d 2066 this.mainui.show();
a756cb37 2067 this.show_recent_repository();
99eaca9d
DC
2068 } else {
2069 this.launch();
2070 }
2071 },
2072 launch: function() {
7b42e81a 2073 this.render();
a756cb37
DC
2074 },
2075 show_recent_repository: function() {
b5e7b638
MG
2076 this.hide_header();
2077 this.viewbar_set_enabled(false);
837eef2e
DP
2078 var repository_id = this.get_preference('recentrepository');
2079 this.viewmode = this.get_preference('recentviewmode');
5bdf63cc 2080 if (this.viewmode != 2 && this.viewmode != 3) {
b5e7b638
MG
2081 this.viewmode = 1;
2082 }
a756cb37
DC
2083 if (this.options.repositories[repository_id]) {
2084 this.list({'repo_id':repository_id});
2085 }
837eef2e
DP
2086 },
2087 get_preference: function (name) {
2088 if (this.options.userprefs[name]) {
2089 return this.options.userprefs[name];
2090 } else {
2091 return false;
2092 }
2093 },
2094 set_preference: function(name, value) {
2095 if (this.options.userprefs[name] != value) {
2096 M.util.set_user_preference('filepicker_' + name, value);
2097 this.options.userprefs[name] = value;
2098 }
d3065a36
RW
2099 },
2100 in_iframe: function () {
2101 // If we're not the top window then we're in an iFrame
2102 return window.self !== window.top;
99eaca9d
DC
2103 }
2104 });
bb496de7
DC
2105 var loading = Y.one('#filepicker-loading-'+options.client_id);
2106 if (loading) {
2107 loading.setStyle('display', 'none');
2108 }
4c508047
PS
2109 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);
2110};