teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! IconWidget — a vector or raster icon rendered at a configurable size.
//!
//! Supports multiple source formats: programmatic `Path` (checkmarks,
//! chevrons, dots), SVG strings, PNG, static WebP, and animated WebP. Icons
//! default to **tintable** mode — the pixels are treated as an alpha mask
//! and multiplied by the widget's color property (defaults to
//! `TextRole::Primary`) so they follow theme switches automatically.
//! `IconMode::FullColor` preserves original pixel colors and is appropriate
//! for emoji-style graphics or brand logos.
//!
//! For arbitrary-aspect-ratio photos or artwork see
//! [`ImageWidget`](super::image_widget::ImageWidget).
//!
//! ## Accessibility
//!
//! Icons are decorative by default — they set no accessibility role and
//! announce nothing. The parent widget (e.g. `Button`, `IconButton`) is
//! responsible for the accessible label.
//!
//! ```rust
//! # use teksilo_widgets::primitives::icon_widget::{IconWidget, IconMode};
//! # use teksilo_tokens::TextRole;
//! let _check = IconWidget::checkmark(20.0);
//!
//! let _chevron = IconWidget::chevron_down(16.0)
//!     .color(TextRole::Primary)
//!     .follow_text_scale(false);
//! ```

use std::borrow::Cow;

use teksilo_canvas::svg::{SvgDrawOp, SvgIcon};
use teksilo_canvas::{
    AnimatedIcon, AnimatedQuadClass, Canvas, Path, PathCommand, Point, RasterIcon, Rect, Size,
    SizeProposal,
};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::animated_quad::{AnimatedQuadHandle, AnimatedQuadKind};
use teksilo_core::color_prop::ColorProp;
use teksilo_core::signal::Signal;
use teksilo_core::widget::{LayoutContext, PaintContext, Widget};
use teksilo_tokens::{Color, Easing, TextRole};

/// Whether an icon is rendered as a theme-tinted mask or in its original colors.
///
/// Applies to every source an [`IconWidget`] can hold — raster *and* SVG. For an
/// SVG the two modes select between the two representations the parser builds
/// (see [`teksilo_canvas::svg`]): [`Tintable`](Self::Tintable) draws the merged
/// silhouette in the widget's color, [`FullColor`](Self::FullColor) walks the
/// document-ordered ops and honours each shape's own fill / stroke / gradient.
///
/// The default is [`Tintable`](Self::Tintable), which is what a UI glyph wants —
/// it follows the theme into dark mode. Reach for
/// [`FullColor`](Self::FullColor) for artwork whose colors *are* the content: a
/// brand mark, a flag, a colored file-type badge. A `currentColor` shape inside
/// full-color artwork still takes the widget's color, so the two are mixable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IconMode {
    /// Treat as an alpha mask: tint the whole icon with the widget's color.
    Tintable,
    /// Render the icon's own colors; the widget color supplies `currentColor`
    /// and its alpha attenuates the result.
    FullColor,
}

/// The source data for an icon.
#[derive(Debug, Clone)]
enum IconSource {
    /// A vector path (SVG or programmatic).
    Path(Path),
    /// A parsed SVG icon — scaling deferred to paint time using display_size.
    Svg(SvgIcon),
    /// A decoded raster image (PNG or static WebP).
    /// `upload_pixels` holds the ready-to-upload data (alpha mask pre-applied for tintable).
    Raster {
        name: String,
        icon: RasterIcon,
        upload_pixels: Vec<u8>,
    },
    /// An animated image (animated WebP).
    /// `frame_upload_pixels` holds pre-computed pixels per frame — used
    /// by the legacy signal-based path (reduced-motion fallback and
    /// the static first-frame render). `sprite_atlas` is the shader
    /// path's pre-packed grid of all frames, built lazily on first
    /// build() when reduced-motion is off. `anim_handle` is the
    /// registry slot returned by `ctx.animated_quad` — set in pair
    /// with `sprite_atlas`, used at paint time.
    Animated {
        name: String,
        icon: AnimatedIcon,
        frame_upload_pixels: Vec<Vec<u8>>,
        /// Legacy signal-based frame index driver. `Some` only when
        /// shader pipeline is disabled (reduced-motion, atlas build
        /// failed, etc.); otherwise frame cycling runs shader-side.
        frame_signal: Option<Signal<f32>>,
        /// Sprite-atlas state for the shader pipeline. `Some` once
        /// `build()` has packed the frames into a grid.
        sprite_atlas: Option<SpriteAtlas>,
        /// Animated-quad handle returned by `ctx.animated_quad`.
        /// `Some` only when the shader path is active (paired with
        /// `sprite_atlas`).
        anim_handle: Option<AnimatedQuadHandle>,
    },
}

/// Packed frame-grid for an animated icon, prepared once per mount
/// and reused across every paint. The renderer uploads the atlas
/// pixels as a single texture; the shader samples the cell for the
/// current frame based on `AnimParams::phase` written by the tree.
#[derive(Debug, Clone)]
struct SpriteAtlas {
    /// Unique name under which the atlas is registered with
    /// `Canvas::ensure_image_registered` / the renderer's
    /// `ImageManager`.
    name: String,
    /// Full atlas pixels in RGBA row-major. `cols × frame_w` wide,
    /// `rows × frame_h` tall. Owned `Vec<u8>` so the widget can pass
    /// `Cow::Owned` to `ensure_image_registered` each paint without
    /// recomputing; uploaded once by the renderer's image manager.
    pixels: Vec<u8>,
    width: u32,
    height: u32,
    cols: u32,
    rows: u32,
}

/// A leaf widget that renders an icon from a path, SVG string, PNG, or WebP source.
pub struct IconWidget {
    source: IconSource,
    /// Design size: the coordinate space the path was created in.
    /// Used as the denominator when scaling the path to fit bounds.
    design_size: f32,
    /// Display size: what the icon reports for layout (size_that_fits).
    /// Defaults to `design_size` but can be overridden via `icon_size()`.
    display_size: f32,
    /// Fill/tint color. Defaults to [`TextRole::Primary`] so icons follow
    /// the surrounding text color across theme switches without binding.
    color: ColorProp,
    /// Rendering mode.
    mode: IconMode,
    /// When `true`, the reported size is multiplied by the global accessibility
    /// text scale (`ctx.text_scale`) so the icon grows alongside adjacent text.
    /// Off by default — most icons (toolbar glyphs, chevrons) have fixed
    /// footprints that must not inflate. Opt in via
    /// [`follow_text_scale`](Self::follow_text_scale); used by `SeverityBadge`
    /// so status glyphs track the text they sit beside.
    follow_text_scale: bool,
}

// Auto-generate unique names from data pointer for embedded resources.
// Compile-time data from include_bytes! has stable pointer addresses.
fn auto_name(prefix: &str, ptr: usize) -> String {
    format!("_icon_{prefix}_{ptr:x}")
}

/// Prepare raster pixels for upload: apply alpha mask for tintable mode,
/// or use original pixels for full-color mode.
fn prepare_pixels(icon: &RasterIcon, mode: IconMode) -> Vec<u8> {
    match mode {
        IconMode::Tintable => icon.to_alpha_mask().pixels().to_vec(),
        IconMode::FullColor => icon.pixels().to_vec(),
    }
}

impl IconWidget {
    /// Create an icon from a custom path. The path should be defined
    /// in coordinates matching the given size (e.g., 0..24 for size=24).
    pub fn from_path(path: Path, size: f32) -> Self {
        Self {
            source: IconSource::Path(path),
            design_size: size,
            display_size: size,
            color: ColorProp::TextRole(TextRole::Primary),
            mode: IconMode::Tintable,
            follow_text_scale: false,
        }
    }

    /// A checkmark icon (✓) at the given size.
    pub fn checkmark(size: f32) -> Self {
        let mut path = Path::new();
        let s = size;
        path.move_to(Point::new(s * 0.2, s * 0.5));
        path.line_to(Point::new(s * 0.4, s * 0.75));
        path.line_to(Point::new(s * 0.8, s * 0.25));
        Self::from_path(path, size)
    }

    /// A short horizontal dash at the given size — used as the
    /// indeterminate-state glyph for tristate menu items (mirrors
    /// the Windows "mixed-state" convention).
    pub fn dash(size: f32) -> Self {
        let s = size;
        let y_mid = s * 0.5;
        let half_thickness = s * 0.06; // ~12% of size, matches Checkbox indeterminate bar
        let mut path = Path::new();
        path.move_to(Point::new(s * 0.2, y_mid - half_thickness));
        path.line_to(Point::new(s * 0.8, y_mid - half_thickness));
        path.line_to(Point::new(s * 0.8, y_mid + half_thickness));
        path.line_to(Point::new(s * 0.2, y_mid + half_thickness));
        path.close();
        Self::from_path(path, size)
    }

    /// A small filled disc centered in the given size — used as the
    /// selected-state glyph for radio menu items.
    pub fn radio_dot(size: f32) -> Self {
        let s = size;
        let path = Path::circle(Point::new(s * 0.5, s * 0.5), s * 0.25);
        Self::from_path(path, size)
    }

    /// A downward-pointing chevron (▼) at the given size.
    pub fn chevron_down(size: f32) -> Self {
        let mut path = Path::new();
        let s = size;
        path.move_to(Point::new(s * 0.25, s * 0.35));
        path.line_to(Point::new(s * 0.5, s * 0.65));
        path.line_to(Point::new(s * 0.75, s * 0.35));
        Self::from_path(path, size)
    }

    /// A right-pointing chevron (▶) at the given size.
    pub fn chevron_right(size: f32) -> Self {
        let mut path = Path::new();
        let s = size;
        path.move_to(Point::new(s * 0.35, s * 0.25));
        path.line_to(Point::new(s * 0.65, s * 0.5));
        path.line_to(Point::new(s * 0.35, s * 0.75));
        Self::from_path(path, size)
    }

    /// A left-pointing chevron (◀) at the given size.
    pub fn chevron_left(size: f32) -> Self {
        let mut path = Path::new();
        let s = size;
        path.move_to(Point::new(s * 0.65, s * 0.25));
        path.line_to(Point::new(s * 0.35, s * 0.5));
        path.line_to(Point::new(s * 0.65, s * 0.75));
        Self::from_path(path, size)
    }

    /// An upward-pointing chevron (▲) at the given size.
    pub fn chevron_up(size: f32) -> Self {
        let mut path = Path::new();
        let s = size;
        path.move_to(Point::new(s * 0.25, s * 0.65));
        path.line_to(Point::new(s * 0.5, s * 0.35));
        path.line_to(Point::new(s * 0.75, s * 0.65));
        Self::from_path(path, size)
    }

    /// Create an icon from an SVG string. Parses the SVG and extracts
    /// geometry, ignoring any colors in the SVG. Display size defaults
    /// to the SVG's viewBox dimensions; use [`icon_size`](Self::icon_size)
    /// to override.
    ///
    /// If parsing fails, logs the error in debug mode and produces an empty icon.
    pub fn from_svg(svg_str: &str) -> Self {
        match SvgIcon::parse(svg_str) {
            Ok(icon) => Self::from_svg_icon(&icon),
            Err(_e) => {
                #[cfg(debug_assertions)]
                eprintln!("teksilo: SVG parse error: {_e}");
                Self::from_path(Path::new(), 0.0)
            }
        }
    }

    /// Create an icon from a pre-parsed [`SvgIcon`]. Display size
    /// defaults to the SVG's viewBox; use [`icon_size`](Self::icon_size)
    /// to override. Scaling is deferred to paint time.
    pub fn from_svg_icon(icon: &SvgIcon) -> Self {
        let vb_size = icon.width().max(icon.height());
        Self {
            source: IconSource::Svg(icon.clone()),
            design_size: vb_size,
            display_size: vb_size,
            color: ColorProp::TextRole(TextRole::Primary),
            mode: IconMode::Tintable,
            follow_text_scale: false,
        }
    }

    /// Create an icon from PNG data.
    ///
    /// If decoding fails, logs the error in debug mode and produces an empty icon.
    pub fn from_png(data: &'static [u8], size: f32) -> Self {
        match RasterIcon::decode_png(data) {
            Ok(icon) => {
                let name = auto_name("png", data.as_ptr() as usize);
                let mode = IconMode::Tintable;
                let upload_pixels = prepare_pixels(&icon, mode);
                Self {
                    source: IconSource::Raster {
                        name,
                        icon,
                        upload_pixels,
                    },
                    design_size: size,
                    display_size: size,
                    color: ColorProp::TextRole(TextRole::Primary),
                    mode,
                    follow_text_scale: false,
                }
            }
            Err(_e) => {
                #[cfg(debug_assertions)]
                eprintln!("teksilo: PNG decode error: {_e}");
                Self::from_path(Path::new(), size)
            }
        }
    }

    /// Create an icon from WebP data. Auto-detects static vs animated.
    ///
    /// If decoding fails, logs the error in debug mode and produces an empty icon.
    pub fn from_webp(data: &'static [u8], size: f32) -> Self {
        let mode = IconMode::Tintable;
        // Try animated first
        if let Ok(anim) = AnimatedIcon::decode_webp(data) {
            let name = auto_name("webp", data.as_ptr() as usize);
            let frame_upload_pixels: Vec<Vec<u8>> = anim
                .frames()
                .iter()
                .map(|f| prepare_pixels(f, mode))
                .collect();
            return Self {
                source: IconSource::Animated {
                    name,
                    icon: anim,
                    frame_upload_pixels,
                    frame_signal: None,
                    sprite_atlas: None,
                    anim_handle: None,
                },
                design_size: size,
                display_size: size,
                color: ColorProp::TextRole(TextRole::Primary),
                mode,
                follow_text_scale: false,
            };
        }
        // Fall back to static
        match RasterIcon::decode_webp(data) {
            Ok(icon) => {
                let name = auto_name("webp", data.as_ptr() as usize);
                let upload_pixels = prepare_pixels(&icon, mode);
                Self {
                    source: IconSource::Raster {
                        name,
                        icon,
                        upload_pixels,
                    },
                    design_size: size,
                    display_size: size,
                    color: ColorProp::TextRole(TextRole::Primary),
                    mode,
                    follow_text_scale: false,
                }
            }
            Err(_e) => {
                #[cfg(debug_assertions)]
                eprintln!("teksilo: WebP decode error: {_e}");
                Self::from_path(Path::new(), size)
            }
        }
    }

    /// Create an icon from a pre-decoded [`RasterIcon`].
    /// Accepts a reference — pixel data is copied internally.
    pub fn from_raster(icon: &RasterIcon, size: f32) -> Self {
        let name = format!("_icon_raster_{:p}", icon as *const RasterIcon);
        let mode = IconMode::Tintable;
        let upload_pixels = prepare_pixels(icon, mode);
        Self {
            source: IconSource::Raster {
                name,
                icon: icon.clone(),
                upload_pixels,
            },
            design_size: size,
            display_size: size,
            color: ColorProp::TextRole(TextRole::Primary),
            mode,
            follow_text_scale: false,
        }
    }

    /// Create an icon from a pre-decoded [`AnimatedIcon`].
    /// Accepts a reference — frame data is copied internally.
    pub fn from_animated(icon: &AnimatedIcon, size: f32) -> Self {
        let name = format!("_icon_anim_{:p}", icon as *const AnimatedIcon);
        let mode = IconMode::Tintable;
        let frame_upload_pixels: Vec<Vec<u8>> = icon
            .frames()
            .iter()
            .map(|f| prepare_pixels(f, mode))
            .collect();
        Self {
            source: IconSource::Animated {
                name,
                icon: icon.clone(),
                frame_upload_pixels,
                frame_signal: None,
                sprite_atlas: None,
                anim_handle: None,
            },
            design_size: size,
            display_size: size,
            color: ColorProp::TextRole(TextRole::Primary),
            mode,
            follow_text_scale: false,
        }
    }

    /// Set the icon rendering mode (tintable or full-color).
    /// Re-computes cached pixel data for raster/animated icons.
    pub fn mode(mut self, mode: IconMode) -> Self {
        if self.mode == mode {
            return self;
        }
        self.mode = mode;
        match &mut self.source {
            IconSource::Raster {
                icon,
                upload_pixels,
                ..
            } => {
                *upload_pixels = prepare_pixels(icon, mode);
            }
            IconSource::Animated {
                icon,
                frame_upload_pixels,
                sprite_atlas,
                anim_handle,
                ..
            } => {
                *frame_upload_pixels = icon
                    .frames()
                    .iter()
                    .map(|f| prepare_pixels(f, mode))
                    .collect();
                // Invalidate the atlas — pixels bake the mode
                // (Tintable pre-applies the alpha mask, FullColor
                // keeps raw RGBA); the next build() repacks.
                *sprite_atlas = None;
                *anim_handle = None;
            }
            IconSource::Path(_) | IconSource::Svg(_) => {}
        }
        self
    }

    /// Set the tint. Accepts any `impl Into<ColorProp>`:
    ///
    /// - A raw `Color` — a frozen literal.
    /// - A [`TextRole`] / `SurfaceRole` / `BorderRole` — resolved against
    ///   the theme at paint time (reactive across theme switches).
    /// - A `Signal<Color>` — reactive state (usually interaction-driven).
    pub fn color(mut self, color: impl Into<ColorProp>) -> Self {
        self.color = color.into();
        self
    }

    /// Set the display size of the icon. The path/image is scaled to fit
    /// this size during rendering. This does not affect the design-time
    /// coordinate space — SVG paths scale correctly.
    pub fn icon_size(mut self, size: f32) -> Self {
        self.display_size = size;
        self
    }

    /// Make this icon grow with the global accessibility text scale
    /// (`ctx.text_scale`). Off by default. Enable for icons that sit inline
    /// with text and should scale together — e.g. status glyphs in a
    /// `SeverityBadge`. The reported (and rendered) size becomes
    /// `display_size × text_scale`.
    pub fn follow_text_scale(mut self, follow: bool) -> Self {
        self.follow_text_scale = follow;
        self
    }

    /// The on-screen square extent (dp) this icon renders at — its
    /// `display_size`. Lets a container reserve the right width without
    /// laying the icon out first.
    pub(crate) fn display_size(&self) -> f32 {
        self.display_size
    }

    /// Create a scaled copy of a programmatic [`IconSource::Path`] to fit
    /// within the given bounds. SVG sources are scaled separately in
    /// `paint` (fill via `to_path_in_rect`, strokes via
    /// `stroked_paths_in_rect`) so their stroke widths scale correctly.
    fn scaled_path(&self, bounds: Rect) -> Path {
        let path = match &self.source {
            IconSource::Path(p) => p,
            _ => return Path::new(),
        };
        if path.is_empty() {
            return path.clone();
        }
        let scale_x = bounds.width / self.design_size;
        let scale_y = bounds.height / self.design_size;
        let offset_x = bounds.x;
        let offset_y = bounds.y;

        let mut scaled = Path::new();
        for cmd in &path.commands {
            match *cmd {
                PathCommand::MoveTo(p) => {
                    scaled.move_to(Point::new(
                        p.x * scale_x + offset_x,
                        p.y * scale_y + offset_y,
                    ));
                }
                PathCommand::LineTo(p) => {
                    scaled.line_to(Point::new(
                        p.x * scale_x + offset_x,
                        p.y * scale_y + offset_y,
                    ));
                }
                PathCommand::QuadTo { control, to } => {
                    scaled.quad_to(
                        Point::new(
                            control.x * scale_x + offset_x,
                            control.y * scale_y + offset_y,
                        ),
                        Point::new(to.x * scale_x + offset_x, to.y * scale_y + offset_y),
                    );
                }
                PathCommand::CubicTo {
                    control1,
                    control2,
                    to,
                } => {
                    scaled.cubic_to(
                        Point::new(
                            control1.x * scale_x + offset_x,
                            control1.y * scale_y + offset_y,
                        ),
                        Point::new(
                            control2.x * scale_x + offset_x,
                            control2.y * scale_y + offset_y,
                        ),
                        Point::new(to.x * scale_x + offset_x, to.y * scale_y + offset_y),
                    );
                }
                PathCommand::ArcTo {
                    rect,
                    start_angle,
                    sweep_angle,
                } => {
                    scaled.arc_to(
                        Rect::new(
                            rect.x * scale_x + offset_x,
                            rect.y * scale_y + offset_y,
                            rect.width * scale_x,
                            rect.height * scale_y,
                        ),
                        start_angle,
                        sweep_angle,
                    );
                }
                PathCommand::Close => {
                    scaled.close();
                }
            }
        }
        scaled
    }

    /// Paint a raster icon into the canvas using pre-computed upload pixels.
    fn paint_raster(
        &self,
        bounds: Rect,
        canvas: &mut Canvas,
        name: &str,
        width: u32,
        height: u32,
        upload_pixels: &[u8],
        color: Color,
    ) {
        if !canvas.has_pending_image(name) {
            canvas.ensure_image_registered(name, width, height, Cow::Owned(upload_pixels.to_vec()));
        }
        match self.mode {
            IconMode::Tintable => canvas.draw_tinted_image(bounds, name, color),
            IconMode::FullColor => canvas.draw_image(bounds, name),
        }
    }
}

impl std::fmt::Debug for IconWidget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IconWidget")
            .field("display_size", &self.display_size)
            .field("mode", &self.mode)
            .finish()
    }
}

impl Widget for IconWidget {
    fn build(
        &mut self,
        ctx: &mut teksilo_core::build_context::BuildContext,
    ) -> Vec<teksilo_core::widget_id::WidgetId> {
        // Register color binding
        {
            let self_id = ctx.self_id();
            let registry = ctx.binding_registry();
            self.color.register_if_bound(
                self_id,
                registry,
                teksilo_core::binding::BindingLevel::RepaintOnly,
            );
        }

        // For animated icons: prefer the shader-driven sprite path
        // (paint() emits ONE AnimatedQuad and doesn't re-run per
        // frame; the GPU samples the current frame from a packed
        // atlas). When reduced-motion is on, fall back to the static
        // first-frame render — no animation scheduled at all.
        let mode = self.mode;
        let icon_color = self.color.clone();
        if let IconSource::Animated {
            name,
            icon,
            frame_upload_pixels,
            frame_signal,
            sprite_atlas,
            anim_handle,
        } = &mut self.source
        {
            if ctx.prefers_reduced_motion() {
                *frame_signal = None;
                *sprite_atlas = None;
                *anim_handle = None;
            } else {
                // Pack frames into an atlas once; reuse across rebuilds.
                if sprite_atlas.is_none() {
                    *sprite_atlas = build_sprite_atlas(name, icon, frame_upload_pixels);
                }
                if let Some(atlas) = sprite_atlas.as_ref() {
                    // Tintable icons bake an alpha mask in the pixel
                    // buffer, so the shader must multiply by the
                    // widget's color to get the final tint. FullColor
                    // icons pass pixels through untouched (no tint).
                    let tint = match mode {
                        IconMode::Tintable => Some(icon_color),
                        IconMode::FullColor => None,
                    };
                    *anim_handle = Some(ctx.animated_quad(AnimatedQuadKind::SpriteCycle {
                        image_name: atlas.name.clone(),
                        frame_count: icon.frame_count() as u32,
                        cols: atlas.cols,
                        rows: atlas.rows,
                        period: icon.total_duration(),
                        tint,
                    }));
                    // Shader drives everything now — drop the legacy
                    // signal so the scheduler doesn't tick it.
                    *frame_signal = None;
                } else {
                    // Atlas build failed (e.g. zero-size frames);
                    // fall back to the legacy signal path.
                    let signal = ctx.animated_signal(0.0);
                    {
                        let self_id = ctx.self_id();
                        let registry = ctx.binding_registry();
                        signal.bind_to(
                            self_id,
                            registry,
                            teksilo_core::binding::BindingLevel::RepaintOnly,
                        );
                    }
                    let frame_count = icon.frame_count() as f32;
                    let period = icon.total_duration();
                    signal.animate_looping(
                        frame_count,
                        period,
                        Easing::Linear,
                        Some(std::time::Duration::from_millis(33)),
                    );
                    *frame_signal = Some(signal);
                }
            }
        }

        Vec::new()
    }

    fn layout_response(
        &self,
        _proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        // Paint fills `bounds`, so growing the reported size here is the only
        // change needed to scale the rendered glyph with the text scale.
        let size = if self.follow_text_scale {
            self.display_size * ctx.text_scale
        } else {
            self.display_size
        };
        Size::new(size, size).into()
    }

    fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
        let color = self.color.resolve(ctx.theme, ctx.effective_enabled);

        match &self.source {
            IconSource::Path(_) => {
                if color.a() > 0.0 {
                    let scaled = self.scaled_path(bounds);
                    if !scaled.is_empty() {
                        canvas.fill_path(&scaled, color);
                    }
                }
            }
            IconSource::Svg(icon) => {
                if color.a() <= 0.0 {
                    return;
                }
                // Full-color artwork (a brand mark, a colored file-type icon)
                // keeps its own paints and its document order — see
                // `SvgIcon::draw_ops_in_rect`. A monochrome document is drawn
                // through the tinted path either way: the result is identical,
                // and the tinted path merges the whole icon into one fill.
                if self.mode == IconMode::FullColor && !icon.is_monochrome() {
                    for op in icon.draw_ops_in_rect(bounds, color) {
                        match op {
                            SvgDrawOp::Fill {
                                path,
                                fill_rule,
                                paint,
                            } => canvas.fill_path_with_rule(&path, paint, fill_rule),
                            SvgDrawOp::Stroke { path, style, paint } => {
                                canvas.stroke_path_with_paint(&path, paint, style)
                            }
                        }
                    }
                    return;
                }

                // Tinted: filled geometry (the default for most icons) +
                // even-odd / transparent fills + stroked geometry (line-style
                // icons). An icon may carry any mix.
                let fill = icon.to_path_in_rect(bounds);
                if !fill.is_empty() {
                    canvas.fill_path(&fill, color);
                }
                for (path, rule, opacity) in icon.extra_fills_in_rect(bounds) {
                    let c = color.with_alpha(color.a() * opacity);
                    if !path.is_empty() && c.a() > 0.0 {
                        canvas.fill_path_with_rule(&path, c, rule);
                    }
                }
                for (path, style, opacity) in icon.stroked_paths_in_rect(bounds) {
                    let c = color.with_alpha(color.a() * opacity);
                    if !path.is_empty() && c.a() > 0.0 {
                        canvas.stroke_path(&path, c, style);
                    }
                }
            }
            IconSource::Raster {
                name,
                icon,
                upload_pixels,
            } => {
                self.paint_raster(
                    bounds,
                    canvas,
                    name,
                    icon.width(),
                    icon.height(),
                    upload_pixels,
                    color,
                );
            }
            IconSource::Animated {
                name,
                icon,
                frame_upload_pixels,
                frame_signal,
                sprite_atlas,
                anim_handle,
            } => {
                // Shader path: one AnimatedQuad — the renderer
                // samples the packed atlas at the current frame's
                // cell, driven by per-frame uniforms from the tree.
                if let (Some(atlas), Some(handle)) = (sprite_atlas, anim_handle) {
                    // Register the atlas pixels (idempotent — skipped
                    // if already pending or uploaded this frame).
                    canvas.ensure_image_registered(
                        atlas.name.clone(),
                        atlas.width,
                        atlas.height,
                        std::borrow::Cow::Owned(atlas.pixels.clone()),
                    );
                    canvas.draw_animated_quad(
                        bounds,
                        handle.slot(),
                        AnimatedQuadClass::Sprite {
                            image_name: atlas.name.clone(),
                        },
                    );
                    return;
                }
                // Legacy path: signal-driven frame index with one
                // per-frame image registration. Used when
                // reduced-motion is on (frame_signal is None →
                // frame 0 shown statically) or when atlas build
                // failed and we fell back.
                let idx = frame_signal
                    .as_ref()
                    .map(|s| (s.get() as usize).min(icon.frame_count().saturating_sub(1)))
                    .unwrap_or(0);
                let frame_name = format!("{name}_f{idx}");
                let frame = &icon.frames()[idx];
                let pixels = &frame_upload_pixels[idx];
                self.paint_raster(
                    bounds,
                    canvas,
                    &frame_name,
                    frame.width(),
                    frame.height(),
                    pixels,
                    color,
                );
            }
        }
    }

    fn accessibility(&self, _builder: &mut AccessNodeBuilder) {
        // Icons are typically decorative — the parent widget sets the semantic role.
    }
}

/// Pack animated-icon frames into a single square-ish sprite atlas.
/// The returned `SpriteAtlas` carries the packed pixels, grid layout,
/// and a placeholder handle (`handle.slot() == 0`) that `build()`
/// overwrites with the real scheduler-issued handle before paint runs.
///
/// Frames are laid out row-major: frame index `i` occupies cell
/// `(i % cols, i / cols)`. Unused tail cells (when `frame_count <
/// cols * rows`) are left zeroed — the shader clamps the sampled
/// frame index so it never reads past the last frame.
///
/// Returns `None` when the frames have zero dimensions; the caller
/// falls back to the legacy signal-driven path.
fn build_sprite_atlas(
    name: &str,
    icon: &AnimatedIcon,
    frame_pixels: &[Vec<u8>],
) -> Option<SpriteAtlas> {
    let frames = icon.frames();
    if frames.is_empty() {
        return None;
    }
    let frame_w = frames[0].width();
    let frame_h = frames[0].height();
    if frame_w == 0 || frame_h == 0 {
        return None;
    }

    let n = frames.len() as u32;
    let cols = (n as f32).sqrt().ceil() as u32;
    let rows = n.div_ceil(cols);
    let atlas_w = cols * frame_w;
    let atlas_h = rows * frame_h;
    let mut pixels = vec![0u8; (atlas_w * atlas_h * 4) as usize];

    for (i, cell) in frame_pixels.iter().enumerate() {
        let i = i as u32;
        let col = i % cols;
        let row = i / cols;
        let dst_x = col * frame_w;
        let dst_y = row * frame_h;
        // Copy row-by-row; source is tightly packed (frame_w × 4 bytes
        // per row), destination stride is atlas_w × 4.
        for y in 0..frame_h {
            let src_start = (y * frame_w * 4) as usize;
            let src_end = src_start + (frame_w * 4) as usize;
            if src_end > cell.len() {
                break; // truncated frame — shouldn't happen, but be defensive
            }
            let dst_start = (((dst_y + y) * atlas_w + dst_x) * 4) as usize;
            let dst_end = dst_start + (frame_w * 4) as usize;
            pixels[dst_start..dst_end].copy_from_slice(&cell[src_start..src_end]);
        }
    }

    Some(SpriteAtlas {
        name: format!("{name}_sprite_atlas"),
        pixels,
        width: atlas_w,
        height: atlas_h,
        cols,
        rows,
    })
}

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

    #[test]
    fn icon_intrinsic_size() {
        let mut tree = WidgetTree::new();
        let icon = tree.add(IconWidget::checkmark(24.0));
        tree.layout(SizeProposal::unspecified());
        let b = tree.bounds(icon);
        assert!((b.width - 24.0).abs() < 0.01);
        assert!((b.height - 24.0).abs() < 0.01);
    }

    #[test]
    fn icon_custom_size() {
        let mut tree = WidgetTree::new();
        let icon = tree.add(IconWidget::chevron_down(16.0));
        tree.layout(SizeProposal::unspecified());
        let b = tree.bounds(icon);
        assert!((b.width - 16.0).abs() < 0.01);
        assert!((b.height - 16.0).abs() < 0.01);
    }

    #[test]
    fn follow_text_scale_grows_with_user_scale() {
        // Opt-in icon doubles at 200% text scale; a default icon stays put.
        let mut tree = WidgetTree::new();
        let scaled = tree.add(IconWidget::checkmark(20.0).follow_text_scale(true));
        let fixed = tree.add(IconWidget::checkmark(20.0));
        tree.set_user_text_scale(2.0);
        tree.layout(SizeProposal::unspecified());
        let bs = tree.bounds(scaled);
        let bf = tree.bounds(fixed);
        assert!(
            (bs.width - 40.0).abs() < 0.01,
            "opted-in icon should double: {bs:?}"
        );
        assert!(
            (bf.width - 20.0).abs() < 0.01,
            "default icon must not scale: {bf:?}"
        );
    }

    #[test]
    fn icon_paints_path() {
        let mut tree = WidgetTree::new();
        tree.add(IconWidget::checkmark(24.0).color(Color::BLACK));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        assert!(!frame.paths.is_empty(), "icon should render a path");
    }

    #[test]
    fn empty_path_does_not_paint() {
        let mut tree = WidgetTree::new();
        tree.add(IconWidget::from_path(Path::new(), 24.0).color(Color::BLACK));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        assert!(frame.paths.is_empty(), "empty path should not render");
    }

    #[test]
    fn icon_from_svg() {
        let svg = r#"<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
        </svg>"#;
        let mut tree = WidgetTree::new();
        tree.add(IconWidget::from_svg(svg).color(Color::BLACK));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        assert!(!frame.paths.is_empty(), "SVG icon should render a path");
    }

    #[test]
    fn icon_from_svg_line_style_renders_stroke_not_fill() {
        // A line-style (fill=none, stroke=…) SVG must render as a stroked
        // outline, not a filled blob. Regression guard for the SVG icon
        // parser gaining stroke support.
        let svg = r#"<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"/>
        </svg>"#;
        let mut tree = WidgetTree::new();
        tree.add(IconWidget::from_svg(svg).color(Color::BLACK));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        assert_eq!(
            frame.paths.len(),
            1,
            "line-style SVG should render exactly one (stroked) path"
        );
        assert!(
            frame.paths[0].stroke_style.width > 0.0,
            "the rendered path must be stroked, not filled"
        );
    }

    #[test]
    fn icon_from_svg_evenodd_emits_evenodd_path_entry() {
        // A fill-rule="evenodd" icon must reach the renderer as a PathEntry
        // carrying FillRule::EvenOdd (so holes punch instead of filling in).
        let svg = r#"<svg viewBox="0 0 24 24">
            <path fill-rule="evenodd" d="M2 2L22 2L22 22Z"/>
        </svg>"#;
        let mut tree = WidgetTree::new();
        tree.add(IconWidget::from_svg(svg).color(Color::BLACK));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        assert_eq!(frame.paths.len(), 1, "evenodd icon renders one path");
        assert_eq!(
            frame.paths[0].fill_rule,
            teksilo_canvas::FillRule::EvenOdd,
            "the fill rule must reach the PathEntry"
        );
    }

    #[test]
    fn icon_from_svg_invalid_fallback() {
        let mut tree = WidgetTree::new();
        tree.add(IconWidget::from_svg("<not-svg>"));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        // Invalid SVG should produce empty icon, no panic
        assert!(frame.paths.is_empty());
    }

    #[test]
    fn icon_mode_default_is_tintable() {
        let icon = IconWidget::checkmark(24.0);
        assert_eq!(icon.mode, IconMode::Tintable);
    }

    #[test]
    fn icon_mode_can_be_set() {
        let icon = IconWidget::checkmark(24.0).mode(IconMode::FullColor);
        assert_eq!(icon.mode, IconMode::FullColor);
    }

    #[test]
    fn raster_icon_paints_image() {
        let icon = RasterIcon::from_raw(vec![255; 4], 1, 1);
        let mut tree = WidgetTree::new();
        tree.add(IconWidget::from_raster(&icon, 24.0).color(Color::BLACK));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        // Raster icon should produce an image draw command
        assert!(
            !frame.images.is_empty(),
            "raster icon should render an image"
        );
    }

    #[test]
    fn raster_icon_tintable_has_tint() {
        let icon = RasterIcon::from_raw(vec![255; 4], 1, 1);
        let mut tree = WidgetTree::new();
        tree.add(
            IconWidget::from_raster(&icon, 24.0)
                .color(Color::from_hex("#FF0000"))
                .mode(IconMode::Tintable),
        );
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        assert!(
            frame.images[0].tint.is_some(),
            "tintable icon should have tint"
        );
    }

    #[test]
    fn raster_icon_fullcolor_no_tint() {
        let icon = RasterIcon::from_raw(vec![255; 4], 1, 1);
        let mut tree = WidgetTree::new();
        tree.add(IconWidget::from_raster(&icon, 24.0).mode(IconMode::FullColor));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        assert!(
            frame.images[0].tint.is_none(),
            "full-color icon should not have tint"
        );
    }

    // ── Enabled-state-aware role substitution ─────────────────────
    //
    // When the leaf paints with a role-based ColorProp and any
    // ancestor's arena `enabled_state` resolves to false, the leaf
    // must substitute `TextRole::Disabled` automatically — this is
    // the lynchpin of the "composites stop owning enabled state"
    // architecture and the fix for the format-toolbar bug where
    // table-op IconButtons stayed full-color when `is_in_table` was
    // false.

    /// Color of the single rendered `path` for an `IconWidget` from
    /// `from_path`. The path-icon code puts the resolved fill on
    /// `PathEntry.color`, distinct from raster's `image.tint`.
    fn path_icon_color(frame: &teksilo_canvas::RenderFrame) -> [f32; 4] {
        frame
            .paths
            .first()
            .map(|p| p.color)
            .expect("path icon should render at least one path")
    }

    #[test]
    fn role_based_icon_uses_text_disabled_when_self_disabled() {
        // Direct case: bind `enabled_when` on the IconWidget itself.
        // Default role is `TextRole::Primary`; when disabled the leaf
        // must resolve to `theme.colors.text_disabled`.
        let mut tree = WidgetTree::new();
        let theme = teksilo_core::presets::intui::light();
        tree.set_theme(theme.clone());

        let icon = tree.add(IconWidget::checkmark(24.0));
        tree.enabled_when(icon, false);
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        let color = path_icon_color(&frame);

        let expected = theme.colors.text_disabled.to_array();
        assert_eq!(
            color, expected,
            "default-role IconWidget under enabled_when(false) must paint at text_disabled, got {color:?}"
        );
    }

    #[test]
    fn role_based_icon_uses_text_primary_when_self_enabled() {
        let mut tree = WidgetTree::new();
        let theme = teksilo_core::presets::intui::light();
        tree.set_theme(theme.clone());

        tree.add(IconWidget::checkmark(24.0));
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        let color = path_icon_color(&frame);

        let expected = theme.colors.text_primary.to_array();
        assert_eq!(
            color, expected,
            "default-role IconWidget without enabled_state must paint at text_primary, got {color:?}"
        );
    }

    #[test]
    fn role_based_icon_flips_when_bound_signal_flips_without_rebuild() {
        // The FormatToolbar bug as a unit test. Bind a Signal<bool>
        // via `enabled_when`; flip it after layout+render; re-render;
        // verify the leaf's color flipped from primary to disabled
        // and back to primary, without any rebuild.
        use teksilo_core::signal::Signal;

        let mut tree = WidgetTree::new();
        let theme = teksilo_core::presets::intui::light();
        tree.set_theme(theme.clone());

        let is_enabled = Signal::new(true);
        let icon = tree.add(IconWidget::checkmark(24.0));
        tree.enabled_when(icon, is_enabled.clone());

        tree.layout(SizeProposal::exact(24.0, 24.0));
        let primary = theme.colors.text_primary.to_array();
        let disabled = theme.colors.text_disabled.to_array();
        assert_eq!(path_icon_color(&tree.render()), primary, "starts primary");

        is_enabled.set(false);
        tree.layout(SizeProposal::exact(24.0, 24.0));
        assert_eq!(
            path_icon_color(&tree.render()),
            disabled,
            "after flipping signal to false the leaf must repaint at the disabled color"
        );

        is_enabled.set(true);
        tree.layout(SizeProposal::exact(24.0, 24.0));
        assert_eq!(
            path_icon_color(&tree.render()),
            primary,
            "flipping back to true must re-resolve to primary"
        );
    }

    #[test]
    fn explicit_color_does_not_dim_when_disabled() {
        // The static-opt-out contract: when the caller passed a
        // literal `Color`, role substitution is bypassed entirely.
        // A disabled subtree with an explicit-color icon keeps the
        // caller's literal — same model as Static() everywhere else.
        let mut tree = WidgetTree::new();
        let red = Color::from_hex("#FF0000");
        let icon = tree.add(IconWidget::checkmark(24.0).color(red));
        tree.enabled_when(icon, false);
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        let color = path_icon_color(&frame);
        assert_eq!(
            color,
            red.to_array(),
            "explicit-color icons must NOT auto-dim when disabled — caller picked the literal, framework respects it"
        );
    }

    // ── Full-color SVG ──────────────────────────────────────────────────────

    /// A two-color mark reaches the renderer as two paths carrying **its own**
    /// colors, not the widget's — and in document order, so the shape authored
    /// last paints last.
    #[test]
    fn full_color_svg_keeps_its_own_colors_in_document_order() {
        let svg = r##"<svg viewBox="0 0 24 24">
            <rect width="24" height="24" fill="#5865F2"/>
            <circle cx="12" cy="12" r="6" fill="#FFFFFF"/>
        </svg>"##;
        let mut tree = WidgetTree::new();
        // A tint that appears nowhere in the artwork: if the widget ever leaks
        // through, the assertion below names it.
        tree.add(
            IconWidget::from_svg(svg)
                .icon_size(24.0)
                .mode(IconMode::FullColor)
                .color(Color::from_hex("#FF0000")),
        );
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();

        assert_eq!(frame.paths.len(), 2, "one path per authored shape");
        assert_eq!(frame.paths[0].color, Color::from_hex("#5865F2").to_array());
        assert_eq!(frame.paths[1].color, Color::from_hex("#FFFFFF").to_array());
    }

    /// The same artwork in the default `Tintable` mode is a single merged
    /// silhouette in the widget's color — the pre-existing behaviour, which
    /// full-color support must not disturb.
    #[test]
    fn tintable_mode_still_merges_a_colored_svg_into_one_tinted_path() {
        let svg = r##"<svg viewBox="0 0 24 24">
            <rect width="24" height="24" fill="#5865F2"/>
            <circle cx="12" cy="12" r="6" fill="#FFFFFF"/>
        </svg>"##;
        let mut tree = WidgetTree::new();
        tree.add(
            IconWidget::from_svg(svg)
                .icon_size(24.0)
                .color(Color::from_hex("#FF0000")),
        );
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();

        assert_eq!(frame.paths.len(), 1, "both shapes merge into one fill");
        assert_eq!(
            frame.paths[0].color,
            Color::from_hex("#FF0000").to_array(),
            "tintable ignores the artwork's colors and takes the widget's"
        );
    }

    /// `currentColor` inside full-color artwork still follows the theme — the
    /// mixed case: fixed brand colors plus one themed accent.
    #[test]
    fn current_color_follows_the_widget_inside_full_color_artwork() {
        let svg = r##"<svg viewBox="0 0 24 24">
            <rect width="24" height="24" fill="#5865F2"/>
            <rect width="8" height="8" fill="currentColor"/>
        </svg>"##;
        let mut tree = WidgetTree::new();
        let accent = Color::from_hex("#00FF00");
        tree.add(
            IconWidget::from_svg(svg)
                .icon_size(24.0)
                .mode(IconMode::FullColor)
                .color(accent),
        );
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        assert_eq!(frame.paths[0].color, Color::from_hex("#5865F2").to_array());
        assert_eq!(frame.paths[1].color, accent.to_array());
    }

    /// A gradient fill reaches the renderer as gradient `PaintData` — the
    /// dedicated pipeline — rather than being flattened to a solid.
    #[test]
    fn a_gradient_fill_reaches_the_renderer_as_a_gradient() {
        let svg = r##"<svg viewBox="0 0 24 24">
            <linearGradient id="g">
              <stop offset="0" stop-color="#FF0000"/>
              <stop offset="1" stop-color="#0000FF"/>
            </linearGradient>
            <rect width="24" height="24" fill="url(#g)"/>
        </svg>"##;
        let mut tree = WidgetTree::new();
        tree.add(
            IconWidget::from_svg(svg)
                .icon_size(24.0)
                .mode(IconMode::FullColor)
                .color(Color::BLACK),
        );
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        match &frame.paths[0].paint_data {
            teksilo_canvas::PaintData::LinearGradient { start, end, stops } => {
                assert_eq!(stops.len(), 2);
                assert_eq!(stops[0].color.to_array(), [1.0, 0.0, 0.0, 1.0]);
                // Rect-local: the ramp spans the icon's 24 dp box.
                assert!(start[0].abs() < 0.01);
                assert!((end[0] - 24.0).abs() < 0.01, "end {end:?}");
            }
            other => panic!("expected a linear gradient paint, got {other:?}"),
        }
    }

    /// A gradient **stroke** is a gradient too — and its coordinates are
    /// re-based onto the stroke's expanded bounds, so the ramp lands where the
    /// identical fill gradient would. (Strokes were solid-only before.)
    #[test]
    fn a_gradient_stroke_is_rebased_onto_the_expanded_stroke_bounds() {
        let svg = r##"<svg viewBox="0 0 24 24">
            <linearGradient id="g" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="24" y2="0">
              <stop offset="0" stop-color="#FF0000"/>
              <stop offset="1" stop-color="#0000FF"/>
            </linearGradient>
            <rect x="2" y="2" width="20" height="20" fill="none" stroke="url(#g)" stroke-width="4"/>
        </svg>"##;
        let mut tree = WidgetTree::new();
        tree.add(
            IconWidget::from_svg(svg)
                .icon_size(24.0)
                .mode(IconMode::FullColor)
                .color(Color::BLACK),
        );
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();

        let entry = &frame.paths[0];
        assert!(entry.stroke_style.width > 0.0, "must be a stroke");
        match &entry.paint_data {
            teksilo_canvas::PaintData::LinearGradient { start, end, .. } => {
                // The ramp runs 0→24 in user space; the path sits at x=2, and the
                // stroke expands its bounds by the 4 dp width — so relative to the
                // rect the shader normalizes against, x=0 lands at +2 and x=24 at
                // +26. Un-rebased it would read -2 / +22 and the gradient would sit
                // visibly offset from the geometry.
                assert!((start[0] - 2.0).abs() < 0.05, "start {start:?}");
                assert!((end[0] - 26.0).abs() < 0.05, "end {end:?}");
            }
            other => panic!("expected a linear gradient stroke, got {other:?}"),
        }
    }

    /// The widget's alpha attenuates full-color artwork without replacing its
    /// colors (what `IconMode::FullColor` promises for a raster, now true for
    /// vectors too).
    #[test]
    fn the_widget_alpha_dims_full_color_artwork() {
        let svg =
            r##"<svg viewBox="0 0 24 24"><rect width="24" height="24" fill="#FF0000"/></svg>"##;
        let mut tree = WidgetTree::new();
        tree.add(
            IconWidget::from_svg(svg)
                .icon_size(24.0)
                .mode(IconMode::FullColor)
                .color(Color::new(0.0, 0.0, 0.0, 0.5)),
        );
        tree.layout(SizeProposal::exact(24.0, 24.0));
        let frame = tree.render();
        let c = frame.paths[0].color;
        assert_eq!([c[0], c[1], c[2]], [1.0, 0.0, 0.0], "the red must survive");
        assert!((c[3] - 0.5).abs() < 1e-5, "…at half alpha, got {}", c[3]);
    }
}