Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Partial hydration #1758

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ members = [
"packages/fullstack",
"packages/server-macro",
"packages/fullstack/examples/axum-hello-world",
"packages/fullstack/examples/axum-islands",
"packages/fullstack/examples/axum-router",
"packages/fullstack/examples/axum-desktop",
"packages/fullstack/examples/axum-auth",
Expand Down
2 changes: 2 additions & 0 deletions packages/core-macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ trybuild = "1.0"

[features]
default = []
islands = []
ssr = []
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,38 @@ fn get_out_comp_fn(orig_comp_fn: &ItemFn, cx_pat: &Pat) -> ItemFn {
#[derive(Clone)]
pub struct ComponentDeserializerArgs {
pub case_check: bool,
pub island: bool,
}

/// The output fields and [`ToTokens`] implementation for the [`crate::component`] macro.
#[derive(Clone)]
pub struct ComponentDeserializerOutput {
pub comp_fn: ItemFn,
pub props_struct: Option<ItemStruct>,
pub island: bool,
}

impl ToTokens for ComponentDeserializerOutput {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let comp_fn = &self.comp_fn;
let props_struct = &self.props_struct;

if !self.island && cfg!(all(feature = "islands", not(feature = "ssr"))) {
// if this is not an island, we snip the body of the component function and replace it with unreachable!()
let sig = &comp_fn.sig;
let attrs = &comp_fn.attrs;
let vis = &comp_fn.vis;
tokens.append_all(quote! {
#props_struct

#[allow(non_snake_case)]
#(#attrs)*
#vis #sig {
unreachable!()
}
});
}

tokens.append_all(quote! {
#props_struct
#[allow(non_snake_case)]
Expand All @@ -75,11 +93,17 @@ impl DeserializerArgs<ComponentDeserializerOutput> for ComponentDeserializerArgs
return Err(Error::new(ident.span(), COMPONENT_ARG_CASE_CHECK_ERROR));
}

if component_body.has_extra_args {
let mut output = if component_body.has_extra_args {
Self::deserialize_with_props(component_body)
} else {
Ok(Self::deserialize_no_props(component_body))
};

if let Ok(output) = &mut output {
output.island = self.island;
}

output
}
}

Expand All @@ -97,6 +121,7 @@ impl ComponentDeserializerArgs {
ComponentDeserializerOutput {
comp_fn,
props_struct: None,
island: false
}
}

Expand Down Expand Up @@ -132,6 +157,7 @@ impl ComponentDeserializerArgs {
Ok(ComponentDeserializerOutput {
comp_fn,
props_struct: Some(props_struct),
island: false
})
}
}
Expand Down
17 changes: 11 additions & 6 deletions packages/core-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ pub fn inline_props(_args: TokenStream, s: TokenStream) -> TokenStream {
}

pub(crate) const COMPONENT_ARG_CASE_CHECK_OFF: &str = "no_case_check";
pub(crate) const COMPONENT_ARG_ISLAND: &str = "island";

/// Streamlines component creation.
/// This is the recommended way of creating components,
Expand Down Expand Up @@ -183,18 +184,22 @@ pub(crate) const COMPONENT_ARG_CASE_CHECK_OFF: &str = "no_case_check";
#[proc_macro_attribute]
pub fn component(args: TokenStream, input: TokenStream) -> TokenStream {
let component_body = parse_macro_input!(input as ComponentBody);
let case_check = match Punctuated::<Path, Token![,]>::parse_terminated.parse(args) {
let mut case_check = false;
let mut island = false;
match Punctuated::<Path, Token![,]>::parse_terminated.parse(args) {
Err(e) => return e.to_compile_error().into(),
Ok(args) => {
if let Some(first) = args.first() {
!first.is_ident(COMPONENT_ARG_CASE_CHECK_OFF)
} else {
true
for arg in args {
if arg.is_ident(COMPONENT_ARG_CASE_CHECK_OFF) {
case_check = true
} else if arg.is_ident(COMPONENT_ARG_ISLAND) {
island = true
}
}
}
};

match component_body.deserialize(ComponentDeserializerArgs { case_check }) {
match component_body.deserialize(ComponentDeserializerArgs { case_check, island }) {
Err(e) => e.to_compile_error().into(),
Ok(output) => output.to_token_stream().into(),
}
Expand Down
6 changes: 5 additions & 1 deletion packages/fullstack/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ dioxus-ssr = { workspace = true, optional = true }
hyper = { version = "0.14.25", optional = true }
http = { version = "0.2.9", optional = true }

# Islands
dioxus-core-macro = { workspace = true, optional = true }

# Web Integration
dioxus-web = { workspace = true, features = ["hydrate"], optional = true }

Expand Down Expand Up @@ -79,9 +82,10 @@ desktop = ["dioxus-desktop"]
warp = ["dep:warp", "ssr"]
axum = ["dep:axum", "tower-http", "ssr"]
salvo = ["dep:salvo", "ssr"]
ssr = ["server_fn/ssr", "dioxus_server_macro/ssr", "tokio", "tokio-util", "dioxus-ssr", "tower", "hyper", "http", "http-body", "dioxus-router/ssr", "tokio-stream"]
ssr = ["server_fn/ssr", "dioxus_server_macro/ssr", "tokio", "tokio-util", "dioxus-ssr", "tower", "hyper", "http", "http-body", "dioxus-router/ssr", "tokio-stream", "dioxus-core-macro?/ssr"]
default-tls = ["server_fn/default-tls"]
rustls = ["server_fn/rustls"]
islands = ["dioxus-core-macro"]

[dev-dependencies]
dioxus-fullstack = { path = ".", features = ["router"] }
4 changes: 4 additions & 0 deletions packages/fullstack/examples/axum-islands/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/.dioxus
dist
target
static
23 changes: 23 additions & 0 deletions packages/fullstack/examples/axum-islands/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "axum-islands"
version = "0.1.0"
edition = "2021"
publish = false

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
dioxus = { workspace = true }
dioxus-fullstack = { features = ["islands"], workspace = true }
axum = { version = "0.6.12", optional = true }
serde = "1.0.159"
simple_logger = "4.2.0"
tracing-wasm = "0.2.1"
tracing.workspace = true
tracing-subscriber = "0.3.17"
reqwest = "0.11.18"

[features]
default = []
ssr = ["axum", "dioxus-fullstack/axum"]
web = ["dioxus-fullstack/web"]
39 changes: 39 additions & 0 deletions packages/fullstack/examples/axum-islands/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//! Run with:
//!
//! ```sh
//! dx build --features web --release
//! cargo run --features ssr --release
//! ```

#![allow(non_snake_case, unused)]
use dioxus::prelude::*;
use dioxus_fullstack::{
launch::{self, LaunchBuilder},
prelude::*,
};
use serde::{Deserialize, Serialize};

#[component]
fn app(cx: Scope) -> Element {
let text =
use_server_future(cx, (), |()| async move { get_server_data().await.unwrap() })?.value();

#[cfg(not(feature = "ssr"))]
panic!("This component will only ever be rendered on the server!");

cx.render(rsx! { Child { state: text.clone() } })
}

#[component(island)]
fn Child(cx: Scope, state: String) -> Element {
cx.render(rsx! {"State: {state}"})
}

#[server]
async fn get_server_data() -> Result<String, ServerFnError> {
Ok(reqwest::get("https://httpbin.org/ip").await?.text().await?)
}

fn main() {
LaunchBuilder::new(app).launch()
}