Skip to main content

termwright_ratatui/
lib.rs

1//! Author intent for custom Ratatui widgets, without replacing their render.
2//!
3//! [`Annotated`] implements Ratatui's ordinary [`Widget`] and
4//! [`StatefulWidget`] traits and delegates to the wrapped widget exactly once.
5//! The zero-config build probe still owns geometry, frame boundaries,
6//! collection state and occlusion. This crate can add role, name, description,
7//! test id, application-domain JSON, descriptive actions, relationships and an
8//! explicit stable semantic key.
9//!
10//! ```
11//! use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
12//! use termwright_ratatui::{Action, Annotate, Role, Semantics};
13//!
14//! struct Deploy;
15//! impl Widget for Deploy {
16//!     fn render(self, area: Rect, buffer: &mut Buffer) {
17//!         "Deploy".render(area, buffer);
18//!     }
19//! }
20//!
21//! let widget = Deploy.annotated(
22//!     Semantics::new()
23//!         .role(Role::Button)
24//!         .name("Deploy")
25//!         .test_id("deploy-release")
26//!         .semantic_key("deployment-control")
27//!         .action(Action::Activate)
28//!         .domain("deploymentStatus", "ready"),
29//! );
30//! # let area = Rect::new(0, 0, 10, 1);
31//! # let mut buffer = Buffer::empty(area);
32//! widget.render(area, &mut buffer);
33//! ```
34
35#![forbid(unsafe_code)]
36#![warn(missing_docs)]
37
38use std::any::type_name;
39
40use ratatui::buffer::Buffer;
41use ratatui::layout::Rect;
42use ratatui::widgets::{StatefulWidget, Widget};
43
44pub use serde_json::{json, Value};
45pub use termwright_probe_ratatui::{Action, Annotation as Semantics, Role};
46pub use termwright_protocol::evidence::{
47    register_pointer_evidence_provider, Context as EvidenceContext, HitTest as PointerHitTest,
48    PointerObservation as PointerEvidenceObservation, PointerProvider as PointerEvidenceProvider,
49    Registration as EvidenceRegistration,
50};
51pub use termwright_protocol::{
52    EvidenceMethod, ProviderPointerRegion, ProviderPointerSpan, Rect as ProviderRect,
53};
54
55/// Exact Ratatui release whose traits this SDK implements.
56///
57/// The instrumented build launcher independently pins its core/widget patch
58/// sets. Compatibility tests compare all three declarations.
59pub const RATATUI_VERSION: &str = "0.30.2";
60
61/// A widget paired with author intent.
62///
63/// Construction does not inspect environment variables and rendering while
64/// uninstrumented is a single no-op annotation hook followed by the original
65/// widget render. The inner widget remains accessible for composition and
66/// tests.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct Annotated<W> {
69    widget: W,
70    semantics: Semantics,
71}
72
73impl<W> Annotated<W> {
74    /// Wrap a widget with semantic intent.
75    #[must_use]
76    pub fn new(widget: W, semantics: Semantics) -> Self {
77        Self { widget, semantics }
78    }
79
80    /// Borrow the original widget.
81    #[must_use]
82    pub fn inner(&self) -> &W {
83        &self.widget
84    }
85
86    /// Mutably borrow the original widget.
87    #[must_use]
88    pub fn inner_mut(&mut self) -> &mut W {
89        &mut self.widget
90    }
91
92    /// Recover the original widget and discard the annotation wrapper.
93    #[must_use]
94    pub fn into_inner(self) -> W {
95        self.widget
96    }
97
98    /// Borrow the attached author intent.
99    #[must_use]
100    pub fn semantics(&self) -> &Semantics {
101        &self.semantics
102    }
103}
104
105/// Extension trait for idiomatic `widget.annotated(semantics)` construction.
106pub trait Annotate: Sized {
107    /// Pair this widget with author intent without changing its render logic.
108    #[must_use]
109    fn annotated(self, semantics: Semantics) -> Annotated<Self> {
110        Annotated::new(self, semantics)
111    }
112}
113
114impl<W> Annotate for W {}
115
116impl<W: Widget> Widget for Annotated<W> {
117    fn render(self, area: Rect, buffer: &mut Buffer) {
118        let Self { widget, semantics } = self;
119        let _render = begin::<Self, W>(semantics, area);
120        Widget::render(widget, area, buffer);
121    }
122}
123
124impl<W: StatefulWidget> StatefulWidget for Annotated<W> {
125    type State = W::State;
126
127    fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
128        let Self { widget, semantics } = self;
129        let _render = begin::<Self, W>(semantics, area);
130        StatefulWidget::render(widget, area, buffer, state);
131    }
132}
133
134impl<'a, W> Widget for &'a Annotated<W>
135where
136    &'a W: Widget,
137{
138    fn render(self, area: Rect, buffer: &mut Buffer) {
139        let _render = begin::<Self, &'a W>(self.semantics.clone(), area);
140        Widget::render(&self.widget, area, buffer);
141    }
142}
143
144impl<'a, W> StatefulWidget for &'a Annotated<W>
145where
146    &'a W: StatefulWidget,
147{
148    type State = <&'a W as StatefulWidget>::State;
149
150    fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
151        let _render = begin::<Self, &'a W>(self.semantics.clone(), area);
152        StatefulWidget::render(&self.widget, area, buffer, state);
153    }
154}
155
156fn begin<Wrapper: ?Sized, Inner: ?Sized>(
157    semantics: Semantics,
158    area: Rect,
159) -> termwright_probe_ratatui::AnnotatedRenderGuard {
160    termwright_probe_ratatui::begin_annotated_render(
161        type_name::<Wrapper>(),
162        type_name::<Inner>(),
163        semantics,
164        area.x,
165        area.y,
166        area.width,
167        area.height,
168    )
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    use ratatui::widgets::Paragraph;
176
177    #[derive(Clone, Copy)]
178    struct Paint(&'static str);
179
180    impl Widget for Paint {
181        fn render(self, area: Rect, buffer: &mut Buffer) {
182            Paragraph::new(self.0).render(area, buffer);
183        }
184    }
185
186    #[test]
187    fn owned_wrapper_preserves_widget_output() {
188        let area = Rect::new(0, 0, 12, 1);
189        let mut expected = Buffer::empty(area);
190        let mut annotated = Buffer::empty(area);
191
192        Paint("Deploy").render(area, &mut expected);
193        Paint("Deploy")
194            .annotated(Semantics::new().role(Role::Button).name("Deploy"))
195            .render(area, &mut annotated);
196
197        assert_eq!(annotated, expected);
198    }
199
200    struct Counter;
201
202    impl StatefulWidget for Counter {
203        type State = usize;
204
205        fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
206            *state += 1;
207            Paragraph::new(state.to_string()).render(area, buffer);
208        }
209    }
210
211    #[test]
212    fn stateful_wrapper_delegates_the_same_state_once() {
213        let area = Rect::new(0, 0, 4, 1);
214        let mut expected = Buffer::empty(area);
215        let mut annotated = Buffer::empty(area);
216        let mut expected_state = 0;
217        let mut annotated_state = 0;
218
219        Counter.render(area, &mut expected, &mut expected_state);
220        Counter
221            .annotated(Semantics::new().test_id("counter"))
222            .render(area, &mut annotated, &mut annotated_state);
223
224        assert_eq!(annotated, expected);
225        assert_eq!(annotated_state, expected_state);
226        assert_eq!(annotated_state, 1);
227    }
228
229    struct RefPaint;
230
231    impl Widget for &RefPaint {
232        fn render(self, area: Rect, buffer: &mut Buffer) {
233            Paragraph::new("reference").render(area, buffer);
234        }
235    }
236
237    #[test]
238    fn reference_render_keeps_reference_widget_behavior() {
239        let area = Rect::new(0, 0, 12, 1);
240        let wrapped = RefPaint.annotated(Semantics::new().name("Reference"));
241        let mut buffer = Buffer::empty(area);
242
243        Widget::render(&wrapped, area, &mut buffer);
244
245        assert_eq!(buffer[(0, 0)].symbol(), "r");
246    }
247
248    struct RefCounter;
249
250    impl StatefulWidget for &RefCounter {
251        type State = usize;
252
253        fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
254            *state += 1;
255            Paragraph::new(state.to_string()).render(area, buffer);
256        }
257    }
258
259    #[test]
260    fn reference_stateful_render_delegates_the_same_state_once() {
261        let area = Rect::new(0, 0, 4, 1);
262        let wrapped = RefCounter.annotated(Semantics::new().test_id("ref-counter"));
263        let mut buffer = Buffer::empty(area);
264        let mut state = 0;
265
266        StatefulWidget::render(&wrapped, area, &mut buffer, &mut state);
267
268        assert_eq!(buffer[(0, 0)].symbol(), "1");
269        assert_eq!(state, 1);
270    }
271
272    #[test]
273    fn manifest_floor_matches_the_pinned_framework_floor() {
274        assert_eq!(env!("CARGO_PKG_RUST_VERSION"), "1.88");
275        assert_eq!(RATATUI_VERSION, "0.30.2");
276        let manifest = include_str!("../Cargo.toml");
277        assert!(manifest.contains("ratatui = { version = \"=0.30.2\""));
278    }
279}