import * as _ from "lodash";
const spawn = require('threads').spawn;
/**
* Upload a file. Pass in a valid Element which is an tag with the
* type 'file' and a callback to be invoked when the data is read.
*/
export const uploadFile = (
fileInputElement: HTMLInputElement,
successFn: (result: any, file: File) => void
) => {
const file = fileInputElement.files[0];
const reader = new FileReader();
reader.addEventListener(
"load",
() => {
successFn(reader.result, file);
},
false
);
if (file) {
reader.readAsDataURL(file);
}
};
/**
* Spawn a thread for loading an image
*/
const imageLoaderThread = () => spawn((src: string): Promise => {
return new Promise((resolve, reject) => {
// Guard against invalid src
if (!src) {
// TODO: Use `reject` when can correctly catch in `loadImage`
// reject();
return;
}
// TODO: Use await here. Was getting __awaiter undefined error
fetch(src, {
method: 'GET',
// https://developer.mozilla.org/en-US/docs/Web/API/Request/cache
cache: 'force-cache',
})
.then(response => response.blob())
.then(blob => {
resolve(blob)
});
});
});
export const loadImage = _.memoize((src: string): Promise => {
return new Promise((resolve, reject) => {
// Guard against invalid src
if (!src) {
reject();
return;
}
const thread = imageLoaderThread();
thread
.send(src)
.on('message', (blob) => {
resolve(URL.createObjectURL(blob));
thread.kill();
})
.on('error', () => {
reject();
thread.kill();
});
});
});