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