quadraui 0.1.3

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Shared primitive types used across widgets: colours, icons, styled text,
//! widget identifiers, modifier flags, and tree paths.
//!
//! Design invariants (from `docs/UI_CRATE_DESIGN.md` §10, plugin-driven UI):
//! - Every type is owned (no `&'static` or borrowed data in public API).
//! - Every type is `Serialize + Deserialize` so Lua plugins can produce them
//!   via JSON → Rust struct conversion.
//! - No Rust closures cross the Rust/plugin boundary; events are plain data.

use serde::{Deserialize, Serialize};

/// RGBA colour, 0-255 each channel.
///
/// Matches the shape of `vimcode::Color` conceptually. Adapter code in apps
/// (e.g. vimcode) maps app-specific colour types to this.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Color {
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b, a: 255 }
    }

    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    /// Parse `"#rrggbb"` or `"#rrggbbaa"`. Returns `None` on malformed input.
    pub fn from_hex(s: &str) -> Option<Self> {
        let s = s.strip_prefix('#')?;
        // Every byte must be an ASCII hex digit before we index into `s` by
        // byte offset below — this also guarantees `s` is all-ASCII, so
        // `s.len()` (bytes) matches char count and every `&s[i..j]` slice
        // below lands on a char boundary. A non-ASCII (or otherwise
        // non-hex) input like "#\u{20ac}abc" is rejected here instead of
        // panicking on the slice.
        if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
            return None;
        }
        let (r, g, b, a) = match s.len() {
            6 => (
                u8::from_str_radix(&s[0..2], 16).ok()?,
                u8::from_str_radix(&s[2..4], 16).ok()?,
                u8::from_str_radix(&s[4..6], 16).ok()?,
                255,
            ),
            8 => (
                u8::from_str_radix(&s[0..2], 16).ok()?,
                u8::from_str_radix(&s[2..4], 16).ok()?,
                u8::from_str_radix(&s[4..6], 16).ok()?,
                u8::from_str_radix(&s[6..8], 16).ok()?,
            ),
            _ => return None,
        };
        Some(Self { r, g, b, a })
    }

    /// Parse `"#rrggbbaa"` and alpha-composite it over `bg`, discarding the
    /// alpha channel in the result (`a` is always `255`). Falls back to
    /// [`Self::from_hex`] — including its 6-digit-only, no-alpha shape —
    /// when `s` carries no alpha channel, so this is a strict superset of
    /// `from_hex` for callers that always have a background to composite
    /// against. Returns `None` on malformed input, same rules as
    /// `from_hex`.
    ///
    /// Lifted from vimcode's `render::Color::try_from_hex_over` (#775),
    /// where it exists because VS Code theme JSON commonly expresses
    /// translucent overlay colours (`editor.lineHighlightBackground`,
    /// diff backgrounds, bracket-match highlights) as `#rrggbbaa` meant
    /// to be composited over the editor background — a rasteriser that
    /// just took the raw (translucent) colour at face value would ignore
    /// the intended blend.
    pub fn try_from_hex_over(s: &str, bg: Self) -> Option<Self> {
        let stripped = s.strip_prefix('#')?;
        if stripped.len() != 8 {
            return Self::from_hex(s);
        }
        // Same ASCII-hex-digit guard as `from_hex`, for the same reason:
        // guarantees byte offsets below land on char boundaries.
        if !stripped.bytes().all(|b| b.is_ascii_hexdigit()) {
            return None;
        }
        let r = u8::from_str_radix(&stripped[0..2], 16).ok()?;
        let g = u8::from_str_radix(&stripped[2..4], 16).ok()?;
        let b = u8::from_str_radix(&stripped[4..6], 16).ok()?;
        let a = u8::from_str_radix(&stripped[6..8], 16).ok()?;
        let alpha = a as f64 / 255.0;
        let blend = |fg: u8, bg: u8| -> u8 {
            (fg as f64 * alpha + bg as f64 * (1.0 - alpha)).round() as u8
        };
        Some(Self {
            r: blend(r, bg.r),
            g: blend(g, bg.g),
            b: blend(b, bg.b),
            a: 255,
        })
    }

    /// Linearly interpolate each channel toward white by `amount`
    /// (clamped to `[0.0, 1.0]`). Used by primitives that derive a
    /// hover/highlight tint from a base background colour.
    pub fn lighten(self, amount: f64) -> Self {
        let f = amount.clamp(0.0, 1.0);
        Self {
            r: (self.r as f64 + (255.0 - self.r as f64) * f) as u8,
            g: (self.g as f64 + (255.0 - self.g as f64) * f) as u8,
            b: (self.b as f64 + (255.0 - self.b as f64) * f) as u8,
            a: self.a,
        }
    }

    /// Linearly interpolate each channel toward black by `amount`
    /// (clamped to `[0.0, 1.0]`). Symmetric counterpart of [`Self::lighten`].
    pub fn darken(self, amount: f64) -> Self {
        let f = amount.clamp(0.0, 1.0);
        Self {
            r: (self.r as f64 * (1.0 - f)) as u8,
            g: (self.g as f64 * (1.0 - f)) as u8,
            b: (self.b as f64 * (1.0 - f)) as u8,
            a: self.a,
        }
    }

    /// Return this colour with the alpha channel scaled to `alpha`
    /// (clamped to `[0.0, 1.0]`) on the `0..=255` byte scale, leaving
    /// `r`/`g`/`b` untouched.
    ///
    /// Consolidates five copy-pasted `with_alpha` helpers (quadraui#1071)
    /// that used to live in `macos/{multi_section_view,palette,
    /// rich_text_popup}.rs` and `primitives/{scrollbar,drop_zone}.rs` —
    /// all four expressions were mathematically equivalent (scaling by
    /// 255 and clamping to `0.0..=255.0` gives the same rounded byte as
    /// clamping the input to `0.0..=1.0` first and then scaling), just
    /// written with the clamp on either side of the multiply.
    pub fn with_alpha(self, alpha: f64) -> Self {
        Self {
            a: (255.0 * alpha.clamp(0.0, 1.0)).round() as u8,
            ..self
        }
    }

    /// Alpha-blend `over` on top of `self` at `alpha` (clamped to
    /// `[0.0, 1.0]`), discarding both inputs' own alpha channels — the
    /// result is always fully opaque (`a: 255`).
    ///
    /// Used by rasterisers on backends whose fill/line primitives don't
    /// honour `Color::a`, as a CPU-side alpha pre-mix. Consolidates the
    /// byte-identical `win::text::blend` and
    /// `primitives::chart::native_surface_paint::blend` free functions
    /// (quadraui#1071).
    pub fn blend(self, over: Self, alpha: f64) -> Self {
        let alpha = alpha.clamp(0.0, 1.0);
        let mix =
            |b: u8, o: u8| -> u8 { (b as f64 * (1.0 - alpha) + o as f64 * alpha).round() as u8 };
        Self::rgb(
            mix(self.r, over.r),
            mix(self.g, over.g),
            mix(self.b, over.b),
        )
    }
}

/// A contiguous run of text sharing a single style.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyledSpan {
    pub text: String,
    pub fg: Option<Color>,
    pub bg: Option<Color>,
    #[serde(default)]
    pub bold: bool,
    #[serde(default)]
    pub italic: bool,
    #[serde(default)]
    pub underline: bool,
}

impl StyledSpan {
    pub fn plain(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            fg: None,
            bg: None,
            bold: false,
            italic: false,
            underline: false,
        }
    }

    pub fn with_fg(text: impl Into<String>, fg: Color) -> Self {
        Self {
            text: text.into(),
            fg: Some(fg),
            bg: None,
            bold: false,
            italic: false,
            underline: false,
        }
    }
}

/// A sequence of styled spans rendered inline on one line.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyledText {
    pub spans: Vec<StyledSpan>,
}

impl StyledText {
    pub fn plain(text: impl Into<String>) -> Self {
        Self {
            spans: vec![StyledSpan::plain(text)],
        }
    }

    pub fn colored(text: impl Into<String>, fg: Color) -> Self {
        Self {
            spans: vec![StyledSpan::with_fg(text, fg)],
        }
    }

    /// Terminal display width of the concatenated span text, in cells.
    ///
    /// Sums each span's [`crate::text_util::display_width`] — CJK and
    /// wide-emoji glyphs count as 2, combining marks count as 0, so this
    /// is not the same as `chars().count()`. Before #471, this counted
    /// `chars()` directly: the #206 unicode-width fix landed only in the
    /// `tui`-feature-gated rasteriser cell logic and never reached this
    /// core type, so every layout site measuring a `StyledText` with
    /// non-ASCII content (TUI `Form`, `MultiSectionView`, GTK
    /// `sidebar_system`) mis-measured by up to 2x.
    pub fn visible_width(&self) -> usize {
        self.spans
            .iter()
            .map(|s| crate::text_util::display_width(&s.text))
            .sum()
    }
}

/// Icon reference. Each app supplies both the glyph (for icon fonts) and
/// an ASCII/Unicode fallback (for TUI or when the icon font is unavailable).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Icon {
    /// Nerd Font / icon-font glyph string.
    pub glyph: String,
    /// ASCII or basic-Unicode fallback used when `glyph` cannot render.
    pub fallback: String,
    /// Glyph colour. `None` (the default from `Icon::new` / the `From`
    /// impls) paints the icon in the surrounding row's default foreground,
    /// byte-identical to pre-#1057 rendering. `Some` matches
    /// [`crate::TabIcon`]'s always-coloured-glyph behaviour (issue #1057):
    /// every backend's tree renderer paints both the Nerd Font glyph and
    /// its ASCII fallback in this colour when set.
    #[serde(default)]
    pub color: Option<Color>,
}

impl Icon {
    pub fn new(glyph: impl Into<String>, fallback: impl Into<String>) -> Self {
        Self {
            glyph: glyph.into(),
            fallback: fallback.into(),
            color: None,
        }
    }

    /// Attach a glyph colour (#1057). Painted by tree renderers in place of
    /// the row's default foreground; see the `color` field docs.
    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }
}

/// Collapse a bare string into an [`Icon`] with `glyph == fallback` — the
/// common case for a caller that has one glyph and doesn't distinguish a
/// Nerd Font variant from its plain-text fallback (issue #683). Keeps the
/// `.into()` idiom working at call sites that previously produced a
/// `String` for an icon field.
impl From<&str> for Icon {
    fn from(s: &str) -> Self {
        Self::new(s, s)
    }
}

/// See [`impl From<&str> for Icon`] — same collapse, owned-`String` input.
impl From<String> for Icon {
    fn from(s: String) -> Self {
        Self::new(s.clone(), s)
    }
}

/// Stable identifier for a widget across frames.
///
/// Owned `String` so plugins can generate IDs at runtime. Apps should
/// namespace IDs (e.g. `"plugin:my-ext:main-form"`) to avoid collisions
/// with core widget IDs.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WidgetId(pub String);

impl WidgetId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

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

/// Keyboard modifier state carried alongside input events.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Modifiers {
    #[serde(default)]
    pub shift: bool,
    #[serde(default)]
    pub ctrl: bool,
    #[serde(default)]
    pub alt: bool,
    #[serde(default)]
    pub cmd: bool,
}

/// Path to a row in a tree-structured widget.
///
/// `vec![]` is the root; `vec![3, 1]` is the second child of the fourth
/// top-level row. Indices are `u16` to fit comfortably in small fixed-size
/// arrays while still accommodating trees with thousands of siblings.
pub type TreePath = Vec<u16>;

/// Selection behaviour for row-oriented widgets (`TreeView`, `ListView`,
/// `DataTable`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum SelectionMode {
    /// Rows cannot be selected.
    None,
    /// At most one row is selected at a time.
    #[default]
    Single,
    /// Multiple rows may be selected (shift/ctrl click).
    Multi,
}

/// Optional visual decoration applied to a row beyond its text colour.
///
/// Backends map each variant to an appropriate visual treatment. For row
/// widgets like `TreeView`, `Header` typically gets a distinct background
/// (section-header styling); `Muted` dims the foreground; `Error` /
/// `Warning` override the foreground with theme error/warning colours;
/// `Modified` implies italic but otherwise normal colouring.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum Decoration {
    /// Rendered with default foreground and background.
    #[default]
    Normal,
    /// Section-header styling: distinct (typically darker or accent) background,
    /// often with bold text. Use for rows that group others rather than
    /// represent a leaf entity. Row tree-hierarchy status (`is_expanded`
    /// Some vs. None) is orthogonal: not all branches are headers, and a
    /// leaf row can be a header.
    Header,
    /// Dimmed (e.g. gitignored file, stale git log entry).
    Muted,
    /// Red / error-toned (e.g. lint error, merge conflict).
    Error,
    /// Amber / warning-toned (e.g. unsaved changes badge).
    Warning,
    /// Italicised, typically unchanged foreground colour.
    Modified,
}

/// Right-aligned status indicator on a row: short text plus optional
/// foreground/background colouring. Used by `TreeView` / `ListView` /
/// `DataTable` for git-status letters, item counts, conflict markers, etc.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Badge {
    pub text: String,
    pub fg: Option<Color>,
    pub bg: Option<Color>,
}

impl Badge {
    pub fn plain(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            fg: None,
            bg: None,
        }
    }

    pub fn colored(text: impl Into<String>, fg: Color) -> Self {
        Self {
            text: text.into(),
            fg: Some(fg),
            bg: None,
        }
    }
}

/// Visual style configuration for a `TreeView`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TreeStyle {
    /// Cells / pixels per visual indent level.
    pub indent: u16,
    /// Draw expand/collapse chevrons on branches.
    pub show_chevrons: bool,
    /// Chevron drawn for an expanded branch. Painted verbatim on TUI.
    /// On GTK / macOS / Win-GUI, the *default* value (`"▾"`) is instead
    /// painted as a sharper codicon glyph
    /// (`crate::codicon::CHEVRON_DOWN`); any non-default override an
    /// app sets here is still honoured and painted verbatim on every
    /// backend, GUI included.
    pub chevron_expanded: String,
    /// Chevron drawn for a collapsed branch. Painted verbatim on TUI.
    /// On GTK / macOS / Win-GUI, the *default* value (`"▸"`) is instead
    /// painted as a sharper codicon glyph
    /// (`crate::codicon::CHEVRON_RIGHT`); any non-default override an
    /// app sets here is still honoured and painted verbatim on every
    /// backend, GUI included.
    pub chevron_collapsed: String,
    /// Host override for non-header row height, in the backend's native
    /// unit (pixels for GTK / macOS / Win-GUI). `None` (the default)
    /// keeps today's behaviour: GUI backends derive the row pitch from
    /// the editor `line_height` (`line_height * 1.4` for leaves and
    /// branches); TUI rows stay a fixed 1 cell regardless — a terminal
    /// cell can't be subdivided, so TUI ignores this field entirely.
    ///
    /// `Some(h)` pins leaf/branch rows to `h`, independent of editor
    /// font size — e.g. VS Code's fixed 22px `list.rowHeight` (#623).
    /// Header rows (`Decoration::Header`) are unaffected; they stay
    /// pitched off `line_height`, since #623 only concerns item rows.
    ///
    /// Integral because both GUI rasterisers `.round()` the row pitch
    /// to whole native units before painting — a fractional override
    /// could not survive to the frame anyway.
    ///
    /// Both `gtk_tree_layout` / `mac_tree_layout` (hit-test) and
    /// `draw_tree` (paint) read this same field, so paint and hit-test
    /// stay in sync by construction — the measure/paint desync class
    /// documented in #654 does not reappear here.
    #[serde(default)]
    pub row_height: Option<u16>,
}

impl Default for TreeStyle {
    fn default() -> Self {
        Self {
            indent: 2,
            show_chevrons: true,
            chevron_expanded: "▾".into(),
            chevron_collapsed: "▸".into(),
            row_height: None,
        }
    }
}

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

    #[test]
    fn with_alpha_scales_a_leaves_rgb_untouched() {
        let c = Color::rgb(10, 20, 30).with_alpha(0.5);
        assert_eq!((c.r, c.g, c.b, c.a), (10, 20, 30, 128));
    }

    #[test]
    fn with_alpha_clamps_out_of_range_input() {
        assert_eq!(Color::rgb(1, 2, 3).with_alpha(-1.0).a, 0);
        assert_eq!(Color::rgb(1, 2, 3).with_alpha(2.0).a, 255);
    }

    #[test]
    fn blend_zero_alpha_is_base_one_alpha_is_over() {
        let base = Color::rgb(0, 0, 0);
        let over = Color::rgb(200, 100, 50);
        assert_eq!(base.blend(over, 0.0), Color::rgb(0, 0, 0));
        assert_eq!(base.blend(over, 1.0), Color::rgb(200, 100, 50));
    }

    #[test]
    fn blend_midpoint_averages_channels_and_is_opaque() {
        let base = Color::rgba(0, 0, 0, 10);
        let over = Color::rgba(200, 100, 50, 20);
        let mixed = base.blend(over, 0.5);
        assert_eq!((mixed.r, mixed.g, mixed.b, mixed.a), (100, 50, 25, 255));
    }

    #[test]
    fn from_hex_parses_rgb() {
        assert_eq!(
            Color::from_hex("#ff0080"),
            Some(Color::rgb(0xff, 0x00, 0x80))
        );
    }

    #[test]
    fn from_hex_parses_rgba() {
        assert_eq!(
            Color::from_hex("#ff008040"),
            Some(Color::rgba(0xff, 0x00, 0x80, 0x40))
        );
    }

    #[test]
    fn from_hex_rejects_missing_prefix() {
        assert_eq!(Color::from_hex("ff0080"), None);
    }

    #[test]
    fn from_hex_rejects_wrong_length() {
        assert_eq!(Color::from_hex("#ff008"), None);
    }

    #[test]
    fn from_hex_rejects_non_hex_ascii() {
        assert_eq!(Color::from_hex("#zzzzzz"), None);
    }

    /// Regression for issue #503: a multibyte char inside the hex digits
    /// used to make `s.len()` (byte length) satisfy the `6`/`8` length
    /// check while `&s[0..2]` etc. sliced mid-character, panicking
    /// instead of returning `None` as the doc comment promises.
    #[test]
    fn from_hex_multibyte_char_returns_none_instead_of_panicking() {
        // "\u{20ac}abc" ('€' + "abc") is 3 + 3 = 6 bytes, matching the RGB
        // length branch by byte count alone.
        assert_eq!(Color::from_hex("#\u{20ac}abc"), None);
    }

    #[test]
    fn visible_width_ascii_matches_char_count() {
        assert_eq!(StyledText::plain("hello").visible_width(), 5);
        assert_eq!(StyledText::plain("").visible_width(), 0);
    }

    /// Regression for issue #471: CJK/emoji glyphs occupy two terminal
    /// cells each, so `visible_width` must not equal `chars().count()`
    /// for them.
    #[test]
    fn visible_width_cjk_counts_double_width() {
        let text = StyledText::plain("日本語");
        assert_eq!(text.visible_width(), 6);
        assert_ne!(text.visible_width(), text.spans[0].text.chars().count());
    }

    #[test]
    fn visible_width_sums_across_spans() {
        let text = StyledText {
            spans: vec![
                StyledSpan::plain("中"),
                StyledSpan::plain("a"),
                StyledSpan::plain("文"),
            ],
        };
        // "中" (2) + "a" (1) + "文" (2) = 5, vs. a char count of 3.
        assert_eq!(text.visible_width(), 5);
    }

    #[test]
    fn visible_width_combining_mark_counts_zero() {
        // "e" + U+0301 COMBINING ACUTE ACCENT renders as one visual
        // column even though it is two `char`s.
        let text = StyledText::plain("e\u{0301}");
        assert_eq!(text.visible_width(), 1);
    }

    #[test]
    fn color_from_hex_rgb() {
        let c = Color::from_hex("#1a2b3c").unwrap();
        assert_eq!(c, Color::rgb(0x1a, 0x2b, 0x3c));
    }

    #[test]
    fn color_from_hex_rgba() {
        let c = Color::from_hex("#1a2b3c80").unwrap();
        assert_eq!(c, Color::rgba(0x1a, 0x2b, 0x3c, 0x80));
    }

    #[test]
    fn color_from_hex_invalid() {
        assert!(Color::from_hex("not a hex").is_none());
        assert!(Color::from_hex("#xyz").is_none());
        assert!(Color::from_hex("#12345").is_none()); // wrong length
    }

    #[test]
    fn try_from_hex_over_blends_alpha_against_background() {
        let bg = Color::rgb(0, 0, 0);
        // Full alpha (`ff`) over black should equal the opaque colour.
        let c = Color::try_from_hex_over("#ff008040", bg).unwrap();
        // alpha byte 0x40 = 64/255 ≈ 0.251
        let alpha = 0x40 as f64 / 255.0;
        let blend = |fg: u8| -> u8 { (fg as f64 * alpha).round() as u8 };
        assert_eq!(c, Color::rgba(blend(0xff), blend(0x00), blend(0x80), 255));
    }

    #[test]
    fn try_from_hex_over_full_alpha_ignores_background() {
        let bg = Color::rgb(10, 20, 30);
        let c = Color::try_from_hex_over("#ff0080ff", bg).unwrap();
        assert_eq!(c, Color::rgba(0xff, 0x00, 0x80, 255));
    }

    #[test]
    fn try_from_hex_over_zero_alpha_equals_background() {
        let bg = Color::rgb(10, 20, 30);
        let c = Color::try_from_hex_over("#ff008000", bg).unwrap();
        assert_eq!(c, Color::rgba(10, 20, 30, 255));
    }

    #[test]
    fn try_from_hex_over_falls_back_to_from_hex_without_alpha() {
        let bg = Color::rgb(10, 20, 30);
        assert_eq!(
            Color::try_from_hex_over("#1a2b3c", bg),
            Color::from_hex("#1a2b3c")
        );
    }

    #[test]
    fn try_from_hex_over_rejects_malformed_input() {
        let bg = Color::rgb(0, 0, 0);
        assert_eq!(Color::try_from_hex_over("not a hex", bg), None);
        assert_eq!(Color::try_from_hex_over("#zzzzzzzz", bg), None);
        assert_eq!(Color::try_from_hex_over("#12345", bg), None);
    }

    #[test]
    fn widget_id_roundtrip() {
        let id = WidgetId::new("sc-tree");
        assert_eq!(id.as_str(), "sc-tree");
        let id2: WidgetId = "sc-tree".into();
        assert_eq!(id, id2);
    }

    #[test]
    fn styled_text_visible_width() {
        let text = StyledText {
            spans: vec![
                StyledSpan::plain("hello "),
                StyledSpan::with_fg("world", Color::rgb(255, 0, 0)),
            ],
        };
        assert_eq!(text.visible_width(), 11);
    }
}