Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use functions from gloo_utils instead of re-implementing them #2124

Merged
merged 5 commits into from
Nov 11, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/dyn_create_destroy_apps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ yew = { path = "../../packages/yew" }
slab = "0.4.3"
gloo = "0.3"
wasm-bindgen = "0.2"
gloo-utils = "0.1"

[dependencies.web-sys]
version = "0.3.50"
Expand Down
2 changes: 1 addition & 1 deletion examples/dyn_create_destroy_apps/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use gloo_utils::document;
use slab::Slab;
use web_sys::Element;
use yew::prelude::*;
use yew::utils::document;

mod counter;

Expand Down
1 change: 1 addition & 0 deletions examples/futures/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pulldown-cmark = { version = "0.8", default-features = false }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
yew = { path = "../../packages/yew" }
gloo-utils = "0.1"

[dependencies.web-sys]
version = "0.3"
Expand Down
2 changes: 1 addition & 1 deletion examples/futures/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ async fn fetch_markdown(url: &'static str) -> Result<String, FetchError> {

let request = Request::new_with_str_and_init(url, &opts)?;

let window = yew::utils::window();
let window = gloo_utils::window();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
let resp: Response = resp_value.dyn_into().unwrap();

Expand Down
1 change: 1 addition & 0 deletions examples/inner_html/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ license = "MIT OR Apache-2.0"

[dependencies]
yew = { path = "../../packages/yew" }
gloo-utils = "0.1"

[dependencies.web-sys]
version = "0.3"
Expand Down
2 changes: 1 addition & 1 deletion examples/inner_html/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl Component for Model {
}

fn view(&self, _ctx: &Context<Self>) -> Html {
let div = yew::utils::document().create_element("div").unwrap();
let div = gloo_utils::document().create_element("div").unwrap();
div.set_inner_html(HTML);
// See <https://github.com/yewstack/yew/issues/1546>
console::log_1(&div);
Expand Down
1 change: 1 addition & 0 deletions examples/mount_point/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ license = "MIT OR Apache-2.0"
[dependencies]
wasm-bindgen = "0.2"
yew = { path = "../../packages/yew" }
gloo-utils = "0.1"

[dependencies.web-sys]
version = "0.3"
Expand Down
2 changes: 1 addition & 1 deletion examples/mount_point/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ fn create_canvas(document: &Document) -> HtmlCanvasElement {
}

fn main() {
let document = yew::utils::document();
let document = gloo_utils::document();
let body = document.query_selector("body").unwrap().unwrap();

let canvas = create_canvas(&document);
Expand Down
1 change: 1 addition & 0 deletions examples/two_apps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ license = "MIT OR Apache-2.0"

[dependencies]
yew = { path = "../../packages/yew" }
gloo-utils = "0.1"
2 changes: 1 addition & 1 deletion examples/two_apps/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl Component for Model {
}

fn mount_app(selector: &'static str) -> AppHandle<Model> {
let document = yew::utils::document();
let document = gloo_utils::document();
let element = document.query_selector(selector).unwrap().unwrap();
yew::start_app_in_element(element)
}
Expand Down
1 change: 1 addition & 0 deletions packages/website-test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ yew-agent = { path = "../../packages/yew-agent/" }
boolinator = "2.4"
derive_more = "0.99"
gloo-events = "0.1"
gloo-utils = "0.1"
ranile marked this conversation as resolved.
Show resolved Hide resolved
js-sys = "0.3"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
Expand Down
1 change: 1 addition & 0 deletions packages/yew-agent/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ edition = "2018"
anymap2 = "0.13"
bincode = "1"
gloo-console = "0.1"
gloo-utils = "0.1"
js-sys = "0.3"
serde = { version = "1", features = ["derive"] }
slab = "0.4"
Expand Down
2 changes: 1 addition & 1 deletion packages/yew-agent/src/worker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ where
}

fn worker_new(name_of_resource: &str, is_module: bool) -> Worker {
let origin = yew::utils::origin().unwrap();
let origin = gloo_utils::document().location().unwrap().origin().unwrap();
ranile marked this conversation as resolved.
Show resolved Hide resolved
let script_url = format!("{}/{}", origin, name_of_resource);
let wasm_url = format!("{}/{}", origin, name_of_resource.replace(".js", "_bg.wasm"));
let array = Array::new();
Expand Down
1 change: 1 addition & 0 deletions packages/yew-router/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ wasm_test = []
[dependencies]
yew = { path = "../yew", default-features= false }
yew-router-macro = { path = "../yew-router-macro" }
gloo-utils = "0.1"

wasm-bindgen = "0.2"
js-sys = "0.3"
Expand Down
4 changes: 2 additions & 2 deletions packages/yew-router/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ where

fn create(ctx: &Context<Self>) -> Self {
let link = ctx.link().clone();
let route_listener = EventListener::new(&yew::utils::window(), "popstate", move |_| {
let route_listener = EventListener::new(&gloo_utils::window(), "popstate", move |_| {
link.send_message(Msg::ReRender)
});

Expand All @@ -97,7 +97,7 @@ where
}

fn view(&self, ctx: &Context<Self>) -> Html {
let pathname = yew::utils::window().location().pathname().unwrap();
let pathname = gloo_utils::window().location().pathname().unwrap();
let route = R::recognize(&pathname);

match route {
Expand Down
8 changes: 4 additions & 4 deletions packages/yew-router/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ where
}

fn update_route_impl(url: String, push: bool) {
let history = yew::utils::window().history().expect("no history");
let history = gloo_utils::window().history().expect("no history");
let base = base_url();
let path = match base {
Some(base) => {
Expand All @@ -88,7 +88,7 @@ fn update_route_impl(url: String, push: bool) {
.expect("replace history");
}
let event = Event::new("popstate").unwrap();
yew::utils::window()
gloo_utils::window()
.dispatch_event(&event)
.expect("dispatch");
}
Expand All @@ -97,7 +97,7 @@ pub fn parse_query<T>() -> Result<T, serde_urlencoded::de::Error>
where
T: for<'de> Deserialize<'de>,
{
let query = yew::utils::document().location().unwrap().search().unwrap();
let query = gloo_utils::document().location().unwrap().search().unwrap();
serde_urlencoded::from_str(query.strip_prefix('?').unwrap_or(""))
}

Expand All @@ -119,7 +119,7 @@ pub fn attach_route_listener<R>(callback: Callback<Option<R>>) -> RouteListener
where
R: Routable + 'static,
{
let listener = EventListener::new(&yew::utils::window(), "popstate", move |_| {
let listener = EventListener::new(&gloo_utils::window(), "popstate", move |_| {
callback.emit(current_route())
});

Expand Down
4 changes: 2 additions & 2 deletions packages/yew-router/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn base_url() -> Option<String> {
}

pub fn fetch_base_url() -> Option<String> {
match yew::utils::document().query_selector("base[href]") {
match gloo_utils::document().query_selector("base[href]") {
Ok(Some(base)) => {
let base = base.unchecked_into::<web_sys::HtmlBaseElement>().href();

Expand All @@ -43,10 +43,10 @@ pub fn fetch_base_url() -> Option<String> {

#[cfg(test)]
mod tests {
use gloo_utils::document;
use serde::Serialize;
use std::collections::HashMap;
use wasm_bindgen_test::wasm_bindgen_test as test;
use yew::utils::*;
use yew_router::parse_query;
use yew_router::prelude::*;
use yew_router::utils::*;
Expand Down
2 changes: 1 addition & 1 deletion packages/yew-router/tests/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ fn component() -> Html {
// - 404 redirects
#[test]
fn router_works() {
yew::start_app_in_element::<Comp>(yew::utils::document().get_element_by_id("output").unwrap());
yew::start_app_in_element::<Comp>(gloo_utils::document().get_element_by_id("output").unwrap());

assert_eq!("Home", obtain_result_by_id("result"));

Expand Down
6 changes: 3 additions & 3 deletions packages/yew-router/tests/utils.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use wasm_bindgen::JsCast;

pub fn obtain_result_by_id(id: &str) -> String {
yew::utils::document()
gloo_utils::document()
.get_element_by_id(id)
.expect("No result found. Most likely, the application crashed and burned")
.inner_html()
}

pub fn click(selector: &str) {
yew::utils::document()
gloo_utils::document()
.query_selector(selector)
.unwrap()
.unwrap()
Expand All @@ -18,7 +18,7 @@ pub fn click(selector: &str) {
}

pub fn history_length() -> u32 {
yew::utils::window()
gloo_utils::window()
.history()
.expect("No history found")
.length()
Expand Down
2 changes: 1 addition & 1 deletion packages/yew/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ categories = ["gui", "wasm", "web-programming"]
description = "A framework for making client-side single-page apps"

[dependencies]
anyhow = "1"
console_error_panic_hook = "0.1"
gloo = "0.3"
gloo-utils = "0.1.0"
indexmap = { version = "1", features = ["std"] }
js-sys = "0.3"
slab = "0.4"
Expand Down
2 changes: 1 addition & 1 deletion packages/yew/src/app_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::ops::Deref;

use crate::html::{Component, NodeRef, Scope, Scoped};
use crate::utils::document;
use gloo_utils::document;
use std::rc::Rc;
use web_sys::Element;

Expand Down
4 changes: 2 additions & 2 deletions packages/yew/src/functional/hooks/use_effect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ struct UseEffect<Destructor> {
/// let counter_one = counter.clone();
/// use_effect(move || {
/// // Make a call to DOM API after component is rendered
/// yew::utils::document().set_title(&format!("You clicked {} times", *counter_one));
/// gloo_utils::document().set_title(&format!("You clicked {} times", *counter_one));
///
/// // Perform the cleanup
/// || yew::utils::document().set_title(&format!("You clicked 0 times"))
/// || gloo_utils::document().set_title(&format!("You clicked 0 times"))
/// });
///
/// let onclick = {
Expand Down
2 changes: 1 addition & 1 deletion packages/yew/src/functional/hooks/use_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use std::{cell::RefCell, rc::Rc};
/// let message_count = use_ref(|| 0);
///
/// let onclick = Callback::from(move |e| {
/// let window = yew::utils::window();
/// let window = gloo_utils::window();
///
/// if *message_count.borrow_mut() > 3 {
/// window.alert_with_message("Message limit reached");
Expand Down
2 changes: 1 addition & 1 deletion packages/yew/src/html/component/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ mod tests {
}

fn test_lifecycle(props: Props, expected: &[&str]) {
let document = crate::utils::document();
let document = gloo_utils::document();
let scope = Scope::<Comp>::new(None);
let el = document.create_element("div").unwrap();
let lifecycle = props.lifecycle.clone();
Expand Down
2 changes: 1 addition & 1 deletion packages/yew/src/html/component/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use crate::callback::Callback;
use crate::context::{ContextHandle, ContextProvider};
use crate::html::NodeRef;
use crate::scheduler::{self, Shared};
use crate::utils::document;
use crate::virtual_dom::{insert_node, VNode};
use gloo_utils::document;
use std::any::{Any, TypeId};
use std::cell::{Ref, RefCell};
use std::future::Future;
Expand Down
2 changes: 1 addition & 1 deletion packages/yew/src/html/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ impl NodeRef {
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::document;
use gloo_utils::document;

#[cfg(feature = "wasm_test")]
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
Expand Down
2 changes: 1 addition & 1 deletion packages/yew/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ where
COMP: Component,
{
start_app_with_props_in_element(
crate::utils::document()
gloo_utils::document()
.body()
.expect("no body node found")
.into(),
Expand Down
43 changes: 0 additions & 43 deletions packages/yew/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,8 @@
//! This module contains useful utilities to get information about the current document.

use std::marker::PhantomData;

use anyhow::{anyhow, Error};
use web_sys::{Document, Window};

use yew::html::ChildrenRenderer;

/// Returns the current window. This function will panic if there is no available window.
pub fn window() -> Window {
web_sys::window().expect("no window available")
}

/// Returns the current document.
pub fn document() -> Document {
window().document().unwrap()
}

/// Returns the `host` for the current document. Useful for connecting to the server which serves
/// the app.
pub fn host() -> Result<String, Error> {
let location = document()
.location()
.ok_or_else(|| anyhow!("can't get location"))?;

let host = location.host().map_err(|e| {
anyhow!(e
.as_string()
.unwrap_or_else(|| String::from("error not recoverable")),)
})?;

Ok(host)
}

/// Returns the `origin` of the current window.
pub fn origin() -> Result<String, Error> {
let location = window().location();

let origin = location.origin().map_err(|e| {
anyhow!(e
.as_string()
.unwrap_or_else(|| String::from("error not recoverable")),)
})?;

Ok(origin)
}

/// Map IntoIterator<Item=Into<T>> to Iterator<Item=T>
pub fn into_node_iter<IT, T, R>(it: IT) -> impl Iterator<Item = R>
where
Expand Down
7 changes: 4 additions & 3 deletions packages/yew/src/virtual_dom/listeners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ thread_local! {
static LISTENER_ID_PROP: wasm_bindgen::JsValue = "__yew_listener_id".into();

/// Cached reference to the document body
static BODY: web_sys::HtmlElement = crate::utils::document().body().unwrap();
static BODY: web_sys::HtmlElement = gloo_utils::document().body().unwrap();
}

/// Bubble events during delegation
Expand Down Expand Up @@ -526,7 +526,8 @@ mod tests {
use web_sys::{Event, EventInit};
wasm_bindgen_test_configure!(run_in_browser);

use crate::{html, html::TargetCast, utils::document, AppHandle, Component, Context, Html};
use crate::{html, html::TargetCast, AppHandle, Component, Context, Html};
use gloo_utils::document;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;

Expand Down Expand Up @@ -665,7 +666,7 @@ mod tests {

async fn await_animation_frame() {
JsFuture::from(js_sys::Promise::new(&mut |resolve, _| {
crate::utils::window()
gloo_utils::window()
.request_animation_frame(&resolve)
.unwrap();
}))
Expand Down
Loading