Created
September 11, 2020 19:48
-
-
Save mitchellirvin/261d82bbf09d5fdee41715fa2622d4a6 to your computer and use it in GitHub Desktop.
Deep clone a DataTransfer, to persist in asynchronous code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/kind | |
enum DataTransferItemKind { | |
FILE = "file", | |
STRING = "string", | |
} | |
/** | |
* Returns a properly deep-cloned object of type DataTransfer. This is necessary because dataTransfer items are lost | |
* in asynchronous calls. See https://stackoverflow.com/questions/55658851/javascript-datatransfer-items-not-persisting-through-async-calls | |
* for more details. | |
* | |
* @param original the DataTransfer to deep clone | |
*/ | |
export function cloneDataTransfer(original: DataTransfer): DataTransfer { | |
const cloned = new DataTransfer(); | |
cloned.dropEffect = original.dropEffect; | |
cloned.effectAllowed = original.effectAllowed; | |
const originalItems = original.items; | |
let i = 0; | |
let originalItem = originalItems[i]; | |
while (originalItem != null) { | |
switch (originalItem.kind) { | |
case DataTransferItemKind.FILE: | |
const file = originalItem.getAsFile(); | |
if (file != null) { | |
cloned.items.add(file); | |
} | |
break; | |
case DataTransferItemKind.STRING: | |
cloned.setData(originalItem.type, original.getData(originalItem.type)); | |
break; | |
default: | |
console.error("Unrecognized DataTransferItem.kind: ", originalItem.kind); | |
break; | |
} | |
i++; | |
originalItem = originalItems[i]; | |
} | |
return cloned; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment