mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-28 09:02:37 -05:00
Compare commits
4 Commits
context-do
...
component-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c8b640855 | ||
|
|
621976c92c | ||
|
|
b2d7ad2afd | ||
|
|
73b21487b9 |
@@ -18,7 +18,6 @@ members = [
|
||||
"router",
|
||||
|
||||
# examples
|
||||
"examples/cloudflare-worker",
|
||||
"examples/counter",
|
||||
"examples/counter-isomorphic",
|
||||
"examples/counters",
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
# http://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = tab
|
||||
tab_width = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.yml]
|
||||
indent_style = space
|
||||
10
examples/cloudflare-worker/.gitignore
vendored
10
examples/cloudflare-worker/.gitignore
vendored
@@ -1,10 +0,0 @@
|
||||
.DS_Store
|
||||
/node_modules
|
||||
|
||||
**/*.rs.bk
|
||||
wasm-pack.log
|
||||
|
||||
build/
|
||||
/target
|
||||
/dist
|
||||
pkg
|
||||
@@ -1,20 +0,0 @@
|
||||
[package]
|
||||
name = "counter-worker"
|
||||
version = "0.0.0"
|
||||
edition = "2018"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
cfg-if = "1"
|
||||
worker = { version = "0.0.12", optional = true }
|
||||
serde_json = "1"
|
||||
leptos = { path = "../../leptos", default-features = false }
|
||||
console_error_panic_hook = "0.1"
|
||||
wasm-bindgen = "0.2"
|
||||
|
||||
[features]
|
||||
default = ["ssr"]
|
||||
ssr = ["leptos/ssr", "dep:worker"]
|
||||
hydrate = ["leptos/hydrate"]
|
||||
@@ -1,19 +0,0 @@
|
||||
This example shows the basics of how you’d render a Leptos component to HTML in a Cloudflare Worker and then hydrate it on the client side.
|
||||
|
||||
First, compile the client-side WebAssembly with
|
||||
```sh
|
||||
wasm-pack build --target=web --no-default-features --features=hydrate
|
||||
```
|
||||
|
||||
Then run the Worker:
|
||||
|
||||
```sh
|
||||
# run your Worker in an ideal development workflow (with a local server, file watcher & more)
|
||||
$ npm run dev
|
||||
|
||||
# deploy your Worker globally to the Cloudflare network (update your wrangler.toml file for configuration)
|
||||
$ npm run deploy
|
||||
```
|
||||
|
||||
## Important Note
|
||||
It's possible the URL for some of the JS necessary for hydration will change between `wasm-pack` builds. Obviously this is not great, but this is a proof of concept more than anything. If there's trouble loading JS, check the URL at `lib.rs:72` against the filenames in `pkg` and adjust `lib.rs` to match the correct path.
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"deploy": "wrangler publish",
|
||||
"dev": "wrangler dev --local"
|
||||
},
|
||||
"devDependencies": {
|
||||
"wrangler": "^2.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
use cfg_if::cfg_if;
|
||||
use leptos::*;
|
||||
use worker::ResponseBody;
|
||||
|
||||
const PKG_PATH: &str = "/pkg/counter_worker";
|
||||
|
||||
#[component]
|
||||
pub fn Counter(cx: Scope) -> Element {
|
||||
let (value, set_value) = create_signal(cx, 0);
|
||||
|
||||
view! { cx,
|
||||
<div>
|
||||
<button on:click=move |_| set_value(0)>"Clear"</button>
|
||||
<button on:click=move |_| set_value.update(|value| *value -= 1)>"-1"</button>
|
||||
<span>"Value: " {move || value().to_string()} "!"</span>
|
||||
<button on:click=move |_| set_value.update(|value| *value += 1)>"+1"</button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
// Load client-side Wasm and hydrate rendered app
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "hydrate")] {
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn hydrate() {
|
||||
console_error_panic_hook::set_once();
|
||||
leptos::hydrate(body().unwrap(), move |cx| {
|
||||
view! { cx, <Counter/> }
|
||||
});
|
||||
}
|
||||
} else {
|
||||
use worker::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn log_request(req: &Request) {
|
||||
console_log!(
|
||||
"{} - [{}], located at: {:?}, within: {}",
|
||||
Date::now().to_string(),
|
||||
req.path(),
|
||||
req.cf().coordinates().unwrap_or_default(),
|
||||
req.cf().region().unwrap_or_else(|| "unknown region".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[event(fetch)]
|
||||
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
|
||||
log_request(&req);
|
||||
|
||||
// Optionally, use the Router to handle matching endpoints, use ":name" placeholders, or "*name"
|
||||
// catch-alls to match on specific patterns. Alternatively, use `Router::with_data(D)` to
|
||||
// provide arbitrary data that will be accessible in each route via the `ctx.data()` method.
|
||||
let router = Router::new();
|
||||
|
||||
// Add as many routes as your Worker needs! Each route will get a `Request` for handling HTTP
|
||||
// functionality and a `RouteContext` which you can use to and get route parameters and
|
||||
// Environment bindings like KV Stores, Durable Objects, Secrets, and Variables.
|
||||
router
|
||||
.get("/", |_, _| Response::from_html(render_html_page(&render_to_string(|cx| view! { cx, <Counter/> }))))
|
||||
// serve JS to load Wasm
|
||||
// this section is kind of a mess; ideally it could point to static files rather than inlining them and serving like this
|
||||
.get(&format!("{PKG_PATH}.js"), |_, _| {
|
||||
let mut headers = Headers::new();
|
||||
headers.set("Content-Type", "text/javascript")?;
|
||||
let body = ResponseBody::Body(include_str!("../pkg/counter_worker.js").as_bytes().to_vec());
|
||||
Ok(
|
||||
Response::from_body(body)?
|
||||
.with_headers(headers)
|
||||
)
|
||||
})
|
||||
.get("/pkg/snippets/leptos_dom-68e8edfe5e6c8b92/inline0.js", |_, _| {
|
||||
let mut headers = Headers::new();
|
||||
headers.set("Content-Type", "text/javascript")?;
|
||||
let body = ResponseBody::Body(include_str!("../pkg/snippets/leptos_dom-68e8edfe5e6c8b92/inline0.js").as_bytes().to_vec());
|
||||
Ok(
|
||||
Response::from_body(body)?
|
||||
.with_headers(headers)
|
||||
)
|
||||
})
|
||||
.get(&format!("{PKG_PATH}_bg.wasm"), |_, _| {
|
||||
let mut headers = Headers::new();
|
||||
headers.set("Content-Type", "application/wasm")?;
|
||||
let body = ResponseBody::Body(include_bytes!("../pkg/counter_worker_bg.wasm").to_vec());
|
||||
Ok(
|
||||
Response::from_body(body)?
|
||||
.with_headers(headers)
|
||||
)
|
||||
})
|
||||
.get("/worker-version", |_, ctx| {
|
||||
let version = ctx.var("WORKERS_RS_VERSION")?.to_string();
|
||||
Response::ok(version)
|
||||
})
|
||||
.run(req, env)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_html_page(body: &str) -> String {
|
||||
format!(
|
||||
r#"<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<link rel="modulepreload" href="{PKG_PATH}.js">
|
||||
<link rel="preload" href="{PKG_PATH}_bg.wasm" as="fetch" type="application/wasm" crossorigin="">
|
||||
<script type="module">import init, {{ hydrate }} from '{PKG_PATH}.js'; init('{PKG_PATH}_bg.wasm').then(hydrate);</script>
|
||||
</head>
|
||||
<body>
|
||||
{body}
|
||||
</body>
|
||||
</html>"#
|
||||
)
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
name = "" # todo
|
||||
main = "build/worker/shim.mjs"
|
||||
compatibility_date = "2022-01-20"
|
||||
|
||||
[vars]
|
||||
WORKERS_RS_VERSION = "0.0.11"
|
||||
|
||||
[build]
|
||||
command = "cargo install -q worker-build --version 0.0.7 && worker-build --release"
|
||||
@@ -177,7 +177,8 @@ mod server;
|
||||
/// # });
|
||||
/// ```
|
||||
///
|
||||
/// 8. You can use the `_ref` attribute to store a reference to its DOM element in a [NodeRef](leptos::NodeRef) to use later.
|
||||
/// 8. You can use the `_ref` attribute to store a reference to its DOM element in a
|
||||
/// [NodeRef](leptos_reactive::NodeRef) to use later.
|
||||
/// ```rust
|
||||
/// # use leptos_reactive::*; use leptos_dom::*; use leptos_macro::view; use leptos_dom::wasm_bindgen::JsCast;
|
||||
/// # run_scope(create_runtime(), |cx| {
|
||||
@@ -242,9 +243,50 @@ pub fn view(tokens: TokenStream) -> TokenStream {
|
||||
}
|
||||
}
|
||||
|
||||
/// Annotates a function so that it can be used with your template as a <Component/>
|
||||
/// Annotates a function so that it can be used with your template as a Leptos `<Component/>`.
|
||||
///
|
||||
/// The `#[component]` macro allows you to annotate plain Rust functions that return [Element](leptos_dom::Element)s,
|
||||
/// and use them within your Leptos [view](mod@view) as if they were custom HTML elements. The
|
||||
/// component function takes a [Scope](leptos_reactive::Scope) and any number of other arguments.
|
||||
/// When you use the component somewhere else, the names of its arguments are the names
|
||||
/// of the properties you use in the [view](mod@view) macro.
|
||||
///
|
||||
/// Here’s how you would define and use a simple Leptos component which can accept custom properties for a name and age:
|
||||
/// ```rust
|
||||
/// # use leptos::*;
|
||||
/// use std::time::Duration;
|
||||
///
|
||||
/// #[component]
|
||||
/// fn HelloComponent(cx: Scope, name: String, age: u8) -> Element {
|
||||
/// // create the signals (reactive values) that will update the UI
|
||||
/// let (age, set_age) = create_signal(cx, age);
|
||||
/// // increase `age` by 1 every second
|
||||
/// set_interval(move || {
|
||||
/// set_age.update(|age| *age += 1)
|
||||
/// }, Duration::from_secs(1));
|
||||
///
|
||||
/// // return the user interface, which will be automatically updated
|
||||
/// // when signal values change
|
||||
/// view! { cx,
|
||||
/// <p>"Your name is " {name} " and you are " {age} " years old."</p>
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// fn App(cx: Scope) -> Element {
|
||||
/// view! { cx,
|
||||
/// <main>
|
||||
/// <HelloComponent name="Greg".to_string() age=32/>
|
||||
/// </main>
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `#[component]` macro creates a struct with a name like `HelloComponentProps`. If you define
|
||||
/// your component in one module and import it into another, make sure you import this `___Props`
|
||||
/// struct as well.
|
||||
///
|
||||
/// Here are some things you should know.
|
||||
/// Here are some important details about how Leptos components work within the framework:
|
||||
/// 1. **The component function only runs once.** Your component function is not a “render” function
|
||||
/// that re-runs whenever changes happen in the state. It’s a “setup” function that runs once to
|
||||
/// create the user interface, and sets up a reactive system to update it. This means it’s okay
|
||||
@@ -350,7 +392,7 @@ pub fn component(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream
|
||||
}
|
||||
}
|
||||
|
||||
/// Declares that a function is a [server function](leptos::leptos_server). This means that
|
||||
/// Declares that a function is a [server function](leptos_server). This means that
|
||||
/// its body will only run on the server, i.e., when the `ssr` feature is enabled.
|
||||
///
|
||||
/// If you call a server function from the client (i.e., when the `csr` or `hydrate` features
|
||||
|
||||
@@ -33,7 +33,6 @@ cfg-if = "1.0.0"
|
||||
rmp-serde = "1.1.1"
|
||||
|
||||
[dev-dependencies]
|
||||
leptos = "0.0"
|
||||
tokio-test = "0.4"
|
||||
|
||||
[features]
|
||||
|
||||
@@ -13,37 +13,35 @@ use crate::{runtime::with_runtime, Scope};
|
||||
/// arguments to a function or properties of a component.
|
||||
///
|
||||
/// ```
|
||||
/// use leptos::*;
|
||||
///
|
||||
/// // define a newtype we'll provide as context
|
||||
/// // contexts are stored by their types, so it can be useful to create
|
||||
/// // a new type to avoid confusion with other `WriteSignal<i32>`s we may have
|
||||
/// // all types to be shared via context should implement `Clone`
|
||||
/// #[derive(Copy, Clone)]
|
||||
/// struct ValueSetter(WriteSignal<i32>);
|
||||
///
|
||||
/// #[component]
|
||||
/// pub fn Provider(cx: Scope) -> Element {
|
||||
/// let (value, set_value) = create_signal(cx, 0);
|
||||
///
|
||||
/// // 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 ButtonD
|
||||
/// provide_context(cx, ValueSetter(set_value));
|
||||
///
|
||||
/// // because <Consumer/> is nested inside <Provider/>,
|
||||
/// // it has access to the provided context
|
||||
/// view! { cx, <div><Consumer/></div> }
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// pub fn Consumer(cx: Scope) -> Element {
|
||||
/// // consume the provided context of type `ValueSetter` using `use_context`
|
||||
/// // this traverses up the tree of `Scope`s and gets the nearest provided `ValueSetter`
|
||||
/// let set_value = use_context::<ValueSetter>(cx).unwrap().0;
|
||||
///
|
||||
/// todo!()
|
||||
/// # use leptos_reactive::*;
|
||||
/// # create_scope(create_runtime(), |cx| {
|
||||
///
|
||||
/// // Note: this example doesn’t use Leptos’s DOM model or component structure,
|
||||
/// // so it ends up being a little silly.
|
||||
///
|
||||
/// #[derive(Clone)]
|
||||
/// struct SharedData {
|
||||
/// name: (ReadSignal<String>, WriteSignal<String>)
|
||||
/// }
|
||||
///
|
||||
/// let my_context_obj = SharedData { name: create_signal(cx, "Greg".to_string()) };
|
||||
/// provide_context(cx, my_context_obj);
|
||||
///
|
||||
/// // we can access it in this Scope
|
||||
/// let shared_data = use_context::<SharedData>(cx).unwrap();
|
||||
/// let (name, set_name) = shared_data.name;
|
||||
///
|
||||
/// // we can access it somewhere in a lower scope
|
||||
/// cx.child_scope(|cx| {
|
||||
/// let shared_data_lower_in_tree = use_context::<SharedData>(cx).unwrap();
|
||||
/// let (name, set_name) = shared_data.name;
|
||||
/// set_name("Bob".to_string());
|
||||
/// });
|
||||
///
|
||||
/// // the change made in a lower scope updated the signal in the parent scope
|
||||
/// assert_eq!(name(), "Bob");
|
||||
///
|
||||
/// # }).dispose();
|
||||
/// ```
|
||||
pub fn provide_context<T>(cx: Scope, value: T)
|
||||
where
|
||||
@@ -67,37 +65,35 @@ where
|
||||
/// arguments to a function or properties of a component.
|
||||
///
|
||||
/// ```
|
||||
/// use leptos::*;
|
||||
///
|
||||
/// // define a newtype we'll provide as context
|
||||
/// // contexts are stored by their types, so it can be useful to create
|
||||
/// // a new type to avoid confusion with other `WriteSignal<i32>`s we may have
|
||||
/// // all types to be shared via context should implement `Clone`
|
||||
/// #[derive(Copy, Clone)]
|
||||
/// struct ValueSetter(WriteSignal<i32>);
|
||||
///
|
||||
/// #[component]
|
||||
/// pub fn Provider(cx: Scope) -> Element {
|
||||
/// let (value, set_value) = create_signal(cx, 0);
|
||||
///
|
||||
/// // 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 ButtonD
|
||||
/// provide_context(cx, ValueSetter(set_value));
|
||||
///
|
||||
/// // because <Consumer/> is nested inside <Provider/>,
|
||||
/// // it has access to the provided context
|
||||
/// view! { cx, <div><Consumer/></div> }
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// pub fn Consumer(cx: Scope) -> Element {
|
||||
/// // consume the provided context of type `ValueSetter` using `use_context`
|
||||
/// // this traverses up the tree of `Scope`s and gets the nearest provided `ValueSetter`
|
||||
/// let set_value = use_context::<ValueSetter>(cx).unwrap().0;
|
||||
///
|
||||
/// todo!()
|
||||
/// # use leptos_reactive::*;
|
||||
/// # create_scope(create_runtime(), |cx| {
|
||||
///
|
||||
/// // Note: this example doesn’t use Leptos’s DOM model or component structure,
|
||||
/// // so it ends up being a little silly.
|
||||
///
|
||||
/// #[derive(Clone)]
|
||||
/// struct SharedData {
|
||||
/// name: (ReadSignal<String>, WriteSignal<String>)
|
||||
/// }
|
||||
///
|
||||
/// let my_context_obj = SharedData { name: create_signal(cx, "Greg".to_string()) };
|
||||
/// provide_context(cx, my_context_obj);
|
||||
///
|
||||
/// // we can access it in this Scope
|
||||
/// let shared_data = use_context::<SharedData>(cx).unwrap();
|
||||
/// let (name, set_name) = shared_data.name;
|
||||
///
|
||||
/// // we can access it somewhere in a lower scope
|
||||
/// cx.child_scope(|cx| {
|
||||
/// let shared_data_lower_in_tree = use_context::<SharedData>(cx).unwrap();
|
||||
/// let (name, set_name) = shared_data.name;
|
||||
/// set_name("Bob".to_string());
|
||||
/// });
|
||||
///
|
||||
/// // the change made in a lower scope updated the signal in the parent scope
|
||||
/// assert_eq!(name(), "Bob");
|
||||
///
|
||||
/// # }).dispose();
|
||||
/// ```
|
||||
pub fn use_context<T>(cx: Scope) -> Option<T>
|
||||
where
|
||||
|
||||
@@ -123,11 +123,6 @@ pub trait UntrackedSettableSignal<T> {
|
||||
/// Runs the provided closure with a mutable reference to the current
|
||||
/// value without notifying dependents.
|
||||
fn update_untracked(&self, f: impl FnOnce(&mut T));
|
||||
|
||||
/// Runs the provided closure with a mutable reference to the current
|
||||
/// value without notifying dependents and returns
|
||||
/// the value the closure returned.
|
||||
fn update_returning_untracked<U>(&self, f: impl FnOnce(&mut T) -> U) -> Option<U>;
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
|
||||
@@ -312,10 +312,6 @@ where
|
||||
fn update_untracked(&self, f: impl FnOnce(&mut T)) {
|
||||
self.id.update_with_no_effect(self.runtime, f);
|
||||
}
|
||||
|
||||
fn update_returning_untracked<U>(&self, f: impl FnOnce(&mut T) -> U) -> Option<U> {
|
||||
self.id.update_with_no_effect(self.runtime, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> WriteSignal<T>
|
||||
@@ -343,31 +339,6 @@ where
|
||||
/// # }).dispose();
|
||||
/// ```
|
||||
pub fn update(&self, f: impl FnOnce(&mut T)) {
|
||||
self.id.update(self.runtime, f);
|
||||
}
|
||||
|
||||
/// Applies a function to the current value to mutate it in place
|
||||
/// and notifies subscribers that the signal has changed.
|
||||
/// Forwards the return value of the closure if the closure was called
|
||||
///
|
||||
/// **Note:** `update()` does not auto-memoize, i.e., it will notify subscribers
|
||||
/// even if the value has not actually changed.
|
||||
/// ```
|
||||
/// # use leptos_reactive::*;
|
||||
/// # create_scope(create_runtime(), |cx| {
|
||||
/// let (count, set_count) = create_signal(cx, 0);
|
||||
///
|
||||
/// // notifies subscribers
|
||||
/// let value = set_count.update_returning(|n| { *n = 1; *n * 10 });
|
||||
/// assert_eq!(value, Some(10));
|
||||
/// assert_eq!(count(), 1);
|
||||
///
|
||||
/// let value = set_count.update_returning(|n| { *n += 1; *n * 10 });
|
||||
/// assert_eq!(value, Some(20));
|
||||
/// assert_eq!(count(), 2);
|
||||
/// # }).dispose();
|
||||
/// ```
|
||||
pub fn update_returning<U>(&self, f: impl FnOnce(&mut T) -> U) -> Option<U> {
|
||||
self.id.update(self.runtime, f)
|
||||
}
|
||||
|
||||
@@ -391,7 +362,7 @@ where
|
||||
/// # }).dispose();
|
||||
/// ```
|
||||
pub fn set(&self, new_value: T) {
|
||||
self.id.update(self.runtime, |n| *n = new_value);
|
||||
self.id.update(self.runtime, |n| *n = new_value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,14 +497,10 @@ impl<T> UntrackedGettableSignal<T> for RwSignal<T> {
|
||||
impl<T> UntrackedSettableSignal<T> for RwSignal<T> {
|
||||
fn set_untracked(&self, new_value: T) {
|
||||
self.id
|
||||
.update_with_no_effect(self.runtime, |v| *v = new_value);
|
||||
.update_with_no_effect(self.runtime, |v| *v = new_value)
|
||||
}
|
||||
|
||||
fn update_untracked(&self, f: impl FnOnce(&mut T)) {
|
||||
self.id.update_with_no_effect(self.runtime, f);
|
||||
}
|
||||
|
||||
fn update_returning_untracked<U>(&self, f: impl FnOnce(&mut T) -> U) -> Option<U> {
|
||||
self.id.update_with_no_effect(self.runtime, f)
|
||||
}
|
||||
}
|
||||
@@ -604,29 +571,6 @@ where
|
||||
/// # }).dispose();
|
||||
/// ```
|
||||
pub fn update(&self, f: impl FnOnce(&mut T)) {
|
||||
self.id.update(self.runtime, f);
|
||||
}
|
||||
|
||||
/// Applies a function to the current value to mutate it in place
|
||||
/// and notifies subscribers that the signal has changed.
|
||||
/// Forwards the return value of the closure if the closure was called
|
||||
///
|
||||
/// ```
|
||||
/// # use leptos_reactive::*;
|
||||
/// # create_scope(create_runtime(), |cx| {
|
||||
/// let count = create_rw_signal(cx, 0);
|
||||
///
|
||||
/// // notifies subscribers
|
||||
/// let value = count.update_returning(|n| { *n = 1; *n * 10 });
|
||||
/// assert_eq!(value, Some(10));
|
||||
/// assert_eq!(count(), 1);
|
||||
///
|
||||
/// let value = count.update_returning(|n| { *n += 1; *n * 10 });
|
||||
/// assert_eq!(value, Some(20));
|
||||
/// assert_eq!(count(), 2);
|
||||
/// # }).dispose();
|
||||
/// ```
|
||||
pub fn update_returning<U>(&self, f: impl FnOnce(&mut T) -> U) -> Option<U> {
|
||||
self.id.update(self.runtime, f)
|
||||
}
|
||||
|
||||
@@ -645,7 +589,7 @@ where
|
||||
/// # }).dispose();
|
||||
/// ```
|
||||
pub fn set(&self, value: T) {
|
||||
self.id.update(self.runtime, |n| *n = value);
|
||||
self.id.update(self.runtime, |n| *n = value)
|
||||
}
|
||||
|
||||
/// Returns a read-only handle to the signal.
|
||||
@@ -853,7 +797,7 @@ impl SignalId {
|
||||
with_runtime(runtime, |runtime| self.try_with(runtime, f).unwrap())
|
||||
}
|
||||
|
||||
fn update_value<T, U>(&self, runtime: RuntimeId, f: impl FnOnce(&mut T) -> U) -> Option<U>
|
||||
fn update_value<T>(&self, runtime: RuntimeId, f: impl FnOnce(&mut T)) -> bool
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
@@ -865,29 +809,26 @@ impl SignalId {
|
||||
if let Some(value) = value {
|
||||
let mut value = value.borrow_mut();
|
||||
if let Some(value) = value.downcast_mut::<T>() {
|
||||
Some(f(value))
|
||||
f(value);
|
||||
true
|
||||
} else {
|
||||
debug_warn!(
|
||||
"[Signal::update] failed when downcasting to Signal<{}>",
|
||||
std::any::type_name::<T>()
|
||||
);
|
||||
None
|
||||
false
|
||||
}
|
||||
} else {
|
||||
debug_warn!(
|
||||
"[Signal::update] You’re trying to update a Signal<{}> that has already been disposed of. This is probably either a logic error in a component that creates and disposes of scopes, or a Resource resolving after its scope has been dropped without having been cleaned up.",
|
||||
std::any::type_name::<T>()
|
||||
);
|
||||
None
|
||||
false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn update<T, U>(
|
||||
&self,
|
||||
runtime_id: RuntimeId,
|
||||
f: impl FnOnce(&mut T) -> U,
|
||||
) -> Option<U>
|
||||
pub(crate) fn update<T>(&self, runtime_id: RuntimeId, f: impl FnOnce(&mut T))
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
@@ -896,7 +837,7 @@ impl SignalId {
|
||||
let updated = self.update_value(runtime_id, f);
|
||||
|
||||
// notify subscribers
|
||||
if updated.is_some() {
|
||||
if updated {
|
||||
let subs = {
|
||||
let subs = runtime.signal_subscribers.borrow();
|
||||
let subs = subs.get(*self);
|
||||
@@ -913,20 +854,15 @@ impl SignalId {
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
updated
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn update_with_no_effect<T, U>(
|
||||
&self,
|
||||
runtime: RuntimeId,
|
||||
f: impl FnOnce(&mut T) -> U,
|
||||
) -> Option<U>
|
||||
pub(crate) fn update_with_no_effect<T>(&self, runtime: RuntimeId, f: impl FnOnce(&mut T))
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
// update the value
|
||||
self.update_value(runtime, f)
|
||||
self.update_value(runtime, f);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,9 +36,7 @@ impl SuspenseContext {
|
||||
/// Notifies the suspense context that a new resource is now pending.
|
||||
pub fn increment(&self) {
|
||||
let setter = self.set_pending_resources;
|
||||
queue_microtask(move || {
|
||||
setter.update(|n| *n += 1);
|
||||
});
|
||||
queue_microtask(move || setter.update(|n| *n += 1));
|
||||
}
|
||||
|
||||
/// Notifies the suspense context that a resource has resolved.
|
||||
@@ -49,7 +47,7 @@ impl SuspenseContext {
|
||||
if *n > 0 {
|
||||
*n -= 1
|
||||
}
|
||||
});
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user