audioview/src/controls.rs

100 lines
2.8 KiB
Rust

use web_sys::HtmlInputElement;
use yew::prelude::*;
use yew::services::reader::{FileChunk, ReaderTask};
use yew::services::{ConsoleService, ReaderService};
pub struct Controls {
link: ComponentLink<Self>,
file_input: NodeRef,
reader_service: ReaderService,
reader_task: Option<ReaderTask>,
}
pub enum Msg {
SubmitForm,
FileProgress(Option<FileChunk>),
}
impl Component for Controls {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
file_input: NodeRef::default(),
reader_service: ReaderService::new(),
reader_task: None,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::SubmitForm => {
if let Err(e) = self.handle_submit_form() {
ConsoleService::error(&e);
};
}
Msg::FileProgress(c) => {
if let Err(e) = self.handle_file_progress(c) {
ConsoleService::error(&e);
};
}
};
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn rendered(&mut self, _: bool) {}
fn view(&self) -> Html {
html! {
<section id="controls" style="width: 800px; height: 100px; border: 1px solid grey">
<label>
{"Select an audio file"}
<input ref=self.file_input.clone() type="file"/>
</label>
<button onclick=self.link.callback(move |_| Msg::SubmitForm)>{"Open file"}</button>
</section>
}
}
}
impl Controls {
fn handle_submit_form(&mut self) -> Result<(), String> {
let file_input = self
.file_input
.cast::<HtmlInputElement>()
.ok_or("could not cast file_input")?;
let file_list = file_input.files().ok_or("could not get file list")?;
let file = file_list.get(0).ok_or("could not get file")?;
let cb = self.link.callback(Msg::FileProgress);
let task = self
.reader_service
.read_file_by_chunks(file, cb, 256)
.map_err(|e| e.to_string())?;
self.reader_task = Some(task);
Ok(())
}
fn handle_file_progress(&self, chunk: Option<FileChunk>) -> Result<(), String> {
match chunk {
Some(FileChunk::Started { name, .. }) => {
ConsoleService::log(&format!("Started: {}", name))
}
Some(FileChunk::DataChunk { progress, .. }) => {
ConsoleService::log(&format!("Got chunk, progress: {}", progress))
}
Some(FileChunk::Finished) => ConsoleService::log("Finished"),
_ => (),
}
Ok(())
}
}