Debian Codegraph @

node/file-selector/src/file-selector.ts

raw
1 import {FileWithPath, toFileWithPath} from './file';
2
3
4 const FILES_TO_IGNORE = [
5 // Thumbnail cache files for macOS and Windows
6 '.DS_Store', // macOs
7 'Thumbs.db' // Windows
8 ];
9
10
11 /**
12 * Convert a DragEvent's DataTrasfer object to a list of File objects
13 * NOTE: If some of the items are folders,
14 * everything will be flattened and placed in the same list but the paths will be kept as a {path} property.
15 *
16 * EXPERIMENTAL: A list of https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle objects can also be passed as an arg
17 * and a list of File objects will be returned.
18 *
19 * @param evt
20 */
21 export async function fromEvent(evt: Event | any): Promise<(FileWithPath | DataTransferItem)[]> {
22 if (isObject<DragEvent>(evt) && isDataTransfer(evt.dataTransfer)) {
23 return getDataTransferFiles(evt.dataTransfer, evt.type);
24 } else if (isChangeEvt(evt)) {
25 return getInputFiles(evt);
26 } else if (Array.isArray(evt) && evt.every(item => 'getFile' in item && typeof item.getFile === 'function')) {
27 return getFsHandleFiles(evt)
28 }
29 return [];
30 }
31
32 function isDataTransfer(value: any): value is DataTransfer {
33 return isObject(value);
34 }
35
36 function isChangeEvt(value: any): value is Event {
37 return isObject<Event>(value) && isObject(value.target);
38 }
39
40 function isObject<T>(v: any): v is T {
41 return typeof v === 'object' && v !== null
42 }
43
44 function getInputFiles(evt: Event) {
45 return fromList<FileWithPath>((evt.target as HTMLInputElement).files).map(file => toFileWithPath(file));
46 }
47
48 // Ee expect each handle to be https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle
49 async function getFsHandleFiles(handles: any[]) {
50 const files = await Promise.all(handles.map(h => h.getFile()));
51 return files.map(file => toFileWithPath(file));
52 }
53
54
55 async function getDataTransferFiles(dt: DataTransfer, type: string) {
56 // IE11 does not support dataTransfer.items
57 // See https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/items#Browser_compatibility
58 if (dt.items) {
59 const items = fromList<DataTransferItem>(dt.items)
60 .filter(item => item.kind === 'file');
61 // According to https://html.spec.whatwg.org/multipage/dnd.html#dndevents,
62 // only 'dragstart' and 'drop' has access to the data (source node)
63 if (type !== 'drop') {
64 return items;
65 }
66 const files = await Promise.all(items.map(toFilePromises));
67 return noIgnoredFiles(flatten<FileWithPath>(files));
68 }
69
70 return noIgnoredFiles(fromList<FileWithPath>(dt.files)
71 .map(file => toFileWithPath(file)));
72 }
73
74 function noIgnoredFiles(files: FileWithPath[]) {
75 return files.filter(file => FILES_TO_IGNORE.indexOf(file.name) === -1);
76 }
77
78 // IE11 does not support Array.from()
79 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibility
80 // https://developer.mozilla.org/en-US/docs/Web/API/FileList
81 // https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList
82 function fromList<T>(items: DataTransferItemList | FileList | null): T[] {
83 if (items === null) {
84 return [];
85 }
86
87 const files = [];
88
89 // tslint:disable: prefer-for-of
90 for (let i = 0; i < items.length; i++) {
91 const file = items[i];
92 files.push(file);
93 }
94
95 return files as any;
96 }
97
98 // https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem
99 function toFilePromises(item: DataTransferItem) {
100 if (typeof item.webkitGetAsEntry !== 'function') {
101 return fromDataTransferItem(item);
102 }
103
104 const entry = item.webkitGetAsEntry();
105
106 // Safari supports dropping an image node from a different window and can be retrieved using
107 // the DataTransferItem.getAsFile() API
108 // NOTE: FileSystemEntry.file() throws if trying to get the file
109 if (entry && entry.isDirectory) {
110 return fromDirEntry(entry) as any;
111 }
112
113 return fromDataTransferItem(item, entry);
114 }
115
116 function flatten<T>(items: any[]): T[] {
117 return items.reduce((acc, files) => [
118 ...acc,
119 ...(Array.isArray(files) ? flatten(files) : [files])
120 ], []);
121 }
122
123 async function fromDataTransferItem(item: DataTransferItem, entry?: FileSystemEntry | null) {
124 // Check if we're in a secure context; due to a bug in Chrome (as far as we know)
125 // the browser crashes when calling this API (yet to be confirmed as a consistent behaviour).
126 //
127 // See:
128 // - https://issues.chromium.org/issues/40186242
129 // - https://github.com/react-dropzone/react-dropzone/issues/1397
130 if (globalThis.isSecureContext && typeof (item as any).getAsFileSystemHandle === 'function') {
131 const h = await (item as any).getAsFileSystemHandle();
132 if (h === null) {
133 throw new Error(`${item} is not a File`);
134 }
135 // It seems that the handle can be `undefined` (see https://github.com/react-dropzone/file-selector/issues/120),
136 // so we check if it isn't; if it is, the code path continues to the next API (`getAsFile`).
137 if (h !== undefined) {
138 const file = await h.getFile();
139 file.handle = h;
140 return toFileWithPath(file);
141 }
142 }
143 const file = item.getAsFile();
144 if (!file) {
145 throw new Error(`${item} is not a File`);
146 }
147 const fwp = toFileWithPath(file, entry?.fullPath ?? undefined);
148 return fwp;
149 }
150
151 // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry
152 async function fromEntry(entry: any) {
153 return entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry);
154 }
155
156 // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry
157 function fromDirEntry(entry: any) {
158 const reader = entry.createReader();
159
160 return new Promise<FileArray[]>((resolve, reject) => {
161 const entries: Promise<FileValue[]>[] = [];
162
163 function readEntries() {
164 // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry/createReader
165 // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader/readEntries
166 reader.readEntries(async (batch: any[]) => {
167 if (!batch.length) {
168 // Done reading directory
169 try {
170 const files = await Promise.all(entries);
171 resolve(files);
172 } catch (err) {
173 reject(err);
174 }
175 } else {
176 const items = Promise.all(batch.map(fromEntry));
177 entries.push(items);
178
179 // Continue reading
180 readEntries();
181 }
182 }, (err: any) => {
183 reject(err);
184 });
185 }
186
187 readEntries();
188 });
189 }
190
191 // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry
192 async function fromFileEntry(entry: any) {
193 return new Promise<FileWithPath>((resolve, reject) => {
194 entry.file((file: FileWithPath) => {
195 const fwp = toFileWithPath(file, entry.fullPath);
196 resolve(fwp);
197 }, (err: any) => {
198 reject(err);
199 });
200 });
201 }
202
203 // Infinite type recursion
204 // https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
205 interface FileArray extends Array<FileValue> {}
206 type FileValue = FileWithPath
207 | FileArray[];