Giter Club home page Giter Club logo

Comments (6)

tathaha avatar tathaha commented on August 25, 2024 1

fix the routing.rs then it will work

use super::super::{
    url,
    util::{self, ClosureNew},
    Url,
};
use std::convert::{identity, TryFrom, TryInto};
use wasm_bindgen::{closure::Closure, JsCast, JsValue};

/// Add a new route using history's `push_state` method.
///
/// # References
/// * [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/History_API)
pub fn push_route<U: Into<Url>>(url: U) -> Url {
    let url = url.into();
    let data = JsValue::from_str(&serde_json::to_string(&url).expect("Problem serializing route data"));

    let title = match &url.title {
        Some(t) => t,
        None => "",
    };

    let mut path = String::from("/") + &url.path.join("/");
    if let Some(search) = &url.search {
        path = path + "?" + search;
    }

    if let Some(hash) = &url.hash {
        path = path + "#" + hash;
    }

    util::history()
        .push_state_with_url(&data, title, Some(&path))
        .expect("Problem pushing state");
    url
}

pub fn setup_popstate_listener<Ms>(
    update: impl Fn(Ms) + 'static,
    updated_listener: impl Fn(Closure<dyn FnMut(web_sys::Event)>) + 'static,
    routes: fn(Url) -> Option<Ms>,
) where
    Ms: 'static,
{
    let closure: Closure<dyn FnMut(web_sys::Event)> = Closure::new(move |ev: web_sys::Event| {
        let ev = ev
            .dyn_ref::<web_sys::PopStateEvent>()
            .expect("Problem casting as Popstate event");

        let url = match ev.state().as_string() {
            Some(state_str) => serde_json::from_str(&state_str).expect("Problem deserializing popstate state"),
            None => url::current(),
        };

        if let Some(routing_msg) = routes(url) {
            update(routing_msg);
        }
    });

    (util::window().as_ref() as &web_sys::EventTarget)
        .add_event_listener_with_callback("popstate", closure.as_ref().unchecked_ref())
        .expect("Problem adding popstate listener");

    updated_listener(closure);
}

pub fn setup_hashchange_listener<Ms>(
    update: impl Fn(Ms) + 'static,
    updated_listener: impl Fn(Closure<dyn FnMut(web_sys::Event)>) + 'static,
    routes: fn(Url) -> Option<Ms>,
) where
    Ms: 'static,
{
    let closure: Closure<dyn FnMut(web_sys::Event)> = Closure::new(move |ev: web_sys::Event| {
        let ev = ev
            .dyn_ref::<web_sys::HashChangeEvent>()
            .expect("Problem casting as hashchange event");

        let url: Url = ev
            .new_url()
            .try_into()
            .expect("cast hashchange event url to `Url`");

        if let Some(routing_msg) = routes(url) {
            update(routing_msg);
        }
    });

    (util::window().as_ref() as &web_sys::EventTarget)
        .add_event_listener_with_callback("hashchange", closure.as_ref().unchecked_ref())
        .expect("Problem adding hashchange listener");

    updated_listener(closure);
}

#[allow(clippy::option_map_unit_fn)]
pub fn setup_link_listener<Ms>(update: impl Fn(Ms) + 'static, routes: fn(Url) -> Option<Ms>)
where
    Ms: 'static,
{
    let closure: Closure<dyn FnMut(web_sys::Event)> = Closure::new(move |event: web_sys::Event| {
        if let Some(href_el) = event
            .target()
            .and_then(|et| et.dyn_into::<web_sys::Element>().ok())
            .and_then(|el| el.closest("[href]").ok())
        {
            if let Some(Ok(href)) = href_el.and_then(|el| Some(Ok::<_, JsValue>(el.get_attribute("href").unwrap())))
            {
                if href.is_empty() {
                    event.prevent_default(); // Prevent page refresh
                } else {
                    let url = Url::try_from(href).expect("cast link href to `Url`");
                    if let Some(redirect_msg) = routes(url.clone()) {
                        push_route(url);
                        event.prevent_default(); // Prevent page refresh
                        update(redirect_msg);
                    }
                }
            }
        }
    });

    (util::document().as_ref() as &web_sys::EventTarget)
        .add_event_listener_with_callback("click", closure.as_ref().unchecked_ref())
        .expect("Problem setting up link interceptor");

    closure.forget();
}




#[cfg(test)]
mod tests {
    use wasm_bindgen_test::*;

    use super::*;

    wasm_bindgen_test_configure!(run_in_browser);

    #[wasm_bindgen_test]
    fn parse_url_simple() {
        let expected = Url {
            path: vec!["path1".into(), "path2".into()],
            hash: None,
            search: None,
            title: None,
        };

        let actual: Url = "/path1/path2".to_string().try_into().unwrap();
        assert_eq!(expected, actual)
    }

    #[wasm_bindgen_test]
    fn parse_url_with_hash_search() {
        let expected = Url {
            path: vec!["path".into()],
            hash: Some("hash".into()),
            search: Some("search=query".into()),
            title: None,
        };

        let actual: Url = "/path?search=query#hash".to_string().try_into().unwrap();
        assert_eq!(expected, actual)
    }

    #[wasm_bindgen_test]
    fn parse_url_with_hash_only() {
        let expected = Url {
            path: vec!["path".into()],
            hash: Some("hash".into()),
            search: None,
            title: None,
        };

        let actual: Url = "/path#hash".to_string().try_into().unwrap();
        assert_eq!(expected, actual)
    }

    #[wasm_bindgen_test]
    fn parse_url_with_hash_routing() {
        let expected = Url {
            path: vec!["".into()],
            hash: Some("/discover".into()),
            search: None,
            title: None,
        };

        let actual: Url = "/#/discover".to_string().try_into().unwrap();
        assert_eq!(expected, actual)
    }
}

from aiode.

theGunner295 avatar theGunner295 commented on August 25, 2024

Receiving a very similar issue when building...
Note that this is when running cargo make build in src/main/webapp

Error Link

On Aiode Dev branch 2.1

from aiode.

Kryod avatar Kryod commented on August 25, 2024

Same issue

from aiode.

robinfriedli avatar robinfriedli commented on August 25, 2024

Would likely have to update seed but since the webapp is barely a demo it's not a priority right now. When I do continue working on the webapp, which I have no plans for right now, I might switch to a different technology entirely anyway.

from aiode.

Snider avatar Snider commented on August 25, 2024

Would likely have to update seed but since the webapp is barely a demo it's not a priority right now. When I do continue working on the webapp, which I have no plans for right now, I might switch to a different technology entirely anyway.

Could you update the readme for the main branch?

from aiode.

robinfriedli avatar robinfriedli commented on August 25, 2024

routing.rs is not my code, it's from the seed framework. Simply updating the dependency would probably be enough to fix it, the webapp hasn't been touched in years. Howver, I'm more likely to just remove it from the master branch entirely. It got merged into master with the other development/v2.0 stuff in a demo state and I currently have no plans to continue working on it

from aiode.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.