Make pokedex example work on Wasm
This commit is contained in:
parent
ca213922d0
commit
9df3fb13c7
2 changed files with 37 additions and 11 deletions
|
|
@ -8,7 +8,12 @@ publish = false
|
|||
[dependencies]
|
||||
iced = { path = "../..", features = ["image", "debug"] }
|
||||
iced_futures = { path = "../../futures", features = ["tokio"] }
|
||||
reqwest = { version = "0.10", features = ["json"] }
|
||||
rand = "0.7"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
rand = { version = "0.7", features = ["wasm-bindgen"] }
|
||||
|
||||
[dependencies.reqwest]
|
||||
version = "0.10"
|
||||
git = "https://github.com/hecrj/reqwest.git"
|
||||
branch = "feature/wasm-deserialize-json"
|
||||
features = ["json"]
|
||||
|
|
|
|||
|
|
@ -27,7 +27,12 @@ enum Message {
|
|||
}
|
||||
|
||||
impl Application for Pokedex {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
type Executor = iced_futures::executor::Tokio;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
type Executor = iced_futures::executor::WasmBindgen;
|
||||
|
||||
type Message = Message;
|
||||
|
||||
fn new() -> (Pokedex, Command<Message>) {
|
||||
|
|
@ -166,18 +171,20 @@ impl Pokemon {
|
|||
}
|
||||
|
||||
let id = {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut rng = rand::rngs::OsRng::default();
|
||||
|
||||
rng.gen_range(0, Pokemon::TOTAL)
|
||||
};
|
||||
|
||||
let url = format!("https://pokeapi.co/api/v2/pokemon-species/{}", id);
|
||||
let sprite = format!("https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/{}.png", id);
|
||||
let fetch_entry = async {
|
||||
let url =
|
||||
format!("https://pokeapi.co/api/v2/pokemon-species/{}", id);
|
||||
|
||||
let (entry, sprite): (Entry, _) = futures::future::try_join(
|
||||
reqwest::get(&url).await?.json(),
|
||||
reqwest::get(&sprite).await?.bytes(),
|
||||
)
|
||||
reqwest::get(&url).await?.json().await
|
||||
};
|
||||
|
||||
let (entry, image): (Entry, _) =
|
||||
futures::future::try_join(fetch_entry, Self::fetch_image(id))
|
||||
.await?;
|
||||
|
||||
let description = entry
|
||||
|
|
@ -195,9 +202,23 @@ impl Pokemon {
|
|||
.chars()
|
||||
.map(|c| if c.is_control() { ' ' } else { c })
|
||||
.collect(),
|
||||
image: image::Handle::from_memory(sprite.as_ref().to_vec()),
|
||||
image,
|
||||
})
|
||||
}
|
||||
|
||||
async fn fetch_image(id: u16) -> Result<image::Handle, reqwest::Error> {
|
||||
let url = format!("https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/{}.png", id);
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let bytes = reqwest::get(&url).await?.bytes().await?;
|
||||
|
||||
Ok(image::Handle::from_memory(bytes.as_ref().to_vec()))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Ok(image::Handle::from_path(url))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue