Skip to main content

adam_web_ui/binding/
types.rs

1//! Defines canonical transactions, immutable publication, and typed host outcomes.
2//!
3//! Match [`HostOutcome`] at the application boundary; recovery remains explicit.
4
5use crate::input::{InputError, NumberKind, NumericRange};
6use crate::{BuildError, BuiltSheet, RuntimeFailure, ValidationIssue};
7use std::rc::Rc;
8
9/// Reconstructs the same initialized schema on its owning event loop.
10///
11/// The factory must reproduce initial values, relationships, keys, and codecs.
12///
13/// # Examples
14/// ```
15/// let factory: adam_web_ui::binding::ModelFactory =
16///     std::rc::Rc::new(|| adam_web_ui::build_sheet("sheet s {}", "s.adm2"));
17/// assert!(factory().is_ok());
18/// ```
19pub type ModelFactory = Rc<dyn Fn() -> Result<BuiltSheet, BuildError>>;
20
21/// Addresses an input by stable schema key and exact canonical scalar text.
22///
23/// # Examples
24/// ```
25/// let edit = adam_web_ui::binding::CellEdit { key: "count".into(), canonical: "20".into() };
26/// assert_eq!(edit.canonical, "20");
27/// ```
28#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
29pub struct CellEdit {
30    /// Stable host-schema name, never a persisted runtime ID.
31    pub key: String,
32    /// Exact scalar text: an aspiration in a transaction, effective in a recording.
33    pub canonical: String,
34}
35
36/// Identifies feedback-loop policy without changing transaction acceptance.
37///
38/// # Examples
39/// ```
40/// use adam_web_ui::binding::UpdateOrigin;
41/// assert_ne!(UpdateOrigin::User, UpdateOrigin::Playback);
42/// ```
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum UpdateOrigin {
45    /// An application user's edit.
46    User,
47    /// A replayed recording, not a new user recording event.
48    Playback,
49    /// An explicit host recovery operation.
50    Recovery,
51}
52
53/// Retains accepted ordered input groups independently of any mutable model.
54///
55/// Groups preserve write recency and unclamped aspirations, not effective values.
56///
57/// # Examples
58/// ```
59/// let state = adam_web_ui::binding::RecoveryState {
60///     schema_key: "example/v1".into(), transactions: vec![]
61/// };
62/// assert!(state.transactions.is_empty());
63/// ```
64#[derive(Debug, serde::Serialize, serde::Deserialize)]
65pub struct RecoveryState {
66    /// Identifies the factory's schema and codec contract.
67    pub schema_key: String,
68    /// Accepted transaction groups in propagation order.
69    pub transactions: Vec<Vec<CellEdit>>,
70}
71
72/// Publishes interaction state without treating derived cells as disabled.
73///
74/// # Examples
75/// ```
76/// let flags = adam_web_ui::binding::CellFlags::default();
77/// assert!(!flags.disabled);
78/// ```
79#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
80pub struct CellFlags {
81    /// Forced or disconnected from relevant results.
82    pub disabled: bool,
83    /// Explicit output that cannot accept edits.
84    pub readonly: bool,
85    /// Contributes to an output, requirement, or selector, or no outputs restrict relevance.
86    pub relevant: bool,
87    /// Has a filter diagnostic, or contributes to a filter failure.
88    pub invalid: bool,
89    /// Has no alternative relationship direction.
90    pub forced: bool,
91}
92
93/// Publishes one accepted effective value and its editor capabilities.
94///
95/// Supported scalars use exact codec text, independently of Inspector rounding.
96/// Unsupported named cells remain visible as display text; a missing codec is a
97/// capability (`codec_supported`), not a validation issue, and never sets `invalid`.
98///
99/// # Examples
100/// See [`super::SheetOwner::views`] for reading shared immutable views.
101#[derive(Debug, PartialEq)]
102pub struct CellView {
103    /// Stable host-schema key.
104    pub key: String,
105    /// Exact effective scalar encoding, or compound display text.
106    pub text: String,
107    /// Source classification of the last accepted propagation.
108    pub is_source: bool,
109    /// Interaction and diagnostic state.
110    pub flags: CellFlags,
111    /// Concrete primitive type for numeric editors.
112    pub number_kind: Option<NumberKind>,
113    /// Selects the Boolean editor without inferring type from displayed text.
114    pub is_bool: bool,
115    /// Distinguishes editable scalar text from unsupported compound display text.
116    pub codec_supported: bool,
117    /// Exact current filter endpoints, when a range filter exists.
118    pub range: Option<NumericRange>,
119    /// Nonfatal filter diagnostics.
120    pub issues: Vec<ValidationIssue>,
121}
122
123/// Distinguishes key, editor, capability, and owner-lifetime failures.
124///
125/// # Examples
126/// ```
127/// use adam_web_ui::binding::BindingError;
128/// assert!(matches!(BindingError::UnknownKey("x".into()), BindingError::UnknownKey(_)));
129/// ```
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub enum BindingError {
132    /// No cell has this schema key.
133    UnknownKey(String),
134    /// The editor cannot write this cell, including explicit outputs.
135    IncompatibleEditor(String),
136    /// The cell has no exact scalar codec.
137    UnsupportedCodec(String),
138    /// A fatal failure permanently retired the instance.
139    RetiredInstance,
140    /// A recoverable rejection discarded the model; explicit restoration is required.
141    Unavailable,
142    /// Another transaction currently owns the candidate.
143    ReentrantMutation,
144}
145
146impl std::fmt::Display for BindingError {
147    /// Formats the structured failure for a human-readable diagnostic.
148    ///
149    /// - Complexity: O(message bytes).
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        match self {
152            Self::UnknownKey(key) => write!(f, "unknown cell key `{key}`"),
153            Self::IncompatibleEditor(key) => write!(f, "incompatible editor for `{key}`"),
154            Self::UnsupportedCodec(key) => write!(f, "unsupported scalar codec for `{key}`"),
155            Self::RetiredInstance => f.write_str("model instance is permanently retired"),
156            Self::Unavailable => f.write_str("model requires explicit accepted-state restoration"),
157            Self::ReentrantMutation => f.write_str("model transaction is already in progress"),
158        }
159    }
160}
161
162impl std::error::Error for BindingError {}
163
164/// Reports recoverable rejection without retaining the rejected candidate.
165///
166/// # Examples
167/// ```
168/// use adam_web_ui::binding::{HostRejection, BindingError};
169/// let rejected = HostRejection::Binding(BindingError::Unavailable);
170/// assert!(matches!(rejected, HostRejection::Binding(_)));
171/// ```
172#[derive(Debug)]
173pub enum HostRejection {
174    /// Conversion rejected the entire group before any mutation.
175    Input(InputError),
176    /// A key, editor, codec, or owner-state check rejected the group.
177    Binding(BindingError),
178    /// Successful propagation produced false requirements.
179    Validation(Vec<ValidationIssue>),
180    /// A mutating write failed; its candidate was discarded without propagation.
181    Mutation(RuntimeFailure),
182}
183
184/// Returns every transaction outcome to the host without choosing recovery.
185///
186/// # Examples
187/// ```
188/// let outcome = adam_web_ui::binding::HostOutcome::Accepted;
189/// assert!(matches!(outcome, adam_web_ui::binding::HostOutcome::Accepted));
190/// ```
191#[derive(Debug)]
192pub enum HostOutcome {
193    /// Commits the input group and coherently publishes its effective views.
194    Accepted,
195    /// Accepts the transaction and publication but stops a failed recorder.
196    RecordingFailed(super::CaptureError),
197    /// Preserves accepted publication/history but requires explicit restoration.
198    Rejected(HostRejection),
199    /// Permanently retires the model; reconstruction and retry are forbidden.
200    Fatal(RuntimeFailure),
201}