Skip to content
Open
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
31 changes: 31 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,4 @@ chrono = "0.4"
thiserror = "2.0"
bincode = { version = "2.0.0-rc.3", features = ["serde"] }
reqwest = "0.12"
axum = "0.8"
14 changes: 8 additions & 6 deletions examples/function_router/src/content.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use serde::{Deserialize, Serialize};

use crate::generator::{Generated, Generator};

#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Author {
pub seed: u32,
pub name: String,
Expand All @@ -22,7 +24,7 @@ impl Generated for Author {
}
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PostMeta {
pub seed: u32,
pub title: String,
Expand All @@ -48,7 +50,7 @@ impl Generated for PostMeta {
}
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Post {
pub meta: PostMeta,
pub content: Vec<PostPart>,
Expand All @@ -68,7 +70,7 @@ impl Generated for Post {
}
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum PostPart {
Section(Section),
Quote(Quote),
Expand All @@ -87,7 +89,7 @@ impl Generated for PostPart {
}
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Section {
pub title: String,
pub paragraphs: Vec<String>,
Expand All @@ -112,7 +114,7 @@ impl Generated for Section {
}
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Quote {
pub author: Author,
pub content: String,
Expand Down
6 changes: 3 additions & 3 deletions examples/function_router/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
// Hence, it may not yield the same value on the client and server side.

mod app;
mod components;
mod content;
pub mod components;
pub mod content;
mod generator;
pub mod imagegen;
mod pages;
pub mod pages;

pub use app::*;
pub use content::*;
Expand Down
15 changes: 9 additions & 6 deletions examples/ssr_router/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ name = "ssr_router"
version = "0.1.0"
edition = "2021"

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

[[bin]]
name = "ssr_router_hydrate"
required-features = ["hydration"]
Expand All @@ -15,8 +13,14 @@ required-features = ["ssr"]

[dependencies]
yew = { path = "../../packages/yew" }
yew-link = { path = "../../packages/yew-link" }
yew-router = { path = "../../packages/yew-router" }
function_router = { path = "../function_router" }
log = "0.4"
rand = { workspace = true }
getrandom = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
futures = { workspace = true, features = ["std"] }
hyper-util = "0.1.20"

Expand All @@ -25,9 +29,8 @@ wasm-bindgen-futures.workspace = true
wasm-logger.workspace = true

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
yew-router = { path = "../../packages/yew-router" }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "net", "fs"] }
axum = "0.8"
axum = { workspace = true }
tower = { version = "0.5", features = ["make"] }
tower-http = { version = "0.6", features = ["fs"] }
env_logger = "0.11"
Expand All @@ -38,5 +41,5 @@ hyper = { version = "1.4", features = ["server", "http1"] }
jemallocator = "0.5"

[features]
ssr = ["yew/ssr"]
hydration = ["yew/hydration"]
ssr = ["yew/ssr", "yew-link/ssr", "yew-link/axum"]
hydration = ["yew/hydration", "yew-link/hydration"]
2 changes: 1 addition & 1 deletion examples/ssr_router/src/bin/ssr_router_hydrate.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use function_router::App;
use ssr_router::App;

fn main() {
#[cfg(target_arch = "wasm32")]
Expand Down
59 changes: 41 additions & 18 deletions examples/ssr_router/src/bin/ssr_router_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,20 @@ use axum::extract::{Query, Request, State};
use axum::handler::HandlerWithoutStateExt;
use axum::http::Uri;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::routing::{get, post};
use axum::Router;
use clap::Parser;
use function_router::{route_meta, Route, ServerApp, ServerAppProps};
use function_router::{route_meta, Route};
use futures::stream::{self, StreamExt};
use hyper::body::Incoming;
use hyper_util::rt::TokioIo;
use hyper_util::server;
use ssr_router::{LinkedAuthor, LinkedPost, LinkedPostMeta, ServerApp, ServerAppProps};
use tokio::net::TcpListener;
use tower::Service;
use tower_http::services::ServeDir;
use yew::platform::Runtime;
use yew_link::{linked_state_handler, Resolver, ResolverProp};
use yew_router::prelude::Routable;

// We use jemalloc as it produces better performance.
Expand All @@ -45,25 +47,36 @@ fn head_tags_for(path: &str) -> String {
)
}

#[derive(Clone)]
struct AppState {
index_html_before: String,
index_html_after: String,
resolver: ResolverProp,
}

async fn render(
url: Uri,
Query(queries): Query<HashMap<String, String>>,
State((index_html_before, index_html_after)): State<(String, String)>,
State(state): State<AppState>,
) -> impl IntoResponse {
let path = url.path().to_owned();

// Inject route-specific <head> tags before </head>, outside of Yew rendering.
let before = index_html_before.replace("</head>", &format!("{}</head>", head_tags_for(&path)));
let before = state
.index_html_before
.replace("</head>", &format!("{}</head>", head_tags_for(&path)));
let resolver = state.resolver.clone();

let renderer = yew::ServerRenderer::<ServerApp>::with_props(move || ServerAppProps {
url: path.into(),
queries,
resolver,
});

Body::from_stream(
stream::once(async move { before })
.chain(renderer.render_stream())
.chain(stream::once(async move { index_html_after }))
.chain(stream::once(async move { state.index_html_after }))
.map(Result::<_, Infallible>::Ok),
)
}
Expand Down Expand Up @@ -93,33 +106,43 @@ where
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let exec = Executor::default();

env_logger::init();

let opts = Opt::parse();

let resolver_prop: ResolverProp = Resolver::new()
.register_linked::<LinkedPost>(())
.register_linked::<LinkedAuthor>(())
.register_linked::<LinkedPostMeta>(())
.into();
let arc_resolver = resolver_prop.0.clone();

let index_html_s = tokio::fs::read_to_string(opts.dir.join("index.html"))
.await
.expect("failed to read index.html");

let (index_html_before, index_html_after) = index_html_s.split_once("<body>").unwrap();
let mut index_html_before = index_html_before.to_owned();
index_html_before.push_str("<body>");

let index_html_after = index_html_after.to_owned();

let app = Router::new().fallback_service(
ServeDir::new(opts.dir)
.append_index_html_on_directories(false)
.fallback(
get(render)
.with_state((index_html_before.clone(), index_html_after.clone()))
.into_service(),
),
);
let app_state = AppState {
index_html_before,
index_html_after,
resolver: resolver_prop,
};

let app = Router::new()
.route(
"/api/link",
post(linked_state_handler).with_state(arc_resolver),
)
.fallback_service(
ServeDir::new(opts.dir)
.append_index_html_on_directories(false)
.fallback(get(render).with_state(app_state).into_service()),
);

let addr: SocketAddr = ([0, 0, 0, 0], 8080).into();

println!("You can view the website at: http://localhost:8080/");

let listener = TcpListener::bind(addr).await?;
Expand Down
Loading
Loading