dioxus_liveview/
config.rs

1use dioxus_core::{LaunchConfig, VirtualDom};
2
3use crate::LiveviewRouter;
4
5pub(crate) fn app_title() -> String {
6    dioxus_cli_config::app_title().unwrap_or_else(|| "Dioxus Liveview App".to_string())
7}
8
9/// A configuration for the LiveView server.
10pub struct Config<R: LiveviewRouter> {
11    router: R,
12    address: std::net::SocketAddr,
13    route: String,
14}
15
16impl<R: LiveviewRouter + 'static> LaunchConfig for Config<R> {}
17
18impl<R: LiveviewRouter> Default for Config<R> {
19    fn default() -> Self {
20        Self {
21            address: dioxus_cli_config::fullstack_address_or_localhost(),
22            router: R::create_default_liveview_router(),
23            route: "/".to_string(),
24        }
25    }
26}
27
28impl<R: LiveviewRouter> Config<R> {
29    /// Set the route to use for the LiveView server.
30    pub fn route(mut self, route: impl Into<String>) -> Self {
31        self.route = route.into();
32        self
33    }
34
35    /// Create a new configuration for the LiveView server.
36    pub fn with_app(mut self, app: fn() -> dioxus_core::prelude::Element) -> Self {
37        self.router = self.router.with_app(&self.route, app);
38        self
39    }
40
41    /// Create a new configuration for the LiveView server.
42    pub fn with_virtual_dom(
43        mut self,
44        virtual_dom: impl Fn() -> VirtualDom + Send + Sync + 'static,
45    ) -> Self {
46        self.router = self.router.with_virtual_dom(&self.route, virtual_dom);
47        self
48    }
49
50    /// Set the address to listen on.
51    pub fn address(mut self, address: impl Into<std::net::SocketAddr>) -> Self {
52        self.address = address.into();
53        self
54    }
55
56    /// Launch the LiveView server.
57    pub async fn launch(self) {
58        println!("{} started on http://{}", app_title(), self.address);
59        self.router.start(self.address).await
60    }
61}