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 all 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
8 changes: 6 additions & 2 deletions packages/yew-agent/src/worker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub use public::Public;
use super::*;
use js_sys::{Array, Reflect, Uint8Array};
use serde::{Deserialize, Serialize};
use wasm_bindgen::{closure::Closure, JsCast, JsValue};
use wasm_bindgen::{closure::Closure, JsCast, JsValue, UnwrapThrowExt};
use web_sys::{
Blob, BlobPropertyBag, DedicatedWorkerGlobalScope, MessageEvent, Url, Worker, WorkerOptions,
};
Expand Down Expand Up @@ -71,7 +71,11 @@ 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_throw()
.origin()
.unwrap_throw();
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
2 changes: 1 addition & 1 deletion packages/yew-router/src/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use std::cell::RefCell;
use std::rc::{Rc, Weak};

use gloo::events::EventListener;
use gloo_utils::window;
use serde::de::DeserializeOwned;
use serde::Serialize;
use thiserror::Error;
use wasm_bindgen::{JsValue, UnwrapThrowExt};
use yew::callback::Callback;
use yew::utils::window;

use crate::utils::base_url;
use crate::Routable;
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,8 +43,8 @@ pub fn fetch_base_url() -> Option<String> {

#[cfg(test)]
mod tests {
use gloo_utils::document;
use wasm_bindgen_test::wasm_bindgen_test as test;
use yew::utils::*;
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 @@ -113,7 +113,7 @@ fn root() -> Html {
// - 404 redirects
#[test]
fn router_works() {
yew::start_app_in_element::<Root>(yew::utils::document().get_element_by_id("output").unwrap());
yew::start_app_in_element::<Root>(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
4 changes: 2 additions & 2 deletions packages/yew/src/virtual_dom/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ mod layout_tests {
}

pub(crate) fn diff_layouts(layouts: Vec<TestLayout<'_>>) {
let document = crate::utils::document();
let document = gloo_utils::document();
let parent_scope: AnyScope = Scope::<Comp>::new(None).into();
let parent_element = document.create_element("div").unwrap();
let parent_node: Node = parent_element.clone().into();
Expand Down Expand Up @@ -605,7 +605,7 @@ mod benchmarks {
{
let mut old = $old.clone();
let new = $new.clone();
let el = crate::utils::document().create_element("div").unwrap();
let el = gloo_utils::document().create_element("div").unwrap();
old.apply(&el);
(
format!("{} -> {}", attr_variant(&old), attr_variant(&new)),
Expand Down
5 changes: 3 additions & 2 deletions packages/yew/src/virtual_dom/vcomp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,8 @@ impl<COMP: Component> fmt::Debug for VChild<COMP> {
#[cfg(test)]
mod tests {
use super::*;
use crate::{html, utils::document, Children, Component, Context, Html, NodeRef, Properties};
use crate::{html, Children, Component, Context, Html, NodeRef, Properties};
use gloo_utils::document;
use web_sys::Node;

#[cfg(feature = "wasm_test")]
Expand Down Expand Up @@ -319,7 +320,7 @@ mod tests {

#[test]
fn update_loop() {
let document = crate::utils::document();
let document = gloo_utils::document();
let parent_scope: AnyScope = crate::html::Scope::<Comp>::new(None).into();
let parent_element = document.create_element("div").unwrap();

Expand Down
Loading