tauri-plugin-sync-state 0.1.0

Bidirectional, type-keyed state sync between a Tauri backend and a JS/React frontend.
Documentation
use crate::{error::Result, slice::StateRegistry};
use serde_json::Value;
use tauri::{AppHandle, Emitter, Runtime, State};

pub(crate) const EVENT_PREFIX: &str = "plugin:sync-state:updated:";

pub(crate) fn event_name(name: &str) -> String {
    format!("{EVENT_PREFIX}{name}")
}

#[tauri::command]
pub(crate) fn get_state(name: String, registry: State<'_, StateRegistry>) -> Result<Value> {
    registry.get_json(&name)
}

#[tauri::command]
pub(crate) fn set_state<R: Runtime>(
    name: String,
    value: Value,
    registry: State<'_, StateRegistry>,
    app: AppHandle<R>,
) -> Result<()> {
    registry.set_json(&name, value.clone())?;
    app.emit(&event_name(&name), value)
        .map_err(|e| crate::error::Error::Emit(e.to_string()))
}