From 35b439f70fa9e713fde9ed5b2aee440eec212131 Mon Sep 17 00:00:00 2001 From: Tony Date: Wed, 2 Oct 2024 18:19:31 +0800 Subject: [PATCH] Enable auto save by default --- plugins/store/guest-js/index.ts | 4 ++-- plugins/store/src/lib.rs | 21 ++++++++++++++++++--- plugins/store/src/store.rs | 20 +++++++++++++++++++- 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/plugins/store/guest-js/index.ts b/plugins/store/guest-js/index.ts index d173c3f4..5f910192 100644 --- a/plugins/store/guest-js/index.ts +++ b/plugins/store/guest-js/index.ts @@ -17,9 +17,9 @@ interface ChangePayload { */ export type StoreOptions = { /** - * Auto save on modification with debounce duration in milliseconds + * Auto save on modification with debounce duration in milliseconds, it's 100ms by default, pass in `false` to disable it */ - autoSave?: boolean + autoSave?: boolean | number } /** diff --git a/plugins/store/src/lib.rs b/plugins/store/src/lib.rs index 53c71ea1..63951190 100644 --- a/plugins/store/src/lib.rs +++ b/plugins/store/src/lib.rs @@ -13,7 +13,7 @@ pub use error::{Error, Result}; use log::warn; -use serde::Serialize; +use serde::{Deserialize, Serialize}; pub use serde_json::Value as JsonValue; use std::{ collections::HashMap, @@ -42,15 +42,30 @@ pub struct StoreCollection { stores: Mutex>, Option)>>, } +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum AutoSave { + DebounceDuration(u64), + Bool(bool), +} + #[tauri::command] async fn create_store( app: AppHandle, path: PathBuf, - auto_save: Option, + auto_save: Option, ) -> Result { let mut builder = app.store_builder(path.clone()); if let Some(auto_save) = auto_save { - builder = builder.auto_save(Duration::from_millis(auto_save)); + match auto_save { + AutoSave::DebounceDuration(duration) => { + builder = builder.auto_save(Duration::from_millis(duration)); + } + AutoSave::Bool(false) => { + builder = builder.disable_auto_save(); + } + _ => {} + } } let store = builder.build()?; let rid = app.resources_table().add_arc(store); diff --git a/plugins/store/src/store.rs b/plugins/store/src/store.rs index 542a52de..ce9f2fea 100644 --- a/plugins/store/src/store.rs +++ b/plugins/store/src/store.rs @@ -66,7 +66,7 @@ impl StoreBuilder { defaults: None, serialize: default_serialize, deserialize: default_deserialize, - auto_save: None, + auto_save: Some(Duration::from_millis(100)), } } @@ -167,6 +167,24 @@ impl StoreBuilder { self } + /// Auto save on modified with a debounce duration + /// + /// # Examples + /// ``` + /// tauri::Builder::default() + /// .plugin(tauri_plugin_store::Builder::default().build()) + /// .setup(|app| { + /// let store = tauri_plugin_store::StoreBuilder::new(app, "store.json") + /// .auto_save(std::time::Duration::from_millis(100)) + /// .build()?; + /// Ok(()) + /// }); + /// ``` + pub fn disable_auto_save(mut self) -> Self { + self.auto_save = None; + self + } + /// Builds the [`Store`]. /// /// # Examples