Skip to main content

adam_web_ui/graph/
constraints.rs

1//! Pure owner of the embedded Adam graph-view policy.
2//!
3//! Construct one [`ViewConstraints`] per graph, submit absolute proposals, and
4//! use [`ViewAction::Refresh`] for geometry-only updates. Only an explicit
5//! [`ViewAction::Fit`] replaces the user's pan/zoom aspiration with the fit.
6//!
7//! ```
8//! use adam_web_ui::graph::{ViewAction, ViewConstraints, ViewInput};
9//! use cel_euclid::{Point2D, Rect, Size2D};
10//! let mut model = ViewConstraints::new()?;
11//! let output = model.update(ViewInput {
12//!     bounds: Rect::new(Point2D::zero(), Size2D::new(200.0, 100.0)),
13//!     viewport: Size2D::new(400.0, 300.0),
14//!     action: ViewAction::Fit,
15//! })?;
16//! assert_eq!((output.view.x, output.view.y, output.view.k), (0.0, 50.0, 2.0));
17//! # Ok::<(), adam_web_ui::graph::GraphFailure>(())
18//! ```
19
20use adam_lang::{AdamParser, ParsedSheet, SheetDiagnostics};
21use adam_rs::CellId;
22use anyhow::ensure;
23use cel_euclid::{Rect, Size2D, Transform2D, Vector2D};
24use serde::{Deserialize, Serialize};
25
26use super::GraphFailure;
27use crate::{RuntimeFailure, build, labels::Renderer};
28/// Keeps thread-confined diagnostic owners in their original typed error.
29type Result<T> = std::result::Result<T, GraphFailure>;
30
31/// The embedded policy evaluated by every model instance.
32const SOURCE: &str = include_str!("view_constraints.adm2");
33/// The diagnostic source name for the embedded policy.
34const FILE_NAME: &str = "view_constraints.adm2";
35
36/// A uniform scale followed by a viewport-space translation.
37///
38/// Approved values are finite and `k` is positive.
39///
40/// # Examples
41/// ```
42/// use adam_web_ui::graph::ViewTransform;
43/// let view = ViewTransform { x: 0.0, y: 50.0, k: 2.0 };
44/// assert_eq!(view.k, 2.0);
45/// ```
46#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
47pub struct ViewTransform {
48    /// The horizontal viewport-space translation.
49    pub x: f64,
50    /// The vertical viewport-space translation.
51    pub y: f64,
52    /// The positive uniform zoom factor.
53    pub k: f64,
54}
55
56/// An explicit source edit, geometry refresh, or replacement with the sheet's fit.
57///
58/// # Examples
59/// ```
60/// use adam_web_ui::graph::ViewAction;
61/// assert_eq!(serde_json::to_string(&ViewAction::Fit).unwrap(), r#"{"kind":"fit"}"#);
62/// ```
63#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
64#[serde(tag = "kind", rename_all = "snake_case")]
65pub enum ViewAction {
66    /// Replaces the original source aspiration with an absolute proposal.
67    Propose {
68        /// The finite proposed translation and positive finite zoom.
69        view: ViewTransform,
70    },
71    /// Updates only bounds and viewport, preserving source aspirations.
72    Refresh,
73    /// Replaces pan and zoom sources with the sheet's current derived fit.
74    Fit,
75}
76
77/// Geometry and an action for a single model update.
78///
79/// Bounds have finite ordered endpoints and representable nonnegative extents.
80/// Viewport extents are positive and finite.
81///
82/// # Examples
83/// ```
84/// use adam_web_ui::graph::{ViewAction, ViewInput};
85/// use cel_euclid::{Rect, Size2D};
86/// let input = ViewInput {
87///     bounds: Rect::default(),
88///     viewport: Size2D::new(400.0, 300.0),
89///     action: ViewAction::Refresh,
90/// };
91/// assert!(input.viewport.width > 0.0);
92/// ```
93#[derive(Clone, Copy, Debug)]
94pub struct ViewInput {
95    /// The graph's content bounds, including any renderer-provided margin.
96    pub bounds: Rect,
97    /// The measured viewport size.
98    pub viewport: Size2D,
99    /// The requested source operation.
100    pub action: ViewAction,
101}
102
103/// Complete finite approved values and gesture hints derived by Adam.
104///
105/// `min_zoom <= view.k <= max_zoom`; the maximum can exceed eight when fit does.
106///
107/// # Examples
108/// ```
109/// # use adam_web_ui::graph::{ViewOutput, ViewTransform};
110/// let view = ViewTransform { x: 0.0, y: 50.0, k: 2.0 };
111/// let output = ViewOutput { view, fit: view, min_zoom: 2.0, max_zoom: 8.0 };
112/// assert!(output.min_zoom <= output.view.k && output.view.k <= output.max_zoom);
113/// ```
114#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
115pub struct ViewOutput {
116    /// The conformed view to render.
117    pub view: ViewTransform,
118    /// The fit target for the current geometry.
119    pub fit: ViewTransform,
120    /// The fit-derived minimum scale.
121    pub min_zoom: f64,
122    /// The sheet's effective maximum scale.
123    pub max_zoom: f64,
124}
125
126/// Cached identities for the fixed embedded sheet.
127struct Cells {
128    /// The bounds source.
129    bounds: CellId,
130    /// The viewport source.
131    viewport: CellId,
132    /// The ordinary pan cell retaining its source aspiration.
133    pan: CellId,
134    /// The ordinary zoom cell retaining its source aspiration.
135    zoom: CellId,
136    /// The derived fit scale.
137    fit_zoom: CellId,
138    /// The derived fit translation.
139    fit_pan: CellId,
140    /// The derived minimum scale.
141    min_zoom: CellId,
142    /// The derived maximum scale.
143    max_zoom: CellId,
144    /// The derived affine view.
145    view: CellId,
146}
147
148/// Owns one parsed sheet and cached identities without per-request parsing.
149///
150/// All fit, centering, clamping, and zoom-limit arithmetic lives in the sheet.
151/// Invalid input leaves the model available. Any error after mutation discards
152/// its candidate permanently; subsequent updates report unavailable.
153///
154/// # Examples
155/// ```
156/// let model = adam_web_ui::graph::ViewConstraints::new();
157/// assert!(model.is_ok());
158/// ```
159pub struct ViewConstraints {
160    /// The sole candidate, absent after a mutating error.
161    candidate: Option<ViewCandidate>,
162}
163
164impl ViewConstraints {
165    /// Constructs the embedded policy once.
166    ///
167    /// # Errors
168    /// Returns construction, initialization, or output diagnostics.
169    ///
170    /// - Complexity: O(s² + n + p) time and O(s + n + p) space for installed
171    ///   signatures `s`, source bytes `n`, and propagation work `p`.
172    ///
173    /// # Examples
174    /// ```
175    /// let model = adam_web_ui::graph::ViewConstraints::new()?;
176    /// # Ok::<(), adam_web_ui::graph::GraphFailure>(())
177    /// ```
178    pub fn new() -> Result<Self> {
179        Ok(Self {
180            candidate: Some(ViewCandidate::new()?),
181        })
182    }
183
184    /// Applies valid input only to an available candidate and retires it on error.
185    ///
186    /// # Errors
187    /// Returns invalid input before mutation, typed runtime errors, invalid outputs,
188    /// or unavailable after any previous mutating failure.
189    ///
190    /// - Complexity: O(p) time and space in propagation work; no parsing.
191    ///
192    /// # Examples
193    /// See the module example for a fit request.
194    pub fn update(&mut self, input: ViewInput) -> Result<ViewOutput> {
195        if self.candidate.is_none() {
196            return Err(GraphFailure::Unavailable);
197        }
198        validate_input(&input).map_err(|error| GraphFailure::InvalidInput(error.to_string()))?;
199        let mut candidate = self.candidate.take().expect("availability checked");
200        let output = candidate.update(input)?;
201        self.candidate = Some(candidate);
202        Ok(output)
203    }
204}
205
206/// Contains the live model only while its owner admits mutation.
207struct ViewCandidate {
208    /// The persistent source and derived values.
209    parsed: ParsedSheet,
210    /// The identities resolved once during construction.
211    cells: Cells,
212}
213
214impl ViewCandidate {
215    /// Parses and propagates the embedded sheet using the configured library host.
216    ///
217    /// # Errors
218    /// Returns a formatted diagnostic for invalid sheet syntax, missing cells,
219    /// evaluation failure, or incomplete/non-finite initial outputs.
220    ///
221    /// - Complexity: O(s² + n + p) time and O(s + n + p) space for installed
222    ///   signatures `s`, source length `n`, and the sheet's propagation work `p`.
223    ///
224    /// # Examples
225    /// ```
226    /// let mut model = adam_web_ui::graph::ViewConstraints::new()?;
227    /// # Ok::<(), adam_web_ui::graph::GraphFailure>(())
228    /// ```
229    pub fn new() -> Result<Self> {
230        let mut parser = AdamParser::new(build::type_registry(), build::op_lookup());
231        let parsed = parser.parse_str(SOURCE).map_err(|error| {
232            GraphFailure::InvalidInput(error.format_rustc_style(
233                SOURCE,
234                FILE_NAME,
235                1,
236                &Renderer::plain(),
237            ))
238        })?;
239        let id = |name: &str| {
240            parsed
241                .cell_names
242                .get(name)
243                .map(|&(id, _)| id)
244                .ok_or_else(|| {
245                    GraphFailure::InvalidInput(format!("{FILE_NAME}: missing cell `{name}`"))
246                })
247        };
248        let cells = Cells {
249            bounds: id("bounds")?,
250            viewport: id("viewport")?,
251            pan: id("pan")?,
252            zoom: id("zoom")?,
253            fit_zoom: id("fit_zoom")?,
254            fit_pan: id("fit_pan")?,
255            min_zoom: id("min_zoom")?,
256            max_zoom: id("effective_max_zoom")?,
257            view: id("view")?,
258        };
259        let mut model = Self { parsed, cells };
260        model.propagate()?;
261        model.output()?;
262        Ok(model)
263    }
264
265    /// Validates inputs, writes geometry and requested sources, and propagates.
266    ///
267    /// Refresh preserves the original pan/zoom aspiration; Fit copies only the
268    /// sheet's derived fit into those sources and propagates a second time.
269    ///
270    /// # Errors
271    /// Returns an error for non-finite/unordered/unrepresentable bounds,
272    /// nonpositive/non-finite viewport or proposed zoom, non-finite proposed pan,
273    /// sheet evaluation failure, or incomplete/non-finite/nonpositive outputs.
274    /// A failed update never returns a fallback view.
275    ///
276    /// - Complexity: O(p) time and space in sheet propagation work; no parsing.
277    ///
278    /// # Examples
279    /// ```
280    /// # use adam_web_ui::graph::{ViewAction, ViewConstraints, ViewInput};
281    /// # use cel_euclid::{Rect, Size2D};
282    /// let mut model = ViewConstraints::new()?;
283    /// let output = model.update(ViewInput {
284    ///     bounds: Rect::default(),
285    ///     viewport: Size2D::new(400.0, 300.0),
286    ///     action: ViewAction::Fit,
287    /// })?;
288    /// assert_eq!(output.view.k, 300.0);
289    /// # Ok::<(), adam_web_ui::graph::GraphFailure>(())
290    /// ```
291    pub fn update(&mut self, input: ViewInput) -> Result<ViewOutput> {
292        self.write(self.cells.bounds, input.bounds)?;
293        self.write(self.cells.viewport, input.viewport)?;
294        if let ViewAction::Propose { view } = input.action {
295            self.write(self.cells.pan, Vector2D::new(view.x, view.y))?;
296            self.write(self.cells.zoom, view.k)?;
297        }
298        self.propagate()?;
299        let output = self.output()?;
300        if input.action == ViewAction::Fit {
301            let pan: Vector2D = self.read(self.cells.fit_pan)?;
302            let zoom: f64 = self.read(self.cells.fit_zoom)?;
303            self.write(self.cells.pan, pan)?;
304            self.write(self.cells.zoom, zoom)?;
305            self.propagate()?;
306            return self.output();
307        }
308        Ok(output)
309    }
310
311    /// Retains a mutating sheet error with independently owned diagnostics.
312    ///
313    /// - Complexity: O(file name bytes); moves the existing diagnostic snapshot.
314    fn diagnostic(diagnostics: SheetDiagnostics, error: adam_rs::Error) -> GraphFailure {
315        GraphFailure::Runtime(Box::new(RuntimeFailure {
316            error,
317            diagnostics: Box::new(diagnostics),
318            file_name: FILE_NAME.into(),
319        }))
320    }
321
322    /// Writes a typed source, retaining its typed mutation error on failure.
323    fn write<T: 'static>(&mut self, id: CellId, value: T) -> Result<()> {
324        let diagnostics = self.parsed.diagnostics();
325        self.parsed
326            .write(id, value)
327            .map_err(|error| Self::diagnostic(diagnostics, error))
328    }
329
330    /// Reads a complete typed value, snapshotting diagnostics only when it fails.
331    ///
332    /// - Complexity: O(1) when the read succeeds; O(m + e) on error for metadata
333    ///   snapshot size m and rendered error sites e.
334    fn read<T: Copy + 'static>(&self, id: CellId) -> Result<T> {
335        match self.parsed.read::<T>(id).copied() {
336            Ok(value) => Ok(value),
337            Err(error) => {
338                let diagnostics = self.parsed.diagnostics();
339                Err(GraphFailure::InvalidInput(
340                    Self::diagnostic(diagnostics, error).to_string(),
341                ))
342            }
343        }
344    }
345
346    /// Propagates the cached sheet and clears its presentation change flags.
347    ///
348    /// # Errors
349    /// Returns the typed evaluation error with its pre-mutation diagnostic snapshot.
350    ///
351    /// - Complexity: O(p) time and space in sheet propagation work.
352    fn propagate(&mut self) -> Result<()> {
353        let diagnostics = self.parsed.diagnostics();
354        self.parsed
355            .propagate()
356            .map_err(|error| Self::diagnostic(diagnostics, error))?;
357        self.parsed.clear_changed();
358        Ok(())
359    }
360
361    /// Reads complete outputs and rejects non-finite or invalid scale results.
362    ///
363    /// # Errors
364    /// Returns an explicit diagnostic for unavailable values or invalid outputs.
365    fn output(&self) -> Result<ViewOutput> {
366        let view: Transform2D = self.read(self.cells.view)?;
367        let fit_pan: Vector2D = self.read(self.cells.fit_pan)?;
368        let fit_zoom: f64 = self.read(self.cells.fit_zoom)?;
369        let min_zoom: f64 = self.read(self.cells.min_zoom)?;
370        let max_zoom: f64 = self.read(self.cells.max_zoom)?;
371        if !([
372            view.m11, view.m12, view.m21, view.m22, view.m31, view.m32, fit_pan.x, fit_pan.y,
373            fit_zoom, min_zoom, max_zoom,
374        ]
375        .into_iter()
376        .all(f64::is_finite)
377            && fit_zoom > 0.0
378            && min_zoom > 0.0
379            && min_zoom <= view.m11
380            && view.m11 <= max_zoom)
381        {
382            return Err(GraphFailure::InvalidInput(format!(
383                "{FILE_NAME}: invalid or unrepresentable view/fit outputs"
384            )));
385        }
386        Ok(ViewOutput {
387            view: ViewTransform {
388                x: view.m31,
389                y: view.m32,
390                k: view.m11,
391            },
392            fit: ViewTransform {
393                x: fit_pan.x,
394                y: fit_pan.y,
395                k: fit_zoom,
396            },
397            min_zoom,
398            max_zoom,
399        })
400    }
401}
402
403/// Rejects invalid geometry and proposals before any sheet source is written.
404///
405/// Positive extents must advance the represented endpoint.
406///
407/// # Errors
408/// Returns a named input error for invalid bounds, viewport, or proposal.
409fn validate_input(input: &ViewInput) -> anyhow::Result<()> {
410    let bounds = input.bounds;
411    for (origin, extent, end) in [
412        (bounds.origin.x, bounds.size.width, bounds.max_x()),
413        (bounds.origin.y, bounds.size.height, bounds.max_y()),
414    ] {
415        ensure!(
416            origin.is_finite()
417                && extent.is_finite()
418                && extent >= 0.0
419                && end.is_finite()
420                && end >= origin
421                && (end - origin).is_finite()
422                && (extent == 0.0 || end > origin),
423            "invalid bounds: expected finite ordered endpoints and representable nonnegative extents"
424        );
425    }
426
427    ensure!(
428        input.viewport.width.is_finite()
429            && input.viewport.height.is_finite()
430            && input.viewport.width > 0.0
431            && input.viewport.height > 0.0,
432        "invalid viewport: expected positive finite extents"
433    );
434    if let ViewAction::Propose { view } = input.action {
435        ensure!(
436            view.x.is_finite() && view.y.is_finite(),
437            "invalid proposed pan: expected finite coordinates"
438        );
439        ensure!(
440            view.k.is_finite() && view.k > 0.0,
441            "invalid proposed zoom: expected a positive finite scale"
442        );
443    }
444    Ok(())
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    /// A mutating error discards its candidate; later work never invokes that sheet.
452    #[test]
453    fn runtime_failure_retires_without_invoking_sheet_again() {
454        let calls = std::rc::Rc::new(std::cell::Cell::new(0));
455        let observed = calls.clone();
456        let mut model = ViewConstraints::new().unwrap();
457        let candidate = model.candidate.as_mut().unwrap();
458        let output = candidate.parsed.add_cell(0.0_f64);
459        candidate
460            .parsed
461            .add_relationship(vec![adam_rs::Method::from_fn_1_1(
462                candidate.cells.bounds,
463                output,
464                move |_bounds: &Rect| {
465                    observed.set(observed.get() + 1);
466                    Err::<f64, _>(anyhow::anyhow!("graph fixture propagation failure"))
467                },
468            )])
469            .unwrap();
470        let input = ViewInput {
471            bounds: Rect::default(),
472            viewport: Size2D::new(400.0, 300.0),
473            action: ViewAction::Fit,
474        };
475        let error = model.update(input).unwrap_err();
476        let GraphFailure::Runtime(failure) = error else {
477            panic!("typed runtime failure required");
478        };
479        assert_eq!(failure.file_name, FILE_NAME);
480        assert_eq!(calls.get(), 1);
481        assert!(matches!(
482            model.update(input),
483            Err(GraphFailure::Unavailable)
484        ));
485        assert_eq!(calls.get(), 1);
486    }
487}