Dotclear

source: admin/js/jsUpload/jquery.fileupload-ui.js @ 1206:75a0813cea49

Revision 1206:75a0813cea49, 25.5 KB checked in by Sogos <thibault.cordier@…>, 12 years ago (diff)

Remove check on file add (Send button Disabled bug)

Line 
1/*
2 * jQuery File Upload User Interface Plugin 8.2.1
3 * https://github.com/blueimp/jQuery-File-Upload
4 *
5 * Copyright 2010, Sebastian Tschan
6 * https://blueimp.net
7 *
8 * Licensed under the MIT license:
9 * http://www.opensource.org/licenses/MIT
10 */
11
12/*jslint nomen: true, unparam: true, regexp: true */
13/*global define, window, URL, webkitURL, FileReader */
14
15(function (factory) {
16    'use strict';
17    if (typeof define === 'function' && define.amd) {
18        // Register as an anonymous AMD module:
19        define([
20            'jquery',
21            'tmpl',
22            './jquery.fileupload-resize',
23            './jquery.fileupload-validate'
24        ], factory);
25    } else {
26        // Browser globals:
27        factory(
28            window.jQuery,
29            window.tmpl
30        );
31    }
32}(function ($, tmpl, loadImage) {
33    'use strict';
34
35    $.blueimp.fileupload.prototype._specialOptions.push(
36        'filesContainer',
37        'uploadTemplateId',
38        'downloadTemplateId'
39    );
40
41    // The UI version extends the file upload widget
42    // and adds complete user interface interaction:
43    $.widget('blueimp.fileupload', $.blueimp.fileupload, {
44
45        options: {
46            // By default, files added to the widget are uploaded as soon
47            // as the user clicks on the start buttons. To enable automatic
48            // uploads, set the following option to true:
49            autoUpload: false,
50            // The ID of the upload template:
51            uploadTemplateId: 'template-upload',
52            // The ID of the download template:
53            downloadTemplateId: 'template-download',
54            // The container for the list of files. If undefined, it is set to
55            // an element with class "files" inside of the widget element:
56            filesContainer: undefined,
57            // By default, files are appended to the files container.
58            // Set the following option to true, to prepend files instead:
59            prependFiles: false,
60            // The expected data type of the upload response, sets the dataType
61            // option of the $.ajax upload requests:
62            dataType: 'json',
63
64            // Function returning the current number of files,
65            // used by the maxNumberOfFiles validation:
66            getNumberOfFiles: function () {
67                return this.filesContainer.children().length;
68            },
69
70            // Callback to retrieve the list of files from the server response:
71            getFilesFromResponse: function (data) {
72                if (data.result && $.isArray(data.result.files)) {
73                    return data.result.files;
74                }
75                return [];
76            },
77
78            // The add callback is invoked as soon as files are added to the fileupload
79            // widget (via file input selection, drag & drop or add API call).
80            // See the basic file upload widget for more information:
81            add: function (e, data) {
82                var $this = $(this),
83                    that = $this.data('blueimp-fileupload') ||
84                        $this.data('fileupload'),
85                    options = that.options,
86                    files = data.files;
87                data.process(function () {
88                    return $this.fileupload('process', data);
89                }).always(function () {
90                    data.context = that._renderUpload(files).data('data', data);
91                    that._renderPreviews(data);
92                    options.filesContainer[
93                        options.prependFiles ? 'prepend' : 'append'
94                    ](data.context);
95                    that._forceReflow(data.context);
96                    that._transition(data.context).done(
97                        function () {
98                            if ((that._trigger('added', e, data) !== false) &&
99                                    (options.autoUpload || data.autoUpload) &&
100                                    data.autoUpload !== false && !data.files.error) {
101                                data.submit();
102                            }
103                        }
104                    );
105                });
106
107            /*
108             * 
109             *  Activation du bouton si un fichier trouvé
110             */
111                var fileUploadButtonBar = that.element.find('.fileupload-buttonbar');
112                fileUploadButtonBar.find('.start').prop('disabled', false);
113                fileUploadButtonBar.find('.start').removeClass('disabled');
114             /*
115             *
116             */
117            },
118            // Callback for the start of each file upload request:
119            send: function (e, data) {
120                $(this).find('.start').hide();
121                var that = $(this).data('blueimp-fileupload') ||
122                        $(this).data('fileupload');
123                if (data.context && data.dataType &&
124                        data.dataType.substr(0, 6) === 'iframe') {
125                    // Iframe Transport does not support progress events.
126                    // In lack of an indeterminate progress bar, we set
127                    // the progress to 100%, showing the full animated bar:
128                    data.context
129                        .find('.progress').addClass(
130                            !$.support.transition && 'progress-animated'
131                        )
132                        .attr('aria-valuenow', 100)
133                        .find('.bar').css(
134                            'width',
135                            '100%'
136                        );
137                }
138                return that._trigger('sent', e, data);
139            },
140            // Callback for successful uploads:
141            done: function (e, data) {
142
143                var that = $(this).data('blueimp-fileupload') ||
144                        $(this).data('fileupload'),
145                    getFilesFromResponse = data.getFilesFromResponse ||
146                        that.options.getFilesFromResponse,
147                    files = getFilesFromResponse(data),
148                    template,
149                    deferred;
150                if (data.context) {
151                    data.context.each(function (index) {
152                        var file = files[index] ||
153                                {error: 'Empty file upload result'},
154                            deferred = that._addFinishedDeferreds();
155                        that._transition($(this)).done(
156                            function () {
157                                var node = $(this);
158                                template = that._renderDownload([file])
159                                    .replaceAll(node);
160                                that._forceReflow(template);
161                                that._transition(template).done(
162                                    function () {
163                                        data.context = $(this);
164                                        that._trigger('completed', e, data);
165                                        that._trigger('finished', e, data);
166                                        deferred.resolve();
167                                    }
168                                );
169                            }
170                        );
171                    });
172                } else {
173                    template = that._renderDownload(files)
174                        .appendTo(that.options.filesContainer);
175                    that._forceReflow(template);
176                    deferred = that._addFinishedDeferreds();
177                    that._transition(template).done(
178                        function () {
179                            data.context = $(this);
180                            that._trigger('completed', e, data);
181                            that._trigger('finished', e, data);
182                            deferred.resolve();
183                        }
184                    );
185                }
186            },
187            // Callback for failed (abort or error) uploads:
188            fail: function (e, data) {
189                var that = $(this).data('blueimp-fileupload') ||
190                        $(this).data('fileupload'),
191                    template,
192                    deferred;
193                if (data.context) {
194                    data.context.each(function (index) {
195                        if (data.errorThrown !== 'abort') {
196                            var file = data.files[index];
197                            file.error = file.error || data.errorThrown ||
198                                true;
199                            deferred = that._addFinishedDeferreds();
200                            that._transition($(this)).done(
201                                function () {
202                                    var node = $(this);
203                                    template = that._renderDownload([file])
204                                        .replaceAll(node);
205                                    that._forceReflow(template);
206                                    that._transition(template).done(
207                                        function () {
208                                            data.context = $(this);
209                                            that._trigger('failed', e, data);
210                                            that._trigger('finished', e, data);
211                                            deferred.resolve();
212                                        }
213                                    );
214                                }
215                            );
216                        } else {
217                            deferred = that._addFinishedDeferreds();
218                            that._transition($(this)).done(
219                                function () {
220                                    $(this).remove();
221                                    that._trigger('failed', e, data);
222                                    that._trigger('finished', e, data);
223                                    deferred.resolve();
224                                }
225                            );
226                        }
227                    });
228                } else if (data.errorThrown !== 'abort') {
229                    data.context = that._renderUpload(data.files)
230                        .appendTo(that.options.filesContainer)
231                        .data('data', data);
232                    that._forceReflow(data.context);
233                    deferred = that._addFinishedDeferreds();
234                    that._transition(data.context).done(
235                        function () {
236                            data.context = $(this);
237                            that._trigger('failed', e, data);
238                            that._trigger('finished', e, data);
239                            deferred.resolve();
240                        }
241                    );
242                } else {
243                    that._trigger('failed', e, data);
244                    that._trigger('finished', e, data);
245                    that._addFinishedDeferreds().resolve();
246                }
247            },
248            // Callback for upload progress events:
249            progress: function (e, data) {
250                if (data.context) {
251                    var progress = Math.floor(data.loaded / data.total * 100);
252                    data.context.find('.progress')
253                        .attr('aria-valuenow', progress)
254                        .find('.bar').css(
255                            'width',
256                            progress + '%'
257                        );
258                }
259            },
260            // Callback for global upload progress events:
261            progressall: function (e, data) {
262                var $this = $(this),
263                    progress = Math.floor(data.loaded / data.total * 100),
264                    globalProgressNode = $this.find('.fileupload-progress'),
265                    extendedProgressNode = globalProgressNode
266                        .find('.progress-extended');
267                if (extendedProgressNode.length) {
268                    extendedProgressNode.html(
269                        ($this.data('blueimp-fileupload') || $this.data('fileupload'))
270                            ._renderExtendedProgress(data)
271                    );
272                }
273                globalProgressNode
274                    .find('.progress')
275                    .attr('aria-valuenow', progress)
276                    .find('.bar').css(
277                        'width',
278                        progress + '%'
279                    );
280            },
281            // Callback for uploads start, equivalent to the global ajaxStart event:
282            start: function (e) {
283                $(this).find('.start').hide();
284                var that = $(this).data('blueimp-fileupload') ||
285                $(this).data('fileupload');
286                that._resetFinishedDeferreds();
287                that._transition($(this).find('.fileupload-progress')).done(
288
289                    function () {
290
291                        that._trigger('started', e);
292                    }
293                );
294            },
295            // Callback for uploads stop, equivalent to the global ajaxStop event:
296            stop: function (e) {
297                $(this).find('.start').show();
298                var that = $(this).data('blueimp-fileupload') ||
299                        $(this).data('fileupload'),
300                    deferred = that._addFinishedDeferreds();
301                $.when.apply($, that._getFinishedDeferreds())
302                    .done(function () {
303                        that._trigger('stopped', e);
304                    });
305                that._transition($(this).find('.fileupload-progress')).done(
306                    function () {
307                        $(this).find('.progress')
308                            .attr('aria-valuenow', '0')
309                            .find('.bar').css('width', '0%');
310                        $(this).find('.progress-extended').html('&nbsp;');
311                        deferred.resolve();
312                    }
313                );
314            /*
315             *  Recherche des fichers restants à uploader
316             *  Désactivation du bouton si plus rien
317             */
318             var filesList = that.options.filesContainer;
319             if(filesList.find('.start').size() == 0) {
320                var fileUploadButtonBar = that.element.find('.fileupload-buttonbar');
321                fileUploadButtonBar.find('.start').prop('disabled', true);
322                fileUploadButtonBar.find('.start').addClass('disabled');
323             }
324            /*
325             *
326             */
327            },
328            processstart: function () {
329                $(this).addClass('fileupload-processing');
330            },
331            processstop: function () {
332                $(this).removeClass('fileupload-processing');
333            },
334            // Callback for file deletion:
335            destroy: function (e, data) {
336                var that = $(this).data('blueimp-fileupload') ||
337                        $(this).data('fileupload');
338                if (data.url) {
339                    $.ajax(data).done(function () {
340                        that._transition(data.context).done(
341                            function () {
342                                $(this).remove();
343                                that._trigger('destroyed', e, data);
344                            }
345                        );
346                    });
347                }
348            }
349        },
350
351        _resetFinishedDeferreds: function () {
352            this._finishedUploads = [];
353        },
354
355        _addFinishedDeferreds: function (deferred) {
356            if (!deferred) {
357                deferred = $.Deferred();
358            }
359            this._finishedUploads.push(deferred);
360            return deferred;
361        },
362
363        _getFinishedDeferreds: function () {
364            return this._finishedUploads;
365        },
366
367        // Link handler, that allows to download files
368        // by drag & drop of the links to the desktop:
369        _enableDragToDesktop: function () {
370            var link = $(this),
371                url = link.prop('href'),
372                name = link.prop('download'),
373                type = 'application/octet-stream';
374            link.bind('dragstart', function (e) {
375                try {
376                    e.originalEvent.dataTransfer.setData(
377                        'DownloadURL',
378                        [type, name, url].join(':')
379                    );
380                } catch (ignore) {}
381            });
382        },
383
384        _formatFileSize: function (bytes) {
385            if (typeof bytes !== 'number') {
386                return '';
387            }
388            if (bytes >= 1000000000) {
389                return (bytes / 1000000000).toFixed(2) + ' GB';
390            }
391            if (bytes >= 1000000) {
392                return (bytes / 1000000).toFixed(2) + ' MB';
393            }
394            return (bytes / 1000).toFixed(2) + ' KB';
395        },
396
397        _formatBitrate: function (bits) {
398            if (typeof bits !== 'number') {
399                return '';
400            }
401            if (bits >= 1000000000) {
402                return (bits / 1000000000).toFixed(2) + ' Gbit/s';
403            }
404            if (bits >= 1000000) {
405                return (bits / 1000000).toFixed(2) + ' Mbit/s';
406            }
407            if (bits >= 1000) {
408                return (bits / 1000).toFixed(2) + ' kbit/s';
409            }
410            return bits.toFixed(2) + ' bit/s';
411        },
412
413        _formatTime: function (seconds) {
414            var date = new Date(seconds * 1000),
415                days = Math.floor(seconds / 86400);
416            days = days ? days + 'd ' : '';
417            return days +
418                ('0' + date.getUTCHours()).slice(-2) + ':' +
419                ('0' + date.getUTCMinutes()).slice(-2) + ':' +
420                ('0' + date.getUTCSeconds()).slice(-2);
421        },
422
423        _formatPercentage: function (floatValue) {
424            return (floatValue * 100).toFixed(2) + ' %';
425        },
426
427        _renderExtendedProgress: function (data) {
428            return this._formatBitrate(data.bitrate) + ' | ' +
429                this._formatTime(
430                    (data.total - data.loaded) * 8 / data.bitrate
431                ) + ' | ' +
432                this._formatPercentage(
433                    data.loaded / data.total
434                ) + ' | ' +
435                this._formatFileSize(data.loaded) + ' / ' +
436                this._formatFileSize(data.total);
437        },
438
439        _renderTemplate: function (func, files) {
440            if (!func) {
441                return $();
442            }
443            var result = func({
444                files: files,
445                formatFileSize: this._formatFileSize,
446                options: this.options
447            });
448            if (result instanceof $) {
449                return result;
450            }
451            return $(this.options.templatesContainer).html(result).children();
452        },
453
454        _renderPreviews: function (data) {
455            data.context.find('.preview').each(function (index, elm) {
456                $(elm).append(data.files[index].preview);
457            });
458        },
459
460        _renderUpload: function (files) {
461            return this._renderTemplate(
462                this.options.uploadTemplate,
463                files
464            );
465        },
466
467        _renderDownload: function (files) {
468            return this._renderTemplate(
469                this.options.downloadTemplate,
470                files
471            ).find('a[download]').each(this._enableDragToDesktop).end();
472        },
473
474        _startHandler: function (e) {
475            e.preventDefault();
476            var button = $(e.currentTarget),
477                template = button.closest('.template-upload'),
478                data = template.data('data');
479            if (data && data.submit && !data.jqXHR && data.submit()) {
480                button.prop('disabled', true);
481            }
482        },
483
484        _cancelHandler: function (e) {
485            e.preventDefault();
486            var template = $(e.currentTarget).closest('.template-upload'),
487                data = template.data('data') || {};
488            if (!data.jqXHR) {
489                data.errorThrown = 'abort';
490                this._trigger('fail', e, data);
491            } else {
492                data.jqXHR.abort();
493            }
494        },
495
496        _deleteHandler: function (e) {
497            e.preventDefault();
498            var button = $(e.currentTarget);
499            this._trigger('destroy', e, $.extend({
500                context: button.closest('.template-download'),
501                type: 'DELETE'
502            }, button.data()));
503        },
504
505        _forceReflow: function (node) {
506            return $.support.transition && node.length &&
507                node[0].offsetWidth;
508        },
509
510        _transition: function (node) {
511            var dfd = $.Deferred();
512            if ($.support.transition && node.hasClass('fade') && node.is(':visible')) {
513                node.bind(
514                    $.support.transition.end,
515                    function (e) {
516                        // Make sure we don't respond to other transitions events
517                        // in the container element, e.g. from button elements:
518                        if (e.target === node[0]) {
519                            node.unbind($.support.transition.end);
520                            dfd.resolveWith(node);
521                        }
522                    }
523                ).toggleClass('in');
524            } else {
525                node.toggleClass('in');
526                dfd.resolveWith(node);
527            }
528            return dfd;
529        },
530
531        _initButtonBarEventHandlers: function () {
532            var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
533                filesList = this.options.filesContainer;
534            this._on(fileUploadButtonBar.find('.start'), {
535                click: function (e) {
536                    e.preventDefault();
537                    filesList.find('.start').click();
538                }
539            });
540            this._on(fileUploadButtonBar.find('.cancel'), {
541                click: function (e) {
542                    e.preventDefault();
543                    filesList.find('.cancel').click();
544                }
545            });
546            this._on(fileUploadButtonBar.find('.delete'), {
547                click: function (e) {
548                    e.preventDefault();
549                    filesList.find('.toggle:checked')
550                        .closest('.template-download')
551                        .find('.delete').click();
552                    fileUploadButtonBar.find('.toggle')
553                        .prop('checked', false);
554                }
555            });
556            this._on(fileUploadButtonBar.find('.toggle'), {
557                change: function (e) {
558                    filesList.find('.toggle').prop(
559                        'checked',
560                        $(e.currentTarget).is(':checked')
561                    );
562                }
563            });
564        },
565
566        _destroyButtonBarEventHandlers: function () {
567            this._off(
568                this.element.find('.fileupload-buttonbar')
569                    .find('.start, .cancel, .delete'),
570                'click'
571            );
572            this._off(
573                this.element.find('.fileupload-buttonbar .toggle'),
574                'change.'
575            );
576        },
577
578        _initEventHandlers: function () {
579            this._super();
580            this._on(this.options.filesContainer, {
581                'click .start': this._startHandler,
582                'click .cancel': this._cancelHandler,
583                'click .delete': this._deleteHandler
584            });
585            this._initButtonBarEventHandlers();
586        },
587
588        _destroyEventHandlers: function () {
589            this._destroyButtonBarEventHandlers();
590            this._off(this.options.filesContainer, 'click');
591            this._super();
592        },
593
594        _enableFileInputButton: function () {
595            this.element.find('.fileinput-button input')
596                .prop('disabled', false)
597                .parent().removeClass('disabled');
598        },
599
600        _disableFileInputButton: function () {
601            this.element.find('.fileinput-button input')
602                .prop('disabled', true)
603                .parent().addClass('disabled');
604        },
605
606        _initTemplates: function () {
607            var options = this.options;
608            options.templatesContainer = this.document[0].createElement(
609                options.filesContainer.prop('nodeName')
610            );
611            if (tmpl) {
612                if (options.uploadTemplateId) {
613                    options.uploadTemplate = tmpl(options.uploadTemplateId);
614                }
615                if (options.downloadTemplateId) {
616                    options.downloadTemplate = tmpl(options.downloadTemplateId);
617                }
618            }
619        },
620
621        _initFilesContainer: function () {
622            var options = this.options;
623            if (options.filesContainer === undefined) {
624                options.filesContainer = this.element.find('.files');
625            } else if (!(options.filesContainer instanceof $)) {
626                options.filesContainer = $(options.filesContainer);
627            }
628        },
629
630        _initSpecialOptions: function () {
631            this._super();
632            this._initFilesContainer();
633            this._initTemplates();
634        },
635
636        _create: function () {
637            this._super();
638            this._resetFinishedDeferreds();
639        },
640
641        enable: function () {
642            var wasDisabled = false;
643            if (this.options.disabled) {
644                wasDisabled = true;
645            }
646            this._super();
647            if (wasDisabled) {
648                this.element.find('input, button').prop('disabled', false);
649                this._enableFileInputButton();
650            }
651        },
652
653        disable: function () {
654            if (!this.options.disabled) {
655                this.element.find('input, button').prop('disabled', true);
656                this._disableFileInputButton();
657            }
658            this._super();
659        }
660
661    });
662
663}));
Note: See TracBrowser for help on using the repository browser.

Sites map