Skip to main content

rcus_core/
host.rs

1//! The scripting boundary for rcus.
2//!
3//! A view module is a pure function from state to a view spec. It has no
4//! ambient authority: everything it needs arrives in state, and everything it
5//! wants the host to do arrives as a [`Call`]. The runtime collects calls in
6//! order and the host drains them, which is the same path in a window and in a
7//! headless run.
8
9/// One request from view code, in the order the runtime received it.
10#[derive(Clone, Debug, PartialEq)]
11pub enum Call {
12    /// Replace the view. The payload is a JSON view spec.
13    SetView(String),
14    /// Repaint without a tree change, for a caret blink or a spinner.
15    Invalidate,
16    /// A value the host should observe, such as a breadcrumb or a metric.
17    Write { name: String, value: String },
18    /// A user action for the host reducer, which owns every state change.
19    Dispatch { name: String, value: String },
20    /// Open a host-owned view: command palette, file picker, diff.
21    Open { name: String, value: String },
22    /// Close the host-owned view with this name.
23    Close { name: String },
24}
25
26/// The host side of the bridge. A host implements these once and receives every
27/// call through [`deliver`].
28pub trait Host {
29    /// Decode a view spec and make it the current view.
30    fn set_view(&mut self, spec: &str) -> Result<(), String>;
31    /// Repaint without a new view.
32    fn invalidate(&mut self);
33    /// Observe a value from view code.
34    fn write(&mut self, name: &str, value: &str);
35    /// Handle a user action.
36    fn dispatch(&mut self, name: &str, value: &str);
37    /// Open a host-owned view.
38    fn open(&mut self, name: &str, value: &str);
39    /// Close a host-owned view.
40    fn close(&mut self, name: &str);
41}
42
43/// Hands a batch of calls to the host in order, stopping at the first error.
44pub fn deliver(host: &mut impl Host, calls: Vec<Call>) -> Result<(), String> {
45    for call in calls {
46        match call {
47            Call::SetView(spec) => host.set_view(&spec)?,
48            Call::Invalidate => host.invalidate(),
49            Call::Write { name, value } => host.write(&name, &value),
50            Call::Dispatch { name, value } => host.dispatch(&name, &value),
51            Call::Open { name, value } => host.open(&name, &value),
52            Call::Close { name } => host.close(&name),
53        }
54    }
55    Ok(())
56}
57
58/// The engine contract every rcus scripting backend implements.
59pub trait ScriptRuntime {
60    /// Evaluates `source` as an expression and returns its JSON result.
61    fn evaluate(&mut self, source: &str) -> Result<String, String>;
62    /// Evaluates a view module and calls its `view(state)` export with
63    /// `state_json`, returning the JSON view spec it produced.
64    fn update(&mut self, source: &str, state_json: &str) -> Result<String, String>;
65}