Reputation: 11
I want my Cycle.js web application to read data from a file dropped by the user on the page. I have something working by I'm not sure it is the right way to do it. Moreover, my component isn't easily testable because it needs a proper DragEvent with files in it which is difficult to cradt outside the browser (maybe with jsdom ?).
Here's what I have so far:
// src/index.ts
// I need the line below somewhere, not sure it's the right place
document.addEventListener("dragover", (dragEvent) => {
dragEvent.preventDefault();
});
Then my FileLoader component will listen to 'drop' events and read file:
function readFile(file: File): Stream<string> {
return xs.create({
start: (listener) => {
const reader = new FileReader();
reader.onloadend = (_progressEvent) => {
listener.next(reader.result as string);
};
reader.readAsText(file);
},
stop: () => {
/* nothing to stop */
},
});
}
DOM.select(".dropzone")
.events("drop", { preventDefault: true })
.map((dragEvent) => dragEvent.dataTransfer.files[0])
.map(file => readFile(file))
.flatten()
}
Since the reading of a File is some kind of side-effects, I wonder if I should do it in a driver instead but I'm not sure how to do it. The driver would take a Stream of DragEvent (or a Stream of File) as sink and return a source of file contents ?
Upvotes: 1
Views: 42