Giter Site home page Giter Site logo

Comments (5)

maccesch avatar maccesch commented on July 4, 2024

Yeah that would be awesome!

from leptos-use.

BrandonDyer64 avatar BrandonDyer64 commented on July 4, 2024

Update: I am working on implementing this in a personal project. When I'm done I'll adapt it for leptos-use and make a PR

from leptos-use.

maccesch avatar maccesch commented on July 4, 2024

That's great! Keep me in the loop 👍🏼

from leptos-use.

BrandonDyer64 avatar BrandonDyer64 commented on July 4, 2024

Got a proof of concept working. It's ugly, but it's a start.

On the server, it uses the Accept-Language header.

On the client it defaults to what the server gave it, and updates the signal if the browser's language changes.

The part about Extension<Arc<HeaderMap>> is because I'm running on a Cloudflare Worker. This will need to be adapted to work with axum, actix, and spin like use_cookie() does.

pub fn use_locale() -> Signal<Vec<String>> {
    #[cfg(not(feature = "ssr"))]
    use {leptos_dom::ev::languagechange, leptos_use::*};

    let browser_locales: Signal<Vec<String>> = {
        #[allow(unused_mut)]
        let mut initial_browser_locales: Option<Vec<String>> = None;
        cfg_if::cfg_if! {
            if #[cfg(not(feature = "ssr"))] {
                let window = use_window();
                let navigator = window.navigator();
                initial_browser_locales = navigator
                    .map(|navigator| navigator.languages().to_vec())
                    .map(|vec| vec.into_iter().filter_map(|x| x.as_string()).collect::<Vec<String>>());
            }
        }

        #[allow(unused)]
        let (browser_locales, set_browser_locales) = create_signal(initial_browser_locales);

        cfg_if::cfg_if! {
            if #[cfg(not(feature = "ssr"))] {
                let window = use_window();
                let navigator = window.navigator();
                use_event_listener(window, languagechange, move |evt| {
                    let languages = navigator
                        .as_ref()
                        .map(|navigator| navigator.languages().to_vec())
                        .map(|vec| vec.into_iter().filter_map(|x| x.as_string()).collect());
                    set_browser_locales.set(languages);
                });
            }
        }

        Signal::from(move || browser_locales.get().unwrap_or_default())
    };

    #[allow(unused)]
    let locale = create_blocking_resource(
        move || browser_locales.get(),
        |browser_locales| async move {
            cfg_if::cfg_if! {
                if #[cfg(feature = "ssr")] {
                    use axum::Extension;
                    use leptos_axum::*;
                    use std::sync::Arc;
                    use http::HeaderMap;

                    let Extension(headers): Extension<Arc<HeaderMap>> = extract().await.ok()?;
                    let accept_language = headers.get(http::header::ACCEPT_LANGUAGE)?.to_str().ok()?.to_owned();

                    let locales = accept_language
                        .split(',')
                        .map(|locale| {
                            locale
                                .split_once(';')
                                .map(|x|x.0)
                                .unwrap_or(locale).to_owned()
                        })
                        .collect::<Vec<_>>();


                    Some(locales)
                } else {
                    Some(browser_locales)
                }
            }
        },
    );
    Signal::from(move || locale.get().flatten().unwrap_or_default())
}

from leptos-use.

maccesch avatar maccesch commented on July 4, 2024

Nice! I don't find it that ugly to be honest 👍

from leptos-use.

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.