瀏覽代碼

feat(config): simplify app urls with custom paths (#1432)

Lucas Fernandes Nogueira 4 年之前
父節點
當前提交
9b35cf7a1b
共有 5 個文件被更改,包括 39 次插入52 次删除
  1. 5 3
      examples/multiwindow/src-tauri/src/main.rs
  2. 1 0
      tauri-utils/Cargo.toml
  3. 19 44
      tauri-utils/src/config.rs
  4. 1 1
      tauri/src/endpoints.rs
  5. 13 4
      tauri/src/runtime/manager.rs

+ 5 - 3
examples/multiwindow/src-tauri/src/main.rs

@@ -13,9 +13,11 @@ fn main() {
         println!("got 'clicked' event on window '{}'", label);
       });
     })
-    .create_window("Rust".to_string(), tauri::WindowUrl::App, |attributes| {
-      attributes.title("Tauri - Rust")
-    })
+    .create_window(
+      "Rust".to_string(),
+      tauri::WindowUrl::App("index.html".into()),
+      |attributes| attributes.title("Tauri - Rust"),
+    )
     .build(tauri::generate_context!())
     .run()
     .expect("failed to run tauri application");

+ 1 - 0
tauri-utils/Cargo.toml

@@ -15,6 +15,7 @@ sysinfo = "0.10"
 thiserror = "1.0.19"
 phf = { version = "0.8", features = ["macros"] }
 zstd = "0.7"
+url = { version = "2.2", features = ["serde"] }
 
 # build feature only
 proc-macro2 = { version = "1.0", optional = true }

+ 19 - 44
tauri-utils/src/config.rs

@@ -1,50 +1,22 @@
-use std::collections::HashMap;
+use std::{collections::HashMap, path::PathBuf};
 
-use serde::{
-  de::{Deserializer, Visitor},
-  Deserialize,
-};
+use serde::Deserialize;
 use serde_json::Value as JsonValue;
+use url::Url;
 
 /// The window webview URL options.
-#[derive(PartialEq, Debug, Clone)]
+#[derive(PartialEq, Debug, Clone, Deserialize)]
+#[serde(untagged)]
 pub enum WindowUrl {
-  /// The app's index URL.
-  App,
-  /// A custom URL.
-  Custom(String),
+  /// An external URL.
+  External(Url),
+  /// An app URL.
+  App(PathBuf),
 }
 
 impl Default for WindowUrl {
   fn default() -> Self {
-    Self::App
-  }
-}
-
-impl<'de> Deserialize<'de> for WindowUrl {
-  fn deserialize<D>(deserializer: D) -> Result<WindowUrl, D::Error>
-  where
-    D: Deserializer<'de>,
-  {
-    struct StringVisitor;
-    impl<'de> Visitor<'de> for StringVisitor {
-      type Value = WindowUrl;
-      fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        formatter.write_str("a string representing an url")
-      }
-
-      fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
-      where
-        E: serde::de::Error,
-      {
-        if v.to_lowercase() == "app" {
-          Ok(WindowUrl::App)
-        } else {
-          Ok(WindowUrl::Custom(v.to_string()))
-        }
-      }
-    }
-    deserializer.deserialize_str(StringVisitor)
+    Self::App("index.html".into())
   }
 }
 
@@ -134,7 +106,7 @@ impl Default for WindowConfig {
   fn default() -> Self {
     Self {
       label: default_window_label(),
-      url: WindowUrl::App,
+      url: WindowUrl::default(),
       x: None,
       y: None,
       width: default_width(),
@@ -578,10 +550,13 @@ mod build {
       let prefix = quote! { ::tauri::api::config::WindowUrl };
 
       tokens.append_all(match self {
-        Self::App => quote! { #prefix::App },
-        Self::Custom(str) => {
-          let str = str_lit(str);
-          quote! { #prefix::Custom(#str) }
+        Self::App(path) => {
+          let path = path.to_string_lossy().to_string();
+          quote! { #prefix::App(::std::path::PathBuf::from(#path)) }
+        }
+        Self::External(url) => {
+          let url = url.as_str();
+          quote! { #prefix::External(#url.parse().unwrap()) }
         }
       })
     }
@@ -821,7 +796,7 @@ mod test {
     let tauri = TauriConfig {
       windows: vec![WindowConfig {
         label: "main".to_string(),
-        url: WindowUrl::App,
+        url: WindowUrl::default(),
         x: None,
         y: None,
         width: 800f64,

+ 1 - 1
tauri/src/endpoints.rs

@@ -31,7 +31,7 @@ impl<T: Serialize> From<T> for InvokeResponse {
 #[serde(tag = "module", content = "message")]
 enum Module {
   Fs(file_system::Cmd),
-  Window(window::Cmd),
+  Window(Box<window::Cmd>),
   Shell(shell::Cmd),
   Event(event::Cmd),
   Internal(internal::Cmd),

+ 13 - 4
tauri/src/runtime/manager.rs

@@ -399,10 +399,19 @@ where
     pending_labels: &[L],
   ) -> crate::Result<PendingWindow<Self>> {
     let (is_local, url) = match &pending.url {
-      WindowUrl::App => (true, self.get_url()),
-      // todo: we should probably warn about how custom urls usually need to be valid urls
-      // e.g. cannot be relative without a base
-      WindowUrl::Custom(url) => (url.len() > 7 && &url[0..8] == "tauri://", url.clone()),
+      WindowUrl::App(path) => {
+        let url = self.get_url();
+        (
+          true,
+          // ignore "index.html" just to simplify the url
+          if path.to_str() != Some("index.html") {
+            format!("{}/{}", url, path.to_string_lossy())
+          } else {
+            url
+          },
+        )
+      }
+      WindowUrl::External(url) => (false, url.to_string()),
     };
 
     let attributes = pending.attributes.clone();