Skip to main content

tauri_plugin_sync_state/
builder.rs

1use crate::{
2    commands,
3    error::Result,
4    slice::{StateRegistry, SyncState},
5};
6use tauri::{plugin::TauriPlugin, Manager, Runtime};
7
8type Init = Box<dyn FnOnce(&StateRegistry) -> Result<()> + Send + 'static>;
9
10#[derive(Default)]
11pub struct Builder {
12    inits: Vec<Init>,
13}
14
15impl Builder {
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    pub fn register<S: SyncState>(mut self, initial: S) -> Self {
21        self.inits.push(Box::new(move |reg| reg.insert(initial)));
22        self
23    }
24
25    pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
26        tauri::plugin::Builder::new("sync-state")
27            .invoke_handler(tauri::generate_handler![
28                commands::get_state,
29                commands::set_state
30            ])
31            .setup(move |app, _api| {
32                let registry = StateRegistry::new();
33                for init in self.inits {
34                    init(&registry)?;
35                }
36                app.manage(registry);
37                Ok(())
38            })
39            .build()
40    }
41}