elicit_ui 0.11.1

Typestate-based verified UI system using AccessKit as universal IR
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Cross-backend text IR — the linebender half of the `elicit_ui` IR.
//!
//! These types form the portable text intermediate representation used
//! throughout the `elicit_*` pipeline.  They are intentionally independent
//! of any concrete frontend (ratatui, egui, leptos) and convert *to* the
//! concrete backend types inside the corresponding bridge crates.
//!
//! # Linebender integration
//!
//! - [`UiColor`] converts to [`peniko::Color`] via `From<UiColor>`.
//! - [`FontWeight`] converts to [`parley::style::FontWeight`].
//! - [`FontStyle`] converts to [`parley::style::FontStyle`].
//!
//! # Usage
//!
//! ```rust
//! use elicit_ui::text::{ParagraphText, RichText, TextLine, TextSpan, TextStyle, UiColor, TextModifier};
//!
//! let cursor_style = TextStyle {
//!     fg: None,
//!     bg: None,
//!     modifiers: vec![TextModifier::Reversed, TextModifier::Bold],
//! };
//! let span = TextSpan { content: " X ".to_string(), style: Some(cursor_style) };
//! let line = TextLine { spans: vec![span], style: None, alignment: None };
//! let rich = RichText { lines: vec![line], style: None, alignment: None };
//! let para = ParagraphText::Rich(rich);
//! ```

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Colour
// ---------------------------------------------------------------------------

/// Cross-backend colour.
///
/// Covers the full ANSI palette plus 24-bit RGB and 256-colour indexed modes.
/// Converts to [`peniko::Color`] via `From<UiColor>`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type")]
pub enum UiColor {
    /// Reset to terminal / theme default.
    Reset,
    /// Standard ANSI black.
    Black,
    /// Standard ANSI red.
    Red,
    /// Standard ANSI green.
    Green,
    /// Standard ANSI yellow.
    Yellow,
    /// Standard ANSI blue.
    Blue,
    /// Standard ANSI magenta.
    Magenta,
    /// Standard ANSI cyan.
    Cyan,
    /// Standard ANSI white.
    White,
    /// Dark gray (bright black).
    DarkGray,
    /// Light (bright) red.
    LightRed,
    /// Light (bright) green.
    LightGreen,
    /// Light (bright) yellow.
    LightYellow,
    /// Light (bright) blue.
    LightBlue,
    /// Light (bright) magenta.
    LightMagenta,
    /// Light (bright) cyan.
    LightCyan,
    /// Bright white / gray.
    Gray,
    /// 24-bit RGB colour.
    Rgb {
        /// Red channel (0–255).
        r: u8,
        /// Green channel (0–255).
        g: u8,
        /// Blue channel (0–255).
        b: u8,
    },
    /// 256-colour palette index.
    Indexed {
        /// Palette index (0–255).
        index: u8,
    },
}

impl From<UiColor> for peniko::Color {
    fn from(c: UiColor) -> Self {
        // VS Code terminal palette (reference sRGB values).
        match c {
            UiColor::Reset => peniko::Color::from_rgba8(0, 0, 0, 0),
            UiColor::Black => peniko::Color::from_rgb8(12, 12, 12),
            UiColor::Red => peniko::Color::from_rgb8(197, 15, 31),
            UiColor::Green => peniko::Color::from_rgb8(19, 161, 14),
            UiColor::Yellow => peniko::Color::from_rgb8(193, 156, 0),
            UiColor::Blue => peniko::Color::from_rgb8(0, 55, 218),
            UiColor::Magenta => peniko::Color::from_rgb8(136, 23, 152),
            UiColor::Cyan => peniko::Color::from_rgb8(58, 150, 221),
            UiColor::White => peniko::Color::from_rgb8(204, 204, 204),
            UiColor::DarkGray => peniko::Color::from_rgb8(118, 118, 118),
            UiColor::LightRed => peniko::Color::from_rgb8(231, 72, 86),
            UiColor::LightGreen => peniko::Color::from_rgb8(22, 198, 12),
            UiColor::LightYellow => peniko::Color::from_rgb8(249, 241, 165),
            UiColor::LightBlue => peniko::Color::from_rgb8(59, 120, 255),
            UiColor::LightMagenta => peniko::Color::from_rgb8(180, 0, 158),
            UiColor::LightCyan => peniko::Color::from_rgb8(97, 214, 214),
            UiColor::Gray => peniko::Color::from_rgb8(242, 242, 242),
            UiColor::Rgb { r, g, b } => peniko::Color::from_rgb8(r, g, b),
            UiColor::Indexed { index } => ansi256_to_peniko(index),
        }
    }
}

/// Approximate ANSI 256-colour index to sRGB.
fn ansi256_to_peniko(idx: u8) -> peniko::Color {
    match idx {
        // 0-15: standard ANSI colours (use the named variants above)
        0 => peniko::Color::from_rgb8(12, 12, 12),
        1 => peniko::Color::from_rgb8(197, 15, 31),
        2 => peniko::Color::from_rgb8(19, 161, 14),
        3 => peniko::Color::from_rgb8(193, 156, 0),
        4 => peniko::Color::from_rgb8(0, 55, 218),
        5 => peniko::Color::from_rgb8(136, 23, 152),
        6 => peniko::Color::from_rgb8(58, 150, 221),
        7 => peniko::Color::from_rgb8(204, 204, 204),
        8 => peniko::Color::from_rgb8(118, 118, 118),
        9 => peniko::Color::from_rgb8(231, 72, 86),
        10 => peniko::Color::from_rgb8(22, 198, 12),
        11 => peniko::Color::from_rgb8(249, 241, 165),
        12 => peniko::Color::from_rgb8(59, 120, 255),
        13 => peniko::Color::from_rgb8(180, 0, 158),
        14 => peniko::Color::from_rgb8(97, 214, 214),
        15 => peniko::Color::from_rgb8(242, 242, 242),
        // 16-231: 6×6×6 colour cube
        16..=231 => {
            let n = idx - 16;
            let b = n % 6;
            let g = (n / 6) % 6;
            let r = n / 36;
            let channel = |v: u8| if v == 0 { 0 } else { 55 + v * 40 };
            peniko::Color::from_rgb8(channel(r), channel(g), channel(b))
        }
        // 232-255: greyscale ramp
        232..=255 => {
            let v = 8 + (idx - 232) * 10;
            peniko::Color::from_rgb8(v, v, v)
        }
    }
}

// ---------------------------------------------------------------------------
// Text modifiers
// ---------------------------------------------------------------------------

/// Text rendering attribute.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum TextModifier {
    /// Bold text.
    Bold,
    /// Dim / faint text.
    Dim,
    /// Italic text.
    Italic,
    /// Underlined text.
    Underlined,
    /// Slow blink.
    SlowBlink,
    /// Rapid blink.
    RapidBlink,
    /// Reversed foreground / background.
    Reversed,
    /// Hidden text.
    Hidden,
    /// Crossed-out (strikethrough) text.
    CrossedOut,
}

// ---------------------------------------------------------------------------
// Font weight
// ---------------------------------------------------------------------------

/// Portable font weight (matches `parley::style::FontWeight`).
///
/// Converts to `parley::style::FontWeight` via `From<FontWeight>`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct FontWeight(pub f32);

impl FontWeight {
    /// 100 — Thin.
    pub const THIN: Self = Self(100.0);
    /// 200 — Extra-light.
    pub const EXTRA_LIGHT: Self = Self(200.0);
    /// 300 — Light.
    pub const LIGHT: Self = Self(300.0);
    /// 400 — Normal / Regular.
    pub const NORMAL: Self = Self(400.0);
    /// 500 — Medium.
    pub const MEDIUM: Self = Self(500.0);
    /// 600 — Semi-bold.
    pub const SEMI_BOLD: Self = Self(600.0);
    /// 700 — Bold.
    pub const BOLD: Self = Self(700.0);
    /// 800 — Extra-bold.
    pub const EXTRA_BOLD: Self = Self(800.0);
    /// 900 — Black.
    pub const BLACK: Self = Self(900.0);
}

impl From<FontWeight> for parley::style::FontWeight {
    fn from(w: FontWeight) -> Self {
        Self::new(w.0)
    }
}

// ---------------------------------------------------------------------------
// Font style
// ---------------------------------------------------------------------------

/// Portable font style (matches `parley::style::FontStyle`).
///
/// Converts to `parley::style::FontStyle` via `From<FontStyle>`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
pub enum FontStyle {
    /// Upright text.
    Normal,
    /// Italic text.
    Italic,
    /// Oblique text with optional angle in degrees.
    Oblique(Option<f32>),
}

impl From<FontStyle> for parley::style::FontStyle {
    fn from(s: FontStyle) -> Self {
        match s {
            FontStyle::Normal => Self::Normal,
            FontStyle::Italic => Self::Italic,
            FontStyle::Oblique(angle) => Self::Oblique(angle),
        }
    }
}

// ---------------------------------------------------------------------------
// Text decoration
// ---------------------------------------------------------------------------

/// Text decoration attribute (for GUI frontends; complements [`TextModifier`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum TextDecoration {
    /// Underline.
    Underline,
    /// Strikethrough.
    Strikethrough,
    /// Overline.
    Overline,
}

// ---------------------------------------------------------------------------
// Style
// ---------------------------------------------------------------------------

/// Cross-backend text style.
///
/// Core fields (`fg`, `bg`, `modifiers`) are universally supported.
/// Extended fields (`font_weight`, `font_style`, `decorations`) are used by
/// GUI frontends (egui, wgpu) via the linebender bridge.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct TextStyle {
    /// Foreground colour.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fg: Option<UiColor>,
    /// Background colour.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bg: Option<UiColor>,
    /// Active text modifiers (bold, italic, reversed, etc.).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub modifiers: Vec<TextModifier>,
    /// Font weight override (GUI frontends only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font_weight: Option<FontWeight>,
    /// Font style override (GUI frontends only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font_style: Option<FontStyle>,
    /// Text decorations (GUI frontends only).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub decorations: Vec<TextDecoration>,
}

// ---------------------------------------------------------------------------
// Alignment
// ---------------------------------------------------------------------------

/// Text alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum TextAlign {
    /// Left-aligned.
    Left,
    /// Centred.
    Center,
    /// Right-aligned.
    Right,
}

// ---------------------------------------------------------------------------
// Span / Line / RichText
// ---------------------------------------------------------------------------

/// A styled run of text within a line.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct TextSpan {
    /// Span text content.
    pub content: String,
    /// Per-span style override.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<TextStyle>,
}

/// A line of styled spans.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct TextLine {
    /// Spans composing this line.
    pub spans: Vec<TextSpan>,
    /// Style applied to the whole line (merged with span styles).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<TextStyle>,
    /// Line alignment override.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alignment: Option<TextAlign>,
}

/// Multi-line rich text.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct RichText {
    /// Lines of text.
    pub lines: Vec<TextLine>,
    /// Style applied to the entire block.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<TextStyle>,
    /// Alignment for the entire block.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alignment: Option<TextAlign>,
}

// ---------------------------------------------------------------------------
// ParagraphText — the portable paragraph IR
// ---------------------------------------------------------------------------

/// Paragraph content: a plain string or richly-styled [`RichText`].
///
/// Serialises as a JSON string for [`ParagraphText::Plain`] or a JSON object
/// for [`ParagraphText::Rich`].  This asymmetry is intentional: existing
/// consumers that pass plain strings continue to work, while new consumers
/// can pass a [`RichText`] object for per-span styling.
///
/// # Examples
///
/// Plain text:
/// ```json
/// "Hello world"
/// ```
///
/// Rich text:
/// ```json
/// {"lines":[{"spans":[{"content":" X ","style":{"modifiers":["Reversed","Bold"]}}]}]}
/// ```
#[derive(Debug, Clone, PartialEq, JsonSchema)]
pub enum ParagraphText {
    /// Plain unstyled text.
    Plain(String),
    /// Multi-line text with per-span styling.
    Rich(RichText),
}

impl serde::Serialize for ParagraphText {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Plain(s) => s.serialize(serializer),
            Self::Rich(t) => t.serialize(serializer),
        }
    }
}

impl<'de> serde::Deserialize<'de> for ParagraphText {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = serde_json::Value::deserialize(deserializer)?;
        match value {
            serde_json::Value::String(s) => Ok(Self::Plain(s)),
            serde_json::Value::Object(_) => serde_json::from_value::<RichText>(value)
                .map(Self::Rich)
                .map_err(serde::de::Error::custom),
            other => Err(serde::de::Error::custom(format!(
                "expected string or object for ParagraphText, got {other}"
            ))),
        }
    }
}

impl ParagraphText {
    /// Returns all text content joined with newlines between lines.
    pub fn to_plain_string(&self) -> String {
        match self {
            Self::Plain(s) => s.clone(),
            Self::Rich(t) => t
                .lines
                .iter()
                .map(|l| {
                    l.spans
                        .iter()
                        .map(|s| s.content.as_str())
                        .collect::<String>()
                })
                .collect::<Vec<_>>()
                .join("\n"),
        }
    }
}

impl From<String> for ParagraphText {
    fn from(s: String) -> Self {
        Self::Plain(s)
    }
}

impl From<&str> for ParagraphText {
    fn from(s: &str) -> Self {
        Self::Plain(s.to_string())
    }
}

impl From<RichText> for ParagraphText {
    fn from(t: RichText) -> Self {
        Self::Rich(t)
    }
}