-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
73 lines (58 loc) · 1.69 KB
/
index.ts
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
import { file, options } from './index.dto';
import { JS_BASE64_PNG } from '../mock/base64.js';
const DT: any = () => {
return new DataTransfer() || new ClipboardEvent('').clipboardData;
}
const getBlob: any = async (url: string) => {
try {
return await fetch(url).then(res => res.blob());
} catch (e) {
console.error('Fetching failed');
throw new Error(e.stack);
}
};
const fillInFile = async (
domSelector: string,
files: file | [file] | string,
options: options = {}
) => {
// get element
const $document: Document = options.documentContext || document;
const $element: HTMLInputElement = $document.querySelector(domSelector);
if (!$element) {
throw new Error(`Element not found, ${domSelector}`);
}
const dataTransfer: DataTransfer = DT();
const addFile = async (file) => {
// create blob object
const blob: Blob = await getBlob(file.url);
// create file object
const fileObject: File = new File([blob], file.name, file.options);
// push to data transfer
dataTransfer.items.add(fileObject);
};
switch (typeof files) {
case 'object':
if (Array.isArray(files)) {
for (const file of files) {
await addFile(file);
}
} else {
await addFile(files);
}
break;
case 'string':
await addFile({ url: files, name: 'sample.jpg' });
break;
default:
// mock file
await addFile({ url: JS_BASE64_PNG, name: 'javascript.png' });
}
// set files to element
$element.files = dataTransfer.files;
// trigger change event
let changeEvent: Event = new Event('change');
$element.dispatchEvent(changeEvent);
return true;
};
export { fillInFile, getBlob, DT };