rcus-core 0.1.3

Core types for rcus: retained view tree, style, input, and the host bridge protocol
Documentation
//! The scripting boundary for rcus.
//!
//! A view module is a pure function from state to a view spec. It has no
//! ambient authority: everything it needs arrives in state, and everything it
//! wants the host to do arrives as a [`Call`]. The runtime collects calls in
//! order and the host drains them, which is the same path in a window and in a
//! headless run.

/// One request from view code, in the order the runtime received it.
#[derive(Clone, Debug, PartialEq)]
pub enum Call {
    /// Replace the view. The payload is a JSON view spec.
    SetView(String),
    /// Repaint without a tree change, for a caret blink or a spinner.
    Invalidate,
    /// A value the host should observe, such as a breadcrumb or a metric.
    Write { name: String, value: String },
    /// A user action for the host reducer, which owns every state change.
    Dispatch { name: String, value: String },
    /// Open a host-owned view: command palette, file picker, diff.
    Open { name: String, value: String },
    /// Close the host-owned view with this name.
    Close { name: String },
}

/// The host side of the bridge. A host implements these once and receives every
/// call through [`deliver`].
pub trait Host {
    /// Decode a view spec and make it the current view.
    fn set_view(&mut self, spec: &str) -> Result<(), String>;
    /// Repaint without a new view.
    fn invalidate(&mut self);
    /// Observe a value from view code.
    fn write(&mut self, name: &str, value: &str);
    /// Handle a user action.
    fn dispatch(&mut self, name: &str, value: &str);
    /// Open a host-owned view.
    fn open(&mut self, name: &str, value: &str);
    /// Close a host-owned view.
    fn close(&mut self, name: &str);
}

/// Hands a batch of calls to the host in order, stopping at the first error.
pub fn deliver(host: &mut impl Host, calls: Vec<Call>) -> Result<(), String> {
    for call in calls {
        match call {
            Call::SetView(spec) => host.set_view(&spec)?,
            Call::Invalidate => host.invalidate(),
            Call::Write { name, value } => host.write(&name, &value),
            Call::Dispatch { name, value } => host.dispatch(&name, &value),
            Call::Open { name, value } => host.open(&name, &value),
            Call::Close { name } => host.close(&name),
        }
    }
    Ok(())
}

/// The engine contract every rcus scripting backend implements.
pub trait ScriptRuntime {
    /// Evaluates `source` as an expression and returns its JSON result.
    fn evaluate(&mut self, source: &str) -> Result<String, String>;
    /// Evaluates a view module and calls its `view(state)` export with
    /// `state_json`, returning the JSON view spec it produced.
    fn update(&mut self, source: &str, state_json: &str) -> Result<String, String>;
}