-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputfieldFileS3.js
467 lines (383 loc) · 16.3 KB
/
InputfieldFileS3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
$(document).ready(function() {
/**
* Setup a live change event for the delete links
*
*/
// not IE < 9
$(document).on('change', '.InputfieldFileDelete input', function() {
setInputfieldFileStatus($(this));
}).on('dblclick', '.InputfieldFileDelete', function() {
// enable double-click to delete all
var $input = $(this).find('input');
var $items = $(this).parents('.InputfieldFileList').find('.InputfieldFileDelete input');
if($input.is(":checked")) $items.removeAttr('checked').change();
else $items.attr('checked', 'checked').change();
return false;
});
function setInputfieldFileStatus($t) {
var $info = $t.parents('.InputfieldFileInfo');
// collapsed=items that have no description or tags, so need no visible InputfieldFileData container
var collapsed = $t.closest('.InputfieldFile').hasClass('InputfieldItemListCollapse');
if($t.is(":checked")) {
// not an error, but we want to highlight it in the same manner
$info.addClass("ui-state-error");
if(!collapsed) $info.siblings(".InputfieldFileData").slideUp("fast");
} else {
$info.removeClass("ui-state-error");
if(!collapsed) $info.siblings(".InputfieldFileData").slideDown("fast");
}
}
/**
* Make the lists sortable and hoverable
*
*/
function initSortable($fileLists) {
$fileLists.each(function() {
var $this = $(this);
var qty = $this.children("li").length;
if($this.closest('.InputfieldRenderValueMode').length) return;
var $inputfield = $this.closest('.Inputfield')
if(qty < 2) {
// added to support additional controls when multiple items are present
// and to hide them when not present
if(qty == 0) $inputfield.addClass('InputfieldFileEmpty').removeClass('InputfieldFileMultiple InputfieldFileSingle');
else $inputfield.addClass('InputfieldFileSingle').removeClass('InputfieldFileEmpty InputfieldFileMultiple');
// if we're dealing with a single item list, then don't continue with making it sortable
return;
} else {
$this.closest('.Inputfield').removeClass('InputfieldFileSingle InputfieldFileEmpty').addClass('InputfieldFileMultiple');
}
$this.sortable({
//axis: 'y',
start: function(e, ui) {
ui.item.children(".InputfieldFileInfo").addClass("ui-state-highlight");
},
stop: function(e, ui) {
$(this).children("li").each(function(n) {
$(this).find(".InputfieldFileSort").val(n);
});
ui.item.children(".InputfieldFileInfo").removeClass("ui-state-highlight");
// Firefox has a habit of opening a lightbox popup after a lightbox trigger was used as a sort handle
// so we keep a 500ms class here to keep a handle on what was a lightbox trigger and what was a sort
$inputfield.addClass('InputfieldFileJustSorted InputfieldStateChanged');
setTimeout(function() { $inputfield.removeClass('InputfieldFileJustSorted'); }, 500);
}
});
}).find(".ui-widget-header, .ui-state-default").hover(function() {
$(this).addClass('ui-state-hover');
}, function() {
$(this).removeClass('ui-state-hover');
});
}
/**
* Initialize non-HTML5 uploads
*
function InitOldSchool() {
// $(".InputfieldFileUpload input[type=file]").live('change', function() {
$(document).on('change', '.InputfieldFileUpload input[type=file]', function() {
var $t = $(this);
if($t.next("input.InputfieldFile").size() > 0) return; // not the last one
var maxFiles = parseInt($t.siblings('.InputfieldFileMaxFiles').val());
var numFiles = $t.parent('.InputfieldFileUpload').siblings('.InputfieldFileList').children('li').size() + $t.siblings('input[type=file]').size() + 1;
if(maxFiles > 0 && numFiles >= maxFiles) return;
// if there are any empty inputs, then don't add another
var numEmpty = 0;
$t.siblings('input[type=file]').each(function() { if($(this).val().length < 1) numEmpty++; });
if(numEmpty > 0) return;
// add another input
var $i = $t.clone().hide().val('');
$t.after($i);
$i.slideDown();
});
}
*/
function InitOldSchool() {
$("body").addClass("ie-no-drop"); // ??
$(document).on('change', '.InputfieldFileUpload input[type=file]', function() {
var $t = $(this);
var $mask = $t.parent(".InputMask");
if($t.val().length > 1) {
$mask.addClass("ui-state-disabled");
} else {
$mask.removeClass("ui-state-disabled");
}
if($mask.next(".InputMask").length > 0) return; // not the last one
var $inputfield = $t.closest('.InputfieldFile');
var $upload = $t.closest('.InputfieldFileUpload');
var $list = $inputfield.find('.InputfieldFileList');
var maxFiles = parseInt($upload.find('.InputfieldFileMaxFiles').val());
var numFiles = $list.children('li').length + $upload.find('input[type=file]').length + 1;
if(maxFiles > 0 && numFiles >= maxFiles) return;
$upload.find(".InputMask").not(":last").each(function() {
var $m = $(this);
if($m.find("input[type=file]").val() < 1) $m.remove();
});
// add another input
var $i = $mask.clone().removeClass("ui-state-disabled");
$i.children("input[type=file]").val('');
$i.insertAfter($mask);
$i.css('margin-left', '0.5em').removeClass('ui-state-active');
// update file input to contain file name
var name = $t.val();
var pos = name.lastIndexOf('/');
if(pos === -1) pos = name.lastIndexOf('\\');
name = name.substring(pos+1);
$mask.find('.ui-button-text').text(name).prepend("<i class='fa fa-fw fa-file-o'></i>");
$mask.removeClass('ui-state-active');
});
}
/**
* Initialize HTML5 uploads
*
* By apeisa with additional code by Ryan
*
* Based on the great work and examples of Craig Buckler (http://www.sitepoint.com/html5-file-drag-and-drop/)
* and Robert Nyman (http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html)
*
*/
function InitHTML5($inputfield) {
if($inputfield.length > 0) {
var $target = $inputfield.find(".InputfieldFileUpload"); // just one
} else {
var $target = $(".InputfieldFileUpload"); // all
}
$target.closest('.InputfieldContent').each(function (i) {
if($(this).hasClass('InputfieldFileInit')) return;
initHTML5Item($(this), i);
$(this).addClass('InputfieldFileInit');
});
function initHTML5Item($this, i) {
var $form = $this.parents('form');
var $repeaterItem = $this.closest('.InputfieldRepeaterItem');
var postUrl = $repeaterItem.length ? $repeaterItem.attr('data-editUrl') : $form.attr('action');
postUrl += (postUrl.indexOf('?') > -1 ? '&' : '?') + 'InputfieldFileAjax=1';
// CSRF protection
var $postToken = $form.find('input._post_token');
var postTokenName = $postToken.attr('name');
var postTokenValue = $postToken.val();
var $uploadData = $this.find('.InputfieldFileUpload');
var fieldName = $uploadData.data('fieldname');
fieldName = fieldName.slice(0,-2);
var extensions = $uploadData.data('extensions').toLowerCase();
var maxFilesize = $uploadData.data('maxfilesize');
var filesUpload = $this.find("input[type=file]").get(0);
var dropArea = $this.get(0);
var $fileList = $this.find(".InputfieldFileList");
if($fileList.size() < 1) {
$fileList = $("<ul class='InputfieldFileList InputfieldFileListBlank'></ul>");
$this.prepend($fileList);
$this.parent('.Inputfield').addClass('InputfieldFileEmpty');
}
var fileList = $fileList.get(0);
var maxFiles = parseInt($this.find('.InputfieldFileMaxFiles').val());
$fileList.children().addClass('InputfieldFileItemExisting'); // identify items that are already there
$this.find('.AjaxUploadDropHere').show();
var doneTimer = null; // for AjaxUploadDone event
function uploadFile(file) {
var $progressItem = $('<li class="InputfieldFile ui-widget AjaxUpload"><p class="InputfieldFileInfo ui-widget ui-widget-header InputfieldItemHeader"></p></li>'),
$progressBar = $('<div class="ui-progressbar ui-widget ui-widget-content ui-corner-all" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"></div>'),
$progressBarValue = $('<div class="ui-progressbar-value ui-widget-header InputfieldItemHeader ui-corner-left" style="width: 0%; "></div>'),
img,
reader,
xhr,
fileData;
$progressBar.append($progressBarValue);
$progressItem.append($progressBar);
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();
// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {
if(evt.lengthComputable) {
var completion = (evt.loaded / evt.total) * 100;
$progressBarValue.width(completion + "%");
if(completion > 4) {
$progressBarValue.html("<span>" + parseInt(completion) + "%</span>");
}
$('body').addClass('pw-uploading');
/*
// code for freezing progressbar during testing
$progressBarValue.width("60%");
if(completion > 50) setTimeout(function() { alert('test'); }, 10);
*/
} else {
// No data to calculate on
}
}, false);
// File uploaded: called for each file
xhr.addEventListener("load", function() {
var response = $.parseJSON(xhr.responseText);
if(response.error !== undefined) response = [response];
// note the following loop will always contain only 1 item, unless a file containing more files (ZIP file) was uploaded
for(var n = 0; n < response.length; n++) {
var r = response[n];
if(r.error) {
var $pi = $progressItem.clone();
$pi.find(".InputfieldFileInfo").addClass('ui-state-error');
$pi.find(".InputfieldFileStats").text(' - ' + r.message);
$pi.find(".ui-progressbar").remove();
$progressItem.after($pi);
} else {
if(r.replace) {
var $child = $this.find('.InputfieldFileList').children('li:eq(0)');
if($child.size() > 0) $child.slideUp('fast', function() { $child.remove(); });
}
// ie10 file field stays populated, this fixes that
var $input = $this.find('input[type=file]');
if($input.val()) $input.replaceWith($input.clone(true));
var $markup = $(r.markup);
$markup.hide();
// look for and handle replacements
if(r.overwrite) {
var basename = $markup.find('.InputfieldFileName').text();
var $item = null;
// find an existing item having the same basename
$fileList.children('.InputfieldFileItemExisting').each(function() {
if($item === null && $(this).find('.InputfieldFileName').text() == basename) {
// filenames match
$item = $(this);
}
});
if($item !== null) {
// found replacement
var $newInfo = $markup.find(".InputfieldFileInfo");
var $newLink = $markup.find(".InputfieldFileLink");
var $info = $item.find(".InputfieldFileInfo");
var $link = $item.find(".InputfieldFileLink");
$info.html($newInfo.html() + "<i class='fa fa-check'></i>");
$link.html($newLink.html());
$item.addClass('InputfieldFileItemExisting');
$item.effect('highlight', 500);
} else {
// didn't find a match, just append
$fileList.append($markup);
$markup.slideDown();
$markup.addClass('InputfieldFileItemExisting');
}
} else {
// overwrite mode not active
$fileList.append($markup);
$markup.slideDown();
}
}
}
$progressItem.remove();
if(doneTimer) clearTimeout(doneTimer);
doneTimer = setTimeout(function() {
$('body').removeClass('pw-uploading');
if(maxFiles != 1 && !$fileList.is('.ui-sortable')) initSortable($fileList);
$fileList.trigger('AjaxUploadDone'); // for things like fancybox that need to be re-init'd
}, 500);
}, false);
// Here we go
xhr.open("POST", postUrl, true);
//see:https://github.com/ryancramerdesign/ProcessWire/issues/1487
//xhr.setRequestHeader("X-FILENAME", unescape(encodeURIComponent(file.name)));
xhr.setRequestHeader("X-FILENAME", encodeURIComponent(file.name));
xhr.setRequestHeader("X-FIELDNAME", fieldName);
xhr.setRequestHeader("Content-Type", "application/octet-stream"); // fix issue 96-Pete
xhr.setRequestHeader("X-" + postTokenName, postTokenValue);
xhr.setRequestHeader("X-REQUESTED-WITH", 'XMLHttpRequest');
xhr.send(file);
// Present file info and append it to the list of files
fileData = '' +
"<i class='fa fa-fw fa-spin fa-spinner'></i> " +
'<span class="InputfieldFileName">' + file.name + '</span>' +
'<span class="InputfieldFileStats"> • ' + parseInt(file.size / 1024, 10) + " kb</span>";
$progressItem.find('p.ui-widget-header').html(fileData);
$fileList.append($progressItem);
var $inputfield = $fileList.closest('.Inputfield');
$inputfield.addClass('InputfieldStateChanged');
var numFiles = $inputfield.find('.InputfieldFileItem').length;
if(numFiles == 1) {
$inputfield.removeClass('InputfieldFileEmpty').removeClass('InputfieldFileMultiple').addClass('InputfieldFileSingle');
} else if(numFiles > 1) {
$inputfield.removeClass('InputfieldFileEmpty').removeClass('InputfieldFileSingle').addClass('InputfieldFileMultiple');
}
}
function traverseFiles(files) {
function errorItem(filename, message) {
return '<li class="InputfieldFile ui-widget AjaxUpload">' +
'<p class="InputfieldFileInfo ui-widget ui-widget-header InputfieldItemHeader ui-state-error"> ' + filename + ' ' +
'<span class="InputfieldFileStats"> • ' + message + '</span></p></li>';
}
if(typeof files !== "undefined") {
for(var i=0, l=files.length; i<l; i++) {
var extension = files[i].name.split('.').pop().toLowerCase();
if(extensions.indexOf(extension) == -1) {
$fileList.append(errorItem(files[i].name, extension + ' is a invalid file extension, please use one of: ' + extensions));
} else if(files[i].size > maxFilesize && maxFilesize > 2000000) {
// I do this test only if maxFilesize is at least 2M (php default).
// There might (not sure though) be some issues to get that value so don't want to overvalidate here -apeisa
$fileList.append(errorItem(files[i].name, 'Filesize ' + parseInt(files[i].size / 1024, 10) +' kb is too big. Maximum allowed is ' + parseInt(maxFilesize / 1024, 10) + ' kb'));
} else {
uploadFile(files[i]);
}
if(maxFiles == 1) break;
}
} else {
fileList.innerHTML = "No support for the File API in this web browser";
}
}
filesUpload.addEventListener("change", function(evt) {
traverseFiles(this.files);
evt.preventDefault();
evt.stopPropagation();
this.value = '';
}, false);
dropArea.addEventListener("dragleave", function() { $(this).removeClass('ui-state-hover'); }, false);
dropArea.addEventListener("dragenter", function() { $(this).addClass('ui-state-hover'); }, false);
dropArea.addEventListener("dragover", function (evt) {
if(!$(this).is('ui-state-hover')) $(this).addClass('ui-state-hover');
evt.preventDefault();
evt.stopPropagation();
}, false);
dropArea.addEventListener("drop", function (evt) {
traverseFiles(evt.dataTransfer.files);
$(this).removeClass("ui-state-hover");
evt.preventDefault();
evt.stopPropagation();
}, false);
} // initHTML5Item
} // initHTML5
/**
* MAIN
*
*/
initSortable($(".InputfieldFileList"));
/**
* Progressive enchanchment for browsers that support html5 File API
*
* #PageIDIndictator.size indicates PageEdit, which we're limiting AjaxUpload to since only ProcessPageEdit has the ajax handler
*
*/
if (window.File && window.FileList && window.FileReader
&& ($("#PageIDIndicator").length > 0 || $('.InputfieldAllowAjaxUpload').length > 0)) {
InitHTML5('');
} else {
InitOldSchool();
}
var minContainerWidth = 767; // ...or when the container width is this or smaller
var resizeActive = false;
var windowResize = function() {
$(".AjaxUploadDropHere").each(function() {
var $t = $(this);
if($t.parent().width() <= minContainerWidth) {
$t.hide();
} else {
$t.show();
}
});
resizeActive = false;
}
$(window).resize(function() {
if(resizeActive) return;
resizeActive = true;
setTimeout(windowResize, 1000);
}).resize();
//$(document).on('reloaded', '.InputfieldFileMultiple, .InputfieldFileSingle', function(event) {
$(document).on('reloaded', '.InputfieldHasFileList', function(event) {
initSortable($(this).find(".InputfieldFileList"));
InitHTML5($(this));
windowResize();
});
});