Make desktop fullstack work with the CLI (#2862)

* Make desktop fullstack work with the CLI
* Simplify desktop fullstack example
* move the profiles to the workspace
This commit is contained in:
Evan Almloff authored and GitHub committed 2024-08-20 14:57:51 -07:00
1 parent 6a46a66c9a
commit 5a7a91323a
23 files changed
+239 -259

No files matched your search

+1 -1
View File
@@ -49,7 +49,7 @@ fn main() {
// build our application with some routes
let app = Router::new()
// Server side render the application, serve static assets, and register server functions
.serve_dioxus_application(ServeConfig::default(), app)
.serve_dioxus_application(ServeConfig::new().unwrap(), app)
.layer(
axum_session_auth::AuthSessionLayer::<
crate::auth::User,
+1 -15
View File
@@ -4,25 +4,11 @@ version = "0.1.0"
edition = "2021"
publish = false
[lib]
[dependencies]
dioxus = { workspace = true, features = ["launch", "fullstack"] }
axum = { workspace = true, optional = true }
tokio = { workspace = true, features = ["full"], optional = true }
serde = "1.0.159"
[features]
default = []
server = ["axum", "tokio", "dioxus/axum"]
server = ["dioxus/server"]
desktop = ["dioxus/desktop"]
[[bin]]
name = "client"
path = "src/client.rs"
required-features = ["desktop"]
[[bin]]
name = "server"
path = "src/server.rs"
required-features = ["server"]
@@ -1,15 +0,0 @@
// Run with:
// ```bash
// cargo run --bin client --features desktop
// ```
use fullstack_desktop_example::*;
fn main() {
// Set the url of the server where server functions are hosted.
#[cfg(not(feature = "server"))]
dioxus::fullstack::prelude::server_fn::client::set_server_url("http://127.0.0.1:8080");
#[cfg(feature = "desktop")]
dioxus::prelude::launch_desktop(app)
}
@@ -1,36 +0,0 @@
#![allow(non_snake_case)]
use dioxus::prelude::*;
pub fn app() -> Element {
let mut count = use_signal(|| 0);
let mut text = use_signal(|| "...".to_string());
rsx! {
h1 { "High-Five counter: {count}" }
button { onclick: move |_| count += 1, "Up high!" }
button { onclick: move |_| count -= 1, "Down low!" }
button {
onclick: move |_| async move {
if let Ok(data) = get_server_data().await {
println!("Client received: {}", data);
text.set(data.clone());
post_server_data(data).await.unwrap();
}
},
"Run a server function"
}
"Server said: {text}"
}
}
#[server(PostServerData)]
async fn post_server_data(data: String) -> Result<(), ServerFnError> {
println!("Server received: {}", data);
Ok(())
}
#[server(GetServerData)]
async fn get_server_data() -> Result<String, ServerFnError> {
Ok("Hello from the server!".to_string())
}
@@ -1,42 +1,13 @@
#![allow(non_snake_case)]
use dioxus::prelude::*;
/// Run with `cargo run --features desktop`
#[cfg(feature = "desktop")]
fn main() {
// Set the url of the server where server functions are hosted.
#[cfg(not(feature = "server"))]
dioxus::fullstack::prelude::server_fn::client::set_server_url("http://127.0.0.1:8080");
// And then launch the app
dioxus::prelude::launch_desktop(app);
launch(app);
}
/// Run with `cargo run --features server`
#[cfg(all(feature = "server", not(feature = "desktop")))]
#[tokio::main]
async fn main() {
use server_fn::axum::register_explicit;
let listener = tokio::net::TcpListener::bind("127.0.0.01:8080")
.await
.unwrap();
register_explicit::<PostServerData>();
register_explicit::<GetServerData>();
axum::serve(
listener,
axum::Router::new()
.register_server_functions()
.into_make_service(),
)
.await
.unwrap();
}
#[cfg(all(not(feature = "desktop"), not(feature = "server")))]
fn main() {}
pub fn app() -> Element {
let mut count = use_signal(|| 0);
let mut text = use_signal(|| "...".to_string());
@@ -1,27 +0,0 @@
// Run with:
// ```bash
// cargo run --bin server --features server
// ```
use dioxus::prelude::*;
use fullstack_desktop_example::*;
use server_fn::axum::register_explicit;
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("127.0.0.01:8080")
.await
.unwrap();
register_explicit::<PostServerData>();
register_explicit::<GetServerData>();
axum::serve(
listener,
axum::Router::new()
.register_server_functions()
.into_make_service(),
)
.await
.unwrap();
}
+8 -10
View File
@@ -21,7 +21,7 @@
//! listener,
//! axum::Router::new()
//! // Server side render the application, serve static assets, and register server functions
//! .serve_dioxus_application(ServeConfig::default(), app)
//! .serve_dioxus_application(ServeConfig::new().unwrap(), app)
//! .into_make_service(),
//! )
//! .await
@@ -150,7 +150,7 @@ pub trait DioxusRouterExt<S> {
/// let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
/// let router = axum::Router::new()
/// // Server side render the application, serve static assets, and register server functions
/// .serve_dioxus_application(ServeConfig::default(), app)
/// .serve_dioxus_application(ServeConfig::new().unwrap(), app)
/// .into_make_service();
/// let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
/// axum::serve(listener, router).await.unwrap();
@@ -252,11 +252,8 @@ where
let server = self.serve_static_assets().register_server_functions();
server.fallback(
get(render_handler).with_state(
RenderHandleState::new(app)
.with_config(cfg)
.with_ssr_state(ssr_state),
),
get(render_handler)
.with_state(RenderHandleState::new(cfg, app).with_ssr_state(ssr_state)),
)
}
}
@@ -281,9 +278,9 @@ pub struct RenderHandleState {
impl RenderHandleState {
/// Create a new [`RenderHandleState`]
pub fn new(root: fn() -> Element) -> Self {
pub fn new(config: ServeConfig, root: fn() -> Element) -> Self {
Self {
config: ServeConfig::default(),
config,
build_virtual_dom: Arc::new(move || VirtualDom::new(root)),
ssr_state: Default::default(),
}
@@ -291,10 +288,11 @@ impl RenderHandleState {
/// Create a new [`RenderHandleState`] with a custom [`VirtualDom`] factory. This method can be used to pass context into the root component of your application.
pub fn new_with_virtual_dom_factory(
config: ServeConfig,
build_virtual_dom: impl Fn() -> VirtualDom + Send + Sync + 'static,
) -> Self {
Self {
config: ServeConfig::default(),
config,
build_virtual_dom: Arc::new(build_virtual_dom),
ssr_state: Default::default(),
}
+18 -12
View File
@@ -146,24 +146,30 @@ async fn launch_server(
{
use crate::axum_adapter::DioxusRouterExt;
let router = axum::Router::new().register_server_functions_with_context(context_providers);
#[allow(unused_mut)]
let mut router =
axum::Router::new().register_server_functions_with_context(context_providers);
#[cfg(not(any(feature = "desktop", feature = "mobile")))]
let router = {
{
use crate::prelude::RenderHandleState;
use crate::prelude::SSRState;
let cfg = platform_config.server_cfg.build();
match platform_config.server_cfg.build() {
Ok(cfg) => {
router = router.serve_static_assets();
let mut router = router.serve_static_assets();
router.fallback(
axum::routing::get(crate::axum_adapter::render_handler).with_state(
RenderHandleState::new_with_virtual_dom_factory(build_virtual_dom)
.with_config(cfg),
),
)
};
router = router.fallback(
axum::routing::get(crate::axum_adapter::render_handler).with_state(
RenderHandleState::new_with_virtual_dom_factory(cfg, build_virtual_dom),
),
);
}
Err(err) => {
tracing::trace!("Failed to create render handler. This is expected if you are only using fullstack for desktop/mobile server functions: {}", err);
}
}
}
let router = router.into_make_service();
let listener = tokio::net::TcpListener::bind(address).await.unwrap();
-1
View File
@@ -418,7 +418,6 @@ impl SSRState {
}
/// The template that wraps the body of the HTML for a fullstack page. This template contains the data needed to hydrate server functions that were run on the server.
#[derive(Default)]
pub struct FullstackHTMLTemplate {
cfg: ServeConfig,
}
+27 -21
View File
@@ -50,7 +50,7 @@ impl ServeConfigBuilder {
}
/// Build the ServeConfig
pub fn build(self) -> ServeConfig {
pub fn build(self) -> Result<ServeConfig, UnableToLoadIndex> {
// The CLI always bundles static assets into the exe/public directory
let public_path = public_path();
@@ -61,16 +61,17 @@ impl ServeConfigBuilder {
let root_id = self.root_id.unwrap_or("main");
let index_html = self
.index_html
.unwrap_or_else(|| load_index_path(index_path));
let index_html = match self.index_html {
Some(index) => index,
None => load_index_path(index_path)?,
};
let index = load_index_html(index_html, root_id);
ServeConfig {
Ok(ServeConfig {
index,
incremental: self.incremental,
}
})
}
}
@@ -84,13 +85,25 @@ pub(crate) fn public_path() -> PathBuf {
.join("public")
}
fn load_index_path(path: PathBuf) -> String {
let mut file = File::open(&path).unwrap_or_else(|_| panic!("Failed to find index.html. Make sure the index_path is set correctly and the WASM application has been built. Tried to open file at path: {path:?}"));
/// An error that can occur when loading the index.html file
#[derive(Debug)]
pub struct UnableToLoadIndex(PathBuf);
impl std::fmt::Display for UnableToLoadIndex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Failed to find index.html. Make sure the index_path is set correctly and the WASM application has been built. Tried to open file at path: {:?}", self.0)
}
}
impl std::error::Error for UnableToLoadIndex {}
fn load_index_path(path: PathBuf) -> Result<String, UnableToLoadIndex> {
let mut file = File::open(&path).map_err(|_| UnableToLoadIndex(path))?;
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("Failed to read index.html");
contents
Ok(contents)
}
fn load_index_html(contents: String, root_id: &'static str) -> IndexHtml {
@@ -156,21 +169,14 @@ pub struct ServeConfig {
pub(crate) incremental: Option<dioxus_ssr::incremental::IncrementalRendererConfig>,
}
impl Default for ServeConfig {
fn default() -> Self {
Self::builder().build()
}
}
impl ServeConfig {
/// Create a new ServeConfig
pub fn new() -> Result<Self, UnableToLoadIndex> {
ServeConfigBuilder::new().build()
}
/// Create a new builder for a ServeConfig
pub fn builder() -> ServeConfigBuilder {
ServeConfigBuilder::new()
}
}
impl From<ServeConfigBuilder> for ServeConfig {
fn from(builder: ServeConfigBuilder) -> Self {
builder.build()
}
}