Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
use serde::Deserialize;
use wasm_bindgen::prelude::*;
use yew::prelude::*;
use yew::services::console::ConsoleService;
use yew::services::fetch::{FetchService, FetchTask, Request, Response};
use yew::services::keyboard::{KeyListenerHandle, KeyboardService};
use yew::web_sys::KeyboardEvent;
use yew::{
format::{Json, Nothing},
prelude::*,
};
mod constants;
mod switch_viewer;
use switch_viewer::SwitchViewer;
#[derive(Deserialize, Debug, Clone)]
pub struct SwitchKeyMap {}
#[derive(Deserialize, Debug, Clone)]
pub struct SwitchStock {}
struct Tasks {
switch_fetch_task: Option<FetchTask>,
stock_fetch_task: Option<FetchTask>,
}
struct Model {
initialized: bool,
key: Option<String>,
link: ComponentLink<Self>,
switch_key_map: Option<SwitchKeyMap>,
switch_stock: Option<SwitchStock>,
key_listener: Option<KeyListenerHandle>,
tasks: Tasks,
}
enum Msg {
ReceiveSwitchData(Result<SwitchKeyMap, anyhow::Error>),
ReceiceStockData(Result<SwitchStock, anyhow::Error>),
KeyDown(KeyboardEvent),
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
initialized: false,
link,
key: None,
switch_key_map: None,
switch_stock: None,
key_listener: None,
tasks: Tasks {
switch_fetch_task: None,
stock_fetch_task: None,
},
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ReceiveSwitchData(data) => self.deserialize_switch_json(data),
Msg::ReceiceStockData(data) => self.deserialize_stock_json(data),
Msg::KeyDown(e) => self.keydown_handler(e),
}
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
// Should only return "true" if new properties are different to
// previously received properties.
// This component has no properties so we will always return "false".
false
}
fn view(&self) -> Html {
if !self.initialized {
self.initializing_view()
} else if let Some(key_str) = &self.key {
html! {
<div>
<SwitchViewer key_str=key_str />
</div>
}
} else {
self.default_view()
}
}
fn rendered(&mut self, first_render: bool) {
if first_render {
self.fetch_data();
let callback = self.link.callback(Msg::KeyDown);
let window = yew::web_sys::window().expect("should get window");
self.key_listener = Some(KeyboardService::register_key_down(&window, callback));
}
}
}
impl Model {
fn fetch_data(&mut self) -> bool {
ConsoleService::log("initialize");
let sw_req = Request::get(constants::SWITCHES_JSON_URL)
.body(Nothing)
.expect("Could not build request.");
let st_req = Request::get(constants::STOCKS_JSON_URL)
.body(Nothing)
.expect("Could not build request.");
let sw_callback = self.link.callback(
|response: Response<Json<Result<SwitchKeyMap, anyhow::Error>>>| {
ConsoleService::log(&format!("{:?}", response));
let Json(data) = response.into_body();
Msg::ReceiveSwitchData(data)
},
);
let st_callback = self.link.callback(
|response: Response<Json<Result<SwitchStock, anyhow::Error>>>| {
ConsoleService::log(&format!("{:?}", response));
let Json(data) = response.into_body();
Msg::ReceiceStockData(data)
},
);
let sw_task = FetchService::fetch(sw_req, sw_callback).expect("failed to start request");
let st_task = FetchService::fetch(st_req, st_callback).expect("failed to start request");
self.tasks.switch_fetch_task = Some(sw_task);
self.tasks.stock_fetch_task = Some(st_task);
true
}
fn deserialize_switch_json(&mut self, data: Result<SwitchKeyMap, anyhow::Error>) -> bool {
ConsoleService::log(&format!("{:?}", data));
true
}
fn deserialize_stock_json(&mut self, data: Result<SwitchStock, anyhow::Error>) -> bool {
ConsoleService::log(&format!("{:?}", data));
true
}
fn keydown_handler(&mut self, e: KeyboardEvent) -> bool {
e.prevent_default();
e.stop_propagation();
self.key = Some(KeyboardEvent::key(&e));
true
}
fn default_view(&self) -> Html {
html! {
<img src=constants::TOP_IMAGE_URL />
}
}
fn initializing_view(&self) -> Html {
html! {
<p> {"initializing..."} </p>
}
}
}
#[wasm_bindgen(start)]
pub fn run_app() -> Result<(), JsValue> {
App::<Model>::new().mount_to_body();
ConsoleService::log("hoge");
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment