ratatui-style 0.2.0

A CSS cascade engine for ratatui — selectors, specificity, inheritance, pseudo-states, and data-driven styling.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Framework-agnostic element view: the `StyledNode` trait and supporting
//! types. The cascade engine knows nothing about a2ui, ratatui widgets, or any
//! particular framework — it only knows a [`StyledNode`].

/// A set of pseudo-class flags for one element.
///
/// Maps directly to CSS pseudo-classes: `:focus`, `:hover`, `:disabled`,
/// `:checked`, `:active`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct State {
    pub focus: bool,
    pub hover: bool,
    pub disabled: bool,
    pub checked: bool,
    pub active: bool,
}

impl State {
    pub const fn empty() -> Self {
        Self {
            focus: false,
            hover: false,
            disabled: false,
            checked: false,
            active: false,
        }
    }
    pub const fn focus() -> Self {
        Self {
            focus: true,
            ..Self::empty()
        }
    }
    pub const fn disabled() -> Self {
        Self {
            disabled: true,
            ..Self::empty()
        }
    }
}

/// Where an element sits among its siblings. Used by structural pseudo-class
/// matching (`:nth-child`, `:first-of-type`, etc.); returned by
/// [`StyledNode::position`] for forward-compat.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Position {
    /// 0-based index among siblings.
    pub index: usize,
    /// Total number of siblings (including self).
    pub sibling_count: usize,
    /// The parent element's type name, if any.
    pub parent_type: Option<String>,
    /// 0-based index of this element among its same-type siblings (those sharing
    /// `type_name`). 0 means "unknown / not supplied" — of-type pseudo-classes
    /// that need the total count (`:last/only/nth-last-of-type`) will NOT match
    /// when this is 0. (0-based, like `index`.) Supply it via
    /// [`with_of_type`](Self::with_of_type).
    pub of_type_index: usize,
    /// Total number of same-type siblings (including self). 0 means "unknown".
    /// The forward-looking of-type pseudos (`:last/only/nth-last-of-type`)
    /// require this to be `> 0` to match. `:nth-of-type` / `:first-of-type` will
    /// *prefer* this when `> 0` but fall back to previous-sibling counting
    /// otherwise. Supply it via [`with_of_type`](Self::with_of_type).
    pub of_type_count: usize,
}

impl Position {
    pub fn new(index: usize, sibling_count: usize) -> Self {
        Self {
            index,
            sibling_count,
            parent_type: None,
            of_type_index: 0,
            of_type_count: 0,
        }
    }

    /// Consuming builder that sets the same-type-sibling position info.
    ///
    /// `of_type_index` is 0-based among same-type siblings; `of_type_count` is
    /// the total same-type sibling count (including self). Both `0` (the
    /// default) mean "unknown" — in that state `:last/only/nth-last-of-type`
    /// never match.
    pub fn with_of_type(mut self, of_type_index: usize, of_type_count: usize) -> Self {
        self.of_type_index = of_type_index;
        self.of_type_count = of_type_count;
        self
    }
}

/// A borrowable view over an element's class list.
///
/// Two representations back the same query surface:
/// - [`Classes::from_slice`] borrows a `&'a [&'a str]` directly — used by
///   [`NodeRef`], it is **zero-allocation** (a compile-time guarantee when the
///   source is `&'static str`).
/// - [`Classes::from_vec`] owns a `Vec<&'a str>` — used by [`OwnedNode`], it
///   costs one `Vec` allocation per call (acceptable; the hot path uses
///   `NodeRef`).
///
/// Use [`as_slice`](Self::as_slice) for iteration (`&[&str]`) rather than
/// `iter()` so both representations unify behind a single concrete return
/// type.
pub struct Classes<'a> {
    repr: Repr<'a>,
}

enum Repr<'a> {
    Slice(&'a [&'a str]),
    Owned(Vec<&'a str>),
}

impl<'a> Classes<'a> {
    /// Zero-allocation view over a borrowed slice. The `NodeRef` path uses
    /// this — when `slice` is `&'static [&'static str]` no heap allocation
    /// occurs at any point.
    pub fn from_slice(slice: &'a [&'a str]) -> Self {
        Self {
            repr: Repr::Slice(slice),
        }
    }

    /// Owning view built from an existing `Vec<&str>`. Used by [`OwnedNode`]
    /// which stores `String`s and must materialize `&str` borrows per call.
    pub fn from_vec(v: Vec<&'a str>) -> Self {
        Self {
            repr: Repr::Owned(v),
        }
    }

    /// Unified read-only access to the underlying class names, regardless of
    /// representation. Prefer this over an `iter()` — both reprs return the
    /// same concrete `&[&str]`.
    pub fn as_slice(&self) -> &[&'a str] {
        match &self.repr {
            Repr::Slice(s) => s,
            Repr::Owned(v) => v,
        }
    }

    /// Whether `name` is present (case-sensitive).
    pub fn contains(&self, name: &str) -> bool {
        self.as_slice().contains(&name)
    }

    pub fn is_empty(&self) -> bool {
        self.as_slice().is_empty()
    }

    pub fn len(&self) -> usize {
        self.as_slice().len()
    }
}

/// The minimal contract the cascade needs to match selectors against an
/// element.
///
/// Implement this on your framework's node type (e.g. a2ui's `ComponentModel`,
/// or a plain app-state struct in a vanilla ratatui app).
///
/// For the draw-loop hot path prefer [`NodeRef`] (zero-allocation). [`OwnedNode`]
/// remains available for convenience where owned `String`/`Vec<String>` storage
/// is preferable.
pub trait StyledNode {
    /// Element type name — matches a CSS type selector (e.g. `"Button"`).
    fn type_name(&self) -> &str;

    /// Element id — matches a CSS `#id` selector.
    fn id(&self) -> Option<&str>;

    /// Class names — match CSS `.class` selectors.
    ///
    /// Returns a [`Classes<'_>`] borrow view rather than an allocating
    /// `Vec<&str>`. [`NodeRef`] makes this zero-allocation; [`OwnedNode`]
    /// pays one `Vec` allocation (it is not the hot path). The cascade hoists
    /// this call out of the per-rule loop so the cost is paid at most once per
    /// node regardless.
    fn classes(&self) -> Classes<'_>;

    /// Pseudo-class state — matches `:focus` / `:disabled` / etc.
    fn state(&self) -> State;

    /// Sibling position — for future `:nth-child` support.
    ///
    /// This is **optional**: `:nth-child` matching is P3 and not yet wired into
    /// the cascade, so `compute` does not consult it. The default returns an
    /// empty [`Position`]. Override it only when you need `:nth-child` data at
    /// some future point — until then, leaving the default avoids forcing every
    /// node type to materialize sibling info.
    fn position(&self) -> Position {
        Position::default()
    }
}

/// A convenience node that owns its data (`String` / `Vec<String>`).
///
/// Handy for tests, one-off queries, and places where you want to build a node
/// from runtime-owned strings. It is **not** allocation-free: each
/// [`OwnedNode::new`] allocates a `String`, and [`StyledNode::classes`]
/// allocates one `Vec` per call. For the per-frame draw loop, use [`NodeRef`].
#[derive(Debug, Clone)]
pub struct OwnedNode {
    pub type_name: String,
    pub id: Option<String>,
    pub classes: Vec<String>,
    pub state: State,
    pub position: Position,
}

impl OwnedNode {
    pub fn new(type_name: impl Into<String>) -> Self {
        Self {
            type_name: type_name.into(),
            id: None,
            classes: Vec::new(),
            state: State::empty(),
            position: Position::default(),
        }
    }
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }
    pub fn with_classes(mut self, classes: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.classes = classes.into_iter().map(Into::into).collect();
        self
    }
    pub fn with_state(mut self, state: State) -> Self {
        self.state = state;
        self
    }
    /// Set the sibling position. Mirrors [`NodeRef::position`].
    pub fn with_position(mut self, position: Position) -> Self {
        self.position = position;
        self
    }
}

impl StyledNode for OwnedNode {
    fn type_name(&self) -> &str {
        &self.type_name
    }
    fn id(&self) -> Option<&str> {
        self.id.as_deref()
    }
    fn classes(&self) -> Classes<'_> {
        // One Vec allocation per call — acceptable for OwnedNode (not the hot
        // path). The draw loop uses NodeRef to avoid even this.
        Classes::from_vec(self.classes.iter().map(String::as_str).collect())
    }
    fn state(&self) -> State {
        self.state
    }
    fn position(&self) -> Position {
        self.position.clone()
    }
}

/// A borrowed node: `type_name`, `id`, and `classes` are all `&'a str` /
/// `&'a [&'a str]` borrows, so construction is **zero-allocation** (a
/// compile-time guarantee when the source data is `&'static`).
///
/// Use this in the draw loop:
///
/// ```rust,ignore
/// let node = NodeRef::new("Button").classes(&["primary"]).state(State::focus());
/// let computed = sheet.compute(&node, None);
/// ```
///
/// Builder methods mirror [`OwnedNode`]'s (`with_*`) for easy migration, plus
/// short `classes`/`state` setters.
pub struct NodeRef<'a> {
    type_name: &'a str,
    id: Option<&'a str>,
    classes: &'a [&'a str],
    state: State,
    position: Position,
}

impl<'a> NodeRef<'a> {
    /// Borrow `type_name`. Zero-allocation.
    pub fn new(type_name: &'a str) -> Self {
        Self {
            type_name,
            id: None,
            classes: &[],
            state: State::empty(),
            position: Position::default(),
        }
    }

    /// Set the id (borrowed). Zero-allocation.
    pub fn id(mut self, id: &'a str) -> Self {
        self.id = Some(id);
        self
    }
    /// Alias for [`id`](Self::id), matching [`OwnedNode::with_id`].
    pub fn with_id(self, id: &'a str) -> Self {
        self.id(id)
    }

    /// Set the class list (borrowed slice). Zero-allocation.
    pub fn classes(mut self, classes: &'a [&'a str]) -> Self {
        self.classes = classes;
        self
    }
    /// Alias for [`classes`](Self::classes), matching [`OwnedNode::with_classes`].
    pub fn with_classes(self, classes: &'a [&'a str]) -> Self {
        self.classes(classes)
    }

    /// Set the pseudo-class state. Zero-allocation.
    pub fn state(mut self, state: State) -> Self {
        self.state = state;
        self
    }
    /// Alias for [`state`](Self::state), matching [`OwnedNode::with_state`].
    pub fn with_state(self, state: State) -> Self {
        self.state(state)
    }

    /// Set the sibling position. Rarely needed in the draw loop.
    pub fn position(mut self, position: Position) -> Self {
        self.position = position;
        self
    }
}

impl<'a> StyledNode for NodeRef<'a> {
    fn type_name(&self) -> &str {
        self.type_name
    }
    fn id(&self) -> Option<&str> {
        self.id
    }
    fn classes(&self) -> Classes<'_> {
        // Zero-allocation: borrow the slice directly.
        Classes::from_slice(self.classes)
    }
    fn state(&self) -> State {
        self.state
    }
    fn position(&self) -> Position {
        self.position.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classes_slice_contains() {
        let c = Classes::from_slice(&["a", "b"]);
        assert!(c.contains("b"));
        assert!(!c.contains("c"));
        assert_eq!(c.len(), 2);
        assert!(!c.is_empty());
        assert_eq!(c.as_slice(), &["a", "b"]);
    }

    #[test]
    fn classes_owned_contains() {
        let c = Classes::from_vec(vec!["x", "y"]);
        assert!(c.contains("x"));
        assert!(!c.contains("z"));
        assert_eq!(c.len(), 2);
    }

    #[test]
    fn classes_empty() {
        let c = Classes::from_slice(&[]);
        assert!(c.is_empty());
        assert_eq!(c.len(), 0);
    }

    #[test]
    fn position_default_and_new_leave_of_type_zero() {
        // Default and the two-arg constructor both leave the of-type fields at
        // 0 (unknown) so the forward-looking of-type pseudos never match unless
        // the host explicitly supplies them.
        let d = Position::default();
        assert_eq!(d.of_type_index, 0);
        assert_eq!(d.of_type_count, 0);

        let n = Position::new(2, 5);
        assert_eq!(n.index, 2);
        assert_eq!(n.sibling_count, 5);
        assert_eq!(n.of_type_index, 0);
        assert_eq!(n.of_type_count, 0);
    }

    #[test]
    fn position_with_of_type_sets_fields() {
        let p = Position::new(1, 4).with_of_type(2, 3);
        assert_eq!(p.index, 1);
        assert_eq!(p.sibling_count, 4);
        assert_eq!(p.of_type_index, 2);
        assert_eq!(p.of_type_count, 3);

        // Explicitly setting to 0/0 means "unknown" again.
        let cleared = p.with_of_type(0, 0);
        assert_eq!(cleared.of_type_index, 0);
        assert_eq!(cleared.of_type_count, 0);
    }
}