config.rs 1.8 KB

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