leptos-use

repository·main·Indexed 19 days ago

https://github.com/synphonyte/leptos-use

A collection of over 90 essential utilities for the Leptos web framework, inspired by React-Use and VueUse, designed to simplify common frontend tasks in Rust. Version 0.19.1.

Tokens
14.4K
Snippets
66
Records
80
Agent score
64%

What's inside leptos-use

  1. What is leptos-use?

    main

    leptos-use is a collection of essential utilities for the Leptos framework, inspired by popular libraries like react-use, vueuse, and solidjs-use. It provides a wide range of composable functions (over 90 available) to simplify common tasks in Leptos applications, such as managing browser APIs, handling signals, and managing side effects.

    Key features include:

    • A large collection of utility functions (90+).
    • Support for Server-Side Rendering (SSR).
    • Designed to work seamlessly with Leptos signals and reactivity.
  2. Browse leptos-use function categories

    main

    The leptos-use library is organized into several functional categories to help you find the right hook for your needs:

    • Storage: Hooks for interacting with localStorage, sessionStorage, and generic storage abstractions.
    • Elements: Hooks for interacting with DOM elements (e.g., size, visibility, bounding boxes, observers).
    • Browser: Hooks for browser-level APIs (e.g., cookies, media queries, clipboard, service workers, color modes).
    • Sensors: Hooks for user input and device state (e.g., mouse position, geolocation, idle detection, scroll, click outside).
    • Network: Hooks for real-time communication (e.g., WebSockets, EventSource).
    • Animation: Hooks for timing and frame-based logic (e.g., intervals, requestAnimationFrame, timeouts).
    • Component: Specialized UI component logic (e.g., calendars).
    • Watch: Utilities for observing changes with specific behaviors (e.g., debounced, throttled, or pausable watching).
    • Reactivity: Tools to enhance Leptos signals (e.g., debounced signals, throttled signals, synchronized signals).
    • Iterable: Utilities for working with collections (e.g., sorted iterables).
    • Utilities: General purpose helpers (e.g., toggles, debouncing functions, signal derivation).
    • Intl: Internationalization helpers (e.g., locale, datetime, and number formatting).
    • Math: Mathematical utility hooks (e.g., absolute value, rounding, logical operations).
  3. Encoding and Decoding Data with Codecs

    main

    Several functions in leptos-use use codecs from the codee crate to encode and decode data for storage or network transmission. Codecs implement the Encoder trait (via the encode method) and the Decoder trait (via the decode method).

    There are two primary categories of codecs:

    1. Binary Codecs: Encode data as Vec<u8>.
    2. String Codecs: Encode data as String.

    If you have a binary codec but need to use it in a context that requires strings (such as cookies), you can use the Base64 adapter to wrap the binary codec and represent the data as a base64 string.

  4. Use the `_with_options` versions of functions

    main

    Many functions in leptos-use provide an alternative version suffixed with _with_options (e.g., use_css_var_with_options). These versions allow you to pass a configuration struct to customize the behavior of the hook beyond its standard arguments.

    To use them:

    1. Identify the _with_options version of the function you need.
    2. Locate the corresponding options struct, which follows a PascalCase naming convention (e.g., use_css_var_with_options uses UseCssVarOptions).
    3. Use the builder pattern to configure only the specific fields you wish to change, starting from Default::default().
    let (color, set_color) = use_css_var_with_options(
        "--color",
        UseCssVarOptions::default()
            .target(el)
            .initial_value("#eee"),
    );
  5. Safely access window and document in SSR

    main

    Functions that rely on browser globals like window() or document() (e.g., use_resize_observer) may fail or behave unexpectedly on the server because these globals do not exist.

    To handle this safely, use the helper functions use_window() and use_document(). These return a new-type-wrapped Option<web_sys::Window> or Option<web_sys::Document> respectively, which are safe to use in SSR environments. Many convenience methods, such as use_document().body(), are provided and will gracefully propagate None when running on the server.

    Refer to the specific documentation for a function to see if it has a dedicated "Server-Side Rendering" section; if it doesn't, the function behaves identically on both client and server.

    use leptos::prelude::*;
    use leptos::ev::keyup;
    use leptos_use::{use_event_listener, use_window};
    
    use_event_listener(use_window(), keyup, | evt| {
        // ...
    });
  6. Setup the environment for use_webtransport example

    main

    To run the use_webtransport example, you need to install Trunk, Tailwind CSS, and the Rust nightly toolchain with the wasm32-unknown-unknown target.

    Follow these steps:

    1. Install dependencies:

      • Install trunk via cargo.
      • Install tailwindcss and @tailwindcss/forms via npm.
      • Install the Rust nightly toolchain and the wasm32-unknown-unknown target via rustup.
    2. Run the development servers:

      • Open a terminal and start the Tailwind CSS watcher to compile styles.
      • Open a second terminal and start the Trunk development server.
    # Install dependencies
    cargo install trunk
    npm install -D tailwindcss @tailwindcss/forms
    rustup toolchain install nightly
    rustup target add wasm32-unknown-unknown
    
    # Terminal 1: Watch Tailwind CSS
    npx tailwindcss -i ./input.css -o ./style/output.css --watch
    
    # Terminal 2: Serve the application
    trunk serve --open
  7. Run the watch_debounced example

    main

    After setting up the environment, you must run two processes simultaneously in separate terminals to handle CSS compilation and the WASM development server.

    1. Terminal 1: Start the Tailwind CSS watcher to compile styles.
    2. Terminal 2: Start the Trunk development server to serve the application.

    Execution Steps

    In Terminal 1:

    npx tailwindcss -i ./input.css -o ./style/output.css --watch

    In Terminal 2:

    trunk serve --open
    npx tailwindcss -i ./input.css -o ./style/output.css --watch
    trunk serve --open
  8. Run the use_web_lock example

    main

    The example requires two concurrent processes: one to watch and compile Tailwind CSS styles, and another to serve the Leptos application via Trunk.

    1. Start the Tailwind CSS watcher in one terminal: npx tailwindcss -i ./input.css -o ./style/output.css --watch

    2. Start the Trunk development server in a second terminal: trunk serve --open

    npx tailwindcss -i ./input.css -o ./style/output.css --watch
    
    trunk serve --open
  9. Setup the environment for use_raf_fn examples

    main

    To run the use_raf_fn example, you need to install the Rust nightly toolchain, the wasm32-unknown-unknown target, Trunk for development serving, and Tailwind CSS for styling.

    Prerequisites

    Install the necessary system tools:

    # Install Trunk for WASM development
    cargo install trunk
    
    # Install Tailwind CSS and its forms plugin
    npm install -D tailwindcss @tailwindcss/forms
    
    # Install Rust nightly toolchain and the WASM target
    rustup toolchain install nightly
    rustup target add wasm32-unknown-unknown
    cargo install trunk
    npm install -D tailwindcss @tailwindcss/forms
    rustup toolchain install nightly
    rustup target add wasm32-unknown-unknown
  10. Run the use_throttle_fn demo

    main

    To run the use_throttle_fn example, you must first ensure you have the Rust nightly toolchain and the wasm32-unknown-unknown target installed, along with the trunk build tool. Once the environment is set up, use trunk serve --open to compile the project and launch the demo in your browser.

    # Install dependencies
    cargo install trunk
    rustup toolchain install nightly
    rustup target add wasm32-unknown-unknown
    
    # Run the demo
    trunk serve --open
  11. Implement Custom Codecs

    main

    If existing codecs do not meet your requirements, you can implement your own by following these patterns:

    • For String Codecs: Refer to the implementation of JsonSerdeCodec in the codee crate.
    • For Binary Codecs: Refer to the implementation of BincodeSerdeCodec in the codee crate.