Giter Site home page Giter Site logo

synphonyte / leptos-use Goto Github PK

View Code? Open in Web Editor NEW
249.0 3.0 37.0 1.14 MB

Collection of essential Leptos utilities inspired by React-Use / VueUse / SolidJS-USE

Home Page: https://leptos-use.rs/

License: Apache License 2.0

Rust 97.59% HTML 0.02% CSS 1.50% JavaScript 0.05% Python 0.82% Shell 0.01%
leptos reactive rust webassembly dom utility-library leptos-use react-use solidjs-use vueuse

leptos-use's People

Contributors

danikvitek avatar feral-dot-io avatar flupke avatar freshcobar avatar janos-r avatar javiered avatar joelbeicher avatar lpotthast avatar maccesch avatar mondeja avatar rakshith-ravi avatar sbking avatar seanaye avatar sectore avatar sify21 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

leptos-use's Issues

Consider individual feature-gates for functions

It should be profiled if adding features for all functions (possibly with the same name as the function) reduces wasm binary size when an application or library depending on leptos-use only reqiures a limited set of features from it.

A feature named "full" could be added, automatically enabling all functionality of leptos-use to still enable easy usage if needed.

use_websocket errors on route change

When using use_websocket inside of a route, there are console errors on route change away.

Example console trace (hashes/filenames omitted):

Uncaught RuntimeError: unreachable
    at __rust_start_panic
    at rust_panic
    at std::panicking::rust_panic_with_hook
    at std::panicking::begin_panic_handler::{{closure}}
    at std::sys_common::backtrace::__rust_end_short_backtrace
    at rust_begin_unwind
    at core::panicking::panic_fmt
    at core::option::expect_failed
    at core::option::Option<T>::expect
    at leptos_reactive::stored_value::StoredValue<T>::get_value

The trace would suggest a lifetime issue with one of the stored values in use_websocket. Unfortunately the trace doesn't help identify which stored value it might be.

Example repo to demonstrate the error: https://github.com/BakerNet/leptos-use-websocket-error

Changing color mode panics

Hello,
changing a color mode using use_color_mode causes a panic for me.
I have prepared a simple reproduction app.

Cargo.toml:

[package]
name = "app"
version = "0.0.0"
edition = "2021"

[dependencies]
console_error_panic_hook = "0.1.7"
leptos = { version = "0.5.0-alpha2", features = ["csr", "nightly"] }
leptos-use = { git = "https://github.com/Synphonyte/leptos-use.git", rev = "075b073", features = [
  "storage",
] }

main.rs:

use leptos::*;
use leptos_use::{use_color_mode, ColorMode, UseColorModeReturn};

#[component]
fn App() -> impl IntoView {
    let UseColorModeReturn { mode, set_mode, .. } = use_color_mode();

    let toggle_dark = move |_| {
        set_mode(if mode() == ColorMode::Dark {
            ColorMode::Light
        } else {
            ColorMode::Dark
        });
    };

    view! {
        <div>
            <button on:click=toggle_dark>"Toggle dark"</button>
        </div>
    }
}

fn main() {
    std::panic::set_hook(Box::new(console_error_panic_hook::hook));
    leptos::mount_to_body(|| view! { <App/> })
}

image

Additional context:

  • feature "storage" must be present for the problem to occur
  • only changing color mode (dark -> light / light -> dark) triggers the panic
  • appears in both dev and release profile
  • Trunk was used to run the code above in case that matters :)

"Attempted to get a signal after it was disposed" in use_scroll

The code for the on_scroll_end handler in use_scroll_with_options is debounced. This can cause the event handler to be run after the scope that it is in has already been disposed, resulting in this panic:

panicked at 'Attempted to get a signal after it was disposed.
signal created here: C:\Users\Luxalpa\.cargo\registry\src\index.crates.io-6f17d22bba15001f\leptos-use-0.8.2\src\use_scroll.rs:202:44
warning happened here: C:\Users\Luxalpa\.cargo\registry\src\index.crates.io-6f17d22bba15001f\leptos-use-0.8.2\src\use_scroll.rs:260:34', C:\Users\Luxalpa\.cargo\registry\src\index.crates.io-6f17d22bba15001f\leptos-use-0.8.2\src\use_scroll.rs:260:34

I think it needs to use and handle the result from try_get_untracked instead on this line:

if !is_scrolling.get_untracked() {

Support builds using stable rust

The library seems to be build with the nightly compiler in mind.
This excludes all library consumers which only want to use stable.

Things like using a WriteSignal like a function (write_signal(val)) instead of calling set like write_signal.set(val) will most likely make up most of the incompatibilities.

As of my experience with leptos, it can be used just fine using stable rust, while being only mildly less convenient.

As leptos-use is a library that could potentially reach a wide audience, consider changing the code to build with stable. This would include more users without excluding nightly users.

Leptos changing so that nightly becomes an available feature instead of stable would help. See: leptos-rs/leptos#567

No coords when using use_geolocation with SSR

Hi there :)

I've been trying to get the user's geolocation with use_geolocation in an SSR app. I'm unsure if this is even possible in an SSR context.

I made a small repo for reference that contains a component with use_geolocation.

The critical part is this component you see below. I saw that use_geolocation calls use_window internally and when I call use_window in this component it returns None.

Do you have a hint on what I might be doing wrong (or if it's even possible)?

Thanks in advance :)

#[component]
fn LocateUser() -> impl IntoView {
    let (location, set_location) = create_signal(None as Option<(f64, f64)>);

    create_effect(move |prev_handle: Option<IntervalHandle>| {
        if let Some(prev_handle) = prev_handle {
            prev_handle.clear();
        };

        log::info!("run effect");

        let locate = move || {
            let window = use_window();
            log::info!("window is some: {:?}", window.is_some()); // logs "window is some: false" to browser console

            log::info!("run locate");
            let UseGeolocationReturn { coords, error, .. } = use_geolocation();
            if let Some(coords) = coords.get() {
                log::info!(
                    "lat: {:?}, long: {:?}",
                    coords.latitude(),
                    coords.longitude()
                );
                set_location(Some((coords.latitude(), coords.longitude())));
            } else {
                log::info!("no coords, error: {:?}", error.get()); // logs "no coords, error: None" to browser console
            };
        };

        set_interval_with_handle(locate, Duration::from_millis(500))
            .expect("could not create interval")
    });

    view! {
        <h1>User location</h1>
        <p>{move || format!("location: {:?}", location.get())}</p>
    }
}

Installing issue

After I add the library ( tried it twice ) , when I run cargo leptos watch I get this error

thread 'main' panicked at /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/js-sys-0.3.64/src/lib.rs:5847:9:
cannot call wasm-bindgen imported functions on non-wasm targets
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
hread 'main' panicked at /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos_axum-0.4.10/src/lib.rs:1042:14:
called Result::unwrap() on an Err value: JoinError::Panic(Id(2), ...)

use_timestamp spams these two warnings when I add it to my project.

I've added use_timestamp to a component and didn't make use of the signal.
I get these two errors spammed into my console (very fast, like request animation frame speed) in Firefox.

At /Users/sam/.cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos-use-0.8.2/src/use_timestamp.rs:87:25, you access a signal or memo (defined at /Users/sam/.cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos-use-0.8.2/src/use_timestamp.rs:76:24) outside a reactive tracking context. This might mean your app is not responding to changes in signal values in the way you expect.

Hereโ€™s how to fix it:

1. If this is inside a `view!` macro, make sure you are passing a function, not a value.
  โŒ NO  <p>{x.get() * 2}</p>
  โœ… YES <p>{move || x.get() * 2}</p>

2. If itโ€™s in the body of a component, try wrapping this access in a closure: 
  โŒ NO  let y = x.get() * 2
  โœ… YES let y = move || x.get() * 2.

3. If youโ€™re *trying* to access the value without tracking, use `.get_untracked()` or `.with_untracked()` instead. [site_os.js:626:9](http://0.0.0.0:8080/pkg/site_os.js)
At /Users/sam/.cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos-use-0.8.2/src/use_raf_fn.rs:92:27, you access a signal or memo (defined at /Users/sam/.cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos-use-0.8.2/src/use_raf_fn.rs:55:35) outside a reactive tracking context. This might mean your app is not responding to changes in signal values in the way you expect.

Hereโ€™s how to fix it:

1. If this is inside a `view!` macro, make sure you are passing a function, not a value.
  โŒ NO  <p>{x.get() * 2}</p>
  โœ… YES <p>{move || x.get() * 2}</p>

2. If itโ€™s in the body of a component, try wrapping this access in a closure: 
  โŒ NO  let y = x.get() * 2
  โœ… YES let y = move || x.get() * 2.

3. If youโ€™re *trying* to access the value without tracking, use `.get_untracked()` or `.with_untracked()` instead.

Thanks for your time.

Compilation bug

I'm using github actions to build a leptos app that uses leptos-use , here's an error I'm getting during build

#12 79.33 error: internal compiler error: no errors encountered even though `delay_span_bug` issued
#12 79.33 
#12 79.34 error: internal compiler error: broken MIR in Item(DefId(0:1074 ~ leptos_use[8b2b]::use_mutation_observer::use_mutation_observer_with_options::{closure#5})) (after phase change to runtime-optimized) at bb1[4]:
#12 79.34                                 Alias(Opaque, AliasTy { args: [std::vec::Vec<std::option::Option<T/#1>, std::alloc::Global>, (), Closure(DefId(0:1072 ~ leptos_use[8b2b]::use_mutation_observer::use_mutation_observer_with_options::{closure#3}), [El/#0, T/#1, F/#2, i8, Binder(extern "RustCall" fn(()) -> std::vec::Vec<std::option::Option<T/#1>, std::alloc::Global>, []), (core::elements_maybe_signal::ElementsMaybeSignal<T/#1, web_sys::Element>,)]), Closure(DefId(0:1073 ~ leptos_use[8b2b]::use_mutation_observer::use_mutation_observer_with_options::{closure#4}), [El/#0, T/#1, F/#2, i8, Binder(extern "RustCall" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon }) std::vec::Vec<std::option::Option<T/#1>, std::alloc::Global>, std::option::Option<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon }) std::vec::Vec<std::option::Option<T/#1>, std::alloc::Global>>, std::option::Option<()>)), [Region(BrAnon), Region(BrAnon)]), (Closure(DefId(0:1071 ~ leptos_use[8b2b]::use_mutation_observer::use_mutation_observer_with_options::{closure#2}), [El/#0, T/#1, F/#2, i8, Binder(extern "RustCall" fn(()), []), (std::rc::Rc<std::cell::RefCell<std::option::Option<web_sys::MutationObserver>>, std::alloc::Global>,)]), leptos::Signal<bool>, wasm_bindgen::JsValue, web_sys::MutationObserverInit, std::rc::Rc<std::cell::RefCell<std::option::Option<web_sys::MutationObserver>>, std::alloc::Global>)])], def_id: DefId(0:2890 ~ leptos_use[8b2b]::watch::watch::{opaque#0}) }) does not have fields
#12 79.34     --> /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos_reactive-0.4.10/src/signal.rs:1074:9
#12 79.34      |
#12 79.34 1074 |         self.id.update(
#12 79.34      |         ^^^^^^^
#12 79.34      |
#12 79.34 note: delayed at compiler/rustc_const_eval/src/transform/validate.rs:94:25
#12 79.34          0: <rustc_errors::HandlerInner>::emit_diagnostic
#12 79.34          1: <rustc_errors::Handler>::delay_span_bug::<rustc_span::span_encoding::Span, alloc::string::String>
#12 79.34          2: <rustc_const_eval::transform::validate::CfgChecker>::fail::<alloc::string::String>
#12 79.34          3: <rustc_const_eval::transform::validate::Validator as rustc_middle::mir::MirPass>::run_pass
#12 79.34          4: rustc_mir_transform::pass_manager::run_passes
#12 79.34          5: rustc_mir_transform::optimized_mir
#12 79.34          6: rustc_query_impl::plumbing::__rust_begin_short_backtrace::<rustc_query_impl::query_impl::optimized_mir::dynamic_query::{closure#2}::{closure#0}, rustc_middle::query::erase::Erased<[u8; 8]>>
#12 79.34          7: <rustc_query_impl::query_impl::optimized_mir::dynamic_query::{closure#2} as core::ops::function::FnOnce<(rustc_middle::ty::context::TyCtxt, rustc_span::def_id::DefId)>>::call_once
#12 79.34          8: rustc_query_system::query::plumbing::try_execute_query::<rustc_query_impl::DynamicConfig<rustc_query_system::query::caches::DefaultCache<rustc_span::def_id::DefId, rustc_middle::query::erase::Erased<[u8; 8]>>, false, false, false>, rustc_query_impl::plumbing::QueryCtxt, false>
#12 79.34          9: rustc_query_impl::query_impl::optimized_mir::get_query_non_incr::__rust_end_short_backtrace
#12 79.34         10: <rustc_metadata::rmeta::encoder::EncodeContext>::encode_crate_root
#12 79.34         11: rustc_metadata::rmeta::encoder::encode_metadata_impl
#12 79.34         12: rustc_data_structures::sync::parallel::disabled::join::<rustc_metadata::rmeta::encoder::encode_metadata::{closure#0}, rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}, (), ()>
#12 79.34         13: rustc_metadata::rmeta::encoder::encode_metadata
#12 79.34         14: rustc_metadata::fs::encode_and_write_metadata
#12 79.34         15: rustc_interface::passes::start_codegen
#12 79.34         16: <rustc_middle::ty::context::GlobalCtxt>::enter::<<rustc_interface::queries::Queries>::ongoing_codegen::{closure#0}, core::result::Result<alloc::boxed::Box<dyn core::any::Any>, rustc_span::ErrorGuaranteed>>
#12 79.34         17: rustc_span::set_source_map::<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#1}>::{closure#0}::{closure#0}>
#12 79.34         18: std::sys_common::backtrace::__rust_begin_short_backtrace::<rustc_interface::util::run_in_thread_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#1}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0}::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>
#12 79.34         19: <<std::thread::Builder>::spawn_unchecked_<rustc_interface::util::run_in_thread_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#1}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0}::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#1} as core::ops::function::FnOnce<()>>::call_once::{shim:vtable#0}
#12 79.34         20: <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once
#12 79.34                    at /rustc/ca62d2c445628587660ae48013f460b08b1f5552/library/alloc/src/boxed.rs:2007:9
#12 79.34         21: <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once
#12 79.34                    at /rustc/ca62d2c445628587660ae48013f460b08b1f5552/library/alloc/src/boxed.rs:2007:9
#12 79.34         22: std::sys::unix::thread::Thread::new::thread_start
#12 79.35                    at /rustc/ca62d2c445628587660ae48013f460b08b1f5552/library/std/src/sys/unix/thread.rs:108:17
#12 79.35         23: start_thread
#12 79.35         24: clone
#12 79.35     --> /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos_reactive-0.4.10/src/signal.rs:1074:9
#12 79.35      |
#12 79.35 1074 |         self.id.update(
#12 79.35      |         ^^^^^^^
#12 79.35 
#12 79.35 error: internal compiler error: broken MIR in Item(DefId(0:1074 ~ leptos_use[8b2b]::use_mutation_observer::use_mutation_observer_with_options::{closure#5})) (after phase change to runtime-optimized) at bb0[0]:
#12 79.35                                 Alias(Opaque, AliasTy { args: [std::vec::Vec<std::option::Option<T/#1>, std::alloc::Global>, (), Closure(DefId(0:1072 ~ leptos_use[8b2b]::use_mutation_observer::use_mutation_observer_with_options::{closure#3}), [El/#0, T/#1, F/#2, i8, Binder(extern "RustCall" fn(()) -> std::vec::Vec<std::option::Option<T/#1>, std::alloc::Global>, []), (core::elements_maybe_signal::ElementsMaybeSignal<T/#1, web_sys::Element>,)]), Closure(DefId(0:1073 ~ leptos_use[8b2b]::use_mutation_observer::use_mutation_observer_with_options::{closure#4}), [El/#0, T/#1, F/#2, i8, Binder(extern "RustCall" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon }) std::vec::Vec<std::option::Option<T/#1>, std::alloc::Global>, std::option::Option<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon }) std::vec::Vec<std::option::Option<T/#1>, std::alloc::Global>>, std::option::Option<()>)), [Region(BrAnon), Region(BrAnon)]), (Closure(DefId(0:1071 ~ leptos_use[8b2b]::use_mutation_observer::use_mutation_observer_with_options::{closure#2}), [El/#0, T/#1, F/#2, i8, Binder(extern "RustCall" fn(()), []), (std::rc::Rc<std::cell::RefCell<std::option::Option<web_sys::MutationObserver>>, std::alloc::Global>,)]), leptos::Signal<bool>, wasm_bindgen::JsValue, web_sys::MutationObserverInit, std::rc::Rc<std::cell::RefCell<std::option::Option<web_sys::MutationObserver>>, std::alloc::Global>)])], def_id: DefId(0:2890 ~ leptos_use[8b2b]::watch::watch::{opaque#0}) }) does not have fields
#12 79.35    --> /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos-use-0.6.3/src/use_mutation_observer.rs:134:9
#12 79.35     |
#12 79.35 134 |         cleanup();
#12 79.35     |         ^^^^^^^
#12 79.35     |
#12 79.35 note: delayed at compiler/rustc_const_eval/src/transform/validate.rs:94:25
#12 79.35          0: <rustc_errors::HandlerInner>::emit_diagnostic
#12 79.35          1: <rustc_errors::Handler>::delay_span_bug::<rustc_span::span_encoding::Span, alloc::string::String>
#12 79.35          2: <rustc_const_eval::transform::validate::CfgChecker>::fail::<alloc::string::String>
#12 79.35          3: <rustc_const_eval::transform::validate::Validator as rustc_middle::mir::MirPass>::run_pass
#12 79.36          4: rustc_mir_transform::pass_manager::run_passes
#12 79.36          5: rustc_mir_transform::optimized_mir
#12 79.36          6: rustc_query_impl::plumbing::__rust_begin_short_backtrace::<rustc_query_impl::query_impl::optimized_mir::dynamic_query::{closure#2}::{closure#0}, rustc_middle::query::erase::Erased<[u8; 8]>>
#12 79.36          7: <rustc_query_impl::query_impl::optimized_mir::dynamic_query::{closure#2} as core::ops::function::FnOnce<(rustc_middle::ty::context::TyCtxt, rustc_span::def_id::DefId)>>::call_once
#12 79.36          8: rustc_query_system::query::plumbing::try_execute_query::<rustc_query_impl::DynamicConfig<rustc_query_system::query::caches::DefaultCache<rustc_span::def_id::DefId, rustc_middle::query::erase::Erased<[u8; 8]>>, false, false, false>, rustc_query_impl::plumbing::QueryCtxt, false>
#12 79.36          9: rustc_query_impl::query_impl::optimized_mir::get_query_non_incr::__rust_end_short_backtrace
#12 79.36         10: <rustc_metadata::rmeta::encoder::EncodeContext>::encode_crate_root
#12 79.36         11: rustc_metadata::rmeta::encoder::encode_metadata_impl
#12 79.36         12: rustc_data_structures::sync::parallel::disabled::join::<rustc_metadata::rmeta::encoder::encode_metadata::{closure#0}, rustc_metadata::rmeta::encoder::encode_metadata::{closure#1}, (), ()>
#12 79.36         13: rustc_metadata::rmeta::encoder::encode_metadata
#12 79.36         14: rustc_metadata::fs::encode_and_write_metadata
#12 79.36         15: rustc_interface::passes::start_codegen
#12 79.36         16: <rustc_middle::ty::context::GlobalCtxt>::enter::<<rustc_interface::queries::Queries>::ongoing_codegen::{closure#0}, core::result::Result<alloc::boxed::Box<dyn core::any::Any>, rustc_span::ErrorGuaranteed>>
#12 79.36         17: rustc_span::set_source_map::<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#1}>::{closure#0}::{closure#0}>
#12 79.36         18: std::sys_common::backtrace::__rust_begin_short_backtrace::<rustc_interface::util::run_in_thread_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#1}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0}::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>
#12 79.36         19: <<std::thread::Builder>::spawn_unchecked_<rustc_interface::util::run_in_thread_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_span::ErrorGuaranteed>, rustc_driver_impl::run_compiler::{closure#1}>::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#0}::{closure#0}, core::result::Result<(), rustc_span::ErrorGuaranteed>>::{closure#1} as core::ops::function::FnOnce<()>>::call_once::{shim:vtable#0}
#12 79.36         20: <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once
#12 79.36                    at /rustc/ca62d2c445628587660ae48013f460b08b1f5552/library/alloc/src/boxed.rs:2007:9
#12 79.36         21: <alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once
#12 79.36                    at /rustc/ca62d2c445628587660ae48013f460b08b1f5552/library/alloc/src/boxed.rs:2007:9
#12 79.36         22: std::sys::unix::thread::Thread::new::thread_start
#12 79.36                    at /rustc/ca62d2c445628587660ae48013f460b08b1f5552/library/std/src/sys/unix/thread.rs:108:17
#12 79.36         23: start_thread
#12 79.36         24: clone
#12 79.36    --> /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos-use-0.6.3/src/use_mutation_observer.rs:134:9
#12 79.36     |
#12 79.36 134 |         cleanup();
#12 79.36     |         ^^^^^^^
#12 79.36 
#12 79.37 note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md
#12 79.37 
#12 79.37 note: please attach the file at `/usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/leptos-use-0.6.3/rustc-ice-2023-10-02T19:02:57.75865494Z-2803.txt` to your bug report
#12 79.37 
#12 79.37 note: compiler flags: --crate-type lib -C opt-level=3 -C embed-bitcode=no
#12 79.37 
#12 79.37 note: some of the compiler flags provided by cargo are hidden

leptos-use book in browser difficult to search.

Regarding the very attractive book...the center Leptos-Use Guide div is partially covering the search button so that clicking on that button often does not work. You really have to click left of the magnifier part of the button.

Infinite scroll does trigger too often

I have a component with the following signals and resources:

    let el = create_node_ref::<html::Tbody>();
    let (page, page_set) = create_signal(1);
    let (data, set_data) = create_signal(vec![]);

    let _ = use_infinite_scroll_with_options(
        el,
        move |_| async move {
            // this is called too often
            page_set.update(|page| *page += 1);
        },
        UseInfiniteScrollOptions::default(),
    );

    let documents = create_resource(
        move || page.get(),
        move |page| async move {
            api_call::<Vec<Doc>, FetchError>(
                "api/doc",
                Method::GET,
                None,
                Some(vec![("page", &page.to_string())]),
            )
            .await
        },
    );

    create_effect(move |_| {
        documents.and_then(|data| {
            if data.is_empty() {
                // we hit the last page, no more elements
                return;
            }
            set_data.update(|d| d.extend_from_slice(data));
        });
    });

When I scroll in my component the function for updating the page is triggered at least twice. how can I improve this and make this work as expected?

iOS mobile browsers in debug build - RuntimeError: Out of bounds memory access

Hi, I'm possibly running into another issue with animation hooks.

When testing on mobile my animation plays but crashes with the following error:

[Error] RuntimeError: Out of bounds memory access (near '...e__h17d0812b54a8d9b9(arg0, arg1, arg2);...')
	<?>.wasm-function[<core::hash::sip::Hasher<S> as core::hash::Hasher>::write::hd27f12575b9e2c86] (red-siren.js:221:131)
	<?>.wasm-function[<std::hash::random::DefaultHasher as core::hash::Hasher>::write_str::h1a220c3d28af20f8]
	<?>.wasm-function[<alloc::string::String as core::hash::Hash>::hash::hdea7d3b55e76c4b2]
	<?>.wasm-function[core::hash::impls::<impl core::hash::Hash for &T>::hash::h22fd84024d3544e2]
	<?>.wasm-function[core::hash::BuildHasher::hash_one::h7af2681160fbb34c]
	<?>.wasm-function[hashbrown::map::make_hasher::{{closure}}::hfc1fb74fb13eeaf1]
	<?>.wasm-function[hashbrown::raw::RawTable<T,A>::reserve_rehash::{{closure}}::hc4c6c53599b42dff]
	<?>.wasm-function[hashbrown::raw::RawTable<T,A>::reserve_rehash::h0afb8b405e7be60a]
	<?>.wasm-function[hashbrown::raw::RawTable<T,A>::reserve::h7a72b1e2de2bfa50]
	<?>.wasm-function[hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot::h85ad248e2ab8f1c9]
	<?>.wasm-function[hashbrown::map::HashMap<K,V,S,A>::insert::h4cbe4a8b9c266f0a]
	<?>.wasm-function[std::collections::hash::map::HashMap<K,V,S>::insert::hd1c66d74c9548059]
	<?>.wasm-function[wasm_bindgen::cache::intern::intern_str::{{closure}}::h5a316852da7bcd4a]
	<?>.wasm-function[std::thread::local::LocalKey<T>::try_with::h23223815444d8749]
	<?>.wasm-function[std::thread::local::LocalKey<T>::with::he6bd9024741f5712]
	<?>.wasm-function[wasm_bindgen::cache::intern::intern_str::h4b1a3c4fe6f18d7d]
	<?>.wasm-function[wasm_bindgen::cache::intern::intern::hc6eb8e2671ca7f4c]
	<?>.wasm-function[leptos_dom::macro_helpers::into_attribute::attribute_expression::h90ba44eabcaeb8e6]
	<?>.wasm-function[leptos_dom::macro_helpers::into_attribute::attribute_helper::{{closure}}::h6ad0ed9723ebe516]
	<?>.wasm-function[<leptos_reactive::effect::EffectState<T,F> as leptos_reactive::effect::AnyComputation>::run::h8e94be9b5a3b9501]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update::{{closure}}::h6a09a305ec706bf8]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::with_observer::h0dc4713bef862b4b]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update::h169ebeaa46e8842e]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update_if_necessary::h30aff96a87d47348]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::run_effects::h877b640567663cf4]
	<?>.wasm-function[leptos_reactive::signal::<impl leptos_reactive::node::NodeId>::update::{{closure}}::h4de4265d7ee3ca63]
	<?>.wasm-function[leptos_reactive::runtime::with_runtime::{{closure}}::hc34f0cef5aaecccd]
	<?>.wasm-function[std::thread::local::LocalKey<T>::try_with::h12283b7f14cb9bdb]
	<?>.wasm-function[std::thread::local::LocalKey<T>::with::h6212145df11ca1b1]
	<?>.wasm-function[web_leptos::app::core::process_effect::h935a819c13960f1e]
	<?>.wasm-function[web_leptos::app::core::update::he802ec2a730de1a4]
	<?>.wasm-function[web_leptos::app::RedSirenRoutes::__RedSirenRoutes::{{closure}}::h6c82da443b523c8b]
	<?>.wasm-function[<leptos_reactive::effect::EffectState<T,F> as leptos_reactive::effect::AnyComputation>::run::hae44b3691dddd310]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update::{{closure}}::h6a09a305ec706bf8]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::with_observer::h0dc4713bef862b4b]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update::h169ebeaa46e8842e]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update_if_necessary::h30aff96a87d47348]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::run_effects::h877b640567663cf4]
	<?>.wasm-function[leptos_reactive::signal::<impl leptos_reactive::node::NodeId>::update::{{closure}}::hfeb5cb7a45107127]
	<?>.wasm-function[leptos_reactive::runtime::with_runtime::{{closure}}::h1fa51316342504cc]
	<?>.wasm-function[std::thread::local::LocalKey<T>::try_with::h7939abe82aa82eb0]
	<?>.wasm-function[std::thread::local::LocalKey<T>::with::h2a3ad6479c5e9daf]
	<?>.wasm-function[<leptos_reactive::signal::WriteSignal<T> as leptos_reactive::signal::SignalSet>::set::hb9522028bb3a1220]
	<?>.wasm-function[web_leptos::app::RedSirenRoutes::__RedSirenRoutes::{{closure}}::h5a506e59f6bf9259]
	<?>.wasm-function[<alloc::boxed::Box<F,A> as core::ops::function::Fn<Args>>::call::hcd4f71baf5e8a4e4]
	<?>.wasm-function[leptos_reactive::signal_wrappers_write::SignalSetter<T>::set::{{closure}}::h53e2ad030bb95467]
	<?>.wasm-function[leptos_reactive::stored_value::StoredValue<T>::try_with_value::{{closure}}::hff6899d6c14a20b3]
	<?>.wasm-function[leptos_reactive::runtime::with_runtime::{{closure}}::h449b6716776ff7c4]
	<?>.wasm-function[std::thread::local::LocalKey<T>::try_with::h405d85900a0a038a]
	<?>.wasm-function[std::thread::local::LocalKey<T>::with::h6c965a1db66da2f2]
	<?>.wasm-function[leptos_reactive::stored_value::StoredValue<T>::try_with_value::h424a6bcb2d555310]
	<?>.wasm-function[leptos_reactive::stored_value::StoredValue<T>::with_value::h466903ec859db30a]
	<?>.wasm-function[leptos_reactive::signal_wrappers_write::SignalSetter<T>::set::h3c8dc580bcd56dcc]
	<?>.wasm-function[web_leptos::app::intro::IntroComponent::__IntroComponent::{{closure}}::hf47b40f40372f3f9]
	<?>.wasm-function[<leptos_reactive::effect::EffectState<T,F> as leptos_reactive::effect::AnyComputation>::run::hb4cf3316437558ed]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update::{{closure}}::h6a09a305ec706bf8]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::with_observer::h0dc4713bef862b4b]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update::h169ebeaa46e8842e]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::update_if_necessary::h30aff96a87d47348]
	<?>.wasm-function[leptos_reactive::runtime::Runtime::run_effects::h877b640567663cf4]
	<?>.wasm-function[leptos_reactive::signal::<impl leptos_reactive::node::NodeId>::update::{{closure}}::h26b2187a0c71272d]
	<?>.wasm-function[leptos_reactive::runtime::with_runtime::{{closure}}::h190a72cc70ecd93b]
	<?>.wasm-function[std::thread::local::LocalKey<T>::try_with::ha50a99089044af68]
	<?>.wasm-function[std::thread::local::LocalKey<T>::with::h1bc079b744a4679b]
	<?>.wasm-function[<leptos_reactive::signal::WriteSignal<T> as leptos_reactive::signal::SignalSet>::set::hef157673d0468bb6]
	<?>.wasm-function[leptos_use::use_timestamp::use_timestamp_with_controls_and_options::{{closure}}::hdd14e0253f73a5a9]
	<?>.wasm-function[leptos_use::use_timestamp::use_timestamp_with_controls_and_options::{{closure}}::hdb0543a2b31a211c]
	<?>.wasm-function[leptos_use::use_timestamp::use_timestamp_with_controls_and_options::{{closure}}::h64387bcc4527fe86]
	<?>.wasm-function[leptos_use::use_raf_fn::use_raf_fn_with_options::{{closure}}::h79a2afedc8e0e155]
	<?>.wasm-function[<alloc::boxed::Box<F,A> as core::ops::function::Fn<Args>>::call::h202f74ed834a88c3]
	<?>.wasm-function[leptos_use::use_raf_fn::use_raf_fn_with_options::{{closure}}::{{closure}}::h6a968829ddd5c610]
	<?>.wasm-function[core::ops::function::FnOnce::call_once::h9696a2220e728cf0]
	<?>.wasm-function[<T as wasm_bindgen::closure::WasmClosureFnOnce<A,R>>::into_js_function::{{closure}}::h765a049365f6e03c]
	<?>.wasm-function[<dyn core::ops::function::FnMut<(A,)>+Output = R as wasm_bindgen::closure::WasmClosure>::describe::invoke::h17d0812b54a8d9b9]
	wasm-stub
	__wbg_adapter_41 (red-siren.js:221:131)
	real (red-siren.js:202)

This doesn't happen on android device (tested in emulator), nor in the release build

You can see my usage here

https://github.com/anvlkv/red-siren/blob/4fb9d1ae26c0c3c9af5077b540c70a8f34ededcb/web-leptos/src/app/intro.rs#L9C1-L31C8

Example SSR with 'use_color_mode' runtime panic

Hi,
thanks for your work on this, crate looks really promising!

I cloned this repo and added browser example of use_color_mode and got

1
2
thread 'main' panicked at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/js-sys-0.3.64/src/lib.rs:5847:9:
cannot call wasm-bindgen imported functions on non-wasm targets
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at /rustc/09df6108c84fdec400043d99d9ee232336fd5a9f/library/std/src/thread/local.rs:246:26:
cannot access a Thread Local Storage value during or after destruction: AccessError
fatal runtime error: thread local panicked on drop

Actual code I used for testing:

  logging::log!("1");
  let color_modes = vec![
      "rust".into(),
      "coal".into(),
      "navy".into(),
      "ayu".into(),
  ];
  
  let options = UseColorModeOptions::default().custom_modes(color_modes.to_owned());
  logging::log!("2");
  let UseColorModeReturn { mode, set_mode, .. } = use_color_mode_with_options(options);
  logging::log!("3");
  // Set theme or use existing
  let current = mode.get_untracked();
  logging::log!("4, active: {:?}", current);

  match current {
      ColorMode::Auto => set_mode.set(ColorMode::Custom("white".into())),
      ColorMode::Light => set_mode.set(ColorMode::Custom("white".into())),
      ColorMode::Dark => set_mode.set(ColorMode::Custom("black".into())),
      ColorMode::Custom(ref s) => {
          if ! color_modes.contains(s) {
              set_mode.set(ColorMode::Custom("black".into()))
          }
      },
  }
  logging::log!("5");
  let UseCycleListReturn { state, next, .. } = use_cycle_list_with_options(
      vec![
          ColorMode::Custom("rust".into()),
          ColorMode::Custom("coal".into()),
          ColorMode::Custom("navy".into()),
          ColorMode::Custom("ayu".into()),
      ],
      UseCycleListOptions::default().initial_value(None)
      // UseCycleListOptions::default().initial_value(Some((mode, set_mode).into())),
  );
  logging::log!("6");
  let on_click = move |_| next();

  view! {
      <button on:click=on_click>{format!("{}", state.get_untracked())}</button>
  }

It seems to panic on

  let UseColorModeReturn { mode, set_mode, .. } = use_color_mode_with_options(options);

This should work or did I misunderstood something?

Visible item not marked as visible on Chrome

When you are tracking visibility of a item that is visible on page load it is not marked visible. Only when you scroll away and back again to mark it visible.

In Firefox it works but Chrome it does not.

`use_interval` panics on the server

using use_internal or use_interval_fn causes the following panic on the server, even when not using the ticker:

thread 'main' panicked at C:\Users\andre\.cargo\registry\src\index.crates.io-6f17d22bba15001f\wasm-bindgen-0.2.87\src\lib.rs:996:1:
function not implemented on non-wasm32 targets

The full stack trace can be found here: https://pastebin.com/SnhaBWCR

The expected behaviour is that the ticker just does nothing on the server, as stated here: https://leptos-use.rs/animation/use_interval.html

`use_local_storage` Not Storing Values as Expected

Describe the bug

I'm experiencing an issue with use_local_storage. It appears that values are not being stored or retrieved correctly.

Reproduce

  1. cargo leptos new --git https://github.com/leptos-rs/start-axum
  2. Add leptos-use to Cargo.toml
  • leptos-use = {version = "0.9.0", features = ["ssr"]}
  1. Replace app.rs with
use crate::error_template::{AppError, ErrorTemplate};
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use leptos_use::storage::{use_local_storage, StringCodec};

#[component]
pub fn App() -> impl IntoView {
    // Provides context that manages stylesheets, titles, meta tags, etc.
    provide_meta_context();

    view! {
        <Stylesheet id="leptos" href="/pkg/repro.css"/>

        // sets the document title
        <Title text="Welcome to Leptos"/>

        // content for this welcome page
        <Router fallback=|| {
            let mut outside_errors = Errors::default();
            outside_errors.insert_with_default_key(AppError::NotFound);
            view! { <ErrorTemplate outside_errors/> }.into_view()
        }>
            <main>
                <Routes>
                    <Route path="" view=Demo/>
                </Routes>
            </main>
        </Router>
    }
}

#[component]
fn Demo() -> impl IntoView {
    let (state2, set_state2, _) = use_local_storage::<i32, StringCodec>("abc");

    view! {
        <button on:click=move |_| set_state2(state2.get() +1)>"State 2"</button>

        <p>
            "Second " <b>
                <code>"use_storage"</code>
            </b> ":"
        </p>

        <pre>{move || format!("{:#?}", state2.get())}</pre>
    }
}

Expected behavior

I expect the local storage to update with the new value when it's set through the use_local_storage hook.

Actual Behavior

No entry in local storage.
When refresh page, counter reset to zero.

Environment:

Browser: Tried with Firefox and Safari
OS: macOS 14.2.1

Add more methods to `UseDocument` and `UseWindow`

There are several methods which forward the calls, like UseDocument::body. Depending on the method if it already returns an Option<...> type it makes sense to add the postfix .unwrap_or_default() to return always none on the server.

0.5.0-rc1 breaks compilation

error: cannot find macro `error` in this scope
   --> /home/johan/.cargo/git/checkouts/leptos-use-1f72e309245d77d4/fb1ac55/src/use_breakpoints.rs:200:9
    |
200 |         error!("Breakpoint \"{:?}\" not found", key);
    |         ^^^^^
    |
note: `error` is imported here, but it is a module, not a macro
   --> /home/johan/.cargo/git/checkouts/leptos-use-1f72e309245d77d4/fb1ac55/src/use_breakpoints.rs:2:5
    |
2   | use leptos::*;

Support leptos v0.5

Leptos 0.5 removed scope/cx which means I can't pass it to fn's like use_drop_zone_with_options

`use_media_query` not working when SSR is enabled

Describe the bug

use_media_query (and consequently functions like use_preferred_dark) isn't working on the client side when SSR is enabled.

Reproduce

Create a leptos project with SSR enabled.

#[component]
pub fn App() -> impl IntoView {
    provide_meta_context();
    
    let is_dark_preferred = use_preferred_dark();
    create_effect(|_| {
        log::info!("Dark preferred", is_dark_preferred.get());
    });
    view! {
        <Stylesheet id="leptos" href="/pkg/repro.css"/>

        <Title text="Welcome to Leptos"/>
        <main></main>
        
    }
}

This will always log false, no matter what.
If I test media queries with https://mediaqueriestest.com/, and test (prefers-color-scheme: dark), it returns true for my browser.

In conjunction with #62, this makes use_color_mode pretty much unusable unfortunately.

Support IndexedDb storage

Not sure if this is in scope of the project but calling indexeddb without much boilerplate would be nice :)

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.