mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-27 15:44:42 -05:00
Compare commits
125 Commits
server-fn-
...
1097-v2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7376b76558 | ||
|
|
579abc586c | ||
|
|
b2c75d215b | ||
|
|
951607de74 | ||
|
|
c1c49ce53b | ||
|
|
e8aa9b24f1 | ||
|
|
3036cd223e | ||
|
|
1ae5150b08 | ||
|
|
47148f2033 | ||
|
|
4d4d15436b | ||
|
|
7f4741b3a3 | ||
|
|
85644a7c1c | ||
|
|
f40ae6af30 | ||
|
|
708e1a5aab | ||
|
|
55613c9a31 | ||
|
|
e6590c7d31 | ||
|
|
5af2f4e98d | ||
|
|
8e68699435 | ||
|
|
77580401da | ||
|
|
7902e7edb7 | ||
|
|
4ad223277d | ||
|
|
6f5da11c72 | ||
|
|
3eed86fbf3 | ||
|
|
10d51a854a | ||
|
|
6c60bad757 | ||
|
|
79f666b5da | ||
|
|
3ea3a40395 | ||
|
|
193aa79956 | ||
|
|
3481a6ee53 | ||
|
|
d1ef5fce9f | ||
|
|
5d48911f01 | ||
|
|
8a90f97959 | ||
|
|
e9665b34e5 | ||
|
|
d4b1ceda90 | ||
|
|
a0fae88f7d | ||
|
|
03a8609680 | ||
|
|
3e40f9cc66 | ||
|
|
576bb078f7 | ||
|
|
3cdcc85c87 | ||
|
|
ec3a26dfbc | ||
|
|
c755dae6ee | ||
|
|
b67d51e019 | ||
|
|
7a34d6026f | ||
|
|
548eac8e60 | ||
|
|
05ac8e861f | ||
|
|
7a4d475cca | ||
|
|
eea8e60518 | ||
|
|
f6a272498d | ||
|
|
aef7c4ce8e | ||
|
|
b29eb8e032 | ||
|
|
da9183f4b5 | ||
|
|
ae3ddcb0e6 | ||
|
|
c6b8f0e8ed | ||
|
|
bab9f40a81 | ||
|
|
c2cfdf3678 | ||
|
|
8967eadc02 | ||
|
|
4cc65f837f | ||
|
|
22706e7371 | ||
|
|
9f9302662c | ||
|
|
6b90e1babd | ||
|
|
7e540a8f49 | ||
|
|
f06ffd72aa | ||
|
|
83d3d7579c | ||
|
|
39edb6eb45 | ||
|
|
d81c1a929e | ||
|
|
f69c28df18 | ||
|
|
66f54e7f1a | ||
|
|
81e416b085 | ||
|
|
a5f73b441c | ||
|
|
0f1ebccad5 | ||
|
|
2f01df6185 | ||
|
|
c4982319fe | ||
|
|
8fb4e88439 | ||
|
|
e821efca07 | ||
|
|
568f7b21ae | ||
|
|
d3c0f5320c | ||
|
|
5adc88bf50 | ||
|
|
67300adf41 | ||
|
|
4a3a67bf37 | ||
|
|
8150847218 | ||
|
|
8cb95b4646 | ||
|
|
df4ce904a0 | ||
|
|
1cc3a43268 | ||
|
|
d5a862a406 | ||
|
|
33c83c3e62 | ||
|
|
171adcd09e | ||
|
|
13f7cb9a9a | ||
|
|
ee7dbafc85 | ||
|
|
f5cfe4e8a2 | ||
|
|
c3e45d19d7 | ||
|
|
966100c2d6 | ||
|
|
bce1dea11b | ||
|
|
c55067ab7c | ||
|
|
9da4084561 | ||
|
|
1d7235d4ca | ||
|
|
2cb8171105 | ||
|
|
bbc7799b7c | ||
|
|
a9cbcce8b2 | ||
|
|
3531ca64bb | ||
|
|
e402b85dd6 | ||
|
|
8ae5cf0ccf | ||
|
|
5c34c3fc77 | ||
|
|
3a570dc0d9 | ||
|
|
3c6748b30d | ||
|
|
24945f67bf | ||
|
|
edddab1e51 | ||
|
|
acfc86d2a4 | ||
|
|
651868dec9 | ||
|
|
18bc03e660 | ||
|
|
5f0013e482 | ||
|
|
10c0a2de65 | ||
|
|
b24be2566d | ||
|
|
77439b5db5 | ||
|
|
23594a43ea | ||
|
|
601db7aa86 | ||
|
|
d15ba11104 | ||
|
|
d45d92433f | ||
|
|
97127a90c6 | ||
|
|
55bb63edea | ||
|
|
15a4e54435 | ||
|
|
3a522aef5d | ||
|
|
a98885a123 | ||
|
|
2b7923261b | ||
|
|
b043f829a6 | ||
|
|
f415f7b146 |
6
.github/ISSUE_TEMPLATE/bug_report.md
vendored
6
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -16,10 +16,10 @@ Please copy and paste the Leptos dependencies and features from your `Cargo.toml
|
||||
|
||||
For example:
|
||||
```toml
|
||||
leptos = { version = "0.3", default-features = false, features = ["serde"] }
|
||||
leptos = { version = "0.3", features = ["serde"] }
|
||||
leptos_axum = { version = "0.3", optional = true }
|
||||
leptos_meta = { version = "0.3", default-features = false }
|
||||
leptos_router = { version = "0.3", default-features = false }
|
||||
leptos_meta = { version = "0.3"}
|
||||
leptos_router = { version = "0.3"}
|
||||
```
|
||||
|
||||
**To Reproduce**
|
||||
|
||||
96
.github/workflows/check-examples.yml
vendored
96
.github/workflows/check-examples.yml
vendored
@@ -1,46 +1,74 @@
|
||||
name: Check examples
|
||||
name: Check Examples
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Check examples ${{ matrix.os }} (using rustc ${{ matrix.rust }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- nightly
|
||||
os:
|
||||
- ubuntu-latest
|
||||
|
||||
setup:
|
||||
name: Get Examples
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
source_changed: ${{ steps.set-source-changed.outputs.source_changed }}
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
- name: Install JQ Tool
|
||||
uses: mbround18/install-jq@v1
|
||||
|
||||
- name: Set Matrix
|
||||
id: set-matrix
|
||||
run: |
|
||||
examples=$(ls examples |
|
||||
awk '{print "examples/" $0}' |
|
||||
grep -v examples/README.md |
|
||||
grep -v examples/Makefile.toml |
|
||||
grep -v examples/cargo-make |
|
||||
grep -v examples/gtk |
|
||||
jq -R -s -c 'split("\n")[:-1]')
|
||||
echo "Example Directories: $examples"
|
||||
echo "matrix={\"directory\":$examples}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Get source files that changed
|
||||
id: changed-source
|
||||
uses: tj-actions/changed-files@v36
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
components: rustfmt
|
||||
files: |
|
||||
integrations
|
||||
leptos
|
||||
leptos_config
|
||||
leptos_dom
|
||||
leptos_hot_reload
|
||||
leptos_macro
|
||||
leptos_reactive
|
||||
leptos_server
|
||||
meta
|
||||
router
|
||||
server_fn
|
||||
server_fn_macro
|
||||
|
||||
- name: Add wasm32-unknown-unknown
|
||||
run: rustup target add wasm32-unknown-unknown
|
||||
- name: List source files that changed
|
||||
run: echo '${{ steps.changed-source.outputs.all_changed_files }}'
|
||||
|
||||
- name: Setup cargo-make
|
||||
uses: davidB/rust-cargo-make@v1
|
||||
- name: Set source_changed
|
||||
id: set-source-changed
|
||||
run: |
|
||||
echo "source_changed=${{ steps.changed-source.outputs.any_changed }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Cargo generate-lockfile
|
||||
run: cargo generate-lockfile
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
- name: Run cargo check on all examples
|
||||
run: cargo make check-examples
|
||||
matrix-job:
|
||||
name: Check
|
||||
needs: [setup]
|
||||
if: needs.setup.outputs.source_changed == 'true'
|
||||
strategy:
|
||||
matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}
|
||||
fail-fast: false
|
||||
uses: ./.github/workflows/run-cargo-make-task.yml
|
||||
with:
|
||||
directory: ${{ matrix.directory }}
|
||||
cargo_make_task: "check"
|
||||
|
||||
46
.github/workflows/check.yml
vendored
46
.github/workflows/check.yml
vendored
@@ -1,46 +0,0 @@
|
||||
name: Check
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Run `cargo check` ${{ matrix.os }} (using rustc ${{ matrix.rust }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- nightly
|
||||
os:
|
||||
- ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
components: rustfmt
|
||||
|
||||
- name: Add wasm32-unknown-unknown
|
||||
run: rustup target add wasm32-unknown-unknown
|
||||
|
||||
- name: Setup cargo-make
|
||||
uses: davidB/rust-cargo-make@v1
|
||||
|
||||
- name: Cargo generate-lockfile
|
||||
run: cargo generate-lockfile
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
- name: Run cargo check on all libraries
|
||||
run: cargo make --profile=github-actions check
|
||||
75
.github/workflows/ci.yml
vendored
Normal file
75
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
setup:
|
||||
name: Detect Changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
source_changed: ${{ steps.set-source-changed.outputs.source_changed }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Get source files that changed
|
||||
id: changed-source
|
||||
uses: tj-actions/changed-files@v36
|
||||
with:
|
||||
files: |
|
||||
integrations
|
||||
leptos
|
||||
leptos_config
|
||||
leptos_dom
|
||||
leptos_hot_reload
|
||||
leptos_macro
|
||||
leptos_reactive
|
||||
leptos_server
|
||||
meta
|
||||
router
|
||||
server_fn
|
||||
server_fn_macro
|
||||
|
||||
- name: List source files that changed
|
||||
run: echo '${{ steps.changed-source.outputs.all_changed_files }}'
|
||||
|
||||
- name: Set source_changed
|
||||
id: set-source-changed
|
||||
run: |
|
||||
echo "source_changed=${{ steps.changed-source.outputs.any_changed }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
matrix-job:
|
||||
name: CI
|
||||
needs: [setup]
|
||||
if: needs.setup.outputs.source_changed == 'true'
|
||||
strategy:
|
||||
matrix:
|
||||
directory:
|
||||
[
|
||||
integrations/actix,
|
||||
integrations/axum,
|
||||
integrations/viz,
|
||||
integrations/utils,
|
||||
leptos,
|
||||
leptos_config,
|
||||
leptos_dom,
|
||||
leptos_hot_reload,
|
||||
leptos_macro,
|
||||
leptos_reactive,
|
||||
leptos_server,
|
||||
meta,
|
||||
router,
|
||||
server_fn,
|
||||
server_fn/server_fn_macro_default,
|
||||
server_fn_macro,
|
||||
]
|
||||
uses: ./.github/workflows/run-cargo-make-task.yml
|
||||
with:
|
||||
directory: ${{ matrix.directory }}
|
||||
cargo_make_task: "ci"
|
||||
34
.github/workflows/fmt.yml
vendored
34
.github/workflows/fmt.yml
vendored
@@ -1,34 +0,0 @@
|
||||
name: Format
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Run rustfmt
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- nightly
|
||||
os:
|
||||
- ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
components: rustfmt
|
||||
|
||||
- name: Run Rustfmt
|
||||
run: cargo fmt -- --check
|
||||
@@ -1,17 +1,21 @@
|
||||
name: Verify Examples
|
||||
name: Run Task
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
workflow_call:
|
||||
inputs:
|
||||
directory:
|
||||
required: true
|
||||
type: string
|
||||
cargo_make_task:
|
||||
required: true
|
||||
type: string
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Verify examples ${{ matrix.os }} (using rustc ${{ matrix.rust }}
|
||||
name: Run ${{ matrix.os }} (using rustc ${{ matrix.rust }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -21,6 +25,12 @@ jobs:
|
||||
- ubuntu-latest
|
||||
|
||||
steps:
|
||||
# Setup environment
|
||||
- name: Install playwright browser dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install libegl1 libvpx7 libevent-2.1-7 libopus0 libopengl0 libwoff1 libharfbuzz-icu0 libgstreamer-plugins-base1.0-0 libgstreamer-gl1.0-0 libhyphen0 libmanette-0.2-0 libgles2 gstreamer1.0-libav
|
||||
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Rust
|
||||
@@ -63,7 +73,6 @@ jobs:
|
||||
|
||||
- name: Get pnpm store directory
|
||||
id: pnpm-cache
|
||||
shell: bash
|
||||
run: |
|
||||
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
|
||||
|
||||
@@ -75,5 +84,12 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-store-
|
||||
|
||||
- name: Run verify-flow on all web examples
|
||||
run: cargo make --profile=github-actions verify-examples
|
||||
# Run Cargo Make Task
|
||||
- name: ${{ inputs.cargo_make_task }}
|
||||
run: |
|
||||
if [ "${{ inputs.directory }}" = "INTERNAL" ]; then
|
||||
echo No verification required
|
||||
else
|
||||
cd ${{ inputs.directory }}
|
||||
cargo make --profile=github-actions ${{ inputs.cargo_make_task }}
|
||||
fi
|
||||
46
.github/workflows/test.yml
vendored
46
.github/workflows/test.yml
vendored
@@ -1,46 +0,0 @@
|
||||
name: Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Run tests ${{ matrix.os }} (using rustc ${{ matrix.rust }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
rust:
|
||||
- nightly
|
||||
os:
|
||||
- ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ matrix.rust }}
|
||||
override: true
|
||||
components: rustfmt
|
||||
|
||||
- name: Add wasm32-unknown-unknown
|
||||
run: rustup target add wasm32-unknown-unknown
|
||||
|
||||
- name: Setup cargo-make
|
||||
uses: davidB/rust-cargo-make@v1
|
||||
|
||||
- name: Cargo generate-lockfile
|
||||
run: cargo generate-lockfile
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
- name: Run tests with all features
|
||||
run: cargo make --profile=github-actions test
|
||||
47
.github/workflows/verify-all-examples.yml
vendored
Normal file
47
.github/workflows/verify-all-examples.yml
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
name: Verify All Examples
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
schedule:
|
||||
# Run once a day at 3:00 AM EST
|
||||
- cron: "0 8 * * *"
|
||||
|
||||
jobs:
|
||||
setup:
|
||||
name: Get Examples
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install JQ Tool
|
||||
uses: mbround18/install-jq@v1
|
||||
|
||||
- name: Set Matrix
|
||||
id: set-matrix
|
||||
run: |
|
||||
examples=$(ls examples |
|
||||
awk '{print "examples/" $0}' |
|
||||
grep -v examples/README.md |
|
||||
grep -v examples/Makefile.toml |
|
||||
grep -v examples/cargo-make |
|
||||
grep -v examples/gtk |
|
||||
jq -R -s -c 'split("\n")[:-1]')
|
||||
echo "Example Directories: $examples"
|
||||
echo "matrix={\"directory\":$examples}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
matrix-job:
|
||||
name: Verify
|
||||
needs: [setup]
|
||||
strategy:
|
||||
matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}
|
||||
fail-fast: false
|
||||
uses: ./.github/workflows/run-cargo-make-task.yml
|
||||
with:
|
||||
directory: ${{ matrix.directory }}
|
||||
cargo_make_task: "verify-flow"
|
||||
71
.github/workflows/verify-changed-examples.yml
vendored
Normal file
71
.github/workflows/verify-changed-examples.yml
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
name: Verify Changed Examples
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
setup:
|
||||
name: Get Changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get all example files that changed
|
||||
id: changed-files
|
||||
uses: tj-actions/changed-files@v36
|
||||
with:
|
||||
files: |
|
||||
examples
|
||||
|
||||
- name: List all example files that changed
|
||||
run: echo '${{ steps.changed-files.outputs.all_changed_files }}'
|
||||
|
||||
- name: Get example project directories that changed
|
||||
id: changed-dirs
|
||||
uses: tj-actions/changed-files@v36
|
||||
with:
|
||||
dir_names: true
|
||||
dir_names_max_depth: "2"
|
||||
files: |
|
||||
examples
|
||||
!examples/cargo-make
|
||||
!examples/gtk
|
||||
!examples/Makefile.toml
|
||||
!examples/README.md
|
||||
json: true
|
||||
quotepath: false
|
||||
|
||||
- name: List example project directories that changed
|
||||
run: echo '${{ steps.changed-dirs.outputs.all_changed_files }}'
|
||||
|
||||
- name: Set Matrix
|
||||
id: set-matrix
|
||||
run: |
|
||||
if [ ${{ steps.changed-files.outputs.any_changed }} == 'true' ]; then
|
||||
# Create matrix with changed directories
|
||||
echo "matrix={\"directory\":${{ steps.changed-dirs.outputs.all_changed_files }}}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
# Create matrix with one item to prevent an empty vector error
|
||||
echo "matrix={\"directory\":[\"INTERNAL\"]}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
matrix-job:
|
||||
name: Verify
|
||||
needs: [setup]
|
||||
strategy:
|
||||
matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}
|
||||
fail-fast: false
|
||||
uses: ./.github/workflows/run-cargo-make-task.yml
|
||||
with:
|
||||
directory: ${{ matrix.directory }}
|
||||
cargo_make_task: "verify-flow"
|
||||
@@ -220,8 +220,8 @@ for reference: they include large amounts of manual SSR route handling, etc.
|
||||
## `cargo-leptos` helpers
|
||||
|
||||
`leptos_config` and `leptos_hot_reload` exist to support two different features
|
||||
of `cargo-leptos`, namely its configuration and its view-patching/hot-
|
||||
reloading features.
|
||||
of `cargo-leptos`, namely its configuration and its view-patching/hot-reloading
|
||||
features.
|
||||
|
||||
It’s important to say that the main feature `cargo-leptos` remains its ability
|
||||
to conveniently tie together different build tooling, compiling your app to
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
_This Code of Conduct is based on the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct)
|
||||
and the [Bevy Code of Conduct](https://raw.githubusercontent.com/bevyengine/bevy/main/CODE_OF_CONDUCT.md),
|
||||
which are adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling)
|
||||
which are adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling)
|
||||
and the [Contributor Covenant](https://www.contributor-covenant.org)._
|
||||
|
||||
## Our Pledge
|
||||
|
||||
@@ -22,7 +22,7 @@ Leptos, as a framework, reflects certain technical values:
|
||||
- **Expose primitives rather than imposing patterns.** Provide building blocks
|
||||
that users can combine together to build up more complex behavior, rather than
|
||||
requiring users follow certain templates, file formats, etc. e.g., components
|
||||
are defined as functions, rather than a bespoke single-file comonent format.
|
||||
are defined as functions, rather than a bespoke single-file component format.
|
||||
The reactive system feeds into the rendering system, rather than being defined
|
||||
by it.
|
||||
- **Bottom-up over top-down.** If you envision a user’s application as a tree
|
||||
@@ -42,7 +42,7 @@ Leptos, as a framework, reflects certain technical values:
|
||||
- **Embrace Rust semantics.** Especially in things like UI templating, use Rust
|
||||
semantics or extend them in a predictable way with control-flow components
|
||||
rather than overloading the meaning of Rust terms like `if` or `for` in a
|
||||
framework-speciic way.
|
||||
framework-specific way.
|
||||
- **Enhance ergonomics without obfuscating what’s happening.** This is by far
|
||||
the hardest to achieve. It’s often the case that adding additional layers to
|
||||
improve DX (like a custom build tool and starter templates) comes across as
|
||||
@@ -67,7 +67,7 @@ are a few guidelines that will make it a better experience for everyone:
|
||||
- Our CI tests every PR against all the existing examples, sometimes requiring
|
||||
compilation for both server and client side, etc. It’s thorough but slow. If
|
||||
you want to run CI locally to reduce frustration, you can do that by installing
|
||||
`cargo-make` and using `cargo make check && cargo make test && cargo make
|
||||
`cargo-make` and using `cargo make check && cargo make test && cargo make
|
||||
check-examples`.
|
||||
|
||||
## Architecture
|
||||
|
||||
30
Cargo.toml
30
Cargo.toml
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
resolver="2"
|
||||
resolver = "2"
|
||||
members = [
|
||||
# core
|
||||
"leptos",
|
||||
@@ -26,22 +26,22 @@ members = [
|
||||
exclude = ["benchmarks", "examples"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.3.0"
|
||||
version = "0.4.5"
|
||||
|
||||
[workspace.dependencies]
|
||||
leptos = { path = "./leptos", default-features = false, version = "0.3.0" }
|
||||
leptos_dom = { path = "./leptos_dom", default-features = false, version = "0.3.0" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.3.0" }
|
||||
leptos_macro = { path = "./leptos_macro", default-features = false, version = "0.3.0" }
|
||||
leptos_reactive = { path = "./leptos_reactive", default-features = false, version = "0.3.0" }
|
||||
leptos_server = { path = "./leptos_server", default-features = false, version = "0.3.0" }
|
||||
server_fn = { path = "./server_fn", default-features = false, version = "0.3.0" }
|
||||
server_fn_macro = { path = "./server_fn_macro", default-features = false, version = "0.3.0" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", default-features = false, version = "0.3.0" }
|
||||
leptos_config = { path = "./leptos_config", default-features = false, version = "0.3.0" }
|
||||
leptos_router = { path = "./router", version = "0.3.0" }
|
||||
leptos_meta = { path = "./meta", default-features = false, version = "0.3.0" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.3.0" }
|
||||
leptos = { path = "./leptos", version = "0.4.5" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.4.5" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.4.5" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.4.5" }
|
||||
leptos_reactive = { path = "./leptos_reactive", version = "0.4.5" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.4.5" }
|
||||
server_fn = { path = "./server_fn", version = "0.4.5" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.4.5" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.4.5" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.4.5" }
|
||||
leptos_router = { path = "./router", version = "0.4.5" }
|
||||
leptos_meta = { path = "./meta", version = "0.4.5" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.4.5" }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
|
||||
109
Makefile.toml
109
Makefile.toml
@@ -3,118 +3,25 @@
|
||||
# cargo install --force cargo-make
|
||||
############
|
||||
|
||||
[config]
|
||||
# make tasks run at the workspace root
|
||||
default_to_workspace = false
|
||||
|
||||
[tasks.check]
|
||||
clear = true
|
||||
dependencies = [
|
||||
"check-all",
|
||||
"check-wasm",
|
||||
"check-all-release",
|
||||
"check-wasm-release",
|
||||
]
|
||||
|
||||
[tasks.check-all]
|
||||
command = "cargo"
|
||||
args = ["+nightly", "check-all-features"]
|
||||
install_crate = "cargo-all-features"
|
||||
|
||||
[tasks.check-wasm]
|
||||
clear = true
|
||||
dependencies = [{ name = "check-wasm", path = "leptos" }]
|
||||
|
||||
[tasks.check-all-release]
|
||||
command = "cargo"
|
||||
args = ["+nightly", "check-all-features"]
|
||||
install_crate = "cargo-all-features"
|
||||
|
||||
[tasks.check-wasm-release]
|
||||
clear = true
|
||||
dependencies = [{ name = "check-wasm-release", path = "leptos" }]
|
||||
|
||||
[tasks.check-examples]
|
||||
clear = true
|
||||
dependencies = [
|
||||
{ name = "check", path = "examples/counter" },
|
||||
{ name = "check", path = "examples/counter_isomorphic" },
|
||||
{ name = "check", path = "examples/counters" },
|
||||
{ name = "check", path = "examples/error_boundary" },
|
||||
{ name = "check", path = "examples/errors_axum" },
|
||||
{ name = "check", path = "examples/fetch" },
|
||||
{ name = "check", path = "examples/hackernews" },
|
||||
{ name = "check", path = "examples/hackernews_axum" },
|
||||
{ name = "check", path = "examples/login_with_token_csr_only" },
|
||||
{ name = "check", path = "examples/parent_child" },
|
||||
{ name = "check", path = "examples/router" },
|
||||
{ name = "check", path = "examples/session_auth_axum" },
|
||||
{ name = "check", path = "examples/slots" },
|
||||
{ name = "check", path = "examples/ssr_modes" },
|
||||
{ name = "check", path = "examples/ssr_modes_axum" },
|
||||
{ name = "check", path = "examples/tailwind" },
|
||||
{ name = "check", path = "examples/tailwind_csr_trunk" },
|
||||
{ name = "check", path = "examples/todo_app_sqlite" },
|
||||
{ name = "check", path = "examples/todo_app_sqlite_axum" },
|
||||
{ name = "check", path = "examples/todo_app_sqlite_viz" },
|
||||
{ name = "check", path = "examples/todomvc" },
|
||||
]
|
||||
[env]
|
||||
CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true
|
||||
|
||||
[tasks.check-stable]
|
||||
workspace = false
|
||||
clear = true
|
||||
dependencies = [
|
||||
{ name = "check", path = "examples/counter_without_macros" },
|
||||
{ name = "check", path = "examples/counters_stable" },
|
||||
]
|
||||
|
||||
[tasks.test]
|
||||
clear = true
|
||||
dependencies = [
|
||||
"test-all",
|
||||
"test-leptos_macro-example",
|
||||
"doc-leptos_macro-example",
|
||||
]
|
||||
|
||||
[tasks.test-all]
|
||||
command = "cargo"
|
||||
args = ["+nightly", "test-all-features"]
|
||||
install_crate = "cargo-all-features"
|
||||
|
||||
[tasks.test-leptos_macro-example]
|
||||
description = "Tests the leptos_macro/example to check if macro handles doc comments correctly"
|
||||
command = "cargo"
|
||||
args = ["+nightly", "test", "--doc"]
|
||||
cwd = "leptos_macro/example"
|
||||
install_crate = false
|
||||
|
||||
[tasks.doc-leptos_macro-example]
|
||||
description = "Docs the leptos_macro/example to check if macro handles doc comments correctly"
|
||||
command = "cargo"
|
||||
args = ["+nightly", "doc"]
|
||||
cwd = "leptos_macro/example"
|
||||
install_crate = false
|
||||
|
||||
[tasks.test-examples]
|
||||
description = "Run all unit and web tests for examples"
|
||||
[tasks.ci-examples]
|
||||
workspace = false
|
||||
cwd = "examples"
|
||||
command = "cargo"
|
||||
args = ["make", "test-unit-and-web"]
|
||||
|
||||
[tasks.verify-examples]
|
||||
description = "Run all quality checks and tests for examples"
|
||||
cwd = "examples"
|
||||
command = "cargo"
|
||||
args = ["make", "verify-flow"]
|
||||
args = ["make", "ci-clean"]
|
||||
|
||||
[tasks.clean-examples]
|
||||
description = "Clean all example projects"
|
||||
workspace = false
|
||||
cwd = "examples"
|
||||
command = "cargo"
|
||||
args = ["make", "clean-all"]
|
||||
|
||||
[env]
|
||||
RUSTFLAGS = ""
|
||||
LEPTOS_OUTPUT_NAME = "ci" # allows examples to check/build without cargo-leptos
|
||||
|
||||
[env.github-actions]
|
||||
RUSTFLAGS = "-D warnings"
|
||||
args = ["make", "clean"]
|
||||
|
||||
11
README.md
11
README.md
@@ -8,7 +8,6 @@
|
||||
[](https://discord.gg/YdRAhS7eQB)
|
||||
[](https://matrix.to/#/#leptos:matrix.org)
|
||||
|
||||
|
||||
[Website](https://leptos.dev) | [Book](https://leptos-rs.github.io/leptos/) | [Docs.rs](https://docs.rs/leptos/latest/leptos/) | [Playground](https://codesandbox.io/p/sandbox/leptos-rtfggt?file=%2Fsrc%2Fmain.rs%3A1%2C1) | [Discord](https://discord.gg/YdRAhS7eQB)
|
||||
|
||||
# Leptos
|
||||
@@ -69,7 +68,7 @@ Here are some resources for learning more about Leptos:
|
||||
|
||||
## `nightly` Note
|
||||
|
||||
Most of the examples assume you’re using `nightly` version of Rust. For this, you can either set your toolchain globally or on per-project basis.
|
||||
Most of the examples assume you’re using `nightly` version of Rust and the `nightly` feature of Leptos. To use `nightly` Rust, you can either set your toolchain globally or on per-project basis.
|
||||
|
||||
To set `nightly` as a default toolchain for all projects (and add the ability to compile Rust to WebAssembly, if you haven’t already):
|
||||
|
||||
@@ -87,13 +86,9 @@ channel = "nightly"
|
||||
targets = ["wasm32-unknown-unknown"]
|
||||
```
|
||||
|
||||
If you’re on `stable`, note the following:
|
||||
The `nightly` feature enables the function call syntax for accessing and setting signals, as opposed to `.get()` and `.set()`. This leads to a consistent mental model in which accessing a reactive value of any kind (a signal, memo, or derived signal) is always represented as a function call. This is only possible with nightly Rust and the `nightly` feature.
|
||||
|
||||
1. You need to enable the `"stable"` flag in `Cargo.toml`: `leptos = { version = "0.2", features = ["stable"] }`
|
||||
2. `nightly` enables the function call syntax for accessing and setting signals. If you’re using `stable`,
|
||||
you’ll just call `.get()`, `.set()`, or `.update()` manually. Check out the
|
||||
[`counters_stable` example](https://github.com/leptos-rs/leptos/blob/main/examples/counters_stable/src/main.rs)
|
||||
for examples of the correct API.
|
||||
> Note: The `nightly` feature is present on the main branch version right now, but not in 0.3.x. For 0.3.x, nightly is the default and `stable` has a special feature.
|
||||
|
||||
## `cargo-leptos`
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
l021 = { package = "leptos", version = "0.2.1" }
|
||||
leptos = { path = "../leptos", default-features = false, features = ["ssr"] }
|
||||
leptos = { path = "../leptos", features = ["ssr"] }
|
||||
sycamore = { version = "0.8", features = ["ssr"] }
|
||||
yew = { git = "https://github.com/yewstack/yew", features = ["ssr"] }
|
||||
tokio-test = "0.4"
|
||||
|
||||
7
cargo-make/check.toml
Normal file
7
cargo-make/check.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[tasks.check]
|
||||
alias = "check-all"
|
||||
|
||||
[tasks.check-all]
|
||||
command = "cargo"
|
||||
args = ["+nightly", "check-all-features"]
|
||||
install_crate = "cargo-all-features"
|
||||
9
cargo-make/lint.toml
Normal file
9
cargo-make/lint.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[tasks.pre-clippy]
|
||||
env = { CARGO_MAKE_CLIPPY_ARGS = "--all-targets --all-features -- -D warnings" }
|
||||
|
||||
[tasks.check-style]
|
||||
dependencies = ["check-format-flow", "clippy-flow"]
|
||||
|
||||
[tasks.check-format]
|
||||
env = { LEPTOS_PROJECT_DIRECTORY = "../" }
|
||||
args = ["fmt", "--", "--check", "--config-path", "${LEPTOS_PROJECT_DIRECTORY}"]
|
||||
18
cargo-make/main.toml
Normal file
18
cargo-make/main.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
extend = [
|
||||
{ path = "./check.toml" },
|
||||
{ path = "./lint.toml" },
|
||||
{ path = "./test.toml" },
|
||||
]
|
||||
|
||||
[env]
|
||||
RUSTFLAGS = ""
|
||||
LEPTOS_OUTPUT_NAME = "ci" # allows examples to check/build without cargo-leptos
|
||||
|
||||
[env.github-actions]
|
||||
RUSTFLAGS = "-D warnings"
|
||||
|
||||
[tasks.ci]
|
||||
dependencies = ["lint", "test"]
|
||||
|
||||
[tasks.lint]
|
||||
dependencies = ["check-format-flow"]
|
||||
7
cargo-make/test.toml
Normal file
7
cargo-make/test.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[tasks.test]
|
||||
alias = "test-all"
|
||||
|
||||
[tasks.test-all]
|
||||
command = "cargo"
|
||||
args = ["+nightly", "test-all-features"]
|
||||
install_crate = "cargo-all-features"
|
||||
2
docs/book/book.toml
Normal file
2
docs/book/book.toml
Normal file
@@ -0,0 +1,2 @@
|
||||
[output.html.playground]
|
||||
runnable = false
|
||||
@@ -14,24 +14,38 @@ If you don’t already have it installed, you can install Trunk by running
|
||||
cargo install trunk
|
||||
```
|
||||
|
||||
Create a basic Rust binary project
|
||||
Create a basic Rust project
|
||||
|
||||
```bash
|
||||
cargo init leptos-tutorial
|
||||
```
|
||||
|
||||
> We recommend using `nightly` Rust, as it enables [a few nice features](https://github.com/leptos-rs/leptos#nightly-note). To use `nightly` Rust with WebAssembly, you can run
|
||||
`cd` into your new `leptos-tutorial` project and add `leptos` as a dependency
|
||||
|
||||
```bash
|
||||
cargo add leptos --features=csr,nightly
|
||||
```
|
||||
|
||||
Or you can leave off `nighly` if you're using stable Rust
|
||||
```bash
|
||||
cargo add leptos --features=csr
|
||||
```
|
||||
|
||||
> Using `nightly` Rust, and the `nightly` feature in Leptos enables the function-call syntax for signal getters and setters that is used in most of this book.
|
||||
>
|
||||
> To use `nightly` Rust, you can run
|
||||
>
|
||||
> ```bash
|
||||
> rustup toolchain install nightly
|
||||
> rustup default nightly
|
||||
> rustup target add wasm32-unknown-unknown
|
||||
> ```
|
||||
>
|
||||
> If you’d rather use stable Rust with Leptos, you can do that too. In the guide and examples, you’ll just use the [`ReadSignal::get()`](https://docs.rs/leptos/latest/leptos/struct.ReadSignal.html#impl-SignalGet%3CT%3E-for-ReadSignal%3CT%3E) and [`WriteSignal::set()`](https://docs.rs/leptos/latest/leptos/struct.WriteSignal.html#impl-SignalGet%3CT%3E-for-ReadSignal%3CT%3E) methods instead of calling signal getters and setters as functions.
|
||||
|
||||
`cd` into your new `leptos-tutorial` project and add `leptos` as a dependency
|
||||
Make sure you've added the `wasm32-unknown-unknown` target so that Rust can compile your code to WebAssembly to run in the browser.
|
||||
|
||||
```bash
|
||||
cargo add leptos
|
||||
rustup target add wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
Create a simple `index.html` in the root of the `leptos-tutorial` directory
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
# Responding to Changes with create_effect
|
||||
@@ -183,3 +183,222 @@ data flow and of fine-grained reactive updates.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/1-basic-component-forked-8bte19?selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D&file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/1-basic-component-forked-8bte19?selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D&file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// So far, we've only been working with local state in components
|
||||
// We've only seen how to communicate between parent and child components
|
||||
// But there are also more general ways to manage global state
|
||||
//
|
||||
// The three best approaches to global state are
|
||||
// 1. Using the router to drive global state via the URL
|
||||
// 2. Passing signals through context
|
||||
// 3. Creating a global state struct and creating lenses into it with `create_slice`
|
||||
//
|
||||
// Option #1: URL as Global State
|
||||
// The next few sections of the tutorial will be about the router.
|
||||
// So for now, we'll just look at options #2 and #3.
|
||||
|
||||
// Option #2: Pass Signals through Context
|
||||
//
|
||||
// In virtual DOM libraries like React, using the Context API to manage global
|
||||
// state is a bad idea: because the entire app exists in a tree, changing
|
||||
// some value provided high up in the tree can cause the whole app to render.
|
||||
//
|
||||
// In fine-grained reactive libraries like Leptos, this is simply not the case.
|
||||
// You can create a signal in the root of your app and pass it down to other
|
||||
// components using provide_context(). Changing it will only cause rerendering
|
||||
// in the specific places it is actually used, not the whole app.
|
||||
#[component]
|
||||
fn Option2(cx: Scope) -> impl IntoView {
|
||||
// here we create a signal in the root that can be consumed
|
||||
// anywhere in the app.
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
// we'll pass the setter to specific components,
|
||||
// but provide the count itself to the whole app via context
|
||||
provide_context(cx, count);
|
||||
|
||||
view! { cx,
|
||||
<h1>"Option 2: Passing Signals"</h1>
|
||||
// SetterButton is allowed to modify the count
|
||||
<SetterButton set_count/>
|
||||
// These consumers can only read from it
|
||||
// But we could give them write access by passing `set_count` if we wanted
|
||||
<div style="display: flex">
|
||||
<FancyMath/>
|
||||
<ListItems/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A button that increments our global counter.
|
||||
#[component]
|
||||
fn SetterButton(cx: Scope, set_count: WriteSignal<u32>) -> impl IntoView {
|
||||
view! { cx,
|
||||
<div class="provider red">
|
||||
<button on:click=move |_| set_count.update(|count| *count += 1)>
|
||||
"Increment Global Count"
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that does some "fancy" math with the global count
|
||||
#[component]
|
||||
fn FancyMath(cx: Scope) -> impl IntoView {
|
||||
// here we consume the global count signal with `use_context`
|
||||
let count = use_context::<ReadSignal<u32>>(cx)
|
||||
// we know we just provided this in the parent component
|
||||
.expect("there to be a `count` signal provided");
|
||||
let is_even = move || count() & 1 == 0;
|
||||
|
||||
view! { cx,
|
||||
<div class="consumer blue">
|
||||
"The number "
|
||||
<strong>{count}</strong>
|
||||
{move || if is_even() {
|
||||
" is"
|
||||
} else {
|
||||
" is not"
|
||||
}}
|
||||
" even."
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that shows a list of items generated from the global count.
|
||||
#[component]
|
||||
fn ListItems(cx: Scope) -> impl IntoView {
|
||||
// again, consume the global count signal with `use_context`
|
||||
let count = use_context::<ReadSignal<u32>>(cx).expect("there to be a `count` signal provided");
|
||||
|
||||
let squares = move || {
|
||||
(0..count())
|
||||
.map(|n| view! { cx, <li>{n}<sup>"2"</sup> " is " {n * n}</li> })
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div class="consumer green">
|
||||
<ul>{squares}</ul>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
// Option #3: Create a Global State Struct
|
||||
//
|
||||
// You can use this approach to build a single global data structure
|
||||
// that holds the state for your whole app, and then access it by
|
||||
// taking fine-grained slices using `create_slice` or `create_memo`,
|
||||
// so that changing one part of the state doesn't cause parts of your
|
||||
// app that depend on other parts of the state to change.
|
||||
|
||||
#[derive(Default, Clone, Debug)]
|
||||
struct GlobalState {
|
||||
count: u32,
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Option3(cx: Scope) -> impl IntoView {
|
||||
// we'll provide a single signal that holds the whole state
|
||||
// each component will be responsible for creating its own "lens" into it
|
||||
let state = create_rw_signal(cx, GlobalState::default());
|
||||
provide_context(cx, state);
|
||||
|
||||
view! { cx,
|
||||
<h1>"Option 3: Passing Signals"</h1>
|
||||
<div class="red consumer" style="width: 100%">
|
||||
<h2>"Current Global State"</h2>
|
||||
<pre>
|
||||
{move || {
|
||||
format!("{:#?}", state.get())
|
||||
}}
|
||||
</pre>
|
||||
</div>
|
||||
<div style="display: flex">
|
||||
<GlobalStateCounter/>
|
||||
<GlobalStateInput/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that updates the count in the global state.
|
||||
#[component]
|
||||
fn GlobalStateCounter(cx: Scope) -> impl IntoView {
|
||||
let state = use_context::<RwSignal<GlobalState>>(cx).expect("state to have been provided");
|
||||
|
||||
// `create_slice` lets us create a "lens" into the data
|
||||
let (count, set_count) = create_slice(
|
||||
cx,
|
||||
// we take a slice *from* `state`
|
||||
state,
|
||||
// our getter returns a "slice" of the data
|
||||
|state| state.count,
|
||||
// our setter describes how to mutate that slice, given a new value
|
||||
|state, n| state.count = n,
|
||||
);
|
||||
|
||||
view! { cx,
|
||||
<div class="consumer blue">
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count(count() + 1);
|
||||
}
|
||||
>
|
||||
"Increment Global Count"
|
||||
</button>
|
||||
<br/>
|
||||
<span>"Count is: " {count}</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that updates the count in the global state.
|
||||
#[component]
|
||||
fn GlobalStateInput(cx: Scope) -> impl IntoView {
|
||||
let state = use_context::<RwSignal<GlobalState>>(cx).expect("state to have been provided");
|
||||
|
||||
// this slice is completely independent of the `count` slice
|
||||
// that we created in the other component
|
||||
// neither of them will cause the other to rerun
|
||||
let (name, set_name) = create_slice(
|
||||
cx,
|
||||
// we take a slice *from* `state`
|
||||
state,
|
||||
// our getter returns a "slice" of the data
|
||||
|state| state.name.clone(),
|
||||
// our setter describes how to mutate that slice, given a new value
|
||||
|state, n| state.name = n,
|
||||
);
|
||||
|
||||
view! { cx,
|
||||
<div class="consumer green">
|
||||
<input
|
||||
type="text"
|
||||
prop:value=name
|
||||
on:input=move |ev| {
|
||||
set_name(event_target_value(&ev));
|
||||
}
|
||||
/>
|
||||
<br/>
|
||||
<span>"Name is: " {name}</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
// This `main` function is the entry point into the app
|
||||
// It just mounts our component to the <body>
|
||||
// Because we defined it as `fn App`, we can now use it in a
|
||||
// template as <App/>
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <Option2/><Option3/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
- [Transition](./async/12_transition.md)
|
||||
- [Actions](./async/13_actions.md)
|
||||
- [Interlude: Projecting Children](./interlude_projecting_children.md)
|
||||
- [Responding to Changes with `create_effect`](./14_create_effect.md)
|
||||
- [Global State Management](./15_global_state.md)
|
||||
- [Router](./router/README.md)
|
||||
- [Defining `<Routes/>`](./router/16_routes.md)
|
||||
|
||||
@@ -47,6 +47,12 @@ Note that if you're using this with SSR too, the same Cargo profile will be appl
|
||||
target = "x86_64-unknown-linux-gnu" # or whatever
|
||||
```
|
||||
|
||||
Also note that in some cases, the cfg feature `has_std` will not be set, which may cause build errors with some dependencies which check for `has_std`. You may fix any build errors due to this by adding:
|
||||
```toml
|
||||
[build]
|
||||
rustflags = ["--cfg=has_std"]
|
||||
```
|
||||
|
||||
And you'll need to add `panic = "abort"` to `[profile.release]` in `Cargo.toml`. Note that this applies the same `build-std` and panic settings to your server binary, which may not be desirable. Some further exploration is probably needed here.
|
||||
|
||||
5. One of the sources of binary size in WASM binaries can be `serde` serialization/deserialization code. Leptos uses `serde` by default to serialize and deserialize resources created with `create_resource`. You might try experimenting with the `miniserde` and `serde-lite` features, which allow you to use those crates for serialization and deserialization instead; each only implements a subset of `serde`’s functionality, but typically optimizes for size over speed.
|
||||
|
||||
@@ -53,3 +53,89 @@ Resources also provide a `refetch()` method that allows you to manually reload t
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/10-async-resources-4z0qt3?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/10-async-resources-4z0qt3?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::*;
|
||||
|
||||
// Here we define an async function
|
||||
// This could be anything: a network request, database read, etc.
|
||||
// Here, we just multiply a number by 10
|
||||
async fn load_data(value: i32) -> i32 {
|
||||
// fake a one-second delay
|
||||
TimeoutFuture::new(1_000).await;
|
||||
value * 10
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
// this count is our synchronous, local state
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
// create_resource takes two arguments after its scope
|
||||
let async_data = create_resource(
|
||||
cx,
|
||||
// the first is the "source signal"
|
||||
count,
|
||||
// the second is the loader
|
||||
// it takes the source signal's value as its argument
|
||||
// and does some async work
|
||||
|value| async move { load_data(value).await },
|
||||
);
|
||||
// whenever the source signal changes, the loader reloads
|
||||
|
||||
// you can also create resources that only load once
|
||||
// just return the unit type () from the source signal
|
||||
// that doesn't depend on anything: we just load it once
|
||||
let stable = create_resource(cx, || (), |_| async move { load_data(1).await });
|
||||
|
||||
// we can access the resource values with .read()
|
||||
// this will reactively return None before the Future has resolved
|
||||
// and update to Some(T) when it has resolved
|
||||
let async_result = move || {
|
||||
async_data
|
||||
.read(cx)
|
||||
.map(|value| format!("Server returned {value:?}"))
|
||||
// This loading state will only show before the first load
|
||||
.unwrap_or_else(|| "Loading...".into())
|
||||
};
|
||||
|
||||
// the resource's loading() method gives us a
|
||||
// signal to indicate whether it's currently loading
|
||||
let loading = async_data.loading();
|
||||
let is_loading = move || if loading() { "Loading..." } else { "Idle." };
|
||||
|
||||
view! { cx,
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
}
|
||||
>
|
||||
"Click me"
|
||||
</button>
|
||||
<p>
|
||||
<code>"stable"</code>": " {move || stable.read(cx)}
|
||||
</p>
|
||||
<p>
|
||||
<code>"count"</code>": " {count}
|
||||
</p>
|
||||
<p>
|
||||
<code>"async_value"</code>": "
|
||||
{async_result}
|
||||
<br/>
|
||||
{is_loading}
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -72,3 +72,58 @@ This inversion of the flow of control makes it easier to add or remove individua
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/11-suspense-907niv?file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/11-suspense-907niv?file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::*;
|
||||
|
||||
async fn important_api_call(name: String) -> String {
|
||||
TimeoutFuture::new(1_000).await;
|
||||
name.to_ascii_uppercase()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (name, set_name) = create_signal(cx, "Bill".to_string());
|
||||
|
||||
// this will reload every time `name` changes
|
||||
let async_data = create_resource(
|
||||
cx,
|
||||
name,
|
||||
|name| async move { important_api_call(name).await },
|
||||
);
|
||||
|
||||
view! { cx,
|
||||
<input
|
||||
on:input=move |ev| {
|
||||
set_name(event_target_value(&ev));
|
||||
}
|
||||
prop:value=name
|
||||
/>
|
||||
<p><code>"name:"</code> {name}</p>
|
||||
<Suspense
|
||||
// the fallback will show whenever a resource
|
||||
// read "under" the suspense is loading
|
||||
fallback=move || view! { cx, <p>"Loading..."</p> }
|
||||
>
|
||||
// the children will be rendered once initially,
|
||||
// and then whenever any resources has been resolved
|
||||
<p>
|
||||
"Your shouting name is "
|
||||
{move || async_data.read(cx)}
|
||||
</p>
|
||||
</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -9,3 +9,76 @@ This example shows how you can create a simple tabbed contact list with `<Transi
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/12-transition-sn38sd?selection=%5B%7B%22endColumn%22%3A15%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A15%2C%22startLineNumber%22%3A2%7D%5D&file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/12-transition-sn38sd?selection=%5B%7B%22endColumn%22%3A15%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A15%2C%22startLineNumber%22%3A2%7D%5D&file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::*;
|
||||
|
||||
async fn important_api_call(id: usize) -> String {
|
||||
TimeoutFuture::new(1_000).await;
|
||||
match id {
|
||||
0 => "Alice",
|
||||
1 => "Bob",
|
||||
2 => "Carol",
|
||||
_ => "User not found",
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (tab, set_tab) = create_signal(cx, 0);
|
||||
|
||||
// this will reload every time `tab` changes
|
||||
let user_data = create_resource(cx, tab, |tab| async move { important_api_call(tab).await });
|
||||
|
||||
view! { cx,
|
||||
<div class="buttons">
|
||||
<button
|
||||
on:click=move |_| set_tab(0)
|
||||
class:selected=move || tab() == 0
|
||||
>
|
||||
"Tab A"
|
||||
</button>
|
||||
<button
|
||||
on:click=move |_| set_tab(1)
|
||||
class:selected=move || tab() == 1
|
||||
>
|
||||
"Tab B"
|
||||
</button>
|
||||
<button
|
||||
on:click=move |_| set_tab(2)
|
||||
class:selected=move || tab() == 2
|
||||
>
|
||||
"Tab C"
|
||||
</button>
|
||||
{move || if user_data.loading().get() {
|
||||
"Loading..."
|
||||
} else {
|
||||
""
|
||||
}}
|
||||
</div>
|
||||
<Transition
|
||||
// the fallback will show initially
|
||||
// on subsequent reloads, the current child will
|
||||
// continue showing
|
||||
fallback=move || view! { cx, <p>"Loading..."</p> }
|
||||
>
|
||||
<p>
|
||||
{move || user_data.read(cx)}
|
||||
</p>
|
||||
</Transition>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -11,7 +11,7 @@ Actions and resources seem similar, but they represent fundamentally different t
|
||||
Say we have some `async` function we want to run.
|
||||
|
||||
```rust
|
||||
async fn add_todo(new_title: &str) -> Uuid {
|
||||
async fn add_todo_request(new_title: &str) -> Uuid {
|
||||
/* do some stuff on the server to add a new todo */
|
||||
}
|
||||
```
|
||||
@@ -41,16 +41,16 @@ async fn add_todo(new_title: &str) -> Uuid {
|
||||
So in this case, all we need to do to create an action is
|
||||
|
||||
```rust
|
||||
let add_todo = create_action(cx, |input: &String| {
|
||||
let add_todo_action = create_action(cx, |input: &String| {
|
||||
let input = input.to_owned();
|
||||
async move { add_todo(&input).await }
|
||||
async move { add_todo_request(&input).await }
|
||||
});
|
||||
```
|
||||
|
||||
Rather than calling `add_todo` directly, we’ll call it with `.dispatch()`, as in
|
||||
Rather than calling `add_todo_action` directly, we’ll call it with `.dispatch()`, as in
|
||||
|
||||
```rust
|
||||
add_todo.dispatch("Some value".to_string());
|
||||
add_todo_action.dispatch("Some value".to_string());
|
||||
```
|
||||
|
||||
You can do this from an event listener, a timeout, or anywhere; because `.dispatch()` isn’t an `async` function, it can be called from a synchronous context.
|
||||
@@ -58,9 +58,9 @@ You can do this from an event listener, a timeout, or anywhere; because `.dispat
|
||||
Actions provide access to a few signals that synchronize between the asynchronous action you’re calling and the synchronous reactive system:
|
||||
|
||||
```rust
|
||||
let submitted = add_todo.input(); // RwSignal<Option<String>>
|
||||
let pending = add_todo.pending(); // ReadSignal<bool>
|
||||
let todo_id = add_todo.value(); // RwSignal<Option<Uuid>>
|
||||
let submitted = add_todo_action.input(); // RwSignal<Option<String>>
|
||||
let pending = add_todo_action.pending(); // ReadSignal<bool>
|
||||
let todo_id = add_todo_action.value(); // RwSignal<Option<Uuid>>
|
||||
```
|
||||
|
||||
This makes it easy to track the current state of your request, show a loading indicator, or do “optimistic UI” based on the assumption that the submission will succeed.
|
||||
@@ -73,7 +73,7 @@ view! { cx,
|
||||
on:submit=move |ev| {
|
||||
ev.prevent_default(); // don't reload the page...
|
||||
let input = input_ref.get().expect("input to exist");
|
||||
add_todo.dispatch(input.value());
|
||||
add_todo_action.dispatch(input.value());
|
||||
}
|
||||
>
|
||||
<label>
|
||||
@@ -94,3 +94,83 @@ Now, there’s a chance this all seems a little over-complicated, or maybe too r
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/10-async-resources-forked-hgpfp0?selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A4%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A4%7D%5D&file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/10-async-resources-forked-hgpfp0?selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A4%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A4%7D%5D&file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::{html::Input, *};
|
||||
use uuid::Uuid;
|
||||
|
||||
// Here we define an async function
|
||||
// This could be anything: a network request, database read, etc.
|
||||
// Think of it as a mutation: some imperative async action you run,
|
||||
// whereas a resource would be some async data you load
|
||||
async fn add_todo(text: &str) -> Uuid {
|
||||
_ = text;
|
||||
// fake a one-second delay
|
||||
TimeoutFuture::new(1_000).await;
|
||||
// pretend this is a post ID or something
|
||||
Uuid::new_v4()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
// an action takes an async function with single argument
|
||||
// it can be a simple type, a struct, or ()
|
||||
let add_todo = create_action(cx, |input: &String| {
|
||||
// the input is a reference, but we need the Future to own it
|
||||
// this is important: we need to clone and move into the Future
|
||||
// so it has a 'static lifetime
|
||||
let input = input.to_owned();
|
||||
async move { add_todo(&input).await }
|
||||
});
|
||||
|
||||
// actions provide a bunch of synchronous, reactive variables
|
||||
// that tell us different things about the state of the action
|
||||
let submitted = add_todo.input();
|
||||
let pending = add_todo.pending();
|
||||
let todo_id = add_todo.value();
|
||||
|
||||
let input_ref = create_node_ref::<Input>(cx);
|
||||
|
||||
view! { cx,
|
||||
<form
|
||||
on:submit=move |ev| {
|
||||
ev.prevent_default(); // don't reload the page...
|
||||
let input = input_ref.get().expect("input to exist");
|
||||
add_todo.dispatch(input.value());
|
||||
}
|
||||
>
|
||||
<label>
|
||||
"What do you need to do?"
|
||||
<input type="text"
|
||||
node_ref=input_ref
|
||||
/>
|
||||
</label>
|
||||
<button type="submit">"Add Todo"</button>
|
||||
</form>
|
||||
<p>{move || pending().then(|| "Loading...")}</p>
|
||||
<p>
|
||||
"Submitted: "
|
||||
<code>{move || format!("{:#?}", submitted())}</code>
|
||||
</p>
|
||||
<p>
|
||||
"Pending: "
|
||||
<code>{move || format!("{:#?}", pending())}</code>
|
||||
</p>
|
||||
<p>
|
||||
"Todo ID: "
|
||||
<code>{move || format!("{:#?}", todo_id())}</code>
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -29,9 +29,9 @@ where
|
||||
}
|
||||
```
|
||||
|
||||
This is pretty straightforward: when the user is logged in, we want to show `children`. Until if the user is not logged in, we want to show `fallback`. And while we’re waiting to find out, we just render `()`, i.e., nothing.
|
||||
This is pretty straightforward: when the user is logged in, we want to show `children`. If the user is not logged in, we want to show `fallback`. And while we’re waiting to find out, we just render `()`, i.e., nothing.
|
||||
|
||||
In other words, we want to pass the children of `<WhenLoaded/>` _through_ the `<Suspense/>` component to become the children of the `<Show/>`. This is what I mean by “projection.”
|
||||
In other words, we want to pass the children of `<LoggedIn/>` _through_ the `<Suspense/>` component to become the children of the `<Show/>`. This is what I mean by “projection.”
|
||||
|
||||
This won’t compile.
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ That’s where the [`leptos_meta`](https://docs.rs/leptos_meta/latest/leptos_met
|
||||
|
||||
`leptos_meta` also provides a [`<Script/>`](https://docs.rs/leptos_meta/latest/leptos_meta/fn.Script.html) component, and it’s worth pausing here for a second. All of the other components we’ve considered inject `<head>`-only elements in the `<head>`. But a `<script>` can also be included in the body.
|
||||
|
||||
There’s a very simple way to determine whether you should use a capital-S `<Script/>` component or a lowercase-s `<script>` element: the `<Script/>` component will be rendered in the `<head>`, and the `<script>` element will be rendered wherever in your the `<body>` of your user interface you put in, alongside other normal HTML elements. These cause JavaScript to load and run at different times, so use whichever is appropriate to your needs.
|
||||
There’s a very simple way to determine whether you should use a capital-S `<Script/>` component or a lowercase-s `<script>` element: the `<Script/>` component will be rendered in the `<head>`, and the `<script>` element will be rendered wherever in the `<body>` of your user interface you put it in, alongside other normal HTML elements. These cause JavaScript to load and run at different times, so use whichever is appropriate to your needs.
|
||||
|
||||
## `<Body/>` and `<Html/>`
|
||||
|
||||
|
||||
@@ -112,3 +112,195 @@ Every time `count` is updated, this effect wil rerun. This is what allows reacti
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/serene-thompson-40974n?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/serene-thompson-40974n?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::html::Input;
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
// Just making a visible log here
|
||||
// You can ignore this...
|
||||
let log = create_rw_signal::<Vec<String>>(cx, vec![]);
|
||||
let logged = move || log().join("\n");
|
||||
provide_context(cx, log);
|
||||
|
||||
view! { cx,
|
||||
<CreateAnEffect/>
|
||||
<pre>{logged}</pre>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn CreateAnEffect(cx: Scope) -> impl IntoView {
|
||||
let (first, set_first) = create_signal(cx, String::new());
|
||||
let (last, set_last) = create_signal(cx, String::new());
|
||||
let (use_last, set_use_last) = create_signal(cx, true);
|
||||
|
||||
// this will add the name to the log
|
||||
// any time one of the source signals changes
|
||||
create_effect(cx, move |_| {
|
||||
log(
|
||||
cx,
|
||||
if use_last() {
|
||||
format!("{} {}", first(), last())
|
||||
} else {
|
||||
first()
|
||||
},
|
||||
)
|
||||
});
|
||||
|
||||
view! { cx,
|
||||
<h1><code>"create_effect"</code> " Version"</h1>
|
||||
<form>
|
||||
<label>
|
||||
"First Name"
|
||||
<input type="text" name="first" prop:value=first
|
||||
on:change=move |ev| set_first(event_target_value(&ev))
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
"Last Name"
|
||||
<input type="text" name="last" prop:value=last
|
||||
on:change=move |ev| set_last(event_target_value(&ev))
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
"Show Last Name"
|
||||
<input type="checkbox" name="use_last" prop:checked=use_last
|
||||
on:change=move |ev| set_use_last(event_target_checked(&ev))
|
||||
/>
|
||||
</label>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ManualVersion(cx: Scope) -> impl IntoView {
|
||||
let first = create_node_ref::<Input>(cx);
|
||||
let last = create_node_ref::<Input>(cx);
|
||||
let use_last = create_node_ref::<Input>(cx);
|
||||
|
||||
let mut prev_name = String::new();
|
||||
let on_change = move |_| {
|
||||
log(cx, " listener");
|
||||
let first = first.get().unwrap();
|
||||
let last = last.get().unwrap();
|
||||
let use_last = use_last.get().unwrap();
|
||||
let this_one = if use_last.checked() {
|
||||
format!("{} {}", first.value(), last.value())
|
||||
} else {
|
||||
first.value()
|
||||
};
|
||||
|
||||
if this_one != prev_name {
|
||||
log(cx, &this_one);
|
||||
prev_name = this_one;
|
||||
}
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<h1>"Manual Version"</h1>
|
||||
<form on:change=on_change>
|
||||
<label>
|
||||
"First Name"
|
||||
<input type="text" name="first"
|
||||
node_ref=first
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
"Last Name"
|
||||
<input type="text" name="last"
|
||||
node_ref=last
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
"Show Last Name"
|
||||
<input type="checkbox" name="use_last"
|
||||
checked
|
||||
node_ref=use_last
|
||||
/>
|
||||
</label>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn EffectVsDerivedSignal(cx: Scope) -> impl IntoView {
|
||||
let (my_value, set_my_value) = create_signal(cx, String::new());
|
||||
// Don't do this.
|
||||
/*let (my_optional_value, set_optional_my_value) = create_signal(cx, Option::<String>::None);
|
||||
|
||||
create_effect(cx, move |_| {
|
||||
if !my_value.get().is_empty() {
|
||||
set_optional_my_value(Some(my_value.get()));
|
||||
} else {
|
||||
set_optional_my_value(None);
|
||||
}
|
||||
});*/
|
||||
|
||||
// Do this
|
||||
let my_optional_value =
|
||||
move || (!my_value.with(String::is_empty)).then(|| Some(my_value.get()));
|
||||
|
||||
view! { cx,
|
||||
<input
|
||||
prop:value=my_value
|
||||
on:input= move |ev| set_my_value(event_target_value(&ev))
|
||||
/>
|
||||
|
||||
<p>
|
||||
<code>"my_optional_value"</code>
|
||||
" is "
|
||||
<code>
|
||||
<Show
|
||||
when=move || my_optional_value().is_some()
|
||||
fallback=|cx| view! { cx, "None" }
|
||||
>
|
||||
"Some(\"" {my_optional_value().unwrap()} "\")"
|
||||
</Show>
|
||||
</code>
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
/*#[component]
|
||||
pub fn Show<F, W, IV>(
|
||||
/// The scope the component is running in
|
||||
cx: Scope,
|
||||
/// The components Show wraps
|
||||
children: Box<dyn Fn(Scope) -> Fragment>,
|
||||
/// A closure that returns a bool that determines whether this thing runs
|
||||
when: W,
|
||||
/// A closure that returns what gets rendered if the when statement is false
|
||||
fallback: F,
|
||||
) -> impl IntoView
|
||||
where
|
||||
W: Fn() -> bool + 'static,
|
||||
F: Fn(Scope) -> IV + 'static,
|
||||
IV: IntoView,
|
||||
{
|
||||
let memoized_when = create_memo(cx, move |_| when());
|
||||
|
||||
move || match memoized_when.get() {
|
||||
true => children(cx).into_view(cx),
|
||||
false => fallback(cx).into_view(cx),
|
||||
}
|
||||
}*/
|
||||
|
||||
fn log(cx: Scope, msg: impl std::fmt::Display) {
|
||||
let log = use_context::<RwSignal<Vec<String>>>(cx).unwrap();
|
||||
log.update(|log| log.push(msg.to_string()));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -68,7 +68,7 @@ pub fn SimpleCounter(cx: Scope) -> impl IntoView {
|
||||
|
||||
The `SimpleCounter` function itself runs once. The `value` signal is created once. The framework hands off the `increment` function to the browser as an event listener. When you click the button, the browser calls `increment`, which updates `value` via `set_value`. And that updates the single text node represented in our view by `{value}`.
|
||||
|
||||
Closures are key to reactivity. They provide the framework with the ability to rerun the smallest possible unit of your application in responsive to a change.
|
||||
Closures are key to reactivity. They provide the framework with the ability to rerun the smallest possible unit of your application in response to a change.
|
||||
|
||||
So remember two things:
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ There are four basic signal operations:
|
||||
1. [`.get()`](https://docs.rs/leptos/latest/leptos/struct.ReadSignal.html#impl-SignalGet%3CT%3E-for-ReadSignal%3CT%3E) clones the current value of the signal and tracks any future changes to the value reactively.
|
||||
2. [`.with()`](https://docs.rs/leptos/latest/leptos/struct.ReadSignal.html#impl-SignalWith%3CT%3E-for-ReadSignal%3CT%3E) takes a function, which receives the current value of the signal by reference (`&T`), and tracks any future changes.
|
||||
3. [`.set()`](https://docs.rs/leptos/latest/leptos/struct.WriteSignal.html#impl-SignalSet%3CT%3E-for-WriteSignal%3CT%3E) replaces the current value of the signal and notifies any subscribers that they need to update.
|
||||
4. [`.update()`](https://docs.rs/leptos/latest/leptos/struct.WriteSignal.html#impl-SignalUpdate%3CT%3E-for-WriteSignal%3CT%3E) takes a function, which receives a mutable reference to the current value of the signal (`&T`), and notifies any subscribers that they need to update. (`.update()` doesn’t return the value returned by the closure, but you can use [`.try_update()`](https://docs.rs/leptos/latest/leptos/trait.SignalUpdate.html#tymethod.try_update) if you need to; for example, if you’re removing an item from a `Vec<_>` and want the removed item.)
|
||||
4. [`.update()`](https://docs.rs/leptos/latest/leptos/struct.WriteSignal.html#impl-SignalUpdate%3CT%3E-for-WriteSignal%3CT%3E) takes a function, which receives a mutable reference to the current value of the signal (`&mut T`), and notifies any subscribers that they need to update. (`.update()` doesn’t return the value returned by the closure, but you can use [`.try_update()`](https://docs.rs/leptos/latest/leptos/trait.SignalUpdate.html#tymethod.try_update) if you need to; for example, if you’re removing an item from a `Vec<_>` and want the removed item.)
|
||||
|
||||
Calling a `ReadSignal` as a function is syntax sugar for `.get()`. Calling a `WriteSignal` as a function is syntax sugar for `.set()`. So
|
||||
|
||||
@@ -99,7 +99,7 @@ let clear_handler = move |_| {
|
||||
### If you really must...
|
||||
**4) Create an effect to write to B whenever A changes.** This is officially discouraged, for several reasons:
|
||||
a) It will always be less efficient, as it means every time A updates you do two full trips through the reactive process. (You set A, which causes the effect to run, as well as any other effects that depend on A. Then you set B, which causes any effects that depend on B to run.)
|
||||
b) It increases your chances of accidentally creating things like infinite loops or over-re-running effects. This is the kind of ping-ponging, reactive spaghetti code that was common in the early 2010s and that we try to avoid with things like read-write segregation and discouraging writing to signals frome effects.
|
||||
b) It increases your chances of accidentally creating things like infinite loops or over-re-running effects. This is the kind of ping-ponging, reactive spaghetti code that was common in the early 2010s and that we try to avoid with things like read-write segregation and discouraging writing to signals from effects.
|
||||
|
||||
In most situations, it’s best to rewrite things such that there’s a clear, top-down data flow based on derived signals or memos. But this isn’t the end of the world.
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ You can go even deeper. Say you want to have tabs for each contact’s address,
|
||||
|
||||
## `<Outlet/>`
|
||||
|
||||
Parent routes do not automatically render their nested routes. After all, they are just components; they don’t know exactly where they should render their children, and “just stick at at the end of the parent component” is not a great answer.
|
||||
Parent routes do not automatically render their nested routes. After all, they are just components; they don’t know exactly where they should render their children, and “just stick it at the end of the parent component” is not a great answer.
|
||||
|
||||
Instead, you tell a parent component where to render any nested components with an `<Outlet/>` component. The `<Outlet/>` simply renders one of two things:
|
||||
|
||||
@@ -170,3 +170,121 @@ In fact, in this case, we don’t even need to rerender the `<Contact/>` compone
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<h1>"Contact App"</h1>
|
||||
// this <nav> will show on every routes,
|
||||
// because it's outside the <Routes/>
|
||||
// note: we can just use normal <a> tags
|
||||
// and the router will use client-side navigation
|
||||
<nav>
|
||||
<h2>"Navigation"</h2>
|
||||
<a href="/">"Home"</a>
|
||||
<a href="/contacts">"Contacts"</a>
|
||||
</nav>
|
||||
<main>
|
||||
<Routes>
|
||||
// / just has an un-nested "Home"
|
||||
<Route path="/" view=|cx| view! { cx,
|
||||
<h3>"Home"</h3>
|
||||
}/>
|
||||
// /contacts has nested routes
|
||||
<Route
|
||||
path="/contacts"
|
||||
view=|cx| view! { cx, <ContactList/> }
|
||||
>
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=|cx| view! { cx,
|
||||
<ContactInfo/>
|
||||
}>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
</div>
|
||||
}/>
|
||||
<Route path="conversations" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Conversations)"
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
// if no id specified, fall back
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="select-user">
|
||||
"Select a user to view contact info."
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactList(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<div class="contact-list">
|
||||
// here's our contact list component itself
|
||||
<div class="contact-list-contacts">
|
||||
<h3>"Contacts"</h3>
|
||||
<A href="alice">"Alice"</A>
|
||||
<A href="bob">"Bob"</A>
|
||||
<A href="steve">"Steve"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> will show the nested child route
|
||||
// we can position this outlet wherever we want
|
||||
// within the layout
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactInfo(cx: Scope) -> impl IntoView {
|
||||
// we can access the :id param reactively with `use_params_map`
|
||||
let params = use_params_map(cx);
|
||||
let id = move || params.with(|params| params.get("id").cloned().unwrap_or_default());
|
||||
|
||||
// imagine we're loading data from an API here
|
||||
let name = move || match id().as_str() {
|
||||
"alice" => "Alice",
|
||||
"bob" => "Bob",
|
||||
"steve" => "Steve",
|
||||
_ => "User not found.",
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div class="contact-info">
|
||||
<h4>{name}</h4>
|
||||
<div class="tabs">
|
||||
<A href="" exact=true>"Contact Info"</A>
|
||||
<A href="conversations">"Conversations"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> here is the tabs that are nested
|
||||
// underneath the /contacts/:id route
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -70,10 +70,128 @@ let id = move || {
|
||||
This can get a little messy: deriving a signal that wraps an `Option<_>` or `Result<_>` can involve a couple steps. But it’s worth doing this for two reasons:
|
||||
|
||||
1. It’s correct, i.e., it forces you to consider the cases, “What if the user doesn’t pass a value for this query field? What if they pass an invalid value?”
|
||||
2. It’s performant. Specifically, when you navigate between different paths that match the same `<Route/>` with only params or the query changing, you can get fine-grained updates to different parts of your app without rerendering. For example, navigating between different contacts in our contact-list example does a targeted update to the name field (and eventually contact info) without needing to replacing or rerender the wrapping `<Contact/>`. This is what fine-grained reactivity is for.
|
||||
2. It’s performant. Specifically, when you navigate between different paths that match the same `<Route/>` with only params or the query changing, you can get fine-grained updates to different parts of your app without rerendering. For example, navigating between different contacts in our contact-list example does a targeted update to the name field (and eventually contact info) without needing to replace or rerender the wrapping `<Contact/>`. This is what fine-grained reactivity is for.
|
||||
|
||||
> This is the same example from the previous section. The router is such an integrated system that it makes sense to provide a single example highlighting multiple features, even if we haven’t explain them all yet.
|
||||
> This is the same example from the previous section. The router is such an integrated system that it makes sense to provide a single example highlighting multiple features, even if we haven’t explained them all yet.
|
||||
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<h1>"Contact App"</h1>
|
||||
// this <nav> will show on every routes,
|
||||
// because it's outside the <Routes/>
|
||||
// note: we can just use normal <a> tags
|
||||
// and the router will use client-side navigation
|
||||
<nav>
|
||||
<h2>"Navigation"</h2>
|
||||
<a href="/">"Home"</a>
|
||||
<a href="/contacts">"Contacts"</a>
|
||||
</nav>
|
||||
<main>
|
||||
<Routes>
|
||||
// / just has an un-nested "Home"
|
||||
<Route path="/" view=|cx| view! { cx,
|
||||
<h3>"Home"</h3>
|
||||
}/>
|
||||
// /contacts has nested routes
|
||||
<Route
|
||||
path="/contacts"
|
||||
view=|cx| view! { cx, <ContactList/> }
|
||||
>
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=|cx| view! { cx,
|
||||
<ContactInfo/>
|
||||
}>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
</div>
|
||||
}/>
|
||||
<Route path="conversations" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Conversations)"
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
// if no id specified, fall back
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="select-user">
|
||||
"Select a user to view contact info."
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactList(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<div class="contact-list">
|
||||
// here's our contact list component itself
|
||||
<div class="contact-list-contacts">
|
||||
<h3>"Contacts"</h3>
|
||||
<A href="alice">"Alice"</A>
|
||||
<A href="bob">"Bob"</A>
|
||||
<A href="steve">"Steve"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> will show the nested child route
|
||||
// we can position this outlet wherever we want
|
||||
// within the layout
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactInfo(cx: Scope) -> impl IntoView {
|
||||
// we can access the :id param reactively with `use_params_map`
|
||||
let params = use_params_map(cx);
|
||||
let id = move || params.with(|params| params.get("id").cloned().unwrap_or_default());
|
||||
|
||||
// imagine we're loading data from an API here
|
||||
let name = move || match id().as_str() {
|
||||
"alice" => "Alice",
|
||||
"bob" => "Bob",
|
||||
"steve" => "Steve",
|
||||
_ => "User not found.",
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div class="contact-info">
|
||||
<h4>{name}</h4>
|
||||
<div class="tabs">
|
||||
<A href="" exact=true>"Contact Info"</A>
|
||||
<A href="conversations">"Conversations"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> here is the tabs that are nested
|
||||
// underneath the /contacts/:id route
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -21,3 +21,121 @@ The router also provides an [`<A>`](https://docs.rs/leptos_router/latest/leptos_
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<h1>"Contact App"</h1>
|
||||
// this <nav> will show on every routes,
|
||||
// because it's outside the <Routes/>
|
||||
// note: we can just use normal <a> tags
|
||||
// and the router will use client-side navigation
|
||||
<nav>
|
||||
<h2>"Navigation"</h2>
|
||||
<a href="/">"Home"</a>
|
||||
<a href="/contacts">"Contacts"</a>
|
||||
</nav>
|
||||
<main>
|
||||
<Routes>
|
||||
// / just has an un-nested "Home"
|
||||
<Route path="/" view=|cx| view! { cx,
|
||||
<h3>"Home"</h3>
|
||||
}/>
|
||||
// /contacts has nested routes
|
||||
<Route
|
||||
path="/contacts"
|
||||
view=|cx| view! { cx, <ContactList/> }
|
||||
>
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=|cx| view! { cx,
|
||||
<ContactInfo/>
|
||||
}>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
</div>
|
||||
}/>
|
||||
<Route path="conversations" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Conversations)"
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
// if no id specified, fall back
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="select-user">
|
||||
"Select a user to view contact info."
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactList(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<div class="contact-list">
|
||||
// here's our contact list component itself
|
||||
<div class="contact-list-contacts">
|
||||
<h3>"Contacts"</h3>
|
||||
<A href="alice">"Alice"</A>
|
||||
<A href="bob">"Bob"</A>
|
||||
<A href="steve">"Steve"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> will show the nested child route
|
||||
// we can position this outlet wherever we want
|
||||
// within the layout
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactInfo(cx: Scope) -> impl IntoView {
|
||||
// we can access the :id param reactively with `use_params_map`
|
||||
let params = use_params_map(cx);
|
||||
let id = move || params.with(|params| params.get("id").cloned().unwrap_or_default());
|
||||
|
||||
// imagine we're loading data from an API here
|
||||
let name = move || match id().as_str() {
|
||||
"alice" => "Alice",
|
||||
"bob" => "Bob",
|
||||
"steve" => "Steve",
|
||||
_ => "User not found.",
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div class="contact-info">
|
||||
<h4>{name}</h4>
|
||||
<div class="tabs">
|
||||
<A href="" exact=true>"Contact Info"</A>
|
||||
<A href="conversations">"Conversations"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> here is the tabs that are nested
|
||||
// underneath the /contacts/:id route
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# The `<Form/>` Component
|
||||
|
||||
Links and forms sometimes seem completely unrelated. But in fact, they work in very similar ways.
|
||||
Links and forms sometimes seem completely unrelated. But, in fact, they work in very similar ways.
|
||||
|
||||
In plain HTML, there are three ways to navigate to another page:
|
||||
|
||||
1. An `<a>` element that links to another page. Navigates to the URL in its `href` attribute with the `GET` HTTP method.
|
||||
2. A `<form method="GET">`. Navigates to the URL in its `action` attribute with the `GET` HTTP method and the form data from its inputs encoded in the URL query string.
|
||||
3. A `<form method="POST">`. Navigates to the URL in its `action` attribute with the `POST` HTTP method and the form data from its inputs encoded in the body of the request.
|
||||
1. An `<a>` element that links to another page: Navigates to the URL in its `href` attribute with the `GET` HTTP method.
|
||||
2. A `<form method="GET">`: Navigates to the URL in its `action` attribute with the `GET` HTTP method and the form data from its inputs encoded in the URL query string.
|
||||
3. A `<form method="POST">`: Navigates to the URL in its `action` attribute with the `POST` HTTP method and the form data from its inputs encoded in the body of the request.
|
||||
|
||||
Since we have a client-side router, we can do client-side link navigations without reloading the page, i.e., without a full round-trip to the server and back. It makes sense that we can do client-side form navigations in the same way.
|
||||
|
||||
@@ -65,3 +65,117 @@ You’ll notice that this version drops the `Submit` button. Instead, we add an
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/16-router-forked-hrrt3h?file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/16-router-forked-hrrt3h?file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<h1><code>"<Form/>"</code></h1>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=|cx| view! { cx, <FormExample/> }/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn FormExample(cx: Scope) -> impl IntoView {
|
||||
// reactive access to URL query
|
||||
let query = use_query_map(cx);
|
||||
let name = move || query().get("name").cloned().unwrap_or_default();
|
||||
let number = move || query().get("number").cloned().unwrap_or_default();
|
||||
let select = move || query().get("select").cloned().unwrap_or_default();
|
||||
|
||||
view! { cx,
|
||||
// read out the URL query strings
|
||||
<table>
|
||||
<tr>
|
||||
<td><code>"name"</code></td>
|
||||
<td>{name}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>"number"</code></td>
|
||||
<td>{number}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>"select"</code></td>
|
||||
<td>{select}</td>
|
||||
</tr>
|
||||
</table>
|
||||
// <Form/> will navigate whenever submitted
|
||||
<h2>"Manual Submission"</h2>
|
||||
<Form method="GET" action="">
|
||||
// input names determine query string key
|
||||
<input type="text" name="name" value=name/>
|
||||
<input type="number" name="number" value=number/>
|
||||
<select name="select">
|
||||
// `selected` will set which starts as selected
|
||||
<option selected=move || select() == "A">
|
||||
"A"
|
||||
</option>
|
||||
<option selected=move || select() == "B">
|
||||
"B"
|
||||
</option>
|
||||
<option selected=move || select() == "C">
|
||||
"C"
|
||||
</option>
|
||||
</select>
|
||||
// submitting should cause a client-side
|
||||
// navigation, not a full reload
|
||||
<input type="submit"/>
|
||||
</Form>
|
||||
// This <Form/> uses some JavaScript to submit
|
||||
// on every input
|
||||
<h2>"Automatic Submission"</h2>
|
||||
<Form method="GET" action="">
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
value=name
|
||||
// this oninput attribute will cause the
|
||||
// form to submit on every input to the field
|
||||
oninput="this.form.requestSubmit()"
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
name="number"
|
||||
value=number
|
||||
oninput="this.form.requestSubmit()"
|
||||
/>
|
||||
<select name="select"
|
||||
onchange="this.form.requestSubmit()"
|
||||
>
|
||||
<option selected=move || select() == "A">
|
||||
"A"
|
||||
</option>
|
||||
<option selected=move || select() == "B">
|
||||
"B"
|
||||
</option>
|
||||
<option selected=move || select() == "C">
|
||||
"C"
|
||||
</option>
|
||||
</select>
|
||||
// submitting should cause a client-side
|
||||
// navigation, not a full reload
|
||||
<input type="submit"/>
|
||||
</Form>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
|
||||
Routing drives most websites. A router is the answer to the question, “Given this URL, what should appear on the page?”
|
||||
|
||||
A URL consists of many parts. For example, the URL `https://leptos.dev/blog/search?q=Search#results` consists of
|
||||
A URL consists of many parts. For example, the URL `https://my-cool-blog.com/blog/search?q=Search#results` consists of
|
||||
|
||||
- a _scheme_: `https`
|
||||
- a _domain_: `leptos.dev`
|
||||
- a _domain_: `my-cool-blog.com`
|
||||
- a **path**: `/blog/search`
|
||||
- a **query** (or **search**): `?q=Search`
|
||||
- a _hash_: `#results`
|
||||
|
||||
@@ -97,6 +97,14 @@ In other words, you have two choices:
|
||||
|
||||
**But remember**: Leptos will handle all the details of this encoding and decoding for you. When you use a server function, it looks just like calling any other asynchronous function!
|
||||
|
||||
> **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 don’t support `PUT` or `DELETE`, and they don’t 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. As we’ll see [in a later chapter](../progressive_enhancement), this isn’t always a great idea.
|
||||
>
|
||||
> The CBOR encoding is suported for historical reasons; an earlier version of server functions used a URL encoding that didn’t 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.
|
||||
|
||||
## An Important Note on Security
|
||||
|
||||
Server functions are a cool technology, but it’s very important to remember. **Server functions are not magic; they’re syntax sugar for defining a public API.** The _body_ of a server function is never made public; it’s just part of your server binary. But the server function is a publicly accessible API endpoint, and it’s return value is just a JSON or similar blob. You should _never_ return something sensitive from a server function.
|
||||
|
||||
@@ -62,6 +62,8 @@ pub async fn axum_extract(cx: Scope) -> Result<String, ServerFnError> {
|
||||
|
||||
These are relatively simple examples accessing basic data from the server. But you can use extractors to access things like headers, cookies, database connection pools, and more, using the exact same `extract()` pattern.
|
||||
|
||||
> Note: For now, the Axum `extract` function only supports extractors for which the state is `()`, i.e., you can't yet use it to extract `State(_)`. You can access `State(_)` by using a custom handler that extracts the state and then provides it via context. [Click here for an example](https://github.com/leptos-rs/leptos/blob/a5f73b441c079f9138102b3a7d8d4828f045448c/examples/session_auth_axum/src/main.rs#L91-L92).
|
||||
|
||||
## A Note about Data-Loading Patterns
|
||||
|
||||
Because Actix and (especially) Axum are built on the idea of a single round-trip HTTP request and response, you typically run extractors near the “top” of your application (i.e., before you start rendering) and use the extracted data to determine how that should be rendered. Before you render a `<button>`, you load all the data your app could need. And any given route handler needs to know all the data that will need to be extracted by that route.
|
||||
|
||||
@@ -1 +1,74 @@
|
||||
# Responses and Redirects
|
||||
|
||||
Extractors provide an easy way to access request data inside server functions. Leptos also provides a way to modify the HTTP response, using the `ResponseOptions` type (see docs for [Actix](https://docs.rs/leptos_actix/latest/leptos_actix/struct.ResponseOptions.html) or [Axum](https://docs.rs/leptos_axum/latest/leptos_axum/struct.ResponseOptions.html)) types and the `redirect` helper function (see docs for [Actix](https://docs.rs/leptos_actix/latest/leptos_actix/fn.redirect.html) or [Axum](https://docs.rs/leptos_axum/latest/leptos_axum/fn.redirect.html)).
|
||||
|
||||
## `ResponseOptions`
|
||||
|
||||
`ResponseOptions` is provided via context during the initial server rendering response and during any subsequent server function call. It allows you to easily set the status code for the HTTP response, or to add headers to the HTTP response, e.g., to set cookies.
|
||||
|
||||
```rust
|
||||
#[server(TeaAndCookies)]
|
||||
pub async fn tea_and_cookies(cx: Scope) -> Result<(), ServerFnError> {
|
||||
use actix_web::{cookie::Cookie, http::header, http::header::HeaderValue};
|
||||
use leptos_actix::ResponseOptions;
|
||||
|
||||
// pull ResponseOptions from context
|
||||
let response = expect_context::<ResponseOptions>(cx);
|
||||
|
||||
// set the HTTP status code
|
||||
response.set_status(StatusCode::IM_A_TEAPOT);
|
||||
|
||||
// set a cookie in the HTTP response
|
||||
let mut cookie = Cookie::build("biscuits", "yes").finish();
|
||||
if let Ok(cookie) = HeaderValue::from_str(&cookie.to_string()) {
|
||||
res.insert_header(header::SET_COOKIE, cookie);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `redirect`
|
||||
|
||||
One common modification to an HTTP response is to redirect to another page. The Actix and Axum integrations provide a `redirect` function to make this easy to do. `redirect` simply sets an HTTP status code of `302 Found` and sets the `Location` header.
|
||||
|
||||
Here’s a simplified example from our [`session_auth_axum` example](https://github.com/leptos-rs/leptos/blob/a5f73b441c079f9138102b3a7d8d4828f045448c/examples/session_auth_axum/src/auth.rs#L154-L181).
|
||||
|
||||
```rust
|
||||
#[server(Login, "/api")]
|
||||
pub async fn login(
|
||||
cx: Scope,
|
||||
username: String,
|
||||
password: String,
|
||||
remember: Option<String>,
|
||||
) -> Result<(), ServerFnError> {
|
||||
// pull the DB pool and auth provider from context
|
||||
let pool = pool(cx)?;
|
||||
let auth = auth(cx)?;
|
||||
|
||||
// check whether the user exists
|
||||
let user: User = User::get_from_username(username, &pool)
|
||||
.await
|
||||
.ok_or_else(|| {
|
||||
ServerFnError::ServerError("User does not exist.".into())
|
||||
})?;
|
||||
|
||||
// check whether the user has provided the correct password
|
||||
match verify(password, &user.password)? {
|
||||
// if the password is correct...
|
||||
true => {
|
||||
// log the user in
|
||||
auth.login_user(user.id);
|
||||
auth.remember_user(remember.is_some());
|
||||
|
||||
// and redirect to the home page
|
||||
leptos_axum::redirect(cx, "/");
|
||||
Ok(())
|
||||
}
|
||||
// if not, return an error
|
||||
false => Err(ServerFnError::ServerError(
|
||||
"Password does not match.".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This server function can then be used from your application. This `redirect` works well with the progressively-enhanced `<ActionForm/>` component: without JS/WASM, the server response will redirect because of the status code and header. With JS/WASM, the `<ActionForm/>` will detect the redirect in the server function response, and use client-side navigation to redirect to the new page.
|
||||
|
||||
@@ -74,11 +74,11 @@ In other words, if this is being compiled to WASM, it has three items; otherwise
|
||||
When I load the page in the browser, I see nothing. If I open the console I see a bunch of warnings:
|
||||
|
||||
```
|
||||
element with id 0-0-1 not found, ignoring it for hydration
|
||||
element with id 0-0-2 not found, ignoring it for hydration
|
||||
element with id 0-0-3 not found, ignoring it for hydration
|
||||
component with id _0-0-4c not found, ignoring it for hydration
|
||||
component with id _0-0-4o not found, ignoring it for hydration
|
||||
element with id 0-3 not found, ignoring it for hydration
|
||||
element with id 0-4 not found, ignoring it for hydration
|
||||
element with id 0-5 not found, ignoring it for hydration
|
||||
component with id _0-6c not found, ignoring it for hydration
|
||||
component with id _0-6o not found, ignoring it for hydration
|
||||
```
|
||||
|
||||
The WASM version of your app, running in the browser, expects to find three items; but the HTML has none.
|
||||
@@ -87,6 +87,56 @@ The WASM version of your app, running in the browser, expects to find three item
|
||||
|
||||
It’s pretty rare that you do this intentionally, but it could happen from somehow running different logic on the server and in the browser. If you’re seeing warnings like this and you don’t think it’s your fault, it’s much more likely that it’s a bug with `<Suspense/>` or something. Feel free to go ahead and open an [issue](https://github.com/leptos-rs/leptos/issues) or [discussion](https://github.com/leptos-rs/leptos/discussions) on GitHub for help.
|
||||
|
||||
### Mutating the DOM during rendering
|
||||
|
||||
This is a slightly more common way to create a client/server mismatch: updating a signal _during rendering_ in a way that mutates the view.
|
||||
|
||||
```rust
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
let (loaded, set_loaded) = create_signal(cx, false);
|
||||
|
||||
// create_effect only runs on the client
|
||||
create_effect(cx, move |_| {
|
||||
// do something like reading from localStorage
|
||||
set_loaded(true);
|
||||
});
|
||||
|
||||
move || {
|
||||
if loaded() {
|
||||
view! { cx, <p>"Hello, world!"</p> }.into_any()
|
||||
} else {
|
||||
view! { cx, <div class="loading">"Loading..."</div> }.into_any()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This one gives us the scary panic
|
||||
|
||||
```
|
||||
panicked at 'assertion failed: `(left == right)`
|
||||
left: `"DIV"`,
|
||||
right: `"P"`: SSR and CSR elements have the same hydration key but different node kinds.
|
||||
```
|
||||
|
||||
And a handy link to this page!
|
||||
|
||||
The problem here is that `create_effect` runs **immediately** and **synchronously**, but only in the browser. As a result, on the server, `loaded` is false, and a `<div>` is rendered. But on the browser, by the time the view is being rendered, `loaded` has already been set to `true`, and the browser is expecting to find a `<p>`.
|
||||
|
||||
#### Solution
|
||||
|
||||
You can simply tell the effect to wait a tick before updating the signal, by using something like `request_animation_frame`, which will set a short timeout and then update the signal before the next frame.
|
||||
|
||||
```rust
|
||||
create_effect(cx, move |_| {
|
||||
// do something like reading from localStorage
|
||||
request_animation_frame(move || set_loaded(true));
|
||||
});
|
||||
```
|
||||
|
||||
This allows the browser to hydrate with the correct, matching state (`loaded` is `false` when it reaches the view), then immediately update it to `true` once hydration is complete.
|
||||
|
||||
### Not all client code can run on the server
|
||||
|
||||
Imagine you happily import a dependency like `gloo-net` that you’ve been used to using to make requests in the browser, and use it in a `create_resource` in a server-rendered app.
|
||||
|
||||
@@ -76,7 +76,7 @@ wasm-pack test --firefox
|
||||
### Writing Your Tests
|
||||
|
||||
Most tests will involve some combination of vanilla DOM manipulation and comparison to a `view`. For example, here’s a test [for the
|
||||
`counter` example](https://github.com/leptos-rs/leptos/blob/main/examples/counter/tests/mod.rs).
|
||||
`counter` example](https://github.com/leptos-rs/leptos/blob/main/examples/counter/tests/web.rs).
|
||||
|
||||
First, we set up the testing environment.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
set_count(3);
|
||||
}
|
||||
>
|
||||
"Click me: "
|
||||
@@ -142,7 +142,7 @@ in a function, telling the framework to update the view every time `count` chang
|
||||
`{count()}` access the value of `count` once, and passes an `i32` into the view,
|
||||
rendering it once, unreactively. You can see the difference in the CodeSandbox below!
|
||||
|
||||
Let’s make one final change. `set_count(3)` is a pretty useless thing for a click handler to do. Let’s replacing “set this value to 3” with “increment this value by 1”:
|
||||
Let’s make one final change. `set_count(3)` is a pretty useless thing for a click handler to do. Let’s replace “set this value to 3” with “increment this value by 1”:
|
||||
|
||||
```rust
|
||||
move |_| {
|
||||
@@ -160,3 +160,67 @@ Other Previews > 8080.` Hover over any of the variables to show Rust-Analyzer de
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/1-basic-component-3d74p3?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A31%2C%22endLineNumber%22%3A19%2C%22startColumn%22%3A31%2C%22startLineNumber%22%3A19%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/1-basic-component-3d74p3?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A31%2C%22endLineNumber%22%3A19%2C%22startColumn%22%3A31%2C%22startLineNumber%22%3A19%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// The #[component] macro marks a function as a reusable component
|
||||
// Components are the building blocks of your user interface
|
||||
// They define a reusable unit of behavior
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
// here we create a reactive signal
|
||||
// and get a (getter, setter) pair
|
||||
// signals are the basic unit of change in the framework
|
||||
// we'll talk more about them later
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
// the `view` macro is how we define the user interface
|
||||
// it uses an HTML-like format that can accept certain Rust values
|
||||
view! { cx,
|
||||
<button
|
||||
// on:click will run whenever the `click` event fires
|
||||
// every event handler is defined as `on:{eventname}`
|
||||
|
||||
// we're able to move `set_count` into the closure
|
||||
// because signals are Copy and 'static
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
}
|
||||
>
|
||||
// text nodes in RSX should be wrapped in quotes,
|
||||
// like a normal Rust string
|
||||
"Click me"
|
||||
</button>
|
||||
<p>
|
||||
<strong>"Reactive: "</strong>
|
||||
// you can insert Rust expressions as values in the DOM
|
||||
// by wrapping them in curly braces
|
||||
// if you pass in a function, it will reactively update
|
||||
{move || count.get()}
|
||||
</p>
|
||||
<p>
|
||||
<strong>"Reactive shorthand: "</strong>
|
||||
// signals are functions, so we can remove the wrapping closure
|
||||
{count}
|
||||
</p>
|
||||
<p>
|
||||
<strong>"Not reactive: "</strong>
|
||||
// NOTE: if you write {count()}, this will *not* be reactive
|
||||
// it simply gets the value of count once
|
||||
{count()}
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
// This `main` function is the entry point into the app
|
||||
// It just mounts our component to the <body>
|
||||
// Because we defined it as `fn App`, we can now use it in a
|
||||
// template as <App/>
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
```
|
||||
|
||||
@@ -152,3 +152,67 @@ places in your application with minimal overhead.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/2-dynamic-attribute-pqyvzl?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/2-dynamic-attribute-pqyvzl?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>Code Sandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
// a "derived signal" is a function that accesses other signals
|
||||
// we can use this to create reactive values that depend on the
|
||||
// values of one or more other signals
|
||||
let double_count = move || count() * 2;
|
||||
|
||||
view! { cx,
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
}
|
||||
// the class: syntax reactively updates a single class
|
||||
// here, we'll set the `red` class when `count` is odd
|
||||
class:red=move || count() % 2 == 1
|
||||
>
|
||||
"Click me"
|
||||
</button>
|
||||
// NOTE: self-closing tags like <br> need an explicit /
|
||||
<br/>
|
||||
|
||||
// We'll update this progress bar every time `count` changes
|
||||
<progress
|
||||
// static attributes work as in HTML
|
||||
max="50"
|
||||
|
||||
// passing a function to an attribute
|
||||
// reactively sets that attribute
|
||||
// signals are functions, so this <=> `move || count.get()`
|
||||
value=count
|
||||
>
|
||||
</progress>
|
||||
<br/>
|
||||
|
||||
// This progress bar will use `double_count`
|
||||
// so it should move twice as fast!
|
||||
<progress
|
||||
max="50"
|
||||
// derived signals are functions, so they can also
|
||||
// reactive update the DOM
|
||||
value=double_count
|
||||
>
|
||||
</progress>
|
||||
<p>"Count: " {count}</p>
|
||||
<p>"Double Count: " {double_count}</p>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -98,18 +98,6 @@ notice that you can easily tell the difference between an element and a componen
|
||||
because components always have `PascalCase` names. You pass the `progress` prop
|
||||
in as if it were an HTML element attribute. Simple.
|
||||
|
||||
> ### Important Note
|
||||
>
|
||||
> For every `Component`, Leptos generates a corresponding `ComponentProps` type. This
|
||||
> is what allows us to have named props, when Rust does not have named function parameters.
|
||||
> If you’re defining a component in one module and importing it into another, make
|
||||
> sure you include this `ComponentProps` type:
|
||||
>
|
||||
> `use progress_bar::{ProgressBar, ProgressBarProps};`
|
||||
>
|
||||
> **Note**: This is still true as of `0.2.5`, but the requirement has been removed on `main`
|
||||
> and will not apply to later versions.
|
||||
|
||||
### Reactive and Static Props
|
||||
|
||||
You’ll notice that throughout this example, `progress` takes a reactive
|
||||
@@ -321,3 +309,77 @@ and see the power of the `#[component]` macro combined with rust-analyzer here.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/3-components-50t2e7?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A7%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A7%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/3-components-50t2e7?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A7%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A7%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// Composing different components together is how we build
|
||||
// user interfaces. Here, we'll define a resuable <ProgressBar/>.
|
||||
// You'll see how doc comments can be used to document components
|
||||
// and their properties.
|
||||
|
||||
/// Shows progress toward a goal.
|
||||
#[component]
|
||||
fn ProgressBar(
|
||||
// All components take a reactive `Scope` as the first argument
|
||||
cx: Scope,
|
||||
// Marks this as an optional prop. It will default to the default
|
||||
// value of its type, i.e., 0.
|
||||
#[prop(default = 100)]
|
||||
/// The maximum value of the progress bar.
|
||||
max: u16,
|
||||
// Will run `.into()` on the value passed into the prop.
|
||||
#[prop(into)]
|
||||
// `Signal<T>` is a wrapper for several reactive types.
|
||||
// It can be helpful in component APIs like this, where we
|
||||
// might want to take any kind of reactive value
|
||||
/// How much progress should be displayed.
|
||||
progress: Signal<i32>,
|
||||
) -> impl IntoView {
|
||||
view! { cx,
|
||||
<progress
|
||||
max={max}
|
||||
value=progress
|
||||
/>
|
||||
<br/>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
let double_count = move || count() * 2;
|
||||
|
||||
view! { cx,
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
}
|
||||
>
|
||||
"Click me"
|
||||
</button>
|
||||
<br/>
|
||||
// If you have this open in CodeSandbox or an editor with
|
||||
// rust-analyzer support, try hovering over `ProgressBar`,
|
||||
// `max`, or `progress` to see the docs we defined above
|
||||
<ProgressBar max=50 progress=count/>
|
||||
// Let's use the default max value on this one
|
||||
// the default is 100, so it should move half as fast
|
||||
<ProgressBar progress=count/>
|
||||
// Signal::derive creates a Signal wrapper from our derived signal
|
||||
// using double_count means it should move twice as fast
|
||||
<ProgressBar max=50 progress=Signal::derive(cx, double_count)/>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -106,3 +106,162 @@ Check out the `<DynamicList/>` component below for an example.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/4-iteration-sglt1o?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A6%2C%22endLineNumber%22%3A55%2C%22startColumn%22%3A5%2C%22startLineNumber%22%3A31%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/4-iteration-sglt1o?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A6%2C%22endLineNumber%22%3A55%2C%22startColumn%22%3A5%2C%22startLineNumber%22%3A31%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// Iteration is a very common task in most applications.
|
||||
// So how do you take a list of data and render it in the DOM?
|
||||
// This example will show you the two ways:
|
||||
// 1) for mostly-static lists, using Rust iterators
|
||||
// 2) for lists that grow, shrink, or move items, using <For/>
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<h1>"Iteration"</h1>
|
||||
<h2>"Static List"</h2>
|
||||
<p>"Use this pattern if the list itself is static."</p>
|
||||
<StaticList length=5/>
|
||||
<h2>"Dynamic List"</h2>
|
||||
<p>"Use this pattern if the rows in your list will change."</p>
|
||||
<DynamicList initial_length=5/>
|
||||
}
|
||||
}
|
||||
|
||||
/// A list of counters, without the ability
|
||||
/// to add or remove any.
|
||||
#[component]
|
||||
fn StaticList(
|
||||
cx: Scope,
|
||||
/// How many counters to include in this list.
|
||||
length: usize,
|
||||
) -> impl IntoView {
|
||||
// create counter signals that start at incrementing numbers
|
||||
let counters = (1..=length).map(|idx| create_signal(cx, idx));
|
||||
|
||||
// when you have a list that doesn't change, you can
|
||||
// manipulate it using ordinary Rust iterators
|
||||
// and collect it into a Vec<_> to insert it into the DOM
|
||||
let counter_buttons = counters
|
||||
.map(|(count, set_count)| {
|
||||
view! { cx,
|
||||
<li>
|
||||
<button
|
||||
on:click=move |_| set_count.update(|n| *n += 1)
|
||||
>
|
||||
{count}
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Note that if `counter_buttons` were a reactive list
|
||||
// and its value changed, this would be very inefficient:
|
||||
// it would rerender every row every time the list changed.
|
||||
view! { cx,
|
||||
<ul>{counter_buttons}</ul>
|
||||
}
|
||||
}
|
||||
|
||||
/// A list of counters that allows you to add or
|
||||
/// remove counters.
|
||||
#[component]
|
||||
fn DynamicList(
|
||||
cx: Scope,
|
||||
/// The number of counters to begin with.
|
||||
initial_length: usize,
|
||||
) -> impl IntoView {
|
||||
// This dynamic list will use the <For/> component.
|
||||
// <For/> is a keyed list. This means that each row
|
||||
// has a defined key. If the key does not change, the row
|
||||
// will not be re-rendered. When the list changes, only
|
||||
// the minimum number of changes will be made to the DOM.
|
||||
|
||||
// `next_counter_id` will let us generate unique IDs
|
||||
// we do this by simply incrementing the ID by one
|
||||
// each time we create a counter
|
||||
let mut next_counter_id = initial_length;
|
||||
|
||||
// we generate an initial list as in <StaticList/>
|
||||
// but this time we include the ID along with the signal
|
||||
let initial_counters = (0..initial_length)
|
||||
.map(|id| (id, create_signal(cx, id + 1)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// now we store that initial list in a signal
|
||||
// this way, we'll be able to modify the list over time,
|
||||
// adding and removing counters, and it will change reactively
|
||||
let (counters, set_counters) = create_signal(cx, initial_counters);
|
||||
|
||||
let add_counter = move |_| {
|
||||
// create a signal for the new counter
|
||||
let sig = create_signal(cx, next_counter_id + 1);
|
||||
// add this counter to the list of counters
|
||||
set_counters.update(move |counters| {
|
||||
// since `.update()` gives us `&mut T`
|
||||
// we can just use normal Vec methods like `push`
|
||||
counters.push((next_counter_id, sig))
|
||||
});
|
||||
// increment the ID so it's always unique
|
||||
next_counter_id += 1;
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div>
|
||||
<button on:click=add_counter>
|
||||
"Add Counter"
|
||||
</button>
|
||||
<ul>
|
||||
// The <For/> component is central here
|
||||
// This allows for efficient, key list rendering
|
||||
<For
|
||||
// `each` takes any function that returns an iterator
|
||||
// this should usually be a signal or derived signal
|
||||
// if it's not reactive, just render a Vec<_> instead of <For/>
|
||||
each=counters
|
||||
// the key should be unique and stable for each row
|
||||
// using an index is usually a bad idea, unless your list
|
||||
// can only grow, because moving items around inside the list
|
||||
// means their indices will change and they will all rerender
|
||||
key=|counter| counter.0
|
||||
// the view function receives each item from your `each` iterator
|
||||
// and returns a view
|
||||
view=move |cx, (id, (count, set_count))| {
|
||||
view! { cx,
|
||||
<li>
|
||||
<button
|
||||
on:click=move |_| set_count.update(|n| *n += 1)
|
||||
>
|
||||
{count}
|
||||
</button>
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_counters.update(|counters| {
|
||||
counters.retain(|(counter_id, _)| counter_id != &id)
|
||||
});
|
||||
}
|
||||
>
|
||||
"Remove"
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
}
|
||||
/>
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -112,3 +112,112 @@ The view should be pretty self-explanatory by now. Note two things:
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/5-form-inputs-ih9m62?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A12%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A12%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/5-form-inputs-ih9m62?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A12%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A12%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::{ev::SubmitEvent, *};
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<h2>"Controlled Component"</h2>
|
||||
<ControlledComponent/>
|
||||
<h2>"Uncontrolled Component"</h2>
|
||||
<UncontrolledComponent/>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ControlledComponent(cx: Scope) -> impl IntoView {
|
||||
// create a signal to hold the value
|
||||
let (name, set_name) = create_signal(cx, "Controlled".to_string());
|
||||
|
||||
view! { cx,
|
||||
<input type="text"
|
||||
// fire an event whenever the input changes
|
||||
on:input=move |ev| {
|
||||
// event_target_value is a Leptos helper function
|
||||
// it functions the same way as event.target.value
|
||||
// in JavaScript, but smooths out some of the typecasting
|
||||
// necessary to make this work in Rust
|
||||
set_name(event_target_value(&ev));
|
||||
}
|
||||
|
||||
// the `prop:` syntax lets you update a DOM property,
|
||||
// rather than an attribute.
|
||||
//
|
||||
// IMPORTANT: the `value` *attribute* only sets the
|
||||
// initial value, until you have made a change.
|
||||
// The `value` *property* sets the current value.
|
||||
// This is a quirk of the DOM; I didn't invent it.
|
||||
// Other frameworks gloss this over; I think it's
|
||||
// more important to give you access to the browser
|
||||
// as it really works.
|
||||
//
|
||||
// tl;dr: use prop:value for form inputs
|
||||
prop:value=name
|
||||
/>
|
||||
<p>"Name is: " {name}</p>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn UncontrolledComponent(cx: Scope) -> impl IntoView {
|
||||
// import the type for <input>
|
||||
use leptos::html::Input;
|
||||
|
||||
let (name, set_name) = create_signal(cx, "Uncontrolled".to_string());
|
||||
|
||||
// we'll use a NodeRef to store a reference to the input element
|
||||
// this will be filled when the element is created
|
||||
let input_element: NodeRef<Input> = create_node_ref(cx);
|
||||
|
||||
// fires when the form `submit` event happens
|
||||
// this will store the value of the <input> in our signal
|
||||
let on_submit = move |ev: SubmitEvent| {
|
||||
// stop the page from reloading!
|
||||
ev.prevent_default();
|
||||
|
||||
// here, we'll extract the value from the input
|
||||
let value = input_element()
|
||||
// event handlers can only fire after the view
|
||||
// is mounted to the DOM, so the `NodeRef` will be `Some`
|
||||
.expect("<input> to exist")
|
||||
// `NodeRef` implements `Deref` for the DOM element type
|
||||
// this means we can call`HtmlInputElement::value()`
|
||||
// to get the current value of the input
|
||||
.value();
|
||||
set_name(value);
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<form on:submit=on_submit>
|
||||
<input type="text"
|
||||
// here, we use the `value` *attribute* to set only
|
||||
// the initial value, letting the browser maintain
|
||||
// the state after that
|
||||
value=name
|
||||
|
||||
// store a reference to this input in `input_element`
|
||||
node_ref=input_element
|
||||
/>
|
||||
<input type="submit" value="Submit"/>
|
||||
</form>
|
||||
<p>"Name is: " {name}</p>
|
||||
}
|
||||
}
|
||||
|
||||
// This `main` function is the entry point into the app
|
||||
// It just mounts our component to the <body>
|
||||
// Because we defined it as `fn App`, we can now use it in a
|
||||
// template as <App/>
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -198,7 +198,7 @@ let (value, set_value) = create_signal(cx, 0);
|
||||
|
||||
view! { cx,
|
||||
<Show
|
||||
when=move || value() > 5
|
||||
when=move || { value() > 5 }
|
||||
fallback=|cx| view! { cx, <Small/> }
|
||||
>
|
||||
<Big/>
|
||||
@@ -285,3 +285,100 @@ view! { cx,
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/6-control-flow-in-view-zttwfx?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/6-control-flow-in-view-zttwfx?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (value, set_value) = create_signal(cx, 0);
|
||||
let is_odd = move || value() & 1 == 1;
|
||||
let odd_text = move || if is_odd() { Some("How odd!") } else { None };
|
||||
|
||||
view! { cx,
|
||||
<h1>"Control Flow"</h1>
|
||||
|
||||
// Simple UI to update and show a value
|
||||
<button on:click=move |_| set_value.update(|n| *n += 1)>
|
||||
"+1"
|
||||
</button>
|
||||
<p>"Value is: " {value}</p>
|
||||
|
||||
<hr/>
|
||||
|
||||
<h2><code>"Option<T>"</code></h2>
|
||||
// For any `T` that implements `IntoView`,
|
||||
// so does `Option<T>`
|
||||
|
||||
<p>{odd_text}</p>
|
||||
// This means you can use `Option` methods on it
|
||||
<p>{move || odd_text().map(|text| text.len())}</p>
|
||||
|
||||
<h2>"Conditional Logic"</h2>
|
||||
// You can do dynamic conditional if-then-else
|
||||
// logic in several ways
|
||||
//
|
||||
// a. An "if" expression in a function
|
||||
// This will simply re-render every time the value
|
||||
// changes, which makes it good for lightweight UI
|
||||
<p>
|
||||
{move || if is_odd() {
|
||||
"Odd"
|
||||
} else {
|
||||
"Even"
|
||||
}}
|
||||
</p>
|
||||
|
||||
// b. Toggling some kind of class
|
||||
// This is smart for an element that's going to
|
||||
// toggled often, because it doesn't destroy
|
||||
// it in between states
|
||||
// (you can find the `hidden` class in `index.html`)
|
||||
<p class:hidden=is_odd>"Appears if even."</p>
|
||||
|
||||
// c. The <Show/> component
|
||||
// This only renders the fallback and the child
|
||||
// once, lazily, and toggles between them when
|
||||
// needed. This makes it more efficient in many cases
|
||||
// than a {move || if ...} block
|
||||
<Show when=is_odd
|
||||
fallback=|cx| view! { cx, <p>"Even steven"</p> }
|
||||
>
|
||||
<p>"Oddment"</p>
|
||||
</Show>
|
||||
|
||||
// d. Because `bool::then()` converts a `bool` to
|
||||
// `Option`, you can use it to create a show/hide toggled
|
||||
{move || is_odd().then(|| view! { cx, <p>"Oddity!"</p> })}
|
||||
|
||||
<h2>"Converting between Types"</h2>
|
||||
// e. Note: if branches return different types,
|
||||
// you can convert between them with
|
||||
// `.into_any()` (for different HTML element types)
|
||||
// or `.into_view(cx)` (for all view types)
|
||||
{move || match is_odd() {
|
||||
true if value() == 1 => {
|
||||
// <pre> returns HtmlElement<Pre>
|
||||
view! { cx, <pre>"One"</pre> }.into_any()
|
||||
},
|
||||
false if value() == 2 => {
|
||||
// <p> returns HtmlElement<P>
|
||||
// so we convert into a more generic type
|
||||
view! { cx, <p>"Two"</p> }.into_any()
|
||||
}
|
||||
_ => view! { cx, <textarea>{value()}</textarea> }.into_any()
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -19,7 +19,7 @@ fn NumericInput(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<label>
|
||||
"Type a number (or not!)"
|
||||
<input type="number" on:input=on_input/>
|
||||
<input on:input=on_input/>
|
||||
<p>
|
||||
"You entered "
|
||||
<strong>{value}</strong>
|
||||
@@ -69,7 +69,7 @@ fn NumericInput(cx: Scope) -> impl IntoView {
|
||||
<h1>"Error Handling"</h1>
|
||||
<label>
|
||||
"Type a number (or something that's not a number!)"
|
||||
<input type="number" on:input=on_input/>
|
||||
<input on:input=on_input/>
|
||||
<ErrorBoundary
|
||||
// the fallback receives a signal containing current errors
|
||||
fallback=|cx, errors| view! { cx,
|
||||
@@ -113,3 +113,64 @@ an `<ErrorBoundary/>` will appear again.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/7-error-handling-and-error-boundaries-sroncx?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/7-error-handling-and-error-boundaries-sroncx?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (value, set_value) = create_signal(cx, Ok(0));
|
||||
|
||||
// when input changes, try to parse a number from the input
|
||||
let on_input = move |ev| set_value(event_target_value(&ev).parse::<i32>());
|
||||
|
||||
view! { cx,
|
||||
<h1>"Error Handling"</h1>
|
||||
<label>
|
||||
"Type a number (or something that's not a number!)"
|
||||
<input type="number" on:input=on_input/>
|
||||
// If an `Err(_) had been rendered inside the <ErrorBoundary/>,
|
||||
// the fallback will be displayed. Otherwise, the children of the
|
||||
// <ErrorBoundary/> will be displayed.
|
||||
<ErrorBoundary
|
||||
// the fallback receives a signal containing current errors
|
||||
fallback=|cx, errors| view! { cx,
|
||||
<div class="error">
|
||||
<p>"Not a number! Errors: "</p>
|
||||
// we can render a list of errors
|
||||
// as strings, if we'd like
|
||||
<ul>
|
||||
{move || errors.get()
|
||||
.into_iter()
|
||||
.map(|(_, e)| view! { cx, <li>{e.to_string()}</li>})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<p>
|
||||
"You entered "
|
||||
// because `value` is `Result<i32, _>`,
|
||||
// it will render the `i32` if it is `Ok`,
|
||||
// and render nothing and trigger the error boundary
|
||||
// if it is `Err`. It's a signal, so this will dynamically
|
||||
// update when `value` changes
|
||||
<strong>{value}</strong>
|
||||
</p>
|
||||
</ErrorBoundary>
|
||||
</label>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -117,7 +117,7 @@ pub fn App(cx: Scope) -> impl IntoView {
|
||||
|
||||
|
||||
#[component]
|
||||
pub fn ButtonC<F>(cx: Scope) -> impl IntoView {
|
||||
pub fn ButtonC(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<button>"Toggle"</button>
|
||||
}
|
||||
@@ -288,3 +288,150 @@ signals and effects, all the way down.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/8-parent-child-communication-84we8m?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/8-parent-child-communication-84we8m?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::{ev::MouseEvent, *};
|
||||
|
||||
// This highlights four different ways that child components can communicate
|
||||
// with their parent:
|
||||
// 1) <ButtonA/>: passing a WriteSignal as one of the child component props,
|
||||
// for the child component to write into and the parent to read
|
||||
// 2) <ButtonB/>: passing a closure as one of the child component props, for
|
||||
// the child component to call
|
||||
// 3) <ButtonC/>: adding an `on:` event listener to a component
|
||||
// 4) <ButtonD/>: providing a context that is used in the component (rather than prop drilling)
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct SmallcapsContext(WriteSignal<bool>);
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
// just some signals to toggle three classes on our <p>
|
||||
let (red, set_red) = create_signal(cx, false);
|
||||
let (right, set_right) = create_signal(cx, false);
|
||||
let (italics, set_italics) = create_signal(cx, false);
|
||||
let (smallcaps, set_smallcaps) = create_signal(cx, false);
|
||||
|
||||
// the newtype pattern isn't *necessary* here but is a good practice
|
||||
// it avoids confusion with other possible future `WriteSignal<bool>` contexts
|
||||
// and makes it easier to refer to it in ButtonC
|
||||
provide_context(cx, SmallcapsContext(set_smallcaps));
|
||||
|
||||
view! {
|
||||
cx,
|
||||
<main>
|
||||
<p
|
||||
// class: attributes take F: Fn() => bool, and these signals all implement Fn()
|
||||
class:red=red
|
||||
class:right=right
|
||||
class:italics=italics
|
||||
class:smallcaps=smallcaps
|
||||
>
|
||||
"Lorem ipsum sit dolor amet."
|
||||
</p>
|
||||
|
||||
// Button A: pass the signal setter
|
||||
<ButtonA setter=set_red/>
|
||||
|
||||
// Button B: pass a closure
|
||||
<ButtonB on_click=move |_| set_right.update(|value| *value = !*value)/>
|
||||
|
||||
// Button B: use a regular event listener
|
||||
// setting an event listener on a component like this applies it
|
||||
// to each of the top-level elements the component returns
|
||||
<ButtonC on:click=move |_| set_italics.update(|value| *value = !*value)/>
|
||||
|
||||
// Button D gets its setter from context rather than props
|
||||
<ButtonD/>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
|
||||
/// Button A receives a signal setter and updates the signal itself
|
||||
#[component]
|
||||
pub fn ButtonA(
|
||||
cx: Scope,
|
||||
/// Signal that will be toggled when the button is clicked.
|
||||
setter: WriteSignal<bool>,
|
||||
) -> impl IntoView {
|
||||
view! {
|
||||
cx,
|
||||
<button
|
||||
on:click=move |_| setter.update(|value| *value = !*value)
|
||||
>
|
||||
"Toggle Red"
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
/// Button B receives a closure
|
||||
#[component]
|
||||
pub fn ButtonB<F>(
|
||||
cx: Scope,
|
||||
/// Callback that will be invoked when the button is clicked.
|
||||
on_click: F,
|
||||
) -> impl IntoView
|
||||
where
|
||||
F: Fn(MouseEvent) + 'static,
|
||||
{
|
||||
view! {
|
||||
cx,
|
||||
<button
|
||||
on:click=on_click
|
||||
>
|
||||
"Toggle Right"
|
||||
</button>
|
||||
}
|
||||
|
||||
// just a note: in an ordinary function ButtonB could take on_click: impl Fn(MouseEvent) + 'static
|
||||
// and save you from typing out the generic
|
||||
// the component macro actually expands to define a
|
||||
//
|
||||
// struct ButtonBProps<F> where F: Fn(MouseEvent) + 'static {
|
||||
// on_click: F
|
||||
// }
|
||||
//
|
||||
// this is what allows us to have named props in our component invocation,
|
||||
// instead of an ordered list of function arguments
|
||||
// if Rust ever had named function arguments we could drop this requirement
|
||||
}
|
||||
|
||||
/// Button C is a dummy: it renders a button but doesn't handle
|
||||
/// its click. Instead, the parent component adds an event listener.
|
||||
#[component]
|
||||
pub fn ButtonC(cx: Scope) -> impl IntoView {
|
||||
view! {
|
||||
cx,
|
||||
<button>
|
||||
"Toggle Italics"
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
/// Button D is very similar to Button A, but instead of passing the setter as a prop
|
||||
/// we get it from the context
|
||||
#[component]
|
||||
pub fn ButtonD(cx: Scope) -> impl IntoView {
|
||||
let setter = use_context::<SmallcapsContext>(cx).unwrap().0;
|
||||
|
||||
view! {
|
||||
cx,
|
||||
<button
|
||||
on:click=move |_| setter.update(|value| *value = !*value)
|
||||
>
|
||||
"Toggle Small Caps"
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -126,3 +126,107 @@ view! { cx,
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/9-component-children-2wrdfd?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A12%2C%22endLineNumber%22%3A19%2C%22startColumn%22%3A12%2C%22startLineNumber%22%3A19%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/9-component-children-2wrdfd?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A12%2C%22endLineNumber%22%3A19%2C%22startColumn%22%3A12%2C%22startLineNumber%22%3A19%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// Often, you want to pass some kind of child view to another
|
||||
// component. There are two basic patterns for doing this:
|
||||
// - "render props": creating a component prop that takes a function
|
||||
// that creates a view
|
||||
// - the `children` prop: a special property that contains content
|
||||
// passed as the children of a component in your view, not as a
|
||||
// property
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
let (items, set_items) = create_signal(cx, vec![0, 1, 2]);
|
||||
let render_prop = move || {
|
||||
// items.with(...) reacts to the value without cloning
|
||||
// by applying a function. Here, we pass the `len` method
|
||||
// on a `Vec<_>` directly
|
||||
let len = move || items.with(Vec::len);
|
||||
view! { cx,
|
||||
<p>"Length: " {len}</p>
|
||||
}
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
// This component just displays the two kinds of children,
|
||||
// embedding them in some other markup
|
||||
<TakesChildren
|
||||
// for component props, you can shorthand
|
||||
// `render_prop=render_prop` => `render_prop`
|
||||
// (this doesn't work for HTML element attributes)
|
||||
render_prop
|
||||
>
|
||||
// these look just like the children of an HTML element
|
||||
<p>"Here's a child."</p>
|
||||
<p>"Here's another child."</p>
|
||||
</TakesChildren>
|
||||
<hr/>
|
||||
// This component actually iterates over and wraps the children
|
||||
<WrapsChildren>
|
||||
<p>"Here's a child."</p>
|
||||
<p>"Here's another child."</p>
|
||||
</WrapsChildren>
|
||||
}
|
||||
}
|
||||
|
||||
/// Displays a `render_prop` and some children within markup.
|
||||
#[component]
|
||||
pub fn TakesChildren<F, IV>(
|
||||
cx: Scope,
|
||||
/// Takes a function (type F) that returns anything that can be
|
||||
/// converted into a View (type IV)
|
||||
render_prop: F,
|
||||
/// `children` takes the `Children` type
|
||||
/// this is an alias for `Box<dyn FnOnce(Scope) -> Fragment>`
|
||||
/// ... aren't you glad we named it `Children` instead?
|
||||
children: Children,
|
||||
) -> impl IntoView
|
||||
where
|
||||
F: Fn() -> IV,
|
||||
IV: IntoView,
|
||||
{
|
||||
view! { cx,
|
||||
<h1><code>"<TakesChildren/>"</code></h1>
|
||||
<h2>"Render Prop"</h2>
|
||||
{render_prop()}
|
||||
<hr/>
|
||||
<h2>"Children"</h2>
|
||||
{children(cx)}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps each child in an `<li>` and embeds them in a `<ul>`.
|
||||
#[component]
|
||||
pub fn WrapsChildren(cx: Scope, children: Children) -> impl IntoView {
|
||||
// children(cx) returns a `Fragment`, which has a
|
||||
// `nodes` field that contains a Vec<View>
|
||||
// this means we can iterate over the children
|
||||
// to create something new!
|
||||
let children = children(cx)
|
||||
.nodes
|
||||
.into_iter()
|
||||
.map(|child| view! { cx, <li>{child}</li> })
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
view! { cx,
|
||||
<h1><code>"<WrapsChildren/>"</code></h1>
|
||||
// wrap our wrapped children in a UL
|
||||
<ul>{children}</ul>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -15,16 +15,33 @@ CARGO_MAKE_CRATE_WORKSPACE_MEMBERS = [
|
||||
"fetch",
|
||||
"hackernews",
|
||||
"hackernews_axum",
|
||||
"js-framework-benchmark",
|
||||
"leptos-tailwind-axum",
|
||||
"login_with_token_csr_only",
|
||||
"parent_child",
|
||||
"router",
|
||||
"session_auth_axum",
|
||||
"slots",
|
||||
"ssr_modes",
|
||||
"ssr_modes_axum",
|
||||
"tailwind",
|
||||
"tailwind_csr_trunk",
|
||||
"timer",
|
||||
"todo_app_sqlite",
|
||||
"todo_app_sqlite_axum",
|
||||
"todo_app_sqlite_viz",
|
||||
"todomvc",
|
||||
]
|
||||
|
||||
[tasks.gen-members]
|
||||
workspace = false
|
||||
description = "Generate the list of workspace members"
|
||||
script = '''
|
||||
examples=$(ls |
|
||||
grep -v README.md |
|
||||
grep -v Makefile.toml |
|
||||
grep -v cargo-make |
|
||||
grep -v gtk |
|
||||
jq -R -s -c 'split("\n")[:-1]')
|
||||
echo "CARGO_MAKE_CRATE_WORKSPACE_MEMBERS = $examples"
|
||||
'''
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
[tasks.test-e2e]
|
||||
dependencies = ["setup-node", "cargo-leptos-e2e"]
|
||||
[tasks.integration-test]
|
||||
dependencies = ["cargo-leptos-e2e"]
|
||||
|
||||
[tasks.clean-all]
|
||||
dependencies = ["clean-cargo", "clean-node_modules", "clean-playwright"]
|
||||
[tasks.cargo-leptos-e2e]
|
||||
command = "cargo"
|
||||
args = ["leptos", "end-to-end"]
|
||||
|
||||
28
examples/cargo-make/clean.toml
Normal file
28
examples/cargo-make/clean.toml
Normal file
@@ -0,0 +1,28 @@
|
||||
[tasks.clean]
|
||||
dependencies = [
|
||||
"clean-cargo",
|
||||
"clean-trunk",
|
||||
"clean-node_modules",
|
||||
"clean-playwright",
|
||||
]
|
||||
|
||||
[tasks.clean-cargo]
|
||||
command = "cargo"
|
||||
args = ["clean"]
|
||||
|
||||
[tasks.clean-trunk]
|
||||
command = "trunk"
|
||||
args = ["clean"]
|
||||
|
||||
[tasks.clean-node_modules]
|
||||
script = '''
|
||||
project_dir=${PWD##*/}
|
||||
if [ "$project_dir" != "todomvc" ]; then
|
||||
find . -type d -name node_modules | xargs rm -rf
|
||||
fi
|
||||
'''
|
||||
|
||||
[tasks.clean-playwright]
|
||||
script = '''
|
||||
find . -name playwright-report -name playwright -name test-results | xargs rm -rf
|
||||
'''
|
||||
@@ -1,97 +0,0 @@
|
||||
[tasks.pre-clippy]
|
||||
env = { CARGO_MAKE_CLIPPY_ARGS = "--all-targets --all-features -- -D warnings" }
|
||||
|
||||
[tasks.check-style]
|
||||
description = "Check for style violations"
|
||||
dependencies = ["check-format-flow", "clippy-flow"]
|
||||
|
||||
[tasks.check-format]
|
||||
args = ["fmt", "--", "--check", "--config-path", "../../"]
|
||||
|
||||
[tasks.clean-cargo]
|
||||
description = "Runs the cargo clean command."
|
||||
category = "Cleanup"
|
||||
command = "cargo"
|
||||
args = ["clean"]
|
||||
|
||||
[tasks.clean-trunk]
|
||||
description = "Runs the trunk clean command."
|
||||
category = "Cleanup"
|
||||
command = "trunk"
|
||||
args = ["clean"]
|
||||
|
||||
[tasks.clean-node_modules]
|
||||
description = "Delete all node_modules directories"
|
||||
category = "Cleanup"
|
||||
script = '''
|
||||
find . -type d -name node_modules | xargs rm -rf
|
||||
'''
|
||||
|
||||
[tasks.clean-playwright]
|
||||
description = "Delete playwright directories"
|
||||
category = "Cleanup"
|
||||
script = '''
|
||||
for pw_dir in $(find . -name playwright.config.ts | xargs dirname)
|
||||
do
|
||||
rm -rf $pw_dir/playwright-report
|
||||
done
|
||||
'''
|
||||
|
||||
[tasks.clean-all]
|
||||
description = "Delete all temporary directories"
|
||||
category = "Cleanup"
|
||||
dependencies = ["clean-cargo"]
|
||||
|
||||
[tasks.test-wasm]
|
||||
env = { CARGO_MAKE_WASM_TEST_ARGS = "--headless --chrome" }
|
||||
command = "cargo"
|
||||
args = ["make", "wasm-pack-test"]
|
||||
|
||||
[tasks.cargo-leptos-e2e]
|
||||
description = "Runs end to end tests with cargo leptos"
|
||||
command = "cargo"
|
||||
args = ["leptos", "end-to-end"]
|
||||
|
||||
[tasks.setup-node]
|
||||
description = "Install node dependencies and playwright browsers"
|
||||
env = { PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "1" }
|
||||
script = '''
|
||||
BOLD="\e[1m"
|
||||
GREEN="\e[0;32m"
|
||||
RED="\e[0;31m"
|
||||
RESET="\e[0m"
|
||||
|
||||
project_dir=$CARGO_MAKE_WORKING_DIRECTORY
|
||||
|
||||
# Discover commands
|
||||
if command -v pnpm; then
|
||||
NODE_CMD=pnpm
|
||||
PLAYWRIGHT_CMD=pnpm
|
||||
elif command -v npm; then
|
||||
NODE_CMD=npm
|
||||
PLAYWRIGHT_CMD=npx
|
||||
else
|
||||
echo "${RED}${BOLD}ERROR${RESET} - pnpm or npm is required by this task"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Install node dependencies
|
||||
for node_path in $(find . -name package.json -not -path '*/node_modules/*')
|
||||
do
|
||||
node_dir=$(dirname $node_path)
|
||||
echo Install node dependencies for $node_dir
|
||||
cd $node_dir
|
||||
${NODE_CMD} install
|
||||
cd ${project_dir}
|
||||
done
|
||||
|
||||
# Install playwright browsers
|
||||
for pw_path in $(find . -name playwright.config.ts)
|
||||
do
|
||||
pw_dir=$(dirname $pw_path)
|
||||
echo Install playwright browsers for $pw_dir
|
||||
cd $pw_dir
|
||||
${PLAYWRIGHT_CMD} playwright install
|
||||
cd $project_dir
|
||||
done
|
||||
'''
|
||||
9
examples/cargo-make/lint.toml
Normal file
9
examples/cargo-make/lint.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[tasks.pre-clippy]
|
||||
env = { CARGO_MAKE_CLIPPY_ARGS = "--all-targets --all-features -- -D warnings" }
|
||||
|
||||
[tasks.check-style]
|
||||
dependencies = ["check-format-flow", "clippy-flow"]
|
||||
|
||||
[tasks.check-format]
|
||||
env = { LEPTOS_PROJECT_DIRECTORY = "../../" }
|
||||
args = ["fmt", "--", "--check", "--config-path", "${LEPTOS_PROJECT_DIRECTORY}"]
|
||||
@@ -1,28 +1,32 @@
|
||||
extend = [{ path = "../cargo-make/common.toml" }]
|
||||
extend = [
|
||||
{ path = "../cargo-make/clean.toml" },
|
||||
{ path = "../cargo-make/lint.toml" },
|
||||
{ path = "../cargo-make/node.toml" },
|
||||
]
|
||||
|
||||
# CI Stages
|
||||
|
||||
[tasks.ci]
|
||||
dependencies = ["prepare", "lint", "build", "test-flow", "integration-test"]
|
||||
|
||||
[tasks.ci-clean]
|
||||
dependencies = ["ci", "clean"]
|
||||
|
||||
[tasks.prepare]
|
||||
dependencies = ["setup-node"]
|
||||
|
||||
[tasks.lint]
|
||||
dependencies = ["check-style"]
|
||||
|
||||
[tasks.integration-test]
|
||||
|
||||
# ALIASES
|
||||
|
||||
[tasks.verify-flow]
|
||||
description = "Provides pre and post hooks for verify"
|
||||
dependencies = ["pre-verify", "verify", "post-verify"]
|
||||
alias = "ci"
|
||||
|
||||
[tasks.verify]
|
||||
description = "Run all quality checks and tests"
|
||||
dependencies = ["check-style", "test-unit-and-e2e"]
|
||||
[tasks.t]
|
||||
dependencies = ["test-flow"]
|
||||
|
||||
[tasks.test-unit-and-e2e]
|
||||
description = "Run all unit and e2e tests"
|
||||
dependencies = ["test-flow", "test-e2e-flow"]
|
||||
|
||||
[tasks.pre-verify]
|
||||
|
||||
[tasks.post-verify]
|
||||
dependencies = ["clean-all"]
|
||||
|
||||
[tasks.test-e2e-flow]
|
||||
description = "Provides pre and post hooks for test-e2e"
|
||||
dependencies = ["pre-test-e2e", "test-e2e", "post-test-e2e"]
|
||||
|
||||
[tasks.pre-test-e2e]
|
||||
|
||||
[tasks.test-e2e]
|
||||
|
||||
[tasks.post-test-e2e]
|
||||
[tasks.it]
|
||||
alias = "integration-test"
|
||||
|
||||
43
examples/cargo-make/node.toml
Normal file
43
examples/cargo-make/node.toml
Normal file
@@ -0,0 +1,43 @@
|
||||
[tasks.setup-node]
|
||||
description = "Install node dependencies and playwright browsers"
|
||||
env = { PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "1" }
|
||||
script = '''
|
||||
BOLD="\e[1m"
|
||||
GREEN="\e[0;32m"
|
||||
RED="\e[0;31m"
|
||||
RESET="\e[0m"
|
||||
|
||||
project_dir=$CARGO_MAKE_WORKING_DIRECTORY
|
||||
|
||||
# Discover commands
|
||||
if command -v pnpm; then
|
||||
NODE_CMD=pnpm
|
||||
PLAYWRIGHT_CMD=pnpm
|
||||
elif command -v npm; then
|
||||
NODE_CMD=npm
|
||||
PLAYWRIGHT_CMD=npx
|
||||
else
|
||||
echo "${RED}${BOLD}ERROR${RESET} - pnpm or npm is required by this task"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Install node dependencies
|
||||
for node_path in $(find . -name package.json -not -path '*/node_modules/*')
|
||||
do
|
||||
node_dir=$(dirname $node_path)
|
||||
echo Install node dependencies for $node_dir
|
||||
cd $node_dir
|
||||
${NODE_CMD} install
|
||||
cd ${project_dir}
|
||||
done
|
||||
|
||||
# Install playwright browsers
|
||||
for pw_path in $(find . -name playwright.config.ts)
|
||||
do
|
||||
pw_dir=$(dirname $pw_path)
|
||||
echo Install playwright browsers for $pw_dir
|
||||
cd $pw_dir
|
||||
${PLAYWRIGHT_CMD} playwright install
|
||||
cd $project_dir
|
||||
done
|
||||
'''
|
||||
4
examples/cargo-make/playwright-test.toml
Normal file
4
examples/cargo-make/playwright-test.toml
Normal file
@@ -0,0 +1,4 @@
|
||||
extend = [{ path = "../cargo-make/playwright.toml" }]
|
||||
|
||||
[tasks.integration-test]
|
||||
dependencies = ["test-playwright-autostart"]
|
||||
101
examples/cargo-make/playwright.toml
Normal file
101
examples/cargo-make/playwright.toml
Normal file
@@ -0,0 +1,101 @@
|
||||
[tasks.test-playwright-autostart]
|
||||
command = "npm"
|
||||
args = ["run", "e2e:auto-start"]
|
||||
|
||||
[tasks.test-playwright]
|
||||
script = '''
|
||||
BOLD="\e[1m"
|
||||
GREEN="\e[0;32m"
|
||||
RED="\e[0;31m"
|
||||
RESET="\e[0m"
|
||||
|
||||
project_dir=$CARGO_MAKE_WORKING_DIRECTORY
|
||||
|
||||
# Discover commands
|
||||
if command -v pnpm; then
|
||||
PLAYWRIGHT_CMD=pnpm
|
||||
elif command -v npm; then
|
||||
PLAYWRIGHT_CMD=npx
|
||||
else
|
||||
echo "${RED}${BOLD}ERROR${RESET} - pnpm or npm is required by this task"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Run playwright command
|
||||
for pw_path in $(find . -name playwright.config.ts)
|
||||
do
|
||||
pw_dir=$(dirname $pw_path)
|
||||
cd $pw_dir
|
||||
${PLAYWRIGHT_CMD} playwright test
|
||||
cd $project_dir
|
||||
done
|
||||
'''
|
||||
|
||||
[tasks.test-playwright-ui]
|
||||
script = '''
|
||||
BOLD="\e[1m"
|
||||
GREEN="\e[0;32m"
|
||||
RED="\e[0;31m"
|
||||
RESET="\e[0m"
|
||||
|
||||
project_dir=$CARGO_MAKE_WORKING_DIRECTORY
|
||||
|
||||
# Discover commands
|
||||
if command -v pnpm; then
|
||||
PLAYWRIGHT_CMD=pnpm
|
||||
elif command -v npm; then
|
||||
PLAYWRIGHT_CMD=npx
|
||||
else
|
||||
echo "${RED}${BOLD}ERROR${RESET} - pnpm or npm is required by this task"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Run playwright command
|
||||
for pw_path in $(find . -name playwright.config.ts)
|
||||
do
|
||||
pw_dir=$(dirname $pw_path)
|
||||
cd $pw_dir
|
||||
${PLAYWRIGHT_CMD} playwright test --ui
|
||||
cd $project_dir
|
||||
done
|
||||
'''
|
||||
|
||||
[tasks.test-playwright-report]
|
||||
script = '''
|
||||
BOLD="\e[1m"
|
||||
GREEN="\e[0;32m"
|
||||
RED="\e[0;31m"
|
||||
RESET="\e[0m"
|
||||
|
||||
project_dir=$CARGO_MAKE_WORKING_DIRECTORY
|
||||
|
||||
# Discover commands
|
||||
if command -v pnpm; then
|
||||
PLAYWRIGHT_CMD=pnpm
|
||||
elif command -v npm; then
|
||||
PLAYWRIGHT_CMD=npx
|
||||
else
|
||||
echo "${RED}${BOLD}ERROR${RESET} - pnpm or npm is required by this task"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Run playwright command
|
||||
for pw_path in $(find . -name playwright.config.ts)
|
||||
do
|
||||
pw_dir=$(dirname $pw_path)
|
||||
cd $pw_dir
|
||||
${PLAYWRIGHT_CMD} playwright show-report
|
||||
cd $project_dir
|
||||
done
|
||||
'''
|
||||
|
||||
# ALIASES
|
||||
|
||||
[tasks.pw]
|
||||
dependencies = ["test-playwright"]
|
||||
|
||||
[tasks.pw-ui]
|
||||
dependencies = ["test-playwright-ui"]
|
||||
|
||||
[tasks.pw-report]
|
||||
dependencies = ["test-playwright-report"]
|
||||
18
examples/cargo-make/trunk_server.toml
Normal file
18
examples/cargo-make/trunk_server.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[tasks.build]
|
||||
command = "trunk"
|
||||
args = ["build"]
|
||||
|
||||
[tasks.start-trunk]
|
||||
command = "trunk"
|
||||
args = ["serve", "${@}"]
|
||||
|
||||
[tasks.stop-trunk]
|
||||
script = '''
|
||||
pkill -f "cargo-make"
|
||||
pkill -f "trunk"
|
||||
'''
|
||||
|
||||
# ALIASES
|
||||
|
||||
[tasks.dev]
|
||||
dependencies = ["start-trunk"]
|
||||
@@ -1,5 +1,11 @@
|
||||
[tasks.test]
|
||||
env = { RUN_CARGO_TEST = false }
|
||||
condition = { env_true = ["RUN_CARGO_TEST"] }
|
||||
|
||||
[tasks.post-test]
|
||||
dependencies = ["test-wasm"]
|
||||
|
||||
[tasks.clean-all]
|
||||
dependencies = ["clean-cargo", "clean-trunk"]
|
||||
[tasks.test-wasm]
|
||||
env = { CARGO_MAKE_WASM_TEST_ARGS = "--headless --chrome" }
|
||||
command = "cargo"
|
||||
args = ["make", "wasm-pack-test"]
|
||||
|
||||
@@ -8,7 +8,7 @@ codegen-units = 1
|
||||
lto = true
|
||||
|
||||
[dependencies]
|
||||
leptos = { path = "../../leptos" }
|
||||
leptos = { path = "../../leptos", features = ["csr", "nightly"] }
|
||||
console_log = "1"
|
||||
log = "0.4"
|
||||
console_error_panic_hook = "0.1.7"
|
||||
|
||||
@@ -19,19 +19,17 @@ console_error_panic_hook = "0.1"
|
||||
futures = "0.3"
|
||||
cfg-if = "1"
|
||||
lazy_static = "1"
|
||||
leptos = { path = "../../leptos", default-features = false, features = [
|
||||
"serde",
|
||||
] }
|
||||
leptos = { path = "../../leptos" }
|
||||
leptos_actix = { path = "../../integrations/actix", optional = true }
|
||||
leptos_meta = { path = "../../meta", default-features = false }
|
||||
leptos_router = { path = "../../router", default-features = false }
|
||||
leptos_meta = { path = "../../meta" }
|
||||
leptos_router = { path = "../../router" }
|
||||
log = "0.4"
|
||||
gloo-net = { git = "https://github.com/rustwasm/gloo" }
|
||||
wasm-bindgen = "=0.2.86"
|
||||
wasm-bindgen = "=0.2.87"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
default = ["nightly"]
|
||||
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
|
||||
ssr = [
|
||||
"dep:actix-files",
|
||||
@@ -41,10 +39,10 @@ ssr = [
|
||||
"leptos_meta/ssr",
|
||||
"leptos_router/ssr",
|
||||
]
|
||||
stable = ["leptos/stable", "leptos_router/stable"]
|
||||
nightly = ["leptos/nightly", "leptos_router/nightly"]
|
||||
|
||||
[package.metadata.cargo-all-features]
|
||||
denylist = ["actix-files", "actix-web", "leptos_actix", "stable"]
|
||||
denylist = ["actix-files", "actix-web", "leptos_actix", "nightly"]
|
||||
skip_feature_sets = [["ssr", "hydrate"]]
|
||||
|
||||
[package.metadata.leptos]
|
||||
|
||||
@@ -67,24 +67,10 @@ pub fn Counters(cx: Scope) -> impl IntoView {
|
||||
<Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route
|
||||
path=""
|
||||
view=|cx| {
|
||||
view! { cx, <Counter/> }
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="form"
|
||||
view=|cx| {
|
||||
view! { cx, <FormCounter/> }
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="multi"
|
||||
view=|cx| {
|
||||
view! { cx, <MultiuserCounter/> }
|
||||
}
|
||||
/>
|
||||
<Route path="" view=Counter/>
|
||||
<Route path="form" view=FormCounter/>
|
||||
<Route path="multi" view=MultiuserCounter/>
|
||||
<Route path="multi" view=NotFound/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
@@ -175,13 +161,9 @@ pub fn FormCounter(cx: Scope) -> impl IntoView {
|
||||
"This counter uses forms to set the value on the server. When progressively enhanced, it should behave identically to the “Simple Counter.”"
|
||||
</p>
|
||||
<div>
|
||||
// calling a server function is the same as POSTing to its API URL
|
||||
// so we can just do that with a form and button
|
||||
<ActionForm action=clear>
|
||||
<input type="submit" value="Clear"/>
|
||||
</ActionForm>
|
||||
// We can submit named arguments to the server functions
|
||||
// by including them as input values with the same name
|
||||
<ActionForm action=adjust>
|
||||
<input type="hidden" name="delta" value="-1"/>
|
||||
<input type="hidden" name="msg" value="form value down"/>
|
||||
@@ -256,3 +238,14 @@ pub fn MultiuserCounter(cx: Scope) -> impl IntoView {
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn NotFound(cx: Scope) -> impl IntoView {
|
||||
#[cfg(feature = "ssr")]
|
||||
{
|
||||
let resp = expect_context::<leptos_actix::ResponseOptions>(cx);
|
||||
resp.set_status(actix_web::http::StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
view! { cx, <h1>"Not Found"</h1> }
|
||||
}
|
||||
|
||||
@@ -52,15 +52,36 @@ cfg_if! {
|
||||
App::new()
|
||||
.service(counter_events)
|
||||
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
|
||||
.leptos_routes(leptos_options.to_owned(), routes.to_owned(), |cx| view! { cx, <Counters/> })
|
||||
.service(Files::new("/", site_root))
|
||||
// serve JS/WASM/CSS from `pkg`
|
||||
.service(Files::new("/pkg", format!("{site_root}/pkg")))
|
||||
// serve other assets from the `assets` directory
|
||||
.service(Files::new("/assets", site_root))
|
||||
// serve the favicon from /favicon.ico
|
||||
.service(favicon)
|
||||
.leptos_routes(
|
||||
leptos_options.to_owned(),
|
||||
routes.to_owned(),
|
||||
Counters,
|
||||
)
|
||||
.app_data(web::Data::new(leptos_options.to_owned()))
|
||||
//.wrap(middleware::Compress::default())
|
||||
})
|
||||
.bind(&addr)?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
#[actix_web::get("favicon.ico")]
|
||||
async fn favicon(
|
||||
leptos_options: actix_web::web::Data<leptos::LeptosOptions>,
|
||||
) -> actix_web::Result<actix_files::NamedFile> {
|
||||
let leptos_options = leptos_options.into_inner();
|
||||
let site_root = &leptos_options.site_root;
|
||||
Ok(actix_files::NamedFile::open(format!(
|
||||
"{site_root}/favicon.ico"
|
||||
))?)
|
||||
}
|
||||
}
|
||||
|
||||
// client-only main for Trunk
|
||||
else {
|
||||
|
||||
@@ -8,7 +8,7 @@ codegen-units = 1
|
||||
lto = true
|
||||
|
||||
[dependencies]
|
||||
leptos = { path = "../../leptos", features = ["stable"] }
|
||||
leptos = { path = "../../leptos", features = ["csr"] }
|
||||
console_log = "1"
|
||||
log = "0.4"
|
||||
console_error_panic_hook = "0.1.7"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use counter_without_macros::counter;
|
||||
use leptos::*;
|
||||
|
||||
/// Show the counter
|
||||
pub fn main() {
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
leptos = { path = "../../leptos" }
|
||||
leptos = { path = "../../leptos", features = ["csr", "nightly"] }
|
||||
log = "0.4"
|
||||
console_log = "1"
|
||||
console_error_panic_hook = "0.1.7"
|
||||
|
||||
20
examples/counters_stable/.gitignore
vendored
Normal file
20
examples/counters_stable/.gitignore
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# Support playwright testing
|
||||
node_modules/
|
||||
test-results/
|
||||
end2end/playwright-report/
|
||||
playwright/.cache/
|
||||
pnpm-lock.yaml
|
||||
|
||||
# Support trunk
|
||||
dist
|
||||
@@ -4,11 +4,24 @@ version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
leptos = { path = "../../leptos", features = ["stable"] }
|
||||
leptos = { path = "../../leptos", features = ["csr"] }
|
||||
leptos_meta = { path = "../../meta", features = ["csr"] }
|
||||
log = "0.4"
|
||||
console_log = "1"
|
||||
console_error_panic_hook = "0.1.7"
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = "0.3.0"
|
||||
wasm-bindgen = "0.2.87"
|
||||
wasm-bindgen-test = "0.3.37"
|
||||
pretty_assertions = "1.3.0"
|
||||
|
||||
[dev-dependencies.web-sys]
|
||||
features = [
|
||||
"Event",
|
||||
"EventInit",
|
||||
"EventTarget",
|
||||
"HtmlElement",
|
||||
"HtmlInputElement",
|
||||
"XPathResult",
|
||||
]
|
||||
version = "0.3.64"
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
extend = [{ path = "../cargo-make/main.toml" }]
|
||||
extend = [
|
||||
{ path = "../cargo-make/main.toml" },
|
||||
{ path = "../cargo-make/wasm-test.toml" },
|
||||
{ path = "../cargo-make/trunk_server.toml" },
|
||||
{ path = "../cargo-make/playwright-test.toml" },
|
||||
]
|
||||
|
||||
[tasks.build]
|
||||
command = "cargo"
|
||||
|
||||
4
examples/counters_stable/e2e/.gitignore
vendored
Normal file
4
examples/counters_stable/e2e/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
/test-results/
|
||||
/playwright-report/
|
||||
/playwright/.cache/
|
||||
83
examples/counters_stable/e2e/package-lock.json
generated
Normal file
83
examples/counters_stable/e2e/package-lock.json
generated
Normal file
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"name": "grip",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "grip",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.35.1"
|
||||
}
|
||||
},
|
||||
"node_modules/.pnpm/@playwright+test@1.33.0": {
|
||||
"extraneous": true
|
||||
},
|
||||
"node_modules/.pnpm/@types+node@20.2.1/node_modules/@types/node": {
|
||||
"version": "20.2.1",
|
||||
"extraneous": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/.pnpm/playwright-core@1.33.0/node_modules/playwright-core": {
|
||||
"version": "1.33.0",
|
||||
"extraneous": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.35.1",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.1.tgz",
|
||||
"integrity": "sha512-b5YoFe6J9exsMYg0pQAobNDR85T1nLumUYgUTtKm4d21iX2L7WqKq9dW8NGJ+2vX0etZd+Y7UeuqsxDXm9+5ZA==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"@types/node": "*",
|
||||
"playwright-core": "1.35.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "20.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.1.tgz",
|
||||
"integrity": "sha512-EhcH/wvidPy1WeML3TtYFGR83UzjxeWRen9V402T8aUGYsCHOmfoisV3ZSg03gAFIbLq8TnWOJ0f4cALtnSEUg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.35.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.1.tgz",
|
||||
"integrity": "sha512-pNXb6CQ7OqmGDRspEjlxE49w+4YtR6a3X6mT1hZXeJHWmsEz7SunmvZeiG/+y1yyMZdHnnn73WKYdtV1er0Xyg==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
7
examples/counters_stable/e2e/package.json
Normal file
7
examples/counters_stable/e2e/package.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"private": "true",
|
||||
"scripts": {},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.35.1"
|
||||
}
|
||||
}
|
||||
77
examples/counters_stable/e2e/playwright.config.ts
Normal file
77
examples/counters_stable/e2e/playwright.config.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Read environment variables from file.
|
||||
* https://github.com/motdotla/dotenv
|
||||
*/
|
||||
// require('dotenv').config();
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: "./tests",
|
||||
/* Run tests in files in parallel */
|
||||
fullyParallel: true,
|
||||
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||
forbidOnly: !process.env.DEV,
|
||||
/* Retry on CI only */
|
||||
retries: process.env.DEV ? 0 : 10,
|
||||
/* Opt out of parallel tests on CI. */
|
||||
workers: process.env.DEV ? 1 : 1,
|
||||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||
reporter: [["html", { open: "never" }], ["list"]],
|
||||
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||
use: {
|
||||
/* Base URL to use in actions like `await page.goto('/')`. */
|
||||
baseURL: "http://127.0.0.1:8080",
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: "on-first-retry",
|
||||
},
|
||||
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
name: "chromium",
|
||||
use: { ...devices["Desktop Chrome"] },
|
||||
},
|
||||
|
||||
// {
|
||||
// name: "firefox",
|
||||
// use: { ...devices["Desktop Firefox"] },
|
||||
// },
|
||||
|
||||
// {
|
||||
// name: "webkit",
|
||||
// use: { ...devices["Desktop Safari"] },
|
||||
// },
|
||||
|
||||
/* Test against mobile viewports. */
|
||||
// {
|
||||
// name: 'Mobile Chrome',
|
||||
// use: { ...devices['Pixel 5'] },
|
||||
// },
|
||||
// {
|
||||
// name: 'Mobile Safari',
|
||||
// use: { ...devices['iPhone 12'] },
|
||||
// },
|
||||
|
||||
/* Test against branded browsers. */
|
||||
// {
|
||||
// name: 'Microsoft Edge',
|
||||
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
|
||||
// },
|
||||
// {
|
||||
// name: 'Google Chrome',
|
||||
// use: { ..devices['Desktop Chrome'], channel: 'chrome' },
|
||||
// },
|
||||
],
|
||||
|
||||
/* Run your local dev server before starting the tests */
|
||||
// webServer: {
|
||||
// command: "cd ../ && trunk serve",
|
||||
// url: "http://127.0.0.1:8080",
|
||||
// reuseExistingServer: false, //!process.env.CI,
|
||||
// },
|
||||
});
|
||||
19
examples/counters_stable/e2e/tests/add_1k_counters.spec.ts
Normal file
19
examples/counters_stable/e2e/tests/add_1k_counters.spec.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { CountersPage } from "./fixtures/counters_page";
|
||||
|
||||
test.describe("Add 1000 Counters", () => {
|
||||
test("should increase the number of counters", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
|
||||
await Promise.all([
|
||||
await ui.goto(),
|
||||
await ui.addOneThousandCountersButton.waitFor(),
|
||||
]);
|
||||
|
||||
await ui.addOneThousandCounters();
|
||||
await ui.addOneThousandCounters();
|
||||
await ui.addOneThousandCounters();
|
||||
|
||||
await expect(ui.counters).toHaveText("3000");
|
||||
});
|
||||
});
|
||||
15
examples/counters_stable/e2e/tests/add_counter.spec.ts
Normal file
15
examples/counters_stable/e2e/tests/add_counter.spec.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { CountersPage } from "./fixtures/counters_page";
|
||||
|
||||
test.describe("Add Counter", () => {
|
||||
test("should increase the number of counters", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
await ui.goto();
|
||||
|
||||
await ui.addCounter();
|
||||
await ui.addCounter();
|
||||
await ui.addCounter();
|
||||
|
||||
await expect(ui.counters).toHaveText("3");
|
||||
});
|
||||
});
|
||||
18
examples/counters_stable/e2e/tests/clear_counters.spec.ts
Normal file
18
examples/counters_stable/e2e/tests/clear_counters.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { CountersPage } from "./fixtures/counters_page";
|
||||
|
||||
test.describe("Clear Counters", () => {
|
||||
test("should reset the counts", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
await ui.goto();
|
||||
|
||||
await ui.addCounter();
|
||||
await ui.addCounter();
|
||||
await ui.addCounter();
|
||||
|
||||
await ui.clearCounters();
|
||||
|
||||
await expect(ui.total).toHaveText("0");
|
||||
await expect(ui.counters).toHaveText("0");
|
||||
});
|
||||
});
|
||||
16
examples/counters_stable/e2e/tests/decrement_count.spec.ts
Normal file
16
examples/counters_stable/e2e/tests/decrement_count.spec.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { CountersPage } from "./fixtures/counters_page";
|
||||
|
||||
test.describe("Decrement Count", () => {
|
||||
test("should decrease the total count", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
await ui.goto();
|
||||
await ui.addCounter();
|
||||
|
||||
await ui.decrementCount();
|
||||
await ui.decrementCount();
|
||||
await ui.decrementCount();
|
||||
|
||||
await expect(ui.total).toHaveText("-3");
|
||||
});
|
||||
});
|
||||
30
examples/counters_stable/e2e/tests/enter_count.spec.ts
Normal file
30
examples/counters_stable/e2e/tests/enter_count.spec.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { CountersPage } from "./fixtures/counters_page";
|
||||
|
||||
test.describe("Enter Count", () => {
|
||||
test("should increase the total count", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
await ui.goto();
|
||||
await ui.addCounter();
|
||||
|
||||
await ui.enterCount("5");
|
||||
|
||||
await expect(ui.total).toHaveText("5");
|
||||
await expect(ui.counters).toHaveText("1");
|
||||
});
|
||||
|
||||
test("should decrease the total count", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
await ui.goto();
|
||||
await ui.addCounter();
|
||||
await ui.addCounter();
|
||||
await ui.addCounter();
|
||||
|
||||
await ui.enterCount("100");
|
||||
await ui.enterCount("100", 1);
|
||||
await ui.enterCount("100", 2);
|
||||
await ui.enterCount("50", 1);
|
||||
|
||||
await expect(ui.total).toHaveText("250");
|
||||
});
|
||||
});
|
||||
98
examples/counters_stable/e2e/tests/fixtures/counters_page.ts
vendored
Normal file
98
examples/counters_stable/e2e/tests/fixtures/counters_page.ts
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
import { expect, Locator, Page } from "@playwright/test";
|
||||
|
||||
export class CountersPage {
|
||||
readonly page: Page;
|
||||
readonly addCounterButton: Locator;
|
||||
readonly addOneThousandCountersButton: Locator;
|
||||
readonly clearCountersButton: Locator;
|
||||
|
||||
readonly incrementCountButton: Locator;
|
||||
readonly counterInput: Locator;
|
||||
readonly decrementCountButton: Locator;
|
||||
readonly removeCountButton: Locator;
|
||||
|
||||
readonly total: Locator;
|
||||
readonly counters: Locator;
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page;
|
||||
|
||||
this.addCounterButton = page.locator("button", { hasText: "Add Counter" });
|
||||
|
||||
this.addOneThousandCountersButton = page.locator("button", {
|
||||
hasText: "Add 1000 Counters",
|
||||
});
|
||||
|
||||
this.clearCountersButton = page.locator("button", {
|
||||
hasText: "Clear Counters",
|
||||
});
|
||||
|
||||
this.decrementCountButton = page.locator("button", {
|
||||
hasText: "-1",
|
||||
});
|
||||
|
||||
this.incrementCountButton = page.locator("button", {
|
||||
hasText: "+1",
|
||||
});
|
||||
|
||||
this.removeCountButton = page.locator("button", {
|
||||
hasText: "x",
|
||||
});
|
||||
|
||||
this.total = page.getByTestId("total");
|
||||
|
||||
this.counters = page.getByTestId("counters");
|
||||
|
||||
this.counterInput = page.getByRole("textbox");
|
||||
}
|
||||
|
||||
async goto() {
|
||||
await this.page.goto("/");
|
||||
}
|
||||
|
||||
async addCounter() {
|
||||
await Promise.all([
|
||||
this.addCounterButton.waitFor(),
|
||||
this.addCounterButton.click(),
|
||||
]);
|
||||
}
|
||||
|
||||
async addOneThousandCounters() {
|
||||
this.addOneThousandCountersButton.click();
|
||||
}
|
||||
|
||||
async decrementCount(index: number = 0) {
|
||||
await Promise.all([
|
||||
this.decrementCountButton.nth(index).waitFor(),
|
||||
this.decrementCountButton.nth(index).click(),
|
||||
]);
|
||||
}
|
||||
|
||||
async incrementCount(index: number = 0) {
|
||||
await Promise.all([
|
||||
this.incrementCountButton.nth(index).waitFor(),
|
||||
this.incrementCountButton.nth(index).click(),
|
||||
]);
|
||||
}
|
||||
|
||||
async clearCounters() {
|
||||
await Promise.all([
|
||||
this.clearCountersButton.waitFor(),
|
||||
this.clearCountersButton.click(),
|
||||
]);
|
||||
}
|
||||
|
||||
async enterCount(count: string, index: number = 0) {
|
||||
await Promise.all([
|
||||
this.counterInput.nth(index).waitFor(),
|
||||
this.counterInput.nth(index).fill(count),
|
||||
]);
|
||||
}
|
||||
|
||||
async removeCounter(index: number = 0) {
|
||||
await Promise.all([
|
||||
this.removeCountButton.nth(index).waitFor(),
|
||||
this.removeCountButton.nth(index).click(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
16
examples/counters_stable/e2e/tests/increment_count.spec.ts
Normal file
16
examples/counters_stable/e2e/tests/increment_count.spec.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { CountersPage } from "./fixtures/counters_page";
|
||||
|
||||
test.describe("Increment Count", () => {
|
||||
test("should increase the total count", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
await ui.goto();
|
||||
await ui.addCounter();
|
||||
|
||||
await ui.incrementCount();
|
||||
await ui.incrementCount();
|
||||
await ui.incrementCount();
|
||||
|
||||
await expect(ui.total).toHaveText("3");
|
||||
});
|
||||
});
|
||||
17
examples/counters_stable/e2e/tests/remove_counter.spec.ts
Normal file
17
examples/counters_stable/e2e/tests/remove_counter.spec.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { CountersPage } from "./fixtures/counters_page";
|
||||
|
||||
test.describe("Remove Counter", () => {
|
||||
test("should decrement the number of counters", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
await ui.goto();
|
||||
|
||||
await ui.addCounter();
|
||||
await ui.addCounter();
|
||||
await ui.addCounter();
|
||||
|
||||
await ui.removeCounter(1);
|
||||
|
||||
await expect(ui.counters).toHaveText("2");
|
||||
});
|
||||
});
|
||||
19
examples/counters_stable/e2e/tests/view_counters.spec.ts
Normal file
19
examples/counters_stable/e2e/tests/view_counters.spec.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { CountersPage } from "./fixtures/counters_page";
|
||||
|
||||
test.describe("View Counters", () => {
|
||||
test("should see the title", async ({ page }) => {
|
||||
const ui = new CountersPage(page);
|
||||
await ui.goto();
|
||||
|
||||
await expect(page).toHaveTitle("Counters (Stable)");
|
||||
});
|
||||
|
||||
test("should see the initial counts", async ({ page }) => {
|
||||
const counters = new CountersPage(page);
|
||||
await counters.goto();
|
||||
|
||||
await expect(counters.total).toHaveText("0");
|
||||
await expect(counters.counters).toHaveText("0");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Counters (Stable)</title>
|
||||
<link data-trunk rel="rust" data-wasm-opt="z" data-weak-refs/>
|
||||
</head>
|
||||
<body></body>
|
||||
|
||||
11
examples/counters_stable/package.json
Normal file
11
examples/counters_stable/package.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"private": "true",
|
||||
"scripts": {
|
||||
"start-server": "trunk serve",
|
||||
"e2e": "cargo make test-playwright",
|
||||
"e2e:auto-start": "start-server-and-test start-server http://127.0.0.1:8080 e2e"
|
||||
},
|
||||
"devDependencies": {
|
||||
"start-server-and-test": "^1.15.4"
|
||||
}
|
||||
}
|
||||
109
examples/counters_stable/src/lib.rs
Normal file
109
examples/counters_stable/src/lib.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use leptos::*;
|
||||
use leptos_meta::*;
|
||||
|
||||
const MANY_COUNTERS: usize = 1000;
|
||||
|
||||
type CounterHolder = Vec<(usize, (ReadSignal<i32>, WriteSignal<i32>))>;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct CounterUpdater {
|
||||
set_counters: WriteSignal<CounterHolder>,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Counters(cx: Scope) -> impl IntoView {
|
||||
let (next_counter_id, set_next_counter_id) = create_signal(cx, 0);
|
||||
let (counters, set_counters) = create_signal::<CounterHolder>(cx, vec![]);
|
||||
provide_context(cx, CounterUpdater { set_counters });
|
||||
provide_meta_context(cx);
|
||||
|
||||
let add_counter = move |_| {
|
||||
let id = next_counter_id.get();
|
||||
let sig = create_signal(cx, 0);
|
||||
set_counters.update(move |counters| counters.push((id, sig)));
|
||||
set_next_counter_id.update(|id| *id += 1);
|
||||
};
|
||||
|
||||
let add_many_counters = move |_| {
|
||||
let next_id = next_counter_id.get();
|
||||
let new_counters = (next_id..next_id + MANY_COUNTERS).map(|id| {
|
||||
let signal = create_signal(cx, 0);
|
||||
(id, signal)
|
||||
});
|
||||
|
||||
set_counters.update(move |counters| counters.extend(new_counters));
|
||||
set_next_counter_id.update(|id| *id += MANY_COUNTERS);
|
||||
};
|
||||
|
||||
let clear_counters = move |_| {
|
||||
set_counters.update(|counters| counters.clear());
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<Title text="Counters (Stable)" />
|
||||
<div>
|
||||
<button on:click=add_counter>
|
||||
"Add Counter"
|
||||
</button>
|
||||
<button on:click=add_many_counters>
|
||||
{format!("Add {MANY_COUNTERS} Counters")}
|
||||
</button>
|
||||
<button on:click=clear_counters>
|
||||
"Clear Counters"
|
||||
</button>
|
||||
<p>
|
||||
"Total: "
|
||||
<span data-testid="total">{move ||
|
||||
counters.get()
|
||||
.iter()
|
||||
.map(|(_, (count, _))| count.get())
|
||||
.sum::<i32>()
|
||||
.to_string()
|
||||
}</span>
|
||||
" from "
|
||||
<span data-testid="counters">{move || counters.with(|counters| counters.len()).to_string()}</span>
|
||||
" counters."
|
||||
</p>
|
||||
<ul>
|
||||
<For
|
||||
each={move || counters.get()}
|
||||
key={|counter| counter.0}
|
||||
view=move |cx, (id, (value, set_value))| {
|
||||
view! {
|
||||
cx,
|
||||
<Counter id value set_value/>
|
||||
}
|
||||
}
|
||||
/>
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Counter(
|
||||
cx: Scope,
|
||||
id: usize,
|
||||
value: ReadSignal<i32>,
|
||||
set_value: WriteSignal<i32>,
|
||||
) -> impl IntoView {
|
||||
let CounterUpdater { set_counters } = use_context(cx).unwrap();
|
||||
|
||||
let input = move |ev| {
|
||||
set_value
|
||||
.set(event_target_value(&ev).parse::<i32>().unwrap_or_default())
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<li>
|
||||
<button data-testid="decrement_count" on:click=move |_| set_value.update(move |value| *value -= 1)>"-1"</button>
|
||||
<input data-testid="counter_input" type="text"
|
||||
prop:value={move || value.get().to_string()}
|
||||
on:input=input
|
||||
/>
|
||||
<span>{value}</span>
|
||||
<button data-testid="increment_count" on:click=move |_| set_value.update(move |value| *value += 1)>"+1"</button>
|
||||
<button data-testid="remove_counter" on:click=move |_| set_counters.update(move |counters| counters.retain(|(counter_id, _)| counter_id != &id))>"x"</button>
|
||||
</li>
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use counters_stable::Counters;
|
||||
use leptos::*;
|
||||
|
||||
fn main() {
|
||||
@@ -5,108 +6,3 @@ fn main() {
|
||||
console_error_panic_hook::set_once();
|
||||
mount_to_body(|cx| view! { cx, <Counters/> })
|
||||
}
|
||||
|
||||
const MANY_COUNTERS: usize = 1000;
|
||||
|
||||
type CounterHolder = Vec<(usize, (ReadSignal<i32>, WriteSignal<i32>))>;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct CounterUpdater {
|
||||
set_counters: WriteSignal<CounterHolder>,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Counters(cx: Scope) -> impl IntoView {
|
||||
let (next_counter_id, set_next_counter_id) = create_signal(cx, 0);
|
||||
let (counters, set_counters) = create_signal::<CounterHolder>(cx, vec![]);
|
||||
provide_context(cx, CounterUpdater { set_counters });
|
||||
|
||||
let add_counter = move |_| {
|
||||
let id = next_counter_id.get();
|
||||
let sig = create_signal(cx, 0);
|
||||
set_counters.update(move |counters| counters.push((id, sig)));
|
||||
set_next_counter_id.update(|id| *id += 1);
|
||||
};
|
||||
|
||||
let add_many_counters = move |_| {
|
||||
let next_id = next_counter_id.get();
|
||||
let new_counters = (next_id..next_id + MANY_COUNTERS).map(|id| {
|
||||
let signal = create_signal(cx, 0);
|
||||
(id, signal)
|
||||
});
|
||||
|
||||
set_counters.update(move |counters| counters.extend(new_counters));
|
||||
set_next_counter_id.update(|id| *id += MANY_COUNTERS);
|
||||
};
|
||||
|
||||
let clear_counters = move |_| {
|
||||
set_counters.update(|counters| counters.clear());
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div>
|
||||
<button on:click=add_counter>
|
||||
"Add Counter"
|
||||
</button>
|
||||
<button on:click=add_many_counters>
|
||||
{format!("Add {MANY_COUNTERS} Counters")}
|
||||
</button>
|
||||
<button on:click=clear_counters>
|
||||
"Clear Counters"
|
||||
</button>
|
||||
<p>
|
||||
"Total: "
|
||||
<span>{move ||
|
||||
counters.get()
|
||||
.iter()
|
||||
.map(|(_, (count, _))| count.get())
|
||||
.sum::<i32>()
|
||||
.to_string()
|
||||
}</span>
|
||||
" from "
|
||||
<span>{move || counters.with(|counters| counters.len()).to_string()}</span>
|
||||
" counters."
|
||||
</p>
|
||||
<ul>
|
||||
<For
|
||||
each={move || counters.get()}
|
||||
key={|counter| counter.0}
|
||||
view=move |cx, (id, (value, set_value))| {
|
||||
view! {
|
||||
cx,
|
||||
<Counter id value set_value/>
|
||||
}
|
||||
}
|
||||
/>
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Counter(
|
||||
cx: Scope,
|
||||
id: usize,
|
||||
value: ReadSignal<i32>,
|
||||
set_value: WriteSignal<i32>,
|
||||
) -> impl IntoView {
|
||||
let CounterUpdater { set_counters } = use_context(cx).unwrap();
|
||||
|
||||
let input = move |ev| {
|
||||
set_value
|
||||
.set(event_target_value(&ev).parse::<i32>().unwrap_or_default())
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<li>
|
||||
<button on:click=move |_| set_value.update(move |value| *value -= 1)>"-1"</button>
|
||||
<input type="text"
|
||||
prop:value={move || value.get().to_string()}
|
||||
on:input=input
|
||||
/>
|
||||
<span>{move || value.get().to_string()}</span>
|
||||
<button on:click=move |_| set_value.update(move |value| *value += 1)>"+1"</button>
|
||||
<button on:click=move |_| set_counters.update(move |counters| counters.retain(|(counter_id, _)| counter_id != &id))>"x"</button>
|
||||
</li>
|
||||
}
|
||||
}
|
||||
|
||||
17
examples/counters_stable/tests/web/add_1k_counters.rs
Normal file
17
examples/counters_stable/tests/web/add_1k_counters.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use super::*;
|
||||
use crate::counters_page as ui;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn should_increase_the_number_of_counters() {
|
||||
// Given
|
||||
ui::view_counters();
|
||||
|
||||
// When
|
||||
ui::add_1k_counters();
|
||||
ui::add_1k_counters();
|
||||
ui::add_1k_counters();
|
||||
|
||||
// Then
|
||||
assert_eq!(ui::counters(), 3000);
|
||||
}
|
||||
17
examples/counters_stable/tests/web/add_counter.rs
Normal file
17
examples/counters_stable/tests/web/add_counter.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use super::*;
|
||||
use crate::counters_page as ui;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn should_increase_the_number_of_counters() {
|
||||
// Given
|
||||
ui::view_counters();
|
||||
|
||||
// When
|
||||
ui::add_counter();
|
||||
ui::add_counter();
|
||||
ui::add_counter();
|
||||
|
||||
// Then
|
||||
assert_eq!(ui::counters(), 3);
|
||||
}
|
||||
19
examples/counters_stable/tests/web/clear_counters.rs
Normal file
19
examples/counters_stable/tests/web/clear_counters.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
use super::*;
|
||||
use crate::counters_page as ui;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn should_reset_the_counts() {
|
||||
// Given
|
||||
ui::view_counters();
|
||||
ui::add_counter();
|
||||
ui::add_counter();
|
||||
ui::add_counter();
|
||||
|
||||
// When
|
||||
ui::clear_counters();
|
||||
|
||||
// Then
|
||||
assert_eq!(ui::total(), 0);
|
||||
assert_eq!(ui::counters(), 0);
|
||||
}
|
||||
18
examples/counters_stable/tests/web/decrement_counter.rs
Normal file
18
examples/counters_stable/tests/web/decrement_counter.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use super::*;
|
||||
use crate::counters_page as ui;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn should_decrease_the_total_count() {
|
||||
// Given
|
||||
ui::view_counters();
|
||||
ui::add_counter();
|
||||
|
||||
// When
|
||||
ui::decrement_counter(1);
|
||||
ui::decrement_counter(1);
|
||||
ui::decrement_counter(1);
|
||||
|
||||
// Then
|
||||
assert_eq!(ui::total(), -3);
|
||||
}
|
||||
34
examples/counters_stable/tests/web/enter_count.rs
Normal file
34
examples/counters_stable/tests/web/enter_count.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use super::*;
|
||||
use crate::counters_page as ui;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn should_increase_the_total_count() {
|
||||
// Given
|
||||
ui::view_counters();
|
||||
ui::add_counter();
|
||||
|
||||
// When
|
||||
ui::enter_count(1, 5);
|
||||
|
||||
// Then
|
||||
assert_eq!(ui::total(), 5);
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn should_decrease_the_total_count() {
|
||||
// Given
|
||||
ui::view_counters();
|
||||
ui::add_counter();
|
||||
ui::add_counter();
|
||||
ui::add_counter();
|
||||
|
||||
// When
|
||||
ui::enter_count(1, 100);
|
||||
ui::enter_count(2, 100);
|
||||
ui::enter_count(3, 100);
|
||||
ui::enter_count(1, 50);
|
||||
|
||||
// Then
|
||||
assert_eq!(ui::total(), 250);
|
||||
}
|
||||
112
examples/counters_stable/tests/web/fixtures/counters_page.rs
Normal file
112
examples/counters_stable/tests/web/fixtures/counters_page.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
use counters_stable::Counters;
|
||||
use leptos::*;
|
||||
use wasm_bindgen::JsCast;
|
||||
use web_sys::{Element, Event, EventInit, HtmlElement, HtmlInputElement};
|
||||
|
||||
// Actions
|
||||
|
||||
pub fn add_1k_counters() {
|
||||
find_by_text("Add 1000 Counters").click();
|
||||
}
|
||||
|
||||
pub fn add_counter() {
|
||||
find_by_text("Add Counter").click();
|
||||
}
|
||||
|
||||
pub fn clear_counters() {
|
||||
find_by_text("Clear Counters").click();
|
||||
}
|
||||
|
||||
pub fn decrement_counter(index: u32) {
|
||||
counter_html_element(index, "decrement_count").click();
|
||||
}
|
||||
|
||||
pub fn enter_count(index: u32, count: i32) {
|
||||
let input = counter_input_element(index, "counter_input");
|
||||
input.set_value(count.to_string().as_str());
|
||||
let mut event_init = EventInit::new();
|
||||
event_init.bubbles(true);
|
||||
let event = Event::new_with_event_init_dict("input", &event_init).unwrap();
|
||||
input.dispatch_event(&event).unwrap();
|
||||
}
|
||||
|
||||
pub fn increment_counter(index: u32) {
|
||||
counter_html_element(index, "increment_count").click();
|
||||
}
|
||||
|
||||
pub fn remove_counter(index: u32) {
|
||||
counter_html_element(index, "remove_counter").click();
|
||||
}
|
||||
|
||||
pub fn view_counters() {
|
||||
remove_existing_counters();
|
||||
mount_to_body(|cx| view! { cx, <Counters/> });
|
||||
}
|
||||
|
||||
// Results
|
||||
|
||||
pub fn counters() -> i32 {
|
||||
data_test_id("counters").parse::<i32>().unwrap()
|
||||
}
|
||||
|
||||
pub fn title() -> String {
|
||||
leptos::document().title()
|
||||
}
|
||||
|
||||
pub fn total() -> i32 {
|
||||
data_test_id("total").parse::<i32>().unwrap()
|
||||
}
|
||||
|
||||
// Internal
|
||||
|
||||
fn counter_element(index: u32, text: &str) -> Element {
|
||||
let selector =
|
||||
format!("li:nth-child({}) [data-testid=\"{}\"]", index, text);
|
||||
leptos::document()
|
||||
.query_selector(&selector)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn counter_html_element(index: u32, text: &str) -> HtmlElement {
|
||||
counter_element(index, text)
|
||||
.dyn_into::<HtmlElement>()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn counter_input_element(index: u32, text: &str) -> HtmlInputElement {
|
||||
counter_element(index, text)
|
||||
.dyn_into::<HtmlInputElement>()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn data_test_id(id: &str) -> String {
|
||||
let selector = format!("[data-testid=\"{}\"]", id);
|
||||
leptos::document()
|
||||
.query_selector(&selector)
|
||||
.unwrap()
|
||||
.expect("counters not found")
|
||||
.text_content()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn find_by_text(text: &str) -> HtmlElement {
|
||||
let xpath = format!("//*[text()='{}']", text);
|
||||
let document = leptos::document();
|
||||
document
|
||||
.evaluate(&xpath, &document)
|
||||
.unwrap()
|
||||
.iterate_next()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.dyn_into::<HtmlElement>()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn remove_existing_counters() {
|
||||
if let Some(counter) =
|
||||
leptos::document().query_selector("body div").unwrap()
|
||||
{
|
||||
counter.remove();
|
||||
}
|
||||
}
|
||||
1
examples/counters_stable/tests/web/fixtures/mod.rs
Normal file
1
examples/counters_stable/tests/web/fixtures/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod counters_page;
|
||||
18
examples/counters_stable/tests/web/increment_counter.rs
Normal file
18
examples/counters_stable/tests/web/increment_counter.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use super::*;
|
||||
use crate::counters_page as ui;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn should_increase_the_total_count() {
|
||||
// Given
|
||||
ui::view_counters();
|
||||
ui::add_counter();
|
||||
|
||||
// When
|
||||
ui::increment_counter(1);
|
||||
ui::increment_counter(1);
|
||||
ui::increment_counter(1);
|
||||
|
||||
// Then
|
||||
assert_eq!(ui::total(), 3);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user