Created
July 30, 2020 19:25
-
-
Save mattmccray/4ec336332cd094a8af2c3392a23cb424 to your computer and use it in GitHub Desktop.
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
export function selectImage(accepts: string = "image/*"): Promise<File | null> { | |
return new Promise((resolve, reject) => { | |
const input = createFileInput(accepts) | |
let focusCount = 0 | |
let fileWasSelected = false | |
input.onchange = (e: any) => { | |
fileWasSelected = true | |
const file = e.target.files[0] | |
resolve(file) | |
} | |
input.onfocus = (e: any) => { | |
if (focusCount > 0) { // Second focus happens after the system file picker is closed | |
setTimeout(() => { | |
if (!fileWasSelected) { | |
resolve(null) | |
} | |
//console.log("(REMOVING INPUT)") | |
input.onchange = input.onfocus = null | |
document.body.removeChild(input) | |
}, 200) | |
} | |
focusCount += 1 | |
} | |
//console.log("(ADDING INPUT)") | |
document.body.appendChild(input) | |
input.focus() | |
input.click() | |
}) | |
} | |
function createFileInput(accepts?: string) { | |
const input = document.createElement("input") | |
input.type = "file" | |
input.accept = accepts | |
input.style.position = "absolute" | |
input.style.top = "0px" | |
input.style.left = "0px" | |
input.style.opacity = "0" | |
input.style.pointerEvents = 'none' | |
return input | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment