audioview/src/controls.rs

76 lines
1.9 KiB
Rust

use crate::agents::audio_agent::{self, AudioAgent};
use web_sys::HtmlInputElement;
use yew::agent::Dispatched;
use yew::agent::Dispatcher;
use yew::prelude::*;
use yew::services::ConsoleService;
pub struct Controls {
link: ComponentLink<Self>,
file_input: NodeRef,
audio_agent: Dispatcher<AudioAgent>,
}
pub enum Msg {
SubmitForm,
}
impl Component for Controls {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
file_input: NodeRef::default(),
audio_agent: AudioAgent::dispatcher(),
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::SubmitForm => {
if let Err(e) = self.handle_submit_form() {
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")?;
self.audio_agent
.send(audio_agent::Request::LoadSamplesFromFile(file));
Ok(())
}
}