1
0
mirror of https://github.com/emilk/egui.git synced 2026-08-31 05:40:03 -04:00

egui_web: Add simple fetch API and demostrate it in example_web

This commit is contained in:
Emil Ernerfeldt
2020-11-18 00:43:58 +01:00
parent 0cb3bb791b
commit fad0029119
8 changed files with 1046 additions and 26 deletions

53
egui_web/src/fetch.rs Normal file
View File

@@ -0,0 +1,53 @@
use wasm_bindgen::prelude::*;
pub struct Response {
pub url: String,
pub ok: bool,
pub status: u16,
pub status_text: String,
pub body: String,
}
/// NOTE: Ok(..) is returned on network error.
/// Err is only for failure to use the fetch api.
pub async fn get_text(url: &str) -> Result<Response, String> {
get_text_jsvalue(url)
.await
.map_err(|err| err.as_string().unwrap_or_default())
}
/// NOTE: Ok(..) is returned on network error.
/// Err is only for failure to use the fetch api.
async fn get_text_jsvalue(url: &str) -> Result<Response, JsValue> {
// https://rustwasm.github.io/wasm-bindgen/examples/fetch.html
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
let mut opts = web_sys::RequestInit::new();
opts.method("GET");
opts.mode(web_sys::RequestMode::Cors);
let request = web_sys::Request::new_with_str_and_init(&url, &opts)?;
request.headers().set("Accept", "*/*")?;
let window = web_sys::window().unwrap();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
assert!(resp_value.is_instance_of::<web_sys::Response>());
let resp: web_sys::Response = resp_value.dyn_into().unwrap();
// TODO: headers
// TODO: support binary get
let body = JsFuture::from(resp.text()?).await?;
let body = body.as_string().unwrap_or_default();
Ok(Response {
status_text: resp.status_text(),
url: resp.url(),
ok: resp.ok(),
status: resp.status(),
body,
})
}

View File

@@ -3,6 +3,7 @@
#![warn(clippy::all)]
pub mod backend;
pub mod fetch;
pub mod webgl;
pub use backend::*;
@@ -14,10 +15,14 @@ use wasm_bindgen::prelude::*;
// ----------------------------------------------------------------------------
// Helpers to hide some of the verbosity of web_sys
pub fn console_log(s: String) {
pub fn console_log(s: impl Into<JsValue>) {
web_sys::console::log_1(&s.into());
}
pub fn console_error(s: impl Into<JsValue>) {
web_sys::console::error_1(&s.into());
}
pub fn now_sec() -> f64 {
web_sys::window()
.expect("should have a Window")
@@ -182,6 +187,13 @@ pub fn set_clipboard_text(s: &str) {
}
}
pub fn spawn_future<F>(future: F)
where
F: std::future::Future<Output = ()> + 'static,
{
wasm_bindgen_futures::spawn_local(future);
}
fn cursor_web_name(cursor: egui::CursorIcon) -> &'static str {
use egui::CursorIcon::*;
match cursor {