Browse Source

feat(examples): add state example (#1687)

* feat(examples): add state example

* clippy
Lucas Fernandes Nogueira 4 năm trước cách đây
mục cha
commit
2122ae61fa

+ 1 - 0
Cargo.toml

@@ -13,6 +13,7 @@ members = [
   "examples/multiwindow/src-tauri",
   "examples/commands/src-tauri",
   "examples/splashscreen/src-tauri/",
+  "examples/state/src-tauri/",
   # used to build updater artifacts
   "examples/updater/src-tauri",
 ]

+ 2 - 2
examples/commands/package.json

@@ -1,7 +1,7 @@
 {
-  "name": "commands",
+  "name": "state",
   "version": "1.0.0",
   "scripts": {
     "tauri": "node ../../tooling/cli.js/bin/tauri"
   }
-}
+}

+ 7 - 0
examples/state/package.json

@@ -0,0 +1,7 @@
+{
+  "name": "hello-world",
+  "version": "1.0.0",
+  "scripts": {
+    "tauri": "node ../../tooling/cli.js/bin/tauri"
+  }
+}

+ 57 - 0
examples/state/public/index.html

@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+  <meta charset="UTF-8" />
+  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+  <title>Tauri</title>
+</head>
+
+<body>
+  <h3>Counter</h3>
+  <div>
+    <button id="increment-btn">Increment counter</button>
+  </div>
+  <h3>Database</h3>
+  <div>
+    <input id="store-input" placeholder="The value to store">
+    <button id="store-btn">Store</button>
+  </div>
+  <div>
+    <button id="read-btn">Read</button>
+  </div>
+  <div id="response"></div>
+
+  <script>
+    const KEY = 'db-key'
+    const storeBtn = document.querySelector('#store-btn')
+    const readBtn = document.querySelector('#read-btn')
+    const incrementBtn = document.querySelector('#increment-btn')
+    const storeInput = document.querySelector('#store-input')
+    const responseContainer = document.querySelector('#response')
+
+    function updateResponse(response) {
+      responseContainer.innerHTML = typeof response === "string" ? response : JSON.stringify(response)
+    }
+
+    incrementBtn.addEventListener('click', () => {
+      window.__TAURI__.invoke('increment_counter').then(updateResponse).catch(updateResponse)
+    })
+
+    storeBtn.addEventListener('click', () => {
+      window.__TAURI__.invoke('db_insert', {
+        key: KEY,
+        value: storeInput.value
+      }).then(updateResponse).catch(updateResponse)
+    })
+
+    readBtn.addEventListener('click', () => {
+      window.__TAURI__.invoke('db_read', {
+        key: KEY
+      }).then(updateResponse).catch(updateResponse)
+    })
+  </script>
+</body>
+
+</html>

+ 10 - 0
examples/state/src-tauri/.gitignore

@@ -0,0 +1,10 @@
+# Generated by Cargo
+# will have compiled files and executables
+/target/
+WixTools
+
+# These are backup files generated by rustfmt
+**/*.rs.bk
+
+config.json
+bundle.json

+ 1 - 0
examples/state/src-tauri/.license_template

@@ -0,0 +1 @@
+../../../.license_template

+ 17 - 0
examples/state/src-tauri/Cargo.toml

@@ -0,0 +1,17 @@
+[package]
+name = "state"
+version = "0.1.0"
+description = "A simple Tauri Appplication showcase the state functionality"
+edition = "2018"
+
+[build-dependencies]
+tauri-build = { path = "../../../core/tauri-build", features = [ "codegen" ] }
+
+[dependencies]
+serde_json = "1.0"
+serde = { version = "1.0", features = [ "derive" ] }
+tauri = { path = "../../../core/tauri", features = ["api-all"] }
+
+[features]
+default = [ "custom-protocol" ]
+custom-protocol = [ "tauri/custom-protocol" ]

+ 14 - 0
examples/state/src-tauri/build.rs

@@ -0,0 +1,14 @@
+// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+use tauri_build::{try_build, Attributes, WindowsAttributes};
+
+fn main() {
+  if let Err(error) = try_build(
+    Attributes::new()
+      .windows_attributes(WindowsAttributes::new().window_icon_path("../../.icons/icon.ico")),
+  ) {
+    panic!("error found during tauri-build: {}", error);
+  }
+}

+ 51 - 0
examples/state/src-tauri/src/main.rs

@@ -0,0 +1,51 @@
+// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+#![cfg_attr(
+  all(not(debug_assertions), target_os = "windows"),
+  windows_subsystem = "windows"
+)]
+
+use std::{
+  collections::HashMap,
+  sync::{
+    atomic::{AtomicUsize, Ordering},
+    Arc, Mutex,
+  },
+};
+
+use tauri::State;
+
+struct Counter(AtomicUsize);
+
+#[derive(Default)]
+struct Database(Arc<Mutex<HashMap<String, String>>>);
+
+#[tauri::command]
+fn increment_counter(counter: State<'_, Counter>) -> usize {
+  counter.0.fetch_add(1, Ordering::Relaxed) + 1
+}
+
+#[tauri::command]
+fn db_insert(key: String, value: String, db: State<'_, Database>) {
+  db.0.lock().unwrap().insert(key, value);
+}
+
+#[tauri::command]
+fn db_read(key: String, db: State<'_, Database>) -> Option<String> {
+  db.0.lock().unwrap().get(&key).cloned()
+}
+
+fn main() {
+  tauri::Builder::default()
+    .manage(Counter(AtomicUsize::new(0)))
+    .manage(Database(Default::default()))
+    .invoke_handler(tauri::generate_handler![
+      increment_counter,
+      db_insert,
+      db_read
+    ])
+    .run(tauri::generate_context!())
+    .expect("error while running tauri application");
+}

+ 56 - 0
examples/state/src-tauri/tauri.conf.json

@@ -0,0 +1,56 @@
+{
+  "build": {
+    "distDir": "../public",
+    "devPath": "../public",
+    "beforeDevCommand": "",
+    "beforeBuildCommand": ""
+  },
+  "tauri": {
+    "bundle": {
+      "active": true,
+      "targets": "all",
+      "identifier": "com.tauri.dev",
+      "icon": [
+        "../../.icons/32x32.png",
+        "../../.icons/128x128.png",
+        "../../.icons/128x128@2x.png",
+        "../../.icons/icon.icns",
+        "../../.icons/icon.ico"
+      ],
+      "resources": [],
+      "externalBin": [],
+      "copyright": "",
+      "category": "DeveloperTool",
+      "shortDescription": "",
+      "longDescription": "",
+      "deb": {
+        "depends": [],
+        "useBootstrapper": false
+      },
+      "macOS": {
+        "frameworks": [],
+        "minimumSystemVersion": "",
+        "useBootstrapper": false,
+        "exceptionDomain": ""
+      }
+    },
+    "allowlist": {
+      "all": true
+    },
+    "windows": [
+      {
+        "title": "Welcome to Tauri!",
+        "width": 800,
+        "height": 600,
+        "resizable": true,
+        "fullscreen": false
+      }
+    ],
+    "security": {
+      "csp": "default-src blob: data: filesystem: ws: http: https: 'unsafe-eval' 'unsafe-inline'"
+    },
+    "updater": {
+      "active": false
+    }
+  }
+}