avatars_for_rails 0.2.9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +1 -0
  3. data/README.rdoc +20 -71
  4. data/app/assets/javascripts/avatars_for_rails.js +67 -11
  5. data/app/assets/stylesheets/avatars_for_rails.css +0 -117
  6. data/app/controllers/avatars_controller.rb +23 -82
  7. data/app/views/avatars/_crop.html.erb +10 -0
  8. data/app/views/avatars/_form.html.erb +8 -80
  9. data/avatars_for_rails.gemspec +10 -12
  10. data/config/locales/en.yml +1 -0
  11. data/config/locales/es.yml +1 -0
  12. data/config/routes.rb +1 -4
  13. data/lib/avatars_for_rails/active_record.rb +13 -0
  14. data/lib/avatars_for_rails/avatarable.rb +86 -0
  15. data/lib/avatars_for_rails/engine.rb +13 -0
  16. data/lib/avatars_for_rails/version.rb +3 -0
  17. data/lib/avatars_for_rails.rb +24 -23
  18. data/vendor/assets/javascripts/jquery.Jcrop.js +1694 -0
  19. data/vendor/assets/javascripts/jquery.fileupload-ui.js +747 -469
  20. data/vendor/assets/javascripts/jquery.fileupload.js +1060 -867
  21. data/vendor/assets/stylesheets/jquery.Jcrop.css +161 -31
  22. metadata +98 -63
  23. data/app/models/avatar.rb +0 -149
  24. data/app/views/avatars/_errors.html.erb +0 -5
  25. data/app/views/avatars/_list.html.erb +0 -30
  26. data/app/views/avatars/_new.html.erb +0 -7
  27. data/app/views/avatars/_precrop.html.erb +0 -38
  28. data/app/views/avatars/destroy.js.erb +0 -2
  29. data/app/views/avatars/edit.html.erb +0 -6
  30. data/app/views/avatars/index.html.erb +0 -2
  31. data/app/views/avatars/new.html.erb +0 -1
  32. data/app/views/avatars/show.html.erb +0 -5
  33. data/app/views/avatars/update.js.erb +0 -9
  34. data/lib/avatars_for_rails/avatars_controller_config.rb +0 -4
  35. data/vendor/assets/javascripts/jquery.Jcrop.min.js +0 -163
@@ -1,529 +1,807 @@
1
1
  /*
2
- * jQuery File Upload User Interface Plugin 4.4
2
+ * jQuery File Upload User Interface Plugin 7.4
3
3
  * https://github.com/blueimp/jQuery-File-Upload
4
4
  *
5
5
  * Copyright 2010, Sebastian Tschan
6
6
  * https://blueimp.net
7
7
  *
8
8
  * Licensed under the MIT license:
9
- * http://creativecommons.org/licenses/MIT/
9
+ * http://www.opensource.org/licenses/MIT
10
10
  */
11
11
 
12
- /*jslint browser: true */
13
- /*global jQuery, FileReader, URL, webkitURL */
12
+ /*jslint nomen: true, unparam: true, regexp: true */
13
+ /*global define, window, URL, webkitURL, FileReader */
14
14
 
15
- (function ($) {
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
+ 'load-image',
23
+ './jquery.fileupload-fp'
24
+ ], factory);
25
+ } else {
26
+ // Browser globals:
27
+ factory(
28
+ window.jQuery,
29
+ window.tmpl,
30
+ window.loadImage
31
+ );
32
+ }
33
+ }(function ($, tmpl, loadImage) {
16
34
  'use strict';
17
35
 
18
- var undef = 'undefined',
19
- func = 'function',
20
- UploadHandler,
21
- methods,
22
-
23
- MultiLoader = function (callBack) {
24
- var loaded = 0,
25
- list = [];
26
- this.complete = function () {
27
- loaded += 1;
28
- if (loaded === list.length + 1) {
29
- // list.length * onComplete + 1 * onLoadAll
30
- callBack(list);
31
- loaded = 0;
32
- list = [];
33
- }
34
- };
35
- this.push = function (item) {
36
- list.push(item);
37
- };
38
- this.getList = function () {
39
- return list;
40
- };
41
- };
42
-
43
- UploadHandler = function (container, options) {
44
- var uploadHandler = this,
45
- dragOverTimeout,
46
- isDropZoneEnlarged,
47
- multiLoader = new MultiLoader(function (list) {
48
- uploadHandler.hideProgressBarAll(function () {
49
- uploadHandler.resetProgressBarAll();
50
- if (typeof uploadHandler.onCompleteAll === func) {
51
- uploadHandler.onCompleteAll(list);
52
- }
36
+ // The UI version extends the file upload widget
37
+ // and adds complete user interface interaction:
38
+ $.widget('blueimp.fileupload', $.blueimp.fileupload, {
39
+
40
+ options: {
41
+ // By default, files added to the widget are uploaded as soon
42
+ // as the user clicks on the start buttons. To enable automatic
43
+ // uploads, set the following option to true:
44
+ autoUpload: false,
45
+ // The following option limits the number of files that are
46
+ // allowed to be uploaded using this widget:
47
+ maxNumberOfFiles: undefined,
48
+ // The maximum allowed file size:
49
+ maxFileSize: undefined,
50
+ // The minimum allowed file size:
51
+ minFileSize: undefined,
52
+ // The regular expression for allowed file types, matches
53
+ // against either file type or file name:
54
+ acceptFileTypes: /.+$/i,
55
+ // The regular expression to define for which files a preview
56
+ // image is shown, matched against the file type:
57
+ previewSourceFileTypes: /^image\/(gif|jpeg|png)$/,
58
+ // The maximum file size of images that are to be displayed as preview:
59
+ previewSourceMaxFileSize: 5000000, // 5MB
60
+ // The maximum width of the preview images:
61
+ previewMaxWidth: 80,
62
+ // The maximum height of the preview images:
63
+ previewMaxHeight: 80,
64
+ // By default, preview images are displayed as canvas elements
65
+ // if supported by the browser. Set the following option to false
66
+ // to always display preview images as img elements:
67
+ previewAsCanvas: true,
68
+ // The ID of the upload template:
69
+ uploadTemplateId: 'template-upload',
70
+ // The ID of the download template:
71
+ downloadTemplateId: 'template-download',
72
+ // The container for the list of files. If undefined, it is set to
73
+ // an element with class "files" inside of the widget element:
74
+ filesContainer: undefined,
75
+ // By default, files are appended to the files container.
76
+ // Set the following option to true, to prepend files instead:
77
+ prependFiles: false,
78
+ // The expected data type of the upload response, sets the dataType
79
+ // option of the $.ajax upload requests:
80
+ dataType: 'json',
81
+
82
+ // The add callback is invoked as soon as files are added to the fileupload
83
+ // widget (via file input selection, drag & drop or add API call).
84
+ // See the basic file upload widget for more information:
85
+ add: function (e, data) {
86
+ var that = $(this).data('blueimp-fileupload') ||
87
+ $(this).data('fileupload'),
88
+ options = that.options,
89
+ files = data.files;
90
+ $(this).fileupload('process', data).done(function () {
91
+ that._adjustMaxNumberOfFiles(-files.length);
92
+ data.maxNumberOfFilesAdjusted = true;
93
+ data.files.valid = data.isValidated = that._validate(files);
94
+ data.context = that._renderUpload(files).data('data', data);
95
+ options.filesContainer[
96
+ options.prependFiles ? 'prepend' : 'append'
97
+ ](data.context);
98
+ that._renderPreviews(data);
99
+ that._forceReflow(data.context);
100
+ that._transition(data.context).done(
101
+ function () {
102
+ if ((that._trigger('added', e, data) !== false) &&
103
+ (options.autoUpload || data.autoUpload) &&
104
+ data.autoUpload !== false && data.isValidated) {
105
+ data.submit();
106
+ }
107
+ }
108
+ );
53
109
  });
54
- }),
55
- getUploadTable = function (handler) {
56
- return typeof handler.uploadTable === func ?
57
- handler.uploadTable(handler) : handler.uploadTable;
58
110
  },
59
- getDownloadTable = function (handler) {
60
- return typeof handler.downloadTable === func ?
61
- handler.downloadTable(handler) : handler.downloadTable;
62
- };
63
-
64
- this.requestHeaders = {'Accept': 'application/json, text/javascript, */*; q=0.01'};
65
- this.dropZone = container;
66
- this.imageTypes = /^image\/(gif|jpeg|png)$/;
67
- this.previewMaxWidth = this.previewMaxHeight = 80;
68
- this.previewLoadDelay = 100;
69
- this.previewAsCanvas = true;
70
- this.previewSelector = '.file_upload_preview';
71
- this.progressSelector = '.file_upload_progress div';
72
- this.cancelSelector = '.file_upload_cancel button';
73
- this.cssClassSmall = 'file_upload_small';
74
- this.cssClassLarge = 'file_upload_large';
75
- this.cssClassHighlight = 'file_upload_highlight';
76
- this.dropEffect = 'highlight';
77
- this.uploadTable = this.downloadTable = null;
78
- this.buildUploadRow = this.buildDownloadRow = null;
79
- this.progressAllNode = null;
80
-
81
- this.loadImage = function (file, callBack, maxWidth, maxHeight, imageTypes, noCanvas) {
82
- var img,
83
- scaleImage,
84
- urlAPI,
85
- fileReader;
86
- if (imageTypes && !imageTypes.test(file.type)) {
87
- return null;
88
- }
89
- scaleImage = function (img) {
90
- var canvas = document.createElement('canvas'),
91
- scale = Math.min(
92
- (maxWidth || img.width) / img.width,
93
- (maxHeight || img.height) / img.height
94
- );
95
- if (scale > 1) {
96
- scale = 1;
111
+ // Callback for the start of each file upload request:
112
+ send: function (e, data) {
113
+ var that = $(this).data('blueimp-fileupload') ||
114
+ $(this).data('fileupload');
115
+ if (!data.isValidated) {
116
+ if (!data.maxNumberOfFilesAdjusted) {
117
+ that._adjustMaxNumberOfFiles(-data.files.length);
118
+ data.maxNumberOfFilesAdjusted = true;
119
+ }
120
+ if (!that._validate(data.files)) {
121
+ return false;
122
+ }
97
123
  }
98
- img.width = parseInt(img.width * scale, 10);
99
- img.height = parseInt(img.height * scale, 10);
100
- if (noCanvas || typeof canvas.getContext !== func) {
101
- return img;
124
+ if (data.context && data.dataType &&
125
+ data.dataType.substr(0, 6) === 'iframe') {
126
+ // Iframe Transport does not support progress events.
127
+ // In lack of an indeterminate progress bar, we set
128
+ // the progress to 100%, showing the full animated bar:
129
+ data.context
130
+ .find('.progress').addClass(
131
+ !$.support.transition && 'progress-animated'
132
+ )
133
+ .attr('aria-valuenow', 100)
134
+ .find('.bar').css(
135
+ 'width',
136
+ '100%'
137
+ );
102
138
  }
103
- canvas.width = img.width;
104
- canvas.height = img.height;
105
- canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
106
- return canvas;
107
- };
108
- img = document.createElement('img');
109
- urlAPI = typeof URL !== undef ? URL : typeof webkitURL !== undef ? webkitURL : null;
110
- if (urlAPI && typeof urlAPI.createObjectURL === func) {
111
- img.onload = function () {
112
- urlAPI.revokeObjectURL(this.src);
113
- callBack(scaleImage(img));
114
- };
115
- img.src = urlAPI.createObjectURL(file);
116
- } else if (typeof FileReader !== undef &&
117
- typeof FileReader.prototype.readAsDataURL === func) {
118
- img.onload = function () {
119
- callBack(scaleImage(img));
120
- };
121
- fileReader = new FileReader();
122
- fileReader.onload = function (e) {
123
- img.src = e.target.result;
124
- };
125
- fileReader.readAsDataURL(file);
126
- } else {
127
- callBack(null);
128
- }
129
- };
130
-
131
- this.addNode = function (parentNode, node, callBack) {
132
- if (parentNode && parentNode.length && node && node.length) {
133
- node.css('display', 'none').appendTo(parentNode).fadeIn(function () {
134
- if (typeof callBack === func) {
135
- try {
136
- callBack();
137
- } catch (e) {
138
- // Fix endless exception loop:
139
- node.stop();
140
- throw e;
139
+ return that._trigger('sent', e, data);
140
+ },
141
+ // Callback for successful uploads:
142
+ done: function (e, data) {
143
+ var that = $(this).data('blueimp-fileupload') ||
144
+ $(this).data('fileupload'),
145
+ files = that._getFilesFromResponse(data),
146
+ template,
147
+ deferred;
148
+ if (data.context) {
149
+ data.context.each(function (index) {
150
+ var file = files[index] ||
151
+ {error: 'Empty file upload result'},
152
+ deferred = that._addFinishedDeferreds();
153
+ if (file.error) {
154
+ that._adjustMaxNumberOfFiles(1);
141
155
  }
156
+ that._transition($(this)).done(
157
+ function () {
158
+ var node = $(this);
159
+ template = that._renderDownload([file])
160
+ .replaceAll(node);
161
+ that._forceReflow(template);
162
+ that._transition(template).done(
163
+ function () {
164
+ data.context = $(this);
165
+ that._trigger('completed', e, data);
166
+ that._trigger('finished', e, data);
167
+ deferred.resolve();
168
+ }
169
+ );
170
+ }
171
+ );
172
+ });
173
+ } else {
174
+ if (files.length) {
175
+ $.each(files, function (index, file) {
176
+ if (data.maxNumberOfFilesAdjusted && file.error) {
177
+ that._adjustMaxNumberOfFiles(1);
178
+ } else if (!data.maxNumberOfFilesAdjusted &&
179
+ !file.error) {
180
+ that._adjustMaxNumberOfFiles(-1);
181
+ }
182
+ });
183
+ data.maxNumberOfFilesAdjusted = true;
142
184
  }
143
- });
144
- } else if (typeof callBack === func) {
145
- callBack();
146
- }
147
- };
148
-
149
- this.removeNode = function (node, callBack) {
150
- if (node && node.length) {
151
- node.fadeOut(function () {
152
- node.remove();
153
- if (typeof callBack === func) {
154
- try {
155
- callBack();
156
- } catch (e) {
157
- // Fix endless exception loop:
158
- node.stop();
159
- throw e;
185
+ template = that._renderDownload(files)
186
+ .appendTo(that.options.filesContainer);
187
+ that._forceReflow(template);
188
+ deferred = that._addFinishedDeferreds();
189
+ that._transition(template).done(
190
+ function () {
191
+ data.context = $(this);
192
+ that._trigger('completed', e, data);
193
+ that._trigger('finished', e, data);
194
+ deferred.resolve();
160
195
  }
161
- }
162
- });
163
- } else if (typeof callBack === func) {
164
- callBack();
165
- }
166
- };
167
-
168
- this.replaceNode = function (oldNode, newNode, callBack) {
169
- if (oldNode && newNode) {
170
- oldNode.fadeOut(function () {
171
- newNode.css('display', 'none');
172
- oldNode.replaceWith(newNode);
173
- newNode.fadeIn(function () {
174
- if (typeof callBack === func) {
175
- try {
176
- callBack();
177
- } catch (e) {
178
- // Fix endless exception loop:
179
- oldNode.stop();
180
- newNode.stop();
181
- throw e;
182
- }
196
+ );
197
+ }
198
+ },
199
+ // Callback for failed (abort or error) uploads:
200
+ fail: function (e, data) {
201
+ var that = $(this).data('blueimp-fileupload') ||
202
+ $(this).data('fileupload'),
203
+ template,
204
+ deferred;
205
+ if (data.maxNumberOfFilesAdjusted) {
206
+ that._adjustMaxNumberOfFiles(data.files.length);
207
+ }
208
+ if (data.context) {
209
+ data.context.each(function (index) {
210
+ if (data.errorThrown !== 'abort') {
211
+ var file = data.files[index];
212
+ file.error = file.error || data.errorThrown ||
213
+ true;
214
+ deferred = that._addFinishedDeferreds();
215
+ that._transition($(this)).done(
216
+ function () {
217
+ var node = $(this);
218
+ template = that._renderDownload([file])
219
+ .replaceAll(node);
220
+ that._forceReflow(template);
221
+ that._transition(template).done(
222
+ function () {
223
+ data.context = $(this);
224
+ that._trigger('failed', e, data);
225
+ that._trigger('finished', e, data);
226
+ deferred.resolve();
227
+ }
228
+ );
229
+ }
230
+ );
231
+ } else {
232
+ deferred = that._addFinishedDeferreds();
233
+ that._transition($(this)).done(
234
+ function () {
235
+ $(this).remove();
236
+ that._trigger('failed', e, data);
237
+ that._trigger('finished', e, data);
238
+ deferred.resolve();
239
+ }
240
+ );
183
241
  }
184
242
  });
185
- });
186
- } else if (typeof callBack === func) {
187
- callBack();
188
- }
189
- };
190
-
191
- this.resetProgressBarAll = function () {
192
- if (uploadHandler.progressbarAll) {
193
- uploadHandler.progressbarAll.progressbar(
194
- 'value',
195
- 0
243
+ } else if (data.errorThrown !== 'abort') {
244
+ data.context = that._renderUpload(data.files)
245
+ .appendTo(that.options.filesContainer)
246
+ .data('data', data);
247
+ that._forceReflow(data.context);
248
+ deferred = that._addFinishedDeferreds();
249
+ that._transition(data.context).done(
250
+ function () {
251
+ data.context = $(this);
252
+ that._trigger('failed', e, data);
253
+ that._trigger('finished', e, data);
254
+ deferred.resolve();
255
+ }
256
+ );
257
+ } else {
258
+ that._trigger('failed', e, data);
259
+ that._trigger('finished', e, data);
260
+ that._addFinishedDeferreds().resolve();
261
+ }
262
+ },
263
+ // Callback for upload progress events:
264
+ progress: function (e, data) {
265
+ if (data.context) {
266
+ var progress = parseInt(data.loaded / data.total * 100, 10);
267
+ data.context.find('.progress')
268
+ .attr('aria-valuenow', progress)
269
+ .find('.bar').css(
270
+ 'width',
271
+ progress + '%'
272
+ );
273
+ }
274
+ },
275
+ // Callback for global upload progress events:
276
+ progressall: function (e, data) {
277
+ var $this = $(this),
278
+ progress = parseInt(data.loaded / data.total * 100, 10),
279
+ globalProgressNode = $this.find('.fileupload-progress'),
280
+ extendedProgressNode = globalProgressNode
281
+ .find('.progress-extended');
282
+ if (extendedProgressNode.length) {
283
+ extendedProgressNode.html(
284
+ ($this.data('blueimp-fileupload') || $this.data('fileupload'))
285
+ ._renderExtendedProgress(data)
286
+ );
287
+ }
288
+ globalProgressNode
289
+ .find('.progress')
290
+ .attr('aria-valuenow', progress)
291
+ .find('.bar').css(
292
+ 'width',
293
+ progress + '%'
294
+ );
295
+ },
296
+ // Callback for uploads start, equivalent to the global ajaxStart event:
297
+ start: function (e) {
298
+ var that = $(this).data('blueimp-fileupload') ||
299
+ $(this).data('fileupload');
300
+ that._resetFinishedDeferreds();
301
+ that._transition($(this).find('.fileupload-progress')).done(
302
+ function () {
303
+ that._trigger('started', e);
304
+ }
305
+ );
306
+ },
307
+ // Callback for uploads stop, equivalent to the global ajaxStop event:
308
+ stop: function (e) {
309
+ var that = $(this).data('blueimp-fileupload') ||
310
+ $(this).data('fileupload'),
311
+ deferred = that._addFinishedDeferreds();
312
+ $.when.apply($, that._getFinishedDeferreds())
313
+ .done(function () {
314
+ that._trigger('stopped', e);
315
+ });
316
+ that._transition($(this).find('.fileupload-progress')).done(
317
+ function () {
318
+ $(this).find('.progress')
319
+ .attr('aria-valuenow', '0')
320
+ .find('.bar').css('width', '0%');
321
+ $(this).find('.progress-extended').html(' ');
322
+ deferred.resolve();
323
+ }
324
+ );
325
+ },
326
+ // Callback for file deletion:
327
+ destroy: function (e, data) {
328
+ var that = $(this).data('blueimp-fileupload') ||
329
+ $(this).data('fileupload');
330
+ if (data.url) {
331
+ $.ajax(data);
332
+ that._adjustMaxNumberOfFiles(1);
333
+ }
334
+ that._transition(data.context).done(
335
+ function () {
336
+ $(this).remove();
337
+ that._trigger('destroyed', e, data);
338
+ }
196
339
  );
197
340
  }
198
- };
199
-
200
- this.hideProgressBarAll = function (callBack) {
201
- if (uploadHandler.progressbarAll && !$(getUploadTable(uploadHandler))
202
- .find(uploadHandler.progressSelector + ':visible:first').length) {
203
- uploadHandler.progressbarAll.fadeOut(callBack);
204
- } else if (typeof callBack === func) {
205
- callBack();
341
+ },
342
+
343
+ _resetFinishedDeferreds: function () {
344
+ this._finishedUploads = [];
345
+ },
346
+
347
+ _addFinishedDeferreds: function (deferred) {
348
+ if (!deferred) {
349
+ deferred = $.Deferred();
206
350
  }
207
- };
208
-
209
- this.onAbort = function (event, files, index, xhr, handler) {
210
- handler.removeNode(handler.uploadRow, handler.hideProgressBarAll);
211
- };
212
-
213
- this.cancelUpload = function (event, files, index, xhr, handler) {
214
- var readyState = xhr.readyState;
215
- xhr.abort();
216
- // If readyState is below 2, abort() has no effect:
217
- if (typeof readyState !== 'number' || readyState < 2) {
218
- handler.onAbort(event, files, index, xhr, handler);
351
+ this._finishedUploads.push(deferred);
352
+ return deferred;
353
+ },
354
+
355
+ _getFinishedDeferreds: function () {
356
+ return this._finishedUploads;
357
+ },
358
+
359
+ _getFilesFromResponse: function (data) {
360
+ if (data.result && $.isArray(data.result.files)) {
361
+ return data.result.files;
219
362
  }
220
- };
221
-
222
- this.initProgressBar = function (node, value) {
223
- if (!node || !node.length) {
224
- return null;
363
+ return [];
364
+ },
365
+
366
+ // Link handler, that allows to download files
367
+ // by drag & drop of the links to the desktop:
368
+ _enableDragToDesktop: function () {
369
+ var link = $(this),
370
+ url = link.prop('href'),
371
+ name = link.prop('download'),
372
+ type = 'application/octet-stream';
373
+ link.bind('dragstart', function (e) {
374
+ try {
375
+ e.originalEvent.dataTransfer.setData(
376
+ 'DownloadURL',
377
+ [type, name, url].join(':')
378
+ );
379
+ } catch (err) {}
380
+ });
381
+ },
382
+
383
+ _adjustMaxNumberOfFiles: function (operand) {
384
+ if (typeof this.options.maxNumberOfFiles === 'number') {
385
+ this.options.maxNumberOfFiles += operand;
386
+ if (this.options.maxNumberOfFiles < 1) {
387
+ this._disableFileInputButton();
388
+ } else {
389
+ this._enableFileInputButton();
390
+ }
225
391
  }
226
- if (typeof node.progressbar === func) {
227
- return node.progressbar({
228
- value: value
229
- });
230
- } else {
231
- node.addClass('progressbar')
232
- .append($('<div/>').css('width', value + '%'))
233
- .progressbar = function (key, value) {
234
- return this.each(function () {
235
- if (key === 'destroy') {
236
- $(this).removeClass('progressbar').empty();
237
- } else {
238
- $(this).children().css('width', value + '%');
239
- }
240
- });
241
- };
242
- return node;
392
+ },
393
+
394
+ _formatFileSize: function (bytes) {
395
+ if (typeof bytes !== 'number') {
396
+ return '';
243
397
  }
244
- };
245
-
246
- this.destroyProgressBar = function (node) {
247
- if (!node || !node.length) {
248
- return null;
398
+ if (bytes >= 1000000000) {
399
+ return (bytes / 1000000000).toFixed(2) + ' GB';
249
400
  }
250
- return node.progressbar('destroy');
251
- };
252
-
253
- this.initUploadProgress = function (xhr, handler) {
254
- if (!xhr.upload && handler.progressbar) {
255
- handler.progressbar.progressbar(
256
- 'value',
257
- 100 // indeterminate progress displayed by a full animated progress bar
258
- );
401
+ if (bytes >= 1000000) {
402
+ return (bytes / 1000000).toFixed(2) + ' MB';
259
403
  }
260
- };
404
+ return (bytes / 1000).toFixed(2) + ' KB';
405
+ },
261
406
 
262
- this.initUploadProgressAll = function () {
263
- if (uploadHandler.progressbarAll && uploadHandler.progressbarAll.is(':hidden')) {
264
- uploadHandler.progressbarAll.fadeIn();
407
+ _formatBitrate: function (bits) {
408
+ if (typeof bits !== 'number') {
409
+ return '';
410
+ }
411
+ if (bits >= 1000000000) {
412
+ return (bits / 1000000000).toFixed(2) + ' Gbit/s';
413
+ }
414
+ if (bits >= 1000000) {
415
+ return (bits / 1000000).toFixed(2) + ' Mbit/s';
265
416
  }
266
- };
417
+ if (bits >= 1000) {
418
+ return (bits / 1000).toFixed(2) + ' kbit/s';
419
+ }
420
+ return bits.toFixed(2) + ' bit/s';
421
+ },
267
422
 
268
- this.onSend = function (event, files, index, xhr, handler) {
269
- handler.initUploadProgress(xhr, handler);
270
- };
423
+ _formatTime: function (seconds) {
424
+ var date = new Date(seconds * 1000),
425
+ days = parseInt(seconds / 86400, 10);
426
+ days = days ? days + 'd ' : '';
427
+ return days +
428
+ ('0' + date.getUTCHours()).slice(-2) + ':' +
429
+ ('0' + date.getUTCMinutes()).slice(-2) + ':' +
430
+ ('0' + date.getUTCSeconds()).slice(-2);
431
+ },
271
432
 
272
- this.onProgress = function (event, files, index, xhr, handler) {
273
- if (handler.progressbar && event.lengthComputable) {
274
- handler.progressbar.progressbar(
275
- 'value',
276
- parseInt(event.loaded / event.total * 100, 10)
277
- );
278
- }
279
- };
433
+ _formatPercentage: function (floatValue) {
434
+ return (floatValue * 100).toFixed(2) + ' %';
435
+ },
280
436
 
281
- this.onProgressAll = function (event, list) {
282
- if (uploadHandler.progressbarAll && event.lengthComputable) {
283
- uploadHandler.progressbarAll.progressbar(
284
- 'value',
285
- parseInt(event.loaded / event.total * 100, 10)
286
- );
437
+ _renderExtendedProgress: function (data) {
438
+ return this._formatBitrate(data.bitrate) + ' | ' +
439
+ this._formatTime(
440
+ (data.total - data.loaded) * 8 / data.bitrate
441
+ ) + ' | ' +
442
+ this._formatPercentage(
443
+ data.loaded / data.total
444
+ ) + ' | ' +
445
+ this._formatFileSize(data.loaded) + ' / ' +
446
+ this._formatFileSize(data.total);
447
+ },
448
+
449
+ _hasError: function (file) {
450
+ if (file.error) {
451
+ return file.error;
287
452
  }
288
- };
289
-
290
- this.onLoadAll = function (list) {
291
- multiLoader.complete();
292
- };
293
-
294
- this.initProgressBarAll = function () {
295
- if (!uploadHandler.progressbarAll) {
296
- uploadHandler.progressbarAll = uploadHandler.initProgressBar(
297
- (typeof uploadHandler.progressAllNode === func ?
298
- uploadHandler.progressAllNode(uploadHandler) : uploadHandler.progressAllNode),
299
- 0
300
- );
453
+ // The number of added files is subtracted from
454
+ // maxNumberOfFiles before validation, so we check if
455
+ // maxNumberOfFiles is below 0 (instead of below 1):
456
+ if (this.options.maxNumberOfFiles < 0) {
457
+ return 'Maximum number of files exceeded';
301
458
  }
302
- };
303
-
304
- this.destroyProgressBarAll = function () {
305
- uploadHandler.destroyProgressBar(uploadHandler.progressbarAll);
306
- };
307
-
308
- this.loadPreviewImage = function (files, index, handler) {
309
- index = index || 0;
310
- handler.uploadRow.find(handler.previewSelector).each(function () {
311
- var previewNode = $(this),
312
- file = files[index];
313
- setTimeout(function () {
314
- handler.loadImage(
315
- file,
316
- function (img) {
317
- handler.addNode(
318
- previewNode,
319
- $(img)
320
- );
321
- },
322
- handler.previewMaxWidth,
323
- handler.previewMaxHeight,
324
- handler.imageTypes,
325
- !handler.previewAsCanvas
326
- );
327
- }, handler.previewLoadDelay);
328
- index += 1;
459
+ // Files are accepted if either the file type or the file name
460
+ // matches against the acceptFileTypes regular expression, as
461
+ // only browsers with support for the File API report the type:
462
+ if (!(this.options.acceptFileTypes.test(file.type) ||
463
+ this.options.acceptFileTypes.test(file.name))) {
464
+ return 'Filetype not allowed';
465
+ }
466
+ if (this.options.maxFileSize &&
467
+ file.size > this.options.maxFileSize) {
468
+ return 'File is too big';
469
+ }
470
+ if (typeof file.size === 'number' &&
471
+ file.size < this.options.minFileSize) {
472
+ return 'File is too small';
473
+ }
474
+ return null;
475
+ },
476
+
477
+ _validate: function (files) {
478
+ var that = this,
479
+ valid = !!files.length;
480
+ $.each(files, function (index, file) {
481
+ file.error = that._hasError(file);
482
+ if (file.error) {
483
+ valid = false;
484
+ }
329
485
  });
330
- };
331
-
332
- this.initUploadRow = function (event, files, index, xhr, handler) {
333
- var uploadRow = handler.uploadRow = (typeof handler.buildUploadRow === func ?
334
- handler.buildUploadRow(files, index, handler) : null);
335
- if (uploadRow) {
336
- handler.progressbar = handler.initProgressBar(
337
- uploadRow.find(handler.progressSelector),
338
- 0
339
- );
340
- uploadRow.find(handler.cancelSelector).click(function (e) {
341
- handler.cancelUpload(e, files, index, xhr, handler);
342
- e.preventDefault();
343
- });
344
- handler.loadPreviewImage(files, index, handler);
486
+ return valid;
487
+ },
488
+
489
+ _renderTemplate: function (func, files) {
490
+ if (!func) {
491
+ return $();
492
+ }
493
+ var result = func({
494
+ files: files,
495
+ formatFileSize: this._formatFileSize,
496
+ options: this.options
497
+ });
498
+ if (result instanceof $) {
499
+ return result;
345
500
  }
346
- };
347
-
348
- this.initUpload = function (event, files, index, xhr, handler, callBack) {
349
- handler.initUploadRow(event, files, index, xhr, handler);
350
- handler.addNode(
351
- getUploadTable(handler),
352
- handler.uploadRow,
353
- function () {
354
- if (typeof handler.beforeSend === func) {
355
- handler.beforeSend(event, files, index, xhr, handler, callBack);
356
- } else {
357
- callBack();
501
+ return $(this.options.templatesContainer).html(result).children();
502
+ },
503
+
504
+ _renderPreview: function (file, node) {
505
+ var that = this,
506
+ options = this.options,
507
+ dfd = $.Deferred();
508
+ return ((loadImage && loadImage(
509
+ file,
510
+ function (img) {
511
+ node.append(img);
512
+ that._forceReflow(node);
513
+ that._transition(node).done(function () {
514
+ dfd.resolveWith(node);
515
+ });
516
+ if (!$.contains(that.document[0].body, node[0])) {
517
+ // If the element is not part of the DOM,
518
+ // transition events are not triggered,
519
+ // so we have to resolve manually:
520
+ dfd.resolveWith(node);
358
521
  }
522
+ node.on('remove', function () {
523
+ // If the element is removed before the
524
+ // transition finishes, transition events are
525
+ // not triggered, resolve manually:
526
+ dfd.resolveWith(node);
527
+ });
528
+ },
529
+ {
530
+ maxWidth: options.previewMaxWidth,
531
+ maxHeight: options.previewMaxHeight,
532
+ canvas: options.previewAsCanvas
533
+ }
534
+ )) || dfd.resolveWith(node)) && dfd;
535
+ },
536
+
537
+ _renderPreviews: function (data) {
538
+ var that = this,
539
+ options = this.options;
540
+ data.context.find('.preview span').each(function (index, element) {
541
+ var file = data.files[index];
542
+ if (options.previewSourceFileTypes.test(file.type) &&
543
+ ($.type(options.previewSourceMaxFileSize) !== 'number' ||
544
+ file.size < options.previewSourceMaxFileSize)) {
545
+ that._processingQueue = that._processingQueue.pipe(function () {
546
+ var dfd = $.Deferred(),
547
+ ev = $.Event('previewdone', {
548
+ target: element
549
+ });
550
+ that._renderPreview(file, $(element)).done(
551
+ function () {
552
+ that._trigger(ev.type, ev, data);
553
+ dfd.resolveWith(that);
554
+ }
555
+ );
556
+ return dfd.promise();
557
+ });
359
558
  }
559
+ });
560
+ return this._processingQueue;
561
+ },
562
+
563
+ _renderUpload: function (files) {
564
+ return this._renderTemplate(
565
+ this.options.uploadTemplate,
566
+ files
360
567
  );
361
- handler.initUploadProgressAll();
362
- };
363
-
364
- this.parseResponse = function (xhr, handler) {
365
- if (typeof xhr.responseText !== undef) {
366
- return $.parseJSON(xhr.responseText);
367
- } else {
368
- // Instead of an XHR object, an iframe is used for legacy browsers:
369
- return $.parseJSON(xhr.contents().text());
568
+ },
569
+
570
+ _renderDownload: function (files) {
571
+ return this._renderTemplate(
572
+ this.options.downloadTemplate,
573
+ files
574
+ ).find('a[download]').each(this._enableDragToDesktop).end();
575
+ },
576
+
577
+ _startHandler: function (e) {
578
+ e.preventDefault();
579
+ var button = $(e.currentTarget),
580
+ template = button.closest('.template-upload'),
581
+ data = template.data('data');
582
+ if (data && data.submit && !data.jqXHR && data.submit()) {
583
+ button.prop('disabled', true);
370
584
  }
371
- };
372
-
373
- this.initDownloadRow = function (event, files, index, xhr, handler) {
374
- var json, downloadRow;
375
- try {
376
- json = handler.response = handler.parseResponse(xhr, handler);
377
- } catch (e) {
378
- if (typeof handler.onError === func) {
379
- handler.originalEvent = event;
380
- handler.onError(e, files, index, xhr, handler);
381
- } else {
382
- throw e;
383
- }
585
+ },
586
+
587
+ _cancelHandler: function (e) {
588
+ e.preventDefault();
589
+ var template = $(e.currentTarget).closest('.template-upload'),
590
+ data = template.data('data') || {};
591
+ if (!data.jqXHR) {
592
+ data.errorThrown = 'abort';
593
+ this._trigger('fail', e, data);
594
+ } else {
595
+ data.jqXHR.abort();
384
596
  }
385
- downloadRow = handler.downloadRow = (typeof handler.buildDownloadRow === func ?
386
- handler.buildDownloadRow(json, handler) : null);
387
- };
388
-
389
- this.onLoad = function (event, files, index, xhr, handler) {
390
- var uploadTable = getUploadTable(handler),
391
- downloadTable = getDownloadTable(handler),
392
- callBack = function () {
393
- if (typeof handler.onComplete === func) {
394
- handler.onComplete(event, files, index, xhr, handler);
597
+ },
598
+
599
+ _deleteHandler: function (e) {
600
+ e.preventDefault();
601
+ var button = $(e.currentTarget);
602
+ this._trigger('destroy', e, $.extend({
603
+ context: button.closest('.template-download'),
604
+ type: 'DELETE',
605
+ dataType: this.options.dataType
606
+ }, button.data()));
607
+ },
608
+
609
+ _forceReflow: function (node) {
610
+ return $.support.transition && node.length &&
611
+ node[0].offsetWidth;
612
+ },
613
+
614
+ _transition: function (node) {
615
+ var dfd = $.Deferred();
616
+ if ($.support.transition && node.hasClass('fade') && node.is(':visible')) {
617
+ node.bind(
618
+ $.support.transition.end,
619
+ function (e) {
620
+ // Make sure we don't respond to other transitions events
621
+ // in the container element, e.g. from button elements:
622
+ if (e.target === node[0]) {
623
+ node.unbind($.support.transition.end);
624
+ dfd.resolveWith(node);
625
+ }
395
626
  }
396
- multiLoader.complete();
397
- };
398
- multiLoader.push(Array.prototype.slice.call(arguments, 1));
399
- handler.initDownloadRow(event, files, index, xhr, handler);
400
- if (uploadTable && (!downloadTable || uploadTable.get(0) === downloadTable.get(0))) {
401
- handler.replaceNode(handler.uploadRow, handler.downloadRow, callBack);
627
+ ).toggleClass('in');
402
628
  } else {
403
- handler.removeNode(handler.uploadRow, function () {
404
- handler.addNode(
405
- downloadTable,
406
- handler.downloadRow,
407
- callBack
408
- );
409
- });
629
+ node.toggleClass('in');
630
+ dfd.resolveWith(node);
410
631
  }
411
- };
412
-
413
- this.dropZoneEnlarge = function () {
414
- if (!isDropZoneEnlarged) {
415
- if (typeof uploadHandler.dropZone.switchClass === func) {
416
- uploadHandler.dropZone.switchClass(
417
- uploadHandler.cssClassSmall,
418
- uploadHandler.cssClassLarge
632
+ return dfd;
633
+ },
634
+
635
+ _initButtonBarEventHandlers: function () {
636
+ var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
637
+ filesList = this.options.filesContainer;
638
+ this._on(fileUploadButtonBar.find('.start'), {
639
+ click: function (e) {
640
+ e.preventDefault();
641
+ filesList.find('.start').click();
642
+ }
643
+ });
644
+ this._on(fileUploadButtonBar.find('.cancel'), {
645
+ click: function (e) {
646
+ e.preventDefault();
647
+ filesList.find('.cancel').click();
648
+ }
649
+ });
650
+ this._on(fileUploadButtonBar.find('.delete'), {
651
+ click: function (e) {
652
+ e.preventDefault();
653
+ filesList.find('.toggle:checked')
654
+ .closest('.template-download')
655
+ .find('.delete').click();
656
+ fileUploadButtonBar.find('.toggle')
657
+ .prop('checked', false);
658
+ }
659
+ });
660
+ this._on(fileUploadButtonBar.find('.toggle'), {
661
+ change: function (e) {
662
+ filesList.find('.toggle').prop(
663
+ 'checked',
664
+ $(e.currentTarget).is(':checked')
419
665
  );
420
- } else {
421
- uploadHandler.dropZone.addClass(uploadHandler.cssClassLarge);
422
- uploadHandler.dropZone.removeClass(uploadHandler.cssClassSmall);
423
666
  }
424
- isDropZoneEnlarged = true;
425
- }
426
- };
427
-
428
- this.dropZoneReduce = function () {
429
- if (typeof uploadHandler.dropZone.switchClass === func) {
430
- uploadHandler.dropZone.switchClass(
431
- uploadHandler.cssClassLarge,
432
- uploadHandler.cssClassSmall
433
- );
434
- } else {
435
- uploadHandler.dropZone.addClass(uploadHandler.cssClassSmall);
436
- uploadHandler.dropZone.removeClass(uploadHandler.cssClassLarge);
437
- }
438
- isDropZoneEnlarged = false;
439
- };
440
-
441
- this.onDocumentDragEnter = function (event) {
442
- uploadHandler.dropZoneEnlarge();
443
- };
444
-
445
- this.onDocumentDragOver = function (event) {
446
- if (dragOverTimeout) {
447
- clearTimeout(dragOverTimeout);
448
- }
449
- dragOverTimeout = setTimeout(function () {
450
- uploadHandler.dropZoneReduce();
451
- }, 200);
452
- };
453
-
454
- this.onDragEnter = this.onDragLeave = function (event) {
455
- uploadHandler.dropZone.toggleClass(uploadHandler.cssClassHighlight);
456
- };
457
-
458
- this.onDrop = function (event) {
459
- if (dragOverTimeout) {
460
- clearTimeout(dragOverTimeout);
667
+ });
668
+ },
669
+
670
+ _destroyButtonBarEventHandlers: function () {
671
+ this._off(
672
+ this.element.find('.fileupload-buttonbar')
673
+ .find('.start, .cancel, .delete'),
674
+ 'click'
675
+ );
676
+ this._off(
677
+ this.element.find('.fileupload-buttonbar .toggle'),
678
+ 'change.'
679
+ );
680
+ },
681
+
682
+ _initEventHandlers: function () {
683
+ this._super();
684
+ this._on(this.options.filesContainer, {
685
+ 'click .start': this._startHandler,
686
+ 'click .cancel': this._cancelHandler,
687
+ 'click .delete': this._deleteHandler
688
+ });
689
+ this._initButtonBarEventHandlers();
690
+ },
691
+
692
+ _destroyEventHandlers: function () {
693
+ this._destroyButtonBarEventHandlers();
694
+ this._off(this.options.filesContainer, 'click');
695
+ this._super();
696
+ },
697
+
698
+ _enableFileInputButton: function () {
699
+ this.element.find('.fileinput-button input')
700
+ .prop('disabled', false)
701
+ .parent().removeClass('disabled');
702
+ },
703
+
704
+ _disableFileInputButton: function () {
705
+ this.element.find('.fileinput-button input')
706
+ .prop('disabled', true)
707
+ .parent().addClass('disabled');
708
+ },
709
+
710
+ _initTemplates: function () {
711
+ var options = this.options;
712
+ options.templatesContainer = this.document[0].createElement(
713
+ options.filesContainer.prop('nodeName')
714
+ );
715
+ if (tmpl) {
716
+ if (options.uploadTemplateId) {
717
+ options.uploadTemplate = tmpl(options.uploadTemplateId);
718
+ }
719
+ if (options.downloadTemplateId) {
720
+ options.downloadTemplate = tmpl(options.downloadTemplateId);
721
+ }
461
722
  }
462
- if (uploadHandler.dropEffect && typeof uploadHandler.dropZone.effect === func) {
463
- uploadHandler.dropZone.effect(uploadHandler.dropEffect, function () {
464
- uploadHandler.dropZone.removeClass(uploadHandler.cssClassHighlight);
465
- uploadHandler.dropZoneReduce();
466
- });
467
- } else {
468
- uploadHandler.dropZone.removeClass(uploadHandler.cssClassHighlight);
469
- uploadHandler.dropZoneReduce();
723
+ },
724
+
725
+ _initFilesContainer: function () {
726
+ var options = this.options;
727
+ if (options.filesContainer === undefined) {
728
+ options.filesContainer = this.element.find('.files');
729
+ } else if (!(options.filesContainer instanceof $)) {
730
+ options.filesContainer = $(options.filesContainer);
470
731
  }
471
- };
732
+ },
472
733
 
473
- this.init = function () {
474
- uploadHandler.initProgressBarAll();
475
- if (typeof uploadHandler.initExtended === func) {
476
- uploadHandler.initExtended();
734
+ _stringToRegExp: function (str) {
735
+ var parts = str.split('/'),
736
+ modifiers = parts.pop();
737
+ parts.shift();
738
+ return new RegExp(parts.join('/'), modifiers);
739
+ },
740
+
741
+ _initRegExpOptions: function () {
742
+ var options = this.options;
743
+ if ($.type(options.acceptFileTypes) === 'string') {
744
+ options.acceptFileTypes = this._stringToRegExp(
745
+ options.acceptFileTypes
746
+ );
477
747
  }
478
- };
479
-
480
- this.destroy = function () {
481
- if (typeof uploadHandler.destroyExtended === func) {
482
- uploadHandler.destroyExtended();
748
+ if ($.type(options.previewSourceFileTypes) === 'string') {
749
+ options.previewSourceFileTypes = this._stringToRegExp(
750
+ options.previewSourceFileTypes
751
+ );
483
752
  }
484
- uploadHandler.destroyProgressBarAll();
485
- };
753
+ },
486
754
 
487
- $.extend(this, options);
488
- };
755
+ _initSpecialOptions: function () {
756
+ this._super();
757
+ this._initFilesContainer();
758
+ this._initTemplates();
759
+ this._initRegExpOptions();
760
+ },
489
761
 
490
- methods = {
491
- init : function (options) {
492
- return this.each(function () {
493
- $(this).fileUpload(new UploadHandler($(this), options));
494
- });
762
+ _setOption: function (key, value) {
763
+ this._super(key, value);
764
+ if (key === 'maxNumberOfFiles') {
765
+ this._adjustMaxNumberOfFiles(0);
766
+ }
495
767
  },
496
-
497
- option: function (option, value, namespace) {
498
- if (!option || (typeof option === 'string' && typeof value === undef)) {
499
- return $(this).fileUpload('option', option, value, namespace);
768
+
769
+ _create: function () {
770
+ this._super();
771
+ this._refreshOptionsList.push(
772
+ 'filesContainer',
773
+ 'uploadTemplateId',
774
+ 'downloadTemplateId'
775
+ );
776
+ if (!this._processingQueue) {
777
+ this._processingQueue = $.Deferred().resolveWith(this).promise();
778
+ this.process = function () {
779
+ return this._processingQueue;
780
+ };
500
781
  }
501
- return this.each(function () {
502
- $(this).fileUpload('option', option, value, namespace);
503
- });
782
+ this._resetFinishedDeferreds();
504
783
  },
505
-
506
- destroy : function (namespace) {
507
- return this.each(function () {
508
- $(this).fileUpload('destroy', namespace);
509
- });
784
+
785
+ enable: function () {
786
+ var wasDisabled = false;
787
+ if (this.options.disabled) {
788
+ wasDisabled = true;
789
+ }
790
+ this._super();
791
+ if (wasDisabled) {
792
+ this.element.find('input, button').prop('disabled', false);
793
+ this._enableFileInputButton();
794
+ }
510
795
  },
511
-
512
- upload: function (files, namespace) {
513
- return this.each(function () {
514
- $(this).fileUpload('upload', files, namespace);
515
- });
516
- }
517
- };
518
-
519
- $.fn.fileUploadUI = function (method) {
520
- if (methods[method]) {
521
- return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
522
- } else if (typeof method === 'object' || !method) {
523
- return methods.init.apply(this, arguments);
524
- } else {
525
- $.error('Method "' + method + '" does not exist on jQuery.fileUploadUI');
796
+
797
+ disable: function () {
798
+ if (!this.options.disabled) {
799
+ this.element.find('input, button').prop('disabled', true);
800
+ this._disableFileInputButton();
801
+ }
802
+ this._super();
526
803
  }
527
- };
528
-
529
- }(jQuery));
804
+
805
+ });
806
+
807
+ }));