소스 검색

refactor(api): reorganize and rename methods (#1277)

Lucas Fernandes Nogueira 4 년 전
부모
커밋
35c75b4197
6개의 변경된 파일88개의 추가작업 그리고 40개의 파일을 삭제
  1. 70 33
      api/src/window.ts
  2. 2 0
      cli/core/config_definition.rs
  3. 1 1
      tauri-api/src/cli.rs
  4. 0 0
      tauri/examples/multiwindow/dist/__tauri.js
  5. 14 6
      tauri/examples/multiwindow/dist/index.html
  6. 1 0
      tauri/src/app/utils.rs

+ 70 - 33
api/src/window.ts

@@ -14,18 +14,24 @@ declare global {
   }
 }
 
-function getCurrentWindow(): WindowDef {
-  return window.__TAURI__.__currentWindow
+function getCurrent(): WebviewWindowHandle {
+  return new WebviewWindowHandle(window.__TAURI__.__currentWindow.label)
 }
 
-function getWindows(): WindowDef[] {
+function getAll(): WindowDef[] {
   return window.__TAURI__.__windows
 }
 
-class TauriWindow {
+// events that are emitted right here instead of by the created webview
+const localTauriEvents = ['tauri://created', 'tauri://error']
+
+class WebviewWindowHandle {
   label: string
+  listeners: { [key: string]: Array<EventCallback<any>> }
+
   constructor(label: string) {
     this.label = label
+    this.listeners = {}
   }
 
   /**
@@ -34,10 +40,10 @@ class TauriWindow {
    * @param event the event name
    * @param handler the event handler callback
    */
-  async listen<T>(
-    event: string,
-    handler: EventCallback<T>
-  ): Promise<void> {
+  async listen<T>(event: string, handler: EventCallback<T>): Promise<void> {
+    if (this._handleTauriEvent(event, handler)) {
+      return Promise.resolve()
+    }
     return listen(event, handler)
   }
 
@@ -47,10 +53,10 @@ class TauriWindow {
    * @param event the event name
    * @param handler the event handler callback
    */
-  async once<T>(
-    event: string,
-    handler: EventCallback<T>
-  ): Promise<void> {
+  async once<T>(event: string, handler: EventCallback<T>): Promise<void> {
+    if (this._handleTauriEvent(event, handler)) {
+      return Promise.resolve()
+    }
     return once(event, handler)
   }
 
@@ -61,16 +67,61 @@ class TauriWindow {
    * @param [payload] the event payload
    */
   async emit(event: string, payload?: string): Promise<void> {
+    if (localTauriEvents.includes(event)) {
+      // eslint-disable-next-line
+      for (const handler of this.listeners[event] || []) {
+        handler({ type: event, payload })
+      }
+      return Promise.resolve()
+    }
     return emit(event, this.label, payload)
   }
+
+  _handleTauriEvent<T>(event: string, handler: EventCallback<T>): boolean {
+    if (localTauriEvents.includes(event)) {
+      if (!(event in this.listeners)) {
+        // eslint-disable-next-line
+        this.listeners[event] = [handler]
+      } else {
+        // eslint-disable-next-line
+        this.listeners[event].push(handler)
+      }
+      return true
+    }
+    return false
+  }
+
+  _emitTauriEvent(event: string): void { }
 }
 
-function getTauriWindow(
-  label: string = getCurrentWindow().label
-): TauriWindow | null {
-  if (getWindows().some((w) => w.label === label)) {
-    return new TauriWindow(label)
-  } else {
+class WebviewWindow extends WebviewWindowHandle {
+  constructor(label: string, options: WindowOptions = {}) {
+    super(label)
+    invoke({
+      __tauriModule: 'Window',
+      message: {
+        cmd: 'createWebview',
+        options: {
+          label,
+          ...options
+        }
+      }
+    })
+      .then(async () => this.emit('tauri://created'))
+      .catch(async (e) => this.emit('tauri://error', e))
+  }
+
+  /**
+   * Gets the WebviewWindow handle for the webview associated with the given label.
+   *
+   * @param {string} label the webview window label.
+   *
+   * @return {WebviewWindowHandle} the handle to communicate with the webview or null if the webview doesn't exist
+   */
+  static getByLabel(label: string): WebviewWindowHandle | null {
+    if (getAll().some((w) => w.label === label)) {
+      return new WebviewWindowHandle(label)
+    }
     return null
   }
 }
@@ -402,18 +453,4 @@ export interface WindowOptions {
   alwaysOnTop?: boolean
 }
 
-async function createWindow(label: string, options: WindowOptions = {}): Promise<TauriWindow> {
-  await invoke({
-    __tauriModule: 'Window',
-    message: {
-      cmd: 'createWebview',
-      options: {
-        label,
-        ...options
-      }
-    }
-  })
-  return new TauriWindow(label)
-}
-
-export { TauriWindow, getTauriWindow, getCurrentWindow, getWindows, manager, createWindow }
+export { WebviewWindow, getCurrent, getAll, manager }

+ 2 - 0
cli/core/config_definition.rs

@@ -1,3 +1,5 @@
+#![allow(clippy::field_reassign_with_default)]
+
 use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};
 use serde_json::Value as JsonValue;

+ 1 - 1
tauri-api/src/cli.rs

@@ -58,7 +58,7 @@ pub fn get_matches(config: &Config) -> crate::Result<Matches> {
     .tauri
     .cli
     .as_ref()
-    .ok_or_else(|| crate::Error::CliNotConfigured)?;
+    .ok_or(crate::Error::CliNotConfigured)?;
 
   let about = cli
     .description()

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 0 - 0
tauri/examples/multiwindow/dist/__tauri.js


+ 14 - 6
tauri/examples/multiwindow/dist/index.html

@@ -7,7 +7,9 @@
   <div id="response"></div>
 
   <script>
-    var windowLabel = window.__TAURI__.window.getCurrentWindow().label;
+    var WebviewWindow = window.__TAURI__.window.WebviewWindow
+    var thisTauriWindow = window.__TAURI__.window.getCurrent();
+    var windowLabel = thisTauriWindow.label;
     var windowLabelContainer = document.getElementById("window-label");
     windowLabelContainer.innerHTML =
       "This is the " + windowLabel + " window.";
@@ -15,7 +17,7 @@
     var container = document.getElementById("container");
 
     function createWindowMessageBtn(label) {
-      var tauriWindow = window.__TAURI__.window.getTauriWindow(label)
+      var tauriWindow = WebviewWindow.getByLabel(label)
       var button = document.createElement("button");
       button.innerHTML = "Send message to " + label;
       button.addEventListener("click", function () {
@@ -33,7 +35,6 @@
     })
 
     var responseContainer = document.getElementById("response");
-    var thisTauriWindow = window.__TAURI__.window.getTauriWindow()
     // listener tied to this window
     thisTauriWindow.listen("clicked", function (event) {
       responseContainer.innerHTML += "Got " + JSON.stringify(event) + " on window listener<br><br>";
@@ -42,7 +43,13 @@
     var createWindowButton = document.createElement("button");
     createWindowButton.innerHTML = "Create window";
     createWindowButton.addEventListener("click", function () {
-      window.__TAURI__.window.createWindow(Math.random().toString());
+      var webviewWindow = new WebviewWindow(Math.random().toString());
+      webviewWindow.once('tauri://created', function () {
+        responseContainer.innerHTML += "Created new webview"
+      })
+      webviewWindow.once('tauri://error', function () {
+        responseContainer.innerHTML += "Error creating new webview"
+      })
     });
     container.appendChild(createWindowButton);
 
@@ -54,8 +61,9 @@
     });
     container.appendChild(globalMessageButton);
 
-    for (var index in window.__TAURI__.window.getWindows()) {
-      var label = window.__TAURI__.window.getWindows()[index].label;
+    var allWindows = window.__TAURI__.window.getAll()
+    for (var index in allWindows) {
+      var label = allWindows[index].label;
       if (label === windowLabel) {
         continue;
       }

+ 1 - 0
tauri/src/app/utils.rs

@@ -38,6 +38,7 @@ struct Message {
 
 // setup content for dev-server
 #[cfg(dev)]
+#[allow(clippy::unnecessary_wraps)]
 pub(super) fn get_url(context: &Context) -> crate::Result<String> {
   let config = &context.config;
   if config.build.dev_path.starts_with("http") {

이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.