mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-27 16:54:41 -05:00
Compare commits
2 Commits
cleanup-te
...
context-do
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ed0bc5abf | ||
|
|
d40c48ab9b |
@@ -18,6 +18,7 @@ members = [
|
||||
"router",
|
||||
|
||||
# examples
|
||||
"examples/cloudflare-worker",
|
||||
"examples/counter",
|
||||
"examples/counter-isomorphic",
|
||||
"examples/counters",
|
||||
|
||||
13
examples/cloudflare-worker/.editorconfig
Normal file
13
examples/cloudflare-worker/.editorconfig
Normal file
@@ -0,0 +1,13 @@
|
||||
# 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
Normal file
10
examples/cloudflare-worker/.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
.DS_Store
|
||||
/node_modules
|
||||
|
||||
**/*.rs.bk
|
||||
wasm-pack.log
|
||||
|
||||
build/
|
||||
/target
|
||||
/dist
|
||||
pkg
|
||||
20
examples/cloudflare-worker/Cargo.toml
Normal file
20
examples/cloudflare-worker/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
[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"]
|
||||
19
examples/cloudflare-worker/README.md
Normal file
19
examples/cloudflare-worker/README.md
Normal file
@@ -0,0 +1,19 @@
|
||||
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.
|
||||
11
examples/cloudflare-worker/package.json
Normal file
11
examples/cloudflare-worker/package.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"deploy": "wrangler publish",
|
||||
"dev": "wrangler dev --local"
|
||||
},
|
||||
"devDependencies": {
|
||||
"wrangler": "^2.0.0"
|
||||
}
|
||||
}
|
||||
116
examples/cloudflare-worker/src/lib.rs
Normal file
116
examples/cloudflare-worker/src/lib.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
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>"#
|
||||
)
|
||||
}
|
||||
9
examples/cloudflare-worker/wrangler.toml
Normal file
9
examples/cloudflare-worker/wrangler.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
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"
|
||||
@@ -33,6 +33,7 @@ cfg-if = "1.0.0"
|
||||
rmp-serde = "1.1.1"
|
||||
|
||||
[dev-dependencies]
|
||||
leptos = "0.0"
|
||||
tokio-test = "0.4"
|
||||
|
||||
[features]
|
||||
|
||||
@@ -13,35 +13,37 @@ use crate::{runtime::with_runtime, Scope};
|
||||
/// arguments to a function or properties of a component.
|
||||
///
|
||||
/// ```
|
||||
/// # 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>)
|
||||
/// 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!()
|
||||
/// }
|
||||
///
|
||||
/// 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
|
||||
@@ -65,35 +67,37 @@ where
|
||||
/// arguments to a function or properties of a component.
|
||||
///
|
||||
/// ```
|
||||
/// # 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>)
|
||||
/// 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!()
|
||||
/// }
|
||||
///
|
||||
/// 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
|
||||
|
||||
Reference in New Issue
Block a user