This commit is contained in:
SDE
2023-05-16 17:14:16 +03:00
commit c17da7eaab
157 changed files with 14503 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 223 KiB

View File

@@ -0,0 +1,294 @@
.files-widget {
display: inline-block;
width: 100%;
}
.files-widget-dropbox {
width: 100%;
min-height: 100px;
border: 1px solid transparent;
margin: 0 -3px;
display: inline-block;
}
.files-widget-dropbox.dragging-files {
background: rgba(0, 0, 0, .05);
border: 1px dashed rgba(0, 0, 0, .2);
}
.files-widget-dropbox.dragging-files.dragover {
background: rgba(0, 0, 0, .1);
border: 1px dashed rgba(0, 0, 0, .4);
}
.files-widget-dropbox .message {
display: block;
color: #a0a2a4;
margin: 30px;
text-align: center;
}
/*для файлов*/
.files-widget-dropbox .preview.filetype, .files-widget-dropbox .sortable-placeholder {
padding: 5px;
display: flex;
vertical-align: middle;
position: relative;
text-align: center;
width: 400px;
float: left;
margin-right: 10px;
}
/*для картинок*/
.files-widget-dropbox .preview, .files-widget-dropbox .sortable-placeholder {
padding: 5px;
display: inline-block;
vertical-align: middle;
position: relative;
text-align: center;
}
.files-widget-dropbox .sortable-placeholder {
background: rgba(0, 0, 0, .1);
}
.files-widget .image-holder {
display: inline-block;
position: relative;
border: 3px solid white;
box-shadow: 0 1px 4px rgba(0, 0, 0, .8);
border-radius: 3px;
background: white;
text-align: center;
}
.files-widget-dropbox .image-holder {
min-height: 50px;
/*min-width: 50px;*/
line-height: 50px;
}
.files-widget-dropbox .image-holder.icon100 {
min-height: 100px;
/*min-width: 100px;*/
line-height: 100px;
}
.files-widget-dropbox .image-holder.icon30 {
min-height: 30px;
/*min-width: 30px;*/
line-height: 30px;
margin-right: 10px;
}
.files-widget-dropbox .preview .thumbnail {
vertical-align: middle;
background: url(/static/files_widget/img/file-icons/file_icon.png) left top;
height: 50px;
/*width: 50px;*/
}
.files-widget-dropbox .preview .thumbnail.icon100 {
vertical-align: middle;
background: url(/static/files_widget/img/file-icons/file_icon.png) left top;
height: 100px;
/*width: 100px;*/
}
.files-widget-dropbox .preview .thumbnail.icon30 {
vertical-align: middle;
background: url(/static/files_widget/img/file-icons/file_icon.png) left top;
height: 30px;
/*width: 100px;*/
}
.file-name-for-icon100 {
overflow: hidden;
width: 100px;
text-overflow: ellipsis;
white-space: nowrap;
height: 10px;
margin-top: 5px;
font-size: 10px;
}
.file-name-for-icon30 {
overflow: hidden;
width: 100%;
/*text-overflow: ellipsis;*/
/*white-space: nowrap;*/
height: 100%;
margin-top: 5px;
font-size: 10px;
text-align: left;
}
.files-widget-dropbox .preview.new .thumbnail {
opacity: .5;
}
.files-widget-dropbox .buttons {
position: absolute;
top: -10px;
right: -10px;
opacity: 0;
white-space: nowrap;
display: block;
}
.files-widget-dropbox .buttons img {
vertical-align: top;
}
.files-widget-dropbox .preview:hover .buttons {
opacity: 1;
}
.files-widget-dropbox .preview.ui-sortable-helper .buttons,
.files-widget-dropbox .preview.new .buttons {
display: none;
}
.files-widget-dropbox .preview:hover .buttons a {
margin: -2px;
}
.files-widget-dropbox .uploaded {
position: absolute;
top:0;
left:0;
height:100%;
width:100%;
background: url('../img/done.png') no-repeat center center rgba(255,255,255,0.5);
display: none;
}
.files-widget-dropbox .preview.done .uploaded {
display: block;
}
.files-widget-dropbox .filename {
display: block;
position: absolute;
left: 0;
right: 0;
top: 20px;
overflow: hidden;
}
.files-widget-dropbox .progress-holder {
position: absolute;
background-color: #252f38;
height: 10px;
right: 8px;
left: 8px;
bottom: 8px;
box-shadow: 0 0 2px #000;
}
.files-widget-dropbox .progress {
background-color: #2586d0;
position: absolute;
height: 100%;
left: 0;
width: 0;
box-shadow: 0 0 1px rgba(255, 255, 255, 0.4) inset;
-moz-transition: 0.25s;
-webkit-transition: 0.25s;
-o-transition: 0.25s;
transition: 0.25s;
}
.files-widget-dropbox .preview.done .progress {
width:100% !important;
}
.files-widget .controls {
padding: 8px 0 0;
text-align: left;
}
.files-widget .controls .fake-files-input {
margin-left: 2px;
position: relative;
display: inline-block;
overflow: hidden;
}
.files-widget .controls .files-input {
padding: 4px;
opacity: .0001;
position: absolute;
top: 0;
bottom: 0;
right: 0;
cursor: pointer;
}
.files-widget .controls input[type=text].add-by-url {
width: 300px;
}
.files-widget .controls .upload-progress-stats {
float: right;
display: block;
padding-top: 5px;
color: #888;
}
.files-widget-deleted {
}
.files-widget-deleted p {
color: #bf3030;
border-bottom: 1px solid #e0e0e0;
padding: 0 1px !important;
margin-top: 10px;
margin-left: 0 !important;
}
.files-widget-deleted .deleted-list {
border-top: 1px solid white;
padding-top: 5px;
}
.files-widget-deleted .deleted-file {
height: 38px;
line-height: 38px;
margin-bottom: 5px;
}
.files-widget-deleted .deleted-file > span {
display: inline-block;
vertical-align: middle;
}
.files-widget-deleted .deleted-file .image-holder {
min-height: 32px;
min-width: 32px;
line-height: 32px;
margin: 0 5px 0 3px;
}
.files-widget-deleted .deleted-file .icon {
max-height: 32px;
max-width: 32px;
vertical-align: middle;
}
.files-widget-deleted .deleted-file .name {
white-space: nowrap;
text-decoration: line-through;
margin: 0 10px;
}
.files-widget-deleted .deleted-file .undo {
font-weight: bold;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 B

View File

@@ -0,0 +1,348 @@
/*
* jQuery File Upload AngularJS Plugin 1.0.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true */
/*global angular */
(function () {
'use strict';
angular.module('blueimp.fileupload', [])
.provider('fileUpload', function () {
var scopeApply = function () {
var scope = angular.element(this)
.fileupload('option', 'scope')();
if (!scope.$$phase) {
scope.$apply();
}
},
$config;
$config = this.defaults = {
handleResponse: function (e, data) {
var files = data.result && data.result.files;
if (files) {
data.scope().replace(data.files, files);
} else if (data.errorThrown ||
data.textStatus === 'error') {
data.files[0].error = data.errorThrown ||
data.textStatus;
}
},
add: function (e, data) {
var scope = data.scope();
data.process(function () {
return scope.process(data);
}).always(
function () {
var file = data.files[0],
submit = function () {
return data.submit();
};
file.$cancel = function () {
scope.clear(data.files);
return data.abort();
};
file.$state = function () {
return data.state();
};
file.$progress = function () {
return data.progress();
};
file.$response = function () {
return data.response();
};
if (file.$state() === 'rejected') {
file._$submit = submit;
} else {
file.$submit = submit;
}
scope.$apply(function () {
var method = scope.option('prependFiles') ?
'unshift' : 'push';
Array.prototype[method].apply(
scope.queue,
data.files
);
if (file.$submit &&
(scope.option('autoUpload') ||
data.autoUpload) &&
data.autoUpload !== false) {
file.$submit();
}
});
}
);
},
progress: function (e, data) {
data.scope().$apply();
},
done: function (e, data) {
var that = this;
data.scope().$apply(function () {
data.handleResponse.call(that, e, data);
});
},
fail: function (e, data) {
var that = this;
if (data.errorThrown === 'abort') {
return;
}
if (data.dataType.indexOf('json') === data.dataType.length - 4) {
try {
data.result = angular.fromJson(data.jqXHR.responseText);
} catch (err) {}
}
data.scope().$apply(function () {
data.handleResponse.call(that, e, data);
});
},
stop: scopeApply,
processstart: scopeApply,
processstop: scopeApply,
getNumberOfFiles: function () {
return this.scope().queue.length;
},
dataType: 'json',
prependFiles: true,
autoUpload: false
};
this.$get = [
function () {
return {
defaults: $config
};
}
];
})
.provider('formatFileSizeFilter', function () {
var $config = this.defaults = {
// Byte units following the IEC format
// http://en.wikipedia.org/wiki/Kilobyte
units: [
{size: 1000000000, suffix: ' GB'},
{size: 1000000, suffix: ' MB'},
{size: 1000, suffix: ' KB'}
]
};
this.$get = function () {
return function (bytes) {
if (!angular.isNumber(bytes)) {
return '';
}
var unit = true,
i = -1;
while (unit) {
unit = $config.units[i += 1];
if (i === $config.units.length - 1 || bytes >= unit.size) {
return (bytes / unit.size).toFixed(2) + unit.suffix;
}
}
};
};
})
.controller('FileUploadController', [
'$scope', '$element', '$attrs', 'fileUpload',
function ($scope, $element, $attrs, fileUpload) {
$scope.disabled = angular.element('<input type="file">')
.prop('disabled');
$scope.queue = $scope.queue || [];
$scope.clear = function (files) {
var queue = this.queue,
i = queue.length,
file = files,
length = 1;
if (angular.isArray(files)) {
file = files[0];
length = files.length;
}
while (i) {
if (queue[i -= 1] === file) {
return queue.splice(i, length);
}
}
};
$scope.replace = function (oldFiles, newFiles) {
var queue = this.queue,
file = oldFiles[0],
i,
j;
for (i = 0; i < queue.length; i += 1) {
if (queue[i] === file) {
for (j = 0; j < newFiles.length; j += 1) {
queue[i + j] = newFiles[j];
}
return;
}
}
};
$scope.progress = function () {
return $element.fileupload('progress');
};
$scope.active = function () {
return $element.fileupload('active');
};
$scope.option = function (option, data) {
return $element.fileupload('option', option, data);
};
$scope.add = function (data) {
return $element.fileupload('add', data);
};
$scope.send = function (data) {
return $element.fileupload('send', data);
};
$scope.process = function (data) {
return $element.fileupload('process', data);
};
$scope.processing = function (data) {
return $element.fileupload('processing', data);
};
$scope.applyOnQueue = function (method) {
var list = this.queue.slice(0),
i,
file;
for (i = 0; i < list.length; i += 1) {
file = list[i];
if (file[method]) {
file[method]();
}
}
};
$scope.submit = function () {
this.applyOnQueue('$submit');
};
$scope.cancel = function () {
this.applyOnQueue('$cancel');
};
// The fileupload widget will initialize with
// the options provided via "data-"-parameters,
// as well as those given via options object:
$element.fileupload(angular.extend(
{scope: function () {
return $scope;
}},
fileUpload.defaults
)).on('fileuploadadd', function (e, data) {
data.scope = $scope.option('scope');
}).on([
'fileuploadadd',
'fileuploadsubmit',
'fileuploadsend',
'fileuploaddone',
'fileuploadfail',
'fileuploadalways',
'fileuploadprogress',
'fileuploadprogressall',
'fileuploadstart',
'fileuploadstop',
'fileuploadchange',
'fileuploadpaste',
'fileuploaddrop',
'fileuploaddragover',
'fileuploadchunksend',
'fileuploadchunkdone',
'fileuploadchunkfail',
'fileuploadchunkalways',
'fileuploadprocessstart',
'fileuploadprocess',
'fileuploadprocessdone',
'fileuploadprocessfail',
'fileuploadprocessalways',
'fileuploadprocessstop'
].join(' '), function (e, data) {
$scope.$emit(e.type, data);
});
// Observe option changes:
$scope.$watch(
$attrs.fileupload,
function (newOptions, oldOptions) {
if (newOptions) {
$element.fileupload('option', newOptions);
}
}
);
}
])
.controller('FileUploadProgressController', [
'$scope', '$attrs', '$parse',
function ($scope, $attrs, $parse) {
var fn = $parse($attrs.progress),
update = function () {
var progress = fn($scope);
if (!progress || !progress.total) {
return;
}
$scope.num = Math.floor(
progress.loaded / progress.total * 100
);
};
update();
$scope.$watch(
$attrs.progress + '.loaded',
function (newValue, oldValue) {
if (newValue !== oldValue) {
update();
}
}
);
}
])
.controller('FileUploadPreviewController', [
'$scope', '$element', '$attrs', '$parse',
function ($scope, $element, $attrs, $parse) {
var fn = $parse($attrs.preview),
file = fn($scope);
if (file.preview) {
$element.append(file.preview);
}
}
])
.directive('fileupload', function () {
return {
controller: 'FileUploadController'
};
})
.directive('progress', function () {
return {
controller: 'FileUploadProgressController'
};
})
.directive('preview', function () {
return {
controller: 'FileUploadPreviewController'
};
})
.directive('download', function () {
return function (scope, elm, attrs) {
elm.on('dragstart', function (e) {
try {
e.originalEvent.dataTransfer.setData(
'DownloadURL',
[
'application/octet-stream',
elm.prop('download'),
elm.prop('href')
].join(':')
);
} catch (err) {}
});
};
});
}());

View File

@@ -0,0 +1,158 @@
/*
* jQuery File Upload Processing Plugin 1.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2012, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true */
/*global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'./jquery.fileupload'
], factory);
} else {
// Browser globals:
factory(
window.jQuery
);
}
}(function ($) {
'use strict';
var originalAdd = $.blueimp.fileupload.prototype.options.add;
// The File Upload Processing plugin extends the fileupload widget
// with file processing functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The list of processing actions:
processQueue: [
/*
{
action: 'log',
type: 'debug'
}
*/
],
add: function (e, data) {
var $this = $(this);
data.process(function () {
return $this.fileupload('process', data);
});
originalAdd.call(this, e, data);
}
},
processActions: {
/*
log: function (data, options) {
console[options.type](
'Processing "' + data.files[data.index].name + '"'
);
}
*/
},
_processFile: function (data) {
var that = this,
dfd = $.Deferred().resolveWith(that, [data]),
chain = dfd.promise();
this._trigger('process', null, data);
$.each(data.processQueue, function (i, settings) {
var func = function (data) {
return that.processActions[settings.action].call(
that,
data,
settings
);
};
chain = chain.pipe(func, settings.always && func);
});
chain
.done(function () {
that._trigger('processdone', null, data);
that._trigger('processalways', null, data);
})
.fail(function () {
that._trigger('processfail', null, data);
that._trigger('processalways', null, data);
});
return chain;
},
// Replaces the settings of each processQueue item that
// are strings starting with an "@", using the remaining
// substring as key for the option map,
// e.g. "@autoUpload" is replaced with options.autoUpload:
_transformProcessQueue: function (options) {
var processQueue = [];
$.each(options.processQueue, function () {
var settings = {};
$.each(this, function (key, value) {
if ($.type(value) === 'string' &&
value.charAt(0) === '@') {
settings[key] = options[value.slice(1)];
} else {
settings[key] = value;
}
});
processQueue.push(settings);
});
options.processQueue = processQueue;
},
// Returns the number of files currently in the processsing queue:
processing: function () {
return this._processing;
},
// Processes the files given as files property of the data parameter,
// returns a Promise object that allows to bind callbacks:
process: function (data) {
var that = this,
options = $.extend({}, this.options, data);
if (options.processQueue && options.processQueue.length) {
this._transformProcessQueue(options);
if (this._processing === 0) {
this._trigger('processstart');
}
$.each(data.files, function (index, file) {
var opts = index ? $.extend({}, options) : options,
func = function () {
return that._processFile(opts);
};
opts.index = index;
that._processing += 1;
that._processingQueue = that._processingQueue.pipe(func, func)
.always(function () {
that._processing -= 1;
if (that._processing === 0) {
that._trigger('processstop');
}
});
});
}
return this._processingQueue;
},
_create: function () {
this._super();
this._processing = 0;
this._processingQueue = $.Deferred().resolveWith(this)
.promise();
}
});
}));

View File

@@ -0,0 +1,212 @@
/*
* jQuery File Upload Image Resize Plugin 1.1.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'load-image',
'canvas-to-blob',
'./jquery.fileupload-process'
], factory);
} else {
// Browser globals:
factory(
window.jQuery,
window.loadImage
);
}
}(function ($, loadImage) {
'use strict';
// Prepend to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.unshift(
{
action: 'loadImage',
fileTypes: '@loadImageFileTypes',
maxFileSize: '@loadImageMaxFileSize',
noRevoke: '@loadImageNoRevoke',
disabled: '@disableImageLoad'
},
{
action: 'resizeImage',
maxWidth: '@imageMaxWidth',
maxHeight: '@imageMaxHeight',
minWidth: '@imageMinWidth',
minHeight: '@imageMinHeight',
crop: '@imageCrop',
disabled: '@disableImageResize'
},
{
action: 'saveImage',
disabled: '@disableImageResize'
},
{
action: 'resizeImage',
maxWidth: '@previewMaxWidth',
maxHeight: '@previewMaxHeight',
minWidth: '@previewMinWidth',
minHeight: '@previewMinHeight',
crop: '@previewCrop',
canvas: '@previewAsCanvas',
disabled: '@disableImagePreview'
},
{
action: 'setImage',
// The name of the property the resized image
// is saved as on the associated file object:
name: 'preview',
disabled: '@disableImagePreview'
}
);
// The File Upload Resize plugin extends the fileupload widget
// with image resize functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The regular expression for the types of images to load:
// matched against the file type:
loadImageFileTypes: /^image\/(gif|jpeg|png)$/,
// The maximum file size of images to load:
loadImageMaxFileSize: 5000000, // 5MB
// The maximum width of resized images:
imageMaxWidth: 1920,
// The maximum height of resized images:
imageMaxHeight: 1080,
// Define if resized images should be cropped or only scaled:
imageCrop: false,
// Disable the resize image functionality by default:
disableImageResize: true,
// The maximum width of the preview images:
previewMaxWidth: 80,
// The maximum height of the preview images:
previewMaxHeight: 80,
// Define if preview images should be cropped or only scaled:
previewCrop: false,
// Define if preview images should be resized as canvas elements:
previewAsCanvas: true
},
processActions: {
// Loads the image given via data.files and data.index
// as img element if the browser supports canvas.
// Accepts the options fileTypes (regular expression)
// and maxFileSize (integer) to limit the files to load:
loadImage: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
dfd = $.Deferred();
if (($.type(options.maxFileSize) === 'number' &&
file.size > options.maxFileSize) ||
(options.fileTypes &&
!options.fileTypes.test(file.type)) ||
!loadImage(
file,
function (img) {
if (!img.src) {
return dfd.rejectWith(that, [data]);
}
data.img = img;
dfd.resolveWith(that, [data]);
},
options
)) {
dfd.rejectWith(that, [data]);
}
return dfd.promise();
},
// Resizes the image given as data.canvas or data.img
// and updates data.canvas or data.img with the resized image.
// Accepts the options maxWidth, maxHeight, minWidth,
// minHeight, canvas and crop:
resizeImage: function (data, options) {
options = $.extend({canvas: true}, options);
var img = (options.canvas && data.canvas) || data.img,
canvas;
if (img && !options.disabled) {
canvas = loadImage.scale(img, options);
if (canvas && (canvas.width !== img.width ||
canvas.height !== img.height)) {
data[canvas.getContext ? 'canvas' : 'img'] = canvas;
}
}
return data;
},
// Saves the processed image given as data.canvas
// inplace at data.index of data.files:
saveImage: function (data, options) {
if (!data.canvas || options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
name = file.name,
dfd = $.Deferred(),
callback = function (blob) {
if (!blob.name) {
if (file.type === blob.type) {
blob.name = file.name;
} else if (file.name) {
blob.name = file.name.replace(
/\..+$/,
'.' + blob.type.substr(6)
);
}
}
// Store the created blob at the position
// of the original file in the files list:
data.files[data.index] = blob;
dfd.resolveWith(that, [data]);
};
// Use canvas.mozGetAsFile directly, to retain the filename, as
// Gecko doesn't support the filename option for FormData.append:
if (data.canvas.mozGetAsFile) {
callback(data.canvas.mozGetAsFile(
(/^image\/(jpeg|png)$/.test(file.type) && name) ||
((name && name.replace(/\..+$/, '')) ||
'blob') + '.png',
file.type
));
} else if (data.canvas.toBlob) {
data.canvas.toBlob(callback, file.type);
} else {
return data;
}
return dfd.promise();
},
// Sets the resized version of the image as a property of the
// file object, must be called after "saveImage":
setImage: function (data, options) {
var img = data.canvas || data.img;
if (img && !options.disabled) {
data.files[data.index][options.name] = img;
}
return data;
}
}
});
}));

View File

@@ -0,0 +1,633 @@
/*
* jQuery File Upload User Interface Plugin 8.2.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, URL, webkitURL, FileReader */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'tmpl',
'./jquery.fileupload-resize',
'./jquery.fileupload-validate'
], factory);
} else {
// Browser globals:
factory(
window.jQuery,
window.tmpl
);
}
}(function ($, tmpl, loadImage) {
'use strict';
$.blueimp.fileupload.prototype._specialOptions.push(
'filesContainer',
'uploadTemplateId',
'downloadTemplateId'
);
// The UI version extends the file upload widget
// and adds complete user interface interaction:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// By default, files added to the widget are uploaded as soon
// as the user clicks on the start buttons. To enable automatic
// uploads, set the following option to true:
autoUpload: false,
// The ID of the upload template:
uploadTemplateId: 'template-upload',
// The ID of the download template:
downloadTemplateId: 'template-download',
// The container for the list of files. If undefined, it is set to
// an element with class "files" inside of the widget element:
filesContainer: undefined,
// By default, files are appended to the files container.
// Set the following option to true, to prepend files instead:
prependFiles: false,
// The expected data type of the upload response, sets the dataType
// option of the $.ajax upload requests:
dataType: 'json',
// Function returning the current number of files,
// used by the maxNumberOfFiles validation:
getNumberOfFiles: function () {
return this.filesContainer.children().length;
},
// Callback to retrieve the list of files from the server response:
getFilesFromResponse: function (data) {
if (data.result && $.isArray(data.result.files)) {
return data.result.files;
}
return [];
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// See the basic file upload widget for more information:
add: function (e, data) {
var $this = $(this),
that = $this.data('blueimp-fileupload') ||
$this.data('fileupload'),
options = that.options,
files = data.files;
data.process(function () {
return $this.fileupload('process', data);
}).always(function () {
data.context = that._renderUpload(files).data('data', data);
that._renderPreviews(data);
options.filesContainer[
options.prependFiles ? 'prepend' : 'append'
](data.context);
that._forceReflow(data.context);
that._transition(data.context).done(
function () {
if ((that._trigger('added', e, data) !== false) &&
(options.autoUpload || data.autoUpload) &&
data.autoUpload !== false && !data.files.error) {
data.submit();
}
}
);
});
},
// Callback for the start of each file upload request:
send: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload');
if (data.context && data.dataType &&
data.dataType.substr(0, 6) === 'iframe') {
// Iframe Transport does not support progress events.
// In lack of an indeterminate progress bar, we set
// the progress to 100%, showing the full animated bar:
data.context
.find('.progress').addClass(
!$.support.transition && 'progress-animated'
)
.attr('aria-valuenow', 100)
.find('.bar').css(
'width',
'100%'
);
}
return that._trigger('sent', e, data);
},
// Callback for successful uploads:
done: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
getFilesFromResponse = data.getFilesFromResponse ||
that.options.getFilesFromResponse,
files = getFilesFromResponse(data),
template,
deferred;
if (data.context) {
data.context.each(function (index) {
var file = files[index] ||
{error: 'Empty file upload result'},
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
var node = $(this);
template = that._renderDownload([file])
.replaceAll(node);
that._forceReflow(template);
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('completed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
);
});
} else {
template = that._renderDownload(files)
.appendTo(that.options.filesContainer);
that._forceReflow(template);
deferred = that._addFinishedDeferreds();
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('completed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
},
// Callback for failed (abort or error) uploads:
fail: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
template,
deferred;
if (data.context) {
data.context.each(function (index) {
if (data.errorThrown !== 'abort') {
var file = data.files[index];
file.error = file.error || data.errorThrown ||
true;
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
var node = $(this);
template = that._renderDownload([file])
.replaceAll(node);
that._forceReflow(template);
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
);
} else {
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
$(this).remove();
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
});
} else if (data.errorThrown !== 'abort') {
data.context = that._renderUpload(data.files)
.appendTo(that.options.filesContainer)
.data('data', data);
that._forceReflow(data.context);
deferred = that._addFinishedDeferreds();
that._transition(data.context).done(
function () {
data.context = $(this);
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
} else {
that._trigger('failed', e, data);
that._trigger('finished', e, data);
that._addFinishedDeferreds().resolve();
}
},
// Callback for upload progress events:
progress: function (e, data) {
if (data.context) {
var progress = Math.floor(data.loaded / data.total * 100);
data.context.find('.progress')
.attr('aria-valuenow', progress)
.find('.bar').css(
'width',
progress + '%'
);
}
},
// Callback for global upload progress events:
progressall: function (e, data) {
var $this = $(this),
progress = Math.floor(data.loaded / data.total * 100),
globalProgressNode = $this.find('.fileupload-progress'),
extendedProgressNode = globalProgressNode
.find('.progress-extended');
if (extendedProgressNode.length) {
extendedProgressNode.html(
($this.data('blueimp-fileupload') || $this.data('fileupload'))
._renderExtendedProgress(data)
);
}
globalProgressNode
.find('.progress')
.attr('aria-valuenow', progress)
.find('.bar').css(
'width',
progress + '%'
);
},
// Callback for uploads start, equivalent to the global ajaxStart event:
start: function (e) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload');
that._resetFinishedDeferreds();
that._transition($(this).find('.fileupload-progress')).done(
function () {
that._trigger('started', e);
}
);
},
// Callback for uploads stop, equivalent to the global ajaxStop event:
stop: function (e) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
deferred = that._addFinishedDeferreds();
$.when.apply($, that._getFinishedDeferreds())
.done(function () {
that._trigger('stopped', e);
});
that._transition($(this).find('.fileupload-progress')).done(
function () {
$(this).find('.progress')
.attr('aria-valuenow', '0')
.find('.bar').css('width', '0%');
$(this).find('.progress-extended').html('&nbsp;');
deferred.resolve();
}
);
},
processstart: function () {
$(this).addClass('fileupload-processing');
},
processstop: function () {
$(this).removeClass('fileupload-processing');
},
// Callback for file deletion:
destroy: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload');
if (data.url) {
$.ajax(data).done(function () {
that._transition(data.context).done(
function () {
$(this).remove();
that._trigger('destroyed', e, data);
}
);
});
}
}
},
_resetFinishedDeferreds: function () {
this._finishedUploads = [];
},
_addFinishedDeferreds: function (deferred) {
if (!deferred) {
deferred = $.Deferred();
}
this._finishedUploads.push(deferred);
return deferred;
},
_getFinishedDeferreds: function () {
return this._finishedUploads;
},
// Link handler, that allows to download files
// by drag & drop of the links to the desktop:
_enableDragToDesktop: function () {
var link = $(this),
url = link.prop('href'),
name = link.prop('download'),
type = 'application/octet-stream';
link.bind('dragstart', function (e) {
try {
e.originalEvent.dataTransfer.setData(
'DownloadURL',
[type, name, url].join(':')
);
} catch (ignore) {}
});
},
_formatFileSize: function (bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
},
_formatBitrate: function (bits) {
if (typeof bits !== 'number') {
return '';
}
if (bits >= 1000000000) {
return (bits / 1000000000).toFixed(2) + ' Gbit/s';
}
if (bits >= 1000000) {
return (bits / 1000000).toFixed(2) + ' Mbit/s';
}
if (bits >= 1000) {
return (bits / 1000).toFixed(2) + ' kbit/s';
}
return bits.toFixed(2) + ' bit/s';
},
_formatTime: function (seconds) {
var date = new Date(seconds * 1000),
days = Math.floor(seconds / 86400);
days = days ? days + 'd ' : '';
return days +
('0' + date.getUTCHours()).slice(-2) + ':' +
('0' + date.getUTCMinutes()).slice(-2) + ':' +
('0' + date.getUTCSeconds()).slice(-2);
},
_formatPercentage: function (floatValue) {
return (floatValue * 100).toFixed(2) + ' %';
},
_renderExtendedProgress: function (data) {
return this._formatBitrate(data.bitrate) + ' | ' +
this._formatTime(
(data.total - data.loaded) * 8 / data.bitrate
) + ' | ' +
this._formatPercentage(
data.loaded / data.total
) + ' | ' +
this._formatFileSize(data.loaded) + ' / ' +
this._formatFileSize(data.total);
},
_renderTemplate: function (func, files) {
if (!func) {
return $();
}
var result = func({
files: files,
formatFileSize: this._formatFileSize,
options: this.options
});
if (result instanceof $) {
return result;
}
return $(this.options.templatesContainer).html(result).children();
},
_renderPreviews: function (data) {
data.context.find('.preview').each(function (index, elm) {
$(elm).append(data.files[index].preview);
});
},
_renderUpload: function (files) {
return this._renderTemplate(
this.options.uploadTemplate,
files
);
},
_renderDownload: function (files) {
return this._renderTemplate(
this.options.downloadTemplate,
files
).find('a[download]').each(this._enableDragToDesktop).end();
},
_startHandler: function (e) {
e.preventDefault();
var button = $(e.currentTarget),
template = button.closest('.template-upload'),
data = template.data('data');
if (data && data.submit && !data.jqXHR && data.submit()) {
button.prop('disabled', true);
}
},
_cancelHandler: function (e) {
e.preventDefault();
var template = $(e.currentTarget).closest('.template-upload'),
data = template.data('data') || {};
if (!data.jqXHR) {
data.errorThrown = 'abort';
this._trigger('fail', e, data);
} else {
data.jqXHR.abort();
}
},
_deleteHandler: function (e) {
e.preventDefault();
var button = $(e.currentTarget);
this._trigger('destroy', e, $.extend({
context: button.closest('.template-download'),
type: 'DELETE'
}, button.data()));
},
_forceReflow: function (node) {
return $.support.transition && node.length &&
node[0].offsetWidth;
},
_transition: function (node) {
var dfd = $.Deferred();
if ($.support.transition && node.hasClass('fade') && node.is(':visible')) {
node.bind(
$.support.transition.end,
function (e) {
// Make sure we don't respond to other transitions events
// in the container element, e.g. from button elements:
if (e.target === node[0]) {
node.unbind($.support.transition.end);
dfd.resolveWith(node);
}
}
).toggleClass('in');
} else {
node.toggleClass('in');
dfd.resolveWith(node);
}
return dfd;
},
_initButtonBarEventHandlers: function () {
var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
filesList = this.options.filesContainer;
this._on(fileUploadButtonBar.find('.start'), {
click: function (e) {
e.preventDefault();
filesList.find('.start').click();
}
});
this._on(fileUploadButtonBar.find('.cancel'), {
click: function (e) {
e.preventDefault();
filesList.find('.cancel').click();
}
});
this._on(fileUploadButtonBar.find('.delete'), {
click: function (e) {
e.preventDefault();
filesList.find('.toggle:checked')
.closest('.template-download')
.find('.delete').click();
fileUploadButtonBar.find('.toggle')
.prop('checked', false);
}
});
this._on(fileUploadButtonBar.find('.toggle'), {
change: function (e) {
filesList.find('.toggle').prop(
'checked',
$(e.currentTarget).is(':checked')
);
}
});
},
_destroyButtonBarEventHandlers: function () {
this._off(
this.element.find('.fileupload-buttonbar')
.find('.start, .cancel, .delete'),
'click'
);
this._off(
this.element.find('.fileupload-buttonbar .toggle'),
'change.'
);
},
_initEventHandlers: function () {
this._super();
this._on(this.options.filesContainer, {
'click .start': this._startHandler,
'click .cancel': this._cancelHandler,
'click .delete': this._deleteHandler
});
this._initButtonBarEventHandlers();
},
_destroyEventHandlers: function () {
this._destroyButtonBarEventHandlers();
this._off(this.options.filesContainer, 'click');
this._super();
},
_enableFileInputButton: function () {
this.element.find('.fileinput-button input')
.prop('disabled', false)
.parent().removeClass('disabled');
},
_disableFileInputButton: function () {
this.element.find('.fileinput-button input')
.prop('disabled', true)
.parent().addClass('disabled');
},
_initTemplates: function () {
var options = this.options;
options.templatesContainer = this.document[0].createElement(
options.filesContainer.prop('nodeName')
);
if (tmpl) {
if (options.uploadTemplateId) {
options.uploadTemplate = tmpl(options.uploadTemplateId);
}
if (options.downloadTemplateId) {
options.downloadTemplate = tmpl(options.downloadTemplateId);
}
}
},
_initFilesContainer: function () {
var options = this.options;
if (options.filesContainer === undefined) {
options.filesContainer = this.element.find('.files');
} else if (!(options.filesContainer instanceof $)) {
options.filesContainer = $(options.filesContainer);
}
},
_initSpecialOptions: function () {
this._super();
this._initFilesContainer();
this._initTemplates();
},
_create: function () {
this._super();
this._resetFinishedDeferreds();
},
enable: function () {
var wasDisabled = false;
if (this.options.disabled) {
wasDisabled = true;
}
this._super();
if (wasDisabled) {
this.element.find('input, button').prop('disabled', false);
this._enableFileInputButton();
}
},
disable: function () {
if (!this.options.disabled) {
this.element.find('input, button').prop('disabled', true);
this._disableFileInputButton();
}
this._super();
}
});
}));

View File

@@ -0,0 +1,116 @@
/*
* jQuery File Upload Validation Plugin 1.0.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'./jquery.fileupload-process'
], factory);
} else {
// Browser globals:
factory(
window.jQuery
);
}
}(function ($) {
'use strict';
// Append to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.push(
{
action: 'validate',
// Always trigger this action,
// even if the previous action was rejected:
always: true,
// Options taken from the global options map:
acceptFileTypes: '@acceptFileTypes',
maxFileSize: '@maxFileSize',
minFileSize: '@minFileSize',
maxNumberOfFiles: '@maxNumberOfFiles',
disabled: '@disableValidation'
}
);
// The File Upload Validation plugin extends the fileupload widget
// with file validation functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
/*
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
// The maximum allowed file size in bytes:
maxFileSize: 10000000, // 10 MB
// The minimum allowed file size in bytes:
minFileSize: undefined, // No minimal file size
// The limit of files to be uploaded:
maxNumberOfFiles: 10,
*/
// Function returning the current number of files,
// has to be overriden for maxNumberOfFiles validation:
getNumberOfFiles: $.noop,
// Error and info messages:
messages: {
maxNumberOfFiles: 'Maximum number of files exceeded',
acceptFileTypes: 'File type not allowed',
maxFileSize: 'File is too large',
minFileSize: 'File is too small'
}
},
processActions: {
validate: function (data, options) {
if (options.disabled) {
return data;
}
var dfd = $.Deferred(),
settings = this.options,
file = data.files[data.index],
numberOfFiles = settings.getNumberOfFiles();
if (numberOfFiles && $.type(options.maxNumberOfFiles) === 'number' &&
numberOfFiles + data.files.length > options.maxNumberOfFiles) {
file.error = settings.i18n('maxNumberOfFiles');
} else if (options.acceptFileTypes &&
!(options.acceptFileTypes.test(file.type) ||
options.acceptFileTypes.test(file.name))) {
file.error = settings.i18n('acceptFileTypes');
} else if (options.maxFileSize && file.size > options.maxFileSize) {
file.error = settings.i18n('maxFileSize');
} else if ($.type(file.size) === 'number' &&
file.size < options.minFileSize) {
file.error = settings.i18n('minFileSize');
} else {
delete file.error;
}
if (file.error || data.files.error) {
data.files.error = true;
dfd.rejectWith(this, [data]);
} else {
dfd.resolveWith(this, [data]);
}
return dfd.promise();
}
}
});
}));

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,205 @@
/*
* jQuery Iframe Transport Plugin 1.7
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint unparam: true, nomen: true */
/*global define, window, document */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0;
// The iframe transport accepts three additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
$.ajaxTransport('iframe', function (options) {
if (options.async) {
var form,
iframe,
addParamChar;
return {
send: function (_, completeCallback) {
form = $('<form style="display:none;"></form>');
form.attr('accept-charset', options.formAcceptCharset);
addParamChar = /\?/.test(options.url) ? '&' : '?';
// XDomainRequest only supports GET and POST:
if (options.type === 'DELETE') {
options.url = options.url + addParamChar + '_method=DELETE';
options.type = 'POST';
} else if (options.type === 'PUT') {
options.url = options.url + addParamChar + '_method=PUT';
options.type = 'POST';
} else if (options.type === 'PATCH') {
options.url = options.url + addParamChar + '_method=PATCH';
options.type = 'POST';
}
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6.
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
counter += 1;
iframe = $(
'<iframe src="javascript:false;" name="iframe-transport-' +
counter + '"></iframe>'
).bind('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName) ?
options.paramName : [options.paramName];
iframe
.unbind('load')
.bind('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(
200,
'success',
{'iframe': response}
);
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('<iframe src="javascript:false;"></iframe>')
.appendTo(form);
window.setTimeout(function () {
// Removing the form in a setTimeout call
// allows Chrome's developer tools to display
// the response result
form.remove();
}, 0);
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$('<input type="hidden"/>')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (options.fileInput && options.fileInput.length &&
options.type === 'POST') {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop(
'name',
paramNames[index] || options.paramName
);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
}
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
$(input).prop('name', clone.prop('name'));
clone.replaceWith(input);
});
}
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
// concat is used to avoid the "Script URL" JSLint error:
iframe
.unbind('load')
.prop('src', 'javascript'.concat(':false;'));
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, xml
// and script.
// Please note that the Content-Type for JSON responses has to be text/plain
// or text/html, if the browser doesn't include application/json in the
// Accept header, else IE will show a download dialog.
// The Content-Type for XML responses on the other hand has to be always
// application/xml or text/xml, so IE properly parses the XML response.
// See also
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
$.ajaxSetup({
converters: {
'iframe text': function (iframe) {
return iframe && $(iframe[0].body).text();
},
'iframe json': function (iframe) {
return iframe && $.parseJSON($(iframe[0].body).text());
},
'iframe html': function (iframe) {
return iframe && $(iframe[0].body).html();
},
'iframe xml': function (iframe) {
var xmlDoc = iframe && iframe[0];
return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc :
$.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
$(xmlDoc.body).html());
},
'iframe script': function (iframe) {
return iframe && $.globalEval($(iframe[0].body).text());
}
}
});
}));

View File

@@ -0,0 +1,485 @@
$(function(){
var csrfToken = getCookie('csrftoken'),
widget = $('.files-widget'),
effectTime = 200,
mediaURL = $('[data-media-url]').data('media-url'),
staticURL = $('[data-static-url]').data('static-url'),
thumbnailURL = $('[data-get-thumbnail-url]').data('get-thumbnail-url'),
undoText = $('[data-undo-text]').data('undo-text'),
template,
deletedTemplate;
template =
'<div class="new preview">'+
'<span class="image-holder">'+
'<img class="thumbnail" />'+
'<span class="buttons">'+
'<a href="javascript:void(0)" class="enlarge-button">'+
'<img src="'+ staticURL + 'files_widget/img/enlarge_button.png" />'+
'</a> '+
'<a href="javascript:void(0)" class="remove-button">'+
'<img src="'+ staticURL + 'files_widget/img/close_button.png" />'+
'</a>'+
'</span>'+
'</span>'+
'<div class="progress-holder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
deletedTemplate =
'<div class="deleted-file">'+
'<span class="image-holder">'+
'<img class="icon" />'+
'</span>'+
'<span class="name"></span>'+
'<span class="undo">'+
'<a href="javascript:void(0);" class="undo-remove-button">'+
undoText+
'</a>'+
'</span>'+
'</div>';
function splitlines(str) {
return str.match(/[^\r\n]+/g) || [];
}
function filenameFromPath(path) {
return path.replace(/^.+\//, '');
}
function stripMediaURL(path) {
if (path.indexOf(mediaURL) === 0) {
return path.replace(mediaURL, '');
}
return path;
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function numberformat( number, decimals, dec_point, thousands_sep ) {
// http://kevin.vanzonneveld.net
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: number_format(1234.5678, 2, '.', '');
// * returns 1: 1234.57
var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
var d = dec_point == undefined ? "," : dec_point;
var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
function sizeformat(filesize, bits) {
var b = 'B';
if (bits) {
b = 'b';
}
// from http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/
if (filesize >= 1073741824) {
filesize = numberformat(filesize / 1073741824, 2, '.', '') + 'G' + b;
} else {
if (filesize >= 1048576) {
filesize = numberformat(filesize / 1048576, 2, '.', '') + 'M' + b;
} else {
if (filesize >= 1024) {
filesize = numberformat(filesize / 1024, 0) + 'k' + b;
} else {
filesize = numberformat(filesize, 0) + b;
};
};
};
return filesize;
};
function fillIn(input, files) {
var value = '';
files.each(function() {
var path = $(this).data('image-path');
if (path) {
value += path + '\n';
}
});
input.val(value);
}
function fillInHiddenInputs(dropbox, movedOutFile, movedInFile) {
var input = $('input[name="' + dropbox.data('input-name') + '_0"]'),
deletedInput = $('input[name="' + dropbox.data('input-name') + '_1"]'),
movedInput = $('input[name="' + dropbox.data('input-name') + '_2"]'),
widget = input.closest('.files-widget'),
files = widget.find('.preview'),
deletedFiles = widget.find('.deleted-file');
fillIn(input, files.add(movedInFile));
fillIn(deletedInput, deletedFiles);
if (movedOutFile) {
var movedInputValue = splitlines(movedInput.val()),
filename = movedOutFile.data('image-path');
movedInputValue.push(filename);
movedInput.val(movedInputValue.join('\n'));
}
if (movedInFile) {
var movedInputValue = splitlines(movedInput.val()),
filename = movedInFile.data('image-path'),
index = movedInputValue.indexOf(filename);
if (index != -1) {
movedInputValue.splice(index, 1);
movedInput.val(movedInputValue);
}
}
}
function downloadThumbnail(preview) {
var imagePath = stripMediaURL(preview.data('image-path')),
dropbox = preview.closest('.files-widget-dropbox'),
previewSize = dropbox.data('preview-size');
$.get(thumbnailURL,
'img=' + encodeURIComponent(imagePath) + '&preview_size=' + previewSize,
function(data) {
preview.find('.thumbnail')
.css({ 'width': '', 'height': '' }).attr('src', data);
preview.removeClass('new');
});
}
function generateThumbnail(preview, file) {
var image = $('.thumbnail', preview),
reader = new FileReader(),
dropbox = preview.closest('.files-widget-dropbox'),
previewSize = dropbox.data('preview-size'),
defaultSize = parseInt(+previewSize * 2 / 3, 10);
reader.onload = function(e) {
image.attr('src', e.target.result);
image.css({ 'width': '', 'height': '' });
};
image.css({
'max-width': previewSize, 'max-height': previewSize,
'width': defaultSize, 'height': defaultSize
});
if (file.size < 500000) {
reader.readAsDataURL(file);
} else {
$('<span/>').addClass('filename').text(file.name)
.appendTo(preview.find('.image-holder'));
}
}
function addPreview(dropbox, imagePath, thumbnailPath, file, fromHiddenInput) {
var preview = $(template);
if (dropbox.data('multiple') != 1) {
dropbox.find('.preview').each(function() {
deletePreview($(this), true);
});
}
dropbox.find('.message').hide();
preview.hide().insertAfter(dropbox.children(':last-child')).fadeIn(effectTime);
if (imagePath) {
completePreview(preview, imagePath, thumbnailPath, fromHiddenInput);
} else if (file) {
generateThumbnail(preview, file);
}
return preview;
}
function completePreview(preview, imagePath, thumbnailPath, fromHiddenInput) {
var dropbox = preview.closest('.files-widget-dropbox');
preview.removeClass('new').attr('data-image-path', imagePath);
preview.find('.progress-holder, .filename').remove();
if (thumbnailPath) {
preview.find('.thumbnail')
.css({ 'width': '', 'height': '' }).attr('src', thumbnailPath);
} else {
downloadThumbnail(preview);
}
if (!fromHiddenInput) {
fillInHiddenInputs(dropbox);
}
}
function onPreviewMove(preview, oldDropbox, newDropbox) {
if (oldDropbox.is(newDropbox)) {
fillInHiddenInputs(oldDropbox);
} else {
if (newDropbox.data('multiple') != 1) {
newDropbox.find('.preview').not(preview).each(function() {
deletePreview($(this), true);
});
}
fillInHiddenInputs(oldDropbox, preview, null);
fillInHiddenInputs(newDropbox, null, preview);
if (!oldDropbox.find('.preview').length) {
oldDropbox.find('.message').show();
}
if (oldDropbox.data('preview-size') !== newDropbox.data('preview-size')) {
downloadThumbnail(preview);
}
}
}
function deletePreview(preview, changingToNewPreview) {
var dropbox = preview.closest('.files-widget-dropbox'),
widget = dropbox.closest('.files-widget'),
deletedPreview = $(deletedTemplate),
deletedContainer = $('.files-widget-deleted', widget),
deletedList = $('.deleted-list', deletedContainer),
path = preview.data('image-path');
function doDelete() {
$('.icon', deletedPreview).attr('src', preview.find('.thumbnail').attr('src'));
$('.name', deletedPreview).text(filenameFromPath(path));
deletedPreview.attr('data-image-path', path);
deletedContainer.show();
deletedPreview.hide().appendTo(deletedList)
deletedPreview.slideDown(effectTime);
preview.remove();
if (!dropbox.find('.preview').length && !changingToNewPreview) {
dropbox.find('.message').show();
};
fillInHiddenInputs(dropbox);
}
if (changingToNewPreview) {
doDelete();
} else {
preview.fadeOut(effectTime, doDelete);
}
}
function undoDeletePreview(deletedPreview) {
var imagePath = deletedPreview.data('image-path'),
thumbnailPath = $('.icon', deletedPreview).attr('src'),
widget = deletedPreview.closest('.files-widget'),
dropbox = widget.find('.files-widget-dropbox'),
deletedContainer = $('.files-widget-deleted', widget),
deletedList = $('.deleted-list', deletedContainer),
preview = addPreview(dropbox, imagePath, thumbnailPath);
deletedPreview.slideUp(effectTime, function() {
$(this).remove();
if (!deletedList.find('.deleted-file').length) {
deletedContainer.hide();
};
fillInHiddenInputs(dropbox);
});
}
$(document).bind('drag dragover', function (e) {
e.preventDefault();
$('.files-widget-dropbox').addClass('dragging-files');
}).bind('drop', function (e) {
e.preventDefault();
$('.files-widget-dropbox').removeClass('dragging-files');
}).bind('dragleave', function (e) {
$('.files-widget-dropbox').removeClass('dragging-files');
});
widget.each(function() {
var that = $(this),
dropbox = $('.files-widget-dropbox', that),
filesInput = $('.files-input', that),
message = $('.message', dropbox),
uploadURL = dropbox.data('upload-url'),
multiple = dropbox.data('multiple') == 1,
previewSize = dropbox.data('preview-size'),
initialFiles = $('.preview', dropbox),
fileBrowserResultInput = $('.filebrowser-result', that),
deletedContainer = $('.files-widget-deleted', that),
deletedList = $('.deleted-list', deletedContainer),
stats = $('.upload-progress-stats', that),
hiddenInput = $('input[name="' + dropbox.data('input-name') + '_0"]'),
initialFileNames = splitlines(hiddenInput.val()),
name;
for (name in initialFileNames) {
if (!initialFiles.filter('[data-image-path="' + initialFileNames[name] + '"]').length) {
addPreview(dropbox, initialFileNames[name], null, null, true);
}
}
initialFiles = $('.preview', dropbox);
if (initialFiles.length) {
message.hide();
}
if (deletedList.find('.deleted-file').length) {
deletedContainer.show();
}
dropbox.on('click', '.remove-button', function() {
var preview = $(this).closest('.preview');
deletePreview(preview);
});
that.on('click', '.undo-remove-button', function() {
var deletedPreview = $(this).closest('.deleted-file');
undoDeletePreview(deletedPreview);
});
dropbox.on('click', '.enlarge-button', function() {
window.open(mediaURL + $(this).closest('.preview').data('image-path'));
});
function onFileBrowserResult() {
var imagePath = stripMediaURL(fileBrowserResultInput.val()),
preview = addPreview(dropbox, imagePath);
fileBrowserResultInput.val('');
}
function checkFileBrowserResult() {
var oldVal = fileBrowserResultInput.val(),
checkInterval;
checkInterval = setInterval(function() {
var newVal = fileBrowserResultInput.val();
if (oldVal != newVal) {
clearInterval(checkInterval);
onFileBrowserResult();
}
}, 250);
}
$('.media-library-button', that).on('click', function() {
var url = window.__filebrowser_url || '/admin/media-library/browse/'
FileBrowser.show(fileBrowserResultInput.attr('id'), url + '?pop=1');
checkFileBrowserResult();
});
$('.add-by-url-button', that).on('click', function() {
$('.add-by-url-container', that).show();
$(this).hide();
$('.add-by-url', that).trigger('focus');
});
$('.add-by-url', that).on('focusout', function() {
$('.add-by-url-button', that).show();
$('.add-by-url-container', that).hide();
}).on('keypress', function (e) {
var urlInput = $(this),
val = urlInput.val();
if (e.which == 13) {
e.stopPropagation();
e.preventDefault();
$('.add-by-url-button', that).show();
$('.add-by-url-container', that).hide();
urlInput.val('');
if (val.length) {
addPreview(dropbox, val);
}
return false;
}
});
dropbox.disableSelection();
dropbox.bind('dragover', function (e) {
dropbox.addClass('dragover');
}).bind('dragleave drop', function (e) {
dropbox.removeClass('dragover');
});
dropbox.sortable({
placeholder: 'sortable-placeholder',
//tolerance: 'pointer',
connectWith: '.files-widget-dropbox',
//cursorAt: { top: 0, left: 0 },
//items: '.preview:not(.controls-preview)',
revert: effectTime,
start: function(e, ui) {
$('.sortable-placeholder').width(ui.item.width()).height(ui.item.height());
},
over: function() {
message.hide();
},
beforeStop: function(e, ui) {
var newDropbox = ui.placeholder.closest('.files-widget-dropbox');
onPreviewMove(ui.item, dropbox, newDropbox);
}
});
filesInput.fileupload({
url: uploadURL,
type: 'POST',
dataType: 'json',
dropZone: dropbox,
pasteZone: dropbox,
paramName: 'files[]',
limitConcurrentUploads: 3,
formData: [
{ name: 'csrfmiddlewaretoken', value: csrfToken },
{ name: 'preview_size', value: previewSize }
],
autoUpload: true,
maxFileSize: 10000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxNumberOfFiles: undefined,
previewMaxWidth: 150,
previewMaxHeight: 150,
previewCrop: true,
add: function(e, data) {
var preview = addPreview(dropbox, undefined, undefined, data.files[0]);
data.context = preview;
data.submit();
},
submit: function(e, data) {
// console.log('submit', data);
// create thumbnail client side?
},
done: function(e, data) {
completePreview(data.context,
data.result.imagePath, data.result.thumbnailPath);
},
fail: function(e, data) {
//console.log('failed', data);
// display errors
},
always: function(e, data) {
//console.log('always', data);
stats.text('');
},
progress: function(e, data) {
//console.log('progress', data);
var progress = parseInt(data.loaded / data.total * 100, 10);
data.context.find('.progress').css('width', progress + '%');
},
progressall: function(e, data) {
//console.log('progressall', data);
stats.text(sizeformat(data.loaded) +
' of ' + sizeformat(data.total) +
' (' + sizeformat(data.bitrate, true) + 'ps)');
},
});
});
});