-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathFormFileInputWidgetBase.js
More file actions
532 lines (496 loc) · 24.5 KB
/
Copy pathFormFileInputWidgetBase.js
File metadata and controls
532 lines (496 loc) · 24.5 KB
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*******************************************************************************
* Copyright 2023 Adobe
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/**
* This class is responsible for interacting with the file input widget. It implements the file preview,
* file list, handling invalid file size, file name, file mime type functionality
*/
class FormFileInputWidgetBase {
fileItemSelector = '.cmp-adaptiveform-fileinput__fileitem'
widget = null
fileArr = []
fileList = null
lang = "en"
model = null // passed by reference
isFileUpdate = false // handle safari state
options = null // initialize options
regexMimeTypeList = [] // initialize
values = [] // initialize
invalidFeature = {
"SIZE": 1,
"NAME": 2,
"MIMETYPE": 3
}
extensionToMimeTypeMap = {
"bat": "application/x-msdownload",
"com": "application/x-msdownload",
"dll": "application/x-msdownload",
"exe": "application/x-msdownload",
"msi": "application/x-msdownload",
"msg": "application/vnd.ms-outlook",
"dwg": "image/vnd.dwg",
"jxr": "image/vnd.ms-photo",
"psd": "image/vnd.adobe.photoshop",
"ico": "image/vnd.microsoft.icon",
"cab": "application/vnd.ms-cab-compressed",
"deb": "application/vnd.debian.binary-package",
"sqlite": "application/vnd.sqlite3",
"inf2": "image/vnd.cns.inf2",
"djv": "image/vnd.djvu",
"djvu": "image/vnd.djvu",
"dxf": "image/vnd.dxf",
"fbs": "image/vnd.fastbidsheet",
"fpx": "image/vnd.fpx",
"fst": "image/vnd.fst",
"mmr": "image/vnd.fujixerox.edmics-mmr",
"rlc": "image/vnd.fujixerox.edmics-rlc",
"pgb": "image/vnd.globalgraphics.pgb",
"mix": "image/vnd.mix",
"mdi": "image/vnd.ms-modi",
"npx": "image/vnd.net-fpx",
"radiance": "image/vnd.radiance",
"sealed.png": "image/vnd.sealed.png",
"softseal.gif": "image/vnd.sealedmedia.softseal.gif",
"softseal.jpg": "image/vnd.sealedmedia.softseal.jpg",
"svf": "image/vnd.svf"
}
initialFileValueFileNameMap;
constructor(widgetFields) {
// initialize the widget and model
this.widget = widgetFields.widget;
this.model = widgetFields.model();
this.fileList = widgetFields.fileListDiv;
// get the current lang
this.lang = this.model.lang;
// initialize options for backward compatibility
this.options = Object.assign({}, {
"contextPath": ""
}, this.model._jsonModel);
this.attachEventHandlers(widgetFields?.widget, widgetFields?.dragArea);
// initialize the regex initially
this.regexMimeTypeList = this.options.accept.map(function (value, i) {
try {
// Special case for */* to match all MIME types
if (value.trim() === '*/*') {
return /.*/; // Match any MIME type
}
return new RegExp(value.trim());
} catch (e) {
if (window.console) {
console.log(e);
}
}
});
}
attachEventHandlers(widget, model) {
widget.addEventListener('change', (e)=> {
this.handleChange(e?.target?.files);
});
}
// checks if file name is valid or not to prevent security threats
static isValid(fname) {
let rg1=/^[^\\/:\*\;\$\%\?"<>\|]+$/; // forbidden characters \ / : * ? " < > | ; % $
let rg2=/^\./; // cannot start with dot (.)
let rg3=/^(nul|prn|con|lpt[0-9]|com[0-9])(\.|$)/i; // forbidden file names
return rg1.test(fname) && !rg2.test(fname) && !rg3.test(fname);
}
/***
* Finds the value in the array, if the value is a url then it uses the filename in the url to search for the text
* This is done since our model stores the URL too in case of draft restore or clicking on save in guide
* @param text string representing the text of which the index is to be found
* @param elem reference to the jquery element. This is used if there are duplicate file names present in the file upload.
* @returns {number}
* @private
*/
getIndexOfText (text, elem){
let index = -1,
self = this,
isDuplicatePresent = false;
this.values.find(function(value, iter){
// if value is a url, then compare with last
let tempValue = value,
// can't use getOrElse here since value can have "." in URL and getOrElse splits based on period to find key inside object
fileName = (typeof self.initialFileValueFileNameMap === "object" && typeof self.initialFileValueFileNameMap[value] !== undefined) ? self._initialFileValueFileNameMap[value] : null;
if(tempValue.match(/\//g) && tempValue.match(/\//g).length > 1){
tempValue = value.substring(value.lastIndexOf("/")+1);
}
// we pass file name explicity as options, if passed use that as fallback to find the URL
if(tempValue === text || fileName === text){
index = iter;
isDuplicatePresent = self.values.indexOf(value, index + 1) !== -1;
if(elem && isDuplicatePresent){
// now check if duplicate present and get its correct index
// today all files are wrapped under .guide-fu-fileItem node
let fileEntry = elem.parentNode.parentNode;
// index = Array.prototype.indexOf.call(elem, fileEntry);
index = Array.prototype.indexOf.call(fileEntry.children, elem.parentElement);
}
// check if there is a duplicate
// this is to just break the loop
return value;
}
});
return index;
}
static displaySVG(objectUrl) {
const url = objectUrl;
const img = document.createElement('img');
img.src = url;
const newTab = window.open('', '_blank', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
newTab?.document?.body.appendChild(img);
}
static previewFileUsingObjectUrl(file) {
if (file) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE
window.navigator.msSaveOrOpenBlob(file, file.name);
} else {
let url = window.URL.createObjectURL(file);
if (file.type === 'image/svg+xml') {
this.displaySVG(url)
} else {
window.open(url, '', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
}
return url;
}
}
}
static previewFile (event){
let url = arguments[1].fileUrl;
let lastIndex = url.lastIndexOf('/');
//to make sure url has a slash '/'
// added check for query param since sas url contains query params & does not have file name, encoding is not required in this case
if(lastIndex >= 0 && url.indexOf('?') === -1) {
//encode the filename after last slash to ensure the handling of special characters
url = url.substr(0, lastIndex) +'/'+ encodeURIComponent(url.substr(lastIndex + 1));
}
// this would work for dataURl or normal URL
window.open(url, '', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
}
// this function maintains a map for
handleFilePreview (event){
let elem = event.target,
text = elem.textContent,
index = this.getIndexOfText(text, elem),
fileDom = null,
fileName = null,
fileUrl = null;
// for draft usecase, if text contains "/" in it, it means the file is already uploaded
// text should contain the path, assuming that the fileUrl is stored in data element
if (index !== -1) {
// Store the url of file as data
if(typeof elem.dataset.key !== "undefined")
fileUrl = elem.dataset.key;
if(fileUrl && fileUrl !== "[object Blob]") {
//prepend context path if not already appended
if (!(fileUrl.lastIndexOf(this.options.contextPath, 0) === 0)) {
fileUrl = this.options.contextPath + fileUrl;
}
FileInputWidget.previewFile.apply(this, [null, {"fileUrl" : fileUrl}]);
} else {
// todo: add support here
//let previewFileObjIdx = this._getFileObjIdx(index);
let previewFile = this.fileArr[index]?.data;
let objectUrl = FileInputWidget.previewFileUsingObjectUrl(previewFile);
if (objectUrl) {
elem.dataset.objectUrl = objectUrl;
}
}
}
}
/**
* This event listener gets called on click of close button in file upload
*
* @param event
*/
handleClick (event){
let elem = event.target,
text = elem.previousSibling.textContent,
index = this.getIndexOfText(text, elem),
url = elem.previousSibling.dataset.key,
objectUrl = elem.previousSibling.dataset.objectUrl;
if (index !== -1) {
this.values.splice(index, 1);
this.fileArr.splice(index, 1);
// set the model with the new value
this.model.value = this.fileArr;
// value and fileArr contains items of both URL and file types, hence while removing from DOM
// get the correct index as per this.widget.files
let domIndex = Array.from(this.widget.files).findIndex(function(file) {
return file.name === text;
});
this.deleteFilesFromInputDom([domIndex]);
if (url != null) {
// remove the data so that others don't use this url
delete elem.previousSibling.dataset.key;
}
if(objectUrl) {
// revoke the object URL to avoid memory leaks in browser
// since file is anyways getting deleted, remove the object URL's too
window.URL.revokeObjectURL(objectUrl);
}
}
// Remove the dom from view
//All bound events and jQuery data associated with the element are also removed
elem.parentElement.remove();
// Set the focus on file upload button after click of close
this.widget.focus();
}
fileItem(fileName, comment, fileUrl) {
let self = this;
let fileItem = document.createElement('li');
fileItem.setAttribute("class", "cmp-adaptiveform-fileinput__fileitem");
let fileNameDom = document.createElement('span');
fileNameDom.setAttribute('tabindex', '0');
fileNameDom.setAttribute('class', "cmp-adaptiveform-fileinput__filename");
fileNameDom.setAttribute('aria-label', fileName);
fileNameDom.textContent = fileName;
fileNameDom.addEventListener('keypress', function(e) {
if (e.keyCode === 13 || e.charCode === 32) {
e.target.click();
}
});
fileNameDom.addEventListener('click', function(e) {
self.handleFilePreview(e);
});
fileItem.appendChild(fileNameDom);
if(fileUrl != null){
fileNameDom.dataset.key = fileUrl;
}
let fileClose = document.createElement('span');
fileClose.setAttribute('tabindex', '0');
fileClose.setAttribute('class', "cmp-adaptiveform-fileinput__filedelete");
fileClose.setAttribute('aria-label', FormView.LanguageUtils.getTranslatedString(this.lang, "FileCloseAccessText") + fileName);
fileClose.setAttribute('role', 'button');
fileClose.textContent = "x";
fileClose.addEventListener('keypress', function(e) {
if (e.keyCode === 13 || e.charCode === 32) {
e.target.click();
}
});
fileClose.addEventListener('click', function(e) {
self.handleClick(e);
});
fileItem.appendChild(fileClose);
return fileItem;
}
isMultiSelect() {
return this.options.type === "file[]" || this.options.type === "string[]";
}
showFileList(fileName, comment, fileUrl) {
if(!this.isMultiSelect() || fileName === null || typeof fileName === "undefined") {
// if not multiselect, remove all the children of file list
while (this.fileList.lastElementChild) {
this.fileList.removeChild(this.fileList.lastElementChild);
}
}
// Add the file item
// On click of close, remove the element and update the model
// handle on click of preview button
if(fileName != null) {
this.fileList.append(this.fileItem(fileName, comment, fileUrl));
}
}
showInvalidMessage(fileName, invalidFeature){
let that = this;
let IS_IPAD = navigator.userAgent.match(/iPad/i) !== null,
IS_IPHONE = (navigator.userAgent.match(/iPhone/i) !== null);
if(IS_IPAD || IS_IPHONE){
setTimeout(function() {
that.invalidMessage(that,fileName, invalidFeature);
}, 0);
}
else {
this.invalidMessage(fileName, invalidFeature);
}
}
invalidMessage(fileName, invalidFeature) {
const customMessages = this.options.constraintMessages || {};
const messages = {
[this.invalidFeature.SIZE]: customMessages.maxFileSize || FormView.LanguageUtils.getTranslatedString(this.lang, "FileSizeGreater", [fileName, this.options.maxFileSize]),
[this.invalidFeature.NAME]: customMessages.invalidFileName || FormView.LanguageUtils.getTranslatedString(this.lang, "FileNameInvalid", [fileName]),
[this.invalidFeature.MIMETYPE]: customMessages.accept || FormView.LanguageUtils.getTranslatedString(this.lang, "FileMimeTypeInvalid", [fileName])
};
alert(messages[invalidFeature]);
}
/*
* This function returns FileList object of the passed file array
*/
getFileListItem(files) {
try {
let dataContainer = new DataTransfer() || (new ClipboardEvent("")).clipboardData;
files.forEach(function (file) {
dataContainer.items.add(file);
});
return dataContainer.files;
} catch(err) {
console.error(err);
throw err;
}
}
updateFilesInDom(files) {
// in safari, a change event is trigged if files property is changed dynamically
// hence adding this check to clear existing state only for safari browsers
this.isFileUpdate = true;
this.widget.files = this.getFileListItem(files);
this.isFileUpdate = false;
}
/*
* This function deletes files at specified indexes from input dom elt
*/
deleteFilesFromInputDom(deletedIndexes) {
let remainingFiles = [];
Array.from(this.widget.files).forEach(function(file,idx){
if(!deletedIndexes.includes(idx)){
remainingFiles.push(file);
}
});
try {
// in safari, a change event is trigged if files property is changed dynamically
// hence adding this check to clear existing state only for safari browsers
this.updateFilesInDom(remainingFiles);
} catch(err){
console.error("Deleting files is not supported in your browser");
}
}
setValue(value) {
let isValueSame = false;
if (value != null) {
// change to array since we store array internally
value = Array.isArray(value) ? value : [value];
}
// check if current values and new values are same
if (this.fileArr != null && value != null) {
isValueSame = JSON.stringify(FormView.FileAttachmentUtils.extractFileInfo(this.fileArr)) === JSON.stringify(value);
}
// if new values, update the DOM
if (!isValueSame) {
let oldUrls = {};
// Cache the url before deletion
this.fileList.querySelectorAll(".cmp-adaptiveform-fileinput__filename").forEach(function (elem) {
let url = elem.dataset.key;
if (typeof url !== "undefined") {
let fileName = url.substring(url.lastIndexOf("/") + 1);
oldUrls[fileName] = url;
}
});
// empty the file list
while (this.fileList.lastElementChild) {
this.fileList.removeChild(this.fileList.lastElementChild);
}
// set the new value
if (value != null) {
let self = this;
// Update the value array with the file
this.values = value.map(function (file, index) {
// Check if file Name is a path, if yes get the last part after "/"
let isFileObject= window.File ? file.data instanceof window.File : false,
fileName = typeof file === "string" ? file : file.name,
fileUrl = typeof file === "string" ? file : (isFileObject ? "" : file.data),
fileUploadUrl = fileUrl;
if (oldUrls[fileName]) {
fileUploadUrl = oldUrls[fileName];
}
self.showFileList(fileName, null, fileUploadUrl);
return fileName;
});
this.fileArr = [...value];
}
}
}
handleChange(filesUploaded) {
if (!this.isFileUpdate) {
let currFileName = '',
inValidSizefileNames = '',
inValidNamefileNames = '',
inValidMimeTypefileNames = '',
self = this,
files = filesUploaded;
// Initially set the invalid flag to false
let isInvalidSize = false,
isInvalidFileName = false,
isInvalidMimeType = false;
if (typeof files !== "undefined") {
let invalidFilesIndexes = [];
Array.from(files).forEach(function (file, fileIndex) {
let isCurrentInvalidFileSize = false,
isCurrentInvalidFileName = false,
isCurrentInvalidMimeType = false;
currFileName = file.name.split("\\").pop();
// Now size is in MB
let size = file.size / 1024 / 1024;
// check if file size limit is within limits
if ((size > parseFloat(this.options.maxFileSize))) {
isInvalidSize = isCurrentInvalidFileSize = true;
inValidSizefileNames = currFileName + "," + inValidSizefileNames;
} else if (!FileInputWidget.isValid(currFileName)) {
// check if file names are valid (ie) there are no control characters in file names
isInvalidFileName = isCurrentInvalidFileName = true;
inValidNamefileNames = currFileName + "," + inValidNamefileNames;
} else {
let isMatch = false;
let extension = currFileName.split('.').pop().toLowerCase();
let mimeType = file.type || self.extensionToMimeTypeMap[extension];
// If no MIME type is detected, check if the file extension is in the accept list
if (!mimeType && this.options.acceptExtensions) {
isMatch = this.options.acceptExtensions.some(function(acceptPattern) {
if(!acceptPattern) {
return false;
}
// Remove leading dot if present and convert to lowercase
let cleanPattern = acceptPattern.replace(/^\./, '').toLowerCase();
return cleanPattern === extension;
});
} else {
isMatch = this.regexMimeTypeList.some(function (rx) {
return rx.test(mimeType);
});
}
if (!isMatch) {
isInvalidMimeType = isCurrentInvalidMimeType = true;
inValidMimeTypefileNames = currFileName + "," + inValidMimeTypefileNames;
}
}
// if the file is not invalid, show it and push it to internal array
if (!isCurrentInvalidFileSize && !isCurrentInvalidFileName && !isCurrentInvalidMimeType) {
if(this.isMultiSelect()) {
this.values.push(currFileName);
this.fileArr.push(file);
} else {
this.values = [currFileName];
this.fileArr = [file];
}
} else {
invalidFilesIndexes.push(fileIndex);
}
}, this);
if (invalidFilesIndexes.length > 0 && this.widget !== null) {
this.deleteFilesFromInputDom(invalidFilesIndexes);
}
}
// set the new model value.
this.model.value = this.fileArr;
//this.model.validate();
if (isInvalidSize) {
this.showInvalidMessage(inValidSizefileNames.substring(0, inValidSizefileNames.lastIndexOf(',')), this.invalidFeature.SIZE);
} else if (isInvalidFileName) {
this.showInvalidMessage(inValidNamefileNames.substring(0, inValidNamefileNames.lastIndexOf(',')), this.invalidFeature.NAME);
} else if (isInvalidMimeType) {
this.showInvalidMessage(inValidMimeTypefileNames.substring(0, inValidMimeTypefileNames.lastIndexOf(',')), this.invalidFeature.MIMETYPE);
}
}
this.widget.value = null;
}
}
export default FormFileInputWidgetBase;