Merge branch 'main' into leptos-0.7

# Conflicts:
#	examples/use_broadcast_channel/src/main.rs
#	src/storage/use_storage.rs
This commit is contained in:
Maccesch 2024-07-27 22:22:06 +01:00
commit 904582f33d
50 changed files with 335 additions and 226 deletions

View file

@ -1,3 +1,3 @@
[unstable] [build]
rustflags = ["--cfg=web_sys_unstable_apis"] rustflags = ["--cfg=web_sys_unstable_apis"]
rustdocflags = ["--cfg=web_sys_unstable_apis"] rustdocflags = ["--cfg=web_sys_unstable_apis"]

82
.github/workflows/cd.yml vendored Normal file
View file

@ -0,0 +1,82 @@
on:
push:
# Pattern matched against refs/tags
tags:
- '*' # Push events to every tag not containing /
workflow_dispatch:
name: CD
permissions: write-all
jobs:
publish:
name: Publish
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
toolchain: nightly
profile: minimal
override: true
components: rustfmt, clippy, rust-src
- name: Cache
uses: Swatinem/rust-cache@v2
- name: Check function count badge
run: python3 docs/generate_count_badge.py --check
- name: Check version in docs
run: python3 docs/add_version_to_docs.py --check
- name: Check formatting
run: cargo fmt --check
- name: Clippy
run: cargo clippy --features docs,math --tests -- -D warnings
- name: Run tests (general)
run: cargo test --features math,docs,ssr
- name: Run tests (axum)
run: cargo test --features math,docs,ssr,axum --doc use_cookie::use_cookie
- name: Run tests (actix)
run: cargo test --features math,docs,ssr,actix --doc use_cookie::use_cookie
#### mdbook
- name: Install mdbook I
uses: taiki-e/install-action@v2
with:
tool: cargo-binstall,mdbook
- name: Install mdbook II
run: |
cargo binstall -y mdbook-cmdrun
cargo binstall -y trunk@0.17.5
rustup target add wasm32-unknown-unknown
- name: Setup Pages
id: pages
uses: actions/configure-pages@v3
- name: Build mdbook # TODO : run mdbook tests
run: |
cd docs/book
mdbook build
python3 post_build.py
- name: Upload artifact
uses: actions/upload-pages-artifact@v1
with:
path: ./docs/book/book
- name: Deploy book to github pages
id: deployment
uses: actions/deploy-pages@v2
##### mdbook end
- name: Publish crate leptos-use
uses: katyo/publish-crates@v2
with:
registry-token: ${{ secrets.CRATES_TOKEN }}
- uses: CSchoel/release-notes-from-changelog@v1
- name: Create Release using GitHub CLI
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: >
gh release create
-d
-F RELEASE.md
-t "Version $RELEASE_VERSION"
${GITHUB_REF#refs/*/}

View file

@ -1,82 +1,48 @@
name: Continuous Integration
on: on:
push: pull_request:
# Pattern matched against refs/tags branches:
tags: - main
- '*' # Push events to every tag not containing / paths:
workflow_dispatch: - "**"
- "!/*.md"
- "!/**.md"
name: CI concurrency:
group: "${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}"
permissions: write-all cancel-in-progress: true
jobs: jobs:
publish: integrity:
name: Publish name: Integrity Checks on Rust ${{ matrix.toolchain }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
matrix:
toolchain:
- stable
- nightly
steps: steps:
- uses: actions/checkout@v3 - name: Checkout
- uses: actions-rs/toolchain@v1 uses: actions/checkout@v4
- name: Setup Rust
uses: dtolnay/rust-toolchain@master
with: with:
toolchain: nightly toolchain: ${{ matrix.toolchain }}
profile: minimal targets: wasm32-unknown-unknown
override: true components: clippy, rustfmt
components: rustfmt, clippy, rust-src
- name: Cache - name: Setup Rust Cache
uses: Swatinem/rust-cache@v2 uses: Swatinem/rust-cache@v2
- name: Check function count badge
run: python3 docs/generate_count_badge.py --check - name: Build
- name: Check version in docs run: cargo build
run: python3 docs/add_version_to_docs.py --check
- name: Check formatting - name: Format
run: cargo fmt --check run: cargo fmt --check
- name: Clippy - name: Clippy
run: cargo clippy --features docs,math --tests -- -D warnings run: cargo clippy -- -D warnings
- name: Run tests (general)
run: cargo test --features math,docs,ssr
- name: Run tests (axum)
run: cargo test --features math,docs,ssr,axum --doc use_cookie::use_cookie
- name: Run tests (actix)
run: cargo test --features math,docs,ssr,actix --doc use_cookie::use_cookie
#### mdbook
- name: Install mdbook I
uses: taiki-e/install-action@v2
with:
tool: cargo-binstall,mdbook
- name: Install mdbook II
run: |
cargo binstall -y mdbook-cmdrun
cargo binstall -y trunk@0.17.5
rustup target add wasm32-unknown-unknown
- name: Setup Pages
id: pages
uses: actions/configure-pages@v3
- name: Build mdbook # TODO : run mdbook tests
run: |
cd docs/book
mdbook build
python3 post_build.py
- name: Upload artifact
uses: actions/upload-pages-artifact@v1
with:
path: ./docs/book/book
- name: Deploy book to github pages
id: deployment
uses: actions/deploy-pages@v2
##### mdbook end
- name: Publish crate leptos-use
uses: katyo/publish-crates@v2
with:
registry-token: ${{ secrets.CRATES_TOKEN }}
- uses: CSchoel/release-notes-from-changelog@v1
- name: Create Release using GitHub CLI
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: >
gh release create
-d
-F RELEASE.md
-t "Version $RELEASE_VERSION"
${GITHUB_REF#refs/*/}

1
.idea/leptos-use.iml generated
View file

@ -77,6 +77,7 @@
<sourceFolder url="file://$MODULE_DIR$/examples/use_or/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/examples/use_or/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/examples/use_event_source/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/examples/use_event_source/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/examples/sync_signal/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/examples/sync_signal/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/examples/use_user_media/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/examples/use_event_listener/target" /> <excludeFolder url="file://$MODULE_DIR$/examples/use_event_listener/target" />
<excludeFolder url="file://$MODULE_DIR$/target" /> <excludeFolder url="file://$MODULE_DIR$/target" />
<excludeFolder url="file://$MODULE_DIR$/docs/book/book" /> <excludeFolder url="file://$MODULE_DIR$/docs/book/book" />

View file

@ -3,7 +3,7 @@
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] ## [0.11.0] - 2024-07-27
### Breaking Changes 🛠 ### Breaking Changes 🛠
@ -50,8 +50,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `JsonCodec` has been renamed to `JsonSerdeCodec`. - `JsonCodec` has been renamed to `JsonSerdeCodec`.
- The feature to enable this codec is now called `json_serde` instead of just `serde`. - The feature to enable this codec is now called `json_serde` instead of just `serde`.
- `ProstCodec` now encodes as binary data. If you want to keep using it with string data you can wrap it like - `ProstCodec` now encodes as binary data. If you want to keep using it with string data you can wrap it like
this: `Base64<ProstCodec>`. You have to enable both features `prost` and `base64` for this. this: `Base64<ProstCodec>`.
- All of these structs, traits and features now live in their own crate called `codee` - All of these structs, traits and features now live in their own crate called `codee`
- A bunch of new codecs are available. Have a look at the docs for crate `codee`.
- `use_websocket`: - `use_websocket`:
- `UseWebsocketOptions` has been renamed to `UseWebSocketOptions` (uppercase S) to be consistent with the return - `UseWebsocketOptions` has been renamed to `UseWebSocketOptions` (uppercase S) to be consistent with the return
type. type.
@ -71,11 +72,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The new `UseWebSocketOptions::on_message` takes a `&T`. - The new `UseWebSocketOptions::on_message` takes a `&T`.
- `UseWebSocketOptions::on_error` now takes a `UseWebSocketError` instead of a `web_sys::Event`. - `UseWebSocketOptions::on_error` now takes a `UseWebSocketError` instead of a `web_sys::Event`.
- `use_storage` now always saves the default value to storage if the key doesn't exist yet. - `use_storage` now always saves the default value to storage if the key doesn't exist yet.
- Renamed `BreakpointsSematic` to `BreakpointsSemantic` and `breakpoints_sematic` to `breakpoints_semantic`
(note the `n`) (thanks to @mondeja).
### Fixes 🍕 ### Fixes 🍕
- Fixed auto-reconnect in `use_websocket` - Fixed auto-reconnect in `use_websocket`
- Fixed typo in compiler error messages in `use_cookie` (thanks to @SleeplessOne1917). - Fixed typo in compiler error messages in `use_cookie` (thanks to @SleeplessOne1917).
- Fixed potential signal out of scope issue with `use_raf_fn`
### Other Changes 🔥
- Better links in docs that work both in the book and in rustdoc (thanks to @mondeja).
- Better CI/CD (thanks to @EstebanBorai).
## [0.10.10] - 2024-05-10 ## [0.10.10] - 2024-05-10

View file

@ -1,6 +1,6 @@
[package] [package]
name = "leptos-use" name = "leptos-use"
version = "0.10.10" version = "0.11.0"
edition = "2021" edition = "2021"
authors = ["Marc-Stefan Cassola"] authors = ["Marc-Stefan Cassola"]
categories = ["gui", "web-programming"] categories = ["gui", "web-programming"]

View file

@ -13,7 +13,7 @@
<a href="https://crates.io/crates/leptos-use"><img src="https://img.shields.io/crates/v/leptos-use.svg?label=&color=%232C1275" alt="Crates.io"/></a> <a href="https://crates.io/crates/leptos-use"><img src="https://img.shields.io/crates/v/leptos-use.svg?label=&color=%232C1275" alt="Crates.io"/></a>
<a href="https://leptos-use.rs/server_side_rendering.html"><img src="https://img.shields.io/badge/-SSR-%236a214b" alt="SSR"></a> <a href="https://leptos-use.rs/server_side_rendering.html"><img src="https://img.shields.io/badge/-SSR-%236a214b" alt="SSR"></a>
<a href="https://leptos-use.rs"><img src="https://img.shields.io/badge/-docs%20%26%20demos-%239A233F" alt="Docs & Demos"></a> <a href="https://leptos-use.rs"><img src="https://img.shields.io/badge/-docs%20%26%20demos-%239A233F" alt="Docs & Demos"></a>
<a href="https://leptos-use.rs"><img src="https://img.shields.io/badge/-77%20functions-%23EF3939" alt="77 Functions" /></a> <a href="https://leptos-use.rs"><img src="https://img.shields.io/badge/-79%20functions-%23EF3939" alt="79 Functions" /></a>
</p> </p>
<br/> <br/>
@ -24,7 +24,7 @@
[![Docs](https://docs.rs/leptos-use/badge.svg)](https://docs.rs/leptos-use/) [![Docs](https://docs.rs/leptos-use/badge.svg)](https://docs.rs/leptos-use/)
[![MIT/Apache 2.0](https://img.shields.io/badge/license-MIT%2FApache-blue.svg)](https://github.com/synphonyte/leptos-use#license) [![MIT/Apache 2.0](https://img.shields.io/badge/license-MIT%2FApache-blue.svg)](https://github.com/synphonyte/leptos-use#license)
[![Build Status](https://github.com/synphonyte/leptos-use/actions/workflows/ci.yml/badge.svg)](https://github.com/synphonyte/leptos-use/actions/workflows/ci.yml) [![Build Status](https://github.com/synphonyte/leptos-use/actions/workflows/cd.yml/badge.svg)](https://github.com/synphonyte/leptos-use/actions/workflows/cd.yml)
[![Discord](https://img.shields.io/discord/1031524867910148188?color=%237289DA&label=discord)](https://discord.com/channels/1031524867910148188/1121154537709895783) [![Discord](https://img.shields.io/discord/1031524867910148188?color=%237289DA&label=discord)](https://discord.com/channels/1031524867910148188/1121154537709895783)
```rust ```rust
@ -92,4 +92,4 @@ This will create the function file in the src directory, scaffold an example dir
| <= 0.3 | 0.3 | | <= 0.3 | 0.3 |
| 0.4, 0.5, 0.6 | 0.4 | | 0.4, 0.5, 0.6 | 0.4 |
| 0.7, 0.8, 0.9 | 0.5 | | 0.7, 0.8, 0.9 | 0.5 |
| 0.10 | 0.6 | | 0.10, 0.11 | 0.6 |

View file

@ -13,7 +13,8 @@ def main():
if os.path.isdir(category_dir): if os.path.isdir(category_dir):
for file in os.listdir(category_dir): for file in os.listdir(category_dir):
if file.endswith(".md") and (len(sys.argv) == 1 or (sys.argv[1] in file)): if file.endswith(".md") and (len(sys.argv) == 1 or (sys.argv[1] in file)):
build_and_copy_demo(category, file) if build_and_copy_demo(category, file):
rewrite_links(category, file)
def build_and_copy_demo(category, md_name): def build_and_copy_demo(category, md_name):
@ -24,7 +25,8 @@ def build_and_copy_demo(category, md_name):
code = p.wait() code = p.wait()
if code != 0: if code != 0:
sys.exit(code, f"failed to build example '{name}'") sys.stderr.write(f"failed to build example '{name}'\n")
sys.exit(code)
example_output_path = os.path.join(example_dir, "dist") example_output_path = os.path.join(example_dir, "dist")
target_path = os.path.join("book", category, name, "demo") target_path = os.path.join("book", category, name, "demo")
@ -60,6 +62,32 @@ def build_and_copy_demo(category, md_name):
</body> </body>
{body_split[1]}""") {body_split[1]}""")
return True
return False
def rewrite_links(category, md_name):
"""Rewrite links in generated documentation to make them
compatible between rustdoc and the book.
"""
html_name = f"{md_name[:-3]}.html"
target_path = os.path.join("book", category, html_name)
with open(target_path, "r") as f:
html = f.read()
html = html.replace(
"fn@crate::", "",
).replace(
"crate::", "",
).replace(
"fn@", "",
)
with open(target_path, "w") as f:
f.write(html)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -12,6 +12,6 @@
<a href="https://crates.io/crates/leptos-use"><img src="https://img.shields.io/crates/v/leptos-use.svg?label=&color=%232C1275" alt="Crates.io"/></a> <a href="https://crates.io/crates/leptos-use"><img src="https://img.shields.io/crates/v/leptos-use.svg?label=&color=%232C1275" alt="Crates.io"/></a>
<a href="https://leptos-use.rs/server_side_rendering.html"><img src="https://img.shields.io/badge/-SSR-%236a214b" alt="SSR"></a> <a href="https://leptos-use.rs/server_side_rendering.html"><img src="https://img.shields.io/badge/-SSR-%236a214b" alt="SSR"></a>
<a href="./get_started.html"><img src="https://img.shields.io/badge/-docs%20%26%20demos-%239A233F" alt="Docs & Demos"></a> <a href="./get_started.html"><img src="https://img.shields.io/badge/-docs%20%26%20demos-%239A233F" alt="Docs & Demos"></a>
<a href="./functions.html"><img src="https://img.shields.io/badge/-77%20functions-%23EF3939" alt="77 Functions" /></a> <a href="./functions.html"><img src="https://img.shields.io/badge/-79%20functions-%23EF3939" alt="79 Functions" /></a>
</p> </p>
</div> </div>

View file

@ -8,6 +8,7 @@ crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
axum = { version = "0.7", optional = true } axum = { version = "0.7", optional = true }
codee = "0.1"
console_error_panic_hook = "0.1" console_error_panic_hook = "0.1"
console_log = "1" console_log = "1"
cfg-if = "1" cfg-if = "1"

View file

@ -4,7 +4,7 @@ use leptos::prelude::*;
use leptos_meta::*; use leptos_meta::*;
use leptos_router::*; use leptos_router::*;
use leptos_use::storage::{use_local_storage, use_local_storage_with_options, UseStorageOptions}; use leptos_use::storage::{use_local_storage, use_local_storage_with_options, UseStorageOptions};
use leptos_use::utils::FromToStringCodec; use codee::string::FromToStringCodec;
use leptos_use::{ use leptos_use::{
use_color_mode_with_options, use_cookie_with_options, use_debounce_fn, use_event_listener, use_color_mode_with_options, use_cookie_with_options, use_debounce_fn, use_event_listener,
use_interval, use_intl_number_format, use_preferred_dark, use_timestamp, use_window, ColorMode, use_interval, use_intl_number_format, use_preferred_dark, use_timestamp, use_window, ColorMode,
@ -78,7 +78,7 @@ fn HomePage() -> impl IntoView {
let (test_cookie, _) = use_cookie_with_options::<String, FromToStringCodec>( let (test_cookie, _) = use_cookie_with_options::<String, FromToStringCodec>(
"test-cookie", "test-cookie",
UseCookieOptions::<String, _>::default() UseCookieOptions::<String, _, _>::default()
.max_age(3000) .max_age(3000)
.default_value(Some("Bogus string".to_owned())), .default_value(Some("Bogus string".to_owned())),
); );

View file

@ -5,6 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
leptos = { version = "0.6", features = ["nightly", "csr"] } leptos = { version = "0.6", features = ["nightly", "csr"] }
codee = "0.1"
console_error_panic_hook = "0.1" console_error_panic_hook = "0.1"
console_log = "1" console_log = "1"
log = "0.4" log = "0.4"

View file

@ -1,6 +1,6 @@
use codee::string::FromToStringCodec;
use leptos::prelude::*; use leptos::prelude::*;
use leptos_use::docs::demo_or_body; use leptos_use::docs::demo_or_body;
use leptos_use::utils::FromToStringCodec;
use leptos_use::{use_broadcast_channel, UseBroadcastChannelReturn}; use leptos_use::{use_broadcast_channel, UseBroadcastChannelReturn};
#[component] #[component]
@ -46,8 +46,8 @@ fn Demo() -> impl IntoView {
<p>"Received message: " {move || message().as_ref().unwrap().to_string()}</p> <p>"Received message: " {move || message().as_ref().unwrap().to_string()}</p>
</Show> </Show>
<Show when=move || error().is_some()> <Show when=move || error.with(|e| e.is_some())>
<p>"Error: " {move || format!("{:?}", error().as_ref().unwrap())}</p> <p>"Error: " {move || error.with(|e| format!("{:?}", e.as_ref().unwrap()))}</p>
</Show> </Show>
</Show> </Show>
} }

View file

@ -1,6 +1,8 @@
use leptos::prelude::*; use leptos::prelude::*;
use leptos_use::docs::{demo_or_body, Note}; use leptos_use::docs::{demo_or_body, Note};
use leptos_use::{use_clipboard, use_permission, UseClipboardReturn}; use leptos_use::{
use_clipboard_with_options, use_permission, UseClipboardOptions, UseClipboardReturn,
};
#[component] #[component]
fn Demo() -> impl IntoView { fn Demo() -> impl IntoView {
@ -11,7 +13,7 @@ fn Demo() -> impl IntoView {
text, text,
copied, copied,
copy, copy,
} = use_clipboard(); } = use_clipboard_with_options(UseClipboardOptions::default().read(true));
let permission_read = use_permission("clipboard-read"); let permission_read = use_permission("clipboard-read");
let permission_write = use_permission("clipboard-write"); let permission_write = use_permission("clipboard-write");

View file

@ -5,6 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
leptos = { version = "0.6", features = ["nightly", "csr"] } leptos = { version = "0.6", features = ["nightly", "csr"] }
codee = "0.1"
console_error_panic_hook = "0.1" console_error_panic_hook = "0.1"
console_log = "1" console_log = "1"
log = "0.4" log = "0.4"

View file

@ -1,7 +1,7 @@
use leptos::prelude::*; use leptos::prelude::*;
use leptos_use::docs::demo_or_body; use leptos_use::docs::demo_or_body;
use leptos_use::use_cookie; use leptos_use::use_cookie;
use leptos_use::utils::FromToStringCodec; use codee::string::FromToStringCodec;
use rand::prelude::*; use rand::prelude::*;
#[component] #[component]

View file

@ -4,14 +4,14 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
codee = { path = "../../../codee", features = ["json_serde"] } codee = { version = "0.1", features = ["json_serde"] }
leptos = { version = "0.6", features = ["nightly", "csr"] }
console_error_panic_hook = "0.1" console_error_panic_hook = "0.1"
console_log = "1" console_log = "1"
log = "0.4" leptos = { version = "0.6", features = ["nightly", "csr"] }
leptos-use = { path = "../..", features = ["docs"] } leptos-use = { path = "../..", features = ["docs"] }
web-sys = "0.3" log = "0.4"
serde = "1.0.163" serde = "1.0.163"
web-sys = "0.3"
[dev-dependencies] [dev-dependencies]
wasm-bindgen = "0.2" wasm-bindgen = "0.2"

View file

@ -1,7 +1,7 @@
use leptos::prelude::*; use leptos::prelude::*;
use leptos_use::docs::{demo_or_body, Note}; use leptos_use::docs::{demo_or_body, Note};
use leptos_use::storage::use_local_storage; use leptos_use::storage::use_local_storage;
use leptos_use::utils::JsonCodec; use codee::string::JsonSerdeCodec;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
@ -25,8 +25,8 @@ impl Default for BananaState {
#[component] #[component]
fn Demo() -> impl IntoView { fn Demo() -> impl IntoView {
let (state, set_state, reset) = use_local_storage::<BananaState, JsonCodec>("banana-state"); let (state, set_state, reset) = use_local_storage::<BananaState, JsonSerdeCodec>("banana-state");
let (state2, _, _) = use_local_storage::<BananaState, JsonCodec>("banana-state"); let (state2, _, _) = use_local_storage::<BananaState, JsonSerdeCodec>("banana-state");
view! { view! {
<input <input

View file

@ -5,7 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
leptos = { version = "0.6", features = ["nightly", "csr"] } leptos = { version = "0.6", features = ["nightly", "csr"] }
codee = { path = "../../../codee", features = ["msgpack_serde"] } codee = { version = "0.1", features = ["msgpack_serde"] }
console_error_panic_hook = "0.1" console_error_panic_hook = "0.1"
console_log = "1" console_log = "1"
log = "0.4" log = "0.4"

View file

@ -7,12 +7,14 @@ use std::marker::PhantomData;
use std::ops::Deref; use std::ops::Deref;
/// Used as an argument type to make it easily possible to pass either /// Used as an argument type to make it easily possible to pass either
///
/// * a `web_sys` element that implements `E` (for example `EventTarget`, `Element` or `HtmlElement`), /// * a `web_sys` element that implements `E` (for example `EventTarget`, `Element` or `HtmlElement`),
/// * an `Option<T>` where `T` is the web_sys element, /// * an `Option<T>` where `T` is the web_sys element,
/// * a `Signal<T>` where `T` is the web_sys element, /// * a `Signal<T>` where `T` is the web_sys element,
/// * a `Signal<Option<T>>` where `T` is the web_sys element, /// * a `Signal<Option<T>>` where `T` is the web_sys element,
/// * a `NodeRef` /// * a `NodeRef`
/// into a function. Used for example in [`use_event_listener`]. ///
/// into a function. Used for example in [`fn@crate::use_event_listener`].
pub enum ElementMaybeSignal<T, E> pub enum ElementMaybeSignal<T, E>
where where
T: Into<E> + Clone + 'static, T: Into<E> + Clone + 'static,

View file

@ -8,12 +8,14 @@ use std::marker::PhantomData;
use std::ops::Deref; use std::ops::Deref;
/// Used as an argument type to make it easily possible to pass either /// Used as an argument type to make it easily possible to pass either
///
/// * a `web_sys` element that implements `E` (for example `EventTarget` or `Element`), /// * a `web_sys` element that implements `E` (for example `EventTarget` or `Element`),
/// * an `Option<T>` where `T` is the web_sys element, /// * an `Option<T>` where `T` is the web_sys element,
/// * a `Signal<T>` where `T` is the web_sys element, /// * a `Signal<T>` where `T` is the web_sys element,
/// * a `Signal<Option<T>>` where `T` is the web_sys element, /// * a `Signal<Option<T>>` where `T` is the web_sys element,
/// * a `NodeRef` /// * a `NodeRef`
/// into a function. Used for example in [`use_event_listener`]. ///
/// into a function. Used for example in [`fn@crate::use_event_listener`].
pub enum ElementsMaybeSignal<T, E> pub enum ElementsMaybeSignal<T, E>
where where
T: Into<E> + Clone + 'static, T: Into<E> + Clone + 'static,

View file

@ -25,7 +25,6 @@ mod is_none;
mod is_ok; mod is_ok;
mod is_some; mod is_some;
mod on_click_outside; mod on_click_outside;
mod use_user_media;
mod signal_debounced; mod signal_debounced;
mod signal_throttled; mod signal_throttled;
mod sync_signal; mod sync_signal;
@ -75,6 +74,7 @@ mod use_throttle_fn;
mod use_timeout_fn; mod use_timeout_fn;
mod use_timestamp; mod use_timestamp;
mod use_to_string; mod use_to_string;
mod use_user_media;
mod use_web_notification; mod use_web_notification;
mod use_websocket; mod use_websocket;
mod use_window; mod use_window;
@ -91,7 +91,6 @@ pub use is_none::*;
pub use is_ok::*; pub use is_ok::*;
pub use is_some::*; pub use is_some::*;
pub use on_click_outside::*; pub use on_click_outside::*;
pub use use_user_media::*;
pub use signal_debounced::*; pub use signal_debounced::*;
pub use signal_throttled::*; pub use signal_throttled::*;
pub use sync_signal::*; pub use sync_signal::*;
@ -141,6 +140,7 @@ pub use use_throttle_fn::*;
pub use use_timeout_fn::*; pub use use_timeout_fn::*;
pub use use_timestamp::*; pub use use_timestamp::*;
pub use use_to_string::*; pub use use_to_string::*;
pub use use_user_media::*;
pub use use_web_notification::*; pub use use_web_notification::*;
pub use use_websocket::*; pub use use_websocket::*;
pub use use_window::*; pub use use_window::*;

View file

@ -45,9 +45,9 @@ cfg_if! { if #[cfg(not(feature = "ssr"))] {
/// ``` /// ```
/// ///
/// > This function uses [Event.composedPath()](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath) /// > This function uses [Event.composedPath()](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath)
/// which is **not** supported by IE 11, Edge 18 and below. /// > which is **not** supported by IE 11, Edge 18 and below.
/// If you are targeting these browsers, we recommend you to include /// > If you are targeting these browsers, we recommend you to include
/// [this code snippet](https://gist.github.com/sibbng/13e83b1dd1b733317ce0130ef07d4efd) on your project. /// > [this code snippet](https://gist.github.com/sibbng/13e83b1dd1b733317ce0130ef07d4efd) on your project.
/// ///
/// ## Excluding Elements /// ## Excluding Elements
/// ///

View file

@ -3,14 +3,19 @@ use codee::{Decoder, Encoder};
use leptos::prelude::wrappers::read::Signal; use leptos::prelude::wrappers::read::Signal;
use leptos::prelude::*; use leptos::prelude::*;
#[allow(rustdoc::bare_urls)]
/// Reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). /// Reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
/// ///
/// LocalStorage stores data in the browser with no expiration time. Access is given to all pages from the same origin (e.g., all pages from "https://example.com" share the same origin). While data doesn't expire the user can view, modify and delete all data stored. Browsers allow 5MB of data to be stored. /// LocalStorage stores data in the browser with no expiration time. Access is given to all pages
/// from the same origin (e.g., all pages from "https://example.com" share the same origin).
/// While data doesn't expire the user can view, modify and delete all data stored.
/// Browsers allow 5MB of data to be stored.
/// ///
/// This is contrast to [`use_session_storage`] which clears data when the page session ends and is not shared. /// This is contrast to [`fn@crate::storage::use_session_storage`] which clears data when the page session ends and is not shared.
/// ///
/// ## Usage /// ## Usage
/// See [`use_storage`] for more details on how to use. ///
/// See [`fn@crate::storage::use_storage`] for more details on how to use.
pub fn use_local_storage<T, C>( pub fn use_local_storage<T, C>(
key: impl AsRef<str>, key: impl AsRef<str>,
) -> (Signal<T>, WriteSignal<T>, impl Fn() + Clone) ) -> (Signal<T>, WriteSignal<T>, impl Fn() + Clone)

View file

@ -6,10 +6,10 @@ use leptos::prelude::*;
/// ///
/// SessionStorages stores data in the browser that is deleted when the page session ends. A page session ends when the browser closes the tab. Data is not shared between pages. While data doesn't expire the user can view, modify and delete all data stored. Browsers allow 5MB of data to be stored. /// SessionStorages stores data in the browser that is deleted when the page session ends. A page session ends when the browser closes the tab. Data is not shared between pages. While data doesn't expire the user can view, modify and delete all data stored. Browsers allow 5MB of data to be stored.
/// ///
/// Use [`use_local_storage`] to store data that is shared amongst all pages with the same origin and persists between page sessions. /// Use [`fn@crate::storage::use_local_storage`] to store data that is shared amongst all pages with the same origin and persists between page sessions.
/// ///
/// ## Usage /// ## Usage
/// See [`use_storage`] for more details on how to use. /// See [`fn@crate::storage::use_storage`] for more details on how to use.
pub fn use_session_storage<T, C>( pub fn use_session_storage<T, C>(
key: impl AsRef<str>, key: impl AsRef<str>,
) -> (Signal<T>, WriteSignal<T>, impl Fn() + Clone) ) -> (Signal<T>, WriteSignal<T>, impl Fn() + Clone)

View file

@ -24,15 +24,15 @@ const INTERNAL_STORAGE_EVENT: &str = "leptos-use-storage";
/// ///
/// Pass a [`StorageType`] to determine the kind of key-value browser storage to use. /// Pass a [`StorageType`] to determine the kind of key-value browser storage to use.
/// The specified key is where data is stored. All values are stored as UTF-16 strings which /// The specified key is where data is stored. All values are stored as UTF-16 strings which
/// is then encoded and decoded via the given [`Codec`]. This value is synced with other calls using /// is then encoded and decoded via the given `*Codec`. This value is synced with other calls using
/// the same key on the smae page and across tabs for local storage. /// the same key on the same page and across tabs for local storage.
/// See [`UseStorageOptions`] to see how behavior can be further customised. /// See [`UseStorageOptions`] to see how behavior can be further customised.
/// ///
/// Values are (en)decoded via the given codec. You can use any of the string codecs or a /// Values are (en)decoded via the given codec. You can use any of the string codecs or a
/// binary codec wrapped in [`Base64`]. /// binary codec wrapped in `Base64`.
/// ///
/// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are /// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are
/// available and what feature flags they require. /// > available and what feature flags they require.
/// ///
/// ## Example /// ## Example
/// ///
@ -277,7 +277,10 @@ where
let notify = Trigger::new(); let notify = Trigger::new();
// Refetch from storage. Keeps track of how many times we've been notified. Does not increment for calls to set_data // Refetch from storage. Keeps track of how many times we've been notified. Does not increment for calls to set_data
let notify_id = Memo::<usize>::new(move |prev| { let notify_id = Memo::<usize>::new({
let fetch_from_storage = fetch_from_storage.clone();
move |prev| {
notify.track(); notify.track();
match prev { match prev {
None => 1, // Avoid async fetch of initial value None => 1, // Avoid async fetch of initial value
@ -286,6 +289,7 @@ where
prev + 1 prev + 1
} }
} }
}
}); });
// Set item on internal (non-event) page changes to the data signal // Set item on internal (non-event) page changes to the data signal
@ -392,7 +396,7 @@ pub enum UseStorageError<E, D> {
ItemCodecError(CodecError<E, D>), ItemCodecError(CodecError<E, D>),
} }
/// Options for use with [`use_local_storage_with_options`], [`use_session_storage_with_options`] and [`use_storage_with_options`]. /// Options for use with [`fn@crate::storage::use_local_storage_with_options`], [`fn@crate::storage::use_session_storage_with_options`] and [`use_storage_with_options`].
#[derive(DefaultBuilder)] #[derive(DefaultBuilder)]
pub struct UseStorageOptions<T, E, D> pub struct UseStorageOptions<T, E, D>
where where

View file

@ -38,6 +38,7 @@ use std::hash::Hash;
/// ## Breakpoints /// ## Breakpoints
/// ///
/// There are many predefined breakpoints for major UI frameworks. The following are provided. /// There are many predefined breakpoints for major UI frameworks. The following are provided.
///
/// * [`breakpoints_tailwind`] /// * [`breakpoints_tailwind`]
/// * [`breakpoints_bootstrap_v5`] /// * [`breakpoints_bootstrap_v5`]
/// * [`breakpoints_material`] /// * [`breakpoints_material`]
@ -108,7 +109,7 @@ use std::hash::Hash;
/// ///
/// ## Server-Side Rendering /// ## Server-Side Rendering
/// ///
/// Since internally this uses [`use_media_query`], which returns always `false` on the server, /// Since internally this uses [`fn@crate::use_media_query`], which returns always `false` on the server,
/// the returned methods also will return `false`. /// the returned methods also will return `false`.
pub fn use_breakpoints<K: Eq + Hash + Debug + Clone>( pub fn use_breakpoints<K: Eq + Hash + Debug + Clone>(
breakpoints: HashMap<K, u32>, breakpoints: HashMap<K, u32>,
@ -277,7 +278,7 @@ impl<K: Eq + Hash + Debug + Clone> UseBreakpointsReturn<K> {
/// Breakpoint keys for Tailwind V2 /// Breakpoint keys for Tailwind V2
/// ///
/// See [https://tailwindcss.com/docs/breakpoints] /// See <https://tailwindcss.com/docs/breakpoints>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsTailwind { pub enum BreakpointsTailwind {
Sm, Sm,
@ -289,7 +290,7 @@ pub enum BreakpointsTailwind {
/// Breakpoint definitions for Tailwind V2 /// Breakpoint definitions for Tailwind V2
/// ///
/// See [https://tailwindcss.com/docs/breakpoints] /// See <https://tailwindcss.com/docs/breakpoints>
pub fn breakpoints_tailwind() -> HashMap<BreakpointsTailwind, u32> { pub fn breakpoints_tailwind() -> HashMap<BreakpointsTailwind, u32> {
HashMap::from([ HashMap::from([
(BreakpointsTailwind::Sm, 640), (BreakpointsTailwind::Sm, 640),
@ -302,7 +303,7 @@ pub fn breakpoints_tailwind() -> HashMap<BreakpointsTailwind, u32> {
/// Breakpoint keys for Bootstrap V5 /// Breakpoint keys for Bootstrap V5
/// ///
/// See [https://getbootstrap.com/docs/5.0/layout/breakpoints] /// See <https://getbootstrap.com/docs/5.0/layout/breakpoints>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsBootstrapV5 { pub enum BreakpointsBootstrapV5 {
Sm, Sm,
@ -314,7 +315,7 @@ pub enum BreakpointsBootstrapV5 {
/// Breakpoint definitions for Bootstrap V5 /// Breakpoint definitions for Bootstrap V5
/// ///
/// See [https://getbootstrap.com/docs/5.0/layout/breakpoints] /// <https://getbootstrap.com/docs/5.0/layout/breakpoints>
pub fn breakpoints_bootstrap_v5() -> HashMap<BreakpointsBootstrapV5, u32> { pub fn breakpoints_bootstrap_v5() -> HashMap<BreakpointsBootstrapV5, u32> {
HashMap::from([ HashMap::from([
(BreakpointsBootstrapV5::Sm, 576), (BreakpointsBootstrapV5::Sm, 576),
@ -327,7 +328,7 @@ pub fn breakpoints_bootstrap_v5() -> HashMap<BreakpointsBootstrapV5, u32> {
/// Breakpoint keys for Material UI V5 /// Breakpoint keys for Material UI V5
/// ///
/// See [https://mui.com/material-ui/customization/breakpoints/] /// See <https://mui.com/material-ui/customization/breakpoints/>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsMaterial { pub enum BreakpointsMaterial {
Xs, Xs,
@ -339,7 +340,7 @@ pub enum BreakpointsMaterial {
/// Breakpoint definitions for Material UI V5 /// Breakpoint definitions for Material UI V5
/// ///
/// See [https://mui.com/material-ui/customization/breakpoints/] /// See <https://mui.com/material-ui/customization/breakpoints/>
pub fn breakpoints_material() -> HashMap<BreakpointsMaterial, u32> { pub fn breakpoints_material() -> HashMap<BreakpointsMaterial, u32> {
HashMap::from([ HashMap::from([
(BreakpointsMaterial::Xs, 1), (BreakpointsMaterial::Xs, 1),
@ -352,7 +353,7 @@ pub fn breakpoints_material() -> HashMap<BreakpointsMaterial, u32> {
/// Breakpoint keys for Ant Design /// Breakpoint keys for Ant Design
/// ///
/// See [https://ant.design/components/layout/#breakpoint-width] /// See <https://ant.design/components/layout/#breakpoint-width>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsAntDesign { pub enum BreakpointsAntDesign {
Xs, Xs,
@ -365,7 +366,7 @@ pub enum BreakpointsAntDesign {
/// Breakpoint definitions for Ant Design /// Breakpoint definitions for Ant Design
/// ///
/// See [https://ant.design/components/layout/#breakpoint-width] /// See <https://ant.design/components/layout/#breakpoint-width>
pub fn breakpoints_ant_design() -> HashMap<BreakpointsAntDesign, u32> { pub fn breakpoints_ant_design() -> HashMap<BreakpointsAntDesign, u32> {
HashMap::from([ HashMap::from([
(BreakpointsAntDesign::Xs, 480), (BreakpointsAntDesign::Xs, 480),
@ -379,7 +380,7 @@ pub fn breakpoints_ant_design() -> HashMap<BreakpointsAntDesign, u32> {
/// Breakpoint keys for Quasar V2 /// Breakpoint keys for Quasar V2
/// ///
/// See [https://quasar.dev/style/breakpoints] /// See <https://quasar.dev/style/breakpoints>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsQuasar { pub enum BreakpointsQuasar {
Xs, Xs,
@ -391,7 +392,7 @@ pub enum BreakpointsQuasar {
/// Breakpoint definitions for Quasar V2 /// Breakpoint definitions for Quasar V2
/// ///
/// See [https://quasar.dev/style/breakpoints] /// See <https://quasar.dev/style/breakpoints>
pub fn breakpoints_quasar() -> HashMap<BreakpointsQuasar, u32> { pub fn breakpoints_quasar() -> HashMap<BreakpointsQuasar, u32> {
HashMap::from([ HashMap::from([
(BreakpointsQuasar::Xs, 1), (BreakpointsQuasar::Xs, 1),
@ -402,32 +403,32 @@ pub fn breakpoints_quasar() -> HashMap<BreakpointsQuasar, u32> {
]) ])
} }
/// Breakpoint keys for Sematic UI /// Breakpoint keys for Semantic UI
/// ///
/// See [https://semantic-ui.com/elements/container.html] /// See <https://semantic-ui.com/elements/container.html>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsSematic { pub enum BreakpointsSemantic {
Mobile, Mobile,
Tablet, Tablet,
SmallMonitor, SmallMonitor,
LargeMonitor, LargeMonitor,
} }
/// Breakpoint definitions for Sematic UI /// Breakpoint definitions for Semantic UI
/// ///
/// See [https://semantic-ui.com/elements/container.html] /// See <https://semantic-ui.com/elements/container.html>
pub fn breakpoints_sematic() -> HashMap<BreakpointsSematic, u32> { pub fn breakpoints_semantic() -> HashMap<BreakpointsSemantic, u32> {
HashMap::from([ HashMap::from([
(BreakpointsSematic::Mobile, 1), (BreakpointsSemantic::Mobile, 1),
(BreakpointsSematic::Tablet, 768), (BreakpointsSemantic::Tablet, 768),
(BreakpointsSematic::SmallMonitor, 992), (BreakpointsSemantic::SmallMonitor, 992),
(BreakpointsSematic::LargeMonitor, 1200), (BreakpointsSemantic::LargeMonitor, 1200),
]) ])
} }
/// Breakpoint keys for Master CSS /// Breakpoint keys for Master CSS
/// ///
/// See [https://docs.master.co/css/breakpoints] /// See <https://docs.master.co/css/breakpoints>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsMasterCss { pub enum BreakpointsMasterCss {
Xxxs, Xxxs,
@ -444,7 +445,7 @@ pub enum BreakpointsMasterCss {
/// Breakpoint definitions for Master CSS /// Breakpoint definitions for Master CSS
/// ///
/// See [https://docs.master.co/css/breakpoints] /// See <https://docs.master.co/css/breakpoints>
pub fn breakpoints_master_css() -> HashMap<BreakpointsMasterCss, u32> { pub fn breakpoints_master_css() -> HashMap<BreakpointsMasterCss, u32> {
HashMap::from([ HashMap::from([
(BreakpointsMasterCss::Xxxs, 360), (BreakpointsMasterCss::Xxxs, 360),

View file

@ -46,10 +46,10 @@ use wasm_bindgen::JsValue;
/// ``` /// ```
/// ///
/// Values are (en)decoded via the given codec. You can use any of the string codecs or a /// Values are (en)decoded via the given codec. You can use any of the string codecs or a
/// binary codec wrapped in [`Base64`]. /// binary codec wrapped in `Base64`.
/// ///
/// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are /// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are
/// available and what feature flags they require. /// > available and what feature flags they require.
/// ///
/// ``` /// ```
/// # use leptos::prelude::*; /// # use leptos::prelude::*;

View file

@ -12,7 +12,7 @@ use leptos::prelude::*;
/// Without user permission, reading or altering the clipboard contents is not permitted. /// Without user permission, reading or altering the clipboard contents is not permitted.
/// ///
/// > This function requires `--cfg=web_sys_unstable_apis` to be activated as /// > This function requires `--cfg=web_sys_unstable_apis` to be activated as
/// [described in the wasm-bindgen guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html). /// > [described in the wasm-bindgen guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html).
/// ///
/// ## Demo /// ## Demo
/// ///
@ -30,14 +30,14 @@ use leptos::prelude::*;
/// ///
/// view! { /// view! {
/// <Show /// <Show
/// when=is_supported /// when=move || is_supported.get()
/// fallback=move || view! { <p>Your browser does not support Clipboard API</p> } /// fallback=move || view! { <p>Your browser does not support Clipboard API</p> }
/// > /// >
/// <button on:click={ /// <button on:click={
/// let copy = copy.clone(); /// let copy = copy.clone();
/// move |_| copy("Hello!") /// move |_| copy("Hello!")
/// }> /// }>
/// <Show when=copied fallback=move || "Copy"> /// <Show when=move || copied.get() fallback=move || "Copy">
/// "Copied!" /// "Copied!"
/// </Show> /// </Show>
/// </button> /// </button>
@ -90,7 +90,7 @@ pub fn use_clipboard_with_options(
}; };
if is_supported.get() && read { if is_supported.get() && read {
let _ = use_event_listener(window(), copy, update_text.clone()); let _ = use_event_listener(window(), copy, update_text);
let _ = use_event_listener(window(), cut, update_text); let _ = use_event_listener(window(), cut, update_text);
} }
@ -128,6 +128,8 @@ pub fn use_clipboard_with_options(
pub struct UseClipboardOptions { pub struct UseClipboardOptions {
/// When `true` event handlers are added so that the returned signal `text` is updated whenever the clipboard changes. /// When `true` event handlers are added so that the returned signal `text` is updated whenever the clipboard changes.
/// Defaults to `false`. /// Defaults to `false`.
///
/// > Please note that clipboard changes are only detected when copying or cutting text inside the same document.
read: bool, read: bool,
/// After how many milliseconds after copying should the returned signal `copied` be set to `false`? /// After how many milliseconds after copying should the returned signal `copied` be set to `false`?

View file

@ -37,7 +37,7 @@ use wasm_bindgen::JsCast;
/// # } /// # }
/// ``` /// ```
/// ///
/// By default, it will match with users' browser preference using [`use_preferred_dark`] (a.k.a. `ColorMode::Auto`). /// By default, it will match with users' browser preference using [`fn@crate::use_preferred_dark`] (a.k.a. `ColorMode::Auto`).
/// When reading the signal, it will by default return the current color mode (`ColorMode::Dark`, `ColorMode::Light` or /// When reading the signal, it will by default return the current color mode (`ColorMode::Dark`, `ColorMode::Light` or
/// your custom modes `ColorMode::Custom("some-custom")`). The `ColorMode::Auto` variant can /// your custom modes `ColorMode::Custom("some-custom")`). The `ColorMode::Auto` variant can
/// be included in the returned modes by enabling the `emit_auto` option and using [`use_color_mode_with_options`]. /// be included in the returned modes by enabling the `emit_auto` option and using [`use_color_mode_with_options`].
@ -88,7 +88,7 @@ use wasm_bindgen::JsCast;
/// ///
/// To persist color mode in a cookie, use `use_cookie_with_options` and specify `.cookie_enabled(true)`. /// To persist color mode in a cookie, use `use_cookie_with_options` and specify `.cookie_enabled(true)`.
/// ///
/// > Note: To work with SSR you have to add the `axum` or `actix` feature as described in [`use_cookie`]. /// > Note: To work with SSR you have to add the `axum` or `actix` feature as described in [`fn@crate::use_cookie`].
/// ///
/// ```rust /// ```rust
/// # use leptos::prelude::*; /// # use leptos::prelude::*;
@ -117,13 +117,13 @@ use wasm_bindgen::JsCast;
/// ///
/// If `cookie_enabled` is set to `true`, cookies will be used and if present this value will be used /// If `cookie_enabled` is set to `true`, cookies will be used and if present this value will be used
/// on the server as well as on the client. Please note that you have to add the `axum` or `actix` /// on the server as well as on the client. Please note that you have to add the `axum` or `actix`
/// feature as described in [`use_cookie`]. /// feature as described in [`fn@crate::use_cookie`].
/// ///
/// ## See also /// ## See also
/// ///
/// * [`use_preferred_dark`] /// * [`fn@crate::use_preferred_dark`]
/// * [`use_storage`] /// * [`fn@crate::storage::use_storage`]
/// * [`use_cookie`] /// * [`fn@crate::use_cookie`]
pub fn use_color_mode() -> UseColorModeReturn { pub fn use_color_mode() -> UseColorModeReturn {
use_color_mode_with_options(UseColorModeOptions::default()) use_color_mode_with_options(UseColorModeOptions::default())
} }
@ -509,9 +509,9 @@ pub struct UseColorModeReturn {
/// Main value setter signal of the color mode /// Main value setter signal of the color mode
pub set_mode: WriteSignal<ColorMode>, pub set_mode: WriteSignal<ColorMode>,
/// Direct access to the returned signal of [`use_storage`] if enabled or [`UseColorModeOptions::storage_signal`] if provided /// Direct access to the returned signal of [`fn@crate::storage::use_storage`] if enabled or [`UseColorModeOptions::storage_signal`] if provided
pub store: Signal<ColorMode>, pub store: Signal<ColorMode>,
/// Direct write access to the returned signal of [`use_storage`] if enabled or [`UseColorModeOptions::storage_signal`] if provided /// Direct write access to the returned signal of [`fn@crate::storage::use_storage`] if enabled or [`UseColorModeOptions::storage_signal`] if provided
pub set_store: WriteSignal<ColorMode>, pub set_store: WriteSignal<ColorMode>,
/// Signal of the system's preferred color mode that you would get from a media query /// Signal of the system's preferred color mode that you would get from a media query

View file

@ -57,10 +57,10 @@ use std::rc::Rc;
/// ``` /// ```
/// ///
/// Values are (en)decoded via the given codec. You can use any of the string codecs or a /// Values are (en)decoded via the given codec. You can use any of the string codecs or a
/// binary codec wrapped in [`Base64`]. /// binary codec wrapped in `Base64`.
/// ///
/// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are /// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are
/// available and what feature flags they require. /// > available and what feature flags they require.
/// ///
/// ## Cookie attributes /// ## Cookie attributes
/// ///
@ -136,10 +136,6 @@ use std::rc::Rc;
/// # view! {} /// # view! {}
/// # } /// # }
/// ``` /// ```
///
/// ## Create Your Own Custom Codec
///
/// All you need to do is to implement the [`StringCodec`] trait together with `Default` and `Clone`.
pub fn use_cookie<T, C>(cookie_name: &str) -> (Signal<Option<T>>, WriteSignal<Option<T>>) pub fn use_cookie<T, C>(cookie_name: &str) -> (Signal<Option<T>>, WriteSignal<Option<T>>)
where where
C: Encoder<T, Encoded = String> + Decoder<T, Encoded = str>, C: Encoder<T, Encoded = String> + Decoder<T, Encoded = str>,
@ -363,6 +359,8 @@ where
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
{ {
if !readonly { if !readonly {
let cookie_name = cookie_name.to_owned();
create_isomorphic_effect(move |_| { create_isomorphic_effect(move |_| {
let value = cookie let value = cookie
.with(|cookie| { .with(|cookie| {
@ -373,9 +371,15 @@ where
}) })
}) })
.flatten(); .flatten();
jar.update_value(|jar| {
jar.update_value({
let domain = domain.clone();
let path = path.clone();
let ssr_set_cookie = Rc::clone(&ssr_set_cookie);
|jar| {
write_server_cookie( write_server_cookie(
cookie_name, &cookie_name,
value, value,
jar, jar,
max_age, max_age,
@ -387,6 +391,7 @@ where
http_only, http_only,
ssr_set_cookie, ssr_set_cookie,
) )
}
}); });
}); });
} }

View file

@ -46,7 +46,7 @@ cfg_if! { if #[cfg(not(feature = "ssr"))] {
/// ///
/// ## See also /// ## See also
/// ///
/// - [`use_resize_observer`] /// - [`fn@crate::use_resize_observer`]
pub fn use_element_size<El, T>(target: El) -> UseElementSizeReturn pub fn use_element_size<El, T>(target: El) -> UseElementSizeReturn
where where
El: Into<ElementMaybeSignal<T, web_sys::Element>> + Clone, El: Into<ElementMaybeSignal<T, web_sys::Element>> + Clone,

View file

@ -41,7 +41,7 @@ use leptos::prelude::wrappers::read::Signal;
/// ///
/// ## See also /// ## See also
/// ///
/// * [`use_intersection_observer`] /// * [`fn@crate::use_intersection_observer`]
pub fn use_element_visibility<El, T>(target: El) -> Signal<bool> pub fn use_element_visibility<El, T>(target: El) -> Signal<bool>
where where
El: Into<ElementMaybeSignal<T, web_sys::Element>>, El: Into<ElementMaybeSignal<T, web_sys::Element>>,

View file

@ -21,11 +21,10 @@ use thiserror::Error;
/// ## Usage /// ## Usage
/// ///
/// Values are decoded via the given decoder. You can use any of the string codecs or a /// Values are decoded via the given decoder. You can use any of the string codecs or a
/// binary codec wrapped in [`Base64`]. /// binary codec wrapped in `Base64`.
/// ///
/// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are /// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are
/// available and what feature flags they require. /// > available and what feature flags they require.
///
/// ///
/// ``` /// ```
/// # use leptos::prelude::*; /// # use leptos::prelude::*;
@ -49,10 +48,6 @@ use thiserror::Error;
/// # } /// # }
/// ``` /// ```
/// ///
/// ### Create Your Own Custom Codec
///
/// All you need to do is to implement the [`StringCodec`] trait together with `Default` and `Clone`.
///
/// ### Named Events /// ### Named Events
/// ///
/// You can define named events when using `use_event_source_with_options`. /// You can define named events when using `use_event_source_with_options`.

View file

@ -53,7 +53,7 @@ cfg_if! { if #[cfg(not(feature = "ssr"))] {
/// ///
/// ## See also /// ## See also
/// ///
/// * [`use_element_visibility`] /// * [`fn@crate::use_element_visibility`]
pub fn use_intersection_observer<El, T, F>( pub fn use_intersection_observer<El, T, F>(
target: El, target: El,
callback: F, callback: F,

View file

@ -485,7 +485,7 @@ pub struct UseIntlNumberFormatOptions {
/// The currency to use in currency formatting. /// The currency to use in currency formatting.
/// Possible values are the ISO 4217 currency codes, such as "USD" for the US dollar, "EUR" for the euro, /// Possible values are the ISO 4217 currency codes, such as "USD" for the US dollar, "EUR" for the euro,
/// or "CNY" for the Chinese RMB — see the [Current currency & funds code list](https://www.six-group.com/en/products-services/financial-information/data-standards.html#scrollTo=currency-codes. /// or "CNY" for the Chinese RMB — see the [Current currency & funds code list](https://www.six-group.com/en/products-services/financial-information/data-standards.html#scrollTo=currency-codes).
/// There is no default value; if the style is `Currency`, the currency property must be provided. /// There is no default value; if the style is `Currency`, the currency property must be provided.
#[builder(into)] #[builder(into)]
currency: Option<String>, currency: Option<String>,

View file

@ -37,8 +37,8 @@ use std::rc::Rc;
/// ///
/// ## See also /// ## See also
/// ///
/// * [`use_preferred_dark`] /// * [`fn@crate::use_preferred_dark`]
/// * [`use_preferred_contrast`] /// * [`fn@crate::use_preferred_contrast`]
pub fn use_media_query(query: impl Into<MaybeSignal<String>>) -> Signal<bool> { pub fn use_media_query(query: impl Into<MaybeSignal<String>>) -> Signal<bool> {
let query = query.into(); let query = query.into();

View file

@ -26,8 +26,8 @@ use std::fmt::Display;
/// ///
/// ## See also /// ## See also
/// ///
/// * [`use_media_query`] /// * [`fn@crate::use_media_query`]
/// * [`use_preferred_dark`] /// * [`fn@crate::use_preferred_dark`]
pub fn use_preferred_contrast() -> Signal<PreferredContrast> { pub fn use_preferred_contrast() -> Signal<PreferredContrast> {
let is_more = use_media_query("(prefers-contrast: more)"); let is_more = use_media_query("(prefers-contrast: more)");
let is_less = use_media_query("(prefers-contrast: less)"); let is_less = use_media_query("(prefers-contrast: less)");

View file

@ -24,8 +24,8 @@ use leptos::prelude::*;
/// ///
/// ## See also /// ## See also
/// ///
/// * [`use_media_query`] /// * [`fn@crate::use_media_query`]
/// * [`use_preferred_contrast`] /// * [`fn@crate::use_preferred_contrast`]
pub fn use_preferred_dark() -> Signal<bool> { pub fn use_preferred_dark() -> Signal<bool> {
use_media_query("(prefers-color-scheme: dark)") use_media_query("(prefers-color-scheme: dark)")
} }

View file

@ -90,7 +90,7 @@ pub fn use_raf_fn_with_options(
let previous_frame_timestamp = Cell::new(0.0_f64); let previous_frame_timestamp = Cell::new(0.0_f64);
move |timestamp: f64| { move |timestamp: f64| {
if !is_active.get_untracked() { if !is_active.try_get_untracked().unwrap_or_default() {
return; return;
} }
@ -167,6 +167,6 @@ pub struct UseRafFnCallbackArgs {
/// Time elapsed between this and the last frame. /// Time elapsed between this and the last frame.
pub delta: f64, pub delta: f64,
/// Time elapsed since the creation of the web page. See [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin Time origin). /// Time elapsed since the creation of the web page. See [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin) Time origin.
pub timestamp: f64, pub timestamp: f64,
} }

View file

@ -51,7 +51,7 @@ cfg_if! { if #[cfg(not(feature = "ssr"))] {
/// ///
/// ## See also /// ## See also
/// ///
/// - [`use_element_size`] /// * [`fn@crate::use_element_size`]
pub fn use_resize_observer<El, T, F>( pub fn use_resize_observer<El, T, F>(
target: El, // TODO : multiple elements? target: El, // TODO : multiple elements?
callback: F, callback: F,

View file

@ -154,10 +154,10 @@ pub struct UseTimestampOptions {
/// Interval type for [`UseTimestampOptions`]. /// Interval type for [`UseTimestampOptions`].
#[derive(Copy, Clone, Eq, PartialEq, Debug)] #[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum TimestampInterval { pub enum TimestampInterval {
/// use [`use_raf_fn`] for updating the timestamp /// use [`fn@crate::use_raf_fn`] for updating the timestamp
RequestAnimationFrame, RequestAnimationFrame,
/// use [`use_interval_fn`] for updating the timestamp /// use [`fn@crate::use_interval_fn`] for updating the timestamp
Interval(u64), Interval(u64),
} }

View file

@ -16,6 +16,7 @@ use js_sys::Array;
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use web_sys::{BinaryType, CloseEvent, Event, MessageEvent, WebSocket}; use web_sys::{BinaryType, CloseEvent, Event, MessageEvent, WebSocket};
#[allow(rustdoc::bare_urls)]
/// Creating and managing a [Websocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) connection. /// Creating and managing a [Websocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) connection.
/// ///
/// ## Demo /// ## Demo
@ -27,7 +28,7 @@ use web_sys::{BinaryType, CloseEvent, Event, MessageEvent, WebSocket};
/// Values are (en)decoded via the given codec. You can use any of the codecs, string or binary. /// Values are (en)decoded via the given codec. You can use any of the codecs, string or binary.
/// ///
/// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are /// > Please check [the codec chapter](https://leptos-use.rs/codecs.html) to see what codecs are
/// available and what feature flags they require. /// > available and what feature flags they require.
/// ///
/// ``` /// ```
/// # use leptos::prelude::*; /// # use leptos::prelude::*;
@ -247,6 +248,7 @@ where
} }
/// Version of [`use_websocket`] that takes `UseWebSocketOptions`. See [`use_websocket`] for how to use. /// Version of [`use_websocket`] that takes `UseWebSocketOptions`. See [`use_websocket`] for how to use.
#[allow(clippy::type_complexity)]
pub fn use_websocket_with_options<T, C>( pub fn use_websocket_with_options<T, C>(
url: &str, url: &str,
options: UseWebSocketOptions< options: UseWebSocketOptions<

View file

@ -54,7 +54,7 @@ impl UseWindow {
navigator(&self) -> Option<web_sys::Navigator> navigator(&self) -> Option<web_sys::Navigator>
); );
/// Returns the same as [`use_document`]. /// Returns the same as [`fn@use_document`].
#[inline(always)] #[inline(always)]
pub fn document(&self) -> UseDocument { pub fn document(&self) -> UseDocument {
use_document() use_document()

View file

@ -1,6 +1,6 @@
/// Macro to easily create helper functions that derive a signal using a piece of code. /// Macro to easily create helper functions that derive a signal using a piece of code.
/// ///
/// See [`is_ok`] or [`use_to_string`] as examples. /// See [`fn@crate::is_ok`] or [`fn@crate::use_to_string`] as examples.
#[macro_export] #[macro_export]
macro_rules! use_derive_signal { macro_rules! use_derive_signal {
( (

View file

@ -34,7 +34,7 @@ use leptos::prelude::*;
/// ///
/// Please note that if the current component is cleaned up before the debounced callback is called, the debounced callback will not be called. /// Please note that if the current component is cleaned up before the debounced callback is called, the debounced callback will not be called.
/// ///
/// There's also `watch_debounced_with_options` where you can specify the other watch options (except `filter`). /// There's also [`watch_debounced_with_options`] where you can specify the other watch options (except `filter`).
/// ///
/// ``` /// ```
/// # use leptos::prelude::*; /// # use leptos::prelude::*;
@ -70,8 +70,8 @@ use leptos::prelude::*;
/// ///
/// ## See also /// ## See also
/// ///
/// * [`watch`] /// * `leptos::watch`
/// * [`watch_throttled`] /// * [`fn@crate::watch_throttled`]
pub fn watch_debounced<W, T, DFn, CFn>(deps: DFn, callback: CFn, ms: f64) -> impl Fn() + Clone pub fn watch_debounced<W, T, DFn, CFn>(deps: DFn, callback: CFn, ms: f64) -> impl Fn() + Clone
where where
DFn: Fn() -> W + 'static, DFn: Fn() -> W + 'static,
@ -82,7 +82,8 @@ where
watch_with_options(deps, callback, WatchOptions::default().debounce(ms)) watch_with_options(deps, callback, WatchOptions::default().debounce(ms))
} }
/// Version of `watch_debounced` that accepts `WatchDebouncedOptions`. See [`watch_debounced`] for how to use. /// Version of `watch_debounced` that accepts `WatchDebouncedOptions`.
/// See [`watch_debounced`] for how to use.
pub fn watch_debounced_with_options<W, T, DFn, CFn>( pub fn watch_debounced_with_options<W, T, DFn, CFn>(
deps: DFn, deps: DFn,
callback: CFn, callback: CFn,

View file

@ -52,7 +52,7 @@ use leptos::prelude::*;
/// ///
/// ## See also /// ## See also
/// ///
/// * [`watch`] /// * `leptos::watch`
pub fn watch_pausable<W, T, DFn, CFn>( pub fn watch_pausable<W, T, DFn, CFn>(
deps: DFn, deps: DFn,
callback: CFn, callback: CFn,

View file

@ -1,7 +1,7 @@
use crate::{watch_with_options, ThrottleOptions, WatchOptions}; use crate::{watch_with_options, ThrottleOptions, WatchOptions};
use default_struct_builder::DefaultBuilder; use default_struct_builder::DefaultBuilder;
/// A throttled version of [`watch`]. /// A throttled version of `leptos::watch`.
/// ///
/// ## Demo /// ## Demo
/// ///
@ -69,8 +69,8 @@ use default_struct_builder::DefaultBuilder;
/// ///
/// ## See also /// ## See also
/// ///
/// * [`watch`] /// * `leptos::watch`
/// * [`watch_debounced`] /// * [`fn@crate::watch_debounced`]
pub fn watch_throttled<W, T, DFn, CFn>(deps: DFn, callback: CFn, ms: f64) -> impl Fn() + Clone pub fn watch_throttled<W, T, DFn, CFn>(deps: DFn, callback: CFn, ms: f64) -> impl Fn() + Clone
where where
DFn: Fn() -> W + 'static, DFn: Fn() -> W + 'static,
@ -81,7 +81,7 @@ where
watch_with_options(deps, callback, WatchOptions::default().throttle(ms)) watch_with_options(deps, callback, WatchOptions::default().throttle(ms))
} }
/// Version of `watch_throttled` that accepts `WatchThrottledOptions`. See [`watch_throttled`] for how to use. /// Version of [`fn@watch_throttled`] that accepts `WatchThrottledOptions`. See [`watch_throttled`] for how to use.
pub fn watch_throttled_with_options<W, T, DFn, CFn>( pub fn watch_throttled_with_options<W, T, DFn, CFn>(
deps: DFn, deps: DFn,
callback: CFn, callback: CFn,

View file

@ -38,7 +38,8 @@ use std::rc::Rc;
/// ///
/// ## Filters /// ## Filters
/// ///
/// The callback can be throttled or debounced. Please see [`watch_throttled`] and [`watch_debounced`] for details. /// The callback can be throttled or debounced. Please see [`fn@crate::watch_throttled`]
/// and [`fn@crate::watch_debounced`] for details.
/// ///
/// ``` /// ```
/// # use leptos::prelude::*; /// # use leptos::prelude::*;
@ -86,10 +87,8 @@ use std::rc::Rc;
/// ///
/// ## See also /// ## See also
/// ///
/// * [`watch_throttled`] /// * [`fn@crate::watch_throttled`]
/// * [`watch_debounced`] /// * [`fn@crate::watch_debounced`]
/// Version of `watch` that accepts `WatchOptions`. See [`watch`] for how to use.
pub fn watch_with_options<W, T, DFn, CFn>( pub fn watch_with_options<W, T, DFn, CFn>(
deps: DFn, deps: DFn,
callback: CFn, callback: CFn,

View file

@ -20,7 +20,7 @@ use crate::{watch_with_options, WatchOptions};
/// ///
/// ### Callback Function /// ### Callback Function
/// ///
/// Same as [`watch`], the callback will be called with `callback(input, prev_input, prev_return)`. /// Same as [`fn@crate::watch`], the callback will be called with `callback(input, prev_input, prev_return)`.
/// ///
/// ``` /// ```
/// # use leptos::prelude::*; /// # use leptos::prelude::*;
@ -39,7 +39,7 @@ use crate::{watch_with_options, WatchOptions};
/// ///
/// ### Computed /// ### Computed
/// ///
/// Same as [`watch`], you can pass a getter function to calculate on each change. /// Same as [`fn@crate::watch`], you can pass a getter function to calculate on each change.
/// ///
/// ``` /// ```
/// # use leptos::prelude::*; /// # use leptos::prelude::*;
@ -59,7 +59,7 @@ use crate::{watch_with_options, WatchOptions};
/// ///
/// ### Options /// ### Options
/// ///
/// Options and defaults are same as [`watch_with_options`]. /// Options and defaults are same as [`fn@watch_with_options`].
/// ///
/// ``` /// ```
/// # use leptos::prelude::*; /// # use leptos::prelude::*;