Compare commits

..

1 Commits
v0.7.0 ... 3221

Author SHA1 Message Date
Greg Johnston
a10ab613b8 fix: support complex punctuated attribute keys in attr: syntax (closes #3221) 2024-11-08 15:53:08 -05:00
111 changed files with 1006 additions and 7521 deletions

View File

@@ -1,49 +0,0 @@
name: autofix.ci
on:
pull_request:
# Running this workflow on main branch pushes requires write permission to apply changes.
# Leave it alone for future uses.
# push:
# branches: ["main"]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
jobs:
autofix:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions-rust-lang/setup-rust-toolchain@v1
with: {toolchain: nightly, components: "rustfmt, clippy", target: "wasm32-unknown-unknown", rustflags: ""}
- name: Install jq
run: sudo apt-get install jq
- run: |
echo "Formatting the workspace"
cargo fmt --all
echo "Running Clippy against each member's features (default features included)"
for member in $(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | .name'); do
echo "Working on member $member":
echo -e "\tdefault-features/no-features:"
# this will also run on members with no features or default features
cargo clippy --allow-dirty --fix --lib --package "$member"
features=$(cargo metadata --no-deps --format-version 1 | jq -r ".packages[] | select(.name == \"$member\") | .features | keys[]")
for feature in $features; do
if [ "$feature" = "default" ]; then
continue
fi
echo -e "\tfeature $feature"
cargo clippy --allow-dirty --fix --lib --package "$member" --features "$feature"
done
done
- uses: autofix-ci/action@v1.3.1
if: ${{ always() }}
with:
fail-fast: false

1
.gitignore vendored
View File

@@ -14,4 +14,3 @@ blob.rs
.vscode
vendor
hash.txt

222
Cargo.lock generated
View File

@@ -88,7 +88,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb"
dependencies = [
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -205,7 +205,7 @@ dependencies = [
"actix-router",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -273,12 +273,12 @@ dependencies = [
[[package]]
name = "any_spawner"
version = "0.2.0"
version = "0.1.1"
dependencies = [
"async-executor",
"futures",
"glib",
"thiserror 2.0.3",
"thiserror 2.0.0",
"tokio",
"tracing",
"wasm-bindgen-futures",
@@ -333,7 +333,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -350,7 +350,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -364,23 +364,23 @@ dependencies = [
[[package]]
name = "attribute-derive"
version = "0.10.3"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0053e96dd3bec5b4879c23a138d6ef26f2cb936c9cdc96274ac2b9ed44b5bb54"
checksum = "f1800e974930e9079c965b9ffbcb6667a40401063a26396c7b4f15edc92da690"
dependencies = [
"attribute-derive-macro",
"derive-where",
"manyhow",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
name = "attribute-derive-macro"
version = "0.10.3"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "463b53ad0fd5b460af4b1915fe045ff4d946d025fb6c4dc3337752eaa980f71b"
checksum = "5d908eb786ef94296bff86f90130b3b748b49401dc81fd2bb8b3dccd44cfacbd"
dependencies = [
"collection_literals",
"interpolator",
@@ -389,7 +389,7 @@ dependencies = [
"proc-macro2",
"quote",
"quote-use",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -400,9 +400,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "axum"
version = "0.7.9"
version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"
checksum = "504e3947307ac8326a5437504c517c4b56716c9d98fac0028c2acc7ca47d70ae"
dependencies = [
"async-trait",
"axum-core",
@@ -571,7 +571,7 @@ checksum = "523363cbe1df49b68215efdf500b103ac3b0fb4836aed6d15689a076eadb8fff"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -867,7 +867,7 @@ checksum = "62d671cc41a825ebabc75757b62d3d168c577f9149b2d49ece1dad1f72119d25"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -880,7 +880,7 @@ dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -901,7 +901,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -1109,7 +1109,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -1171,9 +1171,9 @@ checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
[[package]]
name = "gio-sys"
version = "0.20.6"
version = "0.20.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b965df6f3534c84816b5c1a7d9efcb5671ae790822de5abe8e299797039529bc"
checksum = "217f464cad5946ae4369c355155e2d16b488c08920601083cb4891e352ae777b"
dependencies = [
"glib-sys",
"gobject-sys",
@@ -1184,9 +1184,9 @@ dependencies = [
[[package]]
name = "glib"
version = "0.20.6"
version = "0.20.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86bd3e4ee7998ab5a135d900db56930cc19ad16681adf245daff54f618b9d5e1"
checksum = "358431b0e0eb15b9d02db52e1f19c805b953c5c168099deb3de88beab761768c"
dependencies = [
"bitflags",
"futures-channel",
@@ -1213,14 +1213,14 @@ dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
name = "glib-sys"
version = "0.20.6"
version = "0.20.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d0b1827e8621fc42c0dfb228e5d57ff6a71f9699e666ece8113f979ad87c2de"
checksum = "8a5911863ab7ecd4a6f8d5976f12eeba076b23669c49b066d877e742544aa389"
dependencies = [
"libc",
"system-deps",
@@ -1448,7 +1448,7 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hydration_context"
version = "0.2.0"
version = "0.2.0-rc1"
dependencies = [
"futures",
"js-sys",
@@ -1648,7 +1648,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -1765,7 +1765,7 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "leptos"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"any_spawner",
"base64",
@@ -1792,7 +1792,7 @@ dependencies = [
"server_fn",
"slotmap",
"tachys",
"thiserror 2.0.3",
"thiserror 2.0.0",
"throw_error",
"tracing",
"typed-builder",
@@ -1810,12 +1810,12 @@ dependencies = [
"http 1.1.0",
"proc-macro-error",
"server_fn_macro 0.6.15",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
name = "leptos_actix"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"actix-files",
"actix-http",
@@ -1840,7 +1840,7 @@ dependencies = [
[[package]]
name = "leptos_axum"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"any_spawner",
"axum",
@@ -1863,21 +1863,21 @@ dependencies = [
[[package]]
name = "leptos_config"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"config",
"regex",
"serde",
"temp-env",
"tempfile",
"thiserror 2.0.3",
"thiserror 2.0.0",
"tokio",
"typed-builder",
]
[[package]]
name = "leptos_dom"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"js-sys",
"leptos",
@@ -1894,7 +1894,7 @@ dependencies = [
[[package]]
name = "leptos_hot_reload"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"anyhow",
"camino",
@@ -1904,13 +1904,13 @@ dependencies = [
"quote",
"rstml",
"serde",
"syn 2.0.89",
"syn 2.0.87",
"walkdir",
]
[[package]]
name = "leptos_integration_utils"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"futures",
"hydration_context",
@@ -1923,7 +1923,7 @@ dependencies = [
[[package]]
name = "leptos_macro"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"attribute-derive",
"cfg-if",
@@ -1941,8 +1941,8 @@ dependencies = [
"rstml",
"serde",
"server_fn",
"server_fn_macro 0.7.0",
"syn 2.0.89",
"server_fn_macro 0.7.0-rc1",
"syn 2.0.87",
"tracing",
"trybuild",
"typed-builder",
@@ -1951,7 +1951,7 @@ dependencies = [
[[package]]
name = "leptos_meta"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"futures",
"indexmap",
@@ -1966,7 +1966,7 @@ dependencies = [
[[package]]
name = "leptos_router"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"any_spawner",
"either_of",
@@ -1981,7 +1981,7 @@ dependencies = [
"reactive_graph",
"send_wrapper",
"tachys",
"thiserror 2.0.3",
"thiserror 2.0.0",
"tracing",
"url",
"wasm-bindgen",
@@ -1990,7 +1990,7 @@ dependencies = [
[[package]]
name = "leptos_router_macro"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"leptos_router",
"proc-macro-error2",
@@ -2000,7 +2000,7 @@ dependencies = [
[[package]]
name = "leptos_server"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"any_spawner",
"base64",
@@ -2091,7 +2091,7 @@ dependencies = [
"manyhow-macros",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2141,7 +2141,7 @@ checksum = "f3cd9f9bbedc1b92683a9847b8db12f3203cf32af6a11db085fa007708dc9555"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2217,7 +2217,7 @@ checksum = "1bb5c1d8184f13f7d0ccbeeca0def2f9a181bce2624302793005f5ca8aa62e5e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2239,7 +2239,7 @@ dependencies = [
[[package]]
name = "next_tuple"
version = "0.1.0"
version = "0.1.0-rc1"
[[package]]
name = "nom"
@@ -2291,7 +2291,7 @@ version = "0.2.0"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.3",
"thiserror 2.0.0",
]
[[package]]
@@ -2323,7 +2323,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2412,7 +2412,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2468,7 +2468,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033"
dependencies = [
"proc-macro2",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2523,7 +2523,7 @@ dependencies = [
"proc-macro-error-attr2",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2539,9 +2539,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
version = "1.0.92"
version = "1.0.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e"
dependencies = [
"unicode-ident",
]
@@ -2554,7 +2554,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
"version_check",
"yansi",
]
@@ -2596,7 +2596,7 @@ checksum = "ca414edb151b4c8d125c12566ab0d74dc9cdba36fb80eb7b848c15f495fd32d1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2676,7 +2676,7 @@ dependencies = [
"proc-macro-utils",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2726,7 +2726,7 @@ dependencies = [
[[package]]
name = "reactive_graph"
version = "0.1.0"
version = "0.1.0-rc1"
dependencies = [
"any_spawner",
"async-lock",
@@ -2739,7 +2739,7 @@ dependencies = [
"send_wrapper",
"serde",
"slotmap",
"thiserror 2.0.3",
"thiserror 2.0.0",
"tokio",
"tokio-test",
"tracing",
@@ -2748,7 +2748,7 @@ dependencies = [
[[package]]
name = "reactive_stores"
version = "0.1.0"
version = "0.1.0-rc1"
dependencies = [
"any_spawner",
"guardian",
@@ -2764,13 +2764,13 @@ dependencies = [
[[package]]
name = "reactive_stores_macro"
version = "0.1.0"
version = "0.1.0-rc1"
dependencies = [
"convert_case 0.6.0",
"proc-macro-error2",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2954,7 +2954,7 @@ checksum = "09cb82b74b4810f07e460852c32f522e979787691b0b7b7439fe473e49d49b2f"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -2989,7 +2989,7 @@ dependencies = [
"proc-macro2",
"proc-macro2-diagnostics",
"quote",
"syn 2.0.89",
"syn 2.0.87",
"syn_derive",
"thiserror 1.0.68",
]
@@ -3156,9 +3156,9 @@ dependencies = [
[[package]]
name = "serde"
version = "1.0.215"
version = "1.0.214"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f"
checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5"
dependencies = [
"serde_derive",
]
@@ -3181,7 +3181,7 @@ checksum = "7ce26a84e3d8d10853301cf6a75c58132b8f5d5e8fee65949ea8dd7758d6760b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -3197,20 +3197,20 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.215"
version = "1.0.214"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0"
checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
name = "serde_json"
version = "1.0.133"
version = "1.0.132"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377"
checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03"
dependencies = [
"itoa",
"memchr",
@@ -3262,7 +3262,7 @@ dependencies = [
[[package]]
name = "server_fn"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"actix-web",
"axum",
@@ -3290,7 +3290,7 @@ dependencies = [
"serde_json",
"serde_qs",
"server_fn_macro_default",
"thiserror 2.0.3",
"thiserror 2.0.0",
"throw_error",
"tower",
"tower-layer",
@@ -3312,28 +3312,28 @@ dependencies = [
"convert_case 0.6.0",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
"xxhash-rust",
]
[[package]]
name = "server_fn_macro"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"const_format",
"convert_case 0.6.0",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
"xxhash-rust",
]
[[package]]
name = "server_fn_macro_default"
version = "0.7.0"
version = "0.7.0-rc1"
dependencies = [
"server_fn_macro 0.7.0",
"syn 2.0.89",
"server_fn_macro 0.7.0-rc1",
"syn 2.0.87",
]
[[package]]
@@ -3400,7 +3400,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33a1b4f13e2bbf2f5b29d09dfebc9de69229ffee245aed80e3b70f9b5fd28c06"
dependencies = [
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -3471,9 +3471,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.89"
version = "2.0.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e"
checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d"
dependencies = [
"proc-macro2",
"quote",
@@ -3489,7 +3489,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -3515,7 +3515,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -3533,7 +3533,7 @@ dependencies = [
[[package]]
name = "tachys"
version = "0.1.0"
version = "0.1.0-rc1"
dependencies = [
"any_spawner",
"const_str_slice_concat",
@@ -3596,9 +3596,9 @@ dependencies = [
[[package]]
name = "tempfile"
version = "3.14.0"
version = "3.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c"
checksum = "f0f2c9fc62d0beef6951ccffd757e241266a2c833136efbe35af6cd2567dca5b"
dependencies = [
"cfg-if",
"fastrand",
@@ -3627,11 +3627,11 @@ dependencies = [
[[package]]
name = "thiserror"
version = "2.0.3"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa"
checksum = "15291287e9bff1bc6f9ff3409ed9af665bec7a5fc8ac079ea96be07bca0e2668"
dependencies = [
"thiserror-impl 2.0.3",
"thiserror-impl 2.0.0",
]
[[package]]
@@ -3642,23 +3642,23 @@ checksum = "a7c61ec9a6f64d2793d8a45faba21efbe3ced62a886d44c36a009b2b519b4c7e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
name = "thiserror-impl"
version = "2.0.3"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568"
checksum = "22efd00f33f93fa62848a7cab956c3d38c8d43095efda1decfc2b3a5dc0b8972"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
name = "throw_error"
version = "0.2.0"
version = "0.2.0-rc1"
dependencies = [
"pin-project-lite",
]
@@ -3745,7 +3745,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -3858,9 +3858,9 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697"
checksum = "8437150ab6bbc8c5f0f519e3d5ed4aa883a83dd4cdd3d1b21f9482936046cb97"
dependencies = [
"bitflags",
"bytes",
@@ -3913,7 +3913,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -3963,7 +3963,7 @@ checksum = "560b82d656506509d43abe30e0ba64c56b1953ab3d4fe7ba5902747a7a3cedd5"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -4111,7 +4111,7 @@ dependencies = [
"once_cell",
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
"wasm-bindgen-shared",
]
@@ -4145,7 +4145,7 @@ checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
@@ -4371,7 +4371,7 @@ checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
"synstructure",
]
@@ -4393,7 +4393,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]
@@ -4413,7 +4413,7 @@ checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
"synstructure",
]
@@ -4442,7 +4442,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.89",
"syn 2.0.87",
]
[[package]]

View File

@@ -40,36 +40,36 @@ members = [
exclude = ["benchmarks", "examples", "projects"]
[workspace.package]
version = "0.7.0"
version = "0.7.0-rc1"
edition = "2021"
rust-version = "1.76"
[workspace.dependencies]
throw_error = { path = "./any_error/", version = "0.2.0" }
any_spawner = { path = "./any_spawner/", version = "0.2.0" }
throw_error = { path = "./any_error/", version = "0.2.0-rc1" }
any_spawner = { path = "./any_spawner/", version = "0.1.0" }
const_str_slice_concat = { path = "./const_str_slice_concat", version = "0.1.0" }
either_of = { path = "./either_of/", version = "0.1.0" }
hydration_context = { path = "./hydration_context", version = "0.2.0" }
leptos = { path = "./leptos", version = "0.7.0" }
leptos_config = { path = "./leptos_config", version = "0.7.0" }
leptos_dom = { path = "./leptos_dom", version = "0.7.0" }
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.0" }
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.0" }
leptos_macro = { path = "./leptos_macro", version = "0.7.0" }
leptos_router = { path = "./router", version = "0.7.0" }
leptos_router_macro = { path = "./router_macro", version = "0.7.0" }
leptos_server = { path = "./leptos_server", version = "0.7.0" }
leptos_meta = { path = "./meta", version = "0.7.0" }
next_tuple = { path = "./next_tuple", version = "0.1.0" }
hydration_context = { path = "./hydration_context", version = "0.2.0-rc1" }
leptos = { path = "./leptos", version = "0.7.0-rc1" }
leptos_config = { path = "./leptos_config", version = "0.7.0-rc1" }
leptos_dom = { path = "./leptos_dom", version = "0.7.0-rc1" }
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.0-rc1" }
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.0-rc1" }
leptos_macro = { path = "./leptos_macro", version = "0.7.0-rc1" }
leptos_router = { path = "./router", version = "0.7.0-rc1" }
leptos_router_macro = { path = "./router_macro", version = "0.7.0-rc1" }
leptos_server = { path = "./leptos_server", version = "0.7.0-rc1" }
leptos_meta = { path = "./meta", version = "0.7.0-rc1" }
next_tuple = { path = "./next_tuple", version = "0.1.0-rc1" }
oco_ref = { path = "./oco", version = "0.2.0" }
or_poisoned = { path = "./or_poisoned", version = "0.1.0" }
reactive_graph = { path = "./reactive_graph", version = "0.1.0" }
reactive_stores = { path = "./reactive_stores", version = "0.1.0" }
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.0" }
server_fn = { path = "./server_fn", version = "0.7.0" }
server_fn_macro = { path = "./server_fn_macro", version = "0.7.0" }
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.0" }
tachys = { path = "./tachys", version = "0.1.0" }
reactive_graph = { path = "./reactive_graph", version = "0.1.0-rc1" }
reactive_stores = { path = "./reactive_stores", version = "0.1.0-rc1" }
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.0-rc1" }
server_fn = { path = "./server_fn", version = "0.7.0-rc1" }
server_fn_macro = { path = "./server_fn_macro", version = "0.7.0-rc1" }
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.0-rc1" }
tachys = { path = "./tachys", version = "0.1.0-rc1" }
[profile.release]
codegen-units = 1

View File

@@ -12,6 +12,8 @@
You can find a list of useful libraries and example projects at [`awesome-leptos`](https://github.com/leptos-rs/awesome-leptos).
# The `main` branch is currently undergoing major changes in preparation for the [0.7](https://github.com/leptos-rs/leptos/milestone/4) release. For a stable version, please use the [v0.6.13 tag](https://github.com/leptos-rs/leptos/tree/v0.6.13)
# Leptos
```rust
@@ -157,7 +159,9 @@ Sure! Obviously the `view` macro is for generating DOM nodes but you can use the
- Use event listeners to update signals
- Create effects to update the UI
The 0.7 update originally set out to create a "generic rendering" approach that would allow us to reuse most of the same view logic to do all of the above. Unfortunately, this has had to be shelved for now due to difficulties encountered by the Rust compiler when building larger-scale applications with the number of generics spread throughout the codebase that this required. It's an approach I'm looking forward to exploring again in the future; feel free to reach out if you're interested in this kind of work.
I've put together a [very simple GTK example](https://github.com/leptos-rs/leptos/blob/main/examples/gtk/src/main.rs) so you can see what I mean.
The new rendering approach being developed for 0.7 supports “universal rendering,” i.e., it can use any rendering library that supports a small set of 6-8 functions. (This is intended as a layer over typical retained-mode, OOP-style GUI toolkits like the DOM, GTK, etc.) That future rendering work will allow creating native UI in a way that is much more similar to the declarative approach used by the web framework.
### How is this different from Yew?

View File

@@ -1,6 +1,6 @@
[package]
name = "throw_error"
version = "0.2.0"
version = "0.2.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"

View File

@@ -1,6 +1,6 @@
[package]
name = "any_spawner"
version = "0.2.0"
version = "0.1.1"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"
@@ -11,7 +11,7 @@ edition.workspace = true
[dependencies]
async-executor = { version = "1.13.1", optional = true }
futures = "0.3.31"
glib = { version = "0.20.6", optional = true }
glib = { version = "0.20.5", optional = true }
thiserror = "2.0"
tokio = { version = "1.41", optional = true, default-features = false, features = [
"rt",

View File

@@ -12,7 +12,7 @@ lto = true
[dependencies]
console_error_panic_hook = "0.1.7"
leptos = { path = "../../leptos", features = ["islands"] }
leptos = { path = "../../leptos", features = ["experimental-islands"] }
leptos_axum = { path = "../../integrations/axum", optional = true }
leptos_meta = { path = "../../meta" }
leptos_router = { path = "../../router" }

View File

@@ -12,7 +12,7 @@ futures = "0.3.30"
http = "1.1"
leptos = { path = "../../leptos", features = [
"tracing",
"islands",
"experimental-islands",
] }
server_fn = { path = "../../server_fn", features = ["serde-lite"] }
leptos_axum = { path = "../../integrations/axum", optional = true }

View File

@@ -12,7 +12,7 @@ futures = "0.3.30"
http = "1.1"
leptos = { path = "../../leptos", features = [
"tracing",
"islands",
"experimental-islands",
] }
leptos_router = { path = "../../router" }
server_fn = { path = "../../server_fn", features = ["serde-lite"] }

View File

@@ -44,8 +44,8 @@ window.addEventListener("click", async (ev) => {
// TODO parse from the request stream instead?
const doc = parser.parseFromString(htmlString, 'text/html');
// The 'doc' variable now contains the parsed DOM
const transition = async () => {
// The 'doc' variable now contains the parsed DOM
const transition = document.startViewTransition(async () => {
const oldDocWalker = document.createTreeWalker(document);
const newDocWalker = doc.createTreeWalker(doc);
let oldNode = oldDocWalker.currentNode;
@@ -128,13 +128,8 @@ window.addEventListener("click", async (ev) => {
}
} }
}
};
// Not all browsers support startViewTransition; see https://caniuse.com/?search=startViewTransition
if (document.startViewTransition) {
await document.startViewTransition(transition);
} else {
await transition()
}
});
await transition;
window.history.pushState(undefined, null, url);
});

View File

@@ -10,7 +10,7 @@ crate-type = ["cdylib", "rlib"]
actix-files = { version = "0.6.6", optional = true }
actix-web = { version = "4.8", optional = true, features = ["macros"] }
console_error_panic_hook = "0.1.7"
js-sys = { version = "0.3.72" }
js-sys = { version = "0.3.70", optional = true }
leptos = { path = "../../leptos" }
leptos_actix = { path = "../../integrations/actix", optional = true }
leptos_router = { path = "../../router" }
@@ -21,7 +21,7 @@ tokio = { version = "1.39", features = ["time", "rt"], optional = true }
[features]
hydrate = [
"dep:js-sys",
"leptos/hydrate",
]
ssr = [

View File

@@ -1,121 +0,0 @@
@check_aria_current
Feature: Check aria-current being applied to make links bolded
Background:
Given I see the app
Scenario: Should see the base case working
Then I see the Out-of-Order link being bolded
And I see the following links being bolded
| Out-of-Order |
| Nested |
And I see the In-Order link not being bolded
And I see the following links not being bolded
| In-Order |
| Single |
Scenario: Should see client-side render the correct bolded links
When I select the link In-Order
And I select the link Single
Then I see the following links being bolded
| In-Order |
| Single |
And I see the following links not being bolded
| Out-of-Order |
| Nested |
Scenario: Should see server-side render the correct bolded links
When I select the link In-Order
And I select the link Single
And I reload the page
Then I see the following links being bolded
| In-Order |
| Single |
And I see the following links not being bolded
| Out-of-Order |
| Nested |
Scenario: Check that the base nested route links are working
When I select the link Instrumented
Then I see the Instrumented link being bolded
And I see the Item Listing link not being bolded
Scenario: Should see going deep down into nested routes bold links
When I select the link Instrumented
And I select the link Target 421
Then I see the following links being bolded
| Instrumented |
| Item Listing |
| Target 4## |
| Target 42# |
| Target 421 |
| field1 |
Scenario: Should see going deep down into nested routes in SSR bold links
When I select the link Instrumented
And I select the link Target 421
And I reload the page
Then I see the following links being bolded
| Instrumented |
| Item Listing |
| Target 4## |
| Target 42# |
| Target 421 |
| field1 |
Scenario: Going deep down navigate around nested links bold correctly
When I select the link Instrumented
And I select the link Target 421
And I select the link Inspect path2/field3
Then I see the following links being bolded
| Instrumented |
| Item Listing |
| Target 4## |
| Target 42# |
| field3 |
And I see the following links not being bolded
| Target 421 |
| field1 |
Scenario: Going deep down navigate around nested links bold correctly, SSR
When I select the link Instrumented
And I select the link Target 421
And I select the link Inspect path2/field3
And I reload the page
Then I see the following links being bolded
| Instrumented |
| Item Listing |
| Target 4## |
| Target 42# |
| field3 |
And I see the following links not being bolded
| Target 421 |
| field1 |
Scenario: Going deep down back out nested routes reset bolded states
When I select the link Instrumented
And I select the link Target 421
And I select the link Counters
Then I see the following links being bolded
| Instrumented |
| Counters |
And I see the following links not being bolded
| Item Listing |
| Target 4## |
| Target 42# |
| Target 421 |
Scenario: Going deep down back out nested routes reset bolded states, SSR
When I select the link Instrumented
And I select the link Target 421
And I select the link Counters
And I reload the page
Then I see the following links being bolded
| Instrumented |
| Counters |
And I see the following links not being bolded
| Item Listing |
| Target 4## |
| Target 42# |
| Target 421 |

View File

@@ -81,20 +81,3 @@ pub async fn instrumented_counts(
Ok(())
}
pub async fn link_text_is_aria_current(client: &Client, text: &str) -> Result<()> {
let link = find::link_with_text(client, text).await?;
link.attr("aria-current").await?
.expect(format!("aria-current missing for {text}").as_str());
Ok(())
}
pub async fn link_text_is_not_aria_current(client: &Client, text: &str) -> Result<()> {
let link = find::link_with_text(client, text).await?;
link.attr("aria-current").await?
.map(|_| anyhow::bail!("aria-current mistakenly set for {text}"))
.unwrap_or(Ok(()))
}

View File

@@ -124,12 +124,3 @@ async fn component_message(client: &Client, id: &str) -> Result<String> {
Ok(text)
}
pub async fn link_with_text(client: &Client, text: &str) -> Result<Element> {
let link = client
.wait()
.for_element(Locator::LinkText(text))
.await
.expect(format!("Link not found by `{}`", text).as_str());
Ok(link)
}

View File

@@ -80,58 +80,6 @@ async fn i_see_the_second_count_is(
Ok(())
}
#[then(regex = r"^I see the (.*) link being bolded$")]
async fn i_see_the_link_being_bolded(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::link_text_is_aria_current(client, &text).await?;
Ok(())
}
#[then(expr = "I see the following links being bolded")]
async fn i_see_the_following_links_being_bolded(
world: &mut AppWorld,
step: &Step,
) -> Result<()> {
let client = &world.client;
if let Some(table) = step.table.as_ref() {
for row in table.rows.iter() {
check::link_text_is_aria_current(client, &row[0]).await?;
}
}
Ok(())
}
#[then(regex = r"^I see the (.*) link not being bolded$")]
async fn i_see_the_link_being_not_bolded(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::link_text_is_not_aria_current(client, &text).await?;
Ok(())
}
#[then(expr = "I see the following links not being bolded")]
async fn i_see_the_following_links_not_being_bolded(
world: &mut AppWorld,
step: &Step,
) -> Result<()> {
let client = &world.client;
if let Some(table) = step.table.as_ref() {
for row in table.rows.iter() {
check::link_text_is_not_aria_current(client, &row[0]).await?;
}
}
Ok(())
}
#[then(expr = "I see the following counters under section")]
#[then(expr = "the following counters under section")]
async fn i_see_the_following_counters_under_section(

View File

@@ -4,6 +4,25 @@ use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use server_fn::ServerFnError;
pub fn shell(leptos_options: &LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=leptos_options.clone() />
<HydrationScripts options=leptos_options.clone()/>
<link rel="stylesheet" id="leptos" href="/pkg/todo_app_sqlite_csr.css"/>
<link rel="shortcut icon" type="image/ico" href="/favicon.ico"/>
</head>
<body>
<TodoApp/>
</body>
</html>
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
pub struct Todo {

View File

@@ -1,6 +1,6 @@
[package]
name = "hydration_context"
version = "0.2.0"
version = "0.2.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"

View File

@@ -1,8 +1,3 @@
// #[wasm_bindgen(thread_local)] is deprecated in wasm-bindgen 0.2.96
// but the replacement is also only shipped in that version
// as a result, we'll just allow deprecated for now
#![allow(deprecated)]
use super::{SerializedDataId, SharedContext};
use crate::{PinnedFuture, PinnedStream};
use core::fmt::Debug;

View File

@@ -83,14 +83,15 @@ pub trait SharedContext: Debug {
/// Reads the current value of some data from the shared context, if it has been
/// sent from the server. This returns the serialized data as a `String` that should
/// be deserialized.
/// be deserialized using [`Serializable::de`].
///
/// On the server and in client-side rendered implementations, this should
/// always return [`None`].
fn read_data(&self, id: &SerializedDataId) -> Option<String>;
/// Returns a [`Future`] that resolves with a `String` that should
/// be deserialized once the given piece of server data has resolved.
/// be deserialized using [`Serializable::de`] once the given piece of server
/// data has resolved.
///
/// On the server and in client-side rendered implementations, this should
/// return a [`Future`] that is immediately ready with [`None`].
@@ -147,8 +148,8 @@ pub trait SharedContext: Debug {
/// Adds a `Future` to the set of “blocking resources” that should prevent the servers
/// response stream from beginning until all are resolved. The `Future` returned by
/// blocking resources will not resolve until every `Future` added by this method
/// has resolved.
/// [`blocking_resources`](Self::blocking_resources) will not resolve until every `Future`
/// added by this method has resolved.
///
/// In browser implementations, this should be a no-op.
fn defer_stream(&self, wait_for: PinnedFuture<()>);

View File

@@ -1,5 +1,4 @@
#![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Provides functions to easily integrate Leptos with Actix.
//!
@@ -10,6 +9,7 @@
use actix_files::NamedFile;
use actix_http::header::{HeaderName, HeaderValue, ACCEPT, LOCATION, REFERER};
use actix_web::{
body::BoxBody,
dev::{ServiceFactory, ServiceRequest},
http::header,
test,
@@ -56,10 +56,8 @@ use std::{
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
#[derive(Debug, Clone, Default)]
pub struct ResponseParts {
/// If provided, this will overwrite any other status code for this response.
pub status: Option<StatusCode>,
/// The map of headers that should be added to the response.
pub headers: header::HeaderMap,
pub status: Option<StatusCode>,
}
impl ResponseParts {
@@ -82,18 +80,16 @@ impl ResponseParts {
}
}
/// A wrapper for an Actix [`HttpRequest`] that allows it to be used in an
/// A wrapper for an Actix [`HttpRequest`](actix_web::HttpRequest) that allows it to be used in an
/// `Send`/`Sync` setting like Leptos's Context API.
#[derive(Debug, Clone)]
pub struct Request(SendWrapper<HttpRequest>);
impl Request {
/// Wraps an existing Actix request.
pub fn new(req: &HttpRequest) -> Self {
Self(SendWrapper::new(req.clone()))
}
/// Consumes the wrapper and returns the inner Actix request.
pub fn into_inner(self) -> HttpRequest {
self.0.take()
}
@@ -303,7 +299,7 @@ pub fn redirect(path: &str) {
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -330,7 +326,7 @@ pub fn handle_server_fns() -> Route {
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -419,6 +415,12 @@ pub fn handle_server_fns_with_context(
/// will include fallback content for any `<Suspense/>` nodes, and be immediately interactive,
/// but requires some client-side JavaScript.
///
/// The provides a [MetaContext] and a [RouterIntegrationContext] to apps context before
/// rendering it, and includes any meta tags injected using [leptos_meta].
///
/// The HTML stream is rendered using [render_to_stream](leptos::ssr::render_to_stream), and
/// includes everything described in the documentation for that function.
///
/// This can then be set up at an appropriate route in your application:
/// ```
/// use actix_web::{App, HttpServer};
@@ -457,8 +459,9 @@ pub fn handle_server_fns_with_context(
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -478,6 +481,13 @@ where
/// This stream will pause at each `<Suspense/>` node and wait for it to resolve before
/// sending down its HTML. The app will become interactive once it has fully loaded.
///
/// The provides a [MetaContext] and a [RouterIntegrationContext] to apps context before
/// rendering it, and includes any meta tags injected using [leptos_meta].
///
/// The HTML stream is rendered using
/// [render_to_stream_in_order](leptos::ssr::render_to_stream_in_order),
/// and includes everything described in the documentation for that function.
///
/// This can then be set up at an appropriate route in your application:
/// ```
/// use actix_web::{App, HttpServer};
@@ -519,7 +529,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -536,7 +548,13 @@ where
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
/// to route it using [leptos_router], asynchronously rendering an HTML page after all
/// `async` resources have loaded.
/// `async` [Resource](leptos::Resource)s have loaded.
///
/// The provides a [MetaContext] and a [RouterIntegrationContext] to the apps context before
/// rendering it, and includes any meta tags injected using [leptos_meta].
///
/// The HTML stream is rendered using [render_to_string_async](leptos::ssr::render_to_string_async), and
/// includes everything described in the documentation for that function.
///
/// This can then be set up at an appropriate route in your application:
/// ```
@@ -576,7 +594,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -600,7 +620,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -635,7 +657,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -667,8 +691,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -691,7 +716,7 @@ where
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
/// to route it using [leptos_router], asynchronously serving the page once all `async`
/// resources have loaded.
/// [Resource](leptos::Resource)s have loaded.
///
/// This function allows you to provide additional information to Leptos for your route.
/// It could be used to pass in Path Info, Connection Info, or anything your heart desires.
@@ -699,7 +724,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -1292,12 +1319,14 @@ where
web::get().to(handler)
}
pub enum DataResponse<T> {
Data(T),
Response(actix_web::dev::Response<BoxBody>),
}
/// This trait allows one to pass a list of routes and a render function to Actix's router, letting us avoid
/// having to use wildcards or manually define all routes in multiple places.
pub trait LeptosRoutes {
/// Adds routes to the Axum router that have either
/// 1) been generated by `leptos_router`, or
/// 2) handle a server function.
fn leptos_routes<IV>(
self,
paths: Vec<ActixRouteListing>,
@@ -1306,12 +1335,6 @@ pub trait LeptosRoutes {
where
IV: IntoView + 'static;
/// Adds routes to the Axum router that have either
/// 1) been generated by `leptos_router`, or
/// 2) handle a server function.
///
/// Runs `additional_context` to provide additional data to the reactive system via context,
/// when handling a route.
fn leptos_routes_with_context<IV>(
self,
paths: Vec<ActixRouteListing>,

View File

@@ -11,7 +11,7 @@ edition.workspace = true
[dependencies]
any_spawner = { workspace = true, features = ["tokio"] }
hydration_context = { workspace = true }
axum = { version = "0.7.9", default-features = false, features = [
axum = { version = "0.7.7", default-features = false, features = [
"matched-path",
] }
dashmap = "6"
@@ -26,11 +26,11 @@ once_cell = "1"
parking_lot = "0.12.3"
tokio = { version = "1.41", default-features = false }
tower = { version = "0.5.1", features = ["util"] }
tower-http = "0.6.2"
tower-http = "0.6.1"
tracing = { version = "0.1.40", optional = true }
[dev-dependencies]
axum = "0.7.9"
axum = "0.7.7"
tokio = { version = "1.41", features = ["net", "rt-multi-thread"] }
[features]

View File

@@ -1,6 +1,4 @@
#![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Provides functions to easily integrate Leptos with Axum.
//!
//! ## JS Fetch Integration
@@ -16,7 +14,7 @@
//! - `default`: supports running in a typical native Tokio/Axum environment
//! - `wasm`: with `default-features = false`, supports running in a JS Fetch-based
//! environment
//! - `islands`: activates Leptos [islands mode](https://leptos-rs.github.io/leptos/islands.html)
//! - `experimental-islands`: activates Leptos [islands mode](https://leptos-rs.github.io/leptos/islands.html)
//!
//! ### Important Note
//! Prior to 0.5, using `default-features = false` on `leptos_axum` simply did nothing. Now, it actively
@@ -65,9 +63,10 @@ use leptos_meta::ServerMetaContext;
#[cfg(feature = "default")]
use leptos_router::static_routes::ResolvedStaticPath;
use leptos_router::{
components::provide_server_redirect, location::RequestUrl,
static_routes::RegenerationFn, ExpandOptionals, PathSegment, RouteList,
RouteListing, SsrMode,
components::provide_server_redirect,
location::RequestUrl,
static_routes::{RegenerationFn, StaticParamsMap},
ExpandOptionals, PathSegment, RouteList, RouteListing, SsrMode,
};
#[cfg(feature = "default")]
use once_cell::sync::Lazy;
@@ -86,9 +85,7 @@ use tower_http::services::ServeDir;
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
#[derive(Debug, Clone, Default)]
pub struct ResponseParts {
/// If provided, this will overwrite any other status code for this response.
pub status: Option<StatusCode>,
/// The map of headers that should be added to the response.
pub headers: HeaderMap,
}
@@ -197,9 +194,9 @@ impl ExtendResponse for AxumResponse {
/// 2. A server function that is called from WASM running in the client (e.g., a dispatched action
/// or a spawned `Future`).
/// 3. A `<form>` submitted to the server function endpoint using default browser APIs (often due
/// to using [`ActionForm`] without JS/WASM present.)
/// to using [`ActionForm`](leptos::form::ActionForm) without JS/WASM present.)
///
/// Using it with a non-blocking [`Resource`] will not work if you are using streaming rendering,
/// Using it with a non-blocking [`Resource`](leptos::server::Resource) will not work if you are using streaming rendering,
/// as the response's headers will already have been sent by the time the server function calls `redirect()`.
///
/// ### Implementation
@@ -435,13 +432,18 @@ async fn handle_server_fns_inner(
.expect("could not build Response")
}
/// A stream of bytes of HTML.
pub type PinnedHtmlStream =
Pin<Box<dyn Stream<Item = io::Result<Bytes>> + Send>>;
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application.
///
/// The provides a [MetaContext] and a [RouterIntegrationContext] to apps context before
/// rendering it, and includes any meta tags injected using [leptos_meta].
///
/// The HTML stream is rendered using [render_to_stream](leptos::ssr::render_to_stream), and
/// includes everything described in the documentation for that function.
///
/// This can then be set up at an appropriate route in your application:
/// ```
/// use axum::{handler::Handler, Router};
@@ -479,7 +481,8 @@ pub type PinnedHtmlStream =
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -530,6 +533,12 @@ where
/// This stream will pause at each `<Suspense/>` node and wait for it to resolve before
/// sending down its HTML. The app will become interactive once it has fully loaded.
///
/// The provides a [MetaContext] and a [RouterIntegrationContext] to apps context before
/// rendering it, and includes any meta tags injected using [leptos_meta].
///
/// The HTML stream is rendered using [render_to_stream_in_order], and includes everything described in
/// the documentation for that function.
///
/// This can then be set up at an appropriate route in your application:
/// ```
/// use axum::{handler::Handler, Router};
@@ -567,7 +576,8 @@ where
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -620,7 +630,8 @@ where
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -751,7 +762,8 @@ where
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -818,7 +830,8 @@ where
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -935,7 +948,13 @@ fn provide_contexts(
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], asynchronously rendering an HTML page after all
/// `async` resources have loaded.
/// `async` [Resource](leptos::Resource)s have loaded.
///
/// The provides a [MetaContext] and a [RouterIntegrationContext] to apps context before
/// rendering it, and includes any meta tags injected using [leptos_meta].
///
/// The HTML stream is rendered using [render_to_string_async], and includes everything described in
/// the documentation for that function.
///
/// This can then be set up at an appropriate route in your application:
/// ```
@@ -975,7 +994,8 @@ fn provide_contexts(
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -996,7 +1016,7 @@ where
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], asynchronously rendering an HTML page after all
/// `async` resources have loaded.
/// `async` [Resource](leptos::Resource)s have loaded.
///
/// This version allows us to pass Axum State/Extension/Extractor or other infro from Axum or network
/// layers above Leptos itself. To use it, you'll need to write your own handler function that provides
@@ -1029,7 +1049,8 @@ where
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -1063,7 +1084,7 @@ where
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], asynchronously rendering an HTML page after all
/// `async` resources have loaded.
/// `async` [Resource](leptos::Resource)s have loaded.
///
/// This version allows us to pass Axum State/Extension/Extractor or other infro from Axum or network
/// layers above Leptos itself. To use it, you'll need to write your own handler function that provides
@@ -1096,7 +1117,8 @@ where
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -1185,6 +1207,32 @@ where
generate_route_list_with_exclusions_and_ssg(app_fn, excluded_routes).0
}
/// Builds all routes that have been defined using [`StaticRoute`].
#[allow(unused)]
pub async fn build_static_routes<IV>(
options: &LeptosOptions,
app_fn: impl Fn() -> IV + 'static + Send + Clone,
routes: &[RouteListing],
static_data_map: StaticParamsMap,
) where
IV: IntoView + 'static,
{
todo!()
/*
let options = options.clone();
let routes = routes.to_owned();
spawn_task!(async move {
leptos_router::build_static_routes(
&options,
app_fn,
&routes,
&static_data_map,
)
.await
.expect("could not build static routes")
});*/
}
/// Generates a list of all routes defined in Leptos's Router in your app. We can then use this to automatically
/// create routes in Axum's Router without having to use wildcard matching or fallbacks. Takes in your root app Element
/// as an argument so it can walk you app tree. This version is tailored to generate Axum compatible paths. Adding excluded_routes
@@ -1635,9 +1683,6 @@ where
S: Clone + Send + Sync + 'static,
LeptosOptions: FromRef<S>,
{
/// Adds routes to the Axum router that have either
/// 1) been generated by `leptos_router`, or
/// 2) handle a server function.
fn leptos_routes<IV>(
self,
options: &S,
@@ -1647,12 +1692,6 @@ where
where
IV: IntoView + 'static;
/// Adds routes to the Axum router that have either
/// 1) been generated by `leptos_router`, or
/// 2) handle a server function.
///
/// Runs `additional_context` to provide additional data to the reactive system via context,
/// when handling a route.
fn leptos_routes_with_context<IV>(
self,
options: &S,
@@ -1663,8 +1702,6 @@ where
where
IV: IntoView + 'static;
/// Extends the Axum router with the given paths, and handles the requests with the given
/// handler.
fn leptos_routes_with_handler<H, T>(
self,
paths: Vec<AxumRouteListing>,
@@ -1977,10 +2014,6 @@ where
.map_err(|e| ServerFnError::ServerError(format!("{e:?}")))
}
/// A reasonable handler for serving static files (like JS/WASM/CSS) and 404 errors.
///
/// This is provided as a convenience, but is a fairly simple function. If you need to adapt it,
/// simply reuse the source code of this function in your own application.
#[cfg(feature = "default")]
pub fn file_and_error_handler<S, IV>(
shell: fn(LeptosOptions) -> IV,

View File

@@ -86,7 +86,7 @@ tracing = [
]
nonce = ["base64", "rand"]
spin = ["leptos-spin-macro"]
islands = ["leptos_macro/islands", "dep:serde_json"]
experimental-islands = ["leptos_macro/experimental-islands", "dep:serde_json"]
trace-component-props = [
"leptos_macro/trace-component-props",
"leptos_dom/trace-component-props"
@@ -104,7 +104,7 @@ denylist = [
"rkyv", # was causing clippy issues on nightly
"trace-component-props",
"spin",
"islands",
"experimental-islands",
]
skip_feature_sets = [
["csr", "ssr"],

View File

@@ -31,13 +31,13 @@
//! *Notes*:
//! - The `render_number` prop can receive any type that implements `Fn(i32) -> String`.
//! - Callbacks are most useful when you want optional generic props.
//! - All callbacks implement the [`Callable`](leptos::callback::Callable) trait, and can be invoked with `my_callback.run(input)`.
//! - All callbacks implement the [`Callable`] trait, and can be invoked with `my_callback.run(input)`.
//! - The callback types implement [`Copy`], so they can easily be moved into and out of other closures, just like signals.
//!
//! # Types
//! This modules implements 2 callback types:
//! - [`Callback`](leptos::callback::Callback)
//! - [`UnsyncCallback`](leptos::callback::UnsyncCallback)
//! - [`Callback`]
//! - [`UnsyncCallback`]
//!
//! Use `SyncCallback` if the function is not `Sync` and `Send`.
@@ -223,14 +223,14 @@ mod tests {
#[test]
fn clone_callback() {
let callback = Callback::new(move |_no_clone: NoClone| NoClone {});
let _cloned = callback;
let _cloned = callback.clone();
}
#[test]
fn clone_unsync_callback() {
let callback =
UnsyncCallback::new(move |_no_clone: NoClone| NoClone {});
let _cloned = callback;
let _cloned = callback.clone();
}
#[test]

View File

@@ -228,7 +228,6 @@ impl ViewFnOnce {
pub struct TypedChildren<T>(Box<dyn FnOnce() -> View<T> + Send>);
impl<T> TypedChildren<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> impl FnOnce() -> View<T> + Send {
self.0
}
@@ -246,7 +245,7 @@ where
}
}
/// A typed equivalent to [`ChildrenFnMut`], which takes a generic but preserves type information to
/// A typed equivalent to [`ChildrenMut`], which takes a generic but preserves type information to
/// allow the compiler to optimize the view more effectively.
pub struct TypedChildrenMut<T>(Box<dyn FnMut() -> View<T> + Send>);
@@ -257,7 +256,6 @@ impl<T> Debug for TypedChildrenMut<T> {
}
impl<T> TypedChildrenMut<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> impl FnMut() -> View<T> + Send {
self.0
}
@@ -286,7 +284,6 @@ impl<T> Debug for TypedChildrenFn<T> {
}
impl<T> TypedChildrenFn<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> Arc<dyn Fn() -> View<T> + Send + Sync> {
self.0
}

View File

@@ -72,7 +72,9 @@ use web_sys::{
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
#[component]
pub fn ActionForm<ServFn>(
/// The action from which to build the form.
/// The action from which to build the form. This should include a URL, which can be generated
/// by default using [`create_server_action`](leptos_server::create_server_action) or added
/// manually using [`using_server_fn`](leptos_server::Action::using_server_fn).
action: ServerAction<ServFn>,
/// A [`NodeRef`] in which the `<form>` element should be stored.
#[prop(optional)]
@@ -147,7 +149,9 @@ where
/// progressively enhanced to use client-side routing.
#[component]
pub fn MultiActionForm<ServFn>(
/// The action from which to build the form.
/// The action from which to build the form. This should include a URL, which can be generated
/// by default using [create_server_action](leptos_server::create_server_action) or added
/// manually using [leptos_server::Action::using_server_fn].
action: ServerMultiAction<ServFn>,
/// A [`NodeRef`] in which the `<form>` element should be stored.
#[prop(optional)]
@@ -247,16 +251,12 @@ where
) -> Result<Self, serde_qs::Error>;
}
/// Errors that can arise when coverting from an HTML event or form into a Rust data type.
#[derive(Error, Debug)]
pub enum FromFormDataError {
/// Could not find a `<form>` connected to the event.
#[error("Could not find <form> connected to event.")]
MissingForm(Event),
/// Could not create `FormData` from the form.
#[error("Could not create FormData from <form>: {0:?}")]
FormData(JsValue),
/// Failed to deserialize this Rust type from the form data.
#[error("Deserialization error: {0:?}")]
Deserialization(serde_qs::Error),
}

View File

@@ -1,7 +1,7 @@
(function (root, pkg_path, output_name, wasm_output_name) {
import(`${root}/${pkg_path}/${output_name}.js`)
.then(mod => {
mod.default({module_or_path: `${root}/${pkg_path}/${wasm_output_name}.wasm`}).then(() => {
mod.default(`${root}/${pkg_path}/${wasm_output_name}.wasm`).then(() => {
mod.hydrate();
});
})

View File

@@ -4,15 +4,9 @@ use crate::prelude::*;
use leptos_config::LeptosOptions;
use leptos_macro::{component, view};
/// Inserts auto-reloading code used in `cargo-leptos`.
///
/// This should be included in the `<head>` of your application shell during development.
#[component]
pub fn AutoReload(
/// Whether the file-watching feature should be disabled.
#[prop(optional)]
disable_watch: bool,
/// Configuration options for this project.
#[prop(optional)] disable_watch: bool,
options: LeptosOptions,
) -> impl IntoView {
(!disable_watch && std::env::var("LEPTOS_WATCH").is_ok()).then(|| {
@@ -40,16 +34,10 @@ pub fn AutoReload(
})
}
/// Inserts hydration scripts that add interactivity to your server-rendered HTML.
///
/// This should be included in the `<head>` of your application shell.
#[component]
pub fn HydrationScripts(
/// Configuration options for this project.
options: LeptosOptions,
/// Should be `true` to hydrate in `islands` mode.
#[prop(optional)]
islands: bool,
#[prop(optional)] islands: bool,
/// A base url, not including a trailing slash
#[prop(optional, into)]
root: Option<String>,

View File

@@ -9,7 +9,6 @@ use tachys::{
},
};
/// A wrapper for any kind of view.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct View<T>
where
@@ -21,7 +20,6 @@ where
}
impl<T> View<T> {
/// Wraps the view.
pub fn new(inner: T) -> Self {
Self {
inner,
@@ -30,12 +28,10 @@ impl<T> View<T> {
}
}
/// Unwraps the view, returning the inner type.
pub fn into_inner(self) -> T {
self.inner
}
/// Adds a view marker, which is used for hot-reloading and debug purposes.
#[inline(always)]
pub fn with_view_marker(
#[allow(unused_mut)] // used in debug
@@ -51,12 +47,10 @@ impl<T> View<T> {
}
}
/// A trait that is implemented for types that can be rendered.
pub trait IntoView
where
Self: Sized + Render + RenderHtml + Send,
{
/// Wraps the inner type.
fn into_view(self) -> View<Self>;
}
@@ -194,15 +188,9 @@ impl<T: AddAnyAttr> AddAnyAttr for View<T> {
}
}
/// Collects some iterator of views into a list, so they can be rendered.
///
/// This is a shorthand for `.collect::<Vec<_>>()`, and allows any iterator of renderable
/// items to be collected into a renderable collection.
pub trait CollectView {
/// The inner view type.
type View: IntoView;
/// Collects the iterator into a list of views.
fn collect_view(self) -> Vec<Self::View>;
}

View File

@@ -1,6 +1,5 @@
#![deny(missing_docs)]
#!rdeny(missing_docs)]
#![forbid(unsafe_code)]
//! # About Leptos
//!
//! Leptos is a full-stack framework for building web applications in Rust. You can use it to build
@@ -39,7 +38,7 @@
//! server actions, forms, and server-sent events (SSE).
//! - **[`todomvc`]** shows the basics of building an isomorphic web app. Both the server and the client import the same app code.
//! The server renders the app directly to an HTML string, and the client hydrates that HTML to make it interactive.
//! You might also want to see how we use [`Effect::new`](leptos::prelude::Effect) to
//! You might also want to see how we use [`Effect::new`](leptos::prelude::Effect::new) to
//! [serialize JSON to `localStorage`](https://github.com/leptos-rs/leptos/blob/20af4928b2fffe017408d3f4e7330db22cf68277/examples/todomvc/src/lib.rs#L191-L209)
//! and [reactively call DOM methods](https://github.com/leptos-rs/leptos/blob/16f084a71268ac325fbc4a5e50c260df185eadb6/examples/todomvc/src/lib.rs#L292-L296)
//! on [references to elements](https://github.com/leptos-rs/leptos/blob/20af4928b2fffe017408d3f4e7330db22cf68277/examples/todomvc/src/lib.rs#L228).
@@ -78,7 +77,7 @@
//! + `async` interop: [`Resource`](leptos::prelude::Resource) for loading data using `async` functions
//! and [`Action`](leptos::prelude::Action) to mutate data or imperatively call `async` functions.
//! + reactions: [`Effect`](leptos::prelude::Effect) and [`RenderEffect`](leptos::prelude::RenderEffect).
//! - **Templating/Views**: the [`view`] macro and [`IntoView`] trait.
//! - **Templating/Views**: the [`view`] macro and [`IntoView`](leptos::IntoView) trait.
//! - **Routing**: the [`leptos_router`](https://docs.rs/leptos_router/latest/leptos_router/) crate
//! - **Server Functions**: the [`server`](macro@leptos::prelude::server) macro and [`ServerAction`](leptos::prelude::ServerAction).
//!
@@ -288,9 +287,8 @@ pub mod logging {
pub use leptos_dom::{debug_warn, error, log, warn};
}
/// Utilities for working with asynchronous tasks.
pub mod task {
pub use any_spawner::{self, CustomExecutor, Executor};
pub use any_spawner::Executor;
use std::future::Future;
/// Spawns a thread-safe [`Future`].
@@ -318,10 +316,10 @@ pub mod task {
}
// these reexports are used in islands
#[cfg(feature = "islands")]
#[cfg(feature = "experimental-islands")]
#[doc(hidden)]
pub use serde;
#[cfg(feature = "islands")]
#[cfg(feature = "experimental-islands")]
#[doc(hidden)]
pub use serde_json;
#[cfg(feature = "tracing")]

View File

@@ -87,12 +87,7 @@ use throw_error::ErrorHookFuture;
/// ```
#[component]
pub fn Suspense<Chil>(
/// A function that returns a fallback that will be shown while resources are still loading.
/// By default this is an empty view.
#[prop(optional, into)]
fallback: ViewFnOnce,
/// Children will be rendered once initially to catch any resource reads, then hidden until all
/// data have loaded.
#[prop(optional, into)] fallback: ViewFnOnce,
children: TypedChildren<Chil>,
) -> impl IntoView
where

File diff suppressed because it is too large Load Diff

View File

@@ -21,7 +21,7 @@ typed-builder = "0.20.0"
[dev-dependencies]
tokio = { version = "1.41", features = ["rt", "macros"] }
tempfile = "3.14"
tempfile = "3.13"
temp-env = { version = "0.3.6", features = ["async_closure"] }
[package.metadata.docs.rs]

View File

@@ -30,14 +30,14 @@ fn ws_from_str_test() {
#[test]
fn env_w_default_test() {
temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
_ = temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
assert_eq!(
env_w_default("LEPTOS_CONFIG_ENV_TEST", "default").unwrap(),
String::from("custom")
);
});
temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
_ = temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
assert_eq!(
env_w_default("LEPTOS_CONFIG_ENV_TEST", "default").unwrap(),
String::from("default")
@@ -47,14 +47,14 @@ fn env_w_default_test() {
#[test]
fn env_wo_default_test() {
temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
_ = temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
assert_eq!(
env_wo_default("LEPTOS_CONFIG_ENV_TEST").unwrap(),
Some(String::from("custom"))
);
});
temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
_ = temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
assert_eq!(env_wo_default("LEPTOS_CONFIG_ENV_TEST").unwrap(), None);
});
}

View File

@@ -1,6 +1,6 @@
[package]
name = "leptos_macro"
version = "0.7.0"
version = "0.7.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
repository = "https://github.com/leptos-rs/leptos"
@@ -13,7 +13,7 @@ edition.workspace = true
proc-macro = true
[dependencies]
attribute-derive = { version = "0.10.3", features = ["syn-full"] }
attribute-derive = { version = "0.10.2", features = ["syn-full"] }
cfg-if = "1.0"
html-escape = "0.2.13"
itertools = "0.13.0"
@@ -44,7 +44,7 @@ hydrate = []
ssr = ["server_fn_macro/ssr", "leptos/ssr"]
nightly = ["server_fn_macro/nightly"]
tracing = ["dep:tracing"]
islands = []
experimental-islands = []
trace-component-props = []
actix = ["server_fn_macro/actix"]
axum = ["server_fn_macro/axum"]

View File

@@ -1,5 +1,3 @@
//! Macros for use with the Leptos framework.
#![cfg_attr(feature = "nightly", feature(proc_macro_span))]
#![forbid(unsafe_code)]
// to prevent warnings from popping up when a nightly feature is stabilized
@@ -7,7 +5,6 @@
// FIXME? every use of quote! {} is warning here -- false positive?
#![allow(unknown_lints)]
#![allow(private_macro_use)]
#![deny(missing_docs)]
#[macro_use]
extern crate proc_macro_error2;
@@ -272,8 +269,8 @@ pub fn view(tokens: TokenStream) -> TokenStream {
view_macro_impl(tokens, false)
}
/// The `template` macro behaves like [`view`](view!), except that it wraps the entire tree in a
/// [`ViewTemplate`](https://docs.rs/leptos/0.7.0-gamma3/leptos/prelude/struct.ViewTemplate.html). This optimizes creation speed by rendering
/// The `template` macro behaves like [`view`], except that it wraps the entire tree in a
/// [`ViewTemplate`](leptos::prelude::ViewTemplate). This optimizes creation speed by rendering
/// most of the view into a `<template>` tag with HTML rendered at compile time, then hydrating it.
/// In exchange, there is a small binary size overhead.
#[proc_macro_error2::proc_macro_error]
@@ -366,7 +363,7 @@ fn normalized_call_site(site: proc_macro::Span) -> Option<String> {
}
}
/// This behaves like the [`view`](view!) macro, but loads the view from an external file instead of
/// This behaves like the [`view`] macro, but loads the view from an external file instead of
/// parsing it inline.
///
/// This is designed to allow editing views in a separate file, if this improves a user's workflow.
@@ -559,10 +556,10 @@ pub fn component(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
}
/// Defines a component as an interactive island when you are using the
/// `islands` feature of Leptos. Apart from the macro name,
/// `experimental-islands` feature of Leptos. Apart from the macro name,
/// the API is the same as the [`component`](macro@component) macro.
///
/// When you activate the `islands` feature, every `#[component]`
/// When you activate the `experimental-islands` feature, every `#[component]`
/// is server-only by default. This "default to server" behavior is important:
/// you opt into shipping code to the client, rather than opting out. You can
/// opt into client-side interactivity for any given component by changing from
@@ -639,7 +636,7 @@ pub fn island(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
abort!(
transparent,
"only `transparent` is supported";
help = "try `#[island(transparent)]` or `#[island]`"
help = "try `#[component(transparent)]` or `#[component]`"
);
}

View File

@@ -197,7 +197,7 @@ enum InertElementBuilder<'a> {
},
}
impl ToTokens for InertElementBuilder<'_> {
impl<'a> ToTokens for InertElementBuilder<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
InertElementBuilder::GlobalClass { strs, .. } => {
@@ -219,7 +219,7 @@ enum GlobalClassItem<'a> {
String(String),
}
impl ToTokens for GlobalClassItem<'_> {
impl<'a> ToTokens for GlobalClassItem<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let addl_tokens = match self {
GlobalClassItem::Global(v) => v.to_token_stream(),
@@ -652,18 +652,6 @@ pub(crate) fn element_to_tokens(
},
_ => None,
};
if let NodeAttribute::Attribute(a) = a {
if let Some(Tuple(_)) = a.value() {
return Ordering::Greater;
}
}
if let NodeAttribute::Attribute(b) = b {
if let Some(Tuple(_)) = b.value() {
return Ordering::Less;
}
}
match (key_a.as_deref(), key_b.as_deref()) {
(Some("class"), Some("class")) | (Some("style"), Some("style")) => {
Ordering::Equal
@@ -767,7 +755,7 @@ pub(crate) fn element_to_tokens(
let name = node.name().to_string();
// link custom ident to name span for IDE docs
let custom = Ident::new("custom", name.span());
quote_spanned! { node.name().span() => ::leptos::tachys::html::element::#custom(#name) }
quote! { ::leptos::tachys::html::element::#custom(#name) }
} else if is_svg_element(&tag) {
parent_type = TagType::Svg;
let name = if tag == "use" || tag == "use_" {
@@ -775,33 +763,33 @@ pub(crate) fn element_to_tokens(
} else {
name.to_token_stream()
};
quote_spanned! { node.name().span() => ::leptos::tachys::svg::#name() }
quote! { ::leptos::tachys::svg::#name() }
} else if is_math_ml_element(&tag) {
parent_type = TagType::Math;
quote_spanned! { node.name().span() => ::leptos::tachys::mathml::#name() }
quote! { ::leptos::tachys::mathml::#name() }
} else if is_ambiguous_element(&tag) {
match parent_type {
TagType::Unknown => {
// We decided this warning was too aggressive, but I'll leave it here in case we want it later
/* proc_macro_error2::emit_warning!(name.span(), "The view macro is assuming this is an HTML element, \
but it is ambiguous; if it is an SVG or MathML element, prefix with svg:: or math::"); */
quote_spanned! { node.name().span() =>
quote! {
::leptos::tachys::html::element::#name()
}
}
TagType::Html => {
quote_spanned! { node.name().span() => ::leptos::tachys::html::element::#name() }
quote! { ::leptos::tachys::html::element::#name() }
}
TagType::Svg => {
quote_spanned! { node.name().span() => ::leptos::tachys::svg::#name() }
quote! { ::leptos::tachys::svg::#name() }
}
TagType::Math => {
quote_spanned! { node.name().span() => ::leptos::tachys::math::#name() }
quote! { ::leptos::tachys::math::#name() }
}
}
} else {
parent_type = TagType::Html;
quote_spanned! { name.span() => ::leptos::tachys::html::element::#name() }
quote! { ::leptos::tachys::html::element::#name() }
};
/* TODO restore this
@@ -1013,11 +1001,7 @@ pub(crate) fn attribute_absolute(
) -> Option<TokenStream> {
let key = node.key.to_string();
let contains_dash = key.contains('-');
let attr_colon = key.starts_with("attr:")
|| key.starts_with("style:")
|| key.starts_with("class:")
|| key.starts_with("prop:")
|| key.starts_with("use:");
let attr_colon = key.starts_with("attr:");
// anything that follows the x:y pattern
match &node.key {
NodeName::Punctuated(parts) if !contains_dash || attr_colon => {
@@ -1722,7 +1706,7 @@ fn tuple_name(name: &str, node: &KeyedAttribute) -> TupleName {
TupleName::None
}
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug)]
enum TupleName {
None,
Str(String),

View File

@@ -6,10 +6,6 @@ use reactive_graph::{
use server_fn::{error::ServerFnErrorSerde, ServerFn, ServerFnError};
use std::{ops::Deref, panic::Location, sync::Arc};
/// An error that can be caused by a server action.
///
/// This is used for propagating errors from the server to the client when JS/WASM are not
/// supported.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerActionError {
path: Arc<str>,
@@ -17,7 +13,6 @@ pub struct ServerActionError {
}
impl ServerActionError {
/// Creates a new error associated with the given path.
pub fn new(path: &str, err: &str) -> Self {
Self {
path: path.into(),
@@ -25,18 +20,15 @@ impl ServerActionError {
}
}
/// The path with which this error is associated.
pub fn path(&self) -> &str {
&self.path
}
/// The error message.
pub fn err(&self) -> &str {
&self.err
}
}
/// An [`ArcAction`] that can be used to call a server function.
pub struct ArcServerAction<S>
where
S: ServerFn + 'static,
@@ -53,7 +45,6 @@ where
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`ArcAction`] that will call the server function `S` when dispatched.
#[track_caller]
pub fn new() -> Self {
let err = use_context::<ServerActionError>().and_then(|error| {
@@ -125,7 +116,6 @@ where
}
}
/// An [`Action`] that can be used to call a server function.
pub struct ServerAction<S>
where
S: ServerFn + 'static,
@@ -142,7 +132,6 @@ where
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`Action`] that will call the server function `S` when dispatched.
pub fn new() -> Self {
let err = use_context::<ServerActionError>().and_then(|error| {
(error.path() == S::PATH)

View File

@@ -1,6 +1,4 @@
//! Utilities for communicating between the server and the client with Leptos.
#![deny(missing_docs)]
//#![deny(missing_docs)]
#![forbid(unsafe_code)]
mod action;
@@ -15,25 +13,135 @@ pub use once_resource::*;
mod resource;
pub use resource::*;
mod shared;
////! # Leptos Server Functions
////!
////! This package is based on a simple idea: sometimes its useful to write functions
////! that will only run on the server, and call them from the client.
////!
////! If youre creating anything beyond a toy app, youll need to do this all the time:
////! reading from or writing to a database that only runs on the server, running expensive
////! computations using libraries you dont want to ship down to the client, accessing
////! APIs that need to be called from the server rather than the client for CORS reasons
////! or because you need a secret API key thats stored on the server and definitely
////! shouldnt be shipped down to a users browser.
////!
////! Traditionally, this is done by separating your server and client code, and by setting
////! up something like a REST API or GraphQL API to allow your client to fetch and mutate
////! data on the server. This is fine, but it requires you to write and maintain your code
////! in multiple separate places (client-side code for fetching, server-side functions to run),
////! as well as creating a third thing to manage, which is the API contract between the two.
////!
////! This package provides two simple primitives that allow you instead to write co-located,
////! isomorphic server functions. (*Co-located* means you can write them in your app code so
////! that they are “located alongside” the client code that calls them, rather than separating
////! the client and server sides. *Isomorphic* means you can call them from the client as if
////! you were simply calling a function; the function call has the “same shape” on the client
////! as it does on the server.)
////!
////! ### `#[server]`
////!
////! The [`#[server]`](https://docs.rs/leptos/latest/leptos/attr.server.html) macro allows you to annotate a function to
////! indicate that it should only run on the server (i.e., when you have an `ssr` feature in your
////! crate that is enabled).
////!
////! ```rust,ignore
////! use leptos::prelude::*;
////! #[server(ReadFromDB)]
////! async fn read_posts(how_many: usize, query: String) -> Result<Vec<Posts>, ServerFnError> {
////! // do some server-only work here to access the database
////! let posts = todo!();;
////! Ok(posts)
////! }
////!
////! // call the function
////! spawn_local(async {
////! let posts = read_posts(3, "my search".to_string()).await;
////! log::debug!("posts = {posts:#?}");
////! });
////! ```
////!
////! If you call this function from the client, it will serialize the function arguments and `POST`
////! them to the server as if they were the inputs in `<form method="POST">`.
////!
////! Heres what you need to remember:
////! - **Server functions must be `async`.** Even if the work being done inside the function body
////! can run synchronously on the server, from the clients perspective it involves an asynchronous
////! function call.
////! - **Server functions must return `Result<T, ServerFnError>`.** Even if the work being done
////! inside the function body cant fail, the processes of serialization/deserialization and the
////! network call are fallible.
////! - **Return types must be [Serializable](leptos_reactive::Serializable).**
////! This should be fairly obvious: we have to serialize arguments to send them to the server, and we
////! need to deserialize the result to return it to the client.
////! - **Arguments must be implement [serde::Serialize].** They are serialized as an `application/x-www-form-urlencoded`
////! form data using [`serde_qs`](https://docs.rs/serde_qs/latest/serde_qs/) or as `application/cbor`
////! using [`cbor`](https://docs.rs/cbor/latest/cbor/). **Note**: You should explicitly include `serde` with the
////! `derive` feature enabled in your `Cargo.toml`. You can do this by running `cargo add serde --features=derive`.
////! - Context comes from the server. [`use_context`](leptos_reactive::use_context) can be used to access specific
////! server-related data, as documented in the server integrations. This allows accessing things like HTTP request
////! headers as needed. However, server functions *not* have access to reactive state that exists in the client.
////!
////! ## Server Function Encodings
////!
////! By default, the server function call is a `POST` request that serializes the arguments as URL-encoded form data in the body
////! of the request. But there are a few other methods supported. Optionally, we can provide another argument to the `#[server]`
////! macro to specify an alternate encoding:
////!
////! ```rust,ignore
////! #[server(AddTodo, "/api", "Url")]
////! #[server(AddTodo, "/api", "GetJson")]
////! #[server(AddTodo, "/api", "Cbor")]
////! #[server(AddTodo, "/api", "GetCbor")]
////! ```
////!
////! The four options use different combinations of HTTP verbs and encoding methods:
////!
////! | Name | Method | Request | Response |
////! | ----------------- | ------ | ----------- | -------- |
////! | **Url** (default) | POST | URL encoded | JSON |
////! | **GetJson** | GET | URL encoded | JSON |
////! | **Cbor** | POST | CBOR | CBOR |
////! | **GetCbor** | GET | URL encoded | CBOR |
////!
////! In other words, you have two choices:
////!
////! - `GET` or `POST`? This has implications for things like browser or CDN caching; while `POST` requests should not be cached,
////! `GET` requests can be.
////! - Plain text (arguments sent with URL/form encoding, results sent as JSON) or a binary format (CBOR, encoded as a base64
////! string)?
////!
////! ## Why not `PUT` or `DELETE`? Why URL/form encoding, and not JSON?**
////!
////! These are reasonable questions. Much of the web is built on REST API patterns that encourage the use of semantic HTTP
////! methods like `DELETE` to delete an item from a database, and many devs are accustomed to sending data to APIs in the
////! JSON format.
////!
////! The reason we use `POST` or `GET` with URL-encoded data by default is the `<form>` support. For better or for worse,
////! HTML forms dont support `PUT` or `DELETE`, and they dont support sending JSON. This means that if you use anything
////! but a `GET` or `POST` request with URL-encoded data, it can only work once WASM has loaded.
////!
////! The CBOR encoding is supported for historical reasons; an earlier version of server functions used a URL encoding that
////! didnt support nested objects like structs or vectors as server function arguments, which CBOR did. But note that the
////! CBOR forms encounter the same issue as `PUT`, `DELETE`, or JSON: they do not degrade gracefully if the WASM version of
////! your app is not available.
//pub use server_fn::{error::ServerFnErrorErr, ServerFnError};
//mod action;
//mod multi_action;
//pub use action::*;
//pub use multi_action::*;
//extern crate tracing;
use base64::{engine::general_purpose::STANDARD_NO_PAD, DecodeError, Engine};
pub use shared::*;
/// Encodes data into a string.
pub trait IntoEncodedString {
/// Encodes the data.
fn into_encoded_string(self) -> String;
}
/// Decodes data from a string.
pub trait FromEncodedStr {
/// The decoded data.
type DecodedType<'a>: Borrow<Self>;
/// The type of an error encountered during decoding.
type DecodingError;
/// Decodes the string.
fn from_encoded_str(
data: &str,
) -> Result<Self::DecodedType<'_>, Self::DecodingError>;

View File

@@ -17,7 +17,6 @@ use std::{
panic::Location,
};
/// A reference-counted resource that only loads its data locally on the client.
pub struct ArcLocalResource<T> {
data: ArcAsyncDerived<SendWrapper<T>>,
#[cfg(debug_assertions)]
@@ -35,10 +34,6 @@ impl<T> Clone for ArcLocalResource<T> {
}
impl<T> ArcLocalResource<T> {
/// Creates the resource.
///
/// This will only begin loading data if you are on the client (i.e., if you do not have the
/// `ssr` feature activated).
#[track_caller]
pub fn new<Fut>(fetcher: impl Fn() -> Fut + 'static) -> Self
where
@@ -197,7 +192,6 @@ impl<T> Subscriber for ArcLocalResource<T> {
}
}
/// A resource that only loads its data locally on the client.
pub struct LocalResource<T> {
data: AsyncDerived<SendWrapper<T>>,
#[cfg(debug_assertions)]
@@ -213,10 +207,6 @@ impl<T> Clone for LocalResource<T> {
impl<T> Copy for LocalResource<T> {}
impl<T> LocalResource<T> {
/// Creates the resource.
///
/// This will only begin loading data if you are on the client (i.e., if you do not have the
/// `ssr` feature activated).
#[track_caller]
pub fn new<Fut>(fetcher: impl Fn() -> Fut + 'static) -> Self
where

View File

@@ -5,7 +5,6 @@ use reactive_graph::{
use server_fn::{ServerFn, ServerFnError};
use std::{ops::Deref, panic::Location};
/// An [`ArcMultiAction`] that can be used to call a server function.
pub struct ArcServerMultiAction<S>
where
S: ServerFn + 'static,
@@ -22,7 +21,6 @@ where
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`ArcMultiAction`] which, when dispatched, will call the server function `S`.
#[track_caller]
pub fn new() -> Self {
Self {
@@ -89,7 +87,6 @@ where
}
}
/// A [`MultiAction`] that can be used to call a server function.
pub struct ServerMultiAction<S>
where
S: ServerFn + 'static,
@@ -117,7 +114,6 @@ where
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`MultiAction`] which, when dispatched, will call the server function `S`.
pub fn new() -> Self {
Self {
inner: MultiAction::new(|input: &S| {

View File

@@ -0,0 +1,344 @@
use leptos_reactive::{
is_suppressing_resource_load, signal_prelude::*, spawn_local, store_value,
untrack, StoredValue,
};
use server_fn::{ServerFn, ServerFnError};
use std::{future::Future, pin::Pin, rc::Rc};
/// An action that synchronizes multiple imperative `async` calls to the reactive system,
/// tracking the progress of each one.
///
/// Where an [Action](crate::Action) fires a single call, a `MultiAction` allows you to
/// keep track of multiple in-flight actions.
///
/// If youre trying to load data by running an `async` function reactively, you probably
/// want to use a [Resource](leptos_reactive::Resource) instead. If youre trying to occasionally
/// run an `async` function in response to something like a user adding a task to a todo list,
/// youre in the right place.
///
/// ```rust
/// # use leptos::*;
/// # let runtime = create_runtime();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = create_multi_action(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// # if false {
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
/// # }
///
/// # runtime.dispose();
/// ```
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Submission::input] as well.
///
/// ```rust
/// # use leptos::*;
/// # let runtime = create_runtime();
/// // if there's a single argument, just use that
/// let action1 = create_multi_action(|input: &String| {
/// let input = input.clone();
/// async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = create_multi_action(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 =
/// create_multi_action(|input: &(usize, String)| async { todo!() });
/// # runtime.dispose();
/// ```
pub struct MultiAction<I, O>(StoredValue<MultiActionState<I, O>>)
where
I: 'static,
O: 'static;
impl<I, O> MultiAction<I, O>
where
I: 'static,
O: 'static,
{
}
impl<I, O> Clone for MultiAction<I, O>
where
I: 'static,
O: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<I, O> Copy for MultiAction<I, O>
where
I: 'static,
O: 'static,
{
}
impl<I, O> MultiAction<I, O>
where
I: 'static,
O: 'static,
{
/// Calls the `async` function with a reference to the input type as its argument.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn dispatch(&self, input: I) {
self.0.with_value(|a| a.dispatch(input))
}
/// The set of all submissions to this multi-action.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn submissions(&self) -> ReadSignal<Vec<Submission<I, O>>> {
self.0.with_value(|a| a.submissions())
}
/// The URL associated with the action (typically as part of a server function.)
/// This enables integration with the `MultiActionForm` component in `leptos_router`.
pub fn url(&self) -> Option<String> {
self.0.with_value(|a| a.url.as_ref().cloned())
}
/// How many times an action has successfully resolved.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn version(&self) -> RwSignal<usize> {
self.0.with_value(|a| a.version)
}
/// Associates the URL of the given server function with this action.
/// This enables integration with the `MultiActionForm` component in `leptos_router`.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn using_server_fn<T: ServerFn>(self) -> Self {
self.0.update_value(|a| {
a.url = Some(T::url().to_string());
});
self
}
}
struct MultiActionState<I, O>
where
I: 'static,
O: 'static,
{
/// How many times an action has successfully resolved.
pub version: RwSignal<usize>,
submissions: RwSignal<Vec<Submission<I, O>>>,
url: Option<String>,
#[allow(clippy::complexity)]
action_fn: Rc<dyn Fn(&I) -> Pin<Box<dyn Future<Output = O>>>>,
}
/// An action that has been submitted by dispatching it to a [MultiAction](crate::MultiAction).
pub struct Submission<I, O>
where
I: 'static,
O: 'static,
{
/// The current argument that was dispatched to the `async` function.
/// `Some` while we are waiting for it to resolve, `None` if it has resolved.
pub input: RwSignal<Option<I>>,
/// The most recent return value of the `async` function.
pub value: RwSignal<Option<O>>,
pub(crate) pending: RwSignal<bool>,
/// Controls this submission has been canceled.
pub canceled: RwSignal<bool>,
}
impl<I, O> Clone for Submission<I, O> {
fn clone(&self) -> Self {
*self
}
}
impl<I, O> Copy for Submission<I, O> {}
impl<I, O> Submission<I, O>
where
I: 'static,
O: 'static,
{
/// Whether this submission is currently waiting to resolve.
pub fn pending(&self) -> ReadSignal<bool> {
self.pending.read_only()
}
/// Cancels the submission, preventing it from resolving.
pub fn cancel(&self) {
self.canceled.set(true);
}
}
impl<I, O> MultiActionState<I, O>
where
I: 'static,
O: 'static,
{
/// Calls the `async` function with a reference to the input type as its argument.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn dispatch(&self, input: I) {
if !is_suppressing_resource_load() {
let fut = (self.action_fn)(&input);
let submission = Submission {
input: create_rw_signal(Some(input)),
value: create_rw_signal(None),
pending: create_rw_signal(true),
canceled: create_rw_signal(false),
};
self.submissions.update(|subs| subs.push(submission));
let canceled = submission.canceled;
let input = submission.input;
let pending = submission.pending;
let value = submission.value;
let version = self.version;
spawn_local(async move {
let new_value = fut.await;
let canceled = untrack(move || canceled.get());
if !canceled {
value.set(Some(new_value));
}
input.set(None);
pending.set(false);
version.update(|n| *n += 1);
})
}
}
/// The set of all submissions to this multi-action.
pub fn submissions(&self) -> ReadSignal<Vec<Submission<I, O>>> {
self.submissions.read_only()
}
}
/// Creates an [MultiAction] to synchronize an imperative `async` call to the synchronous reactive system.
///
/// If youre trying to load data by running an `async` function reactively, you probably
/// want to use a [create_resource](leptos_reactive::create_resource) instead. If youre trying
/// to occasionally run an `async` function in response to something like a user clicking a button,
/// you're in the right place.
///
/// ```rust
/// # use leptos::*;
/// # let runtime = create_runtime();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = create_multi_action(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
/// # if false {
///
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// assert_eq!(add_todo.submissions().get().len(), 3);
/// # }
/// # runtime.dispose();
/// ```
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Submission::input] as well.
///
/// ```rust
/// # use leptos::*;
/// # let runtime = create_runtime();
/// // if there's a single argument, just use that
/// let action1 = create_multi_action(|input: &String| {
/// let input = input.clone();
/// async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = create_multi_action(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 =
/// create_multi_action(|input: &(usize, String)| async { todo!() });
/// # runtime.dispose();
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
pub fn create_multi_action<I, O, F, Fu>(action_fn: F) -> MultiAction<I, O>
where
I: 'static,
O: 'static,
F: Fn(&I) -> Fu + 'static,
Fu: Future<Output = O> + 'static,
{
let version = create_rw_signal(0);
let submissions = create_rw_signal(Vec::new());
let action_fn = Rc::new(move |input: &I| {
let fut = action_fn(input);
Box::pin(fut) as Pin<Box<dyn Future<Output = O>>>
});
MultiAction(store_value(MultiActionState {
version,
submissions,
url: None,
action_fn,
}))
}
/// Creates an [MultiAction] that can be used to call a server function.
///
/// ```rust,ignore
/// # use leptos::*;
///
/// #[server(MyServerFn)]
/// async fn my_server_fn() -> Result<(), ServerFnError> {
/// todo!()
/// }
///
/// # let runtime = create_runtime();
/// let my_server_multi_action = create_server_multi_action::<MyServerFn>();
/// # runtime.dispose();
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
pub fn create_server_multi_action<S>(
) -> MultiAction<S, Result<S::Output, ServerFnError<S::Error>>>
where
S: Clone + ServerFn,
{
#[cfg(feature = "ssr")]
let c = move |args: &S| S::run_body(args.clone());
#[cfg(not(feature = "ssr"))]
let c = move |args: &S| S::run_on_client(args.clone());
create_multi_action(c).using_server_fn::<S>()
}

View File

@@ -43,15 +43,6 @@ use std::{
task::{Context, Poll, Waker},
};
/// A reference-counted resource that only loads once.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
#[derive(Debug)]
pub struct ArcOnceResource<T, Ser = JsonSerdeCodec> {
trigger: ArcTrigger,
@@ -89,12 +80,6 @@ where
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`. If `blocking` is `true`, this is a blocking
/// resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options(
fut: impl Future<Output = T> + Send + 'static,
@@ -253,8 +238,7 @@ where
}
}
/// A [`Future`] that is ready when an
/// [`ArcAsyncDerived`](reactive_graph::computed::ArcAsyncDerived) is finished loading or reloading,
/// A [`Future`] that is ready when an [`ArcAsyncDerived`] is finished loading or reloading,
/// and contains its value. `.await`ing this clones the value `T`.
pub struct OnceResourceFuture<T> {
source: AnySource,
@@ -303,17 +287,11 @@ where
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, true)
@@ -329,7 +307,6 @@ T: Send + Sync + 'static,
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`FromToStringCodec`] for encoding/decoding the value.
pub fn new_str(
fut: impl Future<Output = T> + Send + 'static
) -> Self
@@ -337,11 +314,6 @@ T: Send + Sync + 'static,
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`FromToStringCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
@@ -360,7 +332,6 @@ T: Send + Sync + 'static,
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_wb(
fut: impl Future<Output = T> + Send + 'static
@@ -369,11 +340,6 @@ fut: impl Future<Output = T> + Send + 'static
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking(
fut: impl Future<Output = T> + Send + 'static
@@ -394,7 +360,6 @@ where
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`MiniserdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_miniserde(
fut: impl Future<Output = T> + Send + 'static,
@@ -402,11 +367,6 @@ where
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`MiniserdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking(
fut: impl Future<Output = T> + Send + 'static,
@@ -425,7 +385,6 @@ T: Send + Sync + 'static,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`SerdeLite`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_lite(
fut: impl Future<Output = T> + Send + 'static
@@ -434,11 +393,6 @@ fut: impl Future<Output = T> + Send + 'static
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`SerdeLite`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking(
fut: impl Future<Output = T> + Send + 'static
@@ -460,17 +414,11 @@ where
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`RkyvCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_rkyv(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`RkyvCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking(
fut: impl Future<Output = T> + Send + 'static,
@@ -479,15 +427,6 @@ where
}
}
/// A resource that only loads once.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
#[derive(Debug)]
pub struct OnceResource<T, Ser = JsonSerdeCodec> {
inner: ArenaItem<ArcOnceResource<T, Ser>>,
@@ -513,12 +452,6 @@ where
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`. If `blocking` is `true`, this is a blocking
/// resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options(
fut: impl Future<Output = T> + Send + 'static,
@@ -634,17 +567,11 @@ where
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, true)
@@ -660,7 +587,6 @@ T: Send + Sync + 'static,
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`FromToStringCodec`] for encoding/decoding the value.
pub fn new_str(
fut: impl Future<Output = T> + Send + 'static
) -> Self
@@ -668,11 +594,6 @@ T: Send + Sync + 'static,
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`FromToStringCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
@@ -691,7 +612,6 @@ T: Send + Sync + 'static,
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_wb(
fut: impl Future<Output = T> + Send + 'static
@@ -700,11 +620,6 @@ fut: impl Future<Output = T> + Send + 'static
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking(
fut: impl Future<Output = T> + Send + 'static
@@ -725,7 +640,6 @@ where
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`MiniserdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_miniserde(
fut: impl Future<Output = T> + Send + 'static,
@@ -733,11 +647,6 @@ where
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`MiniserdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking(
fut: impl Future<Output = T> + Send + 'static,
@@ -756,7 +665,6 @@ T: Send + Sync + 'static,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`SerdeLite`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_lite(
fut: impl Future<Output = T> + Send + 'static
@@ -765,11 +673,6 @@ fut: impl Future<Output = T> + Send + 'static
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`SerdeLite`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking(
fut: impl Future<Output = T> + Send + 'static
@@ -791,17 +694,11 @@ where
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`RkyvCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_rkyv(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`RkyvCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking(
fut: impl Future<Output = T> + Send + 'static,

View File

@@ -37,12 +37,9 @@ use std::{
pub(crate) static IS_SUPPRESSING_RESOURCE_LOAD: AtomicBool =
AtomicBool::new(false);
/// Used to prevent resources from actually loading, in environments (like server route generation)
/// where they are not needed.
pub struct SuppressResourceLoad;
impl SuppressResourceLoad {
/// Prevents resources from loading until this is dropped.
pub fn new() -> Self {
IS_SUPPRESSING_RESOURCE_LOAD.store(true, Ordering::Relaxed);
Self
@@ -61,15 +58,6 @@ impl Drop for SuppressResourceLoad {
}
}
/// A reference-counted asynchronous resource.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
pub struct ArcResource<T, Ser = JsonSerdeCodec> {
ser: PhantomData<Ser>,
refetch: ArcRwSignal<usize>,
@@ -206,21 +194,6 @@ where
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`.
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// If `blocking` is `true`, this is a blocking resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -305,8 +278,6 @@ where
}
}
/// Synchronously, reactively reads the current value of the resource and applies the function
/// `f` to its value if it is `Some(_)`.
#[track_caller]
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U>
where
@@ -380,13 +351,6 @@ where
T: Send + Sync + 'static,
E: Send + Sync + Clone + 'static,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
@@ -403,15 +367,6 @@ where
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -425,19 +380,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -460,15 +402,6 @@ where
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_str<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -481,19 +414,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -516,15 +436,6 @@ where
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_serde_wb<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -538,19 +449,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -575,15 +473,6 @@ where
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_miniserde<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -597,19 +486,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -633,15 +509,6 @@ where
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_serde_lite<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -655,19 +522,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -693,15 +547,6 @@ where
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_rkyv<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -715,19 +560,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -758,22 +590,11 @@ impl<T, Ser> ArcResource<T, Ser>
where
T: 'static,
{
/// Returns a new [`Future`] that is ready when the resource has loaded, and accesses its inner
/// value by reference.
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
self.data.by_ref()
}
}
/// An asynchronous resource.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
pub struct Resource<T, Ser = JsonSerdeCodec>
where
T: Send + Sync + 'static,
@@ -886,15 +707,6 @@ where
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_str<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -908,19 +720,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_str_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -946,15 +745,6 @@ where
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -968,19 +758,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -1005,15 +782,6 @@ where
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_serde_wb<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1026,19 +794,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_serde_wb_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1064,15 +819,6 @@ where
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_miniserde<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1084,31 +830,6 @@ where
{
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_miniserde_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
Resource::new_with_options(source, fetcher, true)
}
}
#[cfg(feature = "serde-lite")]
@@ -1122,15 +843,6 @@ where
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_serde_lite<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1143,19 +855,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_serde_lite_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1181,15 +880,6 @@ where
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_rkyv<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1202,19 +892,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_rkyv_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1238,21 +915,6 @@ where
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding `Ser`.
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// If `blocking` is `true`, this is a blocking resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -1275,8 +937,6 @@ where
}
}
/// Synchronously, reactively reads the current value of the resource and applies the function
/// `f` to its value if it is `Some(_)`.
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U> {
self.data
.try_with(|n| n.as_ref().map(|n| Some(f(n))))?
@@ -1301,13 +961,6 @@ where
T: Send + Sync,
E: Send + Sync + Clone,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
@@ -1331,8 +984,6 @@ impl<T, Ser> Resource<T, Ser>
where
T: Send + Sync + 'static,
{
/// Returns a new [`Future`] that is ready when the resource has loaded, and accesses its inner
/// value by reference.
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
self.data.by_ref()
}

View File

@@ -31,7 +31,6 @@ pub struct SharedValue<T, Ser = JsonSerdeCodec> {
}
impl<T, Ser> SharedValue<T, Ser> {
/// Returns the inner value.
pub fn into_inner(self) -> T {
self.value
}
@@ -47,12 +46,6 @@ where
<<JsonSerdeCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`JsonSerdeCodec`] encoding.
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
@@ -68,12 +61,6 @@ where
<<FromToStringCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`FromToStringCodec`] encoding.
pub fn new_str(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
@@ -90,13 +77,7 @@ where
<<SerdeLite<JsonSerdeCodec> as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`SerdeLite`] encoding.
pub fn new_serde_lite(initial: impl FnOnce() -> T) -> Self {
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
@@ -112,13 +93,7 @@ where
<<JsonSerdeWasmCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`JsonSerdeWasmCodec`] encoding.
pub fn new_serde_wb(initial: impl FnOnce() -> T) -> Self {
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
@@ -134,13 +109,7 @@ where
<<MiniserdeCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`MiniserdeCodec`] encoding.
pub fn new_miniserde(initial: impl FnOnce() -> T) -> Self {
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
@@ -156,13 +125,7 @@ where
<<RkyvCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`RkyvCodec`] encoding.
pub fn new_rkyv(initial: impl FnOnce() -> T) -> Self {
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
@@ -177,12 +140,6 @@ where
<<Ser as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses `Ser` as an encoding.
pub fn new_with_encoding(initial: impl FnOnce() -> T) -> Self {
let value: T;
#[cfg(feature = "hydration")]

View File

@@ -1,6 +1,6 @@
[package]
name = "leptos_meta"
version = "0.7.0"
version = "0.7.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
repository = "https://github.com/leptos-rs/leptos"

View File

@@ -7,7 +7,8 @@
//! using the [`Leptos`](https://github.com/leptos-rs/leptos) web framework.
//!
//! Document metadata is updated automatically when running in the browser. For server-side
//! rendering, after the component tree is rendered to HTML, [`ServerMetaContextOutput::inject_meta_context`] will inject meta tags into a stream of HTML inside the `<head>`.
//! rendering, after the component tree is rendered to HTML, [`MetaContext::dehydrate`] can generate
//! HTML that should be injected into the `<head>` of the HTML document being rendered.
//!
//! ```
//! use leptos::prelude::*;

View File

@@ -1,6 +1,6 @@
[package]
name = "next_tuple"
version = "0.1.0"
version = "0.1.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"

View File

@@ -1,10 +1,6 @@
//! Defines a trait that allows you to extend a tuple, by returning
//! a new tuple with an element of an arbitrary type added.
#![no_std]
#![allow(non_snake_case)]
#![forbid(unsafe_code)]
#![deny(missing_docs)]
/// Allows extending a tuple, or creating a new tuple, by adding the next value.
pub trait NextTuple {

View File

@@ -70,7 +70,7 @@ pub enum Oco<'a, T: ?Sized + ToOwned + 'a> {
Owned(<T as ToOwned>::Owned),
}
impl<T: ?Sized + ToOwned> Oco<'_, T> {
impl<'a, T: ?Sized + ToOwned> Oco<'a, T> {
/// Converts the value into an owned value.
pub fn into_owned(self) -> <T as ToOwned>::Owned {
match self {
@@ -339,7 +339,7 @@ where
}
}
impl<'b, A: ?Sized, B: ?Sized> PartialEq<Oco<'b, B>> for Oco<'_, A>
impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<Oco<'b, B>> for Oco<'a, A>
where
A: PartialEq<B>,
A: ToOwned,
@@ -352,7 +352,7 @@ where
impl<T: ?Sized + ToOwned + Eq> Eq for Oco<'_, T> {}
impl<'b, A: ?Sized, B: ?Sized> PartialOrd<Oco<'b, B>> for Oco<'_, A>
impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<Oco<'b, B>> for Oco<'a, A>
where
A: PartialOrd<B>,
A: ToOwned,
@@ -551,7 +551,7 @@ impl_slice_eq!(['a, 'b, T: PartialEq] (where [T]: ToOwned), Oco<'a, [T]>, &'b [T
impl_slice_eq!([T: PartialEq] (where [T]: ToOwned), Oco<'_, [T]>, Vec<T>);
impl_slice_eq!(['a, 'b, T: PartialEq] (where [T]: ToOwned), Oco<'a, [T]>, Cow<'b, [T]>);
impl<'b> Add<&'b str> for Oco<'_, str> {
impl<'a, 'b> Add<&'b str> for Oco<'a, str> {
type Output = Oco<'static, str>;
fn add(self, rhs: &'b str) -> Self::Output {
@@ -559,7 +559,7 @@ impl<'b> Add<&'b str> for Oco<'_, str> {
}
}
impl<'b> Add<Cow<'b, str>> for Oco<'_, str> {
impl<'a, 'b> Add<Cow<'b, str>> for Oco<'a, str> {
type Output = Oco<'static, str>;
fn add(self, rhs: Cow<'b, str>) -> Self::Output {
@@ -567,7 +567,7 @@ impl<'b> Add<Cow<'b, str>> for Oco<'_, str> {
}
}
impl<'b> Add<Oco<'b, str>> for Oco<'_, str> {
impl<'a, 'b> Add<Oco<'b, str>> for Oco<'a, str> {
type Output = Oco<'static, str>;
fn add(self, rhs: Oco<'b, str>) -> Self::Output {

View File

@@ -21,6 +21,6 @@ CREATE TABLE IF NOT EXISTS google_tokens (
access_secret TEXT NOT NULL,
refresh_secret TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
FOREIGN KEY (user_id) REFERENCES users(id) CONFLICT REPLACE
);

View File

@@ -64,7 +64,7 @@ pub async fn refresh_token(email: String) -> Result<u64, ServerFnError> {
.execute(&pool)
.await?;
sqlx::query(
"INSERT OR REPLACE INTO google_tokens (user_id,access_secret,refresh_secret) \
"INSERT INTO google_tokens (user_id,access_secret,refresh_secret) \
VALUES (?,?,?)",
)
.bind(user.id)

View File

@@ -96,7 +96,7 @@ async fn main() {
let client = oauth2::basic::BasicClient::new(
oauth2::ClientId::new(
std::env::var("G_AUTH_CLIENT_ID")
.expect("G_AUTH_CLIENT_ID Env var to be set."),
.expect("G_AUTH_CLIENT Env var to be set."),
),
Some(oauth2::ClientSecret::new(
std::env::var("G_AUTH_SECRET")

View File

@@ -1,6 +1,6 @@
[package]
name = "reactive_graph"
version = "0.1.0"
version = "0.1.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"

View File

@@ -19,7 +19,7 @@ pub(crate) use inner::MemoInner;
pub use memo::*;
pub use selector::*;
/// Derives a reactive slice of an [`RwSignal`].
/// Derives a reactive slice of an [`RwSignal`](crate::signal::RwSignal).
///
/// Slices have the same guarantees as [`Memo`s](crate::computed::Memo):
/// they only emit their value when it has actually been changed.

View File

@@ -117,7 +117,6 @@ pub struct ArcAsyncDerived<T> {
pub(crate) loading: Arc<AtomicBool>,
}
#[allow(dead_code)]
pub(crate) trait BlockingLock<T> {
fn blocking_read_arc(self: &Arc<Self>)
-> async_lock::RwLockReadGuardArc<T>;
@@ -584,17 +583,19 @@ impl<T: 'static> ReadUntracked for ArcAsyncDerived<T> {
fn try_read_untracked(&self) -> Option<Self::Value> {
if let Some(suspense_context) = use_context::<SuspenseContext>() {
let handle = suspense_context.task_id();
let ready = SpecialNonReactiveFuture::new(self.ready());
crate::spawn(async move {
ready.await;
drop(handle);
});
self.inner
.write()
.or_poisoned()
.suspenses
.push(suspense_context);
if self.value.blocking_read().is_none() {
let handle = suspense_context.task_id();
let ready = SpecialNonReactiveFuture::new(self.ready());
crate::spawn(async move {
ready.await;
drop(handle);
});
self.inner
.write()
.or_poisoned()
.suspenses
.push(suspense_context);
}
}
AsyncPlain::try_new(&self.value).map(ReadGuard::new)
}

View File

@@ -124,7 +124,7 @@ pub fn log_warning(text: Arguments) {
}
}
/// Calls [`Executor::spawn`](any_spawner::Executor), but ensures that the task also runs in the current arena, if
/// Calls [`Executor::spawn`], but ensures that the task also runs in the current arena, if
/// multithreaded arena sandboxing is enabled.
pub fn spawn(task: impl Future<Output = ()> + Send + 'static) {
#[cfg(feature = "sandboxed-arenas")]
@@ -133,9 +133,8 @@ pub fn spawn(task: impl Future<Output = ()> + Send + 'static) {
any_spawner::Executor::spawn(task);
}
/// Calls [`Executor::spawn_local`](any_spawner::Executor), but ensures that the task runs under the current reactive [`Owner`](crate::owner::Owner) and observer.
///
/// Does not cancel the task if the owner is cleaned up.
/// Calls [`Executor::spawn_local`], but ensures that the task runs under the current reactive [`Owner`]
/// and [`Observed`]. Does not cancel the task if the owner is cleaned up.
pub fn spawn_local_scoped(task: impl Future<Output = ()> + 'static) {
let task = ScopedFuture::new(task);
@@ -145,9 +144,8 @@ pub fn spawn_local_scoped(task: impl Future<Output = ()> + 'static) {
any_spawner::Executor::spawn_local(task);
}
/// Calls [`Executor::spawn_local`](any_spawner::Executor), but ensures that the task runs under the current reactive [`Owner`](crate::owner::Owner) and observer.
///
/// Cancels the task if the owner is cleaned up.
/// Calls [`Executor::spawn_local`], but ensures that the task runs under the current reactive [`Owner`]
/// and [`Observed`]. Cancels the task if the owner is cleaned up.
pub fn spawn_local_scoped_with_cancellation(
task: impl Future<Output = ()> + 'static,
) {

View File

@@ -30,7 +30,7 @@ impl<T> StorageAccess<T> for SendWrapper<T> {
}
}
/// A way of storing an [`ArenaItem`](super::arena_item::ArenaItem), either as itself or with a wrapper to make it threadsafe.
/// A way of storing a [`ArenaItem`], either as itself or with a wrapper to make it threadsafe.
///
/// This exists because all items stored in the arena must be `Send + Sync`, but in single-threaded
/// environments you might want or need to use thread-unsafe types.

View File

@@ -220,7 +220,7 @@ where
}
}
/// Helper trait to implement flatten() on `Option<&Option<T>>`.
/// Helper trait to implement flatten() on Option<&Option<T>>.
pub trait FlattenOptionRefOption {
/// The type of the value contained in the double option.
type Value;

View File

@@ -16,7 +16,7 @@
//! | Trait | Mode | Description |
//! |-------------------|-------|---------------------------------------------------------------------------------------|
//! | [`Track`] | — | Tracks changes to this value, adding it as a source of the current reactive observer. |
//! | [`Notify`] | — | Notifies subscribers that this value has changed. |
//! | [`Trigger`] | — | Notifies subscribers that this value has changed. |
//! | [`ReadUntracked`] | Guard | Gives immutable access to the value of this signal. |
//! | [`Write`] | Guard | Gives mutable access to the value of this signal.
//!
@@ -34,7 +34,7 @@
//! | Trait | Mode | Composition | Description
//! |---------------------|---------------|-----------------------------------|------------
//! | [`UpdateUntracked`] | `fn(&mut T)` | [`Write`] | Applies closure to the current value to update it, but doesn't notify subscribers.
//! | [`Update`] | `fn(&mut T)` | [`UpdateUntracked`] + [`Notify`] | Applies closure to the current value to update it, and notifies subscribers.
//! | [`Update`] | `fn(&mut T)` | [`UpdateUntracked`] + [`Trigger`] | Applies closure to the current value to update it, and notifies subscribers.
//! | [`Set`] | `T` | [`Update`] | Sets the value to a new value, and notifies subscribers.
//!
//! ## Using the Traits

View File

@@ -1,6 +1,6 @@
[package]
name = "reactive_stores"
version = "0.1.0"
version = "0.1.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"

View File

@@ -7,7 +7,6 @@ use reactive_graph::{
owner::Storage,
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Write,
},
};
use std::{
@@ -18,10 +17,6 @@ use std::{
sync::Arc,
};
/// Reference-counted access to a single field of type `T`.
///
/// This can be used to erase the chain of field-accessors, to make it easier to pass this into
/// another component or function without needing to specify the full type signature.
pub struct ArcField<T>
where
T: 'static,
@@ -32,8 +27,7 @@ where
trigger: StoreFieldTrigger,
get_trigger: Arc<dyn Fn(StorePath) -> StoreFieldTrigger + Send + Sync>,
read: Arc<dyn Fn() -> Option<StoreFieldReader<T>> + Send + Sync>,
pub(crate) write:
Arc<dyn Fn() -> Option<StoreFieldWriter<T>> + Send + Sync>,
write: Arc<dyn Fn() -> Option<StoreFieldWriter<T>> + Send + Sync>,
keys: Arc<dyn Fn() -> Option<KeyMap> + Send + Sync>,
track_field: Arc<dyn Fn() + Send + Sync>,
}
@@ -331,22 +325,6 @@ impl<T> ReadUntracked for ArcField<T> {
}
}
impl<T> Write for ArcField<T> {
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
(self.write)()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
let mut guard = (self.write)()?;
guard.untrack();
Some(guard)
}
}
impl<T> IsDisposed for ArcField<T> {
fn is_disposed(&self) -> bool {
false

View File

@@ -6,23 +6,11 @@ use crate::{
};
use reactive_graph::{
owner::{ArenaItem, Storage, SyncStorage},
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Write,
},
traits::{DefinedAt, IsDisposed, Notify, ReadUntracked, Track},
unwrap_signal,
};
use std::{
fmt::Debug,
hash::Hash,
ops::{DerefMut, IndexMut},
panic::Location,
};
use std::{fmt::Debug, hash::Hash, ops::IndexMut, panic::Location};
/// Wraps access to a single field of type `T`.
///
/// This can be used to erase the chain of field-accessors, to make it easier to pass this into
/// another component or function without needing to specify the full type signature.
pub struct Field<T, S = SyncStorage>
where
T: 'static,
@@ -212,24 +200,6 @@ where
}
}
impl<T> Write for Field<T> {
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.inner.try_get_value().and_then(|inner| (inner.write)())
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.inner.try_get_value().and_then(|inner| {
let mut guard = (inner.write)()?;
guard.untrack();
Some(guard)
})
}
}
impl<T, S> IsDisposed for Field<T, S> {
fn is_disposed(&self) -> bool {
self.inner.is_disposed()

View File

@@ -20,7 +20,6 @@ use std::{
panic::Location,
};
/// Provides access to the data at some index in another collection.
#[derive(Debug)]
pub struct AtIndex<Inner, Prev> {
#[cfg(debug_assertions)]
@@ -48,7 +47,6 @@ where
impl<Inner, Prev> Copy for AtIndex<Inner, Prev> where Inner: Copy {}
impl<Inner, Prev> AtIndex<Inner, Prev> {
/// Creates a new accessor for the inner collection at the given index.
#[track_caller]
pub fn new(inner: Inner, index: usize) -> Self {
Self {
@@ -193,15 +191,12 @@ where
}
}
/// Provides unkeyed reactive access to the fields of some collection.
pub trait StoreFieldIterator<Prev>
where
Self: StoreField<Value = Prev>,
{
/// Reactive access to the value at some index.
fn at_unkeyed(self, index: usize) -> AtIndex<Self, Prev>;
/// An iterator over the values in the collection.
fn iter_unkeyed(self) -> StoreFieldIter<Self, Prev>;
}
@@ -236,7 +231,6 @@ where
}
}
/// An iterator over the values in a collection, as reactive fields.
pub struct StoreFieldIter<Inner, Prev> {
inner: Inner,
idx: usize,

View File

@@ -22,7 +22,6 @@ use std::{
panic::Location,
};
/// Provides access to a subfield that contains some kind of keyed collection.
#[derive(Debug)]
pub struct KeyedSubfield<Inner, Prev, K, T>
where
@@ -66,7 +65,6 @@ impl<Inner, Prev, K, T> KeyedSubfield<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
{
/// Creates a keyed subfield of the inner data type with the given key function.
#[track_caller]
pub fn new(
inner: Inner,
@@ -156,7 +154,6 @@ where
}
}
/// Gives keyed write access to a value in some collection.
pub struct KeyedSubfieldWriteGuard<Inner, Prev, K, T, Guard>
where
KeyedSubfield<Inner, Prev, K, T>: Clone,
@@ -350,7 +347,6 @@ where
}
}
/// Gives access to the value in a collection based on some key.
#[derive(Debug)]
pub struct AtKeyed<Inner, Prev, K, T>
where
@@ -390,7 +386,6 @@ impl<Inner, Prev, K, T> AtKeyed<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
{
/// Provides access to the item in the inner collection at this key.
#[track_caller]
pub fn new(inner: KeyedSubfield<Inner, Prev, K, T>, key: K) -> Self {
Self {
@@ -615,7 +610,6 @@ where
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
/// Generates a new set of keys and registers those keys with the parent store.
pub fn update_keys(&self) {
let inner_path = self.path().into_iter().collect();
let keys = self
@@ -666,7 +660,6 @@ where
}
}
/// An iterator over a [`KeyedSubfield`].
pub struct StoreFieldKeyedIter<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,

View File

@@ -1,111 +1,3 @@
#![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Stores are a primitive for creating deeply-nested reactive state, based on [`reactive_graph`].
//!
//! Reactive signals allow you to define atomic units of reactive state. However, signals are
//! imperfect as a mechanism for tracking reactive change in structs or collections, because
//! they do not allow you to track access to individual struct fields or individual items in a
//! collection, rather than the struct as a whole or the collection as a whole. Reactivity for
//! individual fields can be achieved by creating a struct of signals, but this has issues; it
//! means that a struct is no longer a plain data structure, but requires wrappers on each field.
//!
//! Stores attempt to solve this problem by allowing arbitrarily-deep access to the fields of some
//! data structure, while still maintaining fine-grained reactivity.
//!
//! The [`Store`](macro@Store) macro adds getters and setters for the fields of a struct. Call those getters or
//! setters on a reactive [`Store`](struct@Store) or [`ArcStore`], or to a subfield, gives you
//! access to a reactive subfield. This value of this field can be accessed via the ordinary signal
//! traits (`Get`, `Set`, and so on).
//!
//! The [`Patch`](macro@Patch) macro allows you to annotate a struct such that stores and fields have a
//! [`.patch()`](Patch::patch) method, which allows you to provide an entirely new value, but only
//! notify fields that have changed.
//!
//! Updating a field will notify its parents and children, but not its siblings.
//!
//! Stores can therefore
//! 1) work with plain Rust data types, and
//! 2) provide reactive access to individual fields
//!
//! ### Example
//!
//! ```rust
//! use reactive_graph::{
//! effect::Effect,
//! traits::{Read, Write},
//! };
//! use reactive_stores::{Patch, Store};
//!
//! #[derive(Debug, Store, Patch, Default)]
//! struct Todos {
//! user: String,
//! todos: Vec<Todo>,
//! }
//!
//! #[derive(Debug, Store, Patch, Default)]
//! struct Todo {
//! label: String,
//! completed: bool,
//! }
//!
//! let store = Store::new(Todos {
//! user: "Alice".to_string(),
//! todos: Vec::new(),
//! });
//!
//! # if false { // don't run effect in doctests
//! Effect::new(move |_| {
//! // you can access individual store withs field a getter
//! println!("todos: {:?}", &*store.todos().read());
//! });
//! # }
//!
//! // won't notify the effect that listen to `todos`
//! store.todos().write().push(Todo {
//! label: "Test".to_string(),
//! completed: false,
//! });
//! ```
//!
//! ### Implementation Notes
//!
//! Every struct field can be understood as an index. For example, given the following definition
//! ```rust
//! # use reactive_stores::{Store, Patch};
//! #[derive(Debug, Store, Patch, Default)]
//! struct Name {
//! first: String,
//! last: String,
//! }
//! ```
//! We can think of `first` as `0` and `last` as `1`. This means that any deeply-nested field of a
//! struct can be described as a path of indices. So, for example:
//! ```rust
//! # use reactive_stores::{Store, Patch};
//! #[derive(Debug, Store, Patch, Default)]
//! struct User {
//! user: Name,
//! }
//!
//! #[derive(Debug, Store, Patch, Default)]
//! struct Name {
//! first: String,
//! last: String,
//! }
//! ```
//! Here, given a `User`, `first` can be understood as [`0`, `0`] and `last` is [`0`, `1`].
//!
//! This means we can implement a store as the combination of two things:
//! 1) An `Arc<RwLock<T>>` that holds the actual value
//! 2) A map from field paths to reactive "triggers," which are signals that have no value but
//! track reactivity
//!
//! Accessing a field via its getters returns an iterator-like data structure that describes how to
//! get to that subfield. Calling `.read()` returns a guard that dereferences to the value of that
//! field in the signal inner `Arc<RwLock<_>>`, and tracks the trigger that corresponds with its
//! path; calling `.write()` returns a writeable guard, and notifies that same trigger.
use or_poisoned::OrPoisoned;
use reactive_graph::{
owner::{ArenaItem, LocalStorage, Storage, SyncStorage},
@@ -118,7 +10,7 @@ use reactive_graph::{
Write,
},
};
pub use reactive_stores_macro::{Patch, Store};
pub use reactive_stores_macro::*;
use rustc_hash::FxHashMap;
use std::{
any::Any,
@@ -153,15 +45,13 @@ pub use subfield::Subfield;
#[derive(Debug, Default)]
struct TriggerMap(FxHashMap<StorePath, StoreFieldTrigger>);
/// The reactive trigger that can be used to track updates to a store field.
#[derive(Debug, Clone, Default)]
pub struct StoreFieldTrigger {
pub(crate) this: ArcTrigger,
pub(crate) children: ArcTrigger,
pub this: ArcTrigger,
pub children: ArcTrigger,
}
impl StoreFieldTrigger {
/// Creates a new trigger.
pub fn new() -> Self {
Self::default()
}
@@ -184,8 +74,7 @@ impl TriggerMap {
}
}
/// Manages the keys for a keyed field, including the ability to remove and reuse keys.
pub(crate) struct FieldKeys<K> {
pub struct FieldKeys<K> {
spare_keys: Vec<StorePathSegment>,
current_key: usize,
keys: FxHashMap<K, (StorePathSegment, usize)>,
@@ -195,7 +84,6 @@ impl<K> FieldKeys<K>
where
K: Debug + Hash + PartialEq + Eq,
{
/// Creates a new set of keys.
pub fn new(from_keys: Vec<K>) -> Self {
let mut keys = FxHashMap::with_capacity_and_hasher(
from_keys.len(),
@@ -218,7 +106,7 @@ impl<K> FieldKeys<K>
where
K: Hash + PartialEq + Eq,
{
fn get(&self, key: &K) -> Option<(StorePathSegment, usize)> {
pub fn get(&self, key: &K) -> Option<(StorePathSegment, usize)> {
self.keys.get(key).copied()
}
@@ -229,7 +117,7 @@ where
})
}
fn update(&mut self, iter: impl IntoIterator<Item = K>) {
pub fn update(&mut self, iter: impl IntoIterator<Item = K>) {
let new_keys = iter
.into_iter()
.enumerate()
@@ -271,12 +159,11 @@ impl<K> Default for FieldKeys<K> {
}
}
/// A map of the keys for a keyed subfield.
#[derive(Default, Clone)]
pub struct KeyMap(Arc<RwLock<HashMap<StorePath, Box<dyn Any + Send + Sync>>>>);
impl KeyMap {
fn with_field_keys<K, T>(
pub fn with_field_keys<K, T>(
&self,
path: StorePath,
fun: impl FnOnce(&mut FieldKeys<K>) -> T,
@@ -308,12 +195,6 @@ impl KeyMap {
}
}
/// A reference-counted container for a reactive store.
///
/// The type `T` should be a struct that has been annotated with `#[derive(Store)]`.
///
/// This adds a getter method for each field to `Store<T>`, which allow accessing reactive versions
/// of each individual field of the struct.
pub struct ArcStore<T> {
#[cfg(debug_assertions)]
defined_at: &'static Location<'static>,
@@ -323,7 +204,6 @@ pub struct ArcStore<T> {
}
impl<T> ArcStore<T> {
/// Creates a new store from the initial value.
pub fn new(value: T) -> Self {
Self {
#[cfg(debug_assertions)]
@@ -423,15 +303,6 @@ impl<T: 'static> Notify for ArcStore<T> {
}
}
/// An arena-allocated container for a reactive store.
///
/// The type `T` should be a struct that has been annotated with `#[derive(Store)]`.
///
/// This adds a getter method for each field to `Store<T>`, which allow accessing reactive versions
/// of each individual field of the struct.
///
/// This follows the same ownership rules as arena-allocated types like
/// [`RwSignal`](reactive_graph::signal::RwSignal).
pub struct Store<T, S = SyncStorage> {
#[cfg(debug_assertions)]
defined_at: &'static Location<'static>,
@@ -442,7 +313,6 @@ impl<T> Store<T>
where
T: Send + Sync + 'static,
{
/// Creates a new store with the initial value.
pub fn new(value: T) -> Self {
Self {
#[cfg(debug_assertions)]
@@ -456,9 +326,6 @@ impl<T> Store<T, LocalStorage>
where
T: 'static,
{
/// Creates a new store for a type that is `!Send`.
///
/// This pins the value to the current thread. Accessing it from any other thread will panic.
pub fn new_local(value: T) -> Self {
Self {
#[cfg(debug_assertions)]

View File

@@ -1,45 +1,25 @@
use crate::{StoreField, Subfield};
use reactive_graph::traits::{Read, ReadUntracked};
use reactive_graph::traits::Read;
use std::ops::Deref;
/// Extends optional store fields, with the ability to unwrap or map over them.
pub trait OptionStoreExt
where
Self: StoreField<Value = Option<Self::Output>>,
{
/// The inner type of the `Option<_>` this field holds.
type Output;
/// Provides access to the inner value, as a subfield, unwrapping the outer value.
fn unwrap(self) -> Subfield<Self, Option<Self::Output>, Self::Output>;
/// Reactively maps over the field.
///
/// This returns `None` if the subfield is currently `None`,
/// and a new store subfield with the inner value if it is `Some`. This can be used in some
/// other reactive context, which will cause it to re-run if the field toggles betwen `None`
/// and `Some(_)`.
fn map<U>(
self,
map_fn: impl FnOnce(Subfield<Self, Option<Self::Output>, Self::Output>) -> U,
) -> Option<U>;
/// Unreactively maps over the field.
///
/// This returns `None` if the subfield is currently `None`,
/// and a new store subfield with the inner value if it is `Some`. This is an unreactive variant of
/// `[OptionStoreExt::map]`, and will not cause the reactive context to re-run if the field changes.
fn map_untracked<U>(
self,
map_fn: impl FnOnce(Subfield<Self, Option<Self::Output>, Self::Output>) -> U,
) -> Option<U>;
}
impl<T, S> OptionStoreExt for S
where
S: StoreField<Value = Option<T>> + Read + ReadUntracked,
S: StoreField<Value = Option<T>> + Read,
<S as Read>::Value: Deref<Target = Option<T>>,
<S as ReadUntracked>::Value: Deref<Target = Option<T>>,
{
type Output = T;
@@ -62,17 +42,6 @@ where
None
}
}
fn map_untracked<U>(
self,
map_fn: impl FnOnce(Subfield<S, Option<T>, T>) -> U,
) -> Option<U> {
if self.read_untracked().is_some() {
Some(map_fn(self.unwrap()))
} else {
None
}
}
}
#[cfg(test)]

View File

@@ -13,12 +13,9 @@ use std::{
sync::Arc,
};
/// Allows updating a store or field in place with a new value.
pub trait Patch {
/// The type of the new value.
type Value;
/// Patches a store or field with a new value, only notifying fields that have changed.
fn patch(&self, new: Self::Value);
}
@@ -45,7 +42,6 @@ where
/// Allows patching a store field with some new value.
pub trait PatchField {
/// Patches the field with some new value, only notifying if the value has changed.
fn patch_field(
&mut self,
new: Self,

View File

@@ -1,4 +1,3 @@
/// The path of a field within some store.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct StorePath(Vec<StorePathSegment>);
@@ -18,17 +17,14 @@ impl From<Vec<StorePathSegment>> for StorePath {
}
impl StorePath {
/// Adds a new segment to the path.
pub fn push(&mut self, segment: impl Into<StorePathSegment>) {
self.0.push(segment.into());
}
/// Removes a segment from the path and returns it.
pub fn pop(&mut self) -> Option<StorePathSegment> {
self.0.pop()
}
/// Updates the last segment in the place in place.
pub fn replace_last(&mut self, segment: impl Into<StorePathSegment>) {
if let Some(last) = self.0.last_mut() {
*last = segment.into();
@@ -36,7 +32,6 @@ impl StorePath {
}
}
/// One segment of a [`StorePath`].
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct StorePathSegment(pub(crate) usize);

View File

@@ -14,22 +14,15 @@ use reactive_graph::{
};
use std::{iter, ops::Deref, sync::Arc};
/// Describes a type that can be accessed as a reactive store field.
pub trait StoreField: Sized {
/// The value this field contains.
type Value;
/// A read guard to access this field.
type Reader: Deref<Target = Self::Value>;
/// A write guard to update this field.
type Writer: UntrackableGuard<Target = Self::Value>;
/// Returns the trigger that tracks access and updates for this field.
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger;
/// The path of this field (see [`StorePath`]).
fn path(&self) -> impl IntoIterator<Item = StorePathSegment>;
/// Reactively tracks this field.
fn track_field(&self) {
let path = self.path().into_iter().collect();
let trigger = self.get_trigger(path);
@@ -37,13 +30,10 @@ pub trait StoreField: Sized {
trigger.children.track();
}
/// Returns a read guard to access this field.
fn reader(&self) -> Option<Self::Reader>;
/// Returns a write guard to update this field.
fn writer(&self) -> Option<Self::Writer>;
/// The keys for this field, if it is a keyed field.
fn keys(&self) -> Option<KeyMap>;
}

View File

@@ -15,7 +15,6 @@ use reactive_graph::{
};
use std::{iter, marker::PhantomData, ops::DerefMut, panic::Location};
/// Accesses a single field of a reactive structure.
#[derive(Debug)]
pub struct Subfield<Inner, Prev, T> {
#[cfg(debug_assertions)]
@@ -47,7 +46,6 @@ where
impl<Inner, Prev, T> Copy for Subfield<Inner, Prev, T> where Inner: Copy {}
impl<Inner, Prev, T> Subfield<Inner, Prev, T> {
/// Creates an accessor for a single field of the inner structure.
#[track_caller]
pub fn new(
inner: Inner,

View File

@@ -1,6 +1,6 @@
[package]
name = "reactive_stores_macro"
version = "0.1.0"
version = "0.1.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"

View File

@@ -1,6 +1,6 @@
[package]
name = "leptos_router"
version = "0.7.0"
version = "0.7.0-rc1"
authors = ["Greg Johnston", "Ben Wishovich"]
license = "MIT"
readme = "../README.md"

View File

@@ -11,10 +11,10 @@ use crate::{
navigate::NavigateOptions,
nested_router::NestedRoutesView,
resolve_path::resolve_path,
ChooseView, MatchNestedRoutes, NestedRoute, RouteDefs, SsrMode,
ChooseView, MatchNestedRoutes, NestedRoute, Routes, SsrMode,
};
use either_of::EitherOf3;
use leptos::{children, prelude::*};
use either_of::Either;
use leptos::prelude::*;
use reactive_graph::{
owner::{provide_context, use_context, Owner},
signal::ArcRwSignal,
@@ -30,13 +30,10 @@ use std::{
};
use tachys::view::any_view::AnyView;
/// A wrapper that allows passing route definitions as children to a component like [`Routes`],
/// [`FlatRoutes`], [`ParentRoute`], or [`ProtectedParentRoute`].
#[derive(Debug)]
pub struct RouteChildren<Children>(Children);
impl<Children> RouteChildren<Children> {
/// Extracts the inner route definition.
pub fn into_inner(self) -> Children {
self.0
}
@@ -64,8 +61,8 @@ pub fn Router<Chil>(
//#[prop(optional)]
//trailing_slash: TrailingSlash,
/// The `<Router/>` should usually wrap your whole page. It can contain
/// any elements, and should include a [`Routes`] component somewhere
/// to define and display [`Route`]s.
/// any elements, and should include a [`Routes`](crate::Routes) component somewhere
/// to define and display [`Route`](crate::Route)s.
children: TypedChildren<Chil>,
) -> impl IntoView
where
@@ -214,15 +211,30 @@ impl Debug for RouterContext {
}
}
/*
#[component]
pub fn FlatRouter<Children, FallbackFn, Fallback>(
#[prop(optional, into)] base: Option<Cow<'static, str>>,
fallback: FallbackFn,
children: RouteChildren<Children>,
) -> FlatRouter<Dom, BrowserUrl, Children, FallbackFn>
where
FallbackFn: Fn() -> Fallback,
{
let children = Routes::new(children.into_inner());
if let Some(base) = base {
FlatRouter::new_with_base(base, children, fallback)
} else {
FlatRouter::new(children, fallback)
}
}*/
#[component(transparent)]
pub fn Routes<Defs, FallbackFn, Fallback>(
/// A function that returns the view that should be shown if no route is matched.
fallback: FallbackFn,
/// Whether to use the View Transition API during navigation.
#[prop(optional)]
transition: bool,
/// The route definitions. This should consist of one or more [`ParentRoute`] or [`Route`]
/// components.
children: RouteChildren<Defs>,
) -> impl IntoView
where
@@ -243,7 +255,7 @@ where
base.upgrade_inplace();
base
});
let routes = RouteDefs::new_with_base(
let routes = Routes::new_with_base(
children.into_inner(),
base.clone().unwrap_or_default(),
);
@@ -269,13 +281,10 @@ where
#[component(transparent)]
pub fn FlatRoutes<Defs, FallbackFn, Fallback>(
/// A function that returns the view that should be shown if no route is matched.
fallback: FallbackFn,
/// Whether to use the View Transition API during navigation.
#[prop(optional)]
transition: bool,
/// The route definitions. This should consist of one or more [`ParentRoute`] or [`Route`]
/// components.
children: RouteChildren<Defs>,
) -> impl IntoView
where
@@ -299,7 +308,7 @@ where
base.upgrade_inplace();
base
});
let routes = RouteDefs::new_with_base(
let routes = Routes::new_with_base(
children.into_inner(),
base.clone().unwrap_or_default(),
);
@@ -324,21 +333,11 @@ where
}
}
/// Describes a portion of the nested layout of the app, specifying the route it should match
/// and the element it should display.
#[component(transparent)]
pub fn Route<Segments, View>(
/// The path fragment that this route should match. This can be created using the
/// [`path`](crate::path) macro, or path segments ([`StaticSegment`](crate::StaticSegment),
/// [`ParamSegment`](crate::ParamSegment), [`WildcardSegment`](crate::WildcardSegment), and
/// [`OptionalParamSegment`](crate::OptionalParamSegment)).
path: Segments,
/// The view for this route.
view: View,
/// The mode that this route prefers during server-side rendering.
/// Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
#[prop(optional)] ssr: SsrMode,
) -> NestedRoute<Segments, (), (), View>
where
View: ChooseView,
@@ -346,23 +345,12 @@ where
NestedRoute::new(path, view).ssr_mode(ssr)
}
/// Describes a portion of the nested layout of the app, specifying the route it should match
/// and the element it should display.
#[component(transparent)]
pub fn ParentRoute<Segments, View, Children>(
/// The path fragment that this route should match. This can be created using the
/// [`path`](crate::path) macro, or path segments ([`StaticSegment`](crate::StaticSegment),
/// [`ParamSegment`](crate::ParamSegment), [`WildcardSegment`](crate::WildcardSegment), and
/// [`OptionalParamSegment`](crate::OptionalParamSegment)).
path: Segments,
/// The view for this route.
view: View,
/// Nested child routes.
children: RouteChildren<Children>,
/// The mode that this route prefers during server-side rendering.
/// Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
#[prop(optional)] ssr: SsrMode,
) -> NestedRoute<Segments, Children, (), View>
where
View: ChooseView,
@@ -371,31 +359,13 @@ where
NestedRoute::new(path, view).ssr_mode(ssr).child(children)
}
/// Describes a route that is guarded by a certain condition. This works the same way as
/// [`<Route/>`], except that if the `condition` function evaluates to `Some(false)`, it
/// redirects to `redirect_path` instead of displaying its `view`.
#[component(transparent)]
pub fn ProtectedRoute<Segments, ViewFn, View, C, PathFn, P>(
/// The path fragment that this route should match. This can be created using the
/// [`path`](crate::path) macro, or path segments ([`StaticSegment`](crate::StaticSegment),
/// [`ParamSegment`](crate::ParamSegment), [`WildcardSegment`](crate::WildcardSegment), and
/// [`OptionalParamSegment`](crate::OptionalParamSegment)).
path: Segments,
/// The view for this route.
view: ViewFn,
/// A function that returns `Option<bool>`, where `Some(true)` means that the user can access
/// the page, `Some(false)` means the user cannot access the page, and `None` means this
/// information is still loading.
condition: C,
/// The path that will be redirected to if the condition is `Some(false)`.
redirect_path: PathFn,
/// Will be displayed while the condition is pending. By default this is the empty view.
#[prop(optional, into)]
fallback: children::ViewFn,
/// The mode that this route prefers during server-side rendering.
/// Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
#[prop(optional)] ssr: SsrMode,
) -> NestedRoute<Segments, (), (), impl Fn() -> AnyView + Send + Clone>
where
ViewFn: Fn() -> View + Send + Clone + 'static,
@@ -404,26 +374,23 @@ where
PathFn: Fn() -> P + Send + Clone + 'static,
P: Display + 'static,
{
let fallback = move || fallback.run();
let view = move || {
let condition = condition.clone();
let redirect_path = redirect_path.clone();
let view = view.clone();
let fallback = fallback.clone();
(view! {
<Transition fallback=fallback.clone()>
<Transition>
{move || {
let condition = condition();
let view = view.clone();
let redirect_path = redirect_path.clone();
let fallback = fallback.clone();
Unsuspend::new(move || match condition {
Some(true) => EitherOf3::A(view()),
Some(true) => Either::Left(view()),
#[allow(clippy::unit_arg)]
Some(false) => {
EitherOf3::B(view! { <Redirect path=redirect_path()/> }.into_inner())
Either::Right(view! { <Redirect path=redirect_path()/> }.into_inner())
}
None => EitherOf3::C(fallback()),
None => Either::Right(()),
})
}}
@@ -436,28 +403,12 @@ where
#[component(transparent)]
pub fn ProtectedParentRoute<Segments, ViewFn, View, C, PathFn, P, Children>(
/// The path fragment that this route should match. This can be created using the
/// [`path`](crate::path) macro, or path segments ([`StaticSegment`](crate::StaticSegment),
/// [`ParamSegment`](crate::ParamSegment), [`WildcardSegment`](crate::WildcardSegment), and
/// [`OptionalParamSegment`](crate::OptionalParamSegment)).
path: Segments,
/// The view for this route.
view: ViewFn,
/// A function that returns `Option<bool>`, where `Some(true)` means that the user can access
/// the page, `Some(false)` means the user cannot access the page, and `None` means this
/// information is still loading.
condition: C,
/// Will be displayed while the condition is pending. By default this is the empty view.
#[prop(optional, into)]
fallback: children::ViewFn,
/// The path that will be redirected to if the condition is `Some(false)`.
redirect_path: PathFn,
/// Nested child routes.
children: RouteChildren<Children>,
/// The mode that this route prefers during server-side rendering.
/// Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
#[prop(optional)] ssr: SsrMode,
) -> NestedRoute<Segments, Children, (), impl Fn() -> AnyView + Send + Clone>
where
ViewFn: Fn() -> View + Send + Clone + 'static,
@@ -466,21 +417,17 @@ where
PathFn: Fn() -> P + Send + Clone + 'static,
P: Display + 'static,
{
let fallback = move || fallback.run();
let children = children.into_inner();
let view = move || {
let condition = condition.clone();
let redirect_path = redirect_path.clone();
let fallback = fallback.clone();
let view = view.clone();
let owner = Owner::current().unwrap();
let view = {
let fallback = fallback.clone();
move || {
let condition = condition();
let view = view.clone();
let redirect_path = redirect_path.clone();
let fallback = fallback.clone();
let owner = owner.clone();
Unsuspend::new(move || match condition {
// reset the owner so that things like providing context work
@@ -489,16 +436,16 @@ where
//
// clippy: not redundant, a FnOnce vs FnMut issue
#[allow(clippy::redundant_closure)]
Some(true) => EitherOf3::A(owner.with(|| view())),
Some(true) => Either::Left(owner.with(|| view())),
#[allow(clippy::unit_arg)]
Some(false) => EitherOf3::B(
Some(false) => Either::Right(
view! { <Redirect path=redirect_path()/> }.into_inner(),
),
None => EitherOf3::C(fallback()),
None => Either::Right(()),
})
}
};
(view! { <Transition fallback>{view}</Transition> }).into_any()
(view! { <Transition>{view}</Transition> }).into_any()
};
NestedRoute::new(path, view).ssr_mode(ssr).child(children)
}

View File

@@ -1,7 +1,7 @@
use crate::{
hooks::Matched,
location::{LocationProvider, Url},
matching::{MatchParams, RouteDefs},
matching::{MatchParams, Routes},
params::ParamsMap,
view_transition::start_view_transition,
ChooseView, MatchInterface, MatchNestedRoutes, PathSegment, RouteList,
@@ -33,15 +33,14 @@ use tachys::{
pub(crate) struct FlatRoutesView<Loc, Defs, FalFn> {
pub current_url: ArcRwSignal<Url>,
pub location: Option<Loc>,
pub routes: RouteDefs<Defs>,
pub routes: Routes<Defs>,
pub fallback: FalFn,
pub outer_owner: Owner,
pub set_is_routing: Option<SignalSetter<bool>>,
pub transition: bool,
}
/// Retained view state for the flat router.
pub(crate) struct FlatRoutesViewState {
pub struct FlatRoutesViewState {
#[allow(clippy::type_complexity)]
view: AnyViewState,
id: Option<RouteMatchId>,

View File

@@ -75,13 +75,11 @@ impl RouteListing {
}
}
/// Generates the set of static paths for this route listing, depending on prerendered params.
pub async fn into_static_paths(self) -> Option<Vec<ResolvedStaticPath>> {
let params = self.static_route()?.to_prerendered_params().await;
Some(StaticPath::new(self.path).into_paths(params))
}
/// Generates static files for this route listing.
pub async fn generate_static_files<Fut, WriterFut>(
mut self,
render_fn: impl Fn(&ResolvedStaticPath) -> Fut + Send + Clone + 'static,
@@ -150,7 +148,6 @@ impl RouteListing {
*/
}
/// A set of routes generated from the route definitions.
#[derive(Debug, Default, Clone)]
pub struct RouteList(Vec<RouteListing>);
@@ -161,29 +158,24 @@ impl From<Vec<RouteListing>> for RouteList {
}
impl RouteList {
/// Adds a route listing.
pub fn push(&mut self, data: RouteListing) {
self.0.push(data);
}
}
impl RouteList {
/// Creates an empty list of routes.
pub fn new() -> Self {
Self(Vec::new())
}
/// Returns the list of routes.
pub fn into_inner(self) -> Vec<RouteListing> {
self.0
}
/// Returns and iterator over the list of routes.
pub fn iter(&self) -> impl Iterator<Item = &RouteListing> {
self.0.iter()
}
/// Generates a list of resolved static paths based on the inner list of route listings.
pub async fn into_static_paths(self) -> Vec<ResolvedStaticPath> {
futures::future::join_all(
self.into_inner()
@@ -197,7 +189,6 @@ impl RouteList {
.collect::<Vec<_>>()
}
/// Generates static files for the inner list of route listings.
pub async fn generate_static_files<Fut, WriterFut>(
self,
render_fn: impl Fn(&ResolvedStaticPath) -> Fut + Send + Clone + 'static,
@@ -229,7 +220,6 @@ impl RouteList {
static GENERATED: RefCell<Option<RouteList>> = const { RefCell::new(None) };
}
/// Creates a list of routes, based on route definitions in the given app.
pub fn generate<T>(app: impl FnOnce() -> T) -> Option<Self>
where
T: RenderHtml,
@@ -243,12 +233,10 @@ impl RouteList {
Self::GENERATED.take()
}
/// Returns `true` if we are currently in a [`RouteList::generate`] call.
pub fn is_generating() -> bool {
Self::IS_GENERATING.get()
}
/// Sets the given routes as the list of generated routes.
pub fn register(routes: RouteList) {
Self::GENERATED.with(|inner| {
*inner.borrow_mut() = Some(routes);

View File

@@ -17,7 +17,6 @@ use std::{
sync::atomic::{AtomicBool, Ordering},
};
/// See [`query_signal`].
#[track_caller]
#[deprecated = "This has been renamed to `query_signal` to match Rust naming \
conventions."]
@@ -30,7 +29,6 @@ where
query_signal(key)
}
/// See [`query_signal_with_options`].
#[track_caller]
#[deprecated = "This has been renamed to `query_signal_with_options` to mtch \
Rust naming conventions."]
@@ -90,9 +88,6 @@ where
query_signal_with_options::<T>(key, NavigateOptions::default())
}
/// Constructs a signal synchronized with a specific URL query parameter.
///
/// This is the same as [`query_signal`], but allows you to specify additional navigation options.
#[track_caller]
pub fn query_signal_with_options<T>(
key: impl Into<Oco<'static, str>>,
@@ -210,7 +205,6 @@ fn use_url_raw() -> ArcRwSignal<Url> {
})
}
/// Gives reactive access to the current URL.
#[track_caller]
pub fn use_url() -> ReadSignal<Url> {
use_url_raw().read_only().into()

View File

@@ -1,149 +1,20 @@
//! # Leptos Router
//!
//! Leptos Router is a router and state management tool for web applications
//! written in Rust using the Leptos web framework.
//! It is ”isomorphic”, i.e., it can be used for client-side applications/single-page
//! apps (SPAs), server-side rendering/multi-page apps (MPAs), or to synchronize
//! state between the two.
//!
//! ## Philosophy
//!
//! Leptos Router is built on a few simple principles:
//! 1. **URL drives state.** For web applications, the URL should be the ultimate
//! source of truth for most of your apps state. (Its called a **Universal
//! Resource Locator** for a reason!)
//!
//! 2. **Nested routing.** A URL can match multiple routes that exist in a nested tree
//! and are rendered by different components. This means you can navigate between siblings
//! in this tree without re-rendering or triggering any change in the parent routes.
//!
//! 3. **Progressive enhancement.** The [`A`](crate::components::A) and
//! [`Form`](crate::components::Form) components resolve any relative
//! nested routes, render actual `<a>` and `<form>` elements, and (when possible)
//! upgrading them to handle those navigations with client-side routing. If youre using
//! them with server-side rendering (with or without hydration), they just work,
//! whether JS/WASM have loaded or not.
//!
//! ## Example
//!
//! ```rust
//! use leptos::prelude::*;
//! use leptos_router::components::*;
//! use leptos_router::path;
//! use leptos_router::hooks::use_params_map;
//!
//! #[component]
//! pub fn RouterExample() -> impl IntoView {
//! view! {
//!
//! <div id="root">
//! // we wrap the whole app in a <Router/> to allow client-side navigation
//! // from our nav links below
//! <Router>
//! <main>
//! // <Routes/> both defines our routes and shows them on the page
//! <Routes fallback=|| "Not found.">
//! // our root route: the contact list is always shown
//! <ParentRoute
//! path=path!("")
//! view=ContactList
//! >
//! // users like /gbj or /bob
//! <Route
//! path=path!(":id")
//! view=Contact
//! />
//! // a fallback if the /:id segment is missing from the URL
//! <Route
//! path=path!("")
//! view=move || view! { <p class="contact">"Select a contact."</p> }
//! />
//! </ParentRoute>
//! </Routes>
//! </main>
//! </Router>
//! </div>
//! }
//! }
//!
//! type ContactSummary = (); // TODO!
//! type Contact = (); // TODO!()
//!
//! // contact_data reruns whenever the :id param changes
//! async fn contact_data(id: String) -> Contact {
//! todo!()
//! }
//!
//! // contact_list_data *doesn't* rerun when the :id changes,
//! // because that param is nested lower than the <ContactList/> route
//! async fn contact_list_data() -> Vec<ContactSummary> {
//! todo!()
//! }
//!
//! #[component]
//! fn ContactList() -> impl IntoView {
//! // loads the contact list data once; doesn't reload when nested routes change
//! let contacts = Resource::new(|| (), |_| contact_list_data());
//! view! {
//!
//! <div>
//! // show the contacts
//! <ul>
//! {move || contacts.get().map(|contacts| view! { <li>"todo contact info"</li> } )}
//! </ul>
//!
//! // insert the nested child route here
//! <Outlet/>
//! </div>
//! }
//! }
//!
//! #[component]
//! fn Contact() -> impl IntoView {
//! let params = use_params_map();
//! let data = Resource::new(
//! move || params.read().get("id").unwrap_or_default(),
//! move |id| contact_data(id)
//! );
//! todo!()
//! }
//! ```
//!
//! You can find examples of additional APIs in the [`router`] example.
//!
//! # Feature Flags
//! - `ssr` Server-side rendering: Generate an HTML string (typically on the server)
//! - `nightly`: On `nightly` Rust, enables the function-call syntax for signal getters and setters.
//! - `tracing`: Enables support for the `tracing` crate.
//!
//! [`Leptos`]: <https://github.com/leptos-rs/leptos>
//! [`router`]: <https://github.com/leptos-rs/leptos/blob/main/examples/router/src/lib.rs>
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![cfg_attr(feature = "nightly", feature(auto_traits))]
#![cfg_attr(feature = "nightly", feature(negative_impls))]
/// Components for route definition and for enhanced links and forms.
pub mod components;
/// An optimized "flat" router without nested routes.
pub mod flat_router;
mod form;
mod generate_route_list;
/// Hooks that can be used to access router state inside your components.
pub mod hooks;
mod link;
/// Utilities for accessing the current location.
pub mod location;
mod matching;
mod method;
mod navigate;
/// A nested router that supports multiple levels of route definitions.
pub mod nested_router;
/// Support for maps of parameters in the path or in the query.
pub mod params;
mod ssr_mode;
/// Support for static routing.
pub mod static_routes;
pub use generate_route_list::*;

View File

@@ -107,9 +107,9 @@ where
) -> impl IntoView {
let RouterContext { current_url, .. } =
use_context().expect("tried to use <A/> outside a <Router/>.");
let is_active = {
let is_active = ArcMemo::new({
let href = href.clone();
move || {
move |_| {
href.read().as_deref().is_some_and(|to| {
let path = to.split(['?', '#']).next().unwrap_or_default();
current_url.with(|loc| {
@@ -122,13 +122,16 @@ where
})
})
}
};
});
view! {
<a
href=move || href.get().unwrap_or_default()
target=target
aria-current=move || if is_active() { Some("page") } else { None }
aria-current={
let is_active = is_active.clone();
move || if is_active.get() { Some("page") } else { None }
}
>
{children()}

View File

@@ -1,5 +1,3 @@
#![allow(missing_docs)]
use any_spawner::Executor;
use core::fmt::Debug;
use js_sys::Reflect;

View File

@@ -9,7 +9,8 @@ pub use static_segment::*;
/// or URL segment.
///
/// This is a "horizontal" matching: i.e., it treats a tuple of route segments
/// as subsequent segments of the URL and tries to match them all.
/// as subsequent segments of the URL and tries to match them all. For a "vertical"
/// matching that sees a tuple as alternatives to one another, see [`RouteChild`](super::RouteChild).
pub trait PossibleRouteMatch {
const OPTIONAL: bool = false;

View File

@@ -1,5 +1,3 @@
#![allow(missing_docs)]
mod choose_view;
mod path_segment;
pub(crate) mod resolve_path;
@@ -11,16 +9,16 @@ mod vertical;
use crate::{static_routes::RegenerationFn, Method, SsrMode};
pub use horizontal::*;
pub use nested::*;
use std::{borrow::Cow, collections::HashSet, sync::atomic::Ordering};
use std::{borrow::Cow, collections::HashSet};
pub use vertical::*;
#[derive(Debug)]
pub struct RouteDefs<Children> {
pub struct Routes<Children> {
base: Option<Cow<'static, str>>,
children: Children,
}
impl<Children> Clone for RouteDefs<Children>
impl<Children> Clone for Routes<Children>
where
Children: Clone,
{
@@ -32,7 +30,7 @@ where
}
}
impl<Children> RouteDefs<Children> {
impl<Children> Routes<Children> {
pub fn new(children: Children) -> Self {
Self {
base: None,
@@ -51,7 +49,7 @@ impl<Children> RouteDefs<Children> {
}
}
impl<Children> RouteDefs<Children>
impl<Children> Routes<Children>
where
Children: MatchNestedRoutes,
{
@@ -64,7 +62,10 @@ where
} else {
(base.as_ref(), path)
};
path.strip_prefix(base)?
match path.strip_prefix(base) {
Some(path) => path,
None => return None,
}
}
};
@@ -91,16 +92,6 @@ where
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct RouteMatchId(pub(crate) u16);
impl RouteMatchId {
/// Creates a new match ID based on the current route ID used in nested route generation.
///
/// In general, you do not need this; it should only be used for custom route matching behavior
/// in a library that creates its own route types.
pub fn new_from_route_id() -> RouteMatchId {
RouteMatchId(ROUTE_ID.fetch_add(1, Ordering::Relaxed))
}
}
pub trait MatchInterface {
type Child: MatchInterface + MatchParams + 'static;
@@ -139,7 +130,7 @@ pub struct GeneratedRouteData {
#[cfg(test)]
mod tests {
use super::{NestedRoute, ParamSegment, RouteDefs};
use super::{NestedRoute, ParamSegment, Routes};
use crate::{
matching::MatchParams, MatchInterface, PathSegment, StaticSegment,
WildcardSegment,
@@ -149,7 +140,7 @@ mod tests {
#[test]
pub fn matches_single_root_route() {
let routes =
RouteDefs::<_>::new(NestedRoute::new(StaticSegment("/"), || ()));
Routes::<_>::new(NestedRoute::new(StaticSegment("/"), || ()));
let matched = routes.match_route("/");
assert!(matched.is_some());
// this case seems like it should match, but implementing it interferes with
@@ -165,14 +156,13 @@ mod tests {
#[test]
pub fn matches_nested_route() {
let routes: RouteDefs<_> = RouteDefs::new(
NestedRoute::new(StaticSegment(""), || "Home").child(
let routes: Routes<_> =
Routes::new(NestedRoute::new(StaticSegment(""), || "Home").child(
NestedRoute::new(
(StaticSegment("author"), StaticSegment("contact")),
|| "Contact Me",
),
),
);
));
// route generation
let (base, paths) = routes.generate_routes();
@@ -198,7 +188,7 @@ mod tests {
#[test]
pub fn does_not_match_route_unless_full_param_matches() {
let routes = RouteDefs::<_>::new((
let routes = Routes::<_>::new((
NestedRoute::new(StaticSegment("/property-api"), || ()),
NestedRoute::new(StaticSegment("/property"), || ()),
));
@@ -208,21 +198,20 @@ mod tests {
#[test]
pub fn does_not_match_incomplete_route() {
let routes: RouteDefs<_> = RouteDefs::new(
NestedRoute::new(StaticSegment(""), || "Home").child(
let routes: Routes<_> =
Routes::new(NestedRoute::new(StaticSegment(""), || "Home").child(
NestedRoute::new(
(StaticSegment("author"), StaticSegment("contact")),
|| "Contact Me",
),
),
);
));
let matched = routes.match_route("/");
assert!(matched.is_none());
}
#[test]
pub fn chooses_between_nested_routes() {
let routes: RouteDefs<_> = RouteDefs::new((
let routes: Routes<_> = Routes::new((
NestedRoute::new(StaticSegment("/"), || ()).child((
NestedRoute::new(StaticSegment(""), || ()),
NestedRoute::new(StaticSegment("about"), || ()),
@@ -276,7 +265,7 @@ mod tests {
#[test]
pub fn arbitrary_nested_routes() {
let routes: RouteDefs<_> = RouteDefs::new_with_base(
let routes: Routes<_> = Routes::new_with_base(
(
NestedRoute::new(StaticSegment("/"), || ()).child((
NestedRoute::new(StaticSegment("/"), || ()),

View File

@@ -13,7 +13,7 @@ use std::{
mod tuples;
pub(crate) static ROUTE_ID: AtomicU16 = AtomicU16::new(1);
static ROUTE_ID: AtomicU16 = AtomicU16::new(1);
#[derive(Debug, PartialEq, Eq)]
pub struct NestedRoute<Segments, Children, Data, View> {

View File

@@ -1,6 +1,6 @@
use crate::location::State;
/// Options that can be used to configure a navigation. Used with [use_navigate](crate::hooks::use_navigate).
/// Options that can be used to configure a navigation. Used with [use_navigate](crate::use_navigate).
#[derive(Clone, Debug)]
pub struct NavigateOptions {
/// Whether the URL being navigated to should be resolved relative to the current route.

View File

@@ -1,7 +1,7 @@
use crate::{
hooks::Matched,
location::{LocationProvider, Url},
matching::RouteDefs,
matching::Routes,
params::ParamsMap,
view_transition::start_view_transition,
ChooseView, MatchInterface, MatchNestedRoutes, MatchParams, PathSegment,
@@ -44,7 +44,7 @@ use tachys::{
pub(crate) struct NestedRoutesView<Loc, Defs, FalFn> {
pub location: Option<Loc>,
pub routes: RouteDefs<Defs>,
pub routes: Routes<Defs>,
pub outer_owner: Owner,
pub current_url: ArcRwSignal<Url>,
pub base: Option<Oco<'static, str>>,
@@ -53,8 +53,7 @@ pub(crate) struct NestedRoutesView<Loc, Defs, FalFn> {
pub transition: bool,
}
/// Retained view state for the nested router.
pub(crate) struct NestedRouteViewState<Fal>
pub struct NestedRouteViewState<Fal>
where
Fal: Render,
{
@@ -874,8 +873,6 @@ where
}
}
/// Displays the child route nested in a parent route, allowing you to control exactly where
/// that child route is displayed. Renders nothing if there is no nested child.
#[component]
pub fn Outlet() -> impl RenderHtml
where

View File

@@ -4,7 +4,6 @@ use thiserror::Error;
type ParamsMapInner = Vec<(Cow<'static, str>, Vec<String>)>;
/// A key-value map of the current named route params and their values.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct ParamsMap(ParamsMapInner);
@@ -24,7 +23,7 @@ impl ParamsMap {
/// Inserts a value into the map.
///
/// If a value with that key already exists, the new value will be added to it.
/// To replace the value instead, see [`replace`](Self::replace).
/// To replace the value instead, see [`replace`].
pub fn insert(&mut self, key: impl Into<Cow<'static, str>>, value: String) {
let value = Url::unescape(&value);
@@ -170,12 +169,10 @@ impl Params for () {
}
}
/// Converts some parameter value from the URL into a typed parameter with the given name.
pub trait IntoParam
where
Self: Sized,
{
/// Converts the param.
fn into_param(value: Option<&str>, name: &str)
-> Result<Self, ParamsError>;
}

View File

@@ -20,34 +20,17 @@ use crate::static_routes::StaticRoute;
/// 5. **`Async`**: Load all resources on the server. Wait until all data are loaded, and render HTML in one sweep.
/// - *Pros*: Better handling for meta tags (because you know async data even before you render the `<head>`). Faster complete load than **synchronous** because async resources begin loading on server.
/// - *Cons*: Slower load time/TTFB: you need to wait for all async resources to load before displaying anything on the client.
/// 6. **`Static`**: Renders the page when the server starts up, or incrementally, using the
/// configuration provided by a [`StaticRoute`].
/// 6. **`Static`**:
///
/// The mode defaults to out-of-order streaming. For a path that includes multiple nested routes, the most
/// restrictive mode will be used: i.e., if even a single nested route asks for `Async` rendering, the whole initial
/// request will be rendered `Async`. (`Async` is the most restricted requirement, followed by `InOrder`, `PartiallyBlocked`, and `OutOfOrder`.)
#[derive(Default, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum SsrMode {
/// **Out-of-order streaming** (`OutOfOrder`, the default): Serve an HTML shell that includes `fallback` for any `Suspense`. Load data on the **server**, streaming it down to the client as it resolves, and streaming down HTML for `Suspense` nodes.
/// - *Pros*: Combines the best of **synchronous** and `Async`, with a very fast shell and resources that begin loading on the server.
/// - *Cons*: Requires JS for suspended fragments to appear in correct order. Weaker meta tag support when it depends on data that's under suspense (has already streamed down `<head>`)
#[default]
OutOfOrder,
/// **In-order streaming** (`InOrder`): Walk through the tree, returning HTML synchronously as in synchronous rendering and out-of-order streaming until you hit a `Suspense`. At that point, wait for all its data to load, then render it, then the rest of the tree.
/// - *Pros*: Does not require JS for HTML to appear in correct order.
/// - *Cons*: Loads the shell more slowly than out-of-order streaming or synchronous rendering because it needs to pause at every `Suspense`. Cannot begin hydration until the entire page has loaded, so earlier pieces
/// of the page will not be interactive until the suspended chunks have loaded.
PartiallyBlocked,
/// **In-order streaming** (`InOrder`): Walk through the tree, returning HTML synchronously as in synchronous rendering and out-of-order streaming until you hit a `Suspense`. At that point, wait for all its data to load, then render it, then the rest of the tree.
/// - *Pros*: Does not require JS for HTML to appear in correct order.
/// - *Cons*: Loads the shell more slowly than out-of-order streaming or synchronous rendering because it needs to pause at every `Suspense`. Cannot begin hydration until the entire page has loaded, so earlier pieces
/// of the page will not be interactive until the suspended chunks have loaded.
InOrder,
/// **`Async`**: Load all resources on the server. Wait until all data are loaded, and render HTML in one sweep.
/// - *Pros*: Better handling for meta tags (because you know async data even before you render the `<head>`). Faster complete load than **synchronous** because async resources begin loading on server.
/// - *Cons*: Slower load time/TTFB: you need to wait for all async resources to load before displaying anything on the client.
Async,
/// **`Static`**: Renders the page when the server starts up, or incrementally, using the
/// configuration provided by a [`StaticRoute`].
Static(StaticRoute),
}

View File

@@ -13,14 +13,10 @@ use std::{
type PinnedFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
type PinnedStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
/// A reference-counted pointer to a function that can generate a set of params for static site
/// generation.
pub type StaticParams = Arc<StaticParamsFn>;
/// A function that generates a set of params for generating a static route.
pub type StaticParamsFn =
dyn Fn() -> PinnedFuture<StaticParamsMap> + Send + Sync + 'static;
/// A function that defines when a statically-generated page should be regenerated.
#[derive(Clone)]
#[allow(clippy::type_complexity)]
pub struct RegenerationFn(
@@ -47,7 +43,6 @@ impl PartialEq for RegenerationFn {
}
}
/// Defines how a static route should be generated.
#[derive(Clone, Default)]
pub struct StaticRoute {
pub(crate) prerender_params: Option<StaticParams>,
@@ -55,13 +50,10 @@ pub struct StaticRoute {
}
impl StaticRoute {
/// Creates a new static route listing.
pub fn new() -> Self {
Self::default()
}
/// Defines a set of params that should be prerendered on server start-up, depending on some
/// asynchronous function that returns their values.
pub fn prerender_params<Fut>(
mut self,
params: impl Fn() -> Fut + Send + Sync + 'static,
@@ -73,7 +65,6 @@ impl StaticRoute {
self
}
/// Defines when the route should be regenerated.
pub fn regenerate<St>(
mut self,
invalidate: impl Fn(&ParamsMap) -> St + Send + Sync + 'static,
@@ -87,7 +78,6 @@ impl StaticRoute {
self
}
/// Returns a set of params that should be prerendered.
pub async fn to_prerendered_params(&self) -> Option<StaticParamsMap> {
match &self.prerender_params {
None => None,
@@ -128,7 +118,6 @@ impl PartialEq for StaticRoute {
impl Eq for StaticRoute {}
/// A map of params for static routes.
#[derive(Debug, Clone, Default)]
pub struct StaticParamsMap(pub Vec<(String, Vec<String>)>);
@@ -170,7 +159,6 @@ impl IntoIterator for StaticParamsMap {
}
}
/// An iterator over a set of (key, value) pairs for statically-routed params.
#[derive(Debug)]
pub struct StaticParamsIter(
<Vec<(String, Vec<String>)> as IntoIterator>::IntoIter,
@@ -220,7 +208,7 @@ impl StaticPath {
paths = paths
.into_iter()
.map(|p| {
if s.starts_with("/") || s.is_empty() {
if s.starts_with("/") {
ResolvedStaticPath {
path: format!("{}{s}", p.path),
}
@@ -266,14 +254,12 @@ impl StaticPath {
}
}
/// A path to be used in static route generation.
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone)]
pub struct ResolvedStaticPath {
pub(crate) path: String,
}
impl ResolvedStaticPath {
/// Defines a path to be used for static route generation.
pub fn new(path: impl Into<String>) -> Self {
Self { path: path.into() }
}
@@ -292,7 +278,6 @@ impl Display for ResolvedStaticPath {
}
impl ResolvedStaticPath {
/// Builds the page that corresponds to this path.
pub async fn build<Fut, WriterFut>(
self,
render_fn: impl Fn(&ResolvedStaticPath) -> Fut + Send + Clone + 'static,
@@ -377,67 +362,3 @@ impl ResolvedStaticPath {
rx.await.unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn static_path_segments_into_path_ignore_empty_segments() {
let segments = StaticPath::new(vec![
PathSegment::Static("".into()),
PathSegment::Static("post".into()),
]);
assert_eq!(
segments.into_paths(None),
vec![ResolvedStaticPath::new("/post")]
);
}
#[test]
fn static_path_segments_into_path_flatten_param() {
let mut params = StaticParamsMap::new();
params
.0
.push(("slug".into(), vec!["first".into(), "second".into()]));
let segments = StaticPath::new(vec![
PathSegment::Static("/post".into()),
PathSegment::Param("slug".into()),
]);
assert_eq!(
segments.into_paths(Some(params)),
vec![
ResolvedStaticPath::new("/post/first"),
ResolvedStaticPath::new("/post/second")
]
);
}
#[test]
fn static_path_segments_into_path_no_double_slash() {
let segments = StaticPath::new(vec![
PathSegment::Static("/post".into()),
PathSegment::Static("/leptos".into()),
]);
assert_eq!(
segments.into_paths(None),
vec![ResolvedStaticPath::new("/post/leptos")]
);
let mut params = StaticParamsMap::new();
params
.0
.push(("slug".into(), vec!["/first".into(), "/second".into()]));
let segments = StaticPath::new(vec![
PathSegment::Static("/post".into()),
PathSegment::Param("slug".into()),
]);
assert_eq!(
segments.into_paths(Some(params)),
vec![
ResolvedStaticPath::new("/post/first"),
ResolvedStaticPath::new("/post/second")
]
);
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "leptos_router_macro"
version = "0.7.0"
version = "0.7.0-rc1"
authors = ["Greg Johnston", "Ben Wishovich"]
license = "MIT"
readme = "../README.md"

View File

@@ -1,7 +1,3 @@
//! A macro to make path definitions easier with [`leptos_router`].
#![deny(missing_docs)]
use proc_macro::{TokenStream, TokenTree};
use proc_macro2::Span;
use proc_macro_error2::abort;

2555
server_fn/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -30,7 +30,7 @@ once_cell = "1.20"
actix-web = { version = "4.9", optional = true }
# axum
axum = { version = "0.7.9", optional = true, default-features = false, features = [
axum = { version = "0.7.7", optional = true, default-features = false, features = [
"multipart",
] }
tower = { version = "0.5.1", optional = true }

View File

@@ -1,6 +1,6 @@
[package]
name = "tachys"
version = "0.1.0"
version = "0.1.0-rc1"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"

View File

@@ -267,7 +267,7 @@ impl<T: IntoClass> IntoClass for Option<T> {
}
}
impl IntoClass for &str {
impl<'a> IntoClass for &'a str {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Self);
type Cloneable = Self;

View File

@@ -9,9 +9,8 @@ where
E: AsRef<str>,
{
HtmlElement {
#[cfg(debug_assertions)]
defined_at: std::panic::Location::caller(),
tag: Custom(tag),
attributes: (),
children: (),
}

View File

@@ -10,8 +10,8 @@ use crate::{
use wasm_bindgen::JsValue;
use web_sys::Element;
/// Extends an HTML element, allowing you to add attributes and children to the
/// element's built state at runtime, with a similar API to how they
/// Extends the [`Element`](Renderer::Element) type of a [`Renderer`], allowing you to add
/// attributes and children to the element's built state at runtime, with a similar API to how they
/// can be added to the static view tree at compile time.
///
/// ```rust,ignore

View File

@@ -25,11 +25,10 @@ macro_rules! html_element_inner {
{
HtmlElement {
#[cfg(debug_assertions)]
defined_at: std::panic::Location::caller(),
tag: $struct_name,
attributes: (),
children: (),
}
}
@@ -56,17 +55,10 @@ macro_rules! html_element_inner {
At: NextTuple,
<At as NextTuple>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>: Attribute,
{
let HtmlElement {
#[cfg(debug_assertions)]
defined_at,
tag,
children,
attributes
} = self;
let HtmlElement { tag, children, attributes } = self;
HtmlElement {
#[cfg(debug_assertions)]
defined_at,
tag,
children,
attributes: attributes.next_tuple($crate::html::attribute::$attr(value)),
}
@@ -126,16 +118,14 @@ macro_rules! html_self_closing_elements {
paste::paste! {
$(
#[$meta]
#[track_caller]
pub fn $tag() -> HtmlElement<[<$tag:camel>], (), ()>
where
{
HtmlElement {
#[cfg(debug_assertions)]
defined_at: std::panic::Location::caller(),
attributes: (),
children: (),
tag: [<$tag:camel>],
}
}
@@ -148,6 +138,7 @@ macro_rules! html_self_closing_elements {
impl<At> HtmlElement<[<$tag:camel>], At, ()>
where
At: Attribute,
{
$(
#[doc = concat!("The [`", stringify!($attr), "`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/", stringify!($tag), "#", stringify!($attr) ,") attribute on `<", stringify!($tag), ">`.")]
@@ -160,18 +151,13 @@ macro_rules! html_self_closing_elements {
V: AttributeValue,
At: NextTuple,
<At as NextTuple>::Output<Attr<$crate::html::attribute::[<$attr:camel>], V>>: Attribute,
{
let HtmlElement {
#[cfg(debug_assertions)]
defined_at,
tag,
children,
attributes,
let HtmlElement { tag, children, attributes,
} = self;
HtmlElement {
#[cfg(debug_assertions)]
defined_at,
tag,
children,
attributes: attributes.next_tuple($crate::html::attribute::$attr(value)),
}

View File

@@ -308,7 +308,7 @@ impl InnerHtmlValue for Arc<str> {
}
}
impl InnerHtmlValue for &str {
impl<'a> InnerHtmlValue for &'a str {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Self);
type Cloneable = Self;

View File

@@ -1,8 +1,6 @@
#[cfg(debug_assertions)]
use crate::hydration::set_currently_hydrating;
use crate::{
html::attribute::Attribute,
hydration::{failed_to_cast_element, Cursor},
hydration::Cursor,
renderer::{CastFrom, Rndr},
ssr::StreamBuilder,
view::{
@@ -26,14 +24,10 @@ pub use custom::*;
pub use element_ext::*;
pub use elements::*;
pub use inner_html::*;
#[cfg(debug_assertions)]
use std::panic::Location;
/// The typed representation of an HTML element.
#[derive(Debug, PartialEq, Eq)]
pub struct HtmlElement<E, At, Ch> {
#[cfg(debug_assertions)]
pub(crate) defined_at: &'static Location<'static>,
pub(crate) tag: E,
pub(crate) attributes: At,
pub(crate) children: Ch,
@@ -42,9 +36,8 @@ pub struct HtmlElement<E, At, Ch> {
impl<E: Clone, At: Clone, Ch: Clone> Clone for HtmlElement<E, At, Ch> {
fn clone(&self) -> Self {
HtmlElement {
#[cfg(debug_assertions)]
defined_at: self.defined_at,
tag: self.tag.clone(),
attributes: self.attributes.clone(),
children: self.children.clone(),
}
@@ -82,16 +75,14 @@ where
fn child(self, child: NewChild) -> Self::Output {
let HtmlElement {
#[cfg(debug_assertions)]
defined_at,
tag,
attributes,
children,
} = self;
HtmlElement {
#[cfg(debug_assertions)]
defined_at,
tag,
attributes,
children: children.next_tuple(child.into_render()),
}
@@ -112,15 +103,11 @@ where
attr: NewAttr,
) -> Self::Output<NewAttr> {
let HtmlElement {
#[cfg(debug_assertions)]
defined_at,
tag,
attributes,
children,
} = self;
HtmlElement {
#[cfg(debug_assertions)]
defined_at,
tag,
attributes: attributes.add_any_attr(attr),
children,
@@ -242,9 +229,8 @@ where
let (attributes, children) =
join(self.attributes.resolve(), self.children.resolve()).await;
HtmlElement {
#[cfg(debug_assertions)]
defined_at: self.defined_at,
tag: self.tag,
attributes,
children,
}
@@ -350,11 +336,6 @@ where
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
#[cfg(debug_assertions)]
{
set_currently_hydrating(Some(self.defined_at));
}
// non-Static custom elements need special support in templates
// because they haven't been inserted type-wise
if E::TAG.is_empty() && !FROM_SERVER {
@@ -368,9 +349,7 @@ where
cursor.sibling();
}
let el = crate::renderer::types::Element::cast_from(cursor.current())
.unwrap_or_else(|| {
failed_to_cast_element(E::TAG, cursor.current())
});
.unwrap();
let attrs = self.attributes.hydrate::<FROM_SERVER>(&el);

Some files were not shown because too many files have changed in this diff Show More